A live bird collage card for your Home Assistant dashboard.
Ship 1.7.0: remote access through Bird Card Proxy (#84)
Adam Oberleycecbd008457e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5c052316..3b6c0cd2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,22 @@# Changelog+## v1.7.0 — 2026-09-30++### Added+- **Remote access through Home Assistant, recordings included**+ ([#73](https://github.com/adamoberley/HABirdDashboard/issues/73),+ requested by @nowagner). The new, optional companion integration+ [Bird Card Proxy](https://github.com/adamoberley/HABirdDashboard-proxy)+ serves BirdNET-Go's API on Home Assistant's own address. When it's+ installed, the card routes every BirdNET-Go call through it: reads and+ audio via HA's authenticated fetch, the live feed via an HA signed URL,+ and the "not it?" review as a plain POST (the proxy handles BirdNET-Go's+ CSRF check and only lets admins write). That makes the card fully work+ over Nabu Casa, VPNs and `https://` dashboards on every install type,+ including HA in Docker / Core, which has no add-on ingress. BirdNET-Go's+ API token lives in the integration, never in the browser. New card+ option `proxy: false` keeps a card on the direct connection.+## v1.6.3 — 2026-09-30### Changeddiff --git a/README.md b/README.mdindex 941fed16..354d2983 100644--- a/README.md+++ b/README.md@@ -246,6 +246,8 @@ language: "" # UI language override, e.g. "da" - empty = follow# each user's HA language (see Languages below)birdnet_url: "" # empty = this host, port 8080 (the stock app)data_source: auto # auto | api | ha (see Data sources below)+proxy: true # use the Bird Card Proxy integration when it's installed+ # (see Remote access below); false = always directhistory_days: 10 # ha-source span; bounded by recorder retentionsit_confidence: 0.90 # perched at/above, flying belowcollage_fill: 0.5 # screen fill 0.1-1.0 (0.5 = half, 1.0 = full; busier = wider)@@ -410,10 +412,27 @@ The card can feed from two places:their history - the card rebuilds the full detection stream (time,species, confidence per detection) from it through its own HAconnection. No extra URL, no port, no token. The trade-offs: audio- clips can't travel over MQTT (play buttons show "no audio"), and the+ clips can't travel over MQTT (play buttons grey out), and thelife list / ALL window reach back only as far as your recorderretention (default ~10 days; `history_days` caps the query).+### Remote access with Bird Card Proxy (optional)++The REST API is reached **from your browser**, so away from home it only+works if your browser can reach BirdNET-Go. Otherwise the card falls back+to MQTT history, which has no recordings. On Home Assistant OS with the+BirdNET-Go add-on, the card routes through add-on ingress automatically+(admin users only).++For every other setup, including HA in Docker / Core, VPNs, and non-admin+users, install the companion integration+**[Bird Card Proxy](https://github.com/adamoberley/HABirdDashboard-proxy)**+(HACS custom repository, type *Integration*). It serves BirdNET-Go's API+on Home Assistant's own address, so recordings, the live feed and the+"not it?" review work anywhere Home Assistant does. The card detects it+automatically; set `proxy: false` on a card to keep that card talking to+BirdNET-Go directly.+### Enabling MQTT (recommended)MQTT is worth the five minutes even when the API works: detections **push**@@ -677,9 +696,10 @@ ring layout, `?names` (or `?names=scientific` / `?names=both`) plusdefault `birdnet_url` (leave it empty); if it can't be set up, datastill flows via the MQTT sensors - only audio playback is lost.- **HA in Docker / Core (no Supervisor), remote or on a VPN.** Ingress- discovery needs the Supervisor, so on these installs there is no- automatic remote path yet ([#73](https://github.com/adamoberley/HABirdDashboard/issues/73)).- Put BirdNET-Go behind the same HTTPS reverse proxy as HA (Traefik,+ discovery needs the Supervisor, so install+ [Bird Card Proxy](https://github.com/adamoberley/HABirdDashboard-proxy)+ (see [Remote access](#remote-access-with-bird-card-proxy-optional)).+ Alternatively, put BirdNET-Go behind an HTTPS reverse proxy (Traefik,Caddy, nginx...) and set `birdnet_url` to that `https://` hostname: nomixed content, and it works anywhere that hostname resolves.- **"Can't reach BirdNET-Go from this browser."** The card gave up ondiff --git a/addons/birdframe/config.yaml b/addons/birdframe/config.yamlindex 2b547fa2..2388cd53 100644--- a/addons/birdframe/config.yaml+++ b/addons/birdframe/config.yaml@@ -6,7 +6,7 @@# Frame TV's Art Mode - replacing the previous upload in place so the TV's art# library never accumulates duplicates.name: Bird Frame (Samsung Frame TV)-version: "1.6.3"+version: "1.7.0"slug: birdframedescription: >-Render the live Bird collage and push it to a Samsung Frame TV as Art Modediff --git a/addons/birdframe/www/apt.js b/addons/birdframe/www/apt.jsindex 39c9b287..8db306ec 100644--- a/addons/birdframe/www/apt.js+++ b/addons/birdframe/www/apt.js@@ -177,6 +177,23 @@function bgUrl(path) { return BG_BASE + '/api/v2' + path; }+ // ---- Bird Card Proxy (#73) ----+ // The optional habird_proxy integration+ // (github.com/adamoberley/HABirdDashboard-proxy) serves BirdNET-Go's API+ // on HA's own origin, so the card works anywhere HA does - remote, VPN,+ // https - with audio. When it's loaded, route EVERY BirdNET-Go call+ // through it (unless the card sets proxy: false): reads and audio via+ // hass.fetchWithAuth, the live stream via an HA signed URL. BirdNET-Go's+ // own token lives in the integration, so api_token isn't sent from here.+ var PROXY_BASE = '/api/habird_proxy';+ function proxyHass() {+ var h = AV_CFG.proxy !== false && AV_CFG.__getHass && AV_CFG.__getHass();+ var comps = (h && h.config && h.config.components) || [];+ return (h && h.fetchWithAuth && comps.indexOf('habird_proxy') >= 0) ? h : null;+ }+ var PROXY_MODE = !!proxyHass();+ if (PROXY_MODE) BG_BASE = PROXY_BASE;+// ---- API token (Private Mode) ----// BirdNET-Go's "Private Mode" (Security.PrivateMode, mid-2026+) locks the// ENTIRE v2 API behind login - every unauthenticated request 401s, even@@ -190,6 +207,10 @@// and never see it. With no token set this is a transparent passthrough.function bgFetch(url, opts) {opts = opts || {};+ if (PROXY_MODE && url.indexOf(PROXY_BASE + '/') === 0) {+ // HA login instead of BirdNET-Go's token (the proxy adds that).+ return proxyHass().fetchWithAuth(url, opts);+ }if (!AV_CFG.apiToken) return fetch(url, opts);var headers = {}, k;for (k in (opts.headers || {})) headers[k] = opts.headers[k];@@ -301,7 +322,7 @@// rebase ALL reads onto ingress. On plain http the direct LAN base is// faster and stays; ingress is still resolved on demand for writes.var BG_READY = Promise.resolve();- if (!AV_CFG.birdnetGoUrl && location.protocol === 'https:' && AV_CFG.__getHass) {+ if (!PROXY_MODE && !AV_CFG.birdnetGoUrl && location.protocol === 'https:' && AV_CFG.__getHass) {BG_READY = ingressApiBase().then(function (b) { if (b) BG_BASE = b; });}@@ -317,6 +338,16 @@// that's the nature of double-submit; the protection is that cross-site// JS can't set this origin's cookies, and we're legitimately same-origin.function bgReview(id, verified) {+ if (PROXY_MODE) {+ // The proxy handles BirdNET-Go's CSRF check server-side (and only+ // lets HA admins write, like ingress does).+ return bgFetch(PROXY_BASE + '/api/v2/detections/' + encodeURIComponent(id) + '/review', {+ method: 'POST',+ cache: 'no-store',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ verified: verified, correct: verified }),+ }).then(function (r) { return r.ok ? r : Promise.reject(r.status); });+ }return ingressApiBase().then(function (ib) {var sameOrigin = !!ib ||BG_BASE.indexOf(location.protocol + '//' + location.host) === 0 ||@@ -380,7 +411,8 @@var audio = new Audio();var db = +AV_CFG.audioBoostDb || 0;if (db > 0) audio.crossOrigin = 'anonymous';- if (AV_CFG.apiToken) {+ // Through the proxy, the clip request needs HA's login header too.+ if (AV_CFG.apiToken || PROXY_MODE) {// Deliberately never revoke this object URL: the 'emptied' event// (the obvious hook) fires as part of the same load algorithm that// sets audio.src in the first place, which would revoke the blob@@ -3734,10 +3766,27 @@liveDebounceT = null;if (liveSource) { liveSource.close(); liveSource = null; }}+ var liveSigning = false;function startLive() {- if (!LIVE_ENABLED || liveGaveUp || liveSource || document.hidden) return;+ if (!LIVE_ENABLED || liveGaveUp || liveSource || liveSigning || document.hidden) return;+ var ph = PROXY_MODE && proxyHass();+ if (PROXY_MODE) {+ // EventSource can't send HA's login header, so ask HA for a signed+ // URL (valid 5 minutes - it's only checked when the stream opens;+ // every reconnect signs a fresh one).+ if (!ph || !ph.callWS) { liveGaveUp = true; return; }+ liveSigning = true;+ ph.callWS({ type: 'auth/sign_path', path: bgUrl('/detections/stream'), expires: 300 })+ .then(function (r) { liveSigning = false; openLive(r.path); },+ function () { liveSigning = false; liveGaveUp = true; });+ return;+ }+ openLive(bgUrl('/detections/stream'));+ }+ function openLive(url) {+ if (liveSource || document.hidden) return;var opened = false;- var es = new EventSource(bgUrl('/detections/stream'));+ var es = new EventSource(url);liveSource = es;es.addEventListener('detection', liveDebouncedRefresh);es.onopen = function () {diff --git a/dist/habird-card.js b/dist/habird-card.jsindex 22b5a13a..0f2030cb 100644--- a/dist/habird-card.js+++ b/dist/habird-card.js@@ -2328,6 +2328,23 @@ function runHABirdApp(__root, __shell, __cardConfig, __imgBase) {function bgUrl(path) { return BG_BASE + '/api/v2' + path; }+ // ---- Bird Card Proxy (#73) ----+ // The optional habird_proxy integration+ // (github.com/adamoberley/HABirdDashboard-proxy) serves BirdNET-Go's API+ // on HA's own origin, so the card works anywhere HA does - remote, VPN,+ // https - with audio. When it's loaded, route EVERY BirdNET-Go call+ // through it (unless the card sets proxy: false): reads and audio via+ // hass.fetchWithAuth, the live stream via an HA signed URL. BirdNET-Go's+ // own token lives in the integration, so api_token isn't sent from here.+ var PROXY_BASE = '/api/habird_proxy';+ function proxyHass() {+ var h = AV_CFG.proxy !== false && AV_CFG.__getHass && AV_CFG.__getHass();+ var comps = (h && h.config && h.config.components) || [];+ return (h && h.fetchWithAuth && comps.indexOf('habird_proxy') >= 0) ? h : null;+ }+ var PROXY_MODE = !!proxyHass();+ if (PROXY_MODE) BG_BASE = PROXY_BASE;+// ---- API token (Private Mode) ----// BirdNET-Go's "Private Mode" (Security.PrivateMode, mid-2026+) locks the// ENTIRE v2 API behind login - every unauthenticated request 401s, even@@ -2341,6 +2358,10 @@ function runHABirdApp(__root, __shell, __cardConfig, __imgBase) {// and never see it. With no token set this is a transparent passthrough.function bgFetch(url, opts) {opts = opts || {};+ if (PROXY_MODE && url.indexOf(PROXY_BASE + '/') === 0) {+ // HA login instead of BirdNET-Go's token (the proxy adds that).+ return proxyHass().fetchWithAuth(url, opts);+ }if (!AV_CFG.apiToken) return fetch(url, opts);var headers = {}, k;for (k in (opts.headers || {})) headers[k] = opts.headers[k];@@ -2452,7 +2473,7 @@ function runHABirdApp(__root, __shell, __cardConfig, __imgBase) {// rebase ALL reads onto ingress. On plain http the direct LAN base is// faster and stays; ingress is still resolved on demand for writes.var BG_READY = Promise.resolve();- if (!AV_CFG.birdnetGoUrl && location.protocol === 'https:' && AV_CFG.__getHass) {+ if (!PROXY_MODE && !AV_CFG.birdnetGoUrl && location.protocol === 'https:' && AV_CFG.__getHass) {BG_READY = ingressApiBase().then(function (b) { if (b) BG_BASE = b; });}@@ -2468,6 +2489,16 @@ function runHABirdApp(__root, __shell, __cardConfig, __imgBase) {// that's the nature of double-submit; the protection is that cross-site// JS can't set this origin's cookies, and we're legitimately same-origin.function bgReview(id, verified) {+ if (PROXY_MODE) {+ // The proxy handles BirdNET-Go's CSRF check server-side (and only+ // lets HA admins write, like ingress does).+ return bgFetch(PROXY_BASE + '/api/v2/detections/' + encodeURIComponent(id) + '/review', {+ method: 'POST',+ cache: 'no-store',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ verified: verified, correct: verified }),+ }).then(function (r) { return r.ok ? r : Promise.reject(r.status); });+ }return ingressApiBase().then(function (ib) {var sameOrigin = !!ib ||BG_BASE.indexOf(location.protocol + '//' + location.host) === 0 ||@@ -2531,7 +2562,8 @@ function runHABirdApp(__root, __shell, __cardConfig, __imgBase) {var audio = new Audio();var db = +AV_CFG.audioBoostDb || 0;if (db > 0) audio.crossOrigin = 'anonymous';- if (AV_CFG.apiToken) {+ // Through the proxy, the clip request needs HA's login header too.+ if (AV_CFG.apiToken || PROXY_MODE) {// Deliberately never revoke this object URL: the 'emptied' event// (the obvious hook) fires as part of the same load algorithm that// sets audio.src in the first place, which would revoke the blob@@ -5885,10 +5917,27 @@ function runHABirdApp(__root, __shell, __cardConfig, __imgBase) {liveDebounceT = null;if (liveSource) { liveSource.close(); liveSource = null; }}+ var liveSigning = false;function startLive() {- if (!LIVE_ENABLED || liveGaveUp || liveSource || document.hidden) return;+ if (!LIVE_ENABLED || liveGaveUp || liveSource || liveSigning || document.hidden) return;+ var ph = PROXY_MODE && proxyHass();+ if (PROXY_MODE) {+ // EventSource can't send HA's login header, so ask HA for a signed+ // URL (valid 5 minutes - it's only checked when the stream opens;+ // every reconnect signs a fresh one).+ if (!ph || !ph.callWS) { liveGaveUp = true; return; }+ liveSigning = true;+ ph.callWS({ type: 'auth/sign_path', path: bgUrl('/detections/stream'), expires: 300 })+ .then(function (r) { liveSigning = false; openLive(r.path); },+ function () { liveSigning = false; liveGaveUp = true; });+ return;+ }+ openLive(bgUrl('/detections/stream'));+ }+ function openLive(url) {+ if (liveSource || document.hidden) return;var opened = false;- var es = new EventSource(bgUrl('/detections/stream'));+ var es = new EventSource(url);liveSource = es;es.addEventListener('detection', liveDebouncedRefresh);es.onopen = function () {@@ -8195,7 +8244,7 @@ function runHABirdApp(__root, __shell, __cardConfig, __imgBase) {// you copied the artwork locally (homeassistant/install.sh layout).var HABIRD_CDN_ASSETS = 'https://cdn.jsdelivr.net/gh/adamoberley/HABirdDashboard@HABirdDashboard/avian/assets/';-var HABIRD_VERSION = '1.6.3';+var HABIRD_VERSION = '1.7.0';var HABIRD_EDITOR_SCHEMA = [{ name: 'dashboard', type: 'expandable', flatten: true, title: 'Dashboard', expanded: true, schema: [@@ -8384,6 +8433,9 @@ class HABirdCard extends HTMLElement {if (config.names != null && ['off', 'common', 'scientific', 'both'].indexOf(config.names) < 0) {throw new Error("names must be 'off', 'common', 'scientific' or 'both'");}+ if (config.proxy != null && typeof config.proxy !== 'boolean') {+ throw new Error('proxy must be true or false');+ }if (config.names_size != null && !(+config.names_size > 0)) {throw new Error('names_size must be a positive number of pixels');}@@ -8491,6 +8543,7 @@ class HABirdCard extends HTMLElement {windowHours: c.window || 24, // hours, or 'all'birdnetGoUrl: c.birdnet_url || '',apiToken: c.api_token || '', // Bearer token for BirdNET-Go's "Private Mode"+ proxy: c.proxy, // false = ignore the Bird Card Proxy integrationdataSource: c.data_source || 'auto',language: c.language || '', // UI language override ('' = auto: hass -> browser)historyDays: c.history_days,diff --git a/homeassistant/card/build.js b/homeassistant/card/build.jsindex 9c3dd040..9adb7077 100644--- a/homeassistant/card/build.js+++ b/homeassistant/card/build.js@@ -228,7 +228,7 @@ const wrapper = `// you copied the artwork locally (homeassistant/install.sh layout).var HABIRD_CDN_ASSETS = 'https://cdn.jsdelivr.net/gh/adamoberley/HABirdDashboard@HABirdDashboard/avian/assets/';-var HABIRD_VERSION = '1.6.3';+var HABIRD_VERSION = '1.7.0';var HABIRD_EDITOR_SCHEMA = [{ name: 'dashboard', type: 'expandable', flatten: true, title: 'Dashboard', expanded: true, schema: [@@ -417,6 +417,9 @@ class HABirdCard extends HTMLElement {if (config.names != null && ['off', 'common', 'scientific', 'both'].indexOf(config.names) < 0) {throw new Error("names must be 'off', 'common', 'scientific' or 'both'");}+ if (config.proxy != null && typeof config.proxy !== 'boolean') {+ throw new Error('proxy must be true or false');+ }if (config.names_size != null && !(+config.names_size > 0)) {throw new Error('names_size must be a positive number of pixels');}@@ -524,6 +527,7 @@ class HABirdCard extends HTMLElement {windowHours: c.window || 24, // hours, or 'all'birdnetGoUrl: c.birdnet_url || '',apiToken: c.api_token || '', // Bearer token for BirdNET-Go's "Private Mode"+ proxy: c.proxy, // false = ignore the Bird Card Proxy integrationdataSource: c.data_source || 'auto',language: c.language || '', // UI language override ('' = auto: hass -> browser)historyDays: c.history_days,diff --git a/homeassistant/www/apt.js b/homeassistant/www/apt.jsindex 39c9b287..8db306ec 100644--- a/homeassistant/www/apt.js+++ b/homeassistant/www/apt.js@@ -177,6 +177,23 @@function bgUrl(path) { return BG_BASE + '/api/v2' + path; }+ // ---- Bird Card Proxy (#73) ----+ // The optional habird_proxy integration+ // (github.com/adamoberley/HABirdDashboard-proxy) serves BirdNET-Go's API+ // on HA's own origin, so the card works anywhere HA does - remote, VPN,+ // https - with audio. When it's loaded, route EVERY BirdNET-Go call+ // through it (unless the card sets proxy: false): reads and audio via+ // hass.fetchWithAuth, the live stream via an HA signed URL. BirdNET-Go's+ // own token lives in the integration, so api_token isn't sent from here.+ var PROXY_BASE = '/api/habird_proxy';+ function proxyHass() {+ var h = AV_CFG.proxy !== false && AV_CFG.__getHass && AV_CFG.__getHass();+ var comps = (h && h.config && h.config.components) || [];+ return (h && h.fetchWithAuth && comps.indexOf('habird_proxy') >= 0) ? h : null;+ }+ var PROXY_MODE = !!proxyHass();+ if (PROXY_MODE) BG_BASE = PROXY_BASE;+// ---- API token (Private Mode) ----// BirdNET-Go's "Private Mode" (Security.PrivateMode, mid-2026+) locks the// ENTIRE v2 API behind login - every unauthenticated request 401s, even@@ -190,6 +207,10 @@// and never see it. With no token set this is a transparent passthrough.function bgFetch(url, opts) {opts = opts || {};+ if (PROXY_MODE && url.indexOf(PROXY_BASE + '/') === 0) {+ // HA login instead of BirdNET-Go's token (the proxy adds that).+ return proxyHass().fetchWithAuth(url, opts);+ }if (!AV_CFG.apiToken) return fetch(url, opts);var headers = {}, k;for (k in (opts.headers || {})) headers[k] = opts.headers[k];@@ -301,7 +322,7 @@// rebase ALL reads onto ingress. On plain http the direct LAN base is// faster and stays; ingress is still resolved on demand for writes.var BG_READY = Promise.resolve();- if (!AV_CFG.birdnetGoUrl && location.protocol === 'https:' && AV_CFG.__getHass) {+ if (!PROXY_MODE && !AV_CFG.birdnetGoUrl && location.protocol === 'https:' && AV_CFG.__getHass) {BG_READY = ingressApiBase().then(function (b) { if (b) BG_BASE = b; });}@@ -317,6 +338,16 @@// that's the nature of double-submit; the protection is that cross-site// JS can't set this origin's cookies, and we're legitimately same-origin.function bgReview(id, verified) {+ if (PROXY_MODE) {+ // The proxy handles BirdNET-Go's CSRF check server-side (and only+ // lets HA admins write, like ingress does).+ return bgFetch(PROXY_BASE + '/api/v2/detections/' + encodeURIComponent(id) + '/review', {+ method: 'POST',+ cache: 'no-store',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ verified: verified, correct: verified }),+ }).then(function (r) { return r.ok ? r : Promise.reject(r.status); });+ }return ingressApiBase().then(function (ib) {var sameOrigin = !!ib ||BG_BASE.indexOf(location.protocol + '//' + location.host) === 0 ||@@ -380,7 +411,8 @@var audio = new Audio();var db = +AV_CFG.audioBoostDb || 0;if (db > 0) audio.crossOrigin = 'anonymous';- if (AV_CFG.apiToken) {+ // Through the proxy, the clip request needs HA's login header too.+ if (AV_CFG.apiToken || PROXY_MODE) {// Deliberately never revoke this object URL: the 'emptied' event// (the obvious hook) fires as part of the same load algorithm that// sets audio.src in the first place, which would revoke the blob@@ -3734,10 +3766,27 @@liveDebounceT = null;if (liveSource) { liveSource.close(); liveSource = null; }}+ var liveSigning = false;function startLive() {- if (!LIVE_ENABLED || liveGaveUp || liveSource || document.hidden) return;+ if (!LIVE_ENABLED || liveGaveUp || liveSource || liveSigning || document.hidden) return;+ var ph = PROXY_MODE && proxyHass();+ if (PROXY_MODE) {+ // EventSource can't send HA's login header, so ask HA for a signed+ // URL (valid 5 minutes - it's only checked when the stream opens;+ // every reconnect signs a fresh one).+ if (!ph || !ph.callWS) { liveGaveUp = true; return; }+ liveSigning = true;+ ph.callWS({ type: 'auth/sign_path', path: bgUrl('/detections/stream'), expires: 300 })+ .then(function (r) { liveSigning = false; openLive(r.path); },+ function () { liveSigning = false; liveGaveUp = true; });+ return;+ }+ openLive(bgUrl('/detections/stream'));+ }+ function openLive(url) {+ if (liveSource || document.hidden) return;var opened = false;- var es = new EventSource(bgUrl('/detections/stream'));+ var es = new EventSource(url);liveSource = es;es.addEventListener('detection', liveDebouncedRefresh);es.onopen = function () {diff --git a/package-lock.json b/package-lock.jsonindex 3dc6a33d..b90279da 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "habird-dashboard",- "version": "1.6.3",+ "version": "1.7.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "habird-dashboard",- "version": "1.6.3",+ "version": "1.7.0","license": "MIT","devDependencies": {"jsdom": "^24.0.0"diff --git a/package.json b/package.jsonindex cfbf7ef5..f60361b8 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "habird-dashboard",- "version": "1.6.3",+ "version": "1.7.0","private": true,"description": "Bird Card - a live bird collage card for Home Assistant, fed by BirdNET-Go","license": "MIT",diff --git a/tests/test-proxy.js b/tests/test-proxy.jsnew file mode 100644index 00000000..1733d484--- /dev/null+++ b/tests/test-proxy.js@@ -0,0 +1,121 @@+// Bird Card Proxy (#73): with the habird_proxy integration loaded, every+// BirdNET-Go call goes through HA's origin with HA's login - reads and+// audio via hass.fetchWithAuth, the live stream via a signed URL, review+// writes as a plain POST (the proxy does CSRF) - and nothing is fetched+// from BirdNET-Go directly. proxy: false restores the direct connection.+const path = require('path');+const ROOT = path.resolve(__dirname, '..');+const fs = require('fs');+const assert = require('assert');+const { JSDOM } = require('jsdom');+const CARD = fs.readFileSync(ROOT + '/dist/habird-card.js', 'utf8');++const summary = [+ { scientific_name: 'Corvus corax', common_name: 'Common Raven', count: 9, first_heard: '2026-06-01 09:00:00', last_heard: '2026-06-10 08:20:00', max_confidence: 0.95 },+];+const daily = summary.map(s => ({ ...s, hourly_counts: Array(24).fill(1), latest_heard: '08:20:00' }));+function answer(p, opts) {+ const json = (b) => ({ ok: true, status: 200, json: () => Promise.resolve(JSON.parse(JSON.stringify(b))),+ blob: () => Promise.resolve({ size: 3 }), arrayBuffer: () => Promise.resolve(new ArrayBuffer(8)), headers: { get: () => null } });+ if (p.startsWith('/api/v2/analytics/species/summary')) return json(summary);+ if (p.startsWith('/api/v2/analytics/species/daily')) return json(daily);+ if (p.includes('/analytics/')) return json({ data: [] });+ if (p.includes('/detections?queryType=search')) return json({ data: [+ { id: 42, date: '2026-06-10', time: '08:20:00', scientificName: 'Corvus corax', commonName: 'Common Raven', confidence: 0.95 },+ ], total: 1 });+ if (p.includes('/audio/')) return json({});+ if (p.endsWith('/review') && opts && opts.method === 'POST') return json({ ok: true });+ return { ok: false, status: 404, json: () => Promise.reject(404), headers: { get: () => null } };+}++function boot(config) {+ const dom = new JSDOM('<!doctype html><html><body></body></html>', {+ url: 'https://example.ui.nabu.casa/lovelace/birds', runScripts: 'outside-only', pretendToBeVisual: true,+ });+ const { window } = dom;+ const log = { direct: [], viaHa: [], signed: [], streams: [] };+ const errors = [];+ window.addEventListener('error', e => errors.push((e.error && e.error.stack) || e.message));+ window.fetch = (url, opts) => { log.direct.push(String(url)); return Promise.resolve(answer(String(url).replace(/^https?:\/\/[^/]+/, ''), opts)); };+ window.EventSource = class { constructor(u) { log.streams.push(u); } addEventListener() {} close() {} };+ window.URL.createObjectURL = () => 'blob:clip';+ window.Audio = class { addEventListener() {} load() {} play() { return Promise.resolve(); } pause() {} };+ Object.defineProperty(window.HTMLElement.prototype, 'clientWidth', { get() { return this.id === 'collage' ? 1200 : 300; } });+ Object.defineProperty(window.HTMLElement.prototype, 'clientHeight', { get() { return this.id === 'collage' ? 800 : 100; } });+ window.HTMLCanvasElement.prototype.getContext = () => null;+ window.ResizeObserver = class { observe() {} disconnect() {} };+ window.eval(CARD);+ const hass = {+ themes: { darkMode: false },+ states: {},+ user: { is_admin: true },+ config: { components: ['http', 'habird_proxy'] },+ fetchWithAuth: (url, opts) => {+ log.viaHa.push({ url, opts: opts || {} });+ assert.ok(url.startsWith('/api/habird_proxy/api/v2/'), 'proxy path: ' + url);+ return Promise.resolve(answer(url.replace('/api/habird_proxy', ''), opts));+ },+ callWS: (msg) => {+ if (msg.type === 'auth/sign_path') { log.signed.push(msg); return Promise.resolve({ path: msg.path + '?authSig=SIG' }); }+ return Promise.reject(new Error('unexpected ' + msg.type));+ },+ };+ const card = window.document.createElement('habird-card');+ card.setConfig(Object.assign({ api_token: 'bng-token-should-stay-server-side' }, config));+ card.hass = hass;+ window.document.body.appendChild(card);+ return { window, card, log, errors };+}++const click = (window, el) => el.dispatchEvent(new window.MouseEvent('click', { bubbles: true, composed: true }));++const A = boot({});+const B = boot({ proxy: false, birdnet_url: 'http://birdnet.lan:8080' });++setTimeout(() => {+ try {+ const { window, card, log } = A;+ const root = card.shadowRoot;+ assert.strictEqual(root.querySelectorAll('.gtile').length, 1, 'collage rendered from proxied data');+ assert.ok(log.viaHa.length >= 2, 'reads went through hass.fetchWithAuth: ' + log.viaHa.length);+ assert.deepStrictEqual(log.direct.filter(u => /\/api\/v2\//.test(u)), [], 'no direct BirdNET-Go fetches: ' + log.direct);+ assert.ok(log.viaHa.every(c => !JSON.stringify(c.opts.headers || {}).includes('bng-token')), 'api_token never sent from the browser');+ // Live stream: signed URL, then EventSource on it.+ assert.strictEqual(log.signed.length, 1, 'one sign_path request');+ assert.strictEqual(log.signed[0].path, '/api/habird_proxy/api/v2/detections/stream');+ assert.deepStrictEqual(log.streams, ['/api/habird_proxy/api/v2/detections/stream?authSig=SIG'], 'stream opened on the signed URL');+ // Play is enabled (the API is reachable) and fetches the clip through HA.+ const play = root.querySelector('.bird-card .chip.play');+ assert.ok(play && !play.disabled, 'play enabled through the proxy');+ click(window, play);+ setTimeout(() => {+ try {+ assert.ok(log.viaHa.some(c => c.url === '/api/habird_proxy/api/v2/audio/42'), 'clip fetched through HA: ' + log.viaHa.map(c => c.url));+ // Review write-back: plain POST through the proxy, no ingress, no CSRF from the browser.+ click(window, root.querySelector('.bird-card'));+ setTimeout(() => {+ try {+ const flag = root.querySelector('#modalRecordings .rec-row .flag');+ assert.ok(flag, 'flag rendered');+ click(window, flag); click(window, flag);+ setTimeout(() => {+ try {+ const post = log.viaHa.find(c => c.opts.method === 'POST');+ assert.ok(post, 'review POSTed');+ assert.strictEqual(post.url, '/api/habird_proxy/api/v2/detections/42/review');+ assert.strictEqual(JSON.parse(post.opts.body).verified, 'false_positive');+ assert.strictEqual(flag.getAttribute('data-state'), 'done', 'flag done: ' + flag.getAttribute('data-state'));+ // proxy: false -> talks to BirdNET-Go directly, as before.+ assert.strictEqual(B.log.viaHa.length, 0, 'proxy: false never uses the proxy');+ assert.ok(B.log.direct.some(u => u.startsWith('http://birdnet.lan:8080/api/v2/')), 'proxy: false fetches directly');+ assert.deepStrictEqual(A.errors.concat(B.errors), [], 'no page errors');+ console.log('PROXY TEST PASSED');+ process.exit(0);+ } catch (e) { console.error('FAIL:', e.message); process.exit(1); }+ }, 400);+ } catch (e) { console.error('FAIL:', e.message); process.exit(1); }+ }, 900);+ } catch (e) { console.error('FAIL:', e.message); process.exit(1); }+ }, 400);+ } catch (e) { console.error('FAIL:', e.message); process.exit(1); }+}, 1800);