VoiceStudio is the open-source, fully-local ElevenLabs alternative — voice cloning, voice design, video dubbing, dictation, transcription & audiobook creation in 646 languages.
Python aiaudiobookcudadubbingelevenlabs-alternativehuggingfacelocal-firstmlxomnivoice-studiospeech-to-texttext-to-speechtranscriptiontranslatettsvoice-aivoice-cloningvoice-generationvoicestudioworkflow
ci: add manual VirusTotal scans and source archive precautions
Shimul Debnath220034942385
diff --git a/.gitattributes b/.gitattributesindex 55343929c..a70852822 100644--- a/.gitattributes+++ b/.gitattributes@@ -6,3 +6,7 @@ mobile/android/app/src/main/assets/licenses/*.txt text eol=lf# Windows batch files break goto/labels with LF endings.*.bat text eol=crlf++# Repository-only moderation tests contain copied scam commands. Keep them in+# Git checkouts/CI, but do not distribute attack examples in source archives.+/tests/test_scam_guard.py export-ignorediff --git a/.github/SECURITY.md b/.github/SECURITY.mdindex 5613675c7..784aa7deb 100644--- a/.github/SECURITY.md+++ b/.github/SECURITY.md@@ -68,6 +68,65 @@ Every pull request and push to `main` runs [`.github/workflows/security.yml`](woPull requests are additionally reviewed by the **CodeRabbit** and **Greptile**GitHub Apps on creation.+## Source archives++GitHub source ZIPs and tarballs omit `tests/test_scam_guard.py` through+`.gitattributes` (`export-ignore`). This repository-only moderation test contains+copied scam commands and encoded-command examples that can trigger antivirus+heuristics when distributed as source text. Git clones and CI retain the test+and its full coverage; the moderation script and application/build files remain+in source archives. Clone the repository to run the complete test suite.++This packaging precaution does not establish which file caused an antivirus+verdict or guarantee a clean scan. Confirm any reported detection against the+specific file inside the archive and rescan a newly generated archive after a+change.++### Manual VirusTotal check++Run `make virustotal` to create and upload the **committed HEAD** source ZIP,+using the same archive exclusions as GitHub. Commit changes before checking a+future source download. To check an existing ZIP, installer, or individual+public script, use `make virustotal FILE=/path/to/file` instead. Local edits and+untracked files are not included in the default archive.++For a remote scan, set the repository Actions secret `VIRUSTOTAL_API_KEY` and+manually dispatch [the VirusTotal workflow](workflows/virustotal.yml):++```bash+gh workflow run virustotal.yml --repo debpalash/VoiceStudio --ref main+```++The workflow must first be merged into the default branch. It scans the+selected branch's committed source ZIP, keeps API usage serial, and adds the+report link and vendor results to the Actions run summary even if detections+fail the job. Local `make virustotal` cannot read repository Actions secrets;+it uses the local prompt/environment described below.++The command asks for your API key at a hidden prompt without saving it, or reads+`VIRUSTOTAL_API_KEY` from the environment. Obtain a key from your+[VirusTotal account](https://docs.virustotal.com/reference/getting-started);+never commit the key or paste it into an issue. Python 3.11+, Git and Make are+required (`make virustotal PYTHON=python` if that is your Python executable).++Uploads enter VirusTotal's shared dataset: use this command only for public+source/artifacts, not recordings, models, user data or private files. This is a+manual maintainer tool; the app, automatic CI and releases never invoke it. The+[Public API terms](https://docs.virustotal.com/reference/public-vs-premium-api)+limit use to 4 requests/minute and 500/day and exclude commercial products or+services and business workflows that do not contribute new files. Use an+appropriate paid licence when those terms do not cover your use.++The tool spaces requests 16 seconds apart, automatically requests the+[large-file upload URL](https://docs.virustotal.com/reference/files-upload-url)+above 32 MiB, and streams files up to 650 MiB. It prints the SHA-256, report URL,+analysis ID and flagged vendor labels, and waits up to 10 minutes for results.+Exit status is 0 for a completed analysis with no flags, 1 for malicious or+suspicious detections, and 2 for errors or an inconclusive/pending analysis.+Timeouts and unsupported engines are not evidence that a file is safe.+For upload-only use, run `python3 scripts/virustotal.py FILE --no-wait`; its+successful exit means the upload was accepted, not that a clean scan completed.+## Security Best Practices for Users- **Do not expose VoiceStudio beyond loopback without authentication.** The API is unauthenticated on loopback by default. Before remote access, set `OMNIVOICE_API_KEY` (or enable the in-app share PIN for LAN guests) as described in [API authentication](../docs/api-auth.md), and use TLS through a reverse proxy or a private network such as Tailscale.diff --git a/.github/workflows/virustotal.yml b/.github/workflows/virustotal.ymlnew file mode 100644index 000000000..c5a2dbc43--- /dev/null+++ b/.github/workflows/virustotal.yml@@ -0,0 +1,54 @@+# Manual upload of the selected branch's committed source ZIP to VirusTotal.+# Never run on PR/push/release events: uploads are public and consume API quota.+name: VirusTotal++on:+ workflow_dispatch:++env:+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true++permissions:+ contents: read++# One scan at a time for the repository's Public API key.+concurrency:+ group: virustotal-public-api+ cancel-in-progress: false++jobs:+ scan:+ name: Scan source ZIP+ runs-on: ubuntu-24.04+ timeout-minutes: 15+ defaults:+ run:+ shell: bash+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0+ with:+ persist-credentials: false+ - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0+ with:+ python-version: '3.11'+ - name: Upload and wait for vendor results+ env:+ VIRUSTOTAL_API_KEY: ${{ secrets.VIRUSTOTAL_API_KEY }}+ run: |+ if [ -z "$VIRUSTOTAL_API_KEY" ]; then+ echo '::error::Set the VIRUSTOTAL_API_KEY repository Actions secret.'+ exit 2+ fi+ set -o pipefail+ make virustotal 2>&1 | tee "$RUNNER_TEMP/virustotal-report.txt"+ - name: Add report link and results to summary+ if: always()+ run: |+ if [ -f "$RUNNER_TEMP/virustotal-report.txt" ]; then+ {+ echo '## VirusTotal source scan'+ echo '```text'+ cat "$RUNNER_TEMP/virustotal-report.txt"+ echo '```'+ } >> "$GITHUB_STEP_SUMMARY"+ fidiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 470ebdbe0..30665b478 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,8 @@ metadata and the backend fallback mirror it.### Changed+- Source ZIPs and tarballs omit scam-moderation attack examples; Git clones and CI retain their regression tests (#3208, #3211)+- Maintainers can upload public source ZIPs or individual files with `make virustotal`, or scan a branch through the manual VirusTotal Actions workflow (#3208, #3211)- Small models now install with as little as 2 GB spare disk; the setup check only warns below 10 GB instead of blocking (#2969)- iOS Home shows Electron's contributor avatars, Dub is redesigned around one source card with animated icons, and the iOS bottom dock is icon-only (#2969)- Model licence review on iOS and Android opens with a plain summary, rights rows and licence links; the raw terms move under Exact terms (#2969)diff --git a/Makefile b/Makefileindex 98d7da551..66f1e7523 100644--- a/Makefile+++ b/Makefile@@ -1,7 +1,8 @@-# Maintainer shortcuts. The only target today is the release helper-# (docs/RELEASING.md → Release helper); everything else uses bun/uv directly.+# Maintainer shortcuts; product development uses bun/uv directly.-.PHONY: release release-dry release-publish+.PHONY: release release-dry release-publish virustotal++PYTHON ?= python3release: ## Cut a release: asks stable/beta, draft/publish, then confirmsuv run python scripts/release.py@@ -12,3 +13,7 @@ release-dry: ## Show the release plan, change nothingrelease-publish: ## Publish an existing draft: make release-publish TAG=v0.5.8@test -n "$(TAG)" || { echo "usage: make release-publish TAG=vX.Y.Z[-beta.N]"; exit 2; }uv run python scripts/release.py --publish $(TAG)++virustotal: export VIRUSTOTAL_FILE = $(FILE)+virustotal: ## Upload committed HEAD source ZIP, or make virustotal FILE=/path/to/public/file+ $(PYTHON) scripts/virustotal.pydiff --git a/scripts/virustotal.py b/scripts/virustotal.pynew file mode 100644index 000000000..3baaf658e--- /dev/null+++ b/scripts/virustotal.py@@ -0,0 +1,209 @@+#!/usr/bin/env python3+"""Manually upload a public file (default: committed HEAD source ZIP) to VirusTotal."""+from __future__ import annotations++import argparse+import getpass+import hashlib+import json+import os+from pathlib import Path+import re+import subprocess+import sys+import tempfile+import time+from urllib.error import HTTPError, URLError+from urllib.parse import quote, urlsplit+from urllib.request import build_opener, HTTPRedirectHandler, Request+import uuid++ROOT = Path(__file__).resolve().parents[1]+API = "https://www.virustotal.com/api/v3"+DIRECT_LIMIT = 32 * 1024 * 1024+MAX_SIZE = 650 * 1024 * 1024+REQUEST_INTERVAL = 16 # Public API: at most four requests per minute.+++class ScanError(RuntimeError):+ pass+++class NoRedirects(HTTPRedirectHandler):+ def redirect_request(self, req, fp, code, msg, headers, newurl):+ # Never forward the API credential or uploaded bytes to a redirect.+ return None+++def validate_url(url: str) -> str:+ parsed = urlsplit(url)+ if (parsed.scheme != "https" or parsed.hostname != "www.virustotal.com"+ or parsed.port not in (None, 443) or parsed.username or parsed.password+ or parsed.fragment):+ raise ScanError("VirusTotal returned an unexpected upload URL; refusing to send the file/key.")+ return url+++def multipart(path: Path, boundary: str):+ # Send a basename only; never expose the local directory in the multipart header.+ filename = re.sub(r"[^A-Za-z0-9._-]", "_", path.name)+ head = (f"--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; "+ f"filename=\"{filename}\"\r\nContent-Type: application/octet-stream\r\n\r\n").encode()+ tail = f"\r\n--{boundary}--\r\n".encode()++ def chunks():+ yield head+ with path.open("rb") as stream:+ while chunk := stream.read(1024 * 1024):+ yield chunk+ yield tail++ return chunks(), len(head) + path.stat().st_size + len(tail)+++class Client:+ def __init__(self, key: str):+ self.key = key+ self.opener = build_opener(NoRedirects())+ self.last_request = None++ def request(self, method: str, url: str, *, file: Path | None = None,+ deadline: float | None = None) -> dict:+ validate_url(url)+ delay = 0+ if self.last_request is not None:+ delay = REQUEST_INTERVAL - (time.monotonic() - self.last_request)+ if deadline is not None and time.monotonic() + max(delay, 0) >= deadline:+ raise ScanError("Analysis is still pending. Open the report link for results; no clean verdict was returned.")+ if delay > 0:+ time.sleep(delay)+ headers = {"x-apikey": self.key, "Accept": "application/json"}+ data = None+ if file is not None:+ boundary = uuid.uuid4().hex+ data, length = multipart(file, boundary)+ headers.update({"Content-Type": f"multipart/form-data; boundary={boundary}",+ "Content-Length": str(length)})+ self.last_request = time.monotonic()+ request = Request(url, data=data, headers=headers, method=method)+ timeout = 120 if deadline is None else min(120, max(0.001, deadline - time.monotonic()))+ try:+ with self.opener.open(request, timeout=timeout) as response:+ return json.load(response)+ except HTTPError as error:+ status = error.code+ error.close()+ if status == 429:+ raise ScanError("VirusTotal quota reached (HTTP 429). Retry later; other clients share this key's quota.") from None+ if status in (401, 403):+ raise ScanError(f"VirusTotal authorization failed (HTTP {status}); check VIRUSTOTAL_API_KEY and API access.") from None+ raise ScanError(f"VirusTotal request failed (HTTP {status}).") from None+ except (URLError, TimeoutError, OSError):+ raise ScanError("VirusTotal connection failed or timed out. Check the report before retrying an upload.") from None+ except (ValueError, TypeError):+ raise ScanError("VirusTotal returned invalid JSON.") from None++ def upload(self, path: Path) -> str:+ size = path.stat().st_size+ if not 0 < size <= MAX_SIZE:+ raise ScanError("Upload must be nonempty and at most 650 MiB.")+ url = f"{API}/files"+ if size > DIRECT_LIMIT:+ url = self.request("GET", f"{API}/files/upload_url")["data"]+ if not isinstance(url, str):+ raise ScanError("VirusTotal returned an invalid upload URL.")+ result = self.request("POST", url, file=path)+ analysis_id = result.get("data", {}).get("id")+ if not isinstance(analysis_id, str) or not analysis_id:+ raise ScanError("VirusTotal did not return an analysis ID.")+ return analysis_id++ def wait(self, analysis_id: str, timeout: int) -> dict:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ response = self.request("GET", f"{API}/analyses/{quote(analysis_id, safe='')}", deadline=deadline)+ attributes = response.get("data", {}).get("attributes", {})+ status = attributes.get("status")+ if status == "completed":+ return attributes+ if status not in ("queued", "in-progress"):+ raise ScanError("VirusTotal returned an unknown analysis status.")+ print(f"Analysis {status}; waiting…", flush=True)+ raise ScanError("Analysis is still pending. Open the report link for results; no clean verdict was returned.")+++def summarize(attributes: dict) -> int:+ if attributes.get("status") != "completed":+ raise ScanError("Analysis is incomplete; no clean verdict was returned.")+ stats = attributes.get("stats", {})+ if not isinstance(stats, dict) or any(type(value) is not int or value < 0 for value in stats.values()):+ raise ScanError("VirusTotal returned invalid scan statistics.")+ print("Engine results:", json.dumps(stats, sort_keys=True))+ for engine, result in sorted(attributes.get("results", {}).items()):+ if result.get("category") in ("malicious", "suspicious"):+ print(f" {engine}: {result.get('result') or result['category']}")+ if stats.get("malicious", 0) or stats.get("suspicious", 0):+ return 1+ if not stats.get("harmless", 0) and not stats.get("undetected", 0):+ raise ScanError("No engine returned an evaluable result; no clean verdict was returned.")+ print("No engines flagged this file in the completed analysis.")+ return 0+++def source_archive(destination: Path) -> None:+ # Match GitHub's committed tree and export-ignore rules. Local changes are+ # deliberately excluded; use an explicit file to scan a prepared candidate.+ subprocess.run(["git", "archive", "--format=zip", "--prefix=VoiceStudio-main/",+ "-o", str(destination), "HEAD"], cwd=ROOT, check=True)+++def main(argv=None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("file", nargs="?", default=os.environ.get("VIRUSTOTAL_FILE") or None,+ help="Public file to upload; default: source ZIP of committed HEAD")+ parser.add_argument("--no-wait", action="store_true", help="Print the report link after upload without polling")+ parser.add_argument("--timeout", type=int, default=600, help="Analysis wait budget in seconds (default: 600)")+ args = parser.parse_args(argv)+ if args.timeout <= 0:+ parser.error("--timeout must be positive")+ key = os.environ.get("VIRUSTOTAL_API_KEY", "").strip()+ if not key and sys.stdin.isatty():+ try:+ key = getpass.getpass("VirusTotal API key (hidden, not saved): ").strip()+ except (EOFError, KeyboardInterrupt):+ print("No API key entered; nothing uploaded.", file=sys.stderr)+ return 2+ if not key:+ print("Set VIRUSTOTAL_API_KEY or run interactively to enter it at the hidden prompt.", file=sys.stderr)+ return 2+ try:+ with tempfile.TemporaryDirectory(prefix="voicestudio-virustotal-") as temporary:+ path = Path(args.file).expanduser().resolve() if args.file else Path(temporary) / "VoiceStudio-main.zip"+ if args.file is None:+ source_archive(path)+ print("Source: committed HEAD (local changes excluded).")+ if not path.is_file():+ raise ScanError("Upload path must be an existing file.")+ with path.open("rb") as stream:+ digest = hashlib.file_digest(stream, "sha256").hexdigest()+ print(f"File: {path.name} ({path.stat().st_size} bytes)\nSHA-256: {digest}", flush=True)+ print("Uploading to VirusTotal's shared dataset…", flush=True)+ client = Client(key)+ analysis_id = client.upload(path)+ print(f"Report: https://www.virustotal.com/gui/file/{digest}\nAnalysis ID: {analysis_id}", flush=True)+ if args.no_wait:+ print("Upload accepted; analysis verdict is pending.")+ return 0+ return summarize(client.wait(analysis_id, args.timeout))+ except (ScanError, OSError, subprocess.CalledProcessError, KeyError, TypeError) as error:+ # Do not print server bodies, request headers, or credential-bearing URLs.+ message = str(error) if isinstance(error, ScanError) else "Could not prepare the file or process the VirusTotal response."+ print(f"Error: {message}", file=sys.stderr)+ return 2+ except KeyboardInterrupt:+ print("Interrupted; an accepted upload may still be processing at the report link.", file=sys.stderr)+ return 130+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/test_source_archive.py b/tests/test_source_archive.pynew file mode 100644index 000000000..82afa53f3--- /dev/null+++ b/tests/test_source_archive.py@@ -0,0 +1,48 @@+"""Exercise the source-archive boundary with Git's actual ZIP/tar exporters."""++import io+from pathlib import Path+import shutil+import subprocess+import tarfile+import unittest+import zipfile+++ROOT = Path(__file__).resolve().parents[1]+SCAM_TEST = "tests/test_scam_guard.py"+REQUIRED = (+ ".github/scripts/scam_guard.py",+ "tests/test_cla_workflow.py",+ "scripts/install.ps1",+ "scripts/install.sh",+ "electron/tests/packaging-contract.mjs",+ "electron/package.json",+ "pyproject.toml",+ "LICENSE",+)++[email protected]((ROOT / ".git").exists() and shutil.which("git"), "requires a Git checkout")+class SourceArchiveTests(unittest.TestCase):+ def test_attack_examples_stay_in_checkout_but_not_source_archives(self):+ self.assertTrue((ROOT / SCAM_TEST).is_file(), "CI must retain scam-guard coverage")+ for archive_format in ("zip", "tar"):+ with self.subTest(archive_format=archive_format):+ archive = subprocess.run(+ ["git", "archive", "--worktree-attributes", f"--format={archive_format}",+ "HEAD", "--", SCAM_TEST, *REQUIRED],+ cwd=ROOT, check=True, capture_output=True,+ ).stdout+ if archive_format == "zip":+ with zipfile.ZipFile(io.BytesIO(archive)) as bundle:+ names = set(bundle.namelist())+ else:+ with tarfile.open(fileobj=io.BytesIO(archive)) as bundle:+ names = set(bundle.getnames())+ self.assertNotIn(SCAM_TEST, names)+ self.assertTrue(set(REQUIRED) <= names, f"Required source files missing: {set(REQUIRED) - names}")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_virustotal.py b/tests/test_virustotal.pynew file mode 100644index 000000000..20e8dda89--- /dev/null+++ b/tests/test_virustotal.py@@ -0,0 +1,202 @@+"""Offline tests for upload routing, credential handling and scan verdicts."""+import contextlib+import importlib.util+import io+import json+import os+from pathlib import Path+import tempfile+import subprocess+import unittest+from unittest.mock import Mock, patch+from urllib.error import HTTPError, URLError+++ROOT = Path(__file__).resolve().parents[1]+SPEC = importlib.util.spec_from_file_location("virustotal_scan", ROOT / "scripts/virustotal.py")+vt = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(vt)+++def response(payload):+ return io.BytesIO(json.dumps(payload).encode())+++class VirusTotalTests(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.path = Path(self.temporary.name) / 'public "sample".zip'+ self.path.write_bytes(b"public sample bytes\x00\xff")+ self.client = vt.Client("private-test-key")+ self.client.opener = Mock()++ def test_small_upload_streams_multipart_with_exact_length_and_basename(self):+ sent = []++ def upload(request, **kwargs):+ body = b"".join(request.data)+ self.assertEqual(int(request.get_header("Content-length")), len(body))+ self.assertIn(self.path.read_bytes(), body)+ self.assertIn(b'filename="public__sample_.zip"', body)+ self.assertNotIn(str(self.path.parent).encode(), body)+ self.assertEqual(request.get_header("X-apikey"), "private-test-key")+ sent.append(request.full_url)+ return response({"data": {"id": "analysis-1"}})++ self.client.opener.open.side_effect = upload+ self.assertEqual(self.client.upload(self.path), "analysis-1")+ self.assertEqual(sent, [f"{vt.API}/files"])++ def test_large_upload_gets_one_use_url_then_uploads(self):+ upload_url = "https://www.virustotal.com/_ah/upload/one-use-token"+ self.client.opener.open.side_effect = [response({"data": upload_url}), response({"data": {"id": "large"}})]+ with patch.object(vt, "DIRECT_LIMIT", 1), patch.object(vt.time, "sleep"):+ self.assertEqual(self.client.upload(self.path), "large")+ requests = [call.args[0] for call in self.client.opener.open.call_args_list]+ self.assertEqual([(r.get_method(), r.full_url) for r in requests],+ [("GET", f"{vt.API}/files/upload_url"), ("POST", upload_url)])++ def test_empty_or_oversize_files_make_no_requests(self):+ for limit in (0, 1):+ with self.subTest(limit=limit), patch.object(vt, "MAX_SIZE", limit):+ with self.assertRaises(vt.ScanError):+ self.client.upload(self.path)+ self.path.write_bytes(b"")+ with self.assertRaises(vt.ScanError):+ self.client.upload(self.path)+ self.client.opener.open.assert_not_called()++ def test_untrusted_upload_url_cannot_receive_file_or_key(self):+ for url in ("http://www.virustotal.com/upload", "https://evil.example/upload",+ "https://www.virustotal.com.evil.example/upload",+ "https://[email protected]/upload", "https://www.virustotal.com:444/upload"):+ with self.subTest(url=url), patch.object(vt, "DIRECT_LIMIT", 1):+ self.client.opener.open.reset_mock()+ self.client.opener.open.side_effect = None+ self.client.opener.open.return_value = response({"data": url})+ with patch.object(vt.time, "sleep"), self.assertRaises(vt.ScanError):+ self.client.upload(self.path)+ self.assertEqual(self.client.opener.open.call_count, 1)++ def test_redirects_never_forward_credentials(self):+ self.assertIsNone(vt.NoRedirects().redirect_request(None, None, 302, "", {}, "https://evil.example"))++ def test_requests_respect_public_api_interval(self):+ self.client.opener.open.side_effect = [response({}), response({})]+ with patch.object(vt.time, "monotonic", side_effect=[100, 103, 116]), patch.object(vt.time, "sleep") as sleep:+ self.client.request("GET", f"{vt.API}/files/upload_url")+ self.client.request("GET", f"{vt.API}/analyses/test")+ sleep.assert_called_once_with(13)++ def test_api_errors_are_actionable_without_echoing_credentials_or_body(self):+ for code in (401, 403, 429, 500):+ with self.subTest(code=code):+ self.client.last_request = None+ self.client.opener.open.side_effect = HTTPError(+ "https://www.virustotal.com/private-test-key", code, "private-test-key", {},+ io.BytesIO(b"private-test-key"))+ with self.assertRaises(vt.ScanError) as caught:+ self.client.request("GET", f"{vt.API}/analyses/test")+ self.assertIn(str(code), str(caught.exception))+ self.assertNotIn("private-test-key", str(caught.exception))+ self.client.last_request = None+ self.client.opener.open.side_effect = URLError("private-test-key")+ with self.assertRaises(vt.ScanError) as caught:+ self.client.request("GET", f"{vt.API}/analyses/test")+ self.assertNotIn("private-test-key", str(caught.exception))++ def test_polling_waits_for_completed_analysis(self):+ completed = {"status": "completed", "stats": {"undetected": 1}, "results": {}}+ self.client.request = Mock(side_effect=[{"data": {"attributes": {"status": "queued"}}},+ {"data": {"attributes": completed}}])+ with contextlib.redirect_stdout(io.StringIO()):+ self.assertEqual(self.client.wait("id/with=characters", 600), completed)+ self.assertTrue(self.client.request.call_args.args[1].endswith("id%2Fwith%3Dcharacters"))++ def test_timeout_is_not_a_clean_verdict(self):+ with patch.object(vt.time, "monotonic", side_effect=[0, 601]):+ with self.assertRaisesRegex(vt.ScanError, "pending"):+ self.client.wait("analysis", 600)++ def test_poll_deadline_prevents_waiting_for_another_quota_slot(self):+ self.client.last_request = 100+ with patch.object(vt.time, "monotonic", return_value=101), patch.object(vt.time, "sleep") as sleep:+ with self.assertRaisesRegex(vt.ScanError, "pending"):+ self.client.request("GET", f"{vt.API}/analyses/test", deadline=110)+ sleep.assert_not_called()+ self.client.opener.open.assert_not_called()++ def test_flagged_engines_fail_but_unsupported_only_is_inconclusive(self):+ for category in ("malicious", "suspicious"):+ with self.subTest(category=category), contextlib.redirect_stdout(io.StringIO()) as output:+ self.assertEqual(vt.summarize({"status": "completed", "stats": {category: 1},+ "results": {"ExampleEngine": {"category": category, "result": "example-label"}}}), 1)+ self.assertIn("ExampleEngine: example-label", output.getvalue())+ with contextlib.redirect_stdout(io.StringIO()):+ with self.assertRaises(vt.ScanError):+ vt.summarize({"status": "completed", "stats": {"type-unsupported": 58}})+ self.assertEqual(vt.summarize({"status": "completed", "stats": {"undetected": 58}}), 0)+ with self.assertRaises(vt.ScanError):+ vt.summarize({"status": "in-progress", "stats": {"undetected": 1}})++ def test_missing_key_fails_before_archive_or_network(self):+ with patch.dict(os.environ, {}, clear=True), patch.object(vt.sys.stdin, "isatty", return_value=False), \+ patch.object(vt, "Client") as client, patch.object(vt, "source_archive") as archive, \+ contextlib.redirect_stderr(io.StringIO()):+ self.assertEqual(vt.main([]), 2)+ client.assert_not_called()+ archive.assert_not_called()++ def test_file_override_and_no_wait_print_link_without_key(self):+ client = Mock()+ client.upload.return_value = "analysis-1"+ with patch.dict(os.environ, {"VIRUSTOTAL_API_KEY": "private-test-key", "VIRUSTOTAL_FILE": str(self.path)}), \+ patch.object(vt, "Client", return_value=client), patch.object(vt, "source_archive") as archive, \+ contextlib.redirect_stdout(io.StringIO()) as output:+ self.assertEqual(vt.main(["--no-wait"]), 0)+ client.upload.assert_called_once_with(self.path)+ client.wait.assert_not_called()+ archive.assert_not_called()+ self.assertIn("https://www.virustotal.com/gui/file/", output.getvalue())+ self.assertIn("pending", output.getvalue())+ self.assertNotIn("private-test-key", output.getvalue())++ @unittest.skipUnless((ROOT / ".git").exists(), "requires a Git checkout")+ def test_default_archive_uses_committed_tree_instead_of_local_edits(self):+ import zipfile++ archive_path = Path(self.temporary.name) / "source.zip"+ vt.source_archive(archive_path)+ committed_attributes = subprocess.check_output(["git", "show", "HEAD:.gitattributes"], cwd=ROOT)+ with zipfile.ZipFile(archive_path) as archive:+ self.assertEqual(archive.read("VoiceStudio-main/.gitattributes"), committed_attributes)+ self.assertNotIn("VoiceStudio-main/.env", archive.namelist())++ def test_make_passes_file_override_without_needing_a_live_api(self):+ import shutil++ if not shutil.which("make"):+ self.skipTest("Make is unavailable")+ missing_file = Path(self.temporary.name) / "missing public file.zip"+ result = subprocess.run(+ ["make", "virustotal", f"FILE={missing_file}", f"PYTHON={vt.sys.executable}"],+ cwd=ROOT, capture_output=True, text=True,+ env={**os.environ, "VIRUSTOTAL_API_KEY": "private-test-key"},+ )+ self.assertNotEqual(result.returncode, 0)+ self.assertIn("Upload path must be an existing file", result.stderr)+ self.assertNotIn("private-test-key", result.stdout + result.stderr)++ def test_plain_make_keeps_the_existing_release_default(self):+ import shutil++ if not shutil.which("make"):+ self.skipTest("Make is unavailable")+ result = subprocess.run(["make", "-n"], cwd=ROOT, capture_output=True, text=True, check=True)+ self.assertIn("uv run python scripts/release.py", result.stdout)+ self.assertNotIn("virustotal.py", result.stdout)+++if __name__ == "__main__":+ unittest.main()