diff --git a/.gitignore b/.gitignore index 7241094..b3d7393 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ node_modules/ *.tgz .test-artifacts/ +/release-work/ + diff --git a/CHANGELOG.md b/CHANGELOG.md index 49fc7dd..50ed4f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,27 @@ # Changelog +## 1.0.4 — 2026-10-13 + +**Users on version 1.0.x can update normally. No configuration changes or migration are required. This also applies to 1.0.0-beta.1.** + +### ⚠️ Upgrading from a version before 1.0.0 + +**Only these older versions require migration. Back up your Homebridge config.json before updating, then follow the [migration guide](https://github.com/pponce/homebridge-script2/blob/master/MIGRATION.md).** Legacy Script2 accessory mode and old platform configuration formats are no longer supported. + +### Successful commands with stderr + +- Treat ON/OFF and stateless trigger commands that exit `0` as successful when they write stderr, including switches using a state file (issue #125). +- Log a warning when stderr is present and show bounded, escaped stderr text in Homebridge debug logs. Ordinary logs continue to omit script output. +- Preserve action failures for nonzero exits and execution errors, and keep the configurable nonzero state-script policy from issue #29. + +Debug stderr may include sensitive script output. Remove secrets before sharing logs. + +### Update + +Select **1.0.4** / **latest** in Homebridge UI and restart the instance or child bridge running Script2. + +[Full 1.0.4 release notes](releases/v1.0.4.md) + ## 1.0.3 — 2026-09-11 # ⚠️ **BREAKING CHANGE — BACK UP YOUR CONFIGURATION BEFORE UPDATING.** @@ -86,3 +108,4 @@ Select **1.0.3** / **latest** in Homebridge UI and restart the instance or child - Added optional early HomeKit acknowledgement for long-running commands, serialized and coalesced SET requests, deferred state reads, and custom UI saving fixes. - See [published release notes](https://github.com/pponce/homebridge-script2/releases/tag/v0.4.6) for the original release history. + diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index d34011d..fa5f368 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -1,5 +1,7 @@ # Script2 development and release +1.0.4 accepts exit-zero ON/OFF and stateless trigger commands that write stderr, warns in normal logs, and exposes bounded stderr text in Homebridge debug logs. The configurable nonzero state-script behavior is preserved. No configuration migration is needed from stable 1.0.x releases. + 1.0.2 includes Dependabot PR #123: the development-only fast-uri lockfile entry moves to 3.1.7. The 1.0.1 schema fix remains in place; runtime behavior and dependencies are unchanged. 1.0.1 fixes configuration-schema metadata while preserving existing configurations. Runtime code and dependencies are unchanged from 1.0.0. Ajv is a pinned development dependency used to validate the schema against JSON Schema rules; it is not installed as a runtime dependency of the plugin. Publication does not imply Homebridge verification. @@ -12,23 +14,29 @@ Run `python3 scripts/check-publisher.py beta` and `python3 scripts/check-publish Production versions are pinned in package-lock.json. npm ci validates the locked versions in GitHub Actions. The lock's integrity metadata can be refreshed with npm on a connected host. Live Homebridge behavior still depends on the maintainer's configured scripts and service environment. -## Publish 1.0.2 from SSH +## Publish 1.0.4 from SSH The local checkout is `~/devProjects/homebridge-script2`. The stable publisher requires `master` to match `origin/master`. GitHub account: `pponce`; npm account: `klidec`. -Copy the complete contents of [scripts/update-and-publish-stable.txt](scripts/update-and-publish-stable.txt) into the SSH shell. It uses one outer brace block, a child Bash process, `set -e`, and beginning/end output markers. A failure stops the child process while leaving SSH open. Review the reported status before continuing. +Use the complete bootstrap block supplied in the maintainer conversation to fetch the prepared tools and [update wrapper](scripts/update-and-publish-stable.txt) over SSH into `release-work/bootstrap/`. It uses one outer brace block, a child Bash process, `set -e`, and beginning/end output markers. A failure stops the child process while leaving SSH open. Review the reported status before continuing. + +The complete release block supplied in the maintainer conversation fetches the prepared source over SSH, loads the release tools and update wrapper from that commit, waits for PR #126 checks, and merges the prepared head before publishing. + +The helper refuses dirty/unexpected checkouts and existing versions/tags. It validates matching package/lockfile versions, a versioned changelog entry and release notes, packs a source snapshot, installs and tests the exact archive, then publishes `homebridge-script2@1.0.4` to npm `latest`. It creates a normal GitHub release marked latest from the exact source commit, using [releases/v1.0.4.md](releases/v1.0.4.md), with the archive and both final PNG icons attached. The publisher checks the official release body against the notes file and verifies npm's latest tag. -The helper refuses dirty/unexpected checkouts and existing versions/tags. It validates and packs a source snapshot, installs and tests the exact archive, then publishes `homebridge-script2@1.0.2` to npm `latest`. It creates a normal GitHub release marked latest from the exact source commit, using [releases/v1.0.2.md](releases/v1.0.2.md), with the archive and both final PNG icons attached. +Git fetch/pull/tag operations use the repository's SSH remote. Creating the official GitHub release still requires GitHub API authentication: the publisher tests actual API access and starts the browser/device-code login when necessary, instead of relying only on `gh auth status`. Environment token overrides are cleared in the child shell; `GH_BROWSER=echo` displays the browser URL for manual opening. -Interactive commands reconnect to the controlling SSH terminal even though the outer wrapper reads commands from a heredoc. npm uses `--browser=false`: open the displayed authentication URL in your local browser and leave SSH running while npm waits. An existing npm login does not eliminate publish-time authentication. A failed attempt's URL should not be reused. +All release work is contained in `~/devProjects/homebridge-script2/release-work/`, which is ignored by Git. The tools helper downloads the official GitHub CLI 2.102.0 Linux archive into `release-work/tools/`, verifies its published SHA-256 digest, and selects that binary for this release process. Build snapshots, package archives, and test installs are under `release-work/1.0.4/`; npm's cache and subprocess temporary files are under `release-work/npm-cache/` and `release-work/tmp/`. Authentication uses the standard GitHub/npm credential settings. + +Interactive commands reconnect to the controlling SSH terminal even though the outer wrapper reads commands from a heredoc. npm uses `--browser=false` for login and publish: open the displayed authentication URL in your local browser and leave SSH running while npm waits. An existing npm login does not eliminate publish-time authentication. A failed attempt's URL should not be reused. If npm succeeds but GitHub fails, inspect for a partial release and use the printed GitHub-only recovery command if the release is absent. Never publish the same npm version again. The helper does not install the plugin into the running Homebridge instance. ## Release warnings -The release notes and changelog use a large Markdown heading with a warning symbol and bold backup instruction. Homebridge's Release Notes tab obtains the published GitHub release body; its separate Changelog tab may obtain the tagged or installed CHANGELOG.md. Updating a branch file alone does not rewrite either an existing GitHub release body or an already-published npm archive. +The current release notes and changelog first state that 1.0.x users can update without configuration changes or migration. A separate warning explicitly applies only to upgrades from versions before 1.0.0; retain the backup instruction and migration link in that section. The same normal-upgrade guidance applies to 1.0.0-beta.1. Homebridge's Release Notes tab obtains the published GitHub release body; its separate Changelog tab may obtain the tagged or installed CHANGELOG.md. Updating a branch file alone does not rewrite either an existing GitHub release body or an already-published npm archive. -The 1.0.1 archive includes the enlarged changelog warning. Keep it prominent in future 1.0 release notes while users are migrating from pre-1.0 configurations. +Historical 1.0.1–1.0.3 notes used an enlarged general warning. From 1.0.4 onward, make the affected upgrade path explicit instead of presenting that warning to every user. ## Future beta releases @@ -42,3 +50,4 @@ The older [beta publisher](scripts/publish-beta.sh) and [SSH wrapper](scripts/up - For early acknowledgement, verify a long-running success and late failure without duplicate commands. - Confirm shutdown/restart and room/scene/automation assignments. - Inspect the warning in Homebridge's Release Notes and Changelog tabs. + diff --git a/README.md b/README.md index 56efa1a..73f444b 100644 --- a/README.md +++ b/README.md @@ -6,13 +6,15 @@ Run your own scripts from Apple Home and Siri using Homebridge. -# ⚠️ **BREAKING CHANGE — BACK UP YOUR CONFIGURATION BEFORE UPDATING.** +**Users on version 1.0.x can update normally. No configuration changes or migration are required. This also applies to 1.0.0-beta.1.** -**Version 1.0.0 removes legacy Script2 accessory mode and old platform configuration formats. Review and save a copy of your current Homebridge config.json before installing, then follow the [migration guide](https://github.com/pponce/homebridge-script2/blob/master/MIGRATION.md). Legacy configurations will no longer run.** +## ⚠️ Upgrading from a version before 1.0.0 -**Stable release: 1.0.2.** Install the `latest` channel. Homebridge verification is pending; this release does not claim certification. +**Only these older versions require migration. Back up your Homebridge config.json before updating, then follow the [migration guide](https://github.com/pponce/homebridge-script2/blob/master/MIGRATION.md).** Legacy Script2 accessory mode and old platform configuration formats are no longer supported. -**Updating from 1.0.0 or 1.0.1?** Version 1.0.2 includes the schema fix and development dependency maintenance. No configuration changes are required. +**Stable release: 1.0.4.** Install the `latest` channel. Homebridge verification is pending; this release does not claim certification. + +**Updating from a stable 1.0.x release?** Version 1.0.4 accepts successful commands that write stderr and adds debug stderr details. No configuration changes are required. [Quick start](#quick-start) · [Migration](#migration) · [Minimal configuration](#minimal-configuration) · [Settings reference](#settings-reference) · [Full example](#full-configuration-example) · [Advanced behavior](#advanced-behavior) · [FAQ](#troubleshooting-faq) · [Changelog](CHANGELOG.md) @@ -30,7 +32,7 @@ See [advanced behavior](#advanced-behavior) for execution details and [the featu 1. Save a Homebridge backup and your full config.json. 2. Follow [Migration](#migration) if you use an older configuration. -3. In Homebridge UI, install Script2 and select **1.0.2** / **latest** using the plugin version selector. +3. In Homebridge UI, install Script2 and select **1.0.4** / **latest** using the plugin version selector. 4. For a new setup, open Settings and add an **On/Off switch** or a **Stateless switch**. Enter your commands; On/Off switches also need a state command or state file. For an existing valid setup, keep your current entries. 5. Review Advanced settings if needed, use Homebridge Save, then restart the instance or child bridge running Script2. Opening or saving settings never runs commands. @@ -216,9 +218,11 @@ A state-read result uses this format: GetState : ON/OFF (path: , source: ) ``` -The request origin is `homekit-get` or `polling`; the state source is `state-script`, `ttl-cache`, `in-flight-coalesced`, or `file-state`. Errors identify the accessory and action. Raw commands, stdout, and stderr are omitted from plugin diagnostics because scripts may contain credentials. +The request origin is `homekit-get` or `polling`; the state source is `state-script`, `ttl-cache`, `in-flight-coalesced`, or `file-state`. Errors identify the accessory and action. Raw commands and stdout are omitted from plugin diagnostics. When a command writes nonblank stderr, Script2 logs a warning without its contents; enable Homebridge debug logging to see the stderr text, limited to 4,096 characters with control characters escaped. Debug stderr may contain credentials or other sensitive script output; remove secrets before sharing logs. + +ON/OFF and trigger commands succeed when they exit `0`, even if they write stderr. Nonzero exits, timeouts, termination, and other execution errors still fail. This applies to both command-based and file-based state; changing a state file does not override an action command failure. -Timeouts, terminated state commands, and output overflow are failures even if partial output was printed. For an ordinary nonzero state-command exit, `fail_on_state_exit_code` determines whether otherwise usable stdout can still determine state. ON/OFF and trigger commands retain their stderr-as-failure policy. +Timeouts, terminated state commands, and output overflow are failures even if partial output was printed. For an ordinary nonzero state-command exit, `fail_on_state_exit_code` determines whether otherwise usable stdout can still determine state. Its default is `false`: log the nonzero exit and use usable stdout; enable it to return the state-read error to HomeKit. This setting applies only to the state command, and stderr alone does not cause a state-read failure. ### Storage and shutdown @@ -374,3 +378,4 @@ sudo -u homebridge /home/homebridge/scripts/light_off.sh --- Originally based on [homebridge-script](https://github.com/xxcombat/homebridge-script). + diff --git a/index.js b/index.js index 64dac0c..e5b4695 100644 --- a/index.js +++ b/index.js @@ -209,6 +209,17 @@ Script2DeviceLogic.prototype.formatCommandDiagnostics = function (action, comman return `${this.name}: ${action} command ${error?.killed ? "timed out or was terminated" : "failed"} (exit code: ${code}). Check the script as the Homebridge service user. Command text and output are omitted.`; }; +Script2DeviceLogic.prototype.logCommandStderr = function (action, stderr) { + const output = String(stderr ?? "").trim(); + if (!output) return; + this.log.warn(`${this.name}: ${action} command wrote to stderr (enable Homebridge debug logging for details).`); + // Keep diagnostic output bounded and escape control characters so script output + // cannot insert terminal sequences or impersonate another log entry. + const limit = 4096; + const preview = JSON.stringify(output.slice(0, limit)); + this.log.debug(`${this.name}: ${action} command stderr: ${preview}${output.length > limit ? " [truncated]" : ""}`); +}; + Script2DeviceLogic.prototype.executeCommand = function (command, options, callback) { if (this.stopped) return; let child; @@ -424,13 +435,13 @@ Script2DeviceLogic.prototype.startSetCommand = function (setRequest) { let callbackError = null; - if (error || stderr) { + this.logCommandStderr(action, stderr); + if (error) { const diagnostics = this.formatCommandDiagnostics(action, command, error, stdout, stderr); const errMessage = `Set State returned an error. ${diagnostics}`; this.log.error(`Set State returned an error: ${errMessage}`); callbackError = new Error(errMessage); } else { - const commandOutput = stdout.trim().toLowerCase(); this.log.debug(`${this.name}: set command completed.`); this.currentState = powerOn; @@ -627,9 +638,7 @@ Script2DeviceLogic.prototype.getState = function ( const cleanCommandOutput = stdout.trim().toLowerCase(); this.log.debug(`${this.name}: state command returned output.`); - if (stderr && stderr.trim().length > 0) { - this.log.warn(`${this.name}: state command wrote to stderr (output omitted).`); - } + this.logCommandStderr("state", stderr); if (!cleanCommandOutput) { const diagnostics = this.formatCommandDiagnostics("state", command, error, stdout, stderr); @@ -684,7 +693,8 @@ Script2DeviceLogic.prototype.setStatelessTrigger = function (powerOn, callback) this.commandExecutor(this.triggerCommand, { timeout: this.commandTimeout }, (error, stdout, stderr) => { this.triggerInFlight = false; const callbacks = this.triggerCallbacks.splice(0); - const failure = error || stderr ? new Error(this.formatCommandDiagnostics("trigger", this.triggerCommand, error)) : null; + this.logCommandStderr("trigger", stderr); + const failure = error ? new Error(this.formatCommandDiagnostics("trigger", this.triggerCommand, error)) : null; if (failure) this.log.error(failure.message); else this.log.info(`Triggered ${this.name} stateless action`); for (const cb of callbacks) cb(failure, failure ? null : powerOn); @@ -782,3 +792,4 @@ Script2DeviceLogic.prototype.updateReachabilityFault = function (hasFault) { module.exports.Script2DeviceLogic = Script2DeviceLogic; module.exports.Script2Platform = Script2Platform; + diff --git a/package-lock.json b/package-lock.json index 4a56cca..dabaf60 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "homebridge-script2", - "version": "1.0.3", + "version": "1.0.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "homebridge-script2", - "version": "1.0.3", + "version": "1.0.4", "license": "MIT", "dependencies": { "@homebridge/plugin-ui-utils": "2.2.6", @@ -89,3 +89,4 @@ } } } + diff --git a/package.json b/package.json index 3154cc8..3145dff 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "homebridge-script2", - "version": "1.0.3", + "version": "1.0.4", "license": "MIT", "description": "HomeKit script switches with file or command state, shared reads, serialized actions and optional early acknowledgement", "keywords": [ @@ -63,3 +63,4 @@ "ajv": "8.17.1" } } + diff --git a/releases/v1.0.4.md b/releases/v1.0.4.md new file mode 100644 index 0000000..a9747cf --- /dev/null +++ b/releases/v1.0.4.md @@ -0,0 +1,23 @@ +# Script2 1.0.4 + +**Users on version 1.0.x can update normally. No configuration changes or migration are required. This also applies to 1.0.0-beta.1.** + +## ⚠️ Upgrading from a version before 1.0.0 + +**Only these older versions require migration. Back up your Homebridge config.json before updating, then follow the [migration guide](https://github.com/pponce/homebridge-script2/blob/master/MIGRATION.md).** Legacy Script2 accessory mode and old platform configuration formats are no longer supported. + +## Successful commands with stderr + +- ON/OFF and stateless trigger commands that exit `0` now succeed even when they write stderr. This also applies to ON/OFF scripts that create or delete a state file, and addresses the failure mechanism suspected in [issue #125](https://github.com/pponce/homebridge-script2/issues/125). +- Nonzero action exits, timeouts, termination, and other execution errors still return failures to HomeKit. +- Preserve the state-script policy from [issue #29](https://github.com/pponce/homebridge-script2/issues/29): by default, log ordinary nonzero exits and use usable stdout; with `fail_on_state_exit_code` enabled, return a state-read error to HomeKit. This option applies only to state scripts. + +## Stderr diagnostics + +- Normal logs show a warning when ON, OFF, trigger, or state commands write nonblank stderr. +- Enable Homebridge debug logging to see stderr text, limited to 4,096 characters with control characters escaped. +- Raw command text and stdout remain omitted. Debug stderr may contain credentials or other sensitive script output; remove secrets before sharing logs. + +## Update + +Select **1.0.4** / **latest** in Homebridge UI and restart the instance or child bridge running Script2. diff --git a/scripts/check-publisher.py b/scripts/check-publisher.py index 10d42fa..2d08407 100644 --- a/scripts/check-publisher.py +++ b/scripts/check-publisher.py @@ -7,7 +7,8 @@ import sys for script in ["scripts/publish-beta.sh", "scripts/update-and-publish-beta.txt", - "scripts/publish-stable.sh", "scripts/update-and-publish-stable.txt"]: + "scripts/publish-stable.sh", "scripts/update-and-publish-stable.txt", + "scripts/release-tools.sh"]: subprocess.run(["bash", "-n", script], check=True) channel = sys.argv[1] if len(sys.argv) > 1 else "beta" assert channel in ("beta", "stable") @@ -50,3 +51,6 @@ print(output.decode()) assert os.waitstatus_to_exitcode(status) == 0 assert b"PASS:" in output +if channel == 'stable': + subprocess.run([sys.executable, 'scripts/check-release-tools.py'], check=True) + diff --git a/scripts/check-release-tools.py b/scripts/check-release-tools.py new file mode 100644 index 0000000..6024fd0 --- /dev/null +++ b/scripts/check-release-tools.py @@ -0,0 +1,61 @@ +"""Verify the contained CLI bootstrap with a local archive and no network calls.""" +import hashlib +import io +import os +from pathlib import Path +import subprocess +import tarfile +import tempfile + +source = Path('scripts/release-tools.sh').read_text() +with tempfile.TemporaryDirectory(prefix='script2-tools-check-') as directory: + root = Path(directory) + mock_bin = root / 'mock-bin' + mock_bin.mkdir() + archive = root / 'fixture.tar.gz' + binary = b'#!/bin/sh\necho "gh version 2.102.0 (fixture)"\n' + with tarfile.open(archive, 'w:gz') as tar: + info = tarfile.TarInfo('gh_2.102.0_linux_amd64/bin/gh') + info.size = len(binary) + info.mode = 0o755 + tar.addfile(info, io.BytesIO(binary)) + fixture_digest = hashlib.sha256(archive.read_bytes()).hexdigest() + probe_source = source.replace('bb766f710eef8ede859c18578c72c327597cd4c8a85b06001b1f3843c6019386', fixture_digest) + helper = root / 'helper.sh' + helper.write_text(probe_source) + (mock_bin / 'uname').write_text('#!/bin/sh\necho "Linux x86_64"\n') + (mock_bin / 'curl').write_text('''#!/usr/bin/env python3 +import os +from pathlib import Path +import shutil +import sys +destination = sys.argv[sys.argv.index('--output') + 1] +shutil.copyfile(os.environ['SCRIPT2_FIXTURE_ARCHIVE'], destination) +with open(os.environ['SCRIPT2_DOWNLOAD_COUNTER'], 'a') as counter: + counter.write('download\\n') +''') + for executable in mock_bin.iterdir(): + executable.chmod(0o755) + env = dict(os.environ, PATH=str(mock_bin) + ':' + os.environ['PATH'], + SCRIPT2_FIXTURE_ARCHIVE=str(archive), SCRIPT2_DOWNLOAD_COUNTER=str(root / 'downloads.txt')) + checkout = root / 'checkout' + checkout.mkdir() + program = '''set -euo pipefail +. "$1" +script2_setup_release_tools "$2" +case "$(command -v gh)" in "$2"/release-work/tools/*) ;; *) exit 1 ;; esac +test "$TMPDIR" = "$2/release-work/tmp" +test "$npm_config_cache" = "$2/release-work/npm-cache" +script2_setup_release_tools "$2" +''' + subprocess.run(['bash', '-c', program, 'probe', str(helper), str(checkout)], env=env, check=True) + assert (root / 'downloads.txt').read_text().splitlines() == ['download'] + broken_checkout = root / 'broken-checkout' + broken_checkout.mkdir() + archive.write_bytes(b'invalid archive') + failed = subprocess.run(['bash', '-c', program, 'probe', str(helper), str(broken_checkout)], + env=env, capture_output=True, text=True) + assert failed.returncode != 0 + assert 'checksum mismatch' in failed.stderr + assert not (broken_checkout / 'release-work/tools/github-cli-2.102.0/gh_2.102.0_linux_amd64/bin/gh').exists() +print('PASS: CLI files stay in release-work, verified downloads are reused, and bad downloads stop before extraction.') diff --git a/scripts/publish-stable.sh b/scripts/publish-stable.sh index 2e3fea1..b3ad550 100644 --- a/scripts/publish-stable.sh +++ b/scripts/publish-stable.sh @@ -6,6 +6,8 @@ script2_repo='pponce/homebridge-script2' script2_branch='master' script2_registry='https://registry.npmjs.org/' export GH_HOST=github.com +unset GH_TOKEN GITHUB_TOKEN GH_PROMPT_DISABLED +export GH_BROWSER=echo # The SSH wrapper reads its program from a heredoc. Reconnect interactive # commands to the terminal so npm can wait for browser authentication. if ! ( : /dev/null; then @@ -13,19 +15,28 @@ if ! ( : /dev/null; then false fi script2_interactive() { "$@" /dev/tty; } -for script2_tool in git node npm tar gh; do command -v "$script2_tool" >/dev/null; done -cd "$(git rev-parse --show-toplevel)" +for script2_tool in git node npm tar curl; do command -v "$script2_tool" >/dev/null; done +script2_project_root="$(git rev-parse --show-toplevel)" +cd "$script2_project_root" if [ "$(git branch --show-current)" != "$script2_branch" ]; then echo 'STOP: switch to master first.'; false; fi if [ -n "$(git status --porcelain)" ]; then echo 'STOP: commit or move local changes before publishing.'; false; fi case "$(git remote get-url origin)" in git@github.com:pponce/homebridge-script2.git|https://github.com/pponce/homebridge-script2.git|https://github.com/pponce/homebridge-script2|ssh://git@github.com/pponce/homebridge-script2.git) ;; *) echo 'STOP: unexpected origin repository.'; false ;; esac +git remote set-url origin git@github.com:pponce/homebridge-script2.git +. "$script2_project_root/scripts/release-tools.sh" +script2_setup_release_tools "$script2_project_root" git fetch origin "$script2_branch" script2_source="$(git rev-parse HEAD)" if [ "$script2_source" != "$(git rev-parse "origin/$script2_branch")" ]; then echo 'STOP: local branch must match its remote commit.'; false; fi node -e 'const [a,b]=process.versions.node.split(".").map(Number); if(!((a===22&&b>=13)||a===24))throw Error("Use Node 22.13+ within Node 22, or Node 24.");' -if ! gh auth status --hostname github.com >/dev/null 2>&1; then script2_interactive gh auth login --hostname github.com --git-protocol ssh --web --skip-ssh-key; fi +script2_gh_user="$(gh api user --jq .login 2>/dev/null || true)" +if [ "$script2_gh_user" != 'pponce' ]; then + echo 'GitHub API login is needed to create the official release.' + echo 'Open the displayed URL in your browser, enter the displayed code, and authenticate as pponce.' + script2_interactive gh auth login --hostname github.com --git-protocol ssh --web --skip-ssh-key +fi script2_gh_user="$(gh api user --jq .login)" if [ "$script2_gh_user" != 'pponce' ]; then echo 'STOP: GitHub account must be pponce.'; false; fi script2_npm_user="$(npm whoami --registry="$script2_registry" 2>/dev/null || true)" @@ -35,22 +46,24 @@ if [ "$script2_npm_user" != 'klidec' ]; then fi script2_npm_user="$(npm whoami --registry="$script2_registry")" if [ "$script2_npm_user" != 'klidec' ]; then echo 'STOP: npm account must be klidec.'; false; fi -script2_work="$(mktemp -d "${TMPDIR:-/tmp}/script2-stable.XXXXXX")" +mkdir -p "$script2_project_root/release-work/1.0.4" +script2_work="$(mktemp -d "$script2_project_root/release-work/1.0.4/build-XXXXXX")" echo "Source commit: $script2_source" echo "Accounts verified: GitHub $script2_gh_user; npm $script2_npm_user" echo "Release work directory: $script2_work" git archive "$script2_source" | tar -x -C "$script2_work" git ls-remote --tags origin > "$script2_work/remote-tags.txt" cd "$script2_work" -node -e 'const p=require("./package.json");if(p.name!=="homebridge-script2"||p.version!=="1.0.3"||p.publishConfig?.tag!=="latest")throw Error("Expected Script2 1.0.3 stable metadata.");' +node -e 'const p=require("./package.json");if(p.name!=="homebridge-script2"||p.version!=="1.0.4"||p.publishConfig?.tag!=="latest")throw Error("Expected Script2 1.0.4 stable metadata.");' script2_version="$(node -p 'require("./package.json").version')" script2_tag="v$script2_version" script2_notes="releases/$script2_tag.md" test -s "$script2_notes" +node -e 'const fs=require("fs"),p=require("./package.json"),lock=require("./package-lock.json");if(lock.version!==p.version||lock.packages[""].version!==p.version)throw Error("Package and lockfile versions differ.");if(!fs.readFileSync("CHANGELOG.md","utf8").includes(`## ${p.version} —`))throw Error("Versioned changelog entry is missing.");if(!fs.readFileSync(`releases/v${p.version}.md`,"utf8").startsWith(`# Script2 ${p.version}\n`))throw Error("Release notes version does not match.");' node -e 'const fs=require("fs"),p=require("./package.json");if(fs.readFileSync("remote-tags.txt","utf8").split("\n").some(l=>l.split(/\s+/)[1]===`refs/tags/v${p.version}`))throw Error("Tag already exists; it will not be moved.");' gh api "repos/$script2_repo/releases?per_page=100" --paginate --jq '.[].tag_name' > github-releases.txt node -e 'const fs=require("fs"),p=require("./package.json");if(fs.readFileSync("github-releases.txt","utf8").split("\n").includes(`v${p.version}`))throw Error("GitHub release already exists.");' -npm view homebridge-script2 versions --json --registry="$script2_registry" > published-versions.json +npm view homebridge-script2 versions --json --prefer-online --registry="$script2_registry" > published-versions.json node -e 'const p=require("./package.json"),v=require("./published-versions.json");if(!Array.isArray(v)||v.includes(p.version))throw Error("Version already published or unexpected registry response. Do not republish an existing version.");' npm view homebridge-script2 dist-tags.latest --registry="$script2_registry" > stable-before.txt @@ -82,9 +95,23 @@ else echo 'Do not publish the same npm version again.' false fi -npm view homebridge-script2 dist-tags --json --prefer-online --registry="$script2_registry" > stable-after.json -node -e 'const fs=require("fs"); const tags=JSON.parse(fs.readFileSync("stable-after.json","utf8")); const expected=require("./package.json").version; if(tags.latest!==expected) throw Error(`Publication completed, but npm latest reports ${tags.latest}; expected ${expected}. Check dist-tags; do not republish.`);' +gh api "repos/$script2_repo/releases/tags/$script2_tag" > github-release.json +node -e 'const fs=require("fs"),p=require("./package.json"),r=require("./github-release.json"),notes=fs.readFileSync(`releases/v${p.version}.md`,"utf8");if(r.draft||r.prerelease||r.tag_name!==`v${p.version}`||r.body.trim()!==notes.trim())throw Error("GitHub release or release notes do not match the stable package.");' +script2_latest='' +for script2_attempt in {1..12}; do + script2_latest="$(npm view homebridge-script2 dist-tags.latest --prefer-online --registry="$script2_registry" 2>/dev/null || true)" + if [ "$script2_latest" = "$script2_version" ]; then break; fi + if [ "$script2_attempt" -lt 12 ]; then + echo 'Waiting for npm latest to reflect the new publication...' + sleep 5 + fi +done +if [ "$script2_latest" != "$script2_version" ]; then + echo "STOP: publication completed, but npm latest reports $script2_latest; expected $script2_version. Check dist-tags; do not republish." + false +fi echo "Stable release is ready: homebridge-script2@$script2_version (latest)." echo "GitHub: https://github.com/$script2_repo/releases/tag/$script2_tag" echo 'Homebridge review: https://github.com/homebridge/plugins/issues/new/choose' echo 'Install/update Script2 in Homebridge UI, then restart its instance or child bridge.' + diff --git a/scripts/release-tools.sh b/scripts/release-tools.sh new file mode 100644 index 0000000..4ddb581 --- /dev/null +++ b/scripts/release-tools.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# Source this helper, then call script2_setup_release_tools with the checkout root. +script2_setup_release_tools() { + local script2_root="$1" script2_arch script2_digest script2_tool_root script2_gh_binary + case "$(uname -sm)" in + 'Linux x86_64') + script2_arch='amd64' + script2_digest='bb766f710eef8ede859c18578c72c327597cd4c8a85b06001b1f3843c6019386' + ;; + 'Linux aarch64'|'Linux arm64') + script2_arch='arm64' + script2_digest='7862c86c72f43df3a2d93ddde6f473285b4e2af61b494849846827e513ef6484' + ;; + *) echo 'STOP: run this release helper on the Linux machine containing the checkout.'; return 1 ;; + esac + script2_tool_root="$script2_root/release-work/tools/github-cli-2.102.0" + script2_gh_binary="$script2_tool_root/gh_2.102.0_linux_$script2_arch/bin/gh" + mkdir -p "$script2_tool_root" "$script2_root/release-work/tmp" "$script2_root/release-work/npm-cache" + export TMPDIR="$script2_root/release-work/tmp" + export npm_config_cache="$script2_root/release-work/npm-cache" + if [ ! -x "$script2_gh_binary" ]; then + echo "Downloading GitHub CLI 2.102.0 into $script2_tool_root" + curl --fail --location --silent --show-error \ + --output "$script2_tool_root/github-cli.tar.gz.download" \ + "https://github.com/cli/cli/releases/download/v2.102.0/gh_2.102.0_linux_$script2_arch.tar.gz" + node -e 'const fs=require("node:fs"),crypto=require("node:crypto"); const actual=crypto.createHash("sha256").update(fs.readFileSync(process.argv[1])).digest("hex"); if(actual!==process.argv[2])throw Error("GitHub CLI download checksum mismatch.");' \ + "$script2_tool_root/github-cli.tar.gz.download" "$script2_digest" + mv "$script2_tool_root/github-cli.tar.gz.download" "$script2_tool_root/github-cli.tar.gz" + tar -xzf "$script2_tool_root/github-cli.tar.gz" -C "$script2_tool_root" + fi + export PATH="${script2_gh_binary%/gh}:$PATH" + gh --version +} diff --git a/scripts/update-and-publish-stable.txt b/scripts/update-and-publish-stable.txt index 24730c1..e61aa20 100644 --- a/scripts/update-and-publish-stable.txt +++ b/scripts/update-and-publish-stable.txt @@ -1,10 +1,15 @@ { - echo '===== BEGIN SCRIPT2 1.0.2 — COPY OUTPUT FROM HERE =====' + echo '===== BEGIN SCRIPT2 1.0.4 — COPY OUTPUT FROM HERE =====' bash <<'SCRIPT2_STABLE' set -e set -o pipefail -trap 'script2_status=$?; echo "===== END SCRIPT2 1.0.2 — STATUS $script2_status — COPY THROUGH HERE ====="' EXIT +trap 'script2_status=$?; echo "===== END SCRIPT2 1.0.4 — STATUS $script2_status — COPY THROUGH HERE ====="' EXIT +script2_repo='pponce/homebridge-script2' +export GH_HOST=github.com +unset GH_TOKEN GITHUB_TOKEN GH_PROMPT_DISABLED +export GH_BROWSER=echo cd "$HOME/devProjects/homebridge-script2" +for script2_tool in git node npm tar curl; do command -v "$script2_tool" >/dev/null; done if [ -n "$(git status --porcelain)" ]; then echo 'STOP: local changes found. Commit or move them before updating.' false @@ -13,6 +18,21 @@ case "$(git remote get-url origin)" in git@github.com:pponce/homebridge-script2.git|https://github.com/pponce/homebridge-script2.git|https://github.com/pponce/homebridge-script2|ssh://git@github.com/pponce/homebridge-script2.git) ;; *) echo 'STOP: unexpected origin repository.'; false ;; esac +git remote set-url origin git@github.com:pponce/homebridge-script2.git +script2_project_root="$(git rev-parse --show-toplevel)" +. "${SCRIPT2_RELEASE_TOOLS:-$script2_project_root/scripts/release-tools.sh}" +script2_setup_release_tools "$script2_project_root" +script2_gh_user="$(gh api user --jq .login 2>/dev/null || true)" +if [ "$script2_gh_user" != 'pponce' ]; then + echo 'Open the displayed GitHub URL and enter the displayed code. Sign in as pponce.' + gh auth login --hostname github.com --git-protocol ssh --web --skip-ssh-key /dev/tty +fi +if [ "$(gh api user --jq .login)" != 'pponce' ]; then echo 'STOP: GitHub account must be pponce.'; false; fi +script2_head="${SCRIPT2_RELEASE_HEAD:-}" +if [ -z "$script2_head" ]; then + git fetch origin fix/successful-command-stderr + script2_head="$(git rev-parse FETCH_HEAD)" +fi git fetch origin master if git show-ref --verify --quiet refs/heads/master; then git switch master @@ -20,6 +40,29 @@ else git switch --track -c master origin/master fi git pull --ff-only origin master +if [ "$(git rev-parse HEAD)" != "$(git rev-parse origin/master)" ]; then echo 'STOP: local master has unpublished commits.'; false; fi +if [ "$(gh pr view 126 --repo "$script2_repo" --json headRefOid --jq .headRefOid)" != "$script2_head" ]; then + echo 'STOP: PR #126 changed since this release block was prepared.' + false +fi +case "$(gh pr view 126 --repo "$script2_repo" --json state --jq .state)" in + OPEN) + gh pr checks 126 --repo "$script2_repo" --watch --fail-fast + if [ "$(gh pr view 126 --repo "$script2_repo" --json isDraft --jq .isDraft)" = 'true' ]; then + gh pr ready 126 --repo "$script2_repo" + fi + gh pr merge 126 --repo "$script2_repo" --merge --match-head-commit "$script2_head" + ;; + MERGED) echo 'PR #126 is already merged.' ;; + *) echo 'STOP: PR #126 is closed without merging.'; false ;; +esac +script2_merge="$(gh pr view 126 --repo "$script2_repo" --json mergeCommit --jq .mergeCommit.oid)" +git fetch origin master +git pull --ff-only origin master +git merge-base --is-ancestor "$script2_merge" HEAD +node -e 'if(require("./package.json").version!=="1.0.4")throw Error("Expected Script2 1.0.4.");' bash scripts/publish-stable.sh +git fetch origin --tags SCRIPT2_STABLE } + diff --git a/test/reliability.test.js b/test/reliability.test.js index dbe61da..c7ff32f 100644 --- a/test/reliability.test.js +++ b/test/reliability.test.js @@ -89,8 +89,8 @@ test('stateless duplicate activation executes once and zero reset is retained', apiHarness();const {logic,calls}=harness({device_type:'stateless',trigger:'trigger',auto_reset_ms:0});const updates=[];logic.switchService={updateCharacteristic:(c,v)=>updates.push(v)};let count=0; logic.setStatelessTrigger(true,()=>count++);logic.setStatelessTrigger(true,()=>count++);assert.equal(calls.length,1);calls[0].callback(null,'','');await new Promise(r=>setTimeout(r,10));assert.equal(count,2);assert.deepEqual(updates,[false]);logic.shutdown(); }); -test('command diagnostics and failing loggers do not leak or replay commands', () => { - const {logic,calls,logs}=harness({on:'secret-password'});logic.setState(true,()=>{});calls[0].callback(new Error('secret-password'),'secret-password','secret-password');assert.ok(!JSON.stringify(logs).includes('secret-password')); +test('normal command diagnostics and failing loggers do not leak or replay commands', () => { + const {logic,calls,logs}=harness({on:'secret-password'});logic.setState(true,()=>{});calls[0].callback(new Error('secret-password'),'secret-password','secret-password');assert.ok(!JSON.stringify(logs.filter(([level])=>level!=='debug')).includes('secret-password')); const bad=Object.fromEntries(['debug','info','warn','error'].map(l=>[l,()=>{throw new Error('logger');}]));let done=0; const d=new Script2DeviceLogic(bad,valid,(c,o,cb)=>cb(null,'',''));d.setState(true,()=>done++);assert.equal(done,1); }); @@ -98,3 +98,4 @@ test('real external process deadline is bounded and does not use partial output' const {logic}=harness({command_timeout:100,state:`"${process.execPath}" -e "console.log('true');setTimeout(()=>{},10000)"`},require('node:child_process').exec); const error=await new Promise(resolve=>logic.getState(resolve));assert.ok(error);assert.equal(logic.lastStateRead,null);logic.shutdown(); }); + diff --git a/test/stderr.test.js b/test/stderr.test.js new file mode 100644 index 0000000..6a7366f --- /dev/null +++ b/test/stderr.test.js @@ -0,0 +1,144 @@ +'use strict'; +const assert = require('node:assert/strict'); +const test = require('node:test'); +const { exec } = require('node:child_process'); +const { mkdtemp, rm } = require('node:fs/promises'); +const { existsSync } = require('node:fs'); +const { tmpdir } = require('node:os'); +const { join } = require('node:path'); +const { Script2DeviceLogic } = require('../index'); + +function harness(t, config = {}, debug = false, executor) { + const commands = [], logs = []; + const logger = Object.fromEntries(['debug', 'info', 'warn', 'error'].map(level => [level, message => { + if (level !== 'debug' || debug) logs.push([level, message]); + }])); + const logic = new Script2DeviceLogic(logger, { + name: 'Lamp', on: 'on-command', off: 'off-command', state: 'state-command', + ...config, + }, executor || ((command, options, callback) => commands.push({ command, callback }))); + t.after(() => logic.shutdown()); + return { logic, commands, logs }; +} + +for (const source of ['state', 'fileState']) { + test(`successful ON/OFF stderr does not fail HomeKit with ${source}`, t => { + const config = source === 'fileState' ? { state: undefined, fileState: join(tmpdir(), 'script2-stderr.flag') } : {}; + const { logic, commands, logs } = harness(t, config); + const results = [], reads = []; + logic.setState(true, (error, value) => results.push({ error, value })); + logic.setState(false, (error, value) => results.push({ error, value })); + logic.getState((error, value) => reads.push({ error, value })); + commands[0].callback(null, '', 'ON progress\n'); + assert.equal(commands[1].command, 'off-command'); + commands[1].callback(null, '', 'OFF progress\n'); + assert.deepEqual(results, [{ error: null, value: true }, { error: null, value: false }]); + assert.deepEqual(reads, [{ error: null, value: false }]); + assert.equal(logic.inFlightSet, null); + assert.equal(logic.currentState, false); + assert.equal(logs.filter(([level]) => level === 'warn').length, 2); + assert.ok(!logs.some(([level]) => level === 'error')); + }); +} + +test('real ON/OFF processes exit zero with stderr and update the state file', async t => { + const dir = await mkdtemp(join(tmpdir(), 'script2-stderr-')); + const flag = join(dir, 'state.flag'); + t.after(() => rm(dir, { recursive: true, force: true })); + const command = code => `"${process.execPath}" -e '${code.replaceAll("'", "'\\''")}'`; + const { logic, logs } = harness(t, { + state: undefined, fileState: flag, + on: command(`require("node:fs").writeFileSync(${JSON.stringify(flag)}, ""); console.error("ON progress");`), + off: command(`require("node:fs").unlinkSync(${JSON.stringify(flag)}); console.error("OFF progress");`), + }, false, exec); + for (const requested of [true, false]) { + const value = await new Promise((resolve, reject) => logic.setState(requested, (error, result) => error ? reject(error) : resolve(result))); + assert.equal(value, requested); + assert.equal(existsSync(flag), requested); + const read = await new Promise((resolve, reject) => logic.getState((error, result) => error ? reject(error) : resolve(result))); + assert.equal(read, requested); + } + assert.equal(logs.filter(([level]) => level === 'warn').length, 2); +}); + +test('stderr warns by default without exposing command or output', t => { + const { logic, commands, logs } = harness(t, { on: 'secret-command' }); + logic.setState(true, () => {}); + commands[0].callback(null, 'secret-stdout', 'secret-stderr'); + const text = JSON.stringify(logs); + assert.match(text, /on command wrote to stderr/); + assert.doesNotMatch(text, /secret-command|secret-stdout|secret-stderr/); +}); + +test('debug shows stderr for actions and state reads without exposing command or stdout', t => { + const { logic, commands, logs } = harness(t, { on: 'secret-command' }, true); + logic.setState(true, () => {}); + commands[0].callback(null, 'secret-stdout', 'action detail'); + logic.getState(() => {}); + commands[1].callback(null, 'true', 'state detail'); + const debugText = logs.filter(([level]) => level === 'debug').map(([, message]) => message).join('\n'); + assert.match(debugText, /on command stderr: "action detail"/); + assert.match(debugText, /state command stderr: "state detail"/); + assert.doesNotMatch(debugText, /secret-command|secret-stdout/); +}); + +test('debug stderr is bounded and control characters are escaped', t => { + const { logic, commands, logs } = harness(t, {}, true); + logic.setState(true, () => {}); + commands[0].callback(null, '', 'detail\n\u001b[31m' + 'x'.repeat(5000)); + const message = logs.find(([level, text]) => level === 'debug' && text.includes('command stderr:'))[1]; + assert.ok(!message.includes('\n') && !message.includes('\u001b')); + assert.ok(message.includes('\\n') && message.includes('\\u001b')); + assert.match(message, /\[truncated\]$/); + const quoted = message.slice(message.indexOf('stderr: ') + 8, -' [truncated]'.length); + assert.equal(JSON.parse(quoted).length, 4096); +}); + +test('blank stderr produces no warning or stderr debug entry', t => { + const { logic, commands, logs } = harness(t, {}, true); + logic.setState(true, () => {}); + commands[0].callback(null, '', ' \n\t'); + assert.ok(!logs.some(([level, message]) => level === 'warn' || message.includes('stderr'))); +}); + +for (const failure of [ + { code: 1 }, { killed: true }, { signal: 'SIGTERM' }, { code: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' }, +]) { + test(`ON/OFF execution failure stays an error with stderr: ${JSON.stringify(failure)}`, t => { + const { logic, commands } = harness(t, { state: undefined, fileState: join(tmpdir(), 'script2-stderr.flag') }); + let received; + logic.setState(true, (error, value) => { received = { error, value }; }); + commands[0].callback(Object.assign(new Error('failure'), failure), '', 'error detail'); + assert.ok(received.error instanceof Error); + assert.equal(received.value, null); + assert.equal(logic.inFlightSet, null); + }); +} + +for (const strict of [false, true]) { + test(`state exit-code policy stays unchanged with stderr (strict=${strict})`, t => { + const { logic, commands, logs } = harness(t, { fail_on_state_exit_code: strict, state_cache_ttl_ms: 0 }); + let received; + logic.getState((error, value) => { received = { error, value }; }); + commands[0].callback(null, 'true', 'state warning'); + assert.deepEqual(received, { error: null, value: true }); + logic.getState((error, value) => { received = { error, value }; }); + commands[1].callback(Object.assign(new Error('nonzero'), { code: 1 }), 'true', 'state warning'); + assert.equal(Boolean(received.error), strict); + assert.equal(received.value, strict ? null : true); + assert.ok(logs.some(([level, message]) => ['warn', 'error'].includes(level) && message.includes('exited non-zero'))); + }); +} + +test('stateless trigger succeeds with stderr and still rejects nonzero exits', t => { + const { logic, commands, logs } = harness(t, { device_type: 'stateless', trigger: 'trigger-command', auto_reset_ms: 0 }, true); + const results = []; + logic.setStatelessTrigger(true, (error, value) => results.push({ error, value })); + commands[0].callback(null, '', 'trigger progress'); + assert.deepEqual(results[0], { error: null, value: true }); + assert.ok(logs.some(([level, message]) => level === 'debug' && message.includes('trigger command stderr: "trigger progress"'))); + logic.setStatelessTrigger(true, (error, value) => results.push({ error, value })); + commands[1].callback(Object.assign(new Error('failure'), { code: 1 }), '', 'trigger failure'); + assert.ok(results[1].error instanceof Error); + assert.equal(results[1].value, null); +});