diff --git a/README.md b/README.md index db10d64..c0a170a 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ **Automatic backup, history tracking, and instant restore for your Home Assistant configuration.** -[![Release](https://img.shields.io/github/v/release/saihgupr/HomeAssistantVersionControl?style=flat-square&label=release)](https://github.com/saihgupr/HomeAssistantVersionControl/releases) [![Docker pulls](https://img.shields.io/badge/Docker_pulls-58.4K-blue?style=flat-square&logo=docker)](https://github.com/saihgupr/HomeAssistantVersionControl/pkgs/container/home-assistant-version-control) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow?style=flat-square)](https://github.com/saihgupr/HomeAssistantVersionControl/blob/main/LICENSE) +[![Release](https://img.shields.io/github/v/release/saihgupr/HomeAssistantVersionControl?style=flat-square&label=release)](https://github.com/saihgupr/HomeAssistantVersionControl/releases) [![Docker pulls](https://img.shields.io/badge/Docker_pulls-61.9K-blue?style=flat-square&logo=docker)](https://github.com/saihgupr/HomeAssistantVersionControl/pkgs/container/home-assistant-version-control) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow?style=flat-square)](https://github.com/saihgupr/HomeAssistantVersionControl/blob/main/LICENSE) Home Assistant Version Control provides complete version history for your setup. It automatically tracks every change to your YAML configuration files using a robust local Git backend. Browse your history, visualize diffs, and restore individual files or your entire configuration to any previous state with a single click. @@ -14,20 +14,34 @@ Home Assistant Version Control provides complete version history for your setup. Version history navigation in the Home Assistant automation editor

-## What's New in v1.6! +## What's New in v1.7! -v1.6 focuses on cloud sync and hands-free reloads. +v1.7 adds API authentication for standalone Docker and cuts idle CPU. -* **Mirror Remote for Cloud Sync:** Add a second Git remote and every sync pushes to both. Use it for a redundant off-site copy, drift detection, or an audit repository. Mirror pushes are non-fatal, so a failure never blocks your primary backup. -* **Auto-reload Changed Components:** Optionally reload the Home Assistant domain that changed after each automatic backup. Edit automations, scripts, scenes, inputs, or templates and the matching reload service runs without a Developer Tools trip. Off by default. -* **Cleaner Cloud Sync Fields:** Token inputs no longer show the browser's password and autofill icons. +* **API Authentication for Docker:** The standalone container now asks for HTTP Basic auth on `/api/*`. It is on by default there. The username is `havc`, and the password is generated on first start and saved to `/data/api-password`. Set `HAVC_USERNAME` and `HAVC_PASSWORD` to choose your own, or `HAVC_API_AUTH=off` behind an authenticating reverse proxy. The add-on behind Ingress is unchanged. +* **Lower Idle CPU:** The watcher now ignores files HAVC can never commit, so polling no longer stats dependency folders, model caches, and other large directories. +* **Faster Startup Recovery:** A stale `.git/index.lock` is cleared after ten minutes, and startup and watcher retries now share one initialization run instead of racing for the git lock. ### Also in This Release +* **Optional Add-on Auth:** Added `api_auth` and `api_auth_password` for add-on users who publish port 54001 directly. +* **Input Validation:** Client-supplied paths and commit hashes are validated before use. +* **Exact-Match CORS:** `HAVC_ALLOWED_ORIGINS` takes an exact origin list instead of the old substring matching. + +
+v1.6 highlights + +v1.6 focused on cloud sync and hands-free reloads. + +* **Mirror Remote for Cloud Sync:** Add a second Git remote and every sync pushes to both. Use it for a redundant off-site copy, drift detection, or an audit repository. Mirror pushes are non-fatal, so a failure never blocks your primary backup. +* **Auto-reload Changed Components:** Optionally reload the Home Assistant domain that changed after each automatic backup. Edit automations, scripts, scenes, inputs, or templates and the matching reload service runs without a Developer Tools trip. Off by default. +* **Cleaner Cloud Sync Fields:** Token inputs no longer show the browser's password and autofill icons. * **Nested Git Repositories Documented:** Folders under `/config` with their own `.git` are skipped, so an ESPHome repo or similar no longer shows up as a broken submodule. * **Embedded Credentials (from v1.5.2):** Custom remotes using `user:pass@` or `token@` authenticate reliably during automatic pushes and connection tests. * **Masked Logs (from v1.5.1):** Tokens in remote URLs are redacted from startup logs and diagnostics. +
+
v1.5 highlights @@ -146,6 +160,9 @@ There are two ways to install Home Assistant Version Control: as a Home Assistan ### 2. Standalone Docker Installation +> [!WARNING] +> The standalone container requires API authentication by default. Requests to `/api/*` need HTTP Basic auth, while static files and the `/` healthcheck stay open. If you don't set `HAVC_PASSWORD`, a password is generated on first start, printed in the container logs as `[auth] API password: ...`, and saved to `/data/api-password` inside the container. Set `HAVC_USERNAME` and `HAVC_PASSWORD` to use your own credentials. Set `HAVC_API_AUTH=off` only when an authenticating reverse proxy already sits in front of the container. For internet exposure, keep an authenticating reverse proxy in front and leave the port closed on untrusted networks. +
Click to expand Docker deployment options @@ -163,6 +180,8 @@ For Docker users who aren't using the Home Assistant app, you have three deploym nano compose.yaml # Update the volume path: /path/to/your/ha/config # Update timezone: TZ environment variable (e.g., America/New_York) + # Optional: set HAVC_USERNAME and HAVC_PASSWORD for API authentication + # Without HAVC_PASSWORD the generated one is in /data/api-password and the container logs ``` 3. Start the service: @@ -170,7 +189,7 @@ For Docker users who aren't using the Home Assistant app, you have three deploym docker compose up -d ``` -Access the interface at `http://localhost:54001`. +Access the interface at `http://localhost:54001`. Log in with your `HAVC_USERNAME` and `HAVC_PASSWORD`, or with `havc` and the generated password from the logs or `/data/api-password`. **Option B: Docker Run (pre-built image):** @@ -179,6 +198,8 @@ docker run -d \ -p 54001:54001 \ -v /path/to/your/config:/config \ -e TZ=America/New_York \ + -e HAVC_USERNAME=havc \ + -e HAVC_PASSWORD=choose-a-strong-password \ -e SUPERVISOR_TOKEN=your_long_lived_access_token_here \ -e HA_URL=http://homeassistant.local:8123 \ --name home-assistant-version-control \ @@ -198,6 +219,8 @@ docker run -d \ -p 54001:54001 \ -v /path/to/your/config:/config \ -e TZ=America/New_York \ + -e HAVC_USERNAME=havc \ + -e HAVC_PASSWORD=choose-a-strong-password \ -e SUPERVISOR_TOKEN=your_long_lived_access_token_here \ -e HA_URL=http://homeassistant.local:8123 \ --name home-assistant-version-control \ @@ -207,6 +230,9 @@ docker run -d \ > [!NOTE] > The `SUPERVISOR_TOKEN` and `HA_URL` are optional. You can omit those lines if you don't need Home Assistant restart/reload features. +> [!NOTE] +> API authentication is on by default. If you don't set `HAVC_PASSWORD`, the generated password is printed in the container logs and saved to `/data/api-password`. Mount `/data` so it survives container recreation. Set `HAVC_API_AUTH=off` only when an authenticating reverse proxy already protects the container. + Access the interface at `http://localhost:54001`. ### Docker Data & Settings @@ -247,6 +273,8 @@ Notes: - Files are still filtered by `include_extensions` and `exclude_files`. - For `.conf` files, add `conf` to `include_extensions`. +By default the app relies on Ingress and Home Assistant authentication for the panel. If you expose port `54001` directly, set `api_auth: true` to require HTTP Basic auth on `/api/*`, and set `api_auth_password` to choose the password. If the password is left empty, HAVC generates one and stores it in `/data/api-password`. + #### Manual mode (existing git repositories) Set `manual_mode: true` if `/config` is already a git repository you manage yourself. The option is read before HAVC touches the repository, so it applies from the very first start, and when set it takes precedence over the toggle in the settings UI: diff --git a/compose.yaml b/compose.yaml index 08dd0c2..eda8857 100644 --- a/compose.yaml +++ b/compose.yaml @@ -18,6 +18,15 @@ services: # Optional: Home Assistant URL (required for Docker mode to enable reload/restart features) # Format: http://homeassistant.local:8123 or http://192.168.1.100:8123 - HA_URL=http://homeassistant.local:8123 + + # API authentication is on by default. Leave these commented out to use the + # generated password, which is written to /data/api-password and printed in + # the container logs as "[auth] API password: ...". + # - HAVC_USERNAME=havc + # - HAVC_PASSWORD=choose-a-strong-password + + # Set to off only if an authenticating reverse proxy sits in front of this container + # - HAVC_API_AUTH=off volumes: # Mount your Home Assistant config directory # This directory will be tracked for changes diff --git a/homeassistant-version-control/CHANGELOG.md b/homeassistant-version-control/CHANGELOG.md index 0f9f95f..6960739 100644 --- a/homeassistant-version-control/CHANGELOG.md +++ b/homeassistant-version-control/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## [Unreleased] + +## [1.7.0] + +### Security Hardening +- **API Authentication for Docker:** The standalone container can now ask for HTTP Basic auth on `/api/*` routes. It is on by default there because that deployment listens on the network. Static files and the `/` healthcheck stay open. If you do not set a password, one is generated on first start, written to `/data/api-password` (mode 0600), and printed in the container logs. Set `HAVC_USERNAME` and `HAVC_PASSWORD` to choose your own, or `HAVC_API_AUTH=off` when an authenticating reverse proxy already protects the container. +- **Add-on Authentication Option:** Added `api_auth` (default `false`) and `api_auth_password` for add-on users who publish port 54001 directly. With `api_auth` off, Ingress and Home Assistant authentication still protect the panel. +- **Exact-Match CORS Allowlist:** `HAVC_ALLOWED_ORIGINS` takes a comma-separated list of exact origins. No CORS headers are sent when the list is empty. + +### Fixed & Improved +- **Lower CPU Usage:** The watcher now ignores files HAVC can never commit (everything outside the configured extensions and whitelisted `.storage` files), so polling no longer stats `deps`, `tts`, `www`, model caches, and other large folders. Polling is off by default; enable it only for network mounts that need it. +- **Stale Git Lock Recovery:** A crashed git process could leave `.git/index.lock` behind and block every commit, which made the watcher retry initialization forever. The lock is now cleared on startup when it is older than ten minutes. +- **Serialized Initialization:** Startup and watcher retries now share one initialization run and retries are throttled, instead of racing each other for `index.lock` and spawning duplicate git processes. +- **Path and Commit Validation:** All client-supplied paths are checked for traversal, and invalid paths or commit hashes are rejected with `400`. +- **Quieter Health and Debug Endpoints:** `/api/health` and `/api/debug` no longer echo request headers. `/api/debug` only responds when `HAVC_DEBUG=1`. +- **Loopback by Default:** `HOST` now defaults to `127.0.0.1` for bare-metal runs. The Docker image sets `HOST=0.0.0.0` so containers and the app keep listening on all interfaces. +- **Scope:** The add-on behind Ingress was not exposed as long as port 54001 was not published. The standalone Docker deployment was the one that needed this hardening. Details are in advisory GHSA-vm55-p93v-fr5f. + ## [1.6.1] ### Fixed & Improved diff --git a/homeassistant-version-control/Dockerfile b/homeassistant-version-control/Dockerfile index 0efbe66..8f58c37 100644 --- a/homeassistant-version-control/Dockerfile +++ b/homeassistant-version-control/Dockerfile @@ -28,6 +28,7 @@ LABEL \ org.opencontainers.image.version=${BUILD_VERSION} ENV LANG C.UTF-8 +ENV HOST=0.0.0.0 # Install Node.js and npm RUN apk add --no-cache \ diff --git a/homeassistant-version-control/README.md b/homeassistant-version-control/README.md index d8fc0d2..54a01ad 100644 --- a/homeassistant-version-control/README.md +++ b/homeassistant-version-control/README.md @@ -2,7 +2,7 @@ **Automatic backup, history tracking, and instant restore for your Home Assistant configuration.** -[![Release](https://img.shields.io/github/v/release/saihgupr/HomeAssistantVersionControl?style=flat-square&label=release)](https://github.com/saihgupr/HomeAssistantVersionControl/releases) [![Docker pulls](https://img.shields.io/badge/Docker_pulls-58.4K-blue?style=flat-square&logo=docker)](https://github.com/saihgupr/HomeAssistantVersionControl/pkgs/container/home-assistant-version-control) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow?style=flat-square)](https://github.com/saihgupr/HomeAssistantVersionControl/blob/main/LICENSE) +[![Release](https://img.shields.io/github/v/release/saihgupr/HomeAssistantVersionControl?style=flat-square&label=release)](https://github.com/saihgupr/HomeAssistantVersionControl/releases) [![Docker pulls](https://img.shields.io/badge/Docker_pulls-61.9K-blue?style=flat-square&logo=docker)](https://github.com/saihgupr/HomeAssistantVersionControl/pkgs/container/home-assistant-version-control) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow?style=flat-square)](https://github.com/saihgupr/HomeAssistantVersionControl/blob/main/LICENSE) Home Assistant Version Control provides complete version history for your setup. It automatically tracks every change to your YAML configuration files using a robust local Git backend. Browse your history, visualize diffs, and restore individual files or your entire configuration to any previous state with a single click. @@ -14,20 +14,34 @@ Home Assistant Version Control provides complete version history for your setup. Version history navigation in the Home Assistant automation editor

-## What's New in v1.6! +## What's New in v1.7! -v1.6 focuses on cloud sync and hands-free reloads. +v1.7 adds API authentication for standalone Docker and cuts idle CPU. -* **Mirror Remote for Cloud Sync:** Add a second Git remote and every sync pushes to both. Use it for a redundant off-site copy, drift detection, or an audit repository. Mirror pushes are non-fatal, so a failure never blocks your primary backup. -* **Auto-reload Changed Components:** Optionally reload the Home Assistant domain that changed after each automatic backup. Edit automations, scripts, scenes, inputs, or templates and the matching reload service runs without a Developer Tools trip. Off by default. -* **Cleaner Cloud Sync Fields:** Token inputs no longer show the browser's password and autofill icons. +* **API Authentication for Docker:** The standalone container now asks for HTTP Basic auth on `/api/*`. It is on by default there. The username is `havc`, and the password is generated on first start and saved to `/data/api-password`. Set `HAVC_USERNAME` and `HAVC_PASSWORD` to choose your own, or `HAVC_API_AUTH=off` behind an authenticating reverse proxy. The add-on behind Ingress is unchanged. +* **Lower Idle CPU:** The watcher now ignores files HAVC can never commit, so polling no longer stats dependency folders, model caches, and other large directories. +* **Faster Startup Recovery:** A stale `.git/index.lock` is cleared after ten minutes, and startup and watcher retries now share one initialization run instead of racing for the git lock. ### Also in This Release +* **Optional Add-on Auth:** Added `api_auth` and `api_auth_password` for add-on users who publish port 54001 directly. +* **Input Validation:** Client-supplied paths and commit hashes are validated before use. +* **Exact-Match CORS:** `HAVC_ALLOWED_ORIGINS` takes an exact origin list instead of the old substring matching. + +
+v1.6 highlights + +v1.6 focused on cloud sync and hands-free reloads. + +* **Mirror Remote for Cloud Sync:** Add a second Git remote and every sync pushes to both. Use it for a redundant off-site copy, drift detection, or an audit repository. Mirror pushes are non-fatal, so a failure never blocks your primary backup. +* **Auto-reload Changed Components:** Optionally reload the Home Assistant domain that changed after each automatic backup. Edit automations, scripts, scenes, inputs, or templates and the matching reload service runs without a Developer Tools trip. Off by default. +* **Cleaner Cloud Sync Fields:** Token inputs no longer show the browser's password and autofill icons. * **Nested Git Repositories Documented:** Folders under `/config` with their own `.git` are skipped, so an ESPHome repo or similar no longer shows up as a broken submodule. * **Embedded Credentials (from v1.5.2):** Custom remotes using `user:pass@` or `token@` authenticate reliably during automatic pushes and connection tests. * **Masked Logs (from v1.5.1):** Tokens in remote URLs are redacted from startup logs and diagnostics. +
+
v1.5 highlights @@ -147,6 +161,9 @@ There are two ways to install Home Assistant Version Control: as a Home Assistan ### 2. Standalone Docker Installation +> [!WARNING] +> The standalone container requires API authentication by default. Requests to `/api/*` need HTTP Basic auth, while static files and the `/` healthcheck stay open. If you don't set `HAVC_PASSWORD`, a password is generated on first start, printed in the container logs as `[auth] API password: ...`, and saved to `/data/api-password` inside the container. Set `HAVC_USERNAME` and `HAVC_PASSWORD` to use your own credentials. Set `HAVC_API_AUTH=off` only when an authenticating reverse proxy already sits in front of the container. For internet exposure, keep an authenticating reverse proxy in front and leave the port closed on untrusted networks. + For Docker users who aren't using the Home Assistant app, you have three deployment options: **Option A: Docker Compose (recommended):** @@ -161,6 +178,8 @@ For Docker users who aren't using the Home Assistant app, you have three deploym nano compose.yaml # Update the volume path: /path/to/your/ha/config # Update timezone: TZ environment variable (e.g., America/New_York) + # Optional: set HAVC_USERNAME and HAVC_PASSWORD for API authentication + # Without HAVC_PASSWORD the generated one is in /data/api-password and the container logs ``` 3. Start the service: @@ -168,7 +187,7 @@ For Docker users who aren't using the Home Assistant app, you have three deploym docker compose up -d ``` -Access the interface at `http://localhost:54001`. +Access the interface at `http://localhost:54001`. Log in with your `HAVC_USERNAME` and `HAVC_PASSWORD`, or with `havc` and the generated password from the logs or `/data/api-password`. **Option B: Docker Run (pre-built image):** @@ -177,6 +196,8 @@ docker run -d \ -p 54001:54001 \ -v /path/to/your/config:/config \ -e TZ=America/New_York \ + -e HAVC_USERNAME=havc \ + -e HAVC_PASSWORD=choose-a-strong-password \ -e SUPERVISOR_TOKEN=your_long_lived_access_token_here \ -e HA_URL=http://homeassistant.local:8123 \ --name home-assistant-version-control \ @@ -196,6 +217,8 @@ docker run -d \ -p 54001:54001 \ -v /path/to/your/config:/config \ -e TZ=America/New_York \ + -e HAVC_USERNAME=havc \ + -e HAVC_PASSWORD=choose-a-strong-password \ -e SUPERVISOR_TOKEN=your_long_lived_access_token_here \ -e HA_URL=http://homeassistant.local:8123 \ --name home-assistant-version-control \ @@ -205,6 +228,9 @@ docker run -d \ > [!NOTE] > The `SUPERVISOR_TOKEN` and `HA_URL` are optional. You can omit those lines if you don't need Home Assistant restart/reload features. +> [!NOTE] +> API authentication is on by default. If you don't set `HAVC_PASSWORD`, the generated password is printed in the container logs and saved to `/data/api-password`. Mount `/data` so it survives container recreation. Set `HAVC_API_AUTH=off` only when an authenticating reverse proxy already protects the container. + Access the interface at `http://localhost:54001`. ### Docker Data & Settings @@ -243,6 +269,8 @@ Notes: - Files and folders are filtered by `include_extensions`, `exclude_files` (or `exclude`), and `exclude_folders`. - For `.conf` files, add `conf` to `include_extensions`. +By default the app relies on Ingress and Home Assistant authentication for the panel. If you expose port `54001` directly, set `api_auth: true` to require HTTP Basic auth on `/api/*`, and set `api_auth_password` to choose the password. If the password is left empty, HAVC generates one and stores it in `/data/api-password`. + #### Manual mode (existing git repositories) Set `manual_mode: true` if `/config` is already a git repository you manage yourself. The option is read before HAVC touches the repository, so it applies from the very first start, and when set it takes precedence over the toggle in the settings UI: @@ -344,11 +372,12 @@ For containerized deployments (especially when not persisting the `/data` direct | `EXCLUDE_FOLDERS` | Excluded Folders | List | Comma-separated (e.g. `backups,temp`) | `[]` | | `INCLUDE_STORAGE` | Included .storage patterns | List | Comma-separated (e.g. `lovelace,core.entity_registry`) | `lovelace*` | | `ADDITIONAL_PATHS` | Additional Watch Paths | List | Comma-separated (e.g. `/share,/media`) | `[]` | -| `WATCHER_USE_POLLING` | Use Polling for Watcher | Boolean | `true`, `false`, `yes`, `no`, `1`, `0` | `true` | +| `WATCHER_USE_POLLING` | Use Polling for Watcher | Boolean | `true`, `false`, `yes`, `no`, `1`, `0` | `false` | | `WATCHER_INTERVAL` | Watcher Polling Interval | Number | ≥ 100 (milliseconds) | `2000` | | `MANUAL_MODE` | Manual Mode (no auto-commits, repo left untouched) | Boolean | `true`, `false`, `yes`, `no`, `1`, `0` | `false` | **Notes:** +- Polling (`WATCHER_USE_POLLING`) is only needed on network mounts where native file events do not fire. Leave it off for local disks: polling stats every watched file on each interval and can use significant CPU on a large config tree. - Boolean values are case-insensitive and accept: `true`/`false`, `yes`/`no`, `1`/`0` - String values (units, types) are case-insensitive: `SECONDS` and `seconds` are equivalent - Invalid values trigger warnings in logs and fall back to defaults diff --git a/homeassistant-version-control/config.json b/homeassistant-version-control/config.json index 8207903..58920a7 100644 --- a/homeassistant-version-control/config.json +++ b/homeassistant-version-control/config.json @@ -1,6 +1,6 @@ { "name": "Home Assistant Version Control", - "version": "1.6.1", + "version": "1.7.0", "slug": "home-assistant-version-control", "description": "Git-powered version control and automated backup for your Home Assistant configuration files.", "url": "https://github.com/saihgupr/HomeAssistantVersionControl", @@ -51,10 +51,12 @@ "remote_url": "", "mirror_url": "", "mirror_auth_token": "", + "api_auth": false, + "api_auth_password": "", "legacy_arrow_direction": false, "exclude": [], "exclude_folders": [], - "watcher_use_polling": true, + "watcher_use_polling": false, "watcher_interval": 2000, "auto_reload": false }, @@ -74,6 +76,8 @@ "remote_url": "str?", "mirror_url": "str?", "mirror_auth_token": "str?", + "api_auth": "bool?", + "api_auth_password": "str?", "legacy_arrow_direction": "bool", "manual_mode": "bool?", "auto_reload": "bool?", diff --git a/homeassistant-version-control/package.json b/homeassistant-version-control/package.json index 250edac..76f9de0 100644 --- a/homeassistant-version-control/package.json +++ b/homeassistant-version-control/package.json @@ -1,6 +1,6 @@ { "name": "home-assistant-version-control", - "version": "1.6.1", + "version": "1.7.0", "description": "Home Assistant Version Control - Git-powered time travel for your HA config", "main": "server.js", "type": "module", diff --git a/homeassistant-version-control/server.js b/homeassistant-version-control/server.js index 7d382db..3a52e82 100644 --- a/homeassistant-version-control/server.js +++ b/homeassistant-version-control/server.js @@ -26,6 +26,15 @@ import path from 'path'; import { fileURLToPath } from 'url'; import yaml from 'js-yaml'; import { execSync } from 'child_process'; +import crypto from 'crypto'; +import { + resolveInside, + toRepoRelative, + isInside, + realPathInside, + isCommitish, + assertCommitish +} from './utils/path-safety.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); @@ -66,12 +75,32 @@ console.error = function (...args) { +/** + * The Home Assistant base image runs the app through s6, which does not always + * export the container environment to the child process. The same values are + * available as files under /run/s6/container_environment, so check there too. + * + * @param {string} name + * @returns {string|undefined} + */ +function readRuntimeEnv(name) { + if (process.env[name] !== undefined) return process.env[name]; + try { + return fs.readFileSync(`/run/s6/container_environment/${name}`, 'utf8').trim(); + } catch (error) { + return undefined; + } +} + const app = express(); -const PORT = process.env.PORT || 54001; -const HOST = process.env.HOST || '::'; +const DATA_DIR = readRuntimeEnv('DATA_PATH') || '/data'; +const isAddonMode = fs.existsSync(path.join(DATA_DIR, 'options.json')); +const PORT = readRuntimeEnv('PORT') || 54001; +// Add-on/Ingress needs to listen on all interfaces. A bare-metal run only needs +// loopback, and Docker users can set HOST or the Dockerfile default explicitly. +const HOST = readRuntimeEnv('HOST') || (isAddonMode ? '0.0.0.0' : '127.0.0.1'); const EXTERNAL_MIRROR_DIR = '.havc_external'; const ALLOWED_ADDITIONAL_PATH_PREFIXES = ['/share', '/media', '/ssl', '/config', '/addon_configs']; -const DATA_DIR = process.env.DATA_PATH || '/data'; /** * Mask embedded credentials in URLs for safe logging @@ -83,6 +112,126 @@ function maskUrl(url) { return url.replace(/:\/\/([^/]+)@/, '://***@'); } +// --------------------------------------------------------------------------- +// API authentication +// +// Standalone Docker installs are reachable on the network, so basic auth is on +// by default there. Inside a Home Assistant add-on the Supervisor/Ingress layer +// already authenticates users, so it defaults to off. HAVC_API_AUTH always wins. +// --------------------------------------------------------------------------- +let addonOptions = {}; +if (isAddonMode) { + try { + addonOptions = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'options.json'), 'utf-8')) || {}; + } catch (error) { + console.error('[auth] Could not read options.json:', error.message); + addonOptions = {}; + } +} + +function parseBooleanFlag(value) { + if (typeof value !== 'string') return null; + const normalized = value.trim().toLowerCase(); + if (['off', 'false', '0', 'no'].includes(normalized)) return false; + if (['on', 'true', '1', 'yes'].includes(normalized)) return true; + return null; +} + +const apiAuthEnvOverride = parseBooleanFlag(readRuntimeEnv('HAVC_API_AUTH') || ''); +let apiAuthEnabled = apiAuthEnvOverride === null ? !isAddonMode : apiAuthEnvOverride; +if (addonOptions.api_auth === true || addonOptions.api_auth === 'true') { + apiAuthEnabled = true; +} + +const apiUsername = readRuntimeEnv('HAVC_USERNAME') || 'havc'; +const API_PASSWORD_FILE = path.join(DATA_DIR, 'api-password'); +let apiPassword = null; + +function resolveApiPassword() { + const envPassword = readRuntimeEnv('HAVC_PASSWORD'); + if (envPassword) return envPassword; + + if (typeof addonOptions.api_auth_password === 'string' && addonOptions.api_auth_password !== '') { + return addonOptions.api_auth_password; + } + + try { + const stored = fs.readFileSync(API_PASSWORD_FILE, 'utf-8').trim(); + if (stored) return stored; + } catch (error) { + // No password file yet; generate one below. + } + + const generated = crypto.randomBytes(18).toString('base64url'); + try { + fs.mkdirSync(DATA_DIR, { recursive: true }); + fs.writeFileSync(API_PASSWORD_FILE, `${generated}\n`, { mode: 0o600 }); + fs.chmodSync(API_PASSWORD_FILE, 0o600); + } catch (error) { + console.error('[auth] Could not persist generated API password:', error.message); + } + return generated; +} + +if (apiAuthEnabled) { + const passwordIsConfigured = !!(readRuntimeEnv('HAVC_PASSWORD') || + (typeof addonOptions.api_auth_password === 'string' && addonOptions.api_auth_password !== '')); + apiPassword = resolveApiPassword(); + console.log(`[auth] API basic auth enabled (user: ${apiUsername})`); + if (passwordIsConfigured) { + console.log('[auth] Using the configured API password'); + } else { + console.log(`[auth] API password: ${apiPassword}`); + } +} + +function constantTimeEqual(left, right) { + const leftHash = crypto.createHash('sha256').update(String(left ?? ''), 'utf8').digest(); + const rightHash = crypto.createHash('sha256').update(String(right ?? ''), 'utf8').digest(); + return crypto.timingSafeEqual(leftHash, rightHash); +} + +function basicAuth(req, res, next) { + if (!apiAuthEnabled) return next(); + + // CORS preflights never carry credentials. + if (req.method === 'OPTIONS') return res.status(204).end(); + + const header = req.headers.authorization || ''; + const separatorIndex = header.indexOf(' '); + const scheme = separatorIndex === -1 ? '' : header.slice(0, separatorIndex); + const encoded = separatorIndex === -1 ? '' : header.slice(separatorIndex + 1).trim(); + + if (scheme.toLowerCase() === 'basic' && encoded) { + let decoded = ''; + try { + decoded = Buffer.from(encoded, 'base64').toString('utf8'); + } catch (error) { + decoded = ''; + } + + // Only the first colon separates user from password (passwords may contain colons). + const colonIndex = decoded.indexOf(':'); + if (colonIndex !== -1) { + const username = decoded.slice(0, colonIndex); + const password = decoded.slice(colonIndex + 1); + if (constantTimeEqual(username, apiUsername) && constantTimeEqual(password, apiPassword)) { + return next(); + } + } + } + + res.set('WWW-Authenticate', 'Basic realm="Home Assistant Version Control", charset="UTF-8"'); + return res.status(401).json({ success: false, error: 'Authentication required' }); +} + +// Exact-match allowlist. Substring matching let any origin containing +// "localhost" (for example http://localhost.attacker.example) through. +const allowedOrigins = (readRuntimeEnv('HAVC_ALLOWED_ORIGINS') || '') + .split(',') + .map(origin => origin.trim()) + .filter(origin => origin.length > 0); + // Ensure HOME is set for git & SSH compatibility if (!process.env.HOME) { process.env.HOME = '/root'; @@ -125,30 +274,37 @@ function configureGitIdentity() { app.use(express.json()); -// CORS middleware for Home Assistant Ingress +// CORS middleware for explicitly allowed cross-origin clients. +// The SPA is served same-origin, so no CORS headers are needed for normal use. app.use((req, res, next) => { - // Get the origin from the request const origin = req.headers.origin; + const originAllowed = !!origin && allowedOrigins.includes(origin); - // Allow any localhost variation - if (origin && (origin.includes('localhost') || - origin.includes('127.0.0.1') || - origin.includes('192.168.') || - origin.includes('10.') || - origin.includes('172.'))) { + if (originAllowed) { res.header('Access-Control-Allow-Origin', origin); + res.header('Vary', 'Origin'); + res.header('Access-Control-Allow-Credentials', 'true'); + res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); + res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With'); + + // Handle preflight requests + if (req.method === 'OPTIONS') { + return res.status(204).end(); + } } - // Allow credentials - res.header('Access-Control-Allow-Credentials', 'true'); + next(); +}); - // Allowed methods and headers - res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); - res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With'); +// CSRF guard. Browsers send Sec-Fetch-Site on every request, so a cross-site +// mutation is always a forged one. Requests without the header (older clients) +// are left alone: Home Assistant Ingress can rewrite Host, which makes an +// Origin/Host comparison unreliable. +app.use((req, res, next) => { + if (!['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)) return next(); - // Handle preflight requests - if (req.method === 'OPTIONS') { - return res.status(200).end(); + if (req.headers['sec-fetch-site'] === 'cross-site') { + return res.status(403).json({ success: false, error: 'Cross-site request blocked' }); } next(); @@ -175,6 +331,11 @@ app.use((req, res, next) => { next(); }); +// API authentication runs after the ingress rewrite above so req.url is +// already stripped of the /api prefix path prefix. It only guards /api:*, +// leaving the SPA, static assets and the root healthcheck reachable. +app.use('/api', basicAuth); + // Static files - serve public directory at root // Add cache control headers for JSON files to prevent stale translations app.use((req, res, next) => { @@ -448,6 +609,8 @@ let additionalTrackedPaths = []; const debounceTimers = new Map(); let watcher = null; const externalWatchers = []; +const INIT_RETRY_DELAY_MS = 15000; +let lastInitAttemptAt = 0; let configOptions = { yaml_format: true, json_format: false, @@ -499,7 +662,7 @@ let runtimeSettings = { manualMode: false, autoReload: false, legacyArrowDirection: false, - watcherUsePolling: true, + watcherUsePolling: false, watcherInterval: 2000 }; @@ -1585,13 +1748,48 @@ async function setupCaCertificates() { } } -async function initRepo() { +/** + * Remove a Git lock left behind by a crashed or killed process. A stale index.lock makes + * every git command fail forever, which turns the watcher into an endless init retry loop. + */ +async function clearStaleGitLock(repoPath, maxAgeMs = 10 * 60 * 1000) { + const lockPath = path.join(repoPath, '.git', 'index.lock'); + try { + const stats = await fsPromises.stat(lockPath); + if (Date.now() - stats.mtimeMs < maxAgeMs) { + return; + } + await fsPromises.unlink(lockPath); + console.log(`[init] Removed stale Git lock (${Math.round((Date.now() - stats.mtimeMs) / 1000)}s old): ${lockPath}`); + } catch (error) { + if (error.code !== 'ENOENT') { + console.error('[init] Could not check Git lock:', error.message); + } + } +} + +let initRepoPromise = null; + +/** + * Serialize initialization. Startup and watcher retries can overlap; letting them run + * concurrently makes them fight over .git/index.lock and burn CPU. + */ +function initRepo() { + if (!initRepoPromise) { + initRepoPromise = initRepoInternal().finally(() => { + initRepoPromise = null; + }); + } + return initRepoPromise; +} + +async function initRepoInternal() { // Load runtime settings first await loadRuntimeSettings(); try { // Determine CONFIG_PATH - CONFIG_PATH = process.env.CONFIG_PATH; + CONFIG_PATH = readRuntimeEnv('CONFIG_PATH'); // Also check for config.json in the data directory try { @@ -1762,6 +1960,7 @@ async function initRepo() { console.log(`[external-sync] Startup sync complete: paths=${externalSyncStats.paths}, copied=${externalSyncStats.copied}, removed=${externalSyncStats.removed}`); } + await clearStaleGitLock(CONFIG_PATH); const isRepo = await gitCheckIsRepo(); // Check for nested git repositories to ignore @@ -1983,7 +2182,9 @@ app.get('/api/app-settings', async (req, res) => { haAuthConfigured: false, liveConfigPath: CONFIG_PATH, backupFolderPath: null, - haCredentialsSource: 'none' + haCredentialsSource: 'none', + apiAuthEnabled, + apiAuthMode: apiAuthEnabled ? 'basic' : 'none' }); }); @@ -2555,7 +2756,10 @@ app.get('/api/git/history', async (req, res) => { app.get('/api/git/commit-details', async (req, res) => { try { const { commitHash } = req.query; - const status = await gitCommitDetails(commitHash); + if (!isCommitish(commitHash)) { + return res.status(400).json({ success: false, error: 'Invalid commit hash' }); + } + const status = await gitCommitDetails(commitHash.trim()); res.json({ success: true, status }); } catch (error) { res.status(500).json({ success: false, error: error.message }); @@ -2596,7 +2800,20 @@ app.post('/api/git/add-all-and-commit', async (req, res) => { app.get('/api/git/file-at-commit', async (req, res) => { try { const { commitHash, filePath } = req.query; - const content = await gitShowFileAtCommit(commitHash, filePath); + + let safeCommitHash; + try { + safeCommitHash = assertCommitish(commitHash); + } catch (error) { + return res.status(400).json({ success: false, error: 'Invalid commit hash' }); + } + + const safeFilePath = toRepoRelative(CONFIG_PATH, filePath); + if (!safeFilePath) { + return res.status(400).json({ success: false, error: 'Invalid file path' }); + } + + const content = await gitShowFileAtCommit(safeCommitHash, safeFilePath); res.json({ success: true, content }); } catch (error) { res.status(500).json({ success: false, error: error.message }); @@ -2608,12 +2825,25 @@ app.get('/api/file-content', async (req, res) => { try { const { filePath } = req.query; - let fullPath = path.join(CONFIG_PATH, filePath); - if (isMirroredExternalRepoPath(filePath)) { - const externalPath = repoPathToExternalAbsolute(filePath); - if (externalPath && isPathInConfiguredAdditionalPaths(externalPath)) { - fullPath = externalPath; + const normalizedPath = toRepoRelative(CONFIG_PATH, filePath); + if (!normalizedPath) { + return res.status(400).json({ success: false, error: 'Invalid file path' }); + } + + let fullPath = path.join(CONFIG_PATH, normalizedPath); + let allowedRoot = CONFIG_PATH; + + if (isMirroredExternalRepoPath(normalizedPath)) { + const externalPath = repoPathToExternalAbsolute(normalizedPath); + if (!externalPath || !isPathInConfiguredAdditionalPaths(externalPath)) { + return res.status(400).json({ success: false, error: 'Invalid mirrored file path' }); } + fullPath = externalPath; + allowedRoot = additionalTrackedPaths.find(basePath => isPathUnder(basePath, externalPath)) || null; + } + + if (!allowedRoot || !isInside(allowedRoot, fullPath) || !(await realPathInside(allowedRoot, fullPath))) { + return res.status(400).json({ success: false, error: 'File path is outside the allowed directory' }); } const content = await fsPromises.readFile(fullPath, 'utf-8'); @@ -2627,7 +2857,13 @@ app.get('/api/file-content', async (req, res) => { app.get('/api/git/file-history', async (req, res) => { try { const { filePath } = req.query; - const logOptions = { file: filePath }; + + const safeFilePath = toRepoRelative(CONFIG_PATH, filePath); + if (!safeFilePath) { + return res.status(400).json({ success: false, error: 'Invalid file path' }); + } + + const logOptions = { file: safeFilePath }; if (runtimeSettings.limitHistory) { logOptions.maxCount = runtimeSettings.maxCommits; } @@ -2637,7 +2873,7 @@ app.get('/api/git/file-history', async (req, res) => { let currentHash = ''; try { // Use git hash-object to get the hash of the file on disk - currentHash = (await gitRaw(['hash-object', filePath])).trim(); + currentHash = (await gitRaw(['hash-object', '--', safeFilePath])).trim(); } catch (e) { // File might not exist or other error } @@ -2647,7 +2883,7 @@ app.get('/api/git/file-history', async (req, res) => { try { // git ls-tree // Output format: blob \t - const treeOut = await gitRaw(['ls-tree', commit.hash, filePath]); + const treeOut = await gitRaw(['ls-tree', commit.hash, '--', safeFilePath]); const match = treeOut.match(/blob\s+([0-9a-f]+)/); const blobHash = match ? match[1] : null; return { ...commit, blobHash }; @@ -2669,7 +2905,17 @@ app.get('/api/git/file-history', async (req, res) => { app.get('/api/git/file-diff', async (req, res) => { try { const { filePath, commitHash } = req.query; - const diff = await gitDiff([`${commitHash}^`, commitHash, '--', filePath]); + if (!isCommitish(commitHash)) { + return res.status(400).json({ success: false, error: 'Invalid commit hash' }); + } + + const safeFilePath = toRepoRelative(CONFIG_PATH, filePath); + if (!safeFilePath) { + return res.status(400).json({ success: false, error: 'Invalid file path' }); + } + + const safeCommitHash = commitHash.trim(); + const diff = await gitDiff([`${safeCommitHash}^`, safeCommitHash, '--', safeFilePath]); res.json({ success: true, diff }); } catch (error) { res.status(500).json({ success: false, error: error.message }); @@ -2683,7 +2929,11 @@ app.get('/api/git/commit-diff', async (req, res) => { if (!commitHash) { return res.status(400).json({ success: false, error: 'commitHash is required' }); } - const diff = await gitDiff([`${commitHash}^`, commitHash]); + if (!isCommitish(commitHash)) { + return res.status(400).json({ success: false, error: 'Invalid commit hash' }); + } + const safeCommitHash = commitHash.trim(); + const diff = await gitDiff([`${safeCommitHash}^`, safeCommitHash]); res.json({ success: true, diff }); } catch (error) { res.status(500).json({ success: false, error: error.message }); @@ -2694,16 +2944,27 @@ app.get('/api/git/commit-diff', async (req, res) => { app.post('/api/restore-file', async (req, res) => { try { const { commitHash, filePath } = req.body; - console.log(`[restore] Restoring file ${filePath} to commit ${commitHash.substring(0, 8)}`); + + if (!isCommitish(commitHash)) { + return res.status(400).json({ success: false, error: 'Invalid commit hash' }); + } + const safeCommitHash = commitHash.trim(); + + const safeFilePath = toRepoRelative(CONFIG_PATH, filePath); + if (!safeFilePath) { + return res.status(400).json({ success: false, error: 'Invalid file path' }); + } + + console.log(`[restore] Restoring file ${safeFilePath} to commit ${safeCommitHash.substring(0, 8)}`); // Get the date from the commit for the commit message // Get the date from the commit for the commit message - const dateStr = (await gitRaw(['show', '-s', '--format=%aI', commitHash])).trim(); + const dateStr = (await gitRaw(['show', '-s', '--format=%aI', safeCommitHash])).trim(); const commitDate = new Date(dateStr).toLocaleString(); // Restore the file - file watcher will detect and auto-commit - await restorePathToCommit(commitHash, filePath); - console.log(`[restore] File restored: ${filePath}`); + await restorePathToCommit(safeCommitHash, safeFilePath); + console.log(`[restore] File restored: ${safeFilePath}`); console.log(`[restore] File watcher will auto-commit this change`); let message = 'File restored (auto-commit pending)'; @@ -2712,7 +2973,7 @@ app.post('/api/restore-file', async (req, res) => { suppressAutoReload(); // Check if we need to reload Home Assistant components - if (filePath.endsWith('automations.yaml')) { + if (safeFilePath.endsWith('automations.yaml')) { console.log('[restore] Reloading automations in Home Assistant...'); const reloadResult = await callHomeAssistantService('automation', 'reload'); if (reloadResult.success) { @@ -2720,7 +2981,7 @@ app.post('/api/restore-file', async (req, res) => { } else { message += `. Automations reload failed: ${reloadResult.error}`; } - } else if (filePath.endsWith('scripts.yaml')) { + } else if (safeFilePath.endsWith('scripts.yaml')) { console.log('[restore] Reloading scripts in Home Assistant...'); const reloadResult = await callHomeAssistantService('script', 'reload'); if (reloadResult.success) { @@ -2743,13 +3004,20 @@ app.post('/api/restore-commit', async (req, res) => { const { sourceHash, targetHash, commitHash } = req.body; // Backward compatibility: if only commitHash provided, use it for both source and target - const source = sourceHash || commitHash; - const target = targetHash || commitHash; + const rawSource = sourceHash || commitHash; + const rawTarget = targetHash || commitHash; - if (!source || !target) { + if (!rawSource || !rawTarget) { return res.status(400).json({ success: false, error: 'sourceHash and targetHash (or commitHash) required' }); } + if (!isCommitish(rawSource) || !isCommitish(rawTarget)) { + return res.status(400).json({ success: false, error: 'Invalid commit hash' }); + } + + const source = rawSource.trim(); + const target = rawTarget.trim(); + console.log(`[restore] Finding files from commit ${source.substring(0, 8)}`); console.log(`[restore] Restoring to version ${target.substring(0, 8)}`); @@ -2862,23 +3130,29 @@ app.post('/api/git/hard-reset', async (req, res) => { return res.status(400).json({ success: false, error: 'commitHash is required' }); } - console.log(`[hard-reset] Resetting ALL files to commit ${commitHash.substring(0, 8)}`); + if (!isCommitish(commitHash)) { + return res.status(400).json({ success: false, error: 'Invalid commit hash' }); + } + + const safeCommitHash = commitHash.trim(); + + console.log(`[hard-reset] Resetting ALL files to commit ${safeCommitHash.substring(0, 8)}`); // 1. Validate commit exists let commitExists; try { - commitExists = await gitRaw(['cat-file', '-t', commitHash]); + commitExists = await gitRaw(['cat-file', '-t', safeCommitHash]); } catch (error) { return res.status(400).json({ success: false, - error: `Commit ${commitHash.substring(0, 8)} not found` + error: `Commit ${safeCommitHash.substring(0, 8)} not found` }); } if (!commitExists.trim().startsWith('commit')) { return res.status(400).json({ success: false, - error: `Invalid commit: ${commitHash.substring(0, 8)}` + error: `Invalid commit: ${safeCommitHash.substring(0, 8)}` }); } @@ -2896,7 +3170,7 @@ app.post('/api/git/hard-reset', async (req, res) => { if (!status.isClean()) { // Create backup commit const timestamp = new Date().toISOString(); - const backupMessage = `Safety backup before hard reset to ${commitHash.substring(0, 8)} - ${timestamp}`; + const backupMessage = `Safety backup before hard reset to ${safeCommitHash.substring(0, 8)} - ${timestamp}`; await gitCommit(backupMessage); // Get the backup commit hash @@ -2916,11 +3190,11 @@ app.post('/api/git/hard-reset', async (req, res) => { } // 3. Get list of all files in the target commit - console.log(`[hard-reset] Getting file list from commit ${commitHash.substring(0, 8)}`); + console.log(`[hard-reset] Getting file list from commit ${safeCommitHash.substring(0, 8)}`); let filesInCommit; try { // Use git ls-tree to get all files in the commit - const lsTree = await gitRaw(['ls-tree', '-r', '--name-only', commitHash]); + const lsTree = await gitRaw(['ls-tree', '-r', '--name-only', safeCommitHash]); filesInCommit = lsTree.trim().split('\n').filter(f => f); console.log(`[hard-reset] Found ${filesInCommit.length} files in target commit`); } catch (error) { @@ -2932,18 +3206,18 @@ app.post('/api/git/hard-reset', async (req, res) => { } // 4. Checkout each file from the target commit - console.log(`[hard-reset] Checking out ${filesInCommit.length} files from ${commitHash.substring(0, 8)}`); + console.log(`[hard-reset] Checking out ${filesInCommit.length} files from ${safeCommitHash.substring(0, 8)}`); try { // Checkout all files for (const file of filesInCommit) { - await restorePathToCommit(commitHash, file); + await restorePathToCommit(safeCommitHash, file); } - console.log(`[hard-reset] All files checked out from ${commitHash.substring(0, 8)}`); + console.log(`[hard-reset] All files checked out from ${safeCommitHash.substring(0, 8)}`); // Get the commit date for a better commit message let commitDate = ''; try { - const dateStr = (await gitRaw(['show', '-s', '--format=%aI', commitHash])).trim(); + const dateStr = (await gitRaw(['show', '-s', '--format=%aI', safeCommitHash])).trim(); const date = new Date(dateStr); commitDate = date.toLocaleString(undefined, { month: 'short', @@ -2955,7 +3229,7 @@ app.post('/api/git/hard-reset', async (req, res) => { }).replace(',', ''); } catch (error) { console.error('[hard-reset] Failed to get commit date:', error); - commitDate = commitHash.substring(0, 8); + commitDate = safeCommitHash.substring(0, 8); } // Auto-commit the changes @@ -2970,9 +3244,9 @@ app.post('/api/git/hard-reset', async (req, res) => { res.json({ success: true, backupCommitHash: backupHash, - resetToCommit: commitHash, + resetToCommit: safeCommitHash, filesRestored: filesInCommit.length, - message: `Restored ${filesInCommit.length} files to commit ${commitHash.substring(0, 8)}${backupHash ? '. Safety backup created.' : ''}` + message: `Restored ${filesInCommit.length} files to commit ${safeCommitHash.substring(0, 8)}${backupHash ? '. Safety backup created.' : ''}` }); } catch (error) { console.error('[hard-reset] Checkout failed:', error); @@ -2998,30 +3272,36 @@ app.post('/api/git/soft-reset', async (req, res) => { return res.status(400).json({ success: false, error: 'commitHash is required' }); } - console.log(`[soft-reset] Soft resetting to commit ${commitHash.substring(0, 8)}`); + if (!isCommitish(commitHash)) { + return res.status(400).json({ success: false, error: 'Invalid commit hash' }); + } + + const safeCommitHash = commitHash.trim(); + + console.log(`[soft-reset] Soft resetting to commit ${safeCommitHash.substring(0, 8)}`); // 1. Validate commit exists let commitExists; try { - commitExists = await gitRaw(['cat-file', '-t', commitHash]); + commitExists = await gitRaw(['cat-file', '-t', safeCommitHash]); } catch (error) { return res.status(400).json({ success: false, - error: `Commit ${commitHash.substring(0, 8)} not found` + error: `Commit ${safeCommitHash.substring(0, 8)} not found` }); } if (!commitExists.trim().startsWith('commit')) { return res.status(400).json({ success: false, - error: `Invalid commit: ${commitHash.substring(0, 8)}` + error: `Invalid commit: ${safeCommitHash.substring(0, 8)}` }); } // 2. Count how many commits will be removed let commitsToRemove = 0; try { - const logOutput = await gitRaw(['log', '--oneline', `${commitHash}..HEAD`]); + const logOutput = await gitRaw(['log', '--oneline', `${safeCommitHash}..HEAD`]); commitsToRemove = logOutput.trim().split('\n').filter(l => l).length; } catch (error) { // If this fails, we can still proceed @@ -3034,8 +3314,8 @@ app.post('/api/git/soft-reset', async (req, res) => { const headBefore = (await gitRaw(['rev-parse', 'HEAD'])).trim(); console.log(`[soft-reset] HEAD before reset: ${headBefore.substring(0, 8)}`); - await gitRaw(['reset', '--soft', commitHash]); - console.log(`[soft-reset] Executed git reset --soft to ${commitHash.substring(0, 8)}`); + await gitRaw(['reset', '--soft', safeCommitHash]); + console.log(`[soft-reset] Executed git reset --soft to ${safeCommitHash.substring(0, 8)}`); // Verify HEAD actually changed const headAfter = (await gitRaw(['rev-parse', 'HEAD'])).trim(); @@ -3061,7 +3341,7 @@ app.post('/api/git/soft-reset', async (req, res) => { // 5. Get the commit date for the response let commitDate = ''; try { - const dateStr = (await gitRaw(['show', '-s', '--format=%aI', commitHash])).trim(); + const dateStr = (await gitRaw(['show', '-s', '--format=%aI', safeCommitHash])).trim(); const date = new Date(dateStr); commitDate = date.toLocaleString(undefined, { month: 'short', @@ -3072,12 +3352,12 @@ app.post('/api/git/soft-reset', async (req, res) => { hour12: true }).replace(',', ''); } catch (error) { - commitDate = commitHash.substring(0, 8); + commitDate = safeCommitHash.substring(0, 8); } res.json({ success: true, - commitHash: commitHash.substring(0, 8), + commitHash: safeCommitHash.substring(0, 8), commitsRemoved: commitsToRemove, commitDate: commitDate, message: `Soft reset to ${commitDate}. ${commitsToRemove} commit(s) removed from history.` @@ -3144,9 +3424,21 @@ app.get('/api/git/status', async (req, res) => { // List YAML files (legacy) app.post('/api/list-yaml-files', async (req, res) => { try { - const { liveConfigPath, directory = '' } = req.body; - const searchPath = liveConfigPath || CONFIG_PATH; - const dirPath = directory ? `${searchPath}/${directory}` : searchPath; + const { liveConfigPath, directory = '' } = req.body || {}; + + // The body used to pick the directory to list, which let any caller read any + // directory on the host. It may only confirm the configured root. + if (liveConfigPath !== undefined && liveConfigPath !== null && liveConfigPath !== '') { + const resolvedLivePath = path.resolve(String(liveConfigPath)); + if (!CONFIG_PATH || resolvedLivePath !== path.resolve(CONFIG_PATH)) { + return res.status(400).json({ success: false, error: 'liveConfigPath is not allowed' }); + } + } + + const dirPath = resolveInside(CONFIG_PATH, directory || '.', { allowRoot: true }); + if (!dirPath) { + return res.status(400).json({ success: false, error: 'Invalid directory' }); + } const allowedExtensions = getConfiguredExtensions(); const files = fs.readdirSync(dirPath) @@ -3164,7 +3456,7 @@ app.post('/api/list-yaml-files', async (req, res) => { } }); -function shouldIgnoreWatchPath(filePath) { +function shouldIgnoreWatchPath(filePath, stats) { if (!filePath) return true; // Normalize path separators to forward slashes for consistent matching @@ -3180,6 +3472,13 @@ function shouldIgnoreWatchPath(filePath) { return true; } + // Watches are only needed for files HAVC can actually commit: configured extensions + // plus whitelisted .storage entries. Watching everything makes polling mode stat the + // whole config tree on every interval (deps, tts, www, model caches) for no benefit. + if (stats && stats.isFile() && !isFileTrackableForSync(filePath) && !isConfiguredStorageAbsolutePath(filePath)) { + return true; + } + // Ignore database files and related files (very frequent writes) if (/\.(db|db-wal|db-shm|db-journal)$/.test(normalizedPath)) { return true; @@ -3261,7 +3560,7 @@ function initializeWatcher() { stabilityThreshold: 2000, pollInterval: 100 }, - ignored: (filePath, stats) => shouldIgnoreWatchPath(filePath) + ignored: (filePath, stats) => shouldIgnoreWatchPath(filePath, stats) }); // Handler function for both 'change' and 'add' events @@ -3286,8 +3585,14 @@ function initializeWatcher() { // Set a new timer for this specific file const timer = setTimeout(async () => { try { - // Ensure git is initialized + // Ensure git is initialized. Throttle retries so a failing init does not spawn + // a full initialization for every file event. if (!gitInitialized) { + if (Date.now() - lastInitAttemptAt < INIT_RETRY_DELAY_MS) { + debounceTimers.delete(filePath); + return; + } + lastInitAttemptAt = Date.now(); console.log('[watcher] Git not initialized yet, retrying...'); await initRepo(); } @@ -3499,7 +3804,7 @@ async function initializeExternalWatchers() { stabilityThreshold: 2000, pollInterval: 100 }, - ignored: (filePath, stats) => shouldIgnoreWatchPath(filePath) + ignored: (filePath, stats) => shouldIgnoreWatchPath(filePath, stats) }); externalWatcher.on('add', (filePath) => handleExternalWatcherEvent(filePath, 'added')); @@ -3524,8 +3829,6 @@ app.get('/api/health', (req, res) => { additionalTrackedPaths, watching: CONFIG_PATH || '/config', time: new Date().toISOString(), - headers: req.headers, - url: req.originalUrl, url: req.originalUrl }); }); @@ -4239,10 +4542,13 @@ app.get('/api/retention/status', async (req, res) => { // Debug endpoint to check ingress path detection app.get('/api/debug', (req, res) => { + if (readRuntimeEnv('HAVC_DEBUG') !== '1') { + return res.status(404).json({ success: false, error: 'Not found' }); + } + res.json({ originalUrl: req.originalUrl, url: req.url, - headers: req.headers, ingressPath: req.headers['x-ingress-path'] || req.headers['x-forwarded-prefix'] || req.headers['x-external-url'] || @@ -4398,7 +4704,10 @@ app.get('/api/automation/:id/at-commit', async (req, res) => { if (!commitHash) { return res.status(400).json({ success: false, error: 'commitHash is required' }); } - const result = await getAutomationAtCommit(id, commitHash, CONFIG_PATH); + if (!isCommitish(commitHash)) { + return res.status(400).json({ success: false, error: 'Invalid commit hash' }); + } + const result = await getAutomationAtCommit(id, commitHash.trim(), CONFIG_PATH); res.json(result); } catch (error) { console.error('[automation at-commit] Error:', error); @@ -4430,7 +4739,10 @@ app.get('/api/script/:id/at-commit', async (req, res) => { if (!commitHash) { return res.status(400).json({ success: false, error: 'commitHash is required' }); } - const result = await getScriptAtCommit(id, commitHash, CONFIG_PATH); + if (!isCommitish(commitHash)) { + return res.status(400).json({ success: false, error: 'Invalid commit hash' }); + } + const result = await getScriptAtCommit(id, commitHash.trim(), CONFIG_PATH); res.json(result); } catch (error) { console.error('[script at-commit] Error:', error); @@ -4443,7 +4755,10 @@ app.get('/api/automation/:id/diff', async (req, res) => { try { const { id } = req.params; const { commitHash } = req.query; - const diff = await getAutomationDiff(id, commitHash, CONFIG_PATH); + if (!isCommitish(commitHash)) { + return res.status(400).json({ success: false, error: 'Invalid commit hash' }); + } + const diff = await getAutomationDiff(id, commitHash.trim(), CONFIG_PATH); res.json({ success: true, diff }); } catch (error) { console.error('[automation diff] Error:', error); @@ -4456,7 +4771,10 @@ app.get('/api/script/:id/diff', async (req, res) => { try { const { id } = req.params; const { commitHash } = req.query; - const diff = await getScriptDiff(id, commitHash, CONFIG_PATH); + if (!isCommitish(commitHash)) { + return res.status(400).json({ success: false, error: 'Invalid commit hash' }); + } + const diff = await getScriptDiff(id, commitHash.trim(), CONFIG_PATH); res.json({ success: true, diff }); } catch (error) { console.error('[script diff] Error:', error); @@ -4469,7 +4787,10 @@ app.post('/api/automation/:id/restore', async (req, res) => { try { const { id } = req.params; const { commitHash } = req.body; - const success = await restoreAutomation(id, commitHash, CONFIG_PATH); + if (!isCommitish(commitHash)) { + return res.status(400).json({ success: false, error: 'Invalid commit hash' }); + } + const success = await restoreAutomation(id, commitHash.trim(), CONFIG_PATH); if (success) { // The watcher will also see the restored file, so skip its auto-reload @@ -4497,7 +4818,10 @@ app.post('/api/script/:id/restore', async (req, res) => { try { const { id } = req.params; const { commitHash } = req.body; - const success = await restoreScript(id, commitHash, CONFIG_PATH); + if (!isCommitish(commitHash)) { + return res.status(400).json({ success: false, error: 'Invalid commit hash' }); + } + const success = await restoreScript(id, commitHash.trim(), CONFIG_PATH); if (success) { // The watcher will also see the restored file, so skip its auto-reload diff --git a/homeassistant-version-control/tests/api-security.test.mjs b/homeassistant-version-control/tests/api-security.test.mjs new file mode 100644 index 0000000..5eb11d2 --- /dev/null +++ b/homeassistant-version-control/tests/api-security.test.mjs @@ -0,0 +1,197 @@ +// Security regression tests for the API surface: basic auth, path containment, +// commit-ish validation and header echo. +// +// Each test boots the real server against a throwaway config directory. HOME is +// sandboxed so `git config --global` writes can't leak into the machine running +// the tests. +// +// Run: node --test tests/api-security.test.mjs + +import { test, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises'; +import { createServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const SERVER_JS = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'server.js'); +const USERNAME = 'test'; +const PASSWORD = 'secret'; +const AUTH_HEADER = `Basic ${Buffer.from(`${USERNAME}:${PASSWORD}`).toString('base64')}`; +const SECRET_CONTENT = 'outside-the-config-root-4f10ce7'; + +let sandbox; +let configRoot; +let child; +let base; +let output = ''; + +before(async () => { + sandbox = await mkdtemp(path.join(tmpdir(), 'havc-api-security-')); + configRoot = path.join(sandbox, 'config'); + const dataRoot = path.join(sandbox, 'data'); + await mkdir(configRoot, { recursive: true }); + await mkdir(dataRoot, { recursive: true }); + await mkdir(path.join(sandbox, 'home'), { recursive: true }); + await writeFile(path.join(configRoot, 'configuration.yaml'), 'homeassistant:\n'); + // Deliberately outside CONFIG_PATH: traversal attempts must never reach it. + await writeFile(path.join(sandbox, 'secret.yaml'), `api_key: ${SECRET_CONTENT}\n`); + + const port = await freePort(); + child = spawn(process.execPath, [SERVER_JS], { + cwd: path.dirname(SERVER_JS), + env: { + ...process.env, + HOME: path.join(sandbox, 'home'), + GIT_CONFIG_NOSYSTEM: '1', + CONFIG_PATH: configRoot, + DATA_PATH: dataRoot, + PORT: String(port), + HOST: '127.0.0.1', + MANUAL_MODE: 'true', + DEBOUNCE_TIME: '1', + DEBOUNCE_TIME_UNIT: 'seconds', + WATCHER_INTERVAL: '200', + HAVC_API_AUTH: 'on', + HAVC_USERNAME: USERNAME, + HAVC_PASSWORD: PASSWORD, + }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + child.stdout.on('data', (d) => { output += d; }); + child.stderr.on('data', (d) => { output += d; }); + + base = `http://127.0.0.1:${port}/api`; + + await waitFor(async () => { + try { + const res = await api('/health'); + if (res.status !== 200) return false; + return (await res.json()).gitInitialized === true; + } catch { + return false; + } + }, 15000, () => `server did not initialise:\n${output}`); +}); + +after(async () => { + if (child && child.exitCode === null) { + const exited = new Promise((resolve) => child.once('exit', resolve)); + child.kill('SIGTERM'); + await exited; + } + if (sandbox) await rm(sandbox, { recursive: true, force: true }); +}); + +function api(route, { method = 'GET', body, headers = {}, authenticated = true } = {}) { + const requestHeaders = { ...headers }; + if (authenticated && !requestHeaders.Authorization) requestHeaders.Authorization = AUTH_HEADER; + if (body !== undefined) requestHeaders['Content-Type'] = 'application/json'; + + return fetch(`${base}${route}`, { + method, + headers: requestHeaders, + body: body === undefined ? undefined : JSON.stringify(body), + }); +} + +async function freePort() { + return new Promise((resolve, reject) => { + const srv = createServer(); + srv.unref(); + srv.on('error', reject); + srv.listen(0, '127.0.0.1', () => { + const { port } = srv.address(); + srv.close(() => resolve(port)); + }); + }); +} + +async function waitFor(predicate, timeoutMs, message) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (await predicate()) return true; + await new Promise((r) => setTimeout(r, 100)); + } + if (message) assert.fail(message()); + return false; +} + +test('API requires basic auth and does not protect the SPA', async () => { + const unauthorized = await fetch(`${base}/app-settings`); + assert.equal(unauthorized.status, 401); + assert.match(unauthorized.headers.get('www-authenticate') || '', /^Basic\b/); + assert.deepEqual(await unauthorized.json(), { + success: false, + error: 'Authentication required', + }); + + // Static shell stays reachable without credentials. + const spa = await fetch(base.replace(/\/api$/, '/')); + assert.equal(spa.status, 200); +}); + +test('wrong credentials are rejected, correct credentials are accepted', async () => { + const wrongPassword = `Basic ${Buffer.from(`${USERNAME}:not-the-password`).toString('base64')}`; + const rejected = await api('/app-settings', { headers: { Authorization: wrongPassword } }); + assert.equal(rejected.status, 401); + + const accepted = await api('/app-settings'); + assert.equal(accepted.status, 200); + const settings = await accepted.json(); + assert.equal(settings.apiAuthEnabled, true); + assert.equal(settings.apiAuthMode, 'basic'); +}); + +test('file-content rejects traversal outside the config root', async () => { + const positive = await api('/file-content?filePath=configuration.yaml'); + const positiveBody = await positive.json(); + assert.equal(positive.status, 200, JSON.stringify(positiveBody)); + assert.equal(positiveBody.content, 'homeassistant:\n'); + + const traversals = [ + '../secret.yaml', + // URL-encoded ../ and / + '%2e%2e%2fsecret.yaml', + '..%2F..%2Fsecret.yaml', + '%2e%2e/%2e%2e/etc/passwd', + ]; + + for (const traversal of traversals) { + const res = await api(`/file-content?filePath=${traversal}`); + assert.equal(res.status, 400, `expected 400 for ${traversal}`); + const body = await res.json(); + assert.equal(body.success, false); + assert.doesNotMatch(JSON.stringify(body), new RegExp(SECRET_CONTENT)); + } +}); + +test('file-at-commit rejects git option injection in commitHash', async () => { + const outputPath = path.join(sandbox, 'pwn'); + const res = await api( + `/git/file-at-commit?commitHash=${encodeURIComponent(`--output=${outputPath}`)}&filePath=configuration.yaml` + ); + + assert.equal(res.status, 400); + assert.equal((await res.json()).success, false); +}); + +test('list-yaml-files refuses a liveConfigPath outside CONFIG_PATH', async () => { + const res = await api('/list-yaml-files', { + method: 'POST', + body: { liveConfigPath: '/etc' }, + }); + + assert.equal(res.status, 400); + assert.equal((await res.json()).success, false); +}); + +test('health does not echo request headers', async () => { + const res = await api('/health'); + assert.equal(res.status, 200); + const body = await res.json(); + assert.equal(body.status, 'ok'); + assert.equal('headers' in body, false); +}); diff --git a/homeassistant-version-control/tests/auto-reload.test.mjs b/homeassistant-version-control/tests/auto-reload.test.mjs index 7da4d51..c1f1d1c 100644 --- a/homeassistant-version-control/tests/auto-reload.test.mjs +++ b/homeassistant-version-control/tests/auto-reload.test.mjs @@ -86,6 +86,7 @@ async function startServer(config, { haUrl, autoReload, dataPath }) { CONFIG_PATH: config, PORT: String(port), HOST: '127.0.0.1', + HAVC_API_AUTH: 'off', SUPERVISOR_TOKEN: 'test-token', HA_URL: haUrl, AUTO_RELOAD: String(autoReload), diff --git a/homeassistant-version-control/tests/cloud-mirror.test.mjs b/homeassistant-version-control/tests/cloud-mirror.test.mjs index 7ca94a3..131bb38 100644 --- a/homeassistant-version-control/tests/cloud-mirror.test.mjs +++ b/homeassistant-version-control/tests/cloud-mirror.test.mjs @@ -71,6 +71,7 @@ async function startServer(config, { manualMode = false, env = {} } = {}) { CONFIG_PATH: config, PORT: String(port), HOST: '127.0.0.1', + HAVC_API_AUTH: 'off', MANUAL_MODE: String(manualMode), DEBOUNCE_TIME: '1', DEBOUNCE_TIME_UNIT: 'seconds', diff --git a/homeassistant-version-control/tests/cloud-sync-embedded-auth.test.mjs b/homeassistant-version-control/tests/cloud-sync-embedded-auth.test.mjs index 1b4ee28..3cded5a 100644 --- a/homeassistant-version-control/tests/cloud-sync-embedded-auth.test.mjs +++ b/homeassistant-version-control/tests/cloud-sync-embedded-auth.test.mjs @@ -174,6 +174,7 @@ test('Cloud Sync extracts embedded username:password in remoteUrl, configures ex DATA_PATH: dataDir, HOME: homeDir, GIT_CONFIG_NOSYSTEM: '1', + HAVC_API_AUTH: 'off', }, stdio: ['ignore', 'pipe', 'pipe'], }); @@ -290,6 +291,7 @@ test('Cloud Sync extracts embedded personal access token in remoteUrl and config DATA_PATH: dataDir, HOME: homeDir, GIT_CONFIG_NOSYSTEM: '1', + HAVC_API_AUTH: 'off', }, stdio: ['ignore', 'pipe', 'pipe'], }); diff --git a/homeassistant-version-control/tests/credential-masking.test.mjs b/homeassistant-version-control/tests/credential-masking.test.mjs index 8997e9b..4660f43 100644 --- a/homeassistant-version-control/tests/credential-masking.test.mjs +++ b/homeassistant-version-control/tests/credential-masking.test.mjs @@ -70,6 +70,7 @@ test('startup masks embedded tokens in config.remote_url and options.json', asyn DATA_PATH: dataDir, HOME: homeDir, GIT_CONFIG_NOSYSTEM: '1', + HAVC_API_AUTH: 'off', }, stdio: ['ignore', 'pipe', 'pipe'], }); @@ -131,6 +132,7 @@ test('cloud-sync settings endpoint masks embedded url tokens and redacts authTok DATA_PATH: dataDir, HOME: homeDir, GIT_CONFIG_NOSYSTEM: '1', + HAVC_API_AUTH: 'off', }, stdio: ['ignore', 'pipe', 'pipe'], }); diff --git a/homeassistant-version-control/tests/manual-mode.test.mjs b/homeassistant-version-control/tests/manual-mode.test.mjs index c89756e..0b43dbd 100644 --- a/homeassistant-version-control/tests/manual-mode.test.mjs +++ b/homeassistant-version-control/tests/manual-mode.test.mjs @@ -93,6 +93,7 @@ async function startServer(config, { manualMode, env = {} }) { CONFIG_PATH: config, PORT: String(port), HOST: '127.0.0.1', + HAVC_API_AUTH: 'off', MANUAL_MODE: String(manualMode), DEBOUNCE_TIME: '1', DEBOUNCE_TIME_UNIT: 'seconds', diff --git a/homeassistant-version-control/tests/path-safety.test.mjs b/homeassistant-version-control/tests/path-safety.test.mjs new file mode 100644 index 0000000..806a2ad --- /dev/null +++ b/homeassistant-version-control/tests/path-safety.test.mjs @@ -0,0 +1,150 @@ +// Security regression tests for path traversal in the restore endpoints. +// +// These cover the lexical helpers in utils/path-safety.js and the hardening of +// utils/git.js (gitCheckoutSafe / gitShowFileAtCommit / gitCommitDetails). +// +// Run: node --test tests/path-safety.test.mjs + +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises'; +import { existsSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { + resolveInside, + isInside, + toRepoRelative, + isCommitish, +} from '../utils/path-safety.js'; +import { gitCheckoutSafe } from '../utils/git.js'; + +const ROOT = path.join(tmpdir(), 'havc-path-safety-root'); + +// ────────────────────────────────────────────────── +// resolveInside +// ────────────────────────────────────────────────── + +test('resolveInside accepts a normal relative path', () => { + assert.equal(resolveInside(ROOT, 'automations.yaml'), path.join(ROOT, 'automations.yaml')); +}); + +test('resolveInside accepts a nested relative path', () => { + assert.equal(resolveInside(ROOT, 'packages/lights.yaml'), path.join(ROOT, 'packages', 'lights.yaml')); +}); + +test('resolveInside rejects a ../ escape', () => { + assert.equal(resolveInside(ROOT, '../escape.yaml'), null); + assert.equal(resolveInside(ROOT, 'packages/../../escape.yaml'), null); +}); + +test('resolveInside rejects an absolute path', () => { + assert.equal(resolveInside(ROOT, '/etc/passwd'), null); +}); + +test('resolveInside rejects an empty path', () => { + assert.equal(resolveInside(ROOT, ''), null); + assert.equal(resolveInside(ROOT, ' '), null); +}); + +test('resolveInside rejects null bytes', () => { + assert.equal(resolveInside(ROOT, 'automations.yaml\0.png'), null); +}); + +test('resolveInside only allows the root itself when allowRoot is set', () => { + assert.equal(resolveInside(ROOT, '', { allowRoot: true }), path.resolve(ROOT)); + assert.equal(resolveInside(ROOT, '.', { allowRoot: true }), path.resolve(ROOT)); + assert.equal(resolveInside(ROOT, 'automations.yaml', { allowRoot: true }), path.join(ROOT, 'automations.yaml')); +}); + +// ────────────────────────────────────────────────── +// isInside / toRepoRelative +// ────────────────────────────────────────────────── + +test('isInside detects paths inside and outside the root', () => { + assert.equal(isInside(ROOT, path.join(ROOT, 'automations.yaml')), true); + assert.equal(isInside(ROOT, path.join(ROOT, 'packages', 'lights.yaml')), true); + assert.equal(isInside(ROOT, path.resolve(ROOT)), true); + assert.equal(isInside(ROOT, path.join(ROOT, '..', 'escape.yaml')), false); + assert.equal(isInside(ROOT, '/etc/passwd'), false); +}); + +test('toRepoRelative returns forward-slash relative paths and rejects escapes', () => { + assert.equal(toRepoRelative(ROOT, 'automations.yaml'), 'automations.yaml'); + assert.equal(toRepoRelative(ROOT, 'packages/lights.yaml'), 'packages/lights.yaml'); + assert.equal(toRepoRelative(ROOT, './packages/lights.yaml'), 'packages/lights.yaml'); + assert.equal(toRepoRelative(ROOT, '../escape.yaml'), null); + assert.equal(toRepoRelative(ROOT, '/etc/passwd'), null); + assert.equal(toRepoRelative(ROOT, ''), null); +}); + +// ────────────────────────────────────────────────── +// isCommitish +// ────────────────────────────────────────────────── + +test('isCommitish accepts short/full SHAs and ancestor suffixes', () => { + assert.equal(isCommitish('4f10ce7'), true); + assert.equal(isCommitish('4f10ce7^'), true); + assert.equal(isCommitish('4f10ce7~2'), true); + assert.equal(isCommitish('a'.repeat(40)), true); +}); + +test('isCommitish rejects options, refs and shell fragments', () => { + assert.equal(isCommitish('--output=/tmp/x'), false); + assert.equal(isCommitish('HEAD'), false); + assert.equal(isCommitish('4f10ce7; ls'), false); + assert.equal(isCommitish(''), false); + assert.equal(isCommitish(null), false); +}); + +// ────────────────────────────────────────────────── +// gitCheckoutSafe integration +// ────────────────────────────────────────────────── + +function gitEnv(sandbox) { + return { ...process.env, HOME: path.join(sandbox, 'home'), GIT_CONFIG_NOSYSTEM: '1' }; +} + +function git(cwd, sandbox, ...args) { + return execFileSync('git', args, { cwd, encoding: 'utf8', env: gitEnv(sandbox) }).trim(); +} + +test('gitCheckoutSafe restores inside the repo and rejects traversal', async () => { + const sandbox = await mkdtemp(path.join(tmpdir(), 'havc-path-safety-')); + const repo = path.join(sandbox, 'config'); + const previousConfigPath = global.CONFIG_PATH; + + try { + await mkdir(path.join(sandbox, 'home'), { recursive: true }); + await mkdir(repo, { recursive: true }); + + git(repo, sandbox, 'init', '-b', 'main'); + git(repo, sandbox, 'config', 'user.name', 'Test User'); + git(repo, sandbox, 'config', 'user.email', 'test@example.com'); + + const original = 'automations:\n - alias: original\n'; + await writeFile(path.join(repo, 'automations.yaml'), original); + git(repo, sandbox, 'add', '.'); + git(repo, sandbox, 'commit', '-q', '-m', 'add automations'); + const head = git(repo, sandbox, 'rev-parse', 'HEAD'); + + global.CONFIG_PATH = repo; + + // Restore overwrites a modified tracked file with the committed content. + await writeFile(path.join(repo, 'automations.yaml'), 'automations: [] # modified\n'); + await gitCheckoutSafe(head, 'automations.yaml'); + assert.equal(await readFile(path.join(repo, 'automations.yaml'), 'utf8'), original); + + // Traversal must be refused, and nothing may be written outside the repo. + const outside = path.join(sandbox, 'escape.yaml'); + await assert.rejects( + () => gitCheckoutSafe(head, '../escape.yaml'), + /outside the config root/, + ); + assert.equal(existsSync(outside), false, 'nothing was written outside the repo'); + } finally { + global.CONFIG_PATH = previousConfigPath; + await rm(sandbox, { recursive: true, force: true }); + } +}); diff --git a/homeassistant-version-control/utils/git.js b/homeassistant-version-control/utils/git.js index 1a9c794..1a4da22 100644 --- a/homeassistant-version-control/utils/git.js +++ b/homeassistant-version-control/utils/git.js @@ -2,6 +2,7 @@ import { execFile } from 'child_process'; import { promisify } from 'util'; import fs from 'fs'; import path from 'path'; +import { toRepoRelative, assertCommitish, realPathInsideParent } from './path-safety.js'; const execFileAsync = promisify(execFile); @@ -184,14 +185,26 @@ export async function gitStatus() { } export async function gitShowFileAtCommit(commitHash, filePath) { - // Properly escape filePath for git (handles spaces, special chars) - // Actually execFile handles arguments safely, we don't need manual quoting if passed as array arg - const { stdout } = await gitExec(['show', `${commitHash}:${filePath}`]); + const hash = assertCommitish(commitHash); + + // Normalize the path when we have a config root to anchor against. + // Standalone unit-test imports may not set CONFIG_PATH. + let repoPath = filePath; + if (global.CONFIG_PATH) { + repoPath = toRepoRelative(global.CONFIG_PATH, filePath); + if (repoPath === null) { + throw new Error('Refusing to read a path outside the config root'); + } + } + + // execFile handles arguments safely, no manual quoting needed + const { stdout } = await gitExec(['show', `${hash}:${repoPath}`]); return stdout; } export async function gitCommitDetails(commitHash) { - const { stdout } = await gitExec(['show', '--name-status', '--oneline', commitHash]); + const hash = assertCommitish(commitHash); + const { stdout } = await gitExec(['show', '--name-status', '--oneline', hash]); return stdout; } @@ -273,7 +286,23 @@ export async function gitCheckout(args) { * @param {string} filePath - The file path relative to CONFIG_PATH */ export async function gitCheckoutSafe(commitHash, filePath) { - const fullPath = path.join(global.CONFIG_PATH, filePath); + const hash = assertCommitish(commitHash); + + // Anchor the user-supplied path to the config root and reject traversal + // before touching the filesystem. + const repoPath = toRepoRelative(global.CONFIG_PATH, filePath); + if (repoPath === null) { + throw new Error('Refusing to restore a path outside the config root'); + } + + const fullPath = path.join(global.CONFIG_PATH, repoPath); + + // Also follow symlinks on the nearest existing ancestor, so a symlinked + // directory cannot be used to write outside the config root. + if (!(await realPathInsideParent(global.CONFIG_PATH, fullPath))) { + throw new Error('Refusing to restore a path outside the config root'); + } + let backupContent = null; // First, try to backup the existing file content (in case restore fails) @@ -286,7 +315,7 @@ export async function gitCheckoutSafe(commitHash, filePath) { try { // Get the file content from the commit using git show // This avoids git checkout entirely, which has issues with CIFS/SMB mounts - const { stdout: newContent } = await gitExec(['show', `${commitHash}:${filePath}`]); + const { stdout: newContent } = await gitExec(['show', `${hash}:${repoPath}`]); // Ensure parent directory exists const dir = path.dirname(fullPath); diff --git a/homeassistant-version-control/utils/path-safety.js b/homeassistant-version-control/utils/path-safety.js new file mode 100644 index 0000000..6d60265 --- /dev/null +++ b/homeassistant-version-control/utils/path-safety.js @@ -0,0 +1,152 @@ +import path from 'node:path'; +import { promises as fs } from 'node:fs'; + +/** + * Resolve a user-supplied path underneath a fixed root directory. + * + * Returns the absolute path when it stays inside the root, or null when the + * input is missing, contains a null byte, or escapes the root. + * + * This is a lexical check. Use realPathInside()/realPathInsideParent() when a + * symlink could point somewhere else. + * + * @param {string} root + * @param {string} userPath + * @param {{ allowRoot?: boolean }} [options] + * @returns {string|null} + */ +export function resolveInside(root, userPath, options = {}) { + const { allowRoot = false } = options; + + if (typeof root !== 'string' || typeof userPath !== 'string') return null; + if (root.includes('\0') || userPath.includes('\0')) return null; + + const trimmed = userPath.trim(); + if (!trimmed && !allowRoot) return null; + + const base = path.resolve(root); + const target = path.resolve(base, trimmed); + const relative = path.relative(base, target); + + if (relative === '') { + return allowRoot ? target : null; + } + + if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) { + return null; + } + + return target; +} + +/** + * True when target is root itself or sits underneath root. + * Lexical only. + * + * @param {string} root + * @param {string} target + * @returns {boolean} + */ +export function isInside(root, target) { + if (typeof root !== 'string' || typeof target !== 'string') return false; + if (root.includes('\0') || target.includes('\0')) return false; + + const base = path.resolve(root); + const absolute = path.resolve(target); + const relative = path.relative(base, absolute); + + return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative)); +} + +/** + * Convert a user-supplied path into a repo-relative path using forward slashes. + * Returns null when the path is invalid or escapes the root. + * + * @param {string} root + * @param {string} userPath + * @returns {string|null} + */ +export function toRepoRelative(root, userPath) { + const resolved = resolveInside(root, userPath); + if (!resolved) return null; + const relative = path.relative(path.resolve(root), resolved); + return relative.split(path.sep).join('/'); +} + +/** + * Follow symlinks for an existing path and check that the real target stays + * inside the real root. + * + * @param {string} root + * @param {string} target + * @returns {Promise} + */ +export async function realPathInside(root, target) { + try { + const realRoot = await fs.realpath(root); + const realTarget = await fs.realpath(target); + return isInside(realRoot, realTarget); + } catch { + return false; + } +} + +/** + * Follow symlinks for the nearest existing ancestor of a path that may not + * exist yet. This catches a symlinked directory in the middle of the path + * before a caller creates files underneath it. + * + * @param {string} root + * @param {string} target + * @returns {Promise} + */ +export async function realPathInsideParent(root, target) { + try { + const realRoot = await fs.realpath(root); + let ancestor = path.dirname(path.resolve(target)); + + while (true) { + try { + const realAncestor = await fs.realpath(ancestor); + return isInside(realRoot, realAncestor); + } catch (error) { + if (error.code !== 'ENOENT') return false; + const parent = path.dirname(ancestor); + if (parent === ancestor) return false; + ancestor = parent; + } + } + } catch { + return false; + } +} + +// Short or full SHA, optionally followed by parent/ancestor suffixes, e.g. +// 4f10ce7, 4f10ce7^, 4f10ce7~2, 4f10ce7^^. +const COMMITISH_RE = /^[0-9a-f]{4,64}(?:\^|~\d*)*$/i; + +/** + * True when a value is a plain commit-ish we are willing to pass to git. + * Rejects anything that could be parsed as a git option, such as + * --output=/tmp/file. + * + * @param {unknown} value + * @returns {boolean} + */ +export function isCommitish(value) { + return typeof value === 'string' && COMMITISH_RE.test(value.trim()); +} + +/** + * Throw unless the value is a safe commit-ish. + * + * @param {unknown} value + * @param {string} [label] + * @returns {string} + */ +export function assertCommitish(value, label = 'commit hash') { + if (!isCommitish(value)) { + throw new Error(`Invalid ${label}`); + } + return value.trim(); +}