mirror of
https://github.com/debpalash/VoiceStudio.git
synced 2026-12-04 01:18:16 +00:00
Send opt-in analytics to Supermetry instead of PostHog and record the engine used
This commit is contained in:
1 parent
a400091940
commit
48ce9374e4
49 files changed
+777
-878
No files matched your search
@@ -67,8 +67,8 @@ through alembic with a tested upgrade path.
|
||||
**Local-first.** Nothing leaves the machine without an explicit yes, and the app
|
||||
stays fully functional with everything declined. No third-party endpoints for
|
||||
bug reporting or crash dumps. No PAT/token-based GitHub posting from the app.
|
||||
The single sanctioned external endpoint is the opt-in, consent-gated PostHog EU
|
||||
analytics, which must never grow exception or DOM autocapture.
|
||||
The single sanctioned external endpoint is the opt-in, consent-gated Supermetry
|
||||
analytics (`config/analytics.json`), which must never grow exception or DOM autocapture.
|
||||
|
||||
**Keep main green.** A merge must never break CI. Dependency, lockfile, and
|
||||
config changes must be validated against *every* consumer — `frontend/` is a bun
|
||||
|
||||
@@ -602,7 +602,7 @@ test-only PR. Docker Hub overview edits still publish through the small
|
||||
reason, optional note and typed text, app version and model; no audio,
|
||||
account or device identifier (`mobile/contract/SPEC.md` → Reporting
|
||||
generated content; required by Google Play's AI-generated content policy).
|
||||
- PostHog analytics only after a yes at the first-run consent prompt, asked before
|
||||
- Supermetry analytics only after a yes at the first-run consent prompt, asked before
|
||||
runtime setup on a fresh install so setup stage and failure code can be counted
|
||||
(`backend/core/analytics.py`, allowlisted content-free metadata).
|
||||
- The GitHub star count (no credentials or referrer, refreshed every 20
|
||||
|
||||
@@ -143,8 +143,6 @@ jobs:
|
||||
VOICESTUDIO_OMNIVOICE_TTS_PLATFORM: ${{ matrix.gguf_platform }}
|
||||
VOICESTUDIO_UPDATE_CHANNEL: electron-${{ needs.validate.outputs.channel }}-${{ matrix.platform }}-${{ matrix.arch }}
|
||||
CSC_IDENTITY_AUTO_DISCOVERY: 'false'
|
||||
VITE_POSTHOG_KEY: ${{ secrets.POSTHOG_PROJECT_TOKEN }}
|
||||
VITE_POSTHOG_HOST: ${{ vars.POSTHOG_HOST }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
|
||||
@@ -45,8 +45,6 @@ jobs:
|
||||
env:
|
||||
VOICESTUDIO_RUST_TARGET: ${{ matrix.target }}
|
||||
VOICESTUDIO_UPDATE_CHANNEL: electron-stable-darwin-${{ matrix.arch }}
|
||||
VITE_POSTHOG_KEY: ${{ secrets.POSTHOG_PROJECT_TOKEN }}
|
||||
VITE_POSTHOG_HOST: ${{ vars.POSTHOG_HOST }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
|
||||
@@ -84,8 +84,6 @@ jobs:
|
||||
VOICESTUDIO_RUST_TARGET: ${{ matrix.target }}
|
||||
VOICESTUDIO_UPDATE_CHANNEL: electron-microsoft-store-stable-win32-${{ matrix.arch }}
|
||||
CSC_IDENTITY_AUTO_DISCOVERY: "false"
|
||||
VITE_POSTHOG_KEY: ${{ secrets.POSTHOG_PROJECT_TOKEN }}
|
||||
VITE_POSTHOG_HOST: ${{ vars.POSTHOG_HOST }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
|
||||
+6
-12
@@ -1,16 +1,12 @@
|
||||
# Gitleaks config — extends the default ruleset.
|
||||
#
|
||||
# Every entry below is an exact, anchored non-secret value. PostHog's
|
||||
# publishable project token is public by design (owner decision 2026-07-20,
|
||||
# #1193). Per PostHog's docs the `phc_` project
|
||||
# token is a write-only client key with "no access to your private data" —
|
||||
# it ships in every release binary and every official PostHog SDK snippet.
|
||||
# It is NOT a credential. Personal keys (`phx_`) remain fully banned.
|
||||
# `tests/test_no_committed_analytics_token.py` separately pins the literal to
|
||||
# exactly two canonical files and requires both to carry the same value.
|
||||
# Every entry below is an exact, anchored non-secret value. The analytics
|
||||
# destination is a public Supermetry site id (config/analytics.json), not a
|
||||
# credential. Dashboard/API keys (`pnl_`) and PostHog keys stay banned
|
||||
# (tests/test_no_committed_analytics_token.py).
|
||||
#
|
||||
# Rotating the token? The old value stays in git history, so the weekly
|
||||
# full-history scan flags it. Add those findings' fingerprints to
|
||||
# Retired PostHog project tokens stay in git history, so the weekly
|
||||
# full-history scan flags them. Add those findings' fingerprints to
|
||||
# .gitleaksignore rather than keeping the retired value here.
|
||||
|
||||
[extend]
|
||||
@@ -19,8 +15,6 @@ useDefault = true
|
||||
[allowlist]
|
||||
description = "Exact public/test literals misclassified as generic API keys"
|
||||
regexes = [
|
||||
# Public PostHog project token; personal `phx_` keys remain banned.
|
||||
'''^phc_kJK9nFqtwFmB4CYWS4bMDTY7z9P4KCRyiRT7CzJTXm9f$''',
|
||||
# Reviewed immutable Hugging Face commit for the Higgs tokenizer.
|
||||
'''^528e871c2a26c4f0f7773b9754e2e1acae20899d$''',
|
||||
# Deliberately synthetic fixtures that exercise HF-token redaction/storage.
|
||||
|
||||
@@ -44,7 +44,7 @@ Everything else (new engines, fancy features) is downstream of "the thing instal
|
||||
- **Cross-platform parity**: Every fix must work on macOS (Apple Silicon; Intel Macs are limited to the app UI with a remote backend, as README.md and `docs/install/macos.md` document), Windows (x64), and Linux (AppImage + deb). No platform-only regressions; the cross-platform bug bash (PR #51) is the baseline.
|
||||
- **Default features must work on every platform (strict rule, 2026-05-20):** A feature that ships in default mode — out-of-the-box, no user customization, no opt-in toggle — must behave identically on macOS, Windows, and Linux. Platform-specific *implementation code* is allowed for OS APIs / shells / packaging, but the user-visible *default behavior* cannot diverge. Platform-only features (e.g., a macOS-only global shortcut, a Windows-only path picker) must go behind explicit user opt-in: Settings toggle, env var, or CLI flag. When a default doesn't work on a platform, that's a P0 bug — either fix it on the missing platform or move it behind opt-in. No third option. **This rule governs BEHAVIOUR, not PERFORMANCE** (clarified 2026-07-30, council): hardware acceleration is expected to vary by host — CUDA, MPS, DirectML, Triton availability and `torch.compile` are all host-dependent by design, and reading the rule to forbid that would forbid GPU support itself. An optimization that is skipped where it cannot work (missing Triton, an arch the wheel lacks, a path its toolchain cannot link) is NOT a parity violation; a *feature* the user can see and use on one OS but not another is.
|
||||
- **Backward-compatible project data**: Existing `omnivoice_data/` (user voices, projects, settings) must keep working without manual migration. Any DB schema change goes through alembic with a tested upgrade path.
|
||||
- **Local-first guarantee preserved**: nothing leaves the machine without the user's **explicit yes**, and the app must remain fully functional with everything declined. Auto bug reporting is opt-in and submits only to GitHub Issues (prefilled-URL, from the user's own browser). Product analytics (owner-sanctioned 2026-07-16; US project migration 2026-09-26) is opt-in PostHog US with a **first-run consent prompt** — asked before runtime setup on a fresh install, two equal-weight Yes/No buttons, never default-on, skipping = off; consent-gated, allowlisted content-free metadata only (`backend/core/analytics.py`); every build — installer, Docker, and source alike (owner reversal 2026-07-20, #1193) — carries the in-repo publishable write-only token and shows the same consent ask, with env/baked token overriding it. No required cloud calls, accounts, or API keys. Sanctioned calls (owner-set 2026-10-02; full list in `.github/CONTRIBUTING.md` → Quality gates): during first-run setup the user starts — the pinned ffmpeg download from GitHub `zackees/ffmpeg_bins` (`backend/services/media_tools.py`), the huggingface.co/hf-mirror.com reachability probe for restricted networks (`backend/services/endpoint_race.py`), the dependency install's download of the packages pinned in `uv.lock` from their locked URLs or the user's chosen/auto-selected regional mirror, including the parallel wheel prefetch (`electron/src/main/wheel-prefetch.ts`, owner-approved 2026-10-27), the Auto region's one-wheel files.pythonhosted.org vs mirrors.aliyun.com speed check (two small ranged requests, `electron/src/main/pypi-mirror.ts`), a user-clicked setup connection check (256 KiB from the affected pinned package URL, 15-second limit, no uploads), and Hugging Face model downloads; opening the community gallery (jsDelivr manifest, `backend/api/routers/community.py`) or enabling the voice-preview gallery (GitHub Releases, `backend/services/gallery.py`); packaged update checks against GitHub Releases (`electron/src/main/updater.ts`); yt-dlp updates from PyPI when the user clicks update; opt-in Windows ROCm setup the user selects (owner-approved 2026-10-26, hash-pinned in `scripts/windows-rocm-recipe.json`): AMD's `repo.radeon.com` SDK/PyTorch wheels and the OpenNMT/CTranslate2 GitHub release archive; optional engine installs and repairs the user clicks (owner-approved 2026-11-07, `backend/services/sidecar_install.py`): the engine's GitHub source (a shallow branch clone, then the reviewed commit or its source archive, plus pinned GitHub archives of helper sources such as CosyVoice's Matcha-TTS, PyWorld and World), a uv-managed Python from `astral-sh/python-build-standalone` (or the regional mirror) when its version is missing, its Python packages from PyPI or the user's chosen mirror, the host's PyTorch build from `download.pytorch.org` (CUDA or CPU; on Linux AMD, engines with ROCm support use the ROCm index for their Torch version, replaced by `OMNIVOICE_TORCH_INDEX`; uv may also resolve other packages from that index), and its Hugging Face weights where the install fetches them (others download weights on first use, as Hugging Face model downloads); `OMNIVOICE_TORCH_INDEX` replaces it), and its Hugging Face weights; phone content reports to `appapi.voicestudio.sh/v1/content-reports`, only when the user taps Send on a result's Report sheet (`mobile/contract/SPEC.md`); and, only after the user turns account features on (first-run setup or Settings → Account, off by default), VoiceStudio Cloud sign-in and account calls from Electron main (`electron/src/main/account/`), plus settings sync from the backend (`backend/services/cloud_sync/`) once cloud sync is also on, all stopped at once when switched off. Narrow owner-approved exception (2026-09-28): the GitHub Star badge may fetch the public repository star count when shown and refresh every 20 minutes while visible, without credentials or a referrer. It sends no project, recording, or account data, retains the last count on failure, and never blocks offline use.
|
||||
- **Local-first guarantee preserved**: nothing leaves the machine without the user's **explicit yes**, and the app must remain fully functional with everything declined. Auto bug reporting is opt-in and submits only to GitHub Issues (prefilled-URL, from the user's own browser). Product analytics (owner-sanctioned 2026-07-16; US project migration 2026-09-26) is opt-in Supermetry (`https://app.supermetry.com`, public site id in `config/analytics.json`; replaced PostHog, owner decision 2026-11-08) with a **first-run consent prompt** — asked before runtime setup on a fresh install, two equal-weight Yes/No buttons, never default-on, skipping = off; consent-gated, allowlisted content-free metadata only (`backend/core/analytics.py`); every build — installer, Docker, and source alike (owner reversal 2026-07-20, #1193) — uses the public site id in `config/analytics.json` and shows the same consent ask, with `SUPERMETRY_SITE_ID` overriding it. No required cloud calls, accounts, or API keys. Sanctioned calls (owner-set 2026-10-02; full list in `.github/CONTRIBUTING.md` → Quality gates): during first-run setup the user starts — the pinned ffmpeg download from GitHub `zackees/ffmpeg_bins` (`backend/services/media_tools.py`), the huggingface.co/hf-mirror.com reachability probe for restricted networks (`backend/services/endpoint_race.py`), the dependency install's download of the packages pinned in `uv.lock` from their locked URLs or the user's chosen/auto-selected regional mirror, including the parallel wheel prefetch (`electron/src/main/wheel-prefetch.ts`, owner-approved 2026-10-27), the Auto region's one-wheel files.pythonhosted.org vs mirrors.aliyun.com speed check (two small ranged requests, `electron/src/main/pypi-mirror.ts`), a user-clicked setup connection check (256 KiB from the affected pinned package URL, 15-second limit, no uploads), and Hugging Face model downloads; opening the community gallery (jsDelivr manifest, `backend/api/routers/community.py`) or enabling the voice-preview gallery (GitHub Releases, `backend/services/gallery.py`); packaged update checks against GitHub Releases (`electron/src/main/updater.ts`); yt-dlp updates from PyPI when the user clicks update; opt-in Windows ROCm setup the user selects (owner-approved 2026-10-26, hash-pinned in `scripts/windows-rocm-recipe.json`): AMD's `repo.radeon.com` SDK/PyTorch wheels and the OpenNMT/CTranslate2 GitHub release archive; optional engine installs and repairs the user clicks (owner-approved 2026-11-07, `backend/services/sidecar_install.py`): the engine's GitHub source (a shallow branch clone, then the reviewed commit or its source archive, plus pinned GitHub archives of helper sources such as CosyVoice's Matcha-TTS, PyWorld and World), a uv-managed Python from `astral-sh/python-build-standalone` (or the regional mirror) when its version is missing, its Python packages from PyPI or the user's chosen mirror, the host's PyTorch build from `download.pytorch.org` (CUDA or CPU; on Linux AMD, engines with ROCm support use the ROCm index for their Torch version, replaced by `OMNIVOICE_TORCH_INDEX`; uv may also resolve other packages from that index), and its Hugging Face weights where the install fetches them (others download weights on first use, as Hugging Face model downloads); `OMNIVOICE_TORCH_INDEX` replaces it), and its Hugging Face weights; phone content reports to `appapi.voicestudio.sh/v1/content-reports`, only when the user taps Send on a result's Report sheet (`mobile/contract/SPEC.md`); and, only after the user turns account features on (first-run setup or Settings → Account, off by default), VoiceStudio Cloud sign-in and account calls from Electron main (`electron/src/main/account/`), plus settings sync from the backend (`backend/services/cloud_sync/`) once cloud sync is also on, all stopped at once when switched off. Narrow owner-approved exception (2026-09-28): the GitHub Star badge may fetch the public repository star count when shown and refresh every 20 minutes while visible, without credentials or a referrer. It sends no project, recording, or account data, retains the last count on failure, and never blocks offline use.
|
||||
- **Beta release cadence (no RC, no ceremony — strict rule, 2026-05-20):** the current release line (0.5.x today) has **no release candidates, no 48h soak, no formal release ceremony**. Every fix goes continuous-to-main; the owner tags a patch from main whenever the current state is worth cutting. No `-rc` tags. No phased release. The one sanctioned prerelease is the opt-in **Beta channel** (owner-approved 2026-10-22): `vX.Y.Z-beta.N` tags cut from `main`, published as GitHub prereleases that never become `latest`, with their own `electron-beta-*` update feed and `:beta` Docker tag (see `docs/RELEASING.md` → Beta channel). It adds no soak, ceremony or side branch. No deferrals to a future minor or major version — every open issue and every open community PR gets absorbed into the current line or explicitly declined. Users follow `main` for previews; users wanting stable stay on the latest tagged release.
|
||||
<!-- GSD:project-end -->
|
||||
|
||||
@@ -53,7 +53,7 @@ Everything else (new engines, fancy features) is downstream of "the thing instal
|
||||
|
||||
The May-2026 stack research that used to live here served five capabilities that have all since shipped (HF-token Settings panel, prefilled-URL bug reporting, uv mirror fallback for restricted networks, the Supertonic-3 engine, in-repo Markdown docs). Follow the patterns in the code itself; the durable *don'ts* that research established:
|
||||
|
||||
- **No third-party endpoints for bug reporting or crash dumps** (`sentry-tauri` was evaluated and rejected) — bug reporting stays opt-in via prefilled GitHub-issue URLs, submitted from the user's own browser. The one sanctioned third-party endpoint is the opt-in PostHog US product analytics and error tracking (owner-set 2026-07-16; migrated 2026-09-26; sanitized renderer errors approved 2026-09-26), which is consent-gated behind the first-run prompt and ships allowlisted content-free metadata only. Raw exception, DOM, and session autocapture stay disabled; manually captured renderer exceptions must replace messages and scrub stack paths before transmission. Its publishable write-only project token is committed in-repo (owner reversal 2026-07-20, #1193 — source builds get the same consent-gated analytics as installers; env/baked token overrides), allowed by `tests/test_no_committed_analytics_token.py` in exactly `backend/core/analytics.py` + `electron/src/shared/utils/analytics.ts`.
|
||||
- **No third-party endpoints for bug reporting or crash dumps** (`sentry-tauri` was evaluated and rejected) — bug reporting stays opt-in via prefilled GitHub-issue URLs, submitted from the user's own browser. The one sanctioned third-party endpoint is the opt-in Supermetry product analytics (owner-set 2026-07-16; moved from PostHog 2026-11-08), which is consent-gated behind the first-run prompt and ships allowlisted content-free metadata only. Raw exception, DOM, and session autocapture stay disabled; renderer failures are reduced to a coarse class and stage, never a message or stack. The interface sends events only through the local backend (`/api/settings/analytics/event`), which owns the destination. The public site id is committed in `config/analytics.json` (source builds get the same consent-gated analytics as installers; `SUPERMETRY_SITE_ID` overrides it); no dashboard or API key is ever committed (`tests/test_no_committed_analytics_token.py`).
|
||||
- **No PAT/token-based GitHub posting from the app** — the user submits from their own browser.
|
||||
- **Don't recommend `setx` for env vars on Windows** (silent truncation, no current-shell propagation) — use the in-app Settings panel or PowerShell `[Environment]::SetEnvironmentVariable`.
|
||||
- **Don't adopt Material for MkDocs** for any future docs site (maintenance mode since Nov 2025) — Astro Starlight is the precedent if docs ever outgrow the repo.
|
||||
|
||||
@@ -410,6 +410,22 @@ async def transcribe_audio(
|
||||
"transcription_time_s": elapsed,
|
||||
"engine": engine_id,
|
||||
}
|
||||
try:
|
||||
# Which speech-to-text engine people use. Metadata only; the
|
||||
# allowlist drops anything that is not an engine key.
|
||||
from core.analytics import capture as _capture_analytics
|
||||
|
||||
_capture_analytics("transcription_completed", {
|
||||
"feature": "transcription",
|
||||
"action": "transcribe",
|
||||
"outcome": "complete",
|
||||
"engine_id": str(engine_id or ""),
|
||||
"language": str(detected_lang or "auto")[:16],
|
||||
"duration_seconds": round(duration, 2),
|
||||
"gen_time_seconds": elapsed,
|
||||
})
|
||||
except Exception: # noqa: BLE001 — analytics may never break a transcription
|
||||
logger.warning("analytics: transcription_completed capture failed", exc_info=True)
|
||||
if speakers:
|
||||
response["speakers"] = speakers
|
||||
if diarization_error:
|
||||
|
||||
@@ -1654,6 +1654,7 @@ async def _finalize_generation(
|
||||
audio_tensor, sample_rate, *, text, history_mode, ref_audio_path,
|
||||
language, instruct, resolved_profile_id, used_seed, start_time,
|
||||
already_marked=False, design_recipe=None, wav_bits=16, include_wav_bytes=False,
|
||||
engine_id=None,
|
||||
):
|
||||
"""Shared tail of a successful generation: watermark → save WAV →
|
||||
history row (self-healing) → retention prune → event emit.
|
||||
@@ -1781,6 +1782,10 @@ async def _finalize_generation(
|
||||
|
||||
_ph("speech_generated", {
|
||||
"mode": history_mode,
|
||||
"feature": "clone" if ref_audio_path else "design",
|
||||
"action": "generate",
|
||||
"outcome": "complete",
|
||||
**({"engine_id": engine_id} if engine_id else {}),
|
||||
"language": language or "auto",
|
||||
"duration_seconds": audio_dur,
|
||||
"gen_time_seconds": gen_time,
|
||||
@@ -2623,7 +2628,7 @@ async def generate_speech(
|
||||
ref_audio_path=ref_audio_path, language=language,
|
||||
instruct=instruct, resolved_profile_id=resolved_profile_id,
|
||||
used_seed=used_seed, start_time=start_time, wav_bits=int(wav_bits),
|
||||
design_recipe=stored_design_recipe,
|
||||
design_recipe=stored_design_recipe, engine_id=engine_id,
|
||||
)
|
||||
# #1330: before `done`, say what the take is missing. Its own
|
||||
# frame rather than a `done` field so a consumer that only
|
||||
@@ -2780,7 +2785,7 @@ async def generate_speech(
|
||||
ref_audio_path=ref_audio_path, language=language, instruct=instruct,
|
||||
resolved_profile_id=resolved_profile_id, used_seed=used_seed,
|
||||
start_time=start_time, already_marked=False, wav_bits=int(wav_bits), include_wav_bytes=True,
|
||||
design_recipe=stored_design_recipe,
|
||||
design_recipe=stored_design_recipe, engine_id=engine_id,
|
||||
)
|
||||
audio_id = _meta["id"]
|
||||
audio_filename = _meta["filename"]
|
||||
|
||||
@@ -1592,6 +1592,21 @@ def get_analytics():
|
||||
}
|
||||
|
||||
|
||||
class _UiEventBody(BaseModel):
|
||||
event: str = Field(..., max_length=64)
|
||||
props: dict = Field(default_factory=dict)
|
||||
screen: str | None = Field(default=None, max_length=96)
|
||||
|
||||
|
||||
@router.post("/analytics/event")
|
||||
def post_analytics_event(body: _UiEventBody):
|
||||
"""An event the interface reports. A no-op unless the user opted in; only
|
||||
allowlisted, content-free properties are forwarded."""
|
||||
from core import analytics
|
||||
|
||||
return {"sent": analytics.capture_from_ui(body.event, body.props, body.screen)}
|
||||
|
||||
|
||||
@router.put("/analytics")
|
||||
def set_analytics(body: _AnalyticsBody):
|
||||
from core import analytics
|
||||
|
||||
@@ -1658,7 +1658,7 @@ async def tailscale_disable():
|
||||
# stores nothing new, and transmits nothing anywhere: the only consumer is the
|
||||
# user's own UI over loopback. Read-only, content-free (counts and totals,
|
||||
# never the text of a take). Product analytics for the PROJECT is a separate,
|
||||
# consent-gated path (core/analytics.py: opt-in PostHog behind the first-run
|
||||
# consent-gated path (core/analytics.py: opt-in Supermetry behind the first-run
|
||||
# prompt, allowlisted content-free metadata only) — this endpoint stays local
|
||||
# regardless of that consent.
|
||||
@router.get("/stats/usage")
|
||||
|
||||
+130
-81
@@ -4,15 +4,15 @@ VoiceStudio is local-first, so analytics here is held to a higher bar than the
|
||||
usual SDK drop-in. Three rules, each enforced in code below and pinned by tests:
|
||||
|
||||
1. **Off unless the user says yes.** Two independent gates must BOTH be true:
|
||||
a configured destination token (the in-repo publishable default, overridden
|
||||
by ``POSTHOG_PROJECT_TOKEN`` when set — see ``_PUBLIC_PROJECT_TOKEN``) *and*
|
||||
a configured Supermetry site (``config/analytics.json``, overridden by
|
||||
``SUPERMETRY_SITE_ID`` when set) *and*
|
||||
the user's explicit ``analytics_enabled`` preference, which defaults to
|
||||
**False**. A default install transmits nothing, so the product's promise
|
||||
holds out of the box. ``OMNIVOICE_ANALYTICS_DISABLED=1`` is a hard kill
|
||||
switch that outranks both.
|
||||
|
||||
2. **No exception autocapture, ever.** The obvious SDK default
|
||||
(``enable_exception_autocapture=True``) ships raw tracebacks — which carry
|
||||
(autocapturing exceptions) ships raw tracebacks — which carry
|
||||
absolute paths (``/Users/<name>/…``), and in this codebase can carry Hugging
|
||||
Face tokens and model paths straight out of exception messages. That would
|
||||
bypass ``core.failure.sanitize()``, the redaction this project already runs on
|
||||
@@ -31,37 +31,62 @@ tell "same install" from "different install".
|
||||
from __future__ import annotations
|
||||
|
||||
import atexit
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
from core.analytics_transport import SupermetryTransport, user_agent, valid_url
|
||||
|
||||
logger = logging.getLogger("omnivoice.analytics")
|
||||
|
||||
_client = None
|
||||
_client_key: Optional[str] = None # the (token, host) the live client was built for
|
||||
_client_key: Optional[str] = None # the destination the live client was built for
|
||||
|
||||
_KILL_SWITCH = "OMNIVOICE_ANALYTICS_DISABLED"
|
||||
_OFF_VALUES = {"1", "true", "yes", "on"}
|
||||
|
||||
#: In-repo default analytics destination (owner-sanctioned reversal, #1193):
|
||||
#: source builds get the SAME consent-gated analytics as installers. This is a
|
||||
#: PostHog *publishable* client key — write-only event ingestion, no data
|
||||
#: access; PostHog's own FAQ says these are designed to ship in client code —
|
||||
#: NOT a secret. It only names a destination: not one event leaves the machine
|
||||
#: without the user's explicit opt-in (see `enabled()`).
|
||||
#: A `POSTHOG_PROJECT_TOKEN` env var (release builds bake one in via the
|
||||
#: desktop shell; developers can point at their own project) always wins.
|
||||
#: Committed-token guard: tests/test_no_committed_analytics_token.py allows a
|
||||
#: `phc_` literal in exactly this file and electron/src/shared/utils/analytics.ts.
|
||||
_PUBLIC_PROJECT_TOKEN = "phc_kJK9nFqtwFmB4CYWS4bMDTY7z9P4KCRyiRT7CzJTXm9f" # gitleaks:allow — publishable write-only key (#1193)
|
||||
_DEFAULT_HOST = "https://us.i.posthog.com"
|
||||
_CONFIG_PATH = Path(__file__).resolve().parents[2] / "config" / "analytics.json"
|
||||
_client_lock = threading.RLock()
|
||||
_INSTALL_PROFILE_RE = re.compile(r"install_[a-f0-9]{32}")
|
||||
|
||||
|
||||
def _destination() -> dict:
|
||||
"""The public Supermetry destination (``config/analytics.json``). It only
|
||||
names a site: nothing is sent without the user's explicit opt-in.
|
||||
``SUPERMETRY_SITE_ID`` overrides it (a developer's own site, or empty to
|
||||
switch delivery off)."""
|
||||
try:
|
||||
data = json.loads(_CONFIG_PATH.read_text(encoding="utf-8"))
|
||||
if not isinstance(data, dict):
|
||||
return {}
|
||||
site = os.environ.get("SUPERMETRY_SITE_ID")
|
||||
result = {
|
||||
"site": (data.get("site", "") if site is None else site).strip(),
|
||||
"host": os.environ.get("SUPERMETRY_HOST", data.get("host", "https://app.supermetry.com")).strip().rstrip("/"),
|
||||
"appUrl": str(data.get("appUrl", "")).strip().rstrip("/"),
|
||||
}
|
||||
if (not valid_url(result["host"], origin=True) or not valid_url(result["appUrl"])
|
||||
or not re.fullmatch(r"[a-z0-9]{6,32}", result["site"])):
|
||||
return {}
|
||||
return result
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
#: The ONLY property keys that may leave this machine. Anything else is dropped.
|
||||
#: Deliberately conservative: no free text, no paths, no names, no ids of user
|
||||
#: content. Add here only after asking "could this ever hold something the user
|
||||
#: typed, recorded, or named?" — if yes, it doesn't belong.
|
||||
_ALLOWED_PROPS: frozenset[str] = frozenset({
|
||||
"feature",
|
||||
"action",
|
||||
"outcome",
|
||||
"engine_id", # which TTS/ASR engine (our identifier, not the user's)
|
||||
"language", # e.g. "en" / "auto"
|
||||
"mode", # clone | design
|
||||
@@ -92,6 +117,9 @@ _ALLOWED_PROPS: frozenset[str] = frozenset({
|
||||
#: guard so a stray free-text value can't ride in on an allowlisted key.
|
||||
_MAX_STR_LEN = 64
|
||||
|
||||
#: The shape of an engine key (``omnivoice``, ``cosyvoice-3``). Anything else is dropped.
|
||||
_ENGINE_ID_RE = re.compile(r"[a-z0-9][a-z0-9_.\-]{0,39}")
|
||||
|
||||
|
||||
def _kill_switched() -> bool:
|
||||
return (os.environ.get(_KILL_SWITCH, "") or "").strip().lower() in _OFF_VALUES
|
||||
@@ -146,23 +174,10 @@ def user_prompted() -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _resolved_token() -> str:
|
||||
"""The destination token: env (baked builds / developer override) wins,
|
||||
the committed publishable default (#1193) is the fallback. Empty only when
|
||||
both are blank — a destination-less build can never run analytics."""
|
||||
return (os.environ.get("POSTHOG_PROJECT_TOKEN", "") or "").strip() or _PUBLIC_PROJECT_TOKEN
|
||||
|
||||
|
||||
def _resolved_host() -> str:
|
||||
return (os.environ.get("POSTHOG_HOST") or _DEFAULT_HOST).strip()
|
||||
|
||||
|
||||
def token_configured() -> bool:
|
||||
"""Whether this build has an analytics destination at all. Since #1193 the
|
||||
in-repo default means source builds have one too — so they get the same
|
||||
first-run consent ask as installers. False only when both the env var and
|
||||
the committed default are blank; consent stays the real gate regardless."""
|
||||
return bool(_resolved_token())
|
||||
"""Whether this build has an analytics destination at all (name kept for
|
||||
existing callers). Consent stays the real gate regardless."""
|
||||
return bool(_destination())
|
||||
|
||||
|
||||
def enabled() -> bool:
|
||||
@@ -171,49 +186,40 @@ def enabled() -> bool:
|
||||
|
||||
|
||||
def _get_client():
|
||||
"""Lazily build the client, but only while `enabled()`. Rebuilt if the token
|
||||
or host changes; torn down the moment consent is withdrawn."""
|
||||
"""Lazily build the transport, but only while `enabled()`. Rebuilt if the
|
||||
destination changes; torn down the moment consent is withdrawn."""
|
||||
global _client, _client_key
|
||||
|
||||
if not enabled():
|
||||
if _client is not None:
|
||||
shutdown()
|
||||
return None
|
||||
|
||||
token = _resolved_token()
|
||||
host = _resolved_host()
|
||||
key = f"{token}@{host}"
|
||||
if _client is not None and _client_key == key:
|
||||
with _client_lock:
|
||||
if not enabled():
|
||||
if _client is not None:
|
||||
shutdown()
|
||||
return None
|
||||
destination = _destination()
|
||||
key = json.dumps(destination, sort_keys=True)
|
||||
if _client is not None and _client_key == key:
|
||||
return _client
|
||||
try:
|
||||
_client = SupermetryTransport(destination, enabled)
|
||||
_client_key = key
|
||||
atexit.register(shutdown)
|
||||
logger.info("Analytics enabled by user opt-in (host=%s).", destination["host"])
|
||||
except Exception as e: # noqa: BLE001 — analytics must never break the app
|
||||
logger.warning("Analytics client unavailable: %s", e)
|
||||
_client, _client_key = None, None
|
||||
return _client
|
||||
|
||||
try:
|
||||
from posthog import Posthog
|
||||
|
||||
_client = Posthog(
|
||||
token,
|
||||
host=host,
|
||||
# RULE 2. Tracebacks carry home paths and can carry HF tokens; they
|
||||
# would bypass core.failure.sanitize() entirely. Never turn this on.
|
||||
enable_exception_autocapture=False,
|
||||
)
|
||||
_client_key = key
|
||||
atexit.register(shutdown)
|
||||
logger.info("Analytics enabled by user opt-in (host=%s).", host)
|
||||
except Exception as e: # noqa: BLE001 — analytics must never break the app
|
||||
logger.warning("Analytics client unavailable: %s", e)
|
||||
_client, _client_key = None, None
|
||||
return _client
|
||||
|
||||
|
||||
def shutdown() -> None:
|
||||
"""Flush and drop the client. Safe to call repeatedly."""
|
||||
global _client, _client_key
|
||||
if _client is not None:
|
||||
try:
|
||||
_client.shutdown()
|
||||
except Exception: # noqa: BLE001
|
||||
logger.debug("analytics shutdown error (non-fatal)", exc_info=True)
|
||||
_client, _client_key = None, None
|
||||
with _client_lock:
|
||||
if _client is not None:
|
||||
try:
|
||||
_client.shutdown()
|
||||
except Exception: # noqa: BLE001
|
||||
logger.debug("analytics shutdown error (non-fatal)", exc_info=True)
|
||||
_client, _client_key = None, None
|
||||
|
||||
|
||||
def installation_id() -> str:
|
||||
@@ -231,6 +237,11 @@ def installation_id() -> str:
|
||||
return str(iid)
|
||||
|
||||
|
||||
def profile_id() -> str:
|
||||
"""The opaque Supermetry profile: ``install_`` + the random installation id."""
|
||||
return "install_" + installation_id().replace("-", "")
|
||||
|
||||
|
||||
def sanitize_properties(properties: Optional[dict]) -> dict:
|
||||
"""RULE 3. Drop every key not on the allowlist, and refuse long strings.
|
||||
|
||||
@@ -242,24 +253,61 @@ def sanitize_properties(properties: Optional[dict]) -> dict:
|
||||
continue
|
||||
if isinstance(v, str) and len(v) > _MAX_STR_LEN:
|
||||
continue
|
||||
if isinstance(v, (str, int, float, bool)) or v is None:
|
||||
if k == "engine_id" and not (isinstance(v, str) and _ENGINE_ID_RE.fullmatch(v)):
|
||||
continue # our engine keys only: never a path, a file name or typed text
|
||||
if isinstance(v, float) and not math.isfinite(v):
|
||||
continue
|
||||
if isinstance(v, (str, int, float, bool)):
|
||||
out[k] = v
|
||||
return out
|
||||
|
||||
|
||||
def capture(event: str, properties: Optional[dict] = None) -> None:
|
||||
def _identify() -> None:
|
||||
"""Tell Supermetry once per app version which kind of install this is."""
|
||||
from core import prefs
|
||||
|
||||
if prefs.get("analytics_identified") == _app_version():
|
||||
return
|
||||
client = _client
|
||||
if client is not None and client.capture(
|
||||
"identify", {}, profile_id=profile_id(),
|
||||
traits={"platform": _platform()[:256], "app_version": _app_version()[:256], "profile_kind": "installation"},
|
||||
):
|
||||
prefs.set_("analytics_identified", _app_version())
|
||||
|
||||
|
||||
def capture(event: str, properties: Optional[dict] = None, path: str = "/backend") -> bool:
|
||||
"""Record one product event. A no-op unless the user opted in. Never raises."""
|
||||
try:
|
||||
client = _get_client()
|
||||
if client is None:
|
||||
return
|
||||
client.capture(
|
||||
event,
|
||||
distinct_id=installation_id(),
|
||||
properties=sanitize_properties(properties),
|
||||
)
|
||||
return False
|
||||
_identify()
|
||||
return client.capture(event, sanitize_properties(properties), profile_id=profile_id(), path=path)
|
||||
except Exception as e: # noqa: BLE001 — analytics may never break a feature
|
||||
logger.debug("analytics capture failed (%s): %s", event, e)
|
||||
return False
|
||||
|
||||
|
||||
#: Screens the UI may report. Fixed routes only: dynamic ids never appear here.
|
||||
_SAFE_SCREEN = re.compile(
|
||||
r"view:(?:home|clone|personas|stories|dub|batch|gallery|transcriptions|design|audiobook|projects|tools|calls|integrations|pro|other"
|
||||
r"|settings/(?:appearance|general|models|logs|media|pronunciation|network|sharing|credentials|performance|usage|privacy|permissions|storage|support|updates|openapi|diagnostics|other))"
|
||||
)
|
||||
_EVENT_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_:-]{0,63}")
|
||||
|
||||
|
||||
def capture_from_ui(event: str, properties: Optional[dict] = None, screen: Optional[str] = None) -> bool:
|
||||
"""Events the interface reports. Same opt-in gate and allowlist as the
|
||||
backend's own; a screen view becomes a ``pageview`` on a fixed path."""
|
||||
if event == "pageview":
|
||||
if not isinstance(screen, str) or not _SAFE_SCREEN.fullmatch(screen):
|
||||
return False
|
||||
path = "/" + screen[len("view:"):]
|
||||
return capture("pageview", {**sanitize_properties(properties), "source": "electron"}, path=path)
|
||||
if not isinstance(event, str) or not _EVENT_NAME.fullmatch(event) or event in {"identify", "pageview"}:
|
||||
return False
|
||||
return capture(event, properties)
|
||||
|
||||
|
||||
# ── Lifecycle events (owner-sanctioned 2026-07-16) ──────────────────────────
|
||||
@@ -357,7 +405,8 @@ def _maybe_send_installed() -> bool:
|
||||
return False
|
||||
if prefs.get(_INSTALL_MARKER):
|
||||
return False
|
||||
capture("app_installed", _common_props())
|
||||
if not capture("app_installed", _common_props()):
|
||||
return False
|
||||
prefs.set_(_INSTALL_MARKER, True)
|
||||
return True
|
||||
|
||||
@@ -445,8 +494,7 @@ def sync_uninstall_ping_info() -> None:
|
||||
Present ⇔ analytics is enabled (token AND consent AND not kill-switched).
|
||||
The uninstall scripts read it (plus the consent pref itself, belt and
|
||||
braces) to send one best-effort `app_uninstalled` ping before deleting the
|
||||
data. The token is PostHog's publishable write-only client key — the same
|
||||
one baked into every release binary — so this file grants nothing new.
|
||||
data. The site id is public (config/analytics.json), so this file grants nothing new.
|
||||
Never raises."""
|
||||
import json
|
||||
|
||||
@@ -461,9 +509,10 @@ def sync_uninstall_ping_info() -> None:
|
||||
pass
|
||||
return
|
||||
payload = {
|
||||
"token": _resolved_token(),
|
||||
"host": _resolved_host(),
|
||||
"distinct_id": installation_id(),
|
||||
**_destination(),
|
||||
"user_agent": user_agent(),
|
||||
"profile_id": profile_id(),
|
||||
"policy": "opt-in",
|
||||
"app_version": _app_version(),
|
||||
"platform": _platform(),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
"""Bounded Supermetry delivery for opted-in opaque profiles; no user content."""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.client
|
||||
import json
|
||||
import platform
|
||||
import queue
|
||||
import re
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from typing import Callable
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
|
||||
def valid_url(value: str, *, origin: bool = False) -> bool:
|
||||
try:
|
||||
parsed = urlsplit(value)
|
||||
return bool(
|
||||
parsed.scheme in {"http", "https"} and parsed.hostname
|
||||
and not parsed.username and not parsed.password
|
||||
and not parsed.query and not parsed.fragment
|
||||
and (not origin or parsed.path in {"", "/"})
|
||||
and parsed.port != 0
|
||||
and not any(ord(c) < 33 for c in value)
|
||||
)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def user_agent() -> str:
|
||||
os_name = platform.system().lower()
|
||||
device = {"darwin": "Macintosh; Intel Mac OS X 10_15_7", "windows": "Windows NT 10.0; Win64; x64"}.get(os_name, "X11; Linux x86_64")
|
||||
return f"Mozilla/5.0 ({device}) AppleWebKit/537.36 (KHTML, like Gecko) VoiceStudio/1.0 Chrome/130.0.0.0 Safari/537.36"
|
||||
|
||||
|
||||
class _CancellationMixin:
|
||||
"""Check cancellation both before reconnecting and before writing bytes."""
|
||||
def __init__(self, *args, cancelled: threading.Event, **kwargs):
|
||||
self._cancelled = cancelled
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def _check_cancelled(self) -> None:
|
||||
if self._cancelled.is_set():
|
||||
self.close()
|
||||
raise OSError("analytics delivery cancelled")
|
||||
|
||||
def connect(self) -> None:
|
||||
self._check_cancelled()
|
||||
super().connect()
|
||||
# Withdrawal may have happened while DNS/TCP/TLS was in progress.
|
||||
self._check_cancelled()
|
||||
|
||||
def send(self, data) -> None:
|
||||
self._check_cancelled()
|
||||
super().send(data)
|
||||
|
||||
|
||||
class _HTTPConnection(_CancellationMixin, http.client.HTTPConnection):
|
||||
pass
|
||||
|
||||
|
||||
class _HTTPSConnection(_CancellationMixin, http.client.HTTPSConnection):
|
||||
pass
|
||||
|
||||
|
||||
class SupermetryTransport:
|
||||
"""One daemon worker, at most 64 pending events, three attempts per event.
|
||||
|
||||
Shutdown discards work and closes the active socket. Requests already sent
|
||||
cannot be recalled, but no queued event or retry survives withdrawal.
|
||||
"""
|
||||
def __init__(self, destination: dict, should_send: Callable[[], bool]):
|
||||
self.destination = destination
|
||||
self.should_send = should_send
|
||||
self._queue: queue.Queue = queue.Queue(maxsize=64)
|
||||
self._stopped = threading.Event()
|
||||
self._lock = threading.Lock()
|
||||
self._connection = None
|
||||
self._thread = threading.Thread(target=self._run, name="supermetry", daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def capture(self, event: str, properties: dict, profile_id: str | None = None, traits: dict | None = None,
|
||||
path: str = "/backend") -> bool:
|
||||
if (not isinstance(event, str) or not event or len(event.encode()) > 300
|
||||
or self._stopped.is_set() or not self.should_send()):
|
||||
return False
|
||||
if not isinstance(path, str) or not re.fullmatch(r"/[a-z0-9_/-]{0,80}", path):
|
||||
return False
|
||||
payload = {
|
||||
"v": 1, "id": uuid.uuid4().hex, "ts": int(time.time() * 1000),
|
||||
"site": self.destination["site"], "name": event,
|
||||
"url": self.destination["appUrl"].rstrip("/") + path,
|
||||
"props": properties,
|
||||
}
|
||||
if profile_id is not None:
|
||||
if not isinstance(profile_id, str) or not re.fullmatch(r"(?:install_[a-f0-9]{32}|account_[a-f0-9]{64})", profile_id):
|
||||
return False
|
||||
payload["profile_id"] = profile_id
|
||||
if event == "identify" and profile_id is None:
|
||||
return False
|
||||
if traits is not None:
|
||||
if event != "identify" or not profile_id or not isinstance(traits, dict):
|
||||
return False
|
||||
payload["traits"] = {key: value for key, value in traits.items()
|
||||
if key in {"platform", "app_version", "profile_kind"}
|
||||
and isinstance(value, str) and len(value) <= 256}
|
||||
body = json.dumps(payload, allow_nan=False, separators=(",", ":")).encode()
|
||||
if len(body) > 8192:
|
||||
return False
|
||||
with self._lock:
|
||||
if self._stopped.is_set():
|
||||
return False
|
||||
try:
|
||||
self._queue.put_nowait(body)
|
||||
return True
|
||||
except queue.Full:
|
||||
return False
|
||||
|
||||
def _send(self, body: bytes) -> int:
|
||||
parsed = urlsplit(self.destination["host"])
|
||||
factory = _HTTPSConnection if parsed.scheme == "https" else _HTTPConnection
|
||||
connection = factory(parsed.hostname, parsed.port, timeout=2, cancelled=self._stopped)
|
||||
with self._lock:
|
||||
if self._stopped.is_set() or not self.should_send():
|
||||
return 0
|
||||
self._connection = connection
|
||||
try:
|
||||
origin = urlsplit(self.destination["appUrl"])
|
||||
connection.request("POST", "/api/public/v1/events", body, {
|
||||
"Content-Type": "application/json", "User-Agent": user_agent(),
|
||||
"Origin": f"{origin.scheme}://{origin.netloc}",
|
||||
})
|
||||
return connection.getresponse().status
|
||||
finally:
|
||||
connection.close()
|
||||
with self._lock:
|
||||
self._connection = None
|
||||
|
||||
def _run(self) -> None:
|
||||
while not self._stopped.is_set():
|
||||
try:
|
||||
body = self._queue.get(timeout=0.1)
|
||||
except queue.Empty:
|
||||
continue
|
||||
try:
|
||||
for attempt in range(3):
|
||||
if self._stopped.is_set() or not self.should_send():
|
||||
break
|
||||
try:
|
||||
status = self._send(body)
|
||||
if status != 429 and status < 500:
|
||||
break # Includes 4xx and redirects; never follow them.
|
||||
except Exception:
|
||||
pass # Telemetry must never interrupt a feature.
|
||||
if attempt == 2 or self._stopped.wait(0.5 * (2 ** attempt)):
|
||||
break
|
||||
finally:
|
||||
self._queue.task_done()
|
||||
|
||||
def shutdown(self) -> None:
|
||||
self._stopped.set()
|
||||
with self._lock:
|
||||
if self._connection is not None:
|
||||
self._connection.auto_open = 0
|
||||
active_socket = self._connection.sock
|
||||
if active_socket is not None:
|
||||
try:
|
||||
active_socket.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
self._connection.close()
|
||||
while True:
|
||||
try:
|
||||
self._queue.get_nowait()
|
||||
self._queue.task_done()
|
||||
except queue.Empty:
|
||||
break
|
||||
@@ -53,7 +53,6 @@
|
||||
"i18next": "^26.4.2",
|
||||
"i18next-browser-languagedetector": "^8.2.1",
|
||||
"lucide-react": "^1.46.0",
|
||||
"posthog-js": "^1.434.14",
|
||||
"proxy-agent": "6.5.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^19.3.0",
|
||||
@@ -405,21 +404,21 @@
|
||||
|
||||
"@oxfmt/binding-linux-arm-musleabihf": ["@oxfmt/binding-linux-arm-musleabihf@0.76.0", "", { "os": "linux", "cpu": "arm" }, "sha512-303gbamm7NDllTtkeaX+8F5Da+KcSBr64mqELQEFg9XgnjfLX3YBCHUcOfgIlVTSybesy43eoeKai8oGr0P6UA=="],
|
||||
|
||||
"@oxfmt/binding-linux-arm64-gnu": ["@oxfmt/binding-linux-arm64-gnu@0.76.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-j3UAXzCJoWX9bZLaICj6DfwkI/2fzja9RpiCIbIN+2CQAcKoY+5SH5pQUcECvn32mQm17NSPE9YqTAwYx1seZg=="],
|
||||
"@oxfmt/binding-linux-arm64-gnu": ["@oxfmt/binding-linux-arm64-gnu@0.76.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-j3UAXzCJoWX9bZLaICj6DfwkI/2fzja9RpiCIbIN+2CQAcKoY+5SH5pQUcECvn32mQm17NSPE9YqTAwYx1seZg=="],
|
||||
|
||||
"@oxfmt/binding-linux-arm64-musl": ["@oxfmt/binding-linux-arm64-musl@0.76.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-qFZqWVkEzuxWMtUkCtHxsnohXHnUMBQr/ZIxF0KmlCSt8de/bc1lbpVgpqjb3QxCADQHG/O1s3JcowcBF2sqdw=="],
|
||||
"@oxfmt/binding-linux-arm64-musl": ["@oxfmt/binding-linux-arm64-musl@0.76.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-qFZqWVkEzuxWMtUkCtHxsnohXHnUMBQr/ZIxF0KmlCSt8de/bc1lbpVgpqjb3QxCADQHG/O1s3JcowcBF2sqdw=="],
|
||||
|
||||
"@oxfmt/binding-linux-ppc64-gnu": ["@oxfmt/binding-linux-ppc64-gnu@0.76.0", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-ROiAid0UH2GN5lMMX2JTgKlOKx1rN+6a1WxIuBsU3j5A3MuB9U5XkREMW76XBbAImnH45mfOCFcSIwb+drcVYg=="],
|
||||
"@oxfmt/binding-linux-ppc64-gnu": ["@oxfmt/binding-linux-ppc64-gnu@0.76.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-ROiAid0UH2GN5lMMX2JTgKlOKx1rN+6a1WxIuBsU3j5A3MuB9U5XkREMW76XBbAImnH45mfOCFcSIwb+drcVYg=="],
|
||||
|
||||
"@oxfmt/binding-linux-riscv64-gnu": ["@oxfmt/binding-linux-riscv64-gnu@0.76.0", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-Oyd/9ObdM2RYkZ7yzF/GyvVdbNgJcRG8BFVwnAVo3ooqzaem4E2p5eTIGB09FecQD+Q5HQEANOTEnIZTO6rBAQ=="],
|
||||
"@oxfmt/binding-linux-riscv64-gnu": ["@oxfmt/binding-linux-riscv64-gnu@0.76.0", "", { "os": "linux", "cpu": "none" }, "sha512-Oyd/9ObdM2RYkZ7yzF/GyvVdbNgJcRG8BFVwnAVo3ooqzaem4E2p5eTIGB09FecQD+Q5HQEANOTEnIZTO6rBAQ=="],
|
||||
|
||||
"@oxfmt/binding-linux-riscv64-musl": ["@oxfmt/binding-linux-riscv64-musl@0.76.0", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-86DOpmPDR5UzHSOB8y5HlOpYAIBtMx+6L72IyousNx54q1Kz61aykB4ScovFYivZUak+7Ww6tPBUjarluzYKLw=="],
|
||||
"@oxfmt/binding-linux-riscv64-musl": ["@oxfmt/binding-linux-riscv64-musl@0.76.0", "", { "os": "linux", "cpu": "none" }, "sha512-86DOpmPDR5UzHSOB8y5HlOpYAIBtMx+6L72IyousNx54q1Kz61aykB4ScovFYivZUak+7Ww6tPBUjarluzYKLw=="],
|
||||
|
||||
"@oxfmt/binding-linux-s390x-gnu": ["@oxfmt/binding-linux-s390x-gnu@0.76.0", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-u6omjjFooKfnHLBI+3UtBVInAeuEhoM/RAIw/OiFop2QQgOan5zDfqPR6guMaylt68L60kV+by07Ibp87KDjrw=="],
|
||||
"@oxfmt/binding-linux-s390x-gnu": ["@oxfmt/binding-linux-s390x-gnu@0.76.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-u6omjjFooKfnHLBI+3UtBVInAeuEhoM/RAIw/OiFop2QQgOan5zDfqPR6guMaylt68L60kV+by07Ibp87KDjrw=="],
|
||||
|
||||
"@oxfmt/binding-linux-x64-gnu": ["@oxfmt/binding-linux-x64-gnu@0.76.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-L0/hW1MdMrgsvuLGp9YEQOYOGj5xPHa8wVRtybdd5av03PV4qSpAq3pyfC7sn7UCA8ynRhMRTAa9Kr9nV4LGZg=="],
|
||||
"@oxfmt/binding-linux-x64-gnu": ["@oxfmt/binding-linux-x64-gnu@0.76.0", "", { "os": "linux", "cpu": "x64" }, "sha512-L0/hW1MdMrgsvuLGp9YEQOYOGj5xPHa8wVRtybdd5av03PV4qSpAq3pyfC7sn7UCA8ynRhMRTAa9Kr9nV4LGZg=="],
|
||||
|
||||
"@oxfmt/binding-linux-x64-musl": ["@oxfmt/binding-linux-x64-musl@0.76.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-JNk/7HaPDJjy5kih3vq6b71Qif3tHx1ZFACGBzeHeNzyKaIpar4eFGya89GR398K2rwX0eEVmEq1npBPlEkkmg=="],
|
||||
"@oxfmt/binding-linux-x64-musl": ["@oxfmt/binding-linux-x64-musl@0.76.0", "", { "os": "linux", "cpu": "x64" }, "sha512-JNk/7HaPDJjy5kih3vq6b71Qif3tHx1ZFACGBzeHeNzyKaIpar4eFGya89GR398K2rwX0eEVmEq1npBPlEkkmg=="],
|
||||
|
||||
"@oxfmt/binding-openharmony-arm64": ["@oxfmt/binding-openharmony-arm64@0.76.0", "", { "os": "none", "cpu": "arm64" }, "sha512-MDLrOQPXDuPKvPUCvpP3hC6kO72dsYxfpYiR08Nf5DiM75M0d8+D26JwT4uHDf0bcflvlGHcd58Hn2HpxkHUUQ=="],
|
||||
|
||||
@@ -455,21 +454,21 @@
|
||||
|
||||
"@oxlint/binding-linux-arm-musleabihf": ["@oxlint/binding-linux-arm-musleabihf@1.91.0", "", { "os": "linux", "cpu": "arm" }, "sha512-jcNePVpca37lTbHmiPMnVbPAAW0rH9kAoDjsDv6vESEX9pzazIR1q5SyYuc1rQzdjHtc2VVCDN9jDh6tHcOHyA=="],
|
||||
|
||||
"@oxlint/binding-linux-arm64-gnu": ["@oxlint/binding-linux-arm64-gnu@1.91.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-TJi78UX6R+9qZ23ZKtzN6adfW83bjY0NXsCRMBRH6H7IizaMXmZbdRAtjedMkx77bT46YQH0csawsY9lwha8MA=="],
|
||||
"@oxlint/binding-linux-arm64-gnu": ["@oxlint/binding-linux-arm64-gnu@1.91.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-TJi78UX6R+9qZ23ZKtzN6adfW83bjY0NXsCRMBRH6H7IizaMXmZbdRAtjedMkx77bT46YQH0csawsY9lwha8MA=="],
|
||||
|
||||
"@oxlint/binding-linux-arm64-musl": ["@oxlint/binding-linux-arm64-musl@1.91.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-OowlLroUTzKq5OBvbu6iegch8SJ2DivXFCukzPWURwvcJhMj7/P0CUGH5qrDlxT1Kh48dcxqYqrvE8qK6xTLKQ=="],
|
||||
"@oxlint/binding-linux-arm64-musl": ["@oxlint/binding-linux-arm64-musl@1.91.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-OowlLroUTzKq5OBvbu6iegch8SJ2DivXFCukzPWURwvcJhMj7/P0CUGH5qrDlxT1Kh48dcxqYqrvE8qK6xTLKQ=="],
|
||||
|
||||
"@oxlint/binding-linux-ppc64-gnu": ["@oxlint/binding-linux-ppc64-gnu@1.91.0", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-QF/5Ge8yGpWg5s4awMNHfVKh1WOmk591Qg082i6CHenXYBa+W1E5RwWZXaKUOw4Ko7CCjqg3TfBc0AzhnqblYg=="],
|
||||
"@oxlint/binding-linux-ppc64-gnu": ["@oxlint/binding-linux-ppc64-gnu@1.91.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-QF/5Ge8yGpWg5s4awMNHfVKh1WOmk591Qg082i6CHenXYBa+W1E5RwWZXaKUOw4Ko7CCjqg3TfBc0AzhnqblYg=="],
|
||||
|
||||
"@oxlint/binding-linux-riscv64-gnu": ["@oxlint/binding-linux-riscv64-gnu@1.91.0", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-dXlsKlNhzJQX1nageGKnvWe1D7uTng249hQM80CG/YPZ8F/VZHbxVLhImgurdWBOmu86XOemValLjrW6QIOM/Q=="],
|
||||
"@oxlint/binding-linux-riscv64-gnu": ["@oxlint/binding-linux-riscv64-gnu@1.91.0", "", { "os": "linux", "cpu": "none" }, "sha512-dXlsKlNhzJQX1nageGKnvWe1D7uTng249hQM80CG/YPZ8F/VZHbxVLhImgurdWBOmu86XOemValLjrW6QIOM/Q=="],
|
||||
|
||||
"@oxlint/binding-linux-riscv64-musl": ["@oxlint/binding-linux-riscv64-musl@1.91.0", "", { "os": "linux", "cpu": "none", "libc": "musl" }, "sha512-tznkj5VrWNRUfymkaLcJetgMLbP9suL5ob/m7j0Fdbnm5u3Li/Ezo/YcBixiuwdL1sg0oGpyTe86It0J6T+Lxg=="],
|
||||
"@oxlint/binding-linux-riscv64-musl": ["@oxlint/binding-linux-riscv64-musl@1.91.0", "", { "os": "linux", "cpu": "none" }, "sha512-tznkj5VrWNRUfymkaLcJetgMLbP9suL5ob/m7j0Fdbnm5u3Li/Ezo/YcBixiuwdL1sg0oGpyTe86It0J6T+Lxg=="],
|
||||
|
||||
"@oxlint/binding-linux-s390x-gnu": ["@oxlint/binding-linux-s390x-gnu@1.91.0", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-sNvfLiUYQkVsLNUgIW24AEYTHSd2zZ1vAxXssPdjuQHTtCpRvQihYri6d5z5FY7w/QrcnB5+g9E+/sqmZq8tfA=="],
|
||||
"@oxlint/binding-linux-s390x-gnu": ["@oxlint/binding-linux-s390x-gnu@1.91.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-sNvfLiUYQkVsLNUgIW24AEYTHSd2zZ1vAxXssPdjuQHTtCpRvQihYri6d5z5FY7w/QrcnB5+g9E+/sqmZq8tfA=="],
|
||||
|
||||
"@oxlint/binding-linux-x64-gnu": ["@oxlint/binding-linux-x64-gnu@1.91.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-eA25ETvimhUZ89y5BcunNY7yv7qwG2I7V7dFQAU+mIEqZ57gBCXdIERl0yXOEt43zjsw0yK2gRKTc+twF706wQ=="],
|
||||
"@oxlint/binding-linux-x64-gnu": ["@oxlint/binding-linux-x64-gnu@1.91.0", "", { "os": "linux", "cpu": "x64" }, "sha512-eA25ETvimhUZ89y5BcunNY7yv7qwG2I7V7dFQAU+mIEqZ57gBCXdIERl0yXOEt43zjsw0yK2gRKTc+twF706wQ=="],
|
||||
|
||||
"@oxlint/binding-linux-x64-musl": ["@oxlint/binding-linux-x64-musl@1.91.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-4hZ4Z9K+OkcTpAHDoUTMg/8MModbM0aocrl9KnGzp9h5iKqjrXraEUZorYoVCT7xoK93CAHXgTndxRBrOjH/fA=="],
|
||||
"@oxlint/binding-linux-x64-musl": ["@oxlint/binding-linux-x64-musl@1.91.0", "", { "os": "linux", "cpu": "x64" }, "sha512-4hZ4Z9K+OkcTpAHDoUTMg/8MModbM0aocrl9KnGzp9h5iKqjrXraEUZorYoVCT7xoK93CAHXgTndxRBrOjH/fA=="],
|
||||
|
||||
"@oxlint/binding-openharmony-arm64": ["@oxlint/binding-openharmony-arm64@1.91.0", "", { "os": "none", "cpu": "arm64" }, "sha512-gtqn4b0kLpGe46Qh7NHiR86wZpd+TLaesO106s7V3RG33r63VB94LW5qPKEDJX64osh3xfjnPFn1M0484bC7wQ=="],
|
||||
|
||||
@@ -493,12 +492,6 @@
|
||||
|
||||
"@polka/url": ["@polka/url@1.0.0-next.29", "", {}, "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww=="],
|
||||
|
||||
"@posthog/browser-common": ["@posthog/browser-common@0.9.0", "", { "dependencies": { "@posthog/core": "^1.54.2", "@posthog/types": "^1.412.1" } }, "sha512-EWoVzs1vVY7ihpn8yOjj3jyjriHUEEMVSBNL/TW3hk09fTriWRe76vJXrRg0G0yjTYxHmtlSkNn4mOV24ZEzzA=="],
|
||||
|
||||
"@posthog/core": ["@posthog/core@1.55.2", "", { "dependencies": { "@posthog/types": "^1.412.4" } }, "sha512-2mYxGbDmTLUs096VbcZqSWo0lrI48/BrX65r54NynxxFq409BOx9w73HxOAtOKZ1vblkdV6/GxQTe7KDcIQidg=="],
|
||||
|
||||
"@posthog/types": ["@posthog/types@1.412.4", "", {}, "sha512-Q7lV9O9TbLngjOYw1ucm3bS3tn48xb1B4ZQdDy8gv7yfKe99hCTeWYG4xZ36nJM80VxpTF9TriiJt5hngDOkBg=="],
|
||||
|
||||
"@quansync/fs": ["@quansync/fs@1.0.0", "", { "dependencies": { "quansync": "^1.0.0" } }, "sha512-4TJ3DFtlf1L5LDMaM6CanJ/0lckGNtJcMjQ1NAV6zDmA0tEHKZtxNKin8EgPaVX1YzljbxckyT2tJrpQKAtngQ=="],
|
||||
|
||||
"@radix-ui/number": ["@radix-ui/number@1.1.3", "", {}, "sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA=="],
|
||||
@@ -815,8 +808,6 @@
|
||||
|
||||
"@types/responselike": ["@types/responselike@1.0.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw=="],
|
||||
|
||||
"@types/trusted-types": ["@types/trusted-types@2.0.7", "", {}, "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="],
|
||||
|
||||
"@types/unist": ["@types/unist@3.0.3", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="],
|
||||
|
||||
"@types/validate-npm-package-name": ["@types/validate-npm-package-name@4.0.2", "", {}, "sha512-lrpDziQipxCEeK5kWxvljWYhUvOiB2A9izZd9B2AFarYAkqZshb4lPbRs7zKEic6eGtH8V/2qJW+dPp9OtF6bw=="],
|
||||
@@ -893,13 +884,13 @@
|
||||
|
||||
"@voidzero-dev/vite-plus-darwin-x64": ["@voidzero-dev/vite-plus-darwin-x64@1.5.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-mjYYlKvgRsjVVDY4ZCE/Yamhwv2bpYgsj0MmlMlGwM5LqqYpEs5XVBlzYAugRH+0IVt86HOmu7pemO6oc50kkw=="],
|
||||
|
||||
"@voidzero-dev/vite-plus-linux-arm64-gnu": ["@voidzero-dev/vite-plus-linux-arm64-gnu@1.5.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-mRQKf0BWvj4zd2Zz4nVFQ1nztqCcVXIQFIsOytPw+xNPEEbvlMyhQSe8kDYA2YZSB286UnMDGAWRyL8+0uz7+g=="],
|
||||
"@voidzero-dev/vite-plus-linux-arm64-gnu": ["@voidzero-dev/vite-plus-linux-arm64-gnu@1.5.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-mRQKf0BWvj4zd2Zz4nVFQ1nztqCcVXIQFIsOytPw+xNPEEbvlMyhQSe8kDYA2YZSB286UnMDGAWRyL8+0uz7+g=="],
|
||||
|
||||
"@voidzero-dev/vite-plus-linux-arm64-musl": ["@voidzero-dev/vite-plus-linux-arm64-musl@1.5.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-IgNFjoI9XVAnk00VhBC1XM4UtZRkrKpdDUHusU1JRAJaF+4F8A9qth1eCGMnq6Qj9yDfavSxm2TbG9c8VDcjqw=="],
|
||||
"@voidzero-dev/vite-plus-linux-arm64-musl": ["@voidzero-dev/vite-plus-linux-arm64-musl@1.5.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-IgNFjoI9XVAnk00VhBC1XM4UtZRkrKpdDUHusU1JRAJaF+4F8A9qth1eCGMnq6Qj9yDfavSxm2TbG9c8VDcjqw=="],
|
||||
|
||||
"@voidzero-dev/vite-plus-linux-x64-gnu": ["@voidzero-dev/vite-plus-linux-x64-gnu@1.5.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-FJatSHDidGv342hzynLHCZITC3S72c1Zd5At5KDgwDk/0Z2YSqTaWYiosHIyOHr9sGBPhxObLjp0gvfvWlfmqQ=="],
|
||||
"@voidzero-dev/vite-plus-linux-x64-gnu": ["@voidzero-dev/vite-plus-linux-x64-gnu@1.5.0", "", { "os": "linux", "cpu": "x64" }, "sha512-FJatSHDidGv342hzynLHCZITC3S72c1Zd5At5KDgwDk/0Z2YSqTaWYiosHIyOHr9sGBPhxObLjp0gvfvWlfmqQ=="],
|
||||
|
||||
"@voidzero-dev/vite-plus-linux-x64-musl": ["@voidzero-dev/vite-plus-linux-x64-musl@1.5.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-962Ry3YMekkAmSeohSPAiycpUIy3oJujahXTqGsbhxrJ6KLYQgALRguUutV5N9uX7acthAPDqdwycGKzoDFgSA=="],
|
||||
"@voidzero-dev/vite-plus-linux-x64-musl": ["@voidzero-dev/vite-plus-linux-x64-musl@1.5.0", "", { "os": "linux", "cpu": "x64" }, "sha512-962Ry3YMekkAmSeohSPAiycpUIy3oJujahXTqGsbhxrJ6KLYQgALRguUutV5N9uX7acthAPDqdwycGKzoDFgSA=="],
|
||||
|
||||
"@voidzero-dev/vite-plus-win32-arm64-msvc": ["@voidzero-dev/vite-plus-win32-arm64-msvc@1.5.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-g9peiAMaoEZgF/9X9HRNI+Ek/Wa0ubjJ91CAONE2RxPwwWn7bzes8y+DhKHhl0kOvUxnFxQeyfeXTvjIkgmF9A=="],
|
||||
|
||||
@@ -945,17 +936,17 @@
|
||||
|
||||
"@yuku-core/binding-freebsd-x64": ["@yuku-core/binding-freebsd-x64@0.19.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-xrZjF6XOEwyLOiDIfrwDdRCS6ghxcJeirNC1KivQhVcUwlRonaU79S3/Uiyx3lBylPnT8qKJ3/aMT+H52nGTJQ=="],
|
||||
|
||||
"@yuku-core/binding-linux-arm-gnu": ["@yuku-core/binding-linux-arm-gnu@0.19.0", "", { "os": "linux", "cpu": "arm", "libc": "glibc" }, "sha512-0OyIH53C0I1CbADHn9FSdCfX5qbpeLwJhmOVhonFJNYheybOnkSJ50qGMfTJIb8y5zrwqvLs7FVBvz6Fk8maZg=="],
|
||||
"@yuku-core/binding-linux-arm-gnu": ["@yuku-core/binding-linux-arm-gnu@0.19.0", "", { "os": "linux", "cpu": "arm" }, "sha512-0OyIH53C0I1CbADHn9FSdCfX5qbpeLwJhmOVhonFJNYheybOnkSJ50qGMfTJIb8y5zrwqvLs7FVBvz6Fk8maZg=="],
|
||||
|
||||
"@yuku-core/binding-linux-arm-musl": ["@yuku-core/binding-linux-arm-musl@0.19.0", "", { "os": "linux", "cpu": "arm", "libc": "musl" }, "sha512-z/iPfkCOCSXE34VXNt0uP1ORSW+4mEa9b5CiJcWZeqZH08g49bFU/jRM2T04f+Wpw5mJ6HIzNBiojxeAbrHjeg=="],
|
||||
"@yuku-core/binding-linux-arm-musl": ["@yuku-core/binding-linux-arm-musl@0.19.0", "", { "os": "linux", "cpu": "arm" }, "sha512-z/iPfkCOCSXE34VXNt0uP1ORSW+4mEa9b5CiJcWZeqZH08g49bFU/jRM2T04f+Wpw5mJ6HIzNBiojxeAbrHjeg=="],
|
||||
|
||||
"@yuku-core/binding-linux-arm64-gnu": ["@yuku-core/binding-linux-arm64-gnu@0.19.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-jLNTi+gzaRwBJ+gwhCJ+rDb5dmx/8hEBx93UWd7hjMSqPTL1D1wvVSvXVAldV5kALvju7b0/m51EHEhs4+I1fA=="],
|
||||
"@yuku-core/binding-linux-arm64-gnu": ["@yuku-core/binding-linux-arm64-gnu@0.19.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-jLNTi+gzaRwBJ+gwhCJ+rDb5dmx/8hEBx93UWd7hjMSqPTL1D1wvVSvXVAldV5kALvju7b0/m51EHEhs4+I1fA=="],
|
||||
|
||||
"@yuku-core/binding-linux-arm64-musl": ["@yuku-core/binding-linux-arm64-musl@0.19.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-YwyPIdW/rN2Fmv0MTFWi47FaB3F9g+2b+sJISyAw83Yd60RWH4T3Nx6XkAHHVN+uKJNBAd6So7/BVihSiFYvuQ=="],
|
||||
"@yuku-core/binding-linux-arm64-musl": ["@yuku-core/binding-linux-arm64-musl@0.19.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-YwyPIdW/rN2Fmv0MTFWi47FaB3F9g+2b+sJISyAw83Yd60RWH4T3Nx6XkAHHVN+uKJNBAd6So7/BVihSiFYvuQ=="],
|
||||
|
||||
"@yuku-core/binding-linux-x64-gnu": ["@yuku-core/binding-linux-x64-gnu@0.19.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-/vskaAXVX3ESR43FiTdfiYS7z1b9uoQJwVQ/0RgUHgN2sWoAyCZs+aX4CgU7eKGIHTVfp9VFwv+c+2XchYiEtQ=="],
|
||||
"@yuku-core/binding-linux-x64-gnu": ["@yuku-core/binding-linux-x64-gnu@0.19.0", "", { "os": "linux", "cpu": "x64" }, "sha512-/vskaAXVX3ESR43FiTdfiYS7z1b9uoQJwVQ/0RgUHgN2sWoAyCZs+aX4CgU7eKGIHTVfp9VFwv+c+2XchYiEtQ=="],
|
||||
|
||||
"@yuku-core/binding-linux-x64-musl": ["@yuku-core/binding-linux-x64-musl@0.19.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-FuXL5igeSKib9Rye02TdH+D6SQezTyGxIATMu1Qsn/QywrzwpGl35OLpS2C1x5vpGLeVE2XgiLd5mVPFHmIglQ=="],
|
||||
"@yuku-core/binding-linux-x64-musl": ["@yuku-core/binding-linux-x64-musl@0.19.0", "", { "os": "linux", "cpu": "x64" }, "sha512-FuXL5igeSKib9Rye02TdH+D6SQezTyGxIATMu1Qsn/QywrzwpGl35OLpS2C1x5vpGLeVE2XgiLd5mVPFHmIglQ=="],
|
||||
|
||||
"@yuku-core/binding-win32-arm64": ["@yuku-core/binding-win32-arm64@0.19.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-YuJAe7zEKT1Xa7LuHlhGJpPnYQeVtvo0rZvNjJRqkH0hQGOw4C8QeP30Tg5VKGzZfo2x8CjhjEhKt4TmLwfmdg=="],
|
||||
|
||||
@@ -1135,8 +1126,6 @@
|
||||
|
||||
"cookie-signature": ["cookie-signature@1.2.2", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="],
|
||||
|
||||
"core-js": ["core-js@3.50.0", "", {}, "sha512-BRWgOLKkFeCgRudR6zrs8p9XJZcE14grzKMMssoYrk6krtuEZ7MTKPIY5RzOnqsEKIR9kst7wNzphttraT+Yqw=="],
|
||||
|
||||
"core-util-is": ["core-util-is@1.0.3", "", {}, "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="],
|
||||
|
||||
"cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="],
|
||||
@@ -1243,8 +1232,6 @@
|
||||
|
||||
"dom-accessibility-api": ["dom-accessibility-api@0.6.3", "", {}, "sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w=="],
|
||||
|
||||
"dompurify": ["dompurify@3.4.17", "", { "optionalDependencies": { "@types/trusted-types": "^2.0.7" } }, "sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w=="],
|
||||
|
||||
"dot-prop": ["dot-prop@6.0.1", "", { "dependencies": { "is-obj": "^2.0.0" } }, "sha512-tE7ztYzXHIeyvc7N+hR3oi7FIbf/NIjVP9hmAt3yMXzrQ072/fpjGLx2GxNxGxUl5V73MEqYzioOMoVhGMJ5cA=="],
|
||||
|
||||
"dotenv": ["dotenv@16.6.1", "", {}, "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow=="],
|
||||
@@ -1353,7 +1340,7 @@
|
||||
|
||||
"fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
|
||||
|
||||
"fflate": ["fflate@0.4.9", "", {}, "sha512-zdxgIEddhfsyCaWpJ2SdXEP8ZMrKJ6+5jl4OupODcywU0IhRk6gdXuVGcPICyfx2H97hVK7xmJtRLPjkxAX8Vw=="],
|
||||
"fflate": ["fflate@0.8.3", "", {}, "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA=="],
|
||||
|
||||
"figures": ["figures@6.1.0", "", { "dependencies": { "is-unicode-supported": "^2.0.0" } }, "sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg=="],
|
||||
|
||||
@@ -1927,14 +1914,10 @@
|
||||
|
||||
"postcss-selector-parser": ["postcss-selector-parser@7.1.6", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw=="],
|
||||
|
||||
"posthog-js": ["posthog-js@1.434.14", "", { "dependencies": { "@posthog/browser-common": "^0.9.0", "@posthog/core": "^1.55.2", "@posthog/types": "^1.412.4", "core-js": "^3.49.0", "dompurify": "^3.4.13", "fflate": "^0.4.8", "preact": "^10.29.3", "query-selector-shadow-dom": "^1.0.1", "web-vitals": "^6.2.1", "web-vitals-soft-navs": "npm:web-vitals@6.2.1" }, "peerDependencies": { "@types/react": ">=16.8.0", "react": ">=16.8.0" }, "optionalPeers": ["@types/react", "react"] }, "sha512-x1ilSlqpMIYVXq5oerLPRXx4P0sHfTuS43YtCuVkI7Myi5FSeU6lVDitoGZvfhgggc5SFEcKD300l7OGLTDBwQ=="],
|
||||
|
||||
"postject": ["postject@1.0.0-alpha.6", "", { "dependencies": { "commander": "^9.4.0" }, "bin": { "postject": "dist/cli.js" } }, "sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A=="],
|
||||
|
||||
"powershell-utils": ["powershell-utils@0.2.1", "", {}, "sha512-C+y9x90UElAddDZmV4qOx9W53B61PO7cIqWz2dQsWlwswuq4mr8NEwytdGKboYbQlGZ3awrkTeNvcZiZNHnQ8A=="],
|
||||
|
||||
"preact": ["preact@10.29.8", "", { "peerDependencies": { "preact-render-to-string": ">=5" }, "optionalPeers": ["preact-render-to-string"] }, "sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q=="],
|
||||
|
||||
"pretty-format": ["pretty-format@27.5.1", "", { "dependencies": { "ansi-regex": "^5.0.1", "ansi-styles": "^5.0.0", "react-is": "^17.0.1" } }, "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ=="],
|
||||
|
||||
"pretty-ms": ["pretty-ms@9.3.1", "", { "dependencies": { "parse-ms": "^4.0.0" } }, "sha512-HzMy3Geq23nVALD/M2LliU+F+M+gVNsvkQWWqeBZ8HDiCgzo6YPJ/Omrmtq24EFrIsk0a3EkQGEd7bDOo+IhGA=="],
|
||||
@@ -1973,8 +1956,6 @@
|
||||
|
||||
"quansync": ["quansync@1.0.0", "", {}, "sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA=="],
|
||||
|
||||
"query-selector-shadow-dom": ["query-selector-shadow-dom@1.0.1", "", {}, "sha512-lT5yCqEBgfoMYpf3F2xQRK7zEr1rhIIZuceDK6+xRkJQ4NMbHTwXqk4NkwDwQMNqXgG9r9fyHnzwNVs6zV5KRw=="],
|
||||
|
||||
"queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="],
|
||||
|
||||
"quick-lru": ["quick-lru@5.1.1", "", {}, "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA=="],
|
||||
@@ -2347,10 +2328,6 @@
|
||||
|
||||
"web-namespaces": ["web-namespaces@2.0.1", "", {}, "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ=="],
|
||||
|
||||
"web-vitals": ["web-vitals@6.2.1", "", {}, "sha512-rLcLXA2sx6+9dE88NHFubwTtGxpK4yYBLj6qHPdFoCaLr0cXGb4efOqtKLlm4loGA4OEKHIQKMKzZkKyOh5ctw=="],
|
||||
|
||||
"web-vitals-soft-navs": ["web-vitals@6.2.1", "", {}, "sha512-rLcLXA2sx6+9dE88NHFubwTtGxpK4yYBLj6qHPdFoCaLr0cXGb4efOqtKLlm4loGA4OEKHIQKMKzZkKyOh5ctw=="],
|
||||
|
||||
"web-worker": ["web-worker@1.5.0", "", {}, "sha512-RiMReJrTAiA+mBjGONMnjVDP2u3p9R1vkcGz6gDIrOMT3oGuYwX2WRMYI9ipkphSuE5XKEhydbhNEJh4NY9mlw=="],
|
||||
|
||||
"webcrypto-core": ["webcrypto-core@1.9.2", "", { "dependencies": { "@peculiar/asn1-schema": "^2.7.0", "@peculiar/json-schema": "^1.1.12", "@peculiar/utils": "^2.0.2", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-gsXecm82UQNlTBURJGuqOWy1Ww08S3kZUcr3aOJS02Pk0xLtkfeUAVC0u0xhgdonFme80edSJUIJyuvL/7250Q=="],
|
||||
@@ -2527,8 +2504,6 @@
|
||||
|
||||
"@vitest/snapshot/magic-string": ["magic-string@1.4.5", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0" } }, "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w=="],
|
||||
|
||||
"@vitest/ui/fflate": ["fflate@0.8.3", "", {}, "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA=="],
|
||||
|
||||
"@vue/compiler-core/entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
|
||||
|
||||
"@vue/compiler-core/estree-walker": ["estree-walker@2.0.2", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="],
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
Product analytics moved from PostHog to Supermetry, still only after a yes at the first-run prompt, and now also records which engine ran each generation and transcription. (#3901)
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"site": "oxxxnwyfwhx4",
|
||||
"host": "https://app.supermetry.com",
|
||||
"appUrl": "https://app.voicestudio.sh"
|
||||
}
|
||||
@@ -15,7 +15,7 @@ cloning, and cinematic video dubbing — fully local, with no cloud API keys or
|
||||

|
||||
|
||||
VoiceStudio processes media on your own hardware and automatically chooses CUDA,
|
||||
ROCm, or CPU. Data leaves the machine only after you explicitly agree. PostHog
|
||||
ROCm, or CPU. Data leaves the machine only after you explicitly agree. Supermetry
|
||||
analytics collect content-free metadata only when you accept the first-run
|
||||
consent question; declining or skipping keeps analytics disabled, and
|
||||
`-e OMNIVOICE_ANALYTICS_DISABLED=1` turns them off completely. This headless
|
||||
|
||||
+3
-4
@@ -62,10 +62,9 @@ Electron publication uses these GitHub Actions secrets:
|
||||
Play internal testing is not a release channel either.
|
||||
- The repository `GITHUB_TOKEN` for draft creation and asset uploads.
|
||||
- `DOCKERHUB_USERNAME` and `DOCKERHUB_TOKEN` for the Docker Hub mirror.
|
||||
- `POSTHOG_PROJECT_TOKEN` (secret) and `POSTHOG_HOST` (repository variable),
|
||||
baked into packaged builds as the analytics token and host. They override the
|
||||
in-repo publishable token; analytics still sends nothing without a yes at the
|
||||
first-run consent prompt.
|
||||
- No analytics secret is needed: the destination is the public Supermetry site
|
||||
id in `config/analytics.json`. Analytics still sends nothing without a yes at
|
||||
the first-run consent prompt.
|
||||
|
||||
The archived `TAURI_SIGNING_PRIVATE_KEY*` secrets are retained only so the final
|
||||
Tauri release can be audited. The Tauri release workflow has been removed; every
|
||||
|
||||
@@ -8,9 +8,9 @@
|
||||
|
||||
Settings > Privacy exposes the existing invisible-watermark setting, analytics consent and generation-history retention.
|
||||
|
||||
Watermark controls appear when the backend reports AudioSeal available and affect new audio through the existing marking path. No audio producer bypasses `mark_synthetic`. Analytics consent uses the existing backend opt-in endpoint and remains unchanged until the user explicitly switches it. After consent, the renderer records fixed screen labels and workflow action labels (clone, design, dubbing, transcription); the backend records lifecycle/error events. Privacy-safe manual pageviews use fixed app paths under `app.voicestudio.sh`, enabling aggregate Web Analytics without sending renderer URLs or dynamic route segments. Uncaught renderer errors also reach PostHog Error Tracking with their message replaced and credentials, home paths, extension frames, text, audio, filenames, and user-named content removed. Raw exception autocapture, DOM autocapture, automatic pageviews, and session recordings remain disabled. Unavailable features do not display inert toggles, and failed saves preserve confirmed state.
|
||||
Watermark controls appear when the backend reports AudioSeal available and affect new audio through the existing marking path. No audio producer bypasses `mark_synthetic`. Analytics consent uses the existing backend opt-in endpoint and remains unchanged until the user explicitly switches it. After consent, the renderer records fixed screen labels and workflow action labels (clone, design, dubbing, transcription); the backend records lifecycle/error events. Privacy-safe pageviews use fixed app paths under `app.voicestudio.sh`, giving aggregate screen counts without sending renderer URLs or dynamic route segments. The renderer never contacts the analytics service itself: it hands allowlisted events to the local backend, which forwards them only while consent is on. Uncaught renderer errors are reduced to a coarse class and stage; no message, stack, credential, home path, text, audio, filename, or user-named content is sent. Raw exception autocapture, DOM autocapture, automatic pageviews, and session recordings remain disabled. Unavailable features do not display inert toggles, and failed saves preserve confirmed state.
|
||||
|
||||
Electron release builds pass the publishable `POSTHOG_PROJECT_TOKEN` secret as `VITE_POSTHOG_KEY` and the `POSTHOG_HOST` repository variable as `VITE_POSTHOG_HOST`. The same US destination is baked into the renderer and managed backend on macOS, Windows, and Linux. Keep the token paired with `https://us.i.posthog.com`; a project URL or numeric project ID alone cannot ingest events. Local Electron builds can override the defaults with `VITE_POSTHOG_KEY` and `VITE_POSTHOG_HOST`.
|
||||
The analytics destination is the public Supermetry site id in `config/analytics.json` (host `https://app.supermetry.com`); every build uses it, and `SUPERMETRY_SITE_ID` / `SUPERMETRY_HOST` override it for developers. Nothing is baked in at build time.
|
||||
|
||||
Translation privacy classification is shared with Tauri. Unknown or unavailable backend data does not claim offline operation. The existing `libretranslate` identifier is an alias for the backend's local Argos branch, not an assumption about an external LibreTranslate service. The Translation link opens engine settings.
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ it in a normal browser. It is built from the same maintained renderer as the
|
||||
Electron desktop app; controls that require native desktop access are hidden.
|
||||
|
||||
Inference runs inside the container. Nothing is sent off the machine without
|
||||
your explicit yes: product analytics are opt-in (PostHog, content-free usage
|
||||
your explicit yes: product analytics are opt-in (Supermetry, content-free usage
|
||||
metadata only) behind the same first-run consent prompt as the desktop app,
|
||||
and declining or skipping it keeps them off. Set
|
||||
`-e OMNIVOICE_ANALYTICS_DISABLED=1` to switch analytics off entirely. Model
|
||||
|
||||
@@ -196,10 +196,9 @@ gh api --method PATCH repos/debpalash/VoiceStudio --input - <<'JSON'
|
||||
JSON
|
||||
```
|
||||
|
||||
The PostHog project token committed in `backend/core/analytics.py` and
|
||||
`electron/src/shared/utils/analytics.ts` is a publishable write-only token by
|
||||
design (see `tests/test_no_committed_analytics_token.py`). If an alert flags it,
|
||||
close the alert as "used in tests" or "false positive". Do not remove the token.
|
||||
The Supermetry site id in `config/analytics.json` is public by design and is not
|
||||
a credential (see `tests/test_no_committed_analytics_token.py`, which bans any
|
||||
dashboard or API key). If an alert flags it, close it as "false positive".
|
||||
|
||||
## Private vulnerability reporting
|
||||
|
||||
|
||||
@@ -202,6 +202,7 @@ export default {
|
||||
{ from: '../LICENSE', to: 'LICENSE' },
|
||||
{ from: '../LICENSE-NOTICE.md', to: 'LICENSE-NOTICE.md' },
|
||||
{ from: '../config/app.json', to: 'config/app.json' },
|
||||
{ from: '../config/analytics.json', to: 'config/analytics.json' },
|
||||
{ from: 'T3CODE-LICENSE.txt', to: 'electron/T3CODE-LICENSE.txt' },
|
||||
...(!isMacAppStore ? bundledUvResources : []),
|
||||
...bundledOmnivoiceTtsResources,
|
||||
|
||||
@@ -24,11 +24,6 @@ const define = {
|
||||
__BUILD_COMMIT__: JSON.stringify(buildCommit()),
|
||||
__DISTRIBUTION_TARGET__: JSON.stringify(DISTRIBUTION_TARGET),
|
||||
__WEB_DEPLOYMENT__: false,
|
||||
// Keep the renderer and its managed Python backend on one analytics project.
|
||||
__POSTHOG_PROJECT_TOKEN__: JSON.stringify(
|
||||
process.env.VITE_POSTHOG_KEY ?? process.env.POSTHOG_PROJECT_TOKEN ?? '',
|
||||
),
|
||||
__POSTHOG_HOST__: JSON.stringify(process.env.VITE_POSTHOG_HOST ?? process.env.POSTHOG_HOST ?? ''),
|
||||
};
|
||||
|
||||
// OMNIVOICE_UI_PORT is canonical (the backend reads it for its origin
|
||||
|
||||
@@ -75,7 +75,6 @@
|
||||
"i18next": "^26.4.2",
|
||||
"i18next-browser-languagedetector": "^8.2.1",
|
||||
"lucide-react": "^1.46.0",
|
||||
"posthog-js": "^1.434.14",
|
||||
"proxy-agent": "6.5.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^19.3.0",
|
||||
|
||||
@@ -234,14 +234,6 @@ it('passes a live nested-operation drain descriptor to POSIX managed backends',
|
||||
expect(windows.env.OMNIVOICE_DESKTOP_DRAIN_FD).toBeUndefined();
|
||||
});
|
||||
|
||||
it('passes the packaged analytics destination to its managed backend', () => {
|
||||
vi.stubGlobal('__POSTHOG_PROJECT_TOKEN__', 'publishable-test-key');
|
||||
vi.stubGlobal('__POSTHOG_HOST__', 'https://us.i.posthog.com');
|
||||
const { env } = managedBackendSpawnOptions(3900);
|
||||
expect(env.POSTHOG_PROJECT_TOKEN).toBe('publishable-test-key');
|
||||
expect(env.POSTHOG_HOST).toBe('https://us.i.posthog.com');
|
||||
});
|
||||
|
||||
it('recognizes only expected child-pipe close errors', () => {
|
||||
expect(isExpectedPipeClose(Object.assign(new Error('closed'), { code: 'EPIPE' }))).toBe(true);
|
||||
expect(isExpectedPipeClose(Object.assign(new Error('reset'), { code: 'ECONNRESET' }))).toBe(true);
|
||||
|
||||
@@ -664,13 +664,6 @@ function childEnv(
|
||||
}
|
||||
}
|
||||
}
|
||||
const packagedToken =
|
||||
typeof __POSTHOG_PROJECT_TOKEN__ === 'string' ? __POSTHOG_PROJECT_TOKEN__ : '';
|
||||
const packagedHost = typeof __POSTHOG_HOST__ === 'string' ? __POSTHOG_HOST__ : '';
|
||||
if (packagedToken && !env.POSTHOG_PROJECT_TOKEN) {
|
||||
env.POSTHOG_PROJECT_TOKEN = packagedToken;
|
||||
}
|
||||
if (packagedHost && !env.POSTHOG_HOST) env.POSTHOG_HOST = packagedHost;
|
||||
// The backend reports the same build commit as the app in bug reports.
|
||||
if (!env.OMNIVOICE_BUILD_COMMIT && __BUILD_COMMIT__ !== 'unknown') {
|
||||
env.OMNIVOICE_BUILD_COMMIT = __BUILD_COMMIT__;
|
||||
|
||||
Vendored
-2
@@ -2,8 +2,6 @@
|
||||
declare const __APP_VERSION__: string;
|
||||
declare const __BUILD_COMMIT__: string;
|
||||
declare const __DISTRIBUTION_TARGET__: string;
|
||||
declare const __POSTHOG_PROJECT_TOKEN__: string;
|
||||
declare const __POSTHOG_HOST__: string;
|
||||
|
||||
declare module '*.lock?raw' {
|
||||
const content: string;
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta
|
||||
http-equiv="Content-Security-Policy"
|
||||
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob: data:; frame-src https://forms.gle https://docs.google.com https://accounts.google.com; connect-src 'self' blob: ws: http://localhost:* http://127.0.0.1:* https://api.github.com https://eu.i.posthog.com https://eu-assets.i.posthog.com https://us.i.posthog.com https://us-assets.i.posthog.com; font-src 'self' data:; worker-src 'self' blob:"
|
||||
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob: data:; frame-src https://forms.gle https://docs.google.com https://accounts.google.com; connect-src 'self' blob: ws: http://localhost:* http://127.0.0.1:* https://api.github.com; font-src 'self' data:; worker-src 'self' blob:"
|
||||
/>
|
||||
<script src="/early-error-capture.js"></script>
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
|
||||
@@ -13,6 +13,7 @@ vi.mock('@shared/utils/analytics', () => ({
|
||||
capturePageview: vi.fn(),
|
||||
disableAnalytics: vi.fn(),
|
||||
enableAnalytics: vi.fn(async () => {}),
|
||||
setAnalyticsSender: vi.fn(),
|
||||
}));
|
||||
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
|
||||
import { AnalyticsConsent, AnalyticsRuntime, SetupAnalyticsConsent } from './analytics-consent';
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
capturePageview,
|
||||
disableAnalytics,
|
||||
enableAnalytics,
|
||||
setAnalyticsSender,
|
||||
} from '@shared/utils/analytics';
|
||||
import { routeBreadcrumb } from '@/lib/report-breadcrumb';
|
||||
import {
|
||||
@@ -23,6 +24,11 @@ import {
|
||||
SetupFunnel,
|
||||
} from '@/lib/setup-analytics';
|
||||
|
||||
// Events reach the destination through the local backend, which re-checks consent.
|
||||
setAnalyticsSender((body) =>
|
||||
apiJson('/api/settings/analytics/event', { method: 'POST', body: JSON.stringify(body) }),
|
||||
);
|
||||
|
||||
interface AnalyticsState {
|
||||
available: boolean;
|
||||
opted_in: boolean;
|
||||
|
||||
@@ -2,11 +2,7 @@ import { describe, expect, it } from 'vitest';
|
||||
import html from '../index.html?raw';
|
||||
|
||||
describe('renderer content security policy', () => {
|
||||
it('allows PostHog ingestion and its regional configuration endpoints', () => {
|
||||
expect(html).toContain('https://us.i.posthog.com');
|
||||
expect(html).toContain('https://us-assets.i.posthog.com');
|
||||
expect(html).toContain('https://eu.i.posthog.com');
|
||||
expect(html).toContain('https://eu-assets.i.posthog.com');
|
||||
expect(html).not.toContain('*.posthog.com');
|
||||
it('lets the interface reach no analytics host; the backend sends opted-in events', () => {
|
||||
expect(html).not.toMatch(/posthog|supermetry/i);
|
||||
});
|
||||
});
|
||||
@@ -35,8 +35,8 @@ export async function chooseAnalyticsConsent(enabled) {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ enabled }),
|
||||
});
|
||||
// Consent gates the FRONTEND SDK too: posthog-js is only initialised once
|
||||
// the user says yes, and torn down the moment they say no.
|
||||
// Consent gates the interface's reporting too: it starts only once the
|
||||
// user says yes and stops the moment they say no.
|
||||
if (enabled) await enableAnalytics();
|
||||
else disableAnalytics();
|
||||
return true;
|
||||
|
||||
@@ -50,9 +50,9 @@ export default function AnalyticsOptIn() {
|
||||
body: JSON.stringify({ enabled: next }),
|
||||
}).then((r) => r.json());
|
||||
setState(d);
|
||||
// Consent gates the FRONTEND SDK too: posthog-js is only initialised once
|
||||
// the user says yes, and torn down the moment they say no. It is never
|
||||
// started at app load — that would track people before they consented.
|
||||
// Consent gates the interface's reporting too: it starts only once the
|
||||
// user says yes and stops the moment they say no. It is never started at
|
||||
// app load — that would track people before they consented.
|
||||
if (next) await enableAnalytics();
|
||||
else disableAnalytics();
|
||||
toast.success(
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
import { expect, it, vi } from 'vitest';
|
||||
|
||||
it('cannot opt back in when SDK loading completes after consent was withdrawn', async () => {
|
||||
vi.resetModules();
|
||||
const sdk = {
|
||||
init: vi.fn(),
|
||||
opt_in_capturing: vi.fn(),
|
||||
opt_out_capturing: vi.fn(),
|
||||
reset: vi.fn(),
|
||||
captureException: vi.fn(),
|
||||
};
|
||||
let finish!: (value: { default: typeof sdk }) => void;
|
||||
const loading = new Promise<{ default: typeof sdk }>((resolve) => {
|
||||
finish = resolve;
|
||||
});
|
||||
const imported = vi.fn(() => loading);
|
||||
vi.doMock('posthog-js/dist/module.slim.no-external', imported);
|
||||
vi.doMock('posthog-js/dist/extension-bundles', () => ({ ErrorTrackingExtensions: {} }));
|
||||
const analytics = await import('../utils/analytics');
|
||||
const pending = analytics.enableAnalytics();
|
||||
await vi.waitFor(() => expect(imported).toHaveBeenCalled());
|
||||
analytics.disableAnalytics();
|
||||
finish({ default: sdk });
|
||||
await pending;
|
||||
expect(sdk.init).not.toHaveBeenCalled();
|
||||
expect(sdk.opt_in_capturing).not.toHaveBeenCalled();
|
||||
await analytics.enableAnalytics(); // A later explicit opt-in is still honored.
|
||||
expect(sdk.opt_in_capturing).toHaveBeenCalledOnce();
|
||||
vi.doUnmock('posthog-js/dist/module.slim.no-external');
|
||||
vi.doUnmock('posthog-js/dist/extension-bundles');
|
||||
});
|
||||
@@ -1,58 +1,18 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import {
|
||||
disableAnalytics,
|
||||
sanitizeException,
|
||||
sanitizeProps,
|
||||
capture,
|
||||
capturePageview,
|
||||
sanitizeOutgoingEvent,
|
||||
hardenedConfig,
|
||||
captureException,
|
||||
disableAnalytics,
|
||||
enableAnalytics,
|
||||
initAnalyticsFromConsent,
|
||||
sanitizeProps,
|
||||
setAnalyticsSender,
|
||||
} from '../utils/analytics';
|
||||
|
||||
// Hoisted by Vitest above every import either way; kept at top level so
|
||||
// the file reads in execution order.
|
||||
vi.mock('posthog-js/dist/module.slim.no-external', () => ({
|
||||
default: {
|
||||
init: vi.fn(),
|
||||
opt_in_capturing: vi.fn(),
|
||||
opt_out_capturing: vi.fn(),
|
||||
reset: vi.fn(),
|
||||
has_opted_out_capturing: () => false,
|
||||
capture: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// The usual posthog-js integration is `posthog.init(...)` at module load with
|
||||
// autocapture on. Both halves would be a disaster here:
|
||||
//
|
||||
// - init-at-load tracks every user BEFORE they consent, which makes the app's
|
||||
// own promise ("sends nothing out of the box") false;
|
||||
// - autocapture sends the TEXT CONTENT of DOM elements — in this app, the
|
||||
// script the user is about to synthesise, their voice names, their filenames.
|
||||
//
|
||||
// These tests pin both, plus the allowlist that stops a future caller leaking
|
||||
// content by adding a field.
|
||||
|
||||
describe('hardenedConfig — the settings that make the promises true', () => {
|
||||
it('disables autocapture, session recording and pageview capture', () => {
|
||||
const c = hardenedConfig();
|
||||
expect(c.autocapture).toBe(false); // would send DOM text
|
||||
expect(c.disable_session_recording).toBe(true); // would record the screen
|
||||
expect(c.capture_exceptions).toBe(false); // raw exception messages and paths
|
||||
expect(c.capture_pageview).toBe(false);
|
||||
expect(c.capture_pageleave).toBe(false);
|
||||
});
|
||||
|
||||
it('starts opted OUT, so init alone never captures anything', () => {
|
||||
expect(hardenedConfig().opt_out_capturing_by_default).toBe(true);
|
||||
});
|
||||
|
||||
it('masks text and attributes as defence in depth', () => {
|
||||
const c = hardenedConfig();
|
||||
expect(c.mask_all_text).toBe(true);
|
||||
expect(c.mask_all_element_attributes).toBe(true);
|
||||
});
|
||||
});
|
||||
// The interface never calls the analytics service itself: after consent it hands
|
||||
// allowlisted events to the local backend. These tests pin that nothing moves
|
||||
// before consent, that content cannot ride along, and that a withdrawal stops it.
|
||||
|
||||
describe('sanitizeProps — content cannot get out, even by accident', () => {
|
||||
it('drops anything not on the allowlist', () => {
|
||||
@@ -90,66 +50,6 @@ describe('sanitizeProps — content cannot get out, even by accident', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeException — error tracking keeps frames, not user data', () => {
|
||||
it('replaces the message and removes credentials, home paths and extension frames', () => {
|
||||
const failure = new TypeError(
|
||||
'Private script at /home/pal/secret with token sk-12345678901234567890',
|
||||
);
|
||||
failure.stack = [
|
||||
failure.message,
|
||||
' at render (/home/pal/github/VoiceStudio/electron/src/app.tsx:12:3)',
|
||||
' at extension (chrome-extension://private/content.js:2:1)',
|
||||
].join('\n');
|
||||
const clean = sanitizeException(failure);
|
||||
expect(clean.name).toBe('TypeError');
|
||||
expect(clean.message).toBe('VoiceStudio renderer error');
|
||||
expect(clean.stack).toContain('~/github/VoiceStudio/electron/src/app.tsx:12:3');
|
||||
expect(clean.stack).not.toContain('Private script');
|
||||
expect(clean.stack).not.toContain('/home/pal');
|
||||
expect(clean.stack).not.toContain('sk-');
|
||||
expect(clean.stack).not.toContain('chrome-extension');
|
||||
});
|
||||
});
|
||||
|
||||
describe('capturePageview — Web Analytics receives fixed app paths only', () => {
|
||||
it('is safe before analytics consent resolves and rejects dynamic screen labels', () => {
|
||||
expect(() => capturePageview('view:clone')).not.toThrow();
|
||||
expect(() => capturePageview('view:integrations/private-project')).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeOutgoingEvent — renderer URLs never leave', () => {
|
||||
it('removes SDK-added URL metadata from product events', () => {
|
||||
const clean = sanitizeOutgoingEvent({
|
||||
event: 'screen_viewed',
|
||||
properties: {
|
||||
stage: 'view:integrations',
|
||||
$current_url: 'http://localhost:3902/#/integrations/private-slug',
|
||||
$pathname: '/',
|
||||
$title: 'Private project',
|
||||
$referrer: 'https://private.example/',
|
||||
},
|
||||
});
|
||||
expect(clean?.properties).toEqual({ stage: 'view:integrations' });
|
||||
});
|
||||
|
||||
it('keeps only the synthetic app URL for manual pageviews', () => {
|
||||
const clean = sanitizeOutgoingEvent({
|
||||
event: '$pageview',
|
||||
properties: {
|
||||
$current_url: 'http://localhost:3902/#/clone/private-id',
|
||||
$pathname: '/clone',
|
||||
$title: 'Private voice',
|
||||
},
|
||||
});
|
||||
expect(clean?.properties).toEqual({
|
||||
$current_url: 'https://app.voicestudio.sh/clone',
|
||||
$host: 'app.voicestudio.sh',
|
||||
$pathname: '/clone',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('initAnalyticsFromConsent — silence is not consent', () => {
|
||||
it('does NOT start analytics when the user has not opted in', async () => {
|
||||
const started = await initAnalyticsFromConsent(async () => ({
|
||||
@@ -183,14 +83,47 @@ describe('initAnalyticsFromConsent — silence is not consent', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('drops multiline error messages while preserving genuine stack frames', () => {
|
||||
const error = new Error('Failed\nPrivate transcript\nCustomer address');
|
||||
error.stack =
|
||||
'Error: Failed\nPrivate transcript\nCustomer address\n at render (app://voicestudio/assets/index.js:3:4)';
|
||||
const safe = sanitizeException(error);
|
||||
expect(safe.stack).not.toContain('Private transcript');
|
||||
expect(safe.stack).not.toContain('Customer address');
|
||||
expect(safe.stack).toContain('index.js:3:4');
|
||||
|
||||
it('sends nothing until the user has opted in, then stops on withdrawal', async () => {
|
||||
const sent = vi.fn(async () => ({}));
|
||||
setAnalyticsSender(sent);
|
||||
disableAnalytics();
|
||||
capture('feature_used', { feature: 'clone' });
|
||||
capturePageview('view:home');
|
||||
expect(sent).not.toHaveBeenCalled();
|
||||
|
||||
await enableAnalytics();
|
||||
capture('feature_used', { feature: 'clone', text: 'private script' });
|
||||
capturePageview('view:home');
|
||||
expect(sent).toHaveBeenCalledWith({ event: 'feature_used', props: { feature: 'clone' } });
|
||||
expect(sent).toHaveBeenCalledWith({ event: 'pageview', props: {}, screen: 'view:home' });
|
||||
|
||||
sent.mockClear();
|
||||
disableAnalytics();
|
||||
capture('feature_used', { feature: 'clone' });
|
||||
expect(sent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reduces a renderer failure to a coarse class and stage', async () => {
|
||||
const sent = vi.fn(async () => ({}));
|
||||
setAnalyticsSender(sent);
|
||||
disableAnalytics();
|
||||
await enableAnalytics();
|
||||
const error = new Error('Private transcript in /Users/me/secret.wav');
|
||||
error.name = 'CustomerAddressError';
|
||||
captureException(error, 'renderer:uncaught');
|
||||
expect(sent).toHaveBeenCalledWith({
|
||||
event: 'renderer_error',
|
||||
props: { error_class: 'Error', stage: 'renderer:uncaught' },
|
||||
});
|
||||
expect(JSON.stringify(sent.mock.calls)).not.toContain('Private');
|
||||
disableAnalytics();
|
||||
});
|
||||
|
||||
it('accepts only engine keys as engine_id', () => {
|
||||
expect(sanitizeProps({ engine_id: 'My Cool Voice' })).toEqual({});
|
||||
expect(sanitizeProps({ engine_id: '/home/me/model.bin' })).toEqual({});
|
||||
expect(sanitizeProps({ engine_id: 'cosyvoice-3' })).toEqual({ engine_id: 'cosyvoice-3' });
|
||||
});
|
||||
|
||||
it('does not revive analytics when a stale consent request resolves after opt-out', async () => {
|
||||
|
||||
@@ -1,59 +1,30 @@
|
||||
/**
|
||||
* Frontend analytics (posthog-js) — consent-gated, autocapture OFF.
|
||||
* Frontend analytics: consent-gated, content-free, nothing autocaptured.
|
||||
*
|
||||
* The usual integration is one line at module load:
|
||||
* The interface never talks to the analytics service itself. After the user has
|
||||
* said yes, it hands a small allowlisted event to the local backend, which owns
|
||||
* the destination (config/analytics.json), the random installation profile and
|
||||
* the opt-in check, and forwards it. Before consent, or after it is withdrawn,
|
||||
* every call here is a no-op.
|
||||
*
|
||||
* posthog.init(TOKEN, { api_host, defaults: '2026-05-30' })
|
||||
*
|
||||
* That is wrong for this app, twice over, and the reasons are not theoretical:
|
||||
*
|
||||
* 1. **It would track everyone immediately, before consent.** VoiceStudio's whole
|
||||
* promise is that a default install sends nothing (Settings → Privacy is OFF
|
||||
* until you turn it on; see backend/core/analytics.py). Initialising at load
|
||||
* would make the app's own README a lie. So init happens ONLY after the user
|
||||
* has opted in, and never before.
|
||||
*
|
||||
* 2. **posthog-js autocaptures DOM interactions by default** — clicks, form
|
||||
* interactions, and the *text content* of the elements involved. In this app
|
||||
* the DOM holds the script the user is about to synthesise, their voice names,
|
||||
* and their file names. Autocapture would exfiltrate precisely the content we
|
||||
* promise never leaves the machine. It is explicitly disabled, along with
|
||||
* session recording (which would record the screen) and pageview capture.
|
||||
*
|
||||
* What we send instead is a small set of deliberate events with metadata-only
|
||||
* properties, filtered through the same allowlist the backend uses — so no
|
||||
* future caller can leak content by adding a field.
|
||||
*
|
||||
* The project token is a *publishable* key (PostHog's client tokens are designed
|
||||
* to ship in client code); it grants write-only event ingestion, not data access.
|
||||
* What is sent is a small set of deliberate events with metadata-only
|
||||
* properties, filtered through the same allowlist the backend uses, so no
|
||||
* future caller can leak the text of a take, a voice name or a file name by
|
||||
* adding a field. There is no DOM autocapture, no session recording and no
|
||||
* stack trace: a renderer failure is reduced to a coarse class and a stage.
|
||||
*/
|
||||
import { scrubText } from './scrub';
|
||||
|
||||
/**
|
||||
* In-repo default destination (owner-sanctioned reversal, #1193): source builds
|
||||
* get the SAME consent-gated analytics as installers. This is a PostHog
|
||||
* *publishable* client key — write-only event ingestion, no data access;
|
||||
* PostHog's own FAQ says these are designed to ship in client code — NOT a
|
||||
* secret. It only names a destination: nothing is ever sent without the user's
|
||||
* explicit opt-in (init happens only after consent, see enableAnalytics()).
|
||||
* A build-time VITE_POSTHOG_KEY (release builds; developers pointing at their
|
||||
* own project) always wins over it — mirrors backend/core/analytics.py.
|
||||
* tests/test_no_committed_analytics_token.py pins that a `phc_` literal may
|
||||
* live in exactly this file and backend/core/analytics.py.
|
||||
*/
|
||||
const PUBLIC_PROJECT_TOKEN = 'phc_kJK9nFqtwFmB4CYWS4bMDTY7z9P4KCRyiRT7CzJTXm9f'; // gitleaks:allow — publishable write-only key (#1193)
|
||||
const POSTHOG_TOKEN: string = (import.meta.env?.VITE_POSTHOG_KEY as string) || PUBLIC_PROJECT_TOKEN;
|
||||
const POSTHOG_HOST: string =
|
||||
(import.meta.env?.VITE_POSTHOG_HOST as string) || 'https://us.i.posthog.com';
|
||||
|
||||
/** Whether this build has an analytics destination at all. */
|
||||
/** Whether the interface may report at all; the backend's answer decides. */
|
||||
export function analyticsAvailable(): boolean {
|
||||
return Boolean(POSTHOG_TOKEN);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The ONLY property keys allowed to leave. Mirrors backend `_ALLOWED_PROPS`.
|
||||
* A key not on this list is dropped — not trusted. */
|
||||
const ALLOWED_PROPS = new Set([
|
||||
'feature',
|
||||
'action',
|
||||
'outcome',
|
||||
'engine_id',
|
||||
'language',
|
||||
'mode',
|
||||
@@ -84,58 +55,21 @@ const ALLOWED_PROPS = new Set([
|
||||
* an allowlisted key. */
|
||||
const MAX_STR_LEN = 64;
|
||||
|
||||
interface AnalyticsClient {
|
||||
capture(event: string, props?: Record<string, unknown>): unknown;
|
||||
captureException(error: unknown, props?: Record<string, unknown>): unknown;
|
||||
has_opted_out_capturing(): boolean;
|
||||
opt_in_capturing(): void;
|
||||
opt_out_capturing(): void;
|
||||
reset(): void;
|
||||
}
|
||||
export type AnalyticsSender = (body: {
|
||||
event: string;
|
||||
props: Record<string, unknown>;
|
||||
screen?: string;
|
||||
}) => Promise<unknown>;
|
||||
|
||||
const APP_ANALYTICS_ORIGIN = 'https://app.voicestudio.sh';
|
||||
const SAFE_SCREEN =
|
||||
/^view:(?:home|clone|personas|stories|dub|batch|gallery|transcriptions|design|audiobook|projects|tools|calls|integrations|pro|other|settings\/(?:appearance|general|models|logs|media|pronunciation|network|sharing|credentials|performance|usage|privacy|permissions|storage|support|updates|openapi|diagnostics|other))$/;
|
||||
const URL_PROPERTIES = [
|
||||
'$current_url',
|
||||
'$pathname',
|
||||
'$host',
|
||||
'$title',
|
||||
'$referrer',
|
||||
'$referring_domain',
|
||||
'$initial_current_url',
|
||||
'$initial_pathname',
|
||||
'$initial_referrer',
|
||||
'$initial_referring_domain',
|
||||
] as const;
|
||||
|
||||
interface OutgoingAnalyticsEvent {
|
||||
event?: string;
|
||||
properties?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Remove renderer URLs and document metadata the SDK adds automatically. */
|
||||
export function sanitizeOutgoingEvent<T extends OutgoingAnalyticsEvent>(
|
||||
payload: T | null,
|
||||
): T | null {
|
||||
if (!payload) return null;
|
||||
const properties = { ...payload.properties };
|
||||
for (const key of URL_PROPERTIES) delete properties[key];
|
||||
if (payload.event === '$pageview') {
|
||||
const candidate = payload.properties?.$pathname;
|
||||
const pathname = typeof candidate === 'string' ? candidate : '';
|
||||
if (/^\/(?:[a-z-]+|settings\/[a-z-]+)$/.test(pathname)) {
|
||||
properties.$current_url = `${APP_ANALYTICS_ORIGIN}${pathname}`;
|
||||
properties.$host = 'app.voicestudio.sh';
|
||||
properties.$pathname = pathname;
|
||||
}
|
||||
}
|
||||
return { ...payload, properties };
|
||||
}
|
||||
|
||||
let client: AnalyticsClient | null = null;
|
||||
let sender: AnalyticsSender | null = null;
|
||||
let consentGeneration = 0;
|
||||
let captureState: 'unresolved' | 'enabled' | 'disabled' = 'unresolved';
|
||||
let lastScreen: string | null = null;
|
||||
|
||||
/** The consent runtime registers how events reach the local backend. */
|
||||
export function setAnalyticsSender(next: AnalyticsSender | null): void {
|
||||
sender = next;
|
||||
}
|
||||
|
||||
export const ANALYTICS_EXCEPTION_STAGES = [
|
||||
'renderer:uncaught',
|
||||
@@ -146,58 +80,18 @@ export const ANALYTICS_EXCEPTION_STAGES = [
|
||||
|
||||
export type AnalyticsExceptionStage = (typeof ANALYTICS_EXCEPTION_STAGES)[number];
|
||||
|
||||
const SAFE_ERROR_CLASSES = new Set([
|
||||
'Error',
|
||||
'TypeError',
|
||||
'RangeError',
|
||||
'ReferenceError',
|
||||
'SyntaxError',
|
||||
'URIError',
|
||||
'EvalError',
|
||||
'AggregateError',
|
||||
]);
|
||||
const MAX_PENDING_EXCEPTIONS = 10;
|
||||
const MAX_STACK_LINES = 40;
|
||||
const MAX_STACK_LINE_LENGTH = 512;
|
||||
const pendingExceptions: Array<{ error: Error; stage: AnalyticsExceptionStage }> = [];
|
||||
|
||||
function safeErrorClass(error: unknown): string {
|
||||
const candidate = error instanceof Error ? error.name : 'Error';
|
||||
return /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(candidate) ? candidate : 'Error';
|
||||
}
|
||||
|
||||
/** Build the useful part of a stack without sending messages, credentials or home paths. */
|
||||
export function sanitizeException(error: unknown): Error {
|
||||
const errorClass = safeErrorClass(error);
|
||||
const sourceStack = error instanceof Error && typeof error.stack === 'string' ? error.stack : '';
|
||||
const frames = scrubText(sourceStack)
|
||||
.split('\n')
|
||||
.slice(1)
|
||||
.filter((line) =>
|
||||
/^\s*at (?:[\w$.[\]<>]+ )?\(?(?:https?:\/\/|file:\/\/|app:\/\/|~?\/)[^()\s]+:\d+:\d+\)?$/.test(
|
||||
line,
|
||||
),
|
||||
)
|
||||
.slice(0, MAX_STACK_LINES)
|
||||
.map((line) => line.slice(0, MAX_STACK_LINE_LENGTH));
|
||||
const safe = new Error('VoiceStudio renderer error');
|
||||
safe.name = errorClass;
|
||||
safe.stack = [`${errorClass}: VoiceStudio renderer error`, ...frames].join('\n');
|
||||
return safe;
|
||||
}
|
||||
|
||||
function sendException(error: Error, stage: AnalyticsExceptionStage): void {
|
||||
client?.captureException(error, {
|
||||
stage,
|
||||
error_class: error.name,
|
||||
});
|
||||
}
|
||||
|
||||
/** Queue a sanitized renderer failure until the existing consent gate resolves. */
|
||||
export function captureException(error: unknown, stage: AnalyticsExceptionStage): void {
|
||||
try {
|
||||
const safe = sanitizeException(error);
|
||||
if (captureState === 'enabled' && client && !client.has_opted_out_capturing()) {
|
||||
sendException(safe, stage);
|
||||
return;
|
||||
}
|
||||
if (captureState === 'disabled') return;
|
||||
if (pendingExceptions.length >= MAX_PENDING_EXCEPTIONS) pendingExceptions.shift();
|
||||
pendingExceptions.push({ error: safe, stage });
|
||||
} catch {
|
||||
/* Error reporting must never become another renderer error. */
|
||||
}
|
||||
}
|
||||
const pendingExceptions: Array<{ error_class: string; stage: AnalyticsExceptionStage }> = [];
|
||||
|
||||
/** Drop anything that isn't explicitly allowed. Pure + exported for tests: this
|
||||
* is what stops a take's text, a file path, or a voice name from ever going out. */
|
||||
@@ -206,107 +100,72 @@ export function sanitizeProps(props?: Record<string, unknown>): Record<string, u
|
||||
for (const [k, v] of Object.entries(props ?? {})) {
|
||||
if (!ALLOWED_PROPS.has(k)) continue;
|
||||
if (typeof v === 'string' && v.length > MAX_STR_LEN) continue;
|
||||
if (v === null || ['string', 'number', 'boolean'].includes(typeof v)) out[k] = v;
|
||||
if (k === 'engine_id' && !(typeof v === 'string' && /^[a-z0-9][a-z0-9_.-]{0,39}$/.test(v)))
|
||||
continue;
|
||||
if (typeof v === 'number' && !Number.isFinite(v)) continue;
|
||||
if (['string', 'number', 'boolean'].includes(typeof v)) out[k] = v;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Config that makes the promises above true rather than aspirational. */
|
||||
export function hardenedConfig() {
|
||||
return {
|
||||
api_host: POSTHOG_HOST,
|
||||
// The DOM of this app contains the user's script text, voice names and file
|
||||
// names. Autocapture would send them. Never enable.
|
||||
autocapture: false,
|
||||
// Would record the screen. Never enable.
|
||||
disable_session_recording: true,
|
||||
// Renderer failures are captured manually only after redaction.
|
||||
capture_exceptions: false,
|
||||
// We send deliberate events; we don't need URL/pageview streams.
|
||||
capture_pageview: false,
|
||||
capture_pageleave: false,
|
||||
// Defence in depth: even if a recording were somehow switched on upstream,
|
||||
// don't ship text or element attributes.
|
||||
mask_all_text: true,
|
||||
mask_all_element_attributes: true,
|
||||
// Consent is the gate — never start capturing on init.
|
||||
opt_out_capturing_by_default: true,
|
||||
persistence: 'localStorage' as const,
|
||||
before_send: sanitizeOutgoingEvent,
|
||||
};
|
||||
function send(event: string, props: Record<string, unknown>, screen?: string): void {
|
||||
if (!sender) return;
|
||||
void sender({ event, props: sanitizeProps(props), ...(screen ? { screen } : {}) }).catch(() => {
|
||||
/* Analytics never interrupts the app. */
|
||||
});
|
||||
}
|
||||
|
||||
/** Start analytics. Call ONLY when the user has opted in. Idempotent. */
|
||||
export async function enableAnalytics(): Promise<void> {
|
||||
const generation = ++consentGeneration;
|
||||
try {
|
||||
if (!POSTHOG_TOKEN) return; // no destination in this build — nothing to start
|
||||
if (!client) {
|
||||
// Electron blocks runtime extension downloads. Bundle only the error
|
||||
// tracking extension; DOM analytics and session replay stay absent.
|
||||
const [{ default: posthog }, { ErrorTrackingExtensions }] = await Promise.all([
|
||||
import('posthog-js/dist/module.slim.no-external'),
|
||||
import('posthog-js/dist/extension-bundles'),
|
||||
]);
|
||||
if (generation !== consentGeneration) return;
|
||||
posthog.init(POSTHOG_TOKEN, {
|
||||
...hardenedConfig(),
|
||||
__extensionClasses: { ...ErrorTrackingExtensions },
|
||||
});
|
||||
client = posthog;
|
||||
}
|
||||
const activeClient = client;
|
||||
if (!activeClient || generation !== consentGeneration) return;
|
||||
activeClient.opt_in_capturing();
|
||||
captureState = 'enabled';
|
||||
for (const pending of pendingExceptions.splice(0)) {
|
||||
sendException(pending.error, pending.stage);
|
||||
}
|
||||
} catch (e) {
|
||||
if (generation !== consentGeneration) return;
|
||||
captureState = 'disabled';
|
||||
pendingExceptions.length = 0;
|
||||
console.warn('[analytics] init failed (non-fatal)', e);
|
||||
}
|
||||
if (captureState === 'enabled') return;
|
||||
++consentGeneration;
|
||||
captureState = 'enabled';
|
||||
for (const pending of pendingExceptions.splice(0)) send('renderer_error', pending);
|
||||
}
|
||||
|
||||
/** Stop analytics and forget the local id. Safe to call when never started. */
|
||||
/** Stop analytics. Safe to call when never started. */
|
||||
export function disableAnalytics(): void {
|
||||
consentGeneration += 1;
|
||||
try {
|
||||
captureState = 'disabled';
|
||||
pendingExceptions.length = 0;
|
||||
client?.opt_out_capturing();
|
||||
client?.reset();
|
||||
} catch {
|
||||
/* nothing to stop */
|
||||
}
|
||||
++consentGeneration;
|
||||
captureState = 'disabled';
|
||||
pendingExceptions.length = 0;
|
||||
lastScreen = null;
|
||||
}
|
||||
|
||||
/** Record one event. A no-op unless the user opted in. Never throws. */
|
||||
export function capture(event: string, props?: Record<string, unknown>): void {
|
||||
try {
|
||||
if (!client || client.has_opted_out_capturing()) return;
|
||||
client.capture(event, sanitizeProps(props));
|
||||
} catch (e) {
|
||||
console.warn('[analytics] capture failed (non-fatal)', e);
|
||||
if (captureState !== 'enabled' || event === 'pageview' || event === 'identify') return;
|
||||
send(event, props ?? {});
|
||||
} catch {
|
||||
/* Analytics cannot interrupt the app. */
|
||||
}
|
||||
}
|
||||
|
||||
/** Feed PostHog Web Analytics with a fixed app screen path. Dynamic route
|
||||
* segments and the renderer's localhost URL never leave the machine. */
|
||||
/** Report a fixed app screen (``view:...``). Dynamic route segments and the
|
||||
* renderer's localhost URL never leave the machine; the backend re-checks it. */
|
||||
export function capturePageview(screen: string): void {
|
||||
try {
|
||||
if (!client || client.has_opted_out_capturing() || !SAFE_SCREEN.test(screen)) return;
|
||||
const pathname = `/${screen.slice('view:'.length)}`;
|
||||
client.capture('$pageview', {
|
||||
$current_url: `${APP_ANALYTICS_ORIGIN}${pathname}`,
|
||||
$host: 'app.voicestudio.sh',
|
||||
$pathname: pathname,
|
||||
source: 'electron',
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('[analytics] pageview capture failed (non-fatal)', e);
|
||||
if (captureState !== 'enabled' || screen === lastScreen) return;
|
||||
lastScreen = screen;
|
||||
send('pageview', {}, screen);
|
||||
} catch {
|
||||
/* Analytics cannot interrupt the app. */
|
||||
}
|
||||
}
|
||||
|
||||
/** A renderer failure reduced to a coarse class and stage. No message, no stack. */
|
||||
export function captureException(error: unknown, stage: AnalyticsExceptionStage): void {
|
||||
try {
|
||||
if (!ANALYTICS_EXCEPTION_STAGES.includes(stage)) return;
|
||||
const name = error instanceof Error ? error.name : 'Error';
|
||||
const error_class = SAFE_ERROR_CLASSES.has(name) ? name : 'Error';
|
||||
if (captureState === 'enabled') send('renderer_error', { error_class, stage });
|
||||
else if (captureState === 'unresolved') {
|
||||
if (pendingExceptions.length >= MAX_PENDING_EXCEPTIONS) pendingExceptions.shift();
|
||||
pendingExceptions.push({ error_class, stage });
|
||||
}
|
||||
} catch {
|
||||
/* Error reporting must never become another renderer error. */
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ const allowed = [
|
||||
];
|
||||
const rejected = [
|
||||
STAR_COUNT_URL,
|
||||
'https://us.i.posthog.com/e',
|
||||
'https://app.supermetry.com/api/public/v1/events',
|
||||
'https://huggingface.co/',
|
||||
'http://127.0.0.1.evil.com/',
|
||||
'http://localhost.evil.com/',
|
||||
|
||||
@@ -211,6 +211,7 @@ for (const resource of [
|
||||
'backend',
|
||||
'omnivoice',
|
||||
'config/app.json',
|
||||
'config/analytics.json',
|
||||
]) {
|
||||
const entry = config.extraResources.find((item) => item.to === resource);
|
||||
assert(entry && existsSync(resolve(root, entry.from)), 'Required resource: ' + resource);
|
||||
|
||||
@@ -128,10 +128,6 @@ dependencies = [
|
||||
# false — `cryptography` is not on the install path today).
|
||||
"cryptography>=41",
|
||||
"mcp>=1.28.1,<2",
|
||||
# Opt-in product analytics (core/analytics.py). Inert unless the build ships a
|
||||
# POSTHOG_PROJECT_TOKEN *and* the user opts in — default OFF. No exception
|
||||
# autocapture (it would ship raw tracebacks past core.failure.sanitize()).
|
||||
"posthog>=3.7",
|
||||
# Fast model downloads (FDL plan). huggingface_hub arrives transitively via
|
||||
# transformers, but we pin it directly so the Xet fast-download path can't
|
||||
# silently disappear on a resolve, and we pull `hf-xet` explicitly: it is
|
||||
|
||||
+33
-21
@@ -185,34 +185,46 @@ if (-not $Yes) {
|
||||
}
|
||||
|
||||
# ── Opt-in uninstall ping (before anything is deleted) ──────────────────────
|
||||
# If — and only if — the user opted in to anonymous analytics, send a single
|
||||
# best-effort `app_uninstalled` event before the data (and the consent record
|
||||
# it lives in) goes away. The backend writes analytics_info.json next to
|
||||
# prefs.json ONLY while analytics is enabled (explicit consent + a build that
|
||||
# ships a token) and deletes it on opt-out, so the file's presence is itself
|
||||
# consent-gated; the prefs.json check is belt and braces. Content-free: the
|
||||
# event carries the app version, the OS name, and the random per-install id —
|
||||
# nothing else. Never blocks or fails the uninstall (2s timeout, silent
|
||||
# failure). Not opted in => nothing is sent and nothing is printed.
|
||||
# Sent only when the user opted in: the backend writes analytics_info.json
|
||||
# while analytics is enabled and deletes it on opt-out, and prefs.json must
|
||||
# agree. Content-free; redirects and malformed state are refused. Never blocks
|
||||
# the uninstall. Not opted in => nothing is sent and nothing is printed.
|
||||
try {
|
||||
$infoPath = Join-Path $dataDir 'analytics_info.json'
|
||||
$disabled = "$env:OMNIVOICE_ANALYTICS_DISABLED".Trim().ToLowerInvariant() -in @('1', 'true', 'yes', 'on')
|
||||
$emptySite = (Test-Path Env:SUPERMETRY_SITE_ID) -and -not "$env:SUPERMETRY_SITE_ID".Trim()
|
||||
$prefsPath = Join-Path $dataDir 'prefs.json'
|
||||
if ((Test-Path -LiteralPath $infoPath) -and (Test-Path -LiteralPath $prefsPath)) {
|
||||
$prefs = Get-Content -LiteralPath $prefsPath -Raw | ConvertFrom-Json
|
||||
if ($prefs.analytics_enabled -eq $true) {
|
||||
if (-not $disabled -and -not $emptySite -and (Test-Path -LiteralPath $infoPath) -and (Test-Path -LiteralPath $prefsPath) -and ((Get-Content -LiteralPath $prefsPath -Raw | ConvertFrom-Json).analytics_enabled -eq $true)) {
|
||||
$info = Get-Content -LiteralPath $infoPath -Raw | ConvertFrom-Json
|
||||
if ($info.token -and $info.host -and $info.distinct_id) {
|
||||
$hostUri = [Uri]$info.host
|
||||
$appUri = [Uri]$info.appUrl
|
||||
$validUris = $true
|
||||
foreach ($uri in @($hostUri, $appUri)) {
|
||||
if (-not $uri.IsAbsoluteUri -or $uri.Scheme -notin @('http', 'https') -or
|
||||
-not $uri.Host -or $uri.UserInfo -or $uri.Query -or $uri.Fragment) { $validUris = $false }
|
||||
}
|
||||
if ($validUris -and $hostUri.AbsolutePath -eq '/' -and $info.site -and
|
||||
$info.policy -eq 'opt-in' -and $info.profile_id -match '^install_[a-f0-9]{32}$' -and
|
||||
$info.user_agent.StartsWith('Mozilla/5.0 (') -and $info.user_agent -notmatch '[\r\n]') {
|
||||
Write-Host 'Sending anonymous uninstall ping (you opted in to analytics).'
|
||||
$props = @{}
|
||||
foreach ($key in @('app_version', 'platform')) {
|
||||
if ($info.$key -is [string] -and $info.$key.Length -le 64) { $props[$key] = $info.$key }
|
||||
}
|
||||
$body = @{
|
||||
api_key = $info.token
|
||||
event = 'app_uninstalled'
|
||||
distinct_id = $info.distinct_id
|
||||
properties = @{ app_version = "$($info.app_version)"; platform = "$($info.platform)" }
|
||||
} | ConvertTo-Json
|
||||
Invoke-RestMethod -Method Post -Uri "$($info.host)/capture/" `
|
||||
-ContentType 'application/json' -Body $body -TimeoutSec 2 | Out-Null
|
||||
v = 1
|
||||
id = [Guid]::NewGuid().ToString('N')
|
||||
ts = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
|
||||
site = $info.site
|
||||
profile_id = $info.profile_id
|
||||
name = 'app_uninstalled'
|
||||
url = "$($info.appUrl.TrimEnd('/'))/uninstall"
|
||||
props = $props
|
||||
} | ConvertTo-Json -Compress
|
||||
Invoke-RestMethod -Method Post -Uri "$($info.host.TrimEnd('/'))/api/public/v1/events" `
|
||||
-ContentType 'application/json' -Body $body -TimeoutSec 2 -MaximumRedirection 0 `
|
||||
-UserAgent $info.user_agent -Headers @{ Origin = $appUri.GetLeftPart([UriPartial]::Authority) } | Out-Null
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
# Best-effort by design: a dead network must never block the uninstall.
|
||||
|
||||
+53
-18
@@ -174,29 +174,64 @@ fi
|
||||
# If — and only if — the user opted in to anonymous analytics, send a single
|
||||
# best-effort `app_uninstalled` event before the data (and the consent record
|
||||
# it lives in) goes away. The backend writes analytics_info.json next to
|
||||
# prefs.json ONLY while analytics is enabled (explicit consent + a build that
|
||||
# ships a token) and deletes it on opt-out, so the file's presence is itself
|
||||
# consent-gated; the prefs.json check is belt and braces. Content-free: the
|
||||
# event carries the app version, the OS name, and the random per-install id —
|
||||
# nothing else. Never blocks or fails the uninstall (2s timeout, silent
|
||||
# failure). Not opted in ⇒ nothing is sent and nothing is printed.
|
||||
# prefs.json ONLY while analytics is enabled and deletes it on opt-out, so the
|
||||
# file's presence is itself consent-gated; the prefs.json check is belt and
|
||||
# braces. Content-free: the app version, the OS name and the random per-install
|
||||
# profile. Never blocks the uninstall (2s timeout, silent failure). Not opted
|
||||
# in ⇒ nothing is sent and nothing is printed.
|
||||
send_uninstall_ping() {
|
||||
local info="$DATA_DIR/analytics_info.json" prefs="$DATA_DIR/prefs.json"
|
||||
local info="$DATA_DIR/analytics_info.json"
|
||||
local prefs="$DATA_DIR/prefs.json"
|
||||
[ -f "$info" ] && [ -f "$prefs" ] || return 0
|
||||
grep -q '"analytics_enabled"[[:space:]]*:[[:space:]]*true' "$prefs" 2>/dev/null || return 0
|
||||
command -v curl >/dev/null 2>&1 || return 0
|
||||
local token host distinct_id app_version platform
|
||||
token=$(sed -n 's/.*"token"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$info" | head -n1)
|
||||
host=$(sed -n 's/.*"host"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$info" | head -n1)
|
||||
distinct_id=$(sed -n 's/.*"distinct_id"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$info" | head -n1)
|
||||
app_version=$(sed -n 's/.*"app_version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$info" | head -n1)
|
||||
platform=$(sed -n 's/.*"platform"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$info" | head -n1)
|
||||
[ -n "$token" ] && [ -n "$host" ] && [ -n "$distinct_id" ] || return 0
|
||||
command -v python3 >/dev/null 2>&1 || return 0
|
||||
local prepared host agent origin body
|
||||
prepared=$(python3 - "$info" 2>/dev/null <<'PYTHON'
|
||||
import json, os, re, sys, time, uuid
|
||||
from urllib.parse import urlsplit
|
||||
try:
|
||||
if os.environ.get("OMNIVOICE_ANALYTICS_DISABLED", "").strip().lower() in {"1", "true", "yes", "on"}:
|
||||
raise ValueError()
|
||||
if "SUPERMETRY_SITE_ID" in os.environ and not os.environ["SUPERMETRY_SITE_ID"].strip():
|
||||
raise ValueError()
|
||||
with open(sys.argv[1], encoding="utf-8") as f:
|
||||
info = json.load(f)
|
||||
host, url = info["host"].rstrip("/"), info["appUrl"].rstrip("/")
|
||||
for value in (host, url):
|
||||
parsed = urlsplit(value)
|
||||
if (parsed.scheme not in {"http", "https"} or not parsed.hostname
|
||||
or parsed.username or parsed.password or parsed.query or parsed.fragment
|
||||
or any(ord(c) < 33 for c in value)):
|
||||
raise ValueError()
|
||||
if (urlsplit(host).path or not info.get("site") or info.get("policy") != "opt-in"
|
||||
or not re.fullmatch(r"install_[a-f0-9]{32}", info.get("profile_id", ""))):
|
||||
raise ValueError()
|
||||
agent = info["user_agent"]
|
||||
if not agent.startswith("Mozilla/5.0 (") or any(ord(c) < 32 for c in agent):
|
||||
raise ValueError()
|
||||
props = {k: info[k] for k in ("app_version", "platform") if isinstance(info.get(k), str) and len(info[k]) <= 64}
|
||||
event = {"v": 1, "id": uuid.uuid4().hex, "ts": int(time.time() * 1000),
|
||||
"site": info["site"], "name": "app_uninstalled", "url": url + "/uninstall",
|
||||
"profile_id": info["profile_id"], "props": props}
|
||||
parsed = urlsplit(url)
|
||||
print(host)
|
||||
print(agent)
|
||||
print(parsed.scheme + "://" + parsed.netloc)
|
||||
print(json.dumps(event, separators=(",", ":"), allow_nan=False))
|
||||
except Exception:
|
||||
sys.exit(1)
|
||||
PYTHON
|
||||
) || return 0
|
||||
host=$(printf '%s\n' "$prepared" | sed -n '1p')
|
||||
agent=$(printf '%s\n' "$prepared" | sed -n '2p')
|
||||
origin=$(printf '%s\n' "$prepared" | sed -n '3p')
|
||||
body=$(printf '%s\n' "$prepared" | sed -n '4p')
|
||||
[ -n "$host" ] && [ -n "$body" ] || return 0
|
||||
echo "Sending anonymous uninstall ping (you opted in to analytics)."
|
||||
curl -m 2 -s -o /dev/null -X POST "$host/capture/" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d "{\"api_key\":\"$token\",\"event\":\"app_uninstalled\",\"distinct_id\":\"$distinct_id\",\"properties\":{\"app_version\":\"$app_version\",\"platform\":\"$platform\"}}" \
|
||||
|| true
|
||||
curl -m 2 -s -o /dev/null -X POST "$host/api/public/v1/events" \
|
||||
-H 'Content-Type: application/json' -H "Origin: $origin" -A "$agent" \
|
||||
-d "$body" || true
|
||||
}
|
||||
send_uninstall_ping
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ assert.equal(privacy.schemaVersion, 1);
|
||||
assert.equal(privacy.policyUrl, metadata.urls.privacyPolicy);
|
||||
assert.equal(privacy.defaultBehavior.analyticsEnabled, false);
|
||||
assert.equal(privacy.defaultBehavior.audioUploaded, false);
|
||||
assert(privacy.transmittedData.some((entry) => entry.destination === "PostHog US"));
|
||||
assert(privacy.transmittedData.some((entry) => entry.destination === "Supermetry"));
|
||||
|
||||
assert.equal(compliance.schemaVersion, 1);
|
||||
const allowedStatuses = new Set(compliance.statuses);
|
||||
|
||||
+2
-2
@@ -17,7 +17,7 @@
|
||||
],
|
||||
"transmittedData": [
|
||||
{
|
||||
"destination": "PostHog US",
|
||||
"destination": "Supermetry",
|
||||
"condition": "explicit analytics opt-in",
|
||||
"purpose": "product analytics and sanitized error diagnostics",
|
||||
"data": [
|
||||
@@ -25,7 +25,7 @@
|
||||
"application version and platform",
|
||||
"closed-set workflow and engine labels",
|
||||
"counts, durations and text length without text",
|
||||
"sanitized error class and stack frames without messages or local paths"
|
||||
"coarse error class and stage without messages, stack frames or local paths"
|
||||
],
|
||||
"excluded": [
|
||||
"audio",
|
||||
|
||||
@@ -47,9 +47,12 @@ def _run(tmp_path, *args, consented=True, with_info=True):
|
||||
(data / "analytics_info.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"token": "phc_test_token",
|
||||
"host": "https://eu.i.posthog.com",
|
||||
"distinct_id": "11111111-2222-3333-4444-555555555555",
|
||||
"site": "testsite12345",
|
||||
"host": "https://app.supermetry.com",
|
||||
"appUrl": "https://app.voicestudio.sh",
|
||||
"user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 VoiceStudio/1.0",
|
||||
"policy": "opt-in",
|
||||
"profile_id": "install_11111111222233334444555555555555",
|
||||
"app_version": "0.3.23",
|
||||
"platform": "macos",
|
||||
},
|
||||
@@ -89,11 +92,11 @@ def test_consented_delete_sends_one_honest_ping(tmp_path):
|
||||
proc, curl = _run(tmp_path, "--yes")
|
||||
assert proc.returncode == 0, proc.stderr
|
||||
assert "Sending anonymous uninstall ping (you opted in to analytics)." in proc.stdout
|
||||
# One capture call, to the host from analytics_info.json, with the ping.
|
||||
assert "https://eu.i.posthog.com/capture/" in curl
|
||||
# One call, to the host from analytics_info.json, with the ping.
|
||||
assert "https://app.supermetry.com/api/public/v1/events" in curl
|
||||
assert curl.count("app_uninstalled") == 1
|
||||
assert "phc_test_token" in curl
|
||||
assert "11111111-2222-3333-4444-555555555555" in curl
|
||||
assert "testsite12345" in curl
|
||||
assert "install_11111111222233334444555555555555" in curl
|
||||
assert '"app_version":"0.3.23"' in curl.replace(" ", "")
|
||||
# Best-effort timeout is on the call.
|
||||
assert re.search(r"^-m\n2$", curl, re.M)
|
||||
@@ -152,13 +155,13 @@ def test_ps1_ping_is_consent_gated_and_best_effort():
|
||||
assert src.index("exit 0") < src.index("app_uninstalled")
|
||||
|
||||
|
||||
def test_ps1_and_sh_carry_no_baked_token():
|
||||
"""The scripts are generic: the token comes from the backend-written info
|
||||
file, never from a literal in the repo (the secret scanner would agree)."""
|
||||
def test_ps1_and_sh_carry_no_baked_site():
|
||||
"""The scripts are generic: the destination comes from the backend-written
|
||||
info file, never from a literal in the repo."""
|
||||
for path in (SH, PS1):
|
||||
with open(path, encoding="utf-8") as f:
|
||||
src = f.read()
|
||||
assert not re.search(r"phc_[A-Za-z0-9]{16,}", src), path
|
||||
assert "oxxxnwyfwhx4" not in src, path
|
||||
|
||||
|
||||
def test_shellcheck_clean_if_available():
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Lifecycle analytics events (owner-sanctioned 2026-07-16) — the guarantees, pinned.
|
||||
|
||||
install / update / crash / error events ride the SAME rails as everything else
|
||||
in core.analytics: the dual gate (build token AND explicit consent), the
|
||||
in core.analytics: the dual gate (a configured site AND explicit consent), the
|
||||
property allowlist, and never-raises. These tests pin the event-specific
|
||||
guarantees on top:
|
||||
|
||||
@@ -31,12 +31,12 @@ from core import analytics
|
||||
|
||||
@pytest.fixture()
|
||||
def sent(monkeypatch, tmp_path):
|
||||
"""Isolated prefs + DATA_DIR + a fake posthog module recording captures."""
|
||||
"""Isolated prefs + DATA_DIR + a fake transport recording captures."""
|
||||
from core import config, prefs
|
||||
|
||||
monkeypatch.setattr(prefs, "_PREFS_PATH", str(tmp_path / "prefs.json"))
|
||||
monkeypatch.setattr(config, "DATA_DIR", str(tmp_path))
|
||||
monkeypatch.delenv("POSTHOG_PROJECT_TOKEN", raising=False)
|
||||
monkeypatch.delenv("SUPERMETRY_SITE_ID", raising=False)
|
||||
monkeypatch.delenv("OMNIVOICE_ANALYTICS_DISABLED", raising=False)
|
||||
monkeypatch.delenv("OMNIVOICE_INSTALL_CHANNEL", raising=False)
|
||||
monkeypatch.delenv("OMNIVOICE_SERVER_MODE", raising=False)
|
||||
@@ -45,19 +45,19 @@ def sent(monkeypatch, tmp_path):
|
||||
|
||||
events: list[tuple[str, dict]] = []
|
||||
|
||||
class FakePosthog:
|
||||
def __init__(self, token, **kwargs):
|
||||
class FakeTransport:
|
||||
def __init__(self, destination, should_send):
|
||||
pass
|
||||
|
||||
def capture(self, event, distinct_id=None, properties=None):
|
||||
events.append((event, dict(properties or {})))
|
||||
def capture(self, event, properties, profile_id=None, traits=None, path="/backend"):
|
||||
if event != "identify": # the profile handshake is not a product event
|
||||
events.append((event, dict(properties or {})))
|
||||
return True
|
||||
|
||||
def shutdown(self):
|
||||
pass
|
||||
|
||||
fake = types.ModuleType("posthog")
|
||||
fake.Posthog = FakePosthog
|
||||
monkeypatch.setitem(sys.modules, "posthog", fake)
|
||||
monkeypatch.setattr(analytics, "SupermetryTransport", FakeTransport)
|
||||
yield events
|
||||
analytics.shutdown()
|
||||
analytics._reset_error_events_for_tests()
|
||||
@@ -68,7 +68,6 @@ def _consent(monkeypatch, *, install_already_recorded=True):
|
||||
tests about OTHER events aren't polluted by the opt-in's install ping."""
|
||||
from core import prefs
|
||||
|
||||
monkeypatch.setenv("POSTHOG_PROJECT_TOKEN", "phc_test")
|
||||
if install_already_recorded:
|
||||
prefs.set_("analytics_install_recorded", True)
|
||||
analytics.set_opted_in(True)
|
||||
@@ -99,7 +98,6 @@ def test_installed_never_fires_without_consent_but_is_not_swallowed(sent, monkey
|
||||
must not send anything, and must not burn the install marker either."""
|
||||
from core import prefs
|
||||
|
||||
monkeypatch.setenv("POSTHOG_PROJECT_TOKEN", "phc_test")
|
||||
analytics.record_startup_lifecycle(None)
|
||||
assert sent == []
|
||||
assert not prefs.get("analytics_install_recorded")
|
||||
@@ -110,7 +108,7 @@ def test_installed_never_fires_without_consent_but_is_not_swallowed(sent, monkey
|
||||
|
||||
def test_installed_never_fires_without_any_token(sent, monkeypatch):
|
||||
# No destination at all: env absent AND the in-repo default (#1193) blanked.
|
||||
monkeypatch.setattr(analytics, "_PUBLIC_PROJECT_TOKEN", "")
|
||||
monkeypatch.setenv("SUPERMETRY_SITE_ID", "")
|
||||
analytics.set_opted_in(True) # consent but no destination
|
||||
analytics.record_startup_lifecycle(None)
|
||||
assert sent == []
|
||||
@@ -140,7 +138,6 @@ def test_an_unconsented_update_is_never_replayed_after_opt_in(sent, monkeypatch)
|
||||
reports what happens AFTER consent — no retroactive history."""
|
||||
from core import prefs
|
||||
|
||||
monkeypatch.setenv("POSTHOG_PROJECT_TOKEN", "phc_test")
|
||||
prefs.set_("analytics_last_version", "0.0.1-test")
|
||||
analytics.record_startup_lifecycle(None) # not opted in: sends nothing…
|
||||
assert sent == []
|
||||
@@ -197,7 +194,6 @@ def test_no_crash_record_means_no_crash_event(sent, monkeypatch):
|
||||
|
||||
|
||||
def test_crash_event_never_fires_without_consent(sent, monkeypatch):
|
||||
monkeypatch.setenv("POSTHOG_PROJECT_TOKEN", "phc_test")
|
||||
analytics.record_startup_lifecycle(dict(CRASH_RECORD))
|
||||
assert sent == []
|
||||
|
||||
@@ -252,7 +248,6 @@ def test_error_events_hard_cap_per_session(sent, monkeypatch):
|
||||
|
||||
|
||||
def test_error_event_never_fires_without_consent(sent, monkeypatch):
|
||||
monkeypatch.setenv("POSTHOG_PROJECT_TOKEN", "phc_test")
|
||||
analytics.record_error_event("GPU_OOM", "fp1", stage="generate")
|
||||
assert sent == []
|
||||
|
||||
@@ -323,36 +318,35 @@ def test_uninstall_ping_info_written_when_enabled_and_removed_when_not(
|
||||
):
|
||||
info = tmp_path / analytics.UNINSTALL_PING_INFO_BASENAME
|
||||
# Not consented → no file (and startup keeps it that way).
|
||||
monkeypatch.setenv("POSTHOG_PROJECT_TOKEN", "phc_test")
|
||||
analytics.record_startup_lifecycle(None)
|
||||
assert not info.exists()
|
||||
|
||||
analytics.set_opted_in(True)
|
||||
assert info.exists()
|
||||
payload = json.loads(info.read_text(encoding="utf-8"))
|
||||
assert payload["token"] == "phc_test"
|
||||
assert payload["host"] == "https://us.i.posthog.com"
|
||||
assert payload["distinct_id"] == analytics.installation_id()
|
||||
assert payload["site"] == "oxxxnwyfwhx4"
|
||||
assert payload["host"] == "https://app.supermetry.com"
|
||||
assert payload["profile_id"] == analytics.profile_id()
|
||||
assert payload["app_version"] == analytics._app_version()
|
||||
# Consent withdrawn → the file goes with it.
|
||||
analytics.set_opted_in(False)
|
||||
assert not info.exists()
|
||||
|
||||
|
||||
def test_uninstall_ping_info_written_for_a_source_build_with_the_default_token(
|
||||
def test_uninstall_ping_info_written_for_a_source_build_with_the_shared_site(
|
||||
sent, monkeypatch, tmp_path
|
||||
):
|
||||
"""#1193: a consented source build has a destination (the in-repo default),
|
||||
so the uninstall ping must work there too."""
|
||||
analytics.set_opted_in(True) # no env token → in-repo default
|
||||
"""A consented source build has a destination (the shared config), so the
|
||||
uninstall ping must work there too."""
|
||||
analytics.set_opted_in(True) # no override → shared config
|
||||
info = tmp_path / analytics.UNINSTALL_PING_INFO_BASENAME
|
||||
assert info.exists()
|
||||
payload = json.loads(info.read_text(encoding="utf-8"))
|
||||
assert payload["token"] == analytics._PUBLIC_PROJECT_TOKEN
|
||||
assert payload["host"] == "https://us.i.posthog.com"
|
||||
assert payload["site"] == analytics._destination()["site"]
|
||||
assert payload["host"] == "https://app.supermetry.com"
|
||||
|
||||
|
||||
def test_uninstall_ping_info_never_written_without_any_token(sent, monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(analytics, "_PUBLIC_PROJECT_TOKEN", "") # destination-less build
|
||||
def test_uninstall_ping_info_never_written_without_any_site(sent, monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("SUPERMETRY_SITE_ID", "") # destination-less build
|
||||
analytics.set_opted_in(True)
|
||||
assert not (tmp_path / analytics.UNINSTALL_PING_INFO_BASENAME).exists()
|
||||
@@ -4,9 +4,9 @@ OmniVoice is local-first, so an analytics SDK gets held to a higher bar. These
|
||||
tests exist so the guarantees can't quietly rot:
|
||||
|
||||
1. OFF unless the user says yes (default False; silence is not consent).
|
||||
2. NO exception autocapture — the SDK's own default would ship raw tracebacks
|
||||
carrying home paths and, in this codebase, Hugging Face tokens out of
|
||||
exception messages, bypassing core.failure.sanitize() entirely.
|
||||
2. NO exception autocapture — raw tracebacks carry home paths and, in this
|
||||
codebase, Hugging Face tokens, bypassing core.failure.sanitize(). Only
|
||||
coarse classes and stages are ever sent.
|
||||
3. Metadata ONLY, enforced by allowlist — so no future caller can leak the text
|
||||
of a take, a file path, or a voice name by adding a property.
|
||||
"""
|
||||
@@ -22,40 +22,39 @@ import pytest
|
||||
from core import analytics
|
||||
|
||||
|
||||
SENT: list[dict] = []
|
||||
|
||||
|
||||
class _FakeTransport:
|
||||
"""Records what would be sent; the real transport opens a thread and a socket."""
|
||||
|
||||
def __init__(self, destination, should_send):
|
||||
self.destination = destination
|
||||
self.should_send = should_send
|
||||
|
||||
def capture(self, event, properties, profile_id=None, traits=None, path="/backend"):
|
||||
SENT.append({"event": event, "props": properties, "profile_id": profile_id, "path": path})
|
||||
return True
|
||||
|
||||
def shutdown(self):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate(monkeypatch, tmp_path):
|
||||
"""Fresh prefs + isolated DATA_DIR + no token + no kill switch, per test.
|
||||
|
||||
Also pre-installs an inert fake `posthog` module: set_opted_in(True) now
|
||||
fires the one-shot install ping (lifecycle events), which builds the client
|
||||
eagerly — tests must never construct the real SDK (background queue threads
|
||||
+ network attempts). Tests that inspect client construction install their
|
||||
own fake BEFORE opting in."""
|
||||
import sys
|
||||
import types
|
||||
|
||||
"""Fresh prefs + isolated DATA_DIR + no override + no kill switch, per test,
|
||||
with a fake transport so no test opens a socket."""
|
||||
from core import config, prefs
|
||||
|
||||
monkeypatch.setattr(prefs, "_PREFS_PATH", str(tmp_path / "prefs.json"))
|
||||
monkeypatch.setattr(config, "DATA_DIR", str(tmp_path))
|
||||
monkeypatch.delenv("POSTHOG_PROJECT_TOKEN", raising=False)
|
||||
monkeypatch.delenv("SUPERMETRY_SITE_ID", raising=False)
|
||||
monkeypatch.delenv("SUPERMETRY_HOST", raising=False)
|
||||
monkeypatch.delenv("OMNIVOICE_ANALYTICS_DISABLED", raising=False)
|
||||
monkeypatch.delenv("OMNIVOICE_INSTALL_CHANNEL", raising=False)
|
||||
monkeypatch.delenv("OMNIVOICE_SERVER_MODE", raising=False)
|
||||
|
||||
class _InertPosthog:
|
||||
def __init__(self, *a, **k):
|
||||
pass
|
||||
|
||||
def capture(self, *a, **k):
|
||||
pass
|
||||
|
||||
def shutdown(self):
|
||||
pass
|
||||
|
||||
fake = types.ModuleType("posthog")
|
||||
fake.Posthog = _InertPosthog
|
||||
monkeypatch.setitem(sys.modules, "posthog", fake)
|
||||
monkeypatch.setattr(analytics, "SupermetryTransport", _FakeTransport)
|
||||
SENT.clear()
|
||||
|
||||
analytics.shutdown()
|
||||
yield
|
||||
@@ -65,36 +64,33 @@ def _isolate(monkeypatch, tmp_path):
|
||||
# ── Rule 1: off unless the user says yes ────────────────────────────────────
|
||||
|
||||
|
||||
def test_off_by_default_even_when_the_build_ships_a_token(monkeypatch):
|
||||
def test_off_by_default_even_when_the_build_ships_a_destination(monkeypatch):
|
||||
"""The whole promise: a default install transmits nothing."""
|
||||
monkeypatch.setenv("POSTHOG_PROJECT_TOKEN", "phc_test")
|
||||
assert analytics.user_opted_in() is False
|
||||
assert analytics.enabled() is False
|
||||
|
||||
|
||||
def test_source_builds_have_a_destination_via_the_in_repo_default(monkeypatch):
|
||||
"""#1193: with no env/baked token, the committed publishable key is the
|
||||
fallback — so source builds get the SAME consent flow as installers. Consent
|
||||
is still the gate: available ≠ enabled."""
|
||||
assert analytics.token_configured() is True # no env token set by _isolate
|
||||
"""With no override, the committed public site id is the destination, so
|
||||
source builds get the SAME consent flow as installers. Consent is still the
|
||||
gate: available ≠ enabled."""
|
||||
assert analytics.token_configured() is True # no override set by _isolate
|
||||
assert analytics.enabled() is False # …but silence is still not consent
|
||||
analytics.set_opted_in(True)
|
||||
assert analytics.enabled() is True
|
||||
|
||||
|
||||
def test_the_env_token_beats_the_in_repo_default(monkeypatch):
|
||||
"""Release builds bake a token through the shell env; developers set their
|
||||
own. Either must override the committed default."""
|
||||
monkeypatch.setenv("POSTHOG_PROJECT_TOKEN", " phc_env_wins ")
|
||||
assert analytics._resolved_token() == "phc_env_wins"
|
||||
monkeypatch.delenv("POSTHOG_PROJECT_TOKEN")
|
||||
assert analytics._resolved_token() == analytics._PUBLIC_PROJECT_TOKEN
|
||||
def test_the_env_site_beats_the_shared_config(monkeypatch):
|
||||
"""A developer's own site overrides the committed one."""
|
||||
assert analytics._destination()["site"] == "oxxxnwyfwhx4"
|
||||
monkeypatch.setenv("SUPERMETRY_SITE_ID", "devsite12345")
|
||||
assert analytics._destination()["site"] == "devsite12345"
|
||||
|
||||
|
||||
def test_opting_in_without_any_token_still_cannot_transmit(monkeypatch):
|
||||
"""A build with no destination at all (env absent AND in-repo default
|
||||
blanked) — the toggle must not pretend otherwise."""
|
||||
monkeypatch.setattr(analytics, "_PUBLIC_PROJECT_TOKEN", "")
|
||||
"""A build with no destination (the site blanked) — the toggle must not
|
||||
pretend otherwise."""
|
||||
monkeypatch.setenv("SUPERMETRY_SITE_ID", "")
|
||||
analytics.set_opted_in(True)
|
||||
assert analytics.user_opted_in() is True
|
||||
assert analytics.token_configured() is False
|
||||
@@ -102,20 +98,17 @@ def test_opting_in_without_any_token_still_cannot_transmit(monkeypatch):
|
||||
|
||||
|
||||
def test_enabled_only_when_BOTH_gates_are_true(monkeypatch):
|
||||
monkeypatch.setenv("POSTHOG_PROJECT_TOKEN", "phc_test")
|
||||
analytics.set_opted_in(True)
|
||||
assert analytics.enabled() is True
|
||||
|
||||
|
||||
def test_kill_switch_outranks_everything(monkeypatch):
|
||||
monkeypatch.setenv("POSTHOG_PROJECT_TOKEN", "phc_test")
|
||||
analytics.set_opted_in(True)
|
||||
monkeypatch.setenv("OMNIVOICE_ANALYTICS_DISABLED", "1")
|
||||
assert analytics.enabled() is False
|
||||
|
||||
|
||||
def test_withdrawing_consent_takes_effect_immediately(monkeypatch):
|
||||
monkeypatch.setenv("POSTHOG_PROJECT_TOKEN", "phc_test")
|
||||
analytics.set_opted_in(True)
|
||||
assert analytics.enabled() is True
|
||||
analytics.set_opted_in(False)
|
||||
@@ -161,7 +154,6 @@ def test_prompted_never_enables_anything(monkeypatch):
|
||||
from core import prefs
|
||||
|
||||
prefs.set_("analytics_prompted", True)
|
||||
monkeypatch.setenv("POSTHOG_PROJECT_TOKEN", "phc_test")
|
||||
assert analytics.user_opted_in() is False
|
||||
assert analytics.enabled() is False
|
||||
|
||||
@@ -248,53 +240,52 @@ def test_frontend_allowlist_mirrors_backend():
|
||||
# ── Rule 2: no exception autocapture ────────────────────────────────────────
|
||||
|
||||
|
||||
def test_client_is_built_with_exception_autocapture_OFF(monkeypatch):
|
||||
"""The SDK's own default ships raw tracebacks — home paths, and in this
|
||||
codebase HF tokens out of exception messages — bypassing the redaction in
|
||||
core.failure.sanitize(). It must be explicitly disabled."""
|
||||
captured_kwargs = {}
|
||||
|
||||
class FakePosthog:
|
||||
def __init__(self, token, **kwargs):
|
||||
captured_kwargs.update(kwargs)
|
||||
|
||||
def capture(self, *a, **k):
|
||||
pass
|
||||
|
||||
def shutdown(self):
|
||||
pass
|
||||
|
||||
import sys
|
||||
import types
|
||||
|
||||
fake_mod = types.ModuleType("posthog")
|
||||
fake_mod.Posthog = FakePosthog
|
||||
# Installed BEFORE opting in: set_opted_in(True) builds the client eagerly
|
||||
# (one-shot install ping), and that construction is what's under test.
|
||||
monkeypatch.setitem(sys.modules, "posthog", fake_mod)
|
||||
|
||||
monkeypatch.setenv("POSTHOG_PROJECT_TOKEN", "phc_test")
|
||||
def test_events_carry_an_opaque_install_profile_and_only_allowlisted_props():
|
||||
"""The destination sees a random install_ profile and metadata only: never
|
||||
a traceback, a path, or the take's text."""
|
||||
analytics.set_opted_in(True)
|
||||
SENT.clear()
|
||||
analytics.capture("speech_generated", {"engine_id": "omnivoice", "text": "private script"})
|
||||
assert len(SENT) == 1
|
||||
sent = SENT[0]
|
||||
assert sent["props"] == {"engine_id": "omnivoice"}
|
||||
assert sent["profile_id"].startswith("install_") and len(sent["profile_id"]) == len("install_") + 32
|
||||
assert "private" not in repr(sent)
|
||||
|
||||
|
||||
def test_nothing_is_sent_without_consent():
|
||||
analytics.capture("speech_generated", {"engine_id": "omnivoice"})
|
||||
|
||||
assert captured_kwargs.get("enable_exception_autocapture") is False
|
||||
assert SENT == []
|
||||
|
||||
|
||||
def test_capture_never_raises_even_if_the_sdk_explodes(monkeypatch):
|
||||
def test_capture_never_raises_even_if_the_transport_explodes(monkeypatch):
|
||||
class Boom:
|
||||
def __init__(self, *a, **k):
|
||||
raise RuntimeError("network on fire")
|
||||
|
||||
import sys
|
||||
import types
|
||||
|
||||
fake_mod = types.ModuleType("posthog")
|
||||
fake_mod.Posthog = Boom
|
||||
monkeypatch.setitem(sys.modules, "posthog", fake_mod)
|
||||
|
||||
monkeypatch.setenv("POSTHOG_PROJECT_TOKEN", "phc_test")
|
||||
monkeypatch.setattr(analytics, "SupermetryTransport", Boom)
|
||||
analytics.set_opted_in(True) # builds the client eagerly — must not raise
|
||||
analytics.capture("speech_generated", {"engine_id": "omnivoice"}) # must not raise
|
||||
assert analytics.capture("speech_generated", {"engine_id": "omnivoice"}) is False
|
||||
|
||||
|
||||
def test_ui_events_are_gated_and_pageviews_use_fixed_paths():
|
||||
assert analytics.capture_from_ui("pageview", {}, "view:home") is False # not opted in
|
||||
analytics.set_opted_in(True)
|
||||
SENT.clear()
|
||||
assert analytics.capture_from_ui("pageview", {}, "view:home") is True
|
||||
assert SENT[-1]["path"] == "/home" and SENT[-1]["event"] == "pageview"
|
||||
for bad in ("view:../../etc", "view:clone/123", "home", "view:settings/secret"):
|
||||
assert analytics.capture_from_ui("pageview", {}, bad) is False
|
||||
assert analytics.capture_from_ui("identify", {}) is False
|
||||
assert analytics.capture_from_ui("bad name!", {}) is False
|
||||
|
||||
|
||||
def test_engine_id_must_look_like_an_engine_identifier():
|
||||
"""engine_id is for our engine keys only; a path or a typed name is dropped."""
|
||||
for bad in ("My Cool Voice", "/home/me/model.bin", "C:\\Users\\me", "a b", "", "x" * 41):
|
||||
assert "engine_id" not in analytics.sanitize_properties({"engine_id": bad})
|
||||
for good in ("omnivoice", "indextts2", "cosyvoice-3", "faster_whisper", "qwen3.tts"):
|
||||
assert analytics.sanitize_properties({"engine_id": good}) == {"engine_id": good}
|
||||
|
||||
|
||||
def test_installation_id_is_random_not_derived_from_the_machine():
|
||||
|
||||
@@ -6,13 +6,7 @@ import tomllib
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
_POSTHOG_TOKEN = re.search(
|
||||
r"phc_[A-Za-z0-9]{20,}",
|
||||
(ROOT / "backend/core/analytics.py").read_text(encoding="utf-8"),
|
||||
)
|
||||
assert _POSTHOG_TOKEN is not None
|
||||
EXPECTED_EXACT_REGEXES = {
|
||||
f"^{_POSTHOG_TOKEN.group(0)}$",
|
||||
"^528e871c2a26c4f0f7773b9754e2e1acae20899d$",
|
||||
"^hf_abcdefghijklmnopqrstuvwxyz01234567890abcd$",
|
||||
"^hf_abcdefghijklmnopqrstuvwxyz0123456789ABCDEF$",
|
||||
|
||||
@@ -1,41 +1,22 @@
|
||||
"""The analytics token lives in exactly two canonical files — nowhere else.
|
||||
"""No analytics key is committed.
|
||||
|
||||
History: gitleaks once caught a hardcoded PostHog key in analytics.ts, and the
|
||||
repo banned token-shaped literals outright (build-time injection only). Owner
|
||||
reversal #1193: source builds now ship the same consent-gated analytics as
|
||||
installers, so the *publishable* project token (write-only event ingestion, not
|
||||
data access — PostHog's client keys are designed to ship in client code) is
|
||||
committed as an in-repo default in the two files that implement analytics:
|
||||
|
||||
backend/core/analytics.py (_PUBLIC_PROJECT_TOKEN)
|
||||
electron/src/shared/utils/analytics.ts (PUBLIC_PROJECT_TOKEN)
|
||||
|
||||
This guard pins the new contract: a `phc_` literal may exist ONLY there, both
|
||||
files must actually carry one, and the two must be the SAME token (one PostHog
|
||||
project — a drifted pair would silently split the event stream). The build-time
|
||||
override chain (env / baked secret beats the in-repo default) stays pinned
|
||||
below. Same file-scanning idiom as test_no_hardcoded_cjk / test_no_literal_borders.
|
||||
The analytics destination is a public Supermetry site id in
|
||||
``config/analytics.json``; it only names where opted-in events go. Anything
|
||||
that grants access (a Supermetry dashboard/API key ``pnl_...``, a PostHog
|
||||
project or personal key) must never be committed, and the clients take no
|
||||
token from the build environment.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
_REPO = Path(__file__).resolve().parents[1]
|
||||
|
||||
# A PostHog project key. Deliberately matched by SHAPE, not by the specific value,
|
||||
# so a key can't slip into a *different* file unnoticed.
|
||||
_POSTHOG_KEY_RE = re.compile(r"phc_[A-Za-z0-9]{20,}")
|
||||
|
||||
# The ONLY tracked files allowed to contain a `phc_` literal (#1193).
|
||||
_CANONICAL_TOKEN_FILES = (
|
||||
"backend/core/analytics.py",
|
||||
"electron/src/shared/utils/analytics.ts",
|
||||
)
|
||||
|
||||
_SECRET_RE = re.compile(r"\b(?:pnl|phc|phx)_[A-Za-z0-9]{20,}")
|
||||
_SKIP_DIRS = {"node_modules", ".git", "target", "dist", "build", ".venv", "zig-out"}
|
||||
_SCAN_EXT = {".ts", ".tsx", ".js", ".jsx", ".py", ".rs", ".json", ".yml", ".yaml", ".md", ".env"}
|
||||
_SCAN_EXT = {".ts", ".tsx", ".js", ".jsx", ".py", ".rs", ".json", ".yml", ".yaml", ".md", ".env", ".mjs"}
|
||||
|
||||
|
||||
def _tracked_files():
|
||||
@@ -44,83 +25,28 @@ def _tracked_files():
|
||||
).stdout
|
||||
for name in (n for n in out.split("\0") if n):
|
||||
p = Path(name)
|
||||
if any(part in _SKIP_DIRS for part in p.parts):
|
||||
if any(part in _SKIP_DIRS for part in p.parts) or p.suffix.lower() not in _SCAN_EXT:
|
||||
continue
|
||||
if p.suffix.lower() in _SCAN_EXT:
|
||||
yield name, _REPO / p
|
||||
yield name, _REPO / p
|
||||
|
||||
|
||||
def test_posthog_token_literals_only_in_the_two_canonical_files():
|
||||
def test_no_analytics_key_literal_is_committed():
|
||||
offenders = []
|
||||
for name, path in _tracked_files():
|
||||
# This guard describes the pattern it forbids, so exempt itself.
|
||||
if name == "tests/test_no_committed_analytics_token.py":
|
||||
continue
|
||||
if name in _CANONICAL_TOKEN_FILES:
|
||||
if name in {"tests/test_no_committed_analytics_token.py", "tests/test_gitleaks_allowlist.py"}:
|
||||
continue
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8", errors="ignore")
|
||||
except OSError:
|
||||
continue
|
||||
if _POSTHOG_KEY_RE.search(text):
|
||||
if _SECRET_RE.search(text):
|
||||
offenders.append(name)
|
||||
|
||||
assert not offenders, (
|
||||
"A PostHog token literal is committed outside the canonical files ("
|
||||
+ ", ".join(_CANONICAL_TOKEN_FILES)
|
||||
+ "): "
|
||||
+ ", ".join(offenders)
|
||||
+ ". The in-repo default lives ONLY there (#1193); everything else takes "
|
||||
"the token via VITE_POSTHOG_KEY / POSTHOG_PROJECT_TOKEN at build/run time."
|
||||
)
|
||||
assert not offenders, "An analytics key literal is committed in: " + ", ".join(offenders)
|
||||
|
||||
|
||||
def test_both_canonical_files_carry_the_same_default_token():
|
||||
"""#1193's whole point: source builds have a destination. Both halves must
|
||||
ship the in-repo default, and it must be ONE token — a mismatched pair would
|
||||
split installs across PostHog projects with no error anywhere."""
|
||||
tokens = {}
|
||||
for name in _CANONICAL_TOKEN_FILES:
|
||||
found = _POSTHOG_KEY_RE.findall((_REPO / name).read_text(encoding="utf-8"))
|
||||
assert found, f"{name} no longer carries the in-repo default token (#1193)"
|
||||
assert len(set(found)) == 1, f"{name} contains multiple distinct phc_ literals"
|
||||
tokens[name] = found[0]
|
||||
assert len(set(tokens.values())) == 1, f"canonical token files disagree: {tokens}"
|
||||
|
||||
|
||||
# ── the OVERRIDE chain must stay wired ───────────────────────────────────────
|
||||
#
|
||||
# The in-repo default is the fallback; release builds override it with the repo
|
||||
# secret, and a developer's process env overrides everything:
|
||||
#
|
||||
# repo secret -> release.yml -> tauri-action -> option_env! in backend.rs
|
||||
# -> spawned backend process env -> analytics._resolved_token()
|
||||
#
|
||||
# Every link is invisible when it breaks (events just land in the default
|
||||
# project instead of the release one). These pin the links that live in files a
|
||||
# future change could quietly drop.
|
||||
|
||||
|
||||
def test_the_frontend_reads_its_token_override_from_the_build_env():
|
||||
"""The build-time override mechanism must stay in place."""
|
||||
src = (_REPO / "electron/src/shared/utils/analytics.ts").read_text(encoding="utf-8")
|
||||
assert "VITE_POSTHOG_KEY" in src
|
||||
|
||||
|
||||
def test_release_workflow_still_passes_the_secret_to_the_build():
|
||||
wf = (_REPO / ".github/workflows/electron-release.yml").read_text(encoding="utf-8")
|
||||
assert "VITE_POSTHOG_KEY" in wf, "the build no longer receives the analytics token override"
|
||||
assert "secrets.POSTHOG_PROJECT_TOKEN" in wf, "the override must come from the repo secret"
|
||||
|
||||
|
||||
def test_the_shell_hands_the_token_to_the_backend_it_spawns():
|
||||
"""Without this a baked release token could never beat the in-repo default."""
|
||||
src = (_REPO / "electron/src/main/backend.ts").read_text(encoding="utf-8")
|
||||
assert "__POSTHOG_PROJECT_TOKEN__" in src, "the shell no longer bakes in the token"
|
||||
assert "POSTHOG_PROJECT_TOKEN" in src, "the backend process is no longer given the override"
|
||||
# #1193: the shell marks everything it spawns as the "installer" channel.
|
||||
|
||||
# option_env! is resolved at COMPILE time, so cargo must rebuild when the
|
||||
# secret changes — otherwise a cached build keeps the token it first saw.
|
||||
config = (_REPO / "electron/electron.vite.config.ts").read_text(encoding="utf-8")
|
||||
assert "VITE_POSTHOG_KEY" in config
|
||||
def test_the_destination_is_a_public_site_id_only():
|
||||
config = json.loads((_REPO / "config/analytics.json").read_text(encoding="utf-8"))
|
||||
assert set(config) == {"site", "host", "appUrl"}
|
||||
assert re.fullmatch(r"[a-z0-9]{6,32}", config["site"])
|
||||
assert config["host"] == "https://app.supermetry.com"
|
||||
assert config["appUrl"].startswith("https://")
|
||||
@@ -554,15 +554,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/77/f5/21d2de20e8b8b0408f0681956ca2c69f1320a3848ac50e6e7f39c6159675/babel-2.18.0-py3-none-any.whl", hash = "sha256:e2b422b277c2b9a9630c1d7903c2a00d0830c409c59ac8cae9081c92f1aeba35", size = 10196845, upload-time = "2026-02-01T12:30:53.445Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "backoff"
|
||||
version = "2.2.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/47/d7/5bbeb12c44d7c4f2fb5b56abce497eb5ed9f34d85701de869acedd602619/backoff-2.2.1.tar.gz", hash = "sha256:03f829f5bb1923180821643f8753b0502c3b682293992485b0eef2807afa5cba", size = 17001, upload-time = "2022-10-05T19:19:32.061Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/df/73/b6e24bd22e6720ca8ee9a85a0c4a2971af8497d8f3193fa05390cbd46e09/backoff-2.2.1-py3-none-any.whl", hash = "sha256:63579f9a0628e06278f7e47b7d7d5b6ce20dc65c5e96a6f3ca99a6adca0396e8", size = 15148, upload-time = "2022-10-05T19:19:30.546Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "beartype"
|
||||
version = "0.22.9"
|
||||
@@ -4067,7 +4058,6 @@ dependencies = [
|
||||
{ name = "pedalboard" },
|
||||
{ name = "pillow" },
|
||||
{ name = "pip" },
|
||||
{ name = "posthog" },
|
||||
{ name = "psutil" },
|
||||
{ name = "pyannote-audio" },
|
||||
{ name = "pydub" },
|
||||
@@ -4181,7 +4171,6 @@ requires-dist = [
|
||||
{ name = "pillow", specifier = ">=12.1.0" },
|
||||
{ name = "pip", specifier = ">=26.1.2" },
|
||||
{ name = "pocket-tts", marker = "(platform_machine != 'x86_64' and extra == 'pockettts') or (sys_platform != 'darwin' and extra == 'pockettts')", specifier = "==2.1.0" },
|
||||
{ name = "posthog", specifier = ">=3.7" },
|
||||
{ name = "psutil", specifier = ">=7.2.2" },
|
||||
{ name = "pyannote-audio", specifier = ">=3.3.2,<4.0" },
|
||||
{ name = "pydub" },
|
||||
@@ -4690,21 +4679,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/2a/2d/d4bf65e47cea8ff2c794a600c4fd1273a7902f268757c531e0ee9f18aa58/pooch-1.9.0-py3-none-any.whl", hash = "sha256:f265597baa9f760d25ceb29d0beb8186c243d6607b0f60b83ecf14078dbc703b", size = 67175, upload-time = "2026-01-30T19:15:08.36Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "posthog"
|
||||
version = "7.39.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "backoff" },
|
||||
{ name = "distro" },
|
||||
{ name = "requests" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/59/c0/5834e90300f65ccd5e873f2f63a879100c25bf1b63b17ee45e572f612aa5/posthog-7.39.2.tar.gz", hash = "sha256:bb74ac23f99054ea6ca25f76586cd6707b29afcffb5f0e78b0f16cc63019ed2b", size = 430654, upload-time = "2026-08-20T12:49:17.615Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e3/70/b4c01c2d066e81df0f09cce7bea0cde8ce115e8a1c69d907555af07b82b1/posthog-7.39.2-py3-none-any.whl", hash = "sha256:ca149ee4f6595a04150c2bea477995652384df45ca4db9ed372c0f81e0cd9646", size = 506980, upload-time = "2026-08-20T12:49:16.051Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "preshed"
|
||||
version = "3.0.13"
|
||||
|
||||
Reference in new issue
Block a user