From fe95ab09a83664d59530cf2d0be287ea4db6a743 Mon Sep 17 00:00:00 2001 From: Mark DeJong Date: Sat, 7 Nov 2026 15:37:46 -0700 Subject: [PATCH] feat(telemetry): feature-usage counting is opt-in, not on by default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The website is about to say telemetry is opt-in and carries no station name. The code said otherwise: GA4 was on in every install, with the station name attached as a user property. This makes the code match the claim. - `core.telemetry_enabled` is the only switch, and a MISSING key means OFF — so an existing install sends nothing until a human opts in. - Opt-in is asked once on the wizard's Done step (unchecked by default) and toggled in Settings -> About & updates (admin only, effective without a restart: the template globals are refreshed when the switch moves). - The only identifier that reaches GA4 is `core.telemetry_install_id`: 32 random hex characters minted at opt-in. The station-name user property is gone from base.html, and the station name is not exposed to the templates at all — so no path, IP, user name or song data can ride along either. - With the switch off, base.html renders NO tag (not a disabled one). Docs updated where the old behaviour was described: CHANGELOG [Unreleased], config/CONFIG.md (+ a "what is and is not sent" section), the README telemetry section, config.example.json, and the in-app Help page (new "Privacy — what leaves the box" section, plus a Settings table row). tests/test_telemetry.py covers the three claims — default config sends nothing, opt-in payload carries the install ID and no station name, an existing config without the key stays off — and the admin-only switch. It pins its own temp paths so it can never write to a developer's real database, and it is listed in .github/workflows/tests.yml (a new test file is invisible to CI until it is). No release. Ticket 987. --- .github/workflows/tests.yml | 4 +- CHANGELOG.md | 14 +++ README.md | 20 +++-- config/CONFIG.md | 22 +++++ config/config.example.json | 3 +- services/core/app.py | 52 ++++++++++- services/core/config.py | 78 ++++++++++++++-- services/core/setup.py | 3 + tests/test_telemetry.py | 173 ++++++++++++++++++++++++++++++++++++ web/templates/base.html | 9 +- web/templates/help.html | 23 +++++ web/templates/settings.html | 64 +++++++++++++ web/templates/setup.html | 13 ++- 13 files changed, 453 insertions(+), 25 deletions(-) create mode 100644 tests/test_telemetry.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 8a0324a..207b182 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -62,9 +62,9 @@ jobs: "test_status_verdict", "test_streaming_settings", "test_sx_report", + "test_telemetry", "test_time_format", - "test_updater", - "test_updater_paths" + "test_updater", "test_updater_paths" ) $failed = @() foreach ($s in $scripts) { diff --git a/CHANGELOG.md b/CHANGELOG.md index 34ba882..4d421ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,20 @@ plain English a non-technical operator can understand. ## [Unreleased] +### Changed +- **Anonymous usage counts are now off unless you say yes.** Before this, the + web page reported which screens were used and attached your **station name** + to it. Now nothing is sent until someone opts in: the last step of the setup + wizard asks once (unchecked), and **Settings → About & updates** has the + switch, which an admin can turn either way at any time. + * When it is on, the page reports which features are used, tagged with a + **random install ID** generated once — never the station name, a file path, + an IP address, a user name or any song data. + * An existing install has no setting for this, and a missing setting counts + as **off** — upgrading a station never starts sending anything. + * Nothing on the playout path has network code, so this cannot touch audio + either way. While it is off the tracking tag is not rendered at all. + ## [1.6.4] - 2026-11-07 ### Added diff --git a/README.md b/README.md index 9a7e015..568bf86 100644 --- a/README.md +++ b/README.md @@ -93,19 +93,23 @@ users and history. ## Telemetry & privacy -The web GUI includes Google Analytics (GA4) usage telemetry so we can see -which features stations actually use. What this means in practice: +Telemetry is **off unless you turn it on**. Nothing leaves the box while it is +off — the tracking tag is not even rendered into the page. What this means in +practice: - It runs **only in the browser GUI** — the audio engine and playout path never send anything, and playback is never affected. -- The data is feature usage (pages and actions in the GUI), with your - **station name** attached so we can tell deployments apart. No listener - data, no audio, no library contents. +- If you turn it on (the setup wizard asks once, and + **Settings → About & updates** changes it later), the page reports **which + features are used**, tagged with a **random install ID** generated once and + stored in `config\config.json`. Your station name is never sent — nor a file + path, an IP address, a user name or any song data. - With no internet connection, the tag simply never loads and the GUI works identically. -- **Opting out** is one line in `config\config.json`: - `"core": { "ga_measurement_id": "" }` — or set your own GA4 measurement ID - there to send usage data to your own property instead. +- An existing config with no `telemetry_enabled` key counts as **off**, so + upgrading never opts a station in. +- To send the counts to your own GA4 property instead, set + `"core": { "telemetry_enabled": true, "ga_measurement_id": "" }`. ## Architecture (the short version) diff --git a/config/CONFIG.md b/config/CONFIG.md index c8b7d34..5578a5f 100644 --- a/config/CONFIG.md +++ b/config/CONFIG.md @@ -57,6 +57,28 @@ exists so old playlists that contain `Z:\...` keep playing. | `feed_ahead_tracks` | How far ahead of the play head the engine queue is fed. | `3` | | `allow_gui_restart` | Shows a "restart everything" button in the UI. Set `false` on an on-air PC so nobody can drop audio from a browser. | `true` | | `update_check` | Look for a newer release every few hours. | `true` | +| `telemetry_enabled` | Anonymous feature-usage counts from the web page. **Off unless you say yes** — asked once in the setup wizard, changeable in Settings. Missing key = off. | `false` | +| `telemetry_install_id` | The random ID the usage counts are tagged with. Created automatically the first time telemetry is turned on; contains nothing about your station or PC. | empty | +| `ga_measurement_id` | Send the counts to your own GA4 property instead of ours. Only used when `telemetry_enabled` is true. | empty (ours) | + +### Telemetry — what is and is not sent + +Feature-usage counting runs **only in the web page**, and only when +`telemetry_enabled` is `true`. It is asked once at the end of the setup wizard +(unchecked by default) and can be changed at any time in +**Settings → About & updates**. + +- **Sent:** which screens and features the browser opens, tagged with + `telemetry_install_id` — a random value minted the first time telemetry is + turned on. +- **Never sent:** your station name, any file path, IP addresses, user names, + song data or listener data. +- **When the switch is off, nothing is sent at all** — the tracking tag is not + even rendered into the page. +- **Nothing on the playout path has network code**, so this can never affect + audio, and the GUI works identically with no internet connection. +- **A config written before this setting existed has no `telemetry_enabled` + key, and a missing key means off** — upgrading a station never opts it in. ## `nowplaying_push` — song titles to your stream host (optional) diff --git a/config/config.example.json b/config/config.example.json index 5e932ea..5d2ca57 100644 --- a/config/config.example.json +++ b/config/config.example.json @@ -17,7 +17,8 @@ "bind_host": "0.0.0.0", "bind_port": 8080, "precache_target_minutes": 45, - "feed_ahead_tracks": 3 + "feed_ahead_tracks": 3, + "telemetry_enabled": false }, "poller": { "interval_sec": 60, diff --git a/services/core/app.py b/services/core/app.py index 6e80b71..78eec02 100644 --- a/services/core/app.py +++ b/services/core/app.py @@ -73,8 +73,18 @@ def create_app(cfg: dict) -> FastAPI: templates = Jinja2Templates(directory=os.path.join(WEB, "templates")) # env globals so EVERY render (routers included) sees them without # threading extra ctx through each handler - templates.env.globals["ga_id"] = cfg.get("ga_measurement_id") or "" - templates.env.globals["ga_station"] = cfg["station_name"] + # + # Telemetry is OPT-IN. ``ga_id`` is empty unless an operator turned it on, + # and base.html keys the entire GA4 tag off it — so an untouched install + # ships no tracking script at all. ``ga_install_id`` is a random value + # minted at opt-in; the station name is deliberately NOT exposed to the + # templates, so it cannot ride along on anything that leaves the box. + def _telemetry_globals(c: dict) -> None: + on = bool(c.get("telemetry_enabled")) and bool(c.get("telemetry_install_id")) + templates.env.globals["ga_id"] = (c.get("ga_measurement_id") or "") if on else "" + templates.env.globals["ga_install_id"] = ( + (c.get("telemetry_install_id") or "") if on else "") + _telemetry_globals(cfg) # cache-buster for /static/style.css: after an update the browser fetches # the new stylesheet instead of showing the old layout until a hard refresh # (read on every render — one stat — so a stylesheet updated while the @@ -95,6 +105,7 @@ def __str__(self): app.state.cfg = cfg app.state.sessions = sessions app.state.templates = templates + app.state.refresh_telemetry = _telemetry_globals app.mount("/static", StaticFiles(directory=os.path.join(WEB, "static")), name="static") @@ -233,7 +244,7 @@ def api_setup_state(request: Request, conn=Depends(get_conn)): @app.post("/api/setup/step") def api_setup_step(request: Request, body: dict, conn=Depends(get_conn)): """Save one wizard step, then move to the next one.""" - from .config import load_config, update_config + from .config import load_config, update_config, set_telemetry from . import playlists as pl step = (body.get("step") or "").strip() values = body.get("values") or {} @@ -284,6 +295,17 @@ def api_setup_step(request: Request, body: dict, conn=Depends(get_conn)): db.set_setting(conn, nowplaying_file.K_PATH, (values.get("np_file") or "").strip()) elif step == "done": + # Telemetry is asked ONCE, here, and the checkbox is unchecked by + # default. An absent answer (Skip, or a stale wizard page in + # another tab) changes nothing, so nobody is ever opted in by + # omission — only an explicit tick sends anything. + if "telemetry" in values: + t = set_telemetry(bool(values.get("telemetry"))) + _telemetry_globals({ + "telemetry_enabled": t["enabled"], + "telemetry_install_id": t["install_id"], + "ga_measurement_id": t["measurement_id"], + }) setup_mod.complete(conn) return {"ok": True, "next": "done", "complete": True} else: @@ -518,6 +540,30 @@ def set_time_format(body: dict, conn=Depends(get_conn), _=Depends(api_user)): sched.set_hour12(fmt == "12") # live — affects the next label render return {"ok": True, "format": fmt} + # ---- anonymous feature-usage telemetry (opt-in, admin only) + @app.get("/api/settings/telemetry") + def get_telemetry(conn=Depends(get_conn), _=Depends(api_user)): + """Off unless someone turned it on. The install ID is shown so an + operator can see exactly what identifier their box would report.""" + from .config import load_config + c = load_config() + return {"enabled": bool(c.get("telemetry_enabled")), + "install_id": c.get("telemetry_install_id") or ""} + + @app.post("/api/settings/telemetry") + def set_telemetry_settings(body: dict, _=Depends(api_admin)): + """Turn feature-usage counting on or off. Admin only: it is a change to + what the station reports about itself, not a display preference.""" + from .config import set_telemetry + t = set_telemetry(bool((body or {}).get("enabled"))) + _telemetry_globals({ + "telemetry_enabled": t["enabled"], + "telemetry_install_id": t["install_id"], + "ga_measurement_id": t["measurement_id"], + }) + return {"ok": True, "enabled": t["enabled"], + "install_id": t["install_id"]} + # ---- user administration (admin only: the one thing Basic can't do) def _norm_role(r: str | None) -> str | None: r = (r or "").strip().lower() diff --git a/services/core/config.py b/services/core/config.py index 7a0bf97..b18d1ad 100644 --- a/services/core/config.py +++ b/services/core/config.py @@ -11,18 +11,77 @@ import json import logging import os +import uuid ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) log = logging.getLogger("core.config") -# Product telemetry: GA4 measurement ID baked into every install so feature -# usage across customer stations lands in one property (station_name rides -# along as a user property). A station can override with its own ID — or -# disable entirely with "core": {"ga_measurement_id": ""} — in config.json. -# The GUI works identically offline; the tag just never loads. +# Product telemetry: GA4 feature-usage counting in the WEB GUI — and it is +# OFF unless the operator says yes. The setup wizard's Done step asks once +# (unchecked) and Settings -> About & updates can change it later. +# +# What may leave the box when it is on: which screens/features the browser +# opened, tagged with a random install ID minted once at opt-in. What must +# NEVER leave: the station name, any file path, IP, user name or song data. +# Nothing on the playout path has network code at all, so telemetry can never +# touch audio; with the switch off, base.html renders no tag whatsoever. GA_MEASUREMENT_ID_DEFAULT = "G-3BK3GZDSJN" # StudioFire GA4 property (VeteranOp) +def load_telemetry(core: dict | None = None) -> dict: + """Telemetry state for a ``core`` config block. Absent key means OFF. + + ``telemetry_enabled`` is the only switch. Every config written before + opt-in existed lacks it, so an upgraded station stays silent until a human + ticks the box — that is the whole compatibility story. + + ``telemetry_install_id`` is the only identifier that reaches GA4. It is + minted at opt-in and contains nothing about the station or the machine. + + ``measurement_id`` comes back EMPTY unless telemetry is on; ``base.html`` + keys the whole tag off it, so an empty value means no script at all. + """ + core = core or {} + enabled = bool(core.get("telemetry_enabled", False)) + own_property = str(core.get("ga_measurement_id") or "").strip() + return { + "enabled": enabled, + "install_id": str(core.get("telemetry_install_id") or "").strip(), + "measurement_id": ((own_property or GA_MEASUREMENT_ID_DEFAULT) + if enabled else ""), + } + + +def new_install_id() -> str: + """A random install identifier — no hostname, MAC, path or user in it.""" + return uuid.uuid4().hex + + +def set_telemetry(enabled: bool, path: str | None = None) -> dict: + """Turn feature-usage telemetry on or off; mint the install ID once. + + Turning it on mints ``telemetry_install_id`` if there is not one already, + and turning it off keeps the ID so re-opting-in stays the same install. + Written atomically through ``update_config`` because the web service reads + this file on every request. + """ + p = (path or os.environ.get("STUDIOFIRE_CONFIG") + or os.path.join(ROOT, "config", "config.json")) + core: dict = {} + try: + with open(p, encoding="utf-8") as fh: + core = (json.load(fh).get("core") or {}) + except (OSError, ValueError): + core = {} + values: dict = {"telemetry_enabled": bool(enabled)} + if enabled and not str(core.get("telemetry_install_id") or "").strip(): + values["telemetry_install_id"] = new_install_id() + update_config({"core": values}, p) + merged = dict(core) + merged.update(values) + return load_telemetry(merged) + + # Now-playing push (#747): off-box, feature-flagged, fire-and-forget pusher # that mirrors StudioFire's current title to the stream CDN's metadata ingest # (e.g. Icecast `updinfo`) so the public player shows song info. OFF by @@ -209,6 +268,7 @@ def load_config(path: str | None = None) -> dict: paths = cfg.get("paths", {}) core = cfg.get("core", {}) engine = cfg.get("engine", {}) + telemetry = load_telemetry(core) # Where a station's own data lives — resolved by the SAME module the engine # uses (services/paths.py), because a disagreement here means the engine # writes the journal and heartbeat where the core never looks. @@ -242,8 +302,12 @@ def load_config(path: str | None = None) -> dict: # dev/dry-run convenience: a GUI "restart everything" button. Set this # to false on the ON-AIR PC so nobody can drop audio from the browser. "allow_gui_restart": bool(core.get("allow_gui_restart", True)), - "ga_measurement_id": core.get("ga_measurement_id", - GA_MEASUREMENT_ID_DEFAULT), + "ga_measurement_id": telemetry["measurement_id"], + # Feature-usage telemetry is opt-in: both stay empty/false unless an + # operator turned it on. ``base.html`` keys the GA tag off the ID, so + # an untouched install renders no tracking script at all. + "telemetry_enabled": telemetry["enabled"], + "telemetry_install_id": telemetry["install_id"], "precache_target_minutes": int(core.get("precache_target_minutes", 45)), # how many tracks P1's queue itself is fed ahead of the play-head — # deliberately shallow; precache_target_minutes (disk cache) is what diff --git a/services/core/setup.py b/services/core/setup.py index 6732031..f0e7b62 100644 --- a/services/core/setup.py +++ b/services/core/setup.py @@ -98,6 +98,9 @@ def state(conn, cfg: dict | None = None) -> dict: "audio_device_guid": (cfg.get("audio_device_guid") or ""), "np_file": db.get_setting(conn, "np_file") or "", "stream_endpoint": db.get_setting(conn, "stream_endpoint") or "", + # Telemetry is opt-in and asked once, on the Done step. Nothing has + # ticked it yet at this point, so the checkbox starts unchecked. + "telemetry": bool((cfg or {}).get("telemetry_enabled")), } for key, _lbl in (("dir_station_ids", None), ("dir_psas", None), ("dir_jingles", None), ("dir_ads", None), diff --git a/tests/test_telemetry.py b/tests/test_telemetry.py new file mode 100644 index 0000000..e5de3f2 --- /dev/null +++ b/tests/test_telemetry.py @@ -0,0 +1,173 @@ +"""Feature-usage telemetry is OPT-IN: default off, random install ID, no station name. + +What this file locks down (the claim the website makes): + +* a config with no telemetry key sends nothing — no tag in the page at all, +* opting in renders the tag with the random install ID and NOT the station name, +* an existing install (config written before the setting existed) stays off, +* the install ID is minted once and survives turning the switch off and on, +* the Settings endpoint flips it live, for an admin only. + +Run: python tests/test_telemetry.py +""" +import json +import os +import re +import sys +import tempfile + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +from fastapi.testclient import TestClient # noqa: E402 + +from services.core import auth, config as core_config, db # noqa: E402 +from services.core.app import create_app # noqa: E402 + +STATION = "KDPI Test Station 88.5" +passed = 0 +GA_TAG = "googletagmanager.com" + + +def check(name, cond): + global passed + if not cond: + print("FAIL:", name) + sys.exit(1) + passed += 1 + print("ok :", name) + + +def write_config(td, core=None, paths=True): + """A config on disk, exactly as an install would have it. + + ``paths`` is what keeps the throwaway app inside ``td`` — without it the + loader falls back to the machine's real data folder and a test would write + users into the developer's own database. + """ + cfgp = os.path.join(td, "config.json") + body = {"station_name": STATION, "core": core or {}} + if paths: + body["paths"] = {"data_dir": os.path.join(td, "data"), + "logs_dir": os.path.join(td, "logs"), + "precache_dir": os.path.join(td, "precache"), + "emergency_dir": os.path.join(td, "emergency"), + "state_path": os.path.join(td, "state.json"), + "heartbeat_path": os.path.join(td, "hb.txt")} + with open(cfgp, "w", encoding="utf-8") as fh: + json.dump(body, fh) + return cfgp + + +def render(cfgp, path="/setup"): + """Load the config the way the service does, build the app, render a page.""" + os.environ["STUDIOFIRE_CONFIG"] = cfgp + cfg = core_config.load_config() + app = create_app(cfg) + client = TestClient(app, follow_redirects=False) + return cfg, client, client.get(path) + + +def ga_block(html): + """The GA4 script tags only — the part that could send something.""" + start = html.find(" + {% endif %} diff --git a/web/templates/help.html b/web/templates/help.html index abbd82f..9475f41 100644 --- a/web/templates/help.html +++ b/web/templates/help.html @@ -56,6 +56,7 @@

Operator's Manual

Song titles & streaming The royalty report Settings + Privacy — what leaves the box Start at boot — services Duplicate cleanup What's new @@ -309,6 +310,8 @@

Settings

The royalty report. Software updatesInstalls new StudioFire versions. See the note below. + Anonymous usage countsOptional feature-usage counting, off by + default. See Privacy — what leaves the box. Backup / restoreSave a copy of your setup, or restore one. What's newThe full history of this version and the ones @@ -325,6 +328,26 @@

Settings

it's safe to click the normal update button. +

Privacy — what leaves the box

+

By default, nothing. StudioFire plays, schedules and reports on this PC + and the studio network. Nothing on the playout path — neither the audio engine nor the + scheduler — has any code that sends data anywhere, so no privacy setting can affect the + audio, and the station stays on air with no internet connection.

+ + + + + +
WhatWhen it sends anything
Anonymous usage countsOff unless someone turns it + on. The setup wizard asks once, and an admin can change it in + Settings → About & updates. When it is on, the web page reports which + screens get used, tagged with a random install ID — never the station name, a file path, + a user name or song data. While it is off, nothing is sent.
Software update checkA periodic request to GitHub to see + whether a newer version exists. It installs nothing without an admin clicking + Install.
Song titles to your streamOnly if you set it up: the + now-playing file your encoder reads, or the optional direct push to the stream host. + See Song titles & streaming.
+

Start at boot — Windows services

If the installer set StudioFire up to run as Windows services (the "start automatically" option), the station starts by itself when the PC diff --git a/web/templates/settings.html b/web/templates/settings.html index 4d28252..031cebb 100644 --- a/web/templates/settings.html +++ b/web/templates/settings.html @@ -445,6 +445,27 @@

What's new

+
+
+
+ Send anonymous feature-usage counts +

Off — nothing is being sent

+
+ +
+

Optional, and off unless you turn it on. + When it is on, the web page reports which screens get used, linked only to a random + install ID — never your station name, file paths, user names or song data. + Nothing on the playout path sends anything, and the station stays on air with no + internet connection either way.

+

+
+
+

Quit StudioFire

Stops all services, including playout. The station @@ -1480,10 +1501,53 @@

Choose a folder { + if (e.currentTarget.disabled) return; + const b = e.currentTarget; + const next = b.getAttribute("aria-pressed") !== "true"; + b.setAttribute("aria-pressed", next ? "true" : "false"); + const r = await fetch("/api/settings/telemetry", {method: "POST", + headers: {"Content-Type": "application/json"}, + body: JSON.stringify({enabled: next})}); + const d = await r.json().catch(() => ({})); + if (!r.ok) { + b.setAttribute("aria-pressed", next ? "false" : "true"); + flash("tel-msg", d.detail || "Could not save that.", true); + return; + } + telRender(d.enabled, d.install_id); + flash("tel-msg", "Saved \u2713"); + }); +} + /* ============================================================ boot */ stShow(stGroupFromHash(), false); loadDirs(); loadSupportContact(); +loadTelemetry(); loadStreaming(); loadUsers(); loadDevices(); diff --git a/web/templates/setup.html b/web/templates/setup.html index b8a650a..a6dc477 100644 --- a/web/templates/setup.html +++ b/web/templates/setup.html @@ -220,6 +220,16 @@

Ready to go

{{ a.audio_device_guid or 'Windows default' }}
+
+ +

Optional, and off unless you tick + it. If you do, the web page reports which screens get used, linked only to a + random install ID — never your station name, file paths, user names or song data. + Nothing on the playout path sends anything, and you can change this later in + Settings → About & updates.

+
Download a copy of your settings @@ -301,9 +311,10 @@

Choose a folder

function wizBack() { history.back(); } async function wizFinish() { + const tel = document.getElementById("wz-telemetry"); await fetch("/api/setup/step", {method: "POST", headers: {"Content-Type": "application/json"}, - body: JSON.stringify({step: "done", values: {}})}); + body: JSON.stringify({step: "done", values: tel ? {telemetry: tel.checked} : {}})}); location.href = "/"; }