Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 33 additions & 7 deletions dashboard/static/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2275,6 +2275,20 @@ function outputUrl(path) {
return `${baseUrl()}/files/${safePath}`;
}

function downloadableOutputUrl(path) {
const candidate = outputUrl(path);
if (candidate.startsWith("blob:")) return candidate;
try {
const url = new URL(candidate, window.location.href);
const backendOrigin = new URL(baseUrl(), window.location.href).origin;
if (!new Set([window.location.origin, backendOrigin]).has(url.origin)) return "";
if (url.protocol !== "http:" && url.protocol !== "https:") return "";
return url.href;
} catch {
return "";
}
}

function wavetableExportUrl(id, format = "gwt") {
if (!id) return "#";
return `${baseUrl()}/wavetables/${encodeURIComponent(id)}/export?format=${encodeURIComponent(format)}`;
Expand Down Expand Up @@ -2336,8 +2350,8 @@ function metadataSummary(metadata) {
return pieces.filter(Boolean).join(" | ");
}

function trackChips(metadata) {
if (!metadata) return "<span>provider -</span><span>model -</span><span>seed -</span>";
function trackChipValues(metadata) {
if (!metadata) return ["provider -", "model -", "seed -"];
const mode = metadata.germinator_mode || modeAliases[metadata.mode] || metadata.mode;
return [
`provider ${metadata.provider || "-"}`,
Expand All @@ -2347,9 +2361,16 @@ function trackChips(metadata) {
`seed ${metadata.seed ?? "-"}`,
`cfg ${metadata.cfg_scale ?? "-"}`,
`steps ${metadata.steps ?? "-"}`,
]
.map((item) => `<span>${escapeHtml(item)}</span>`)
.join("");
];
}

function renderTrackChips(target, metadata) {
const chips = trackChipValues(metadata).map((value) => {
const chip = document.createElement("span");
chip.textContent = String(value);
return chip;
});
target.replaceChildren(...chips);
}

async function setCurrentTrack(audioPath, metadataPath, metadata = null) {
Expand All @@ -2372,7 +2393,7 @@ async function setCurrentTrack(audioPath, metadataPath, metadata = null) {
$("trackTitle").textContent = displayNameFromPath(audioPath);
$("audioPath").value = audioPath;
$("metadataPath").value = metadataPath || loadedMetadata?.metadata_path || "";
$("trackMeta").innerHTML = trackChips(loadedMetadata);
renderTrackChips($("trackMeta"), loadedMetadata);
$("audioPlayer").src = outputUrl(audioPath);
$("playPauseBtn").disabled = false;
$("playhead").disabled = false;
Expand Down Expand Up @@ -20779,8 +20800,13 @@ if ($("downloadBtn")) {
$("downloadBtn").addEventListener("click", () => {
const path = $("audioPath")?.value;
if (!path) return;
const href = downloadableOutputUrl(path);
if (!href) {
setState("Download Blocked", "warn", "The selected sound does not have a trusted download URL.");
return;
}
const a = document.createElement("a");
a.href = outputUrl(path);
a.href = href;
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
a.download = path.split("/").pop() || "download.wav";
document.body.appendChild(a);
a.click();
Expand Down
17 changes: 8 additions & 9 deletions server/huggingface_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,18 +75,18 @@ def auth_status() -> dict[str, Any]:
"detail": None,
}
if not result["available"]:
status["detail"] = result["stderr"]
status["detail"] = "Hugging Face CLI is unavailable."
return status

if result["returncode"] != 0:
detail = (result["stderr"] or result["stdout"]).strip()
status["detail"] = detail or "hf auth whoami failed."
status["detail"] = "Hugging Face CLI authentication is unavailable."
return status

try:
account = json.loads(result["stdout"] or "{}")
except (json.JSONDecodeError, RecursionError):
account = {"raw": result["stdout"].strip()}
status["detail"] = "Hugging Face CLI returned an unreadable account response."
return status

status["logged_in"] = True
status["account"] = account
Expand All @@ -99,11 +99,10 @@ def model_access_status(repo_id: str) -> dict[str, Any]:
base = {
"repo": repo_id,
"file": "model_config.json",
"command": result["command"],
"returncode": result["returncode"],
}
if not result["available"]:
return {**base, "status": "hf_missing", "detail": result["stderr"]}
return {**base, "status": "hf_missing", "detail": "Hugging Face CLI is unavailable."}

output = f"{result['stdout']}\n{result['stderr']}".strip()
lowered = output.lower()
Expand All @@ -113,11 +112,11 @@ def model_access_status(repo_id: str) -> dict[str, Any]:
return {
**base,
"status": "requires_approval_or_login",
"detail": output,
"detail": "Model access requires accepted terms and an authenticated read token.",
}
if "not logged in" in lowered or "401" in lowered or "unauthorized" in lowered:
return {**base, "status": "not_logged_in", "detail": output}
return {**base, "status": "error", "detail": output}
return {**base, "status": "not_logged_in", "detail": "Hugging Face authentication is required."}
return {**base, "status": "error", "detail": "Hugging Face model access check failed."}


def stable_audio_hf_status(*, check_models: bool = False) -> dict[str, Any]:
Expand Down
5 changes: 4 additions & 1 deletion server/routes/cosmoaudition.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import json
import logging
from pathlib import Path
from typing import Any, Literal
from uuid import uuid4
Expand All @@ -26,6 +27,7 @@
router = APIRouter(prefix="/cosmoaudition", tags=["cosmoaudition"])
MAX_ARCHIVES = 12
MAX_ARCHIVE_BYTES = 1_000_000
LOGGER = logging.getLogger(__name__)


def _bridge() -> CosmoauditionBridge:
Expand All @@ -37,11 +39,12 @@ def _bridge() -> CosmoauditionBridge:


def _bridge_status_from_error(exc: Exception) -> dict[str, Any]:
LOGGER.warning("Cosmoaudition bridge unavailable: %s", exc)
return {
"available": False,
"contract": COSMOAUDITION_GERM_CONTRACT,
"baseUrl": settings.cosmoaudition_url,
"error": str(exc)[:2_000],
"error": "Cosmoaudition bridge unavailable",
}


Expand Down
17 changes: 13 additions & 4 deletions server/routes/lora.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,35 @@
from __future__ import annotations

import logging

from fastapi import APIRouter

from server.registry import registry
from server.schemas import LoraLoadRequest, LoraStrengthRequest


router = APIRouter()
LOGGER = logging.getLogger(__name__)


@router.post("/lora/load")
def load_lora(request: LoraLoadRequest) -> dict:
try:
return registry.get(request.provider).load_lora(request.paths)
except Exception as exc:
return {"status": "error", "provider": request.provider, "error": str(exc)}
except Exception:
LOGGER.exception("LoRA load failed for provider %s", request.provider)
return {"status": "error", "provider": request.provider, "error": "LoRA load failed"}


@router.post("/lora/strength")
def set_lora_strength(request: LoraStrengthRequest) -> dict:
try:
provider = registry.get(request.provider)
return provider.set_lora_strength(request.strength, request.lora_index)
except Exception as exc:
return {"status": "error", "provider": request.provider, "error": str(exc)}
except Exception:
LOGGER.exception("LoRA strength update failed for provider %s", request.provider)
return {
"status": "error",
"provider": request.provider,
"error": "LoRA strength update failed",
}
8 changes: 6 additions & 2 deletions server/routes/strains.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
from __future__ import annotations

import logging

from fastapi import APIRouter, HTTPException

from server.registry import registry, strain_registry
from server.schemas import StrainCard, StrainLoadRequest, StrainRegistryResponse


router = APIRouter(prefix="/strains", tags=["strains"])
LOGGER = logging.getLogger(__name__)


@router.get("", response_model=StrainRegistryResponse)
Expand Down Expand Up @@ -50,8 +53,9 @@ def load_strains(request: StrainLoadRequest) -> dict:
raise HTTPException(status_code=404, detail=f"strain not found: {exc.args[0]}") from exc
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
except Exception as exc:
return {"status": "error", "provider": request.provider, "error": str(exc)}
except Exception:
LOGGER.exception("strain load failed for provider %s", request.provider)
return {"status": "error", "provider": request.provider, "error": "strain load failed"}
return {
**result,
"provider": request.provider,
Expand Down
5 changes: 4 additions & 1 deletion server/storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -1043,7 +1043,10 @@ async def save_upload_stream(
) -> tuple[Path, int]:
stem = safe_stem(Path(filename).stem, fallback="upload")
suffix = safe_suffix(Path(filename).suffix)
target_dir = Path(directory) if directory is not None else self.upload_dir
target_dir = (Path(directory) if directory is not None else self.upload_dir).resolve()
allowed_upload_roots = (self.upload_dir.resolve(), self.scratch_dir.resolve())
if not any(self.is_within(target_dir, root) for root in allowed_upload_roots):
raise ValueError("upload directory must be inside a managed upload root")
target_dir.mkdir(parents=True, exist_ok=True)
path = target_dir / f"{stem}_{uuid4().hex[:8]}{suffix}"
total = 0
Expand Down
5 changes: 4 additions & 1 deletion server/wavetable.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@


def note_to_frequency(note: str) -> float:
match = re.fullmatch(r"\s*([A-Ga-g])([#b]?)(-?\d+)\s*", note or "")
normalized = str(note or "").strip()
if len(normalized) > 5:
raise ValueError(f"invalid note name: {note}")
match = re.fullmatch(r"([A-Ga-g])([#b]?)(-?[0-9]{1,2})", normalized)
if not match:
raise ValueError(f"invalid note name: {note}")
note_name, accidental, octave_text = match.groups()
Expand Down
41 changes: 41 additions & 0 deletions tests/test_server.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import asyncio
import base64
import io
import json
Expand Down Expand Up @@ -49,6 +50,7 @@
MAX_TRACKED_JOBS,
MAX_TRACKED_JOBS_HARD,
)
from server.wavetable import note_to_frequency


client = TestClient(app)
Expand Down Expand Up @@ -908,6 +910,20 @@ def get_json(self, path: str, *, params: dict | None = None) -> dict:
assert deleted.status_code == 200


def test_cosmoaudition_bridge_errors_do_not_expose_backend_details(
monkeypatch: pytest.MonkeyPatch,
) -> None:
class FailingBridge:
def status(self) -> dict:
raise ValueError("private backend path: /Users/listener/secret")

monkeypatch.setattr(cosmoaudition_routes, "_bridge", lambda: FailingBridge())
response = client.get("/cosmoaudition/status")
assert response.status_code == 200
assert response.json()["error"] == "Cosmoaudition bridge unavailable"
assert "secret" not in response.text


@pytest.mark.parametrize(
("value", "expected"),
[
Expand Down Expand Up @@ -1088,6 +1104,31 @@ def test_huggingface_status_reports_cli_auth_without_model_check() -> None:
assert body["models_checked"] is False


def test_note_parser_rejects_oversized_or_ambiguous_input() -> None:
assert note_to_frequency(" C#4 ") == pytest.approx(277.1826309768721)
for value in ("C" + "0" * 10_000, "C4 trailing"):
with pytest.raises(ValueError, match="invalid note name"):
note_to_frequency(value)
with pytest.raises(ValueError, match="outside the supported MIDI range"):
note_to_frequency("C99")


def test_upload_stream_rejects_directory_outside_managed_roots(tmp_path: Path) -> None:
class Upload:
async def read(self, _size: int) -> bytes:
return b"payload"

with pytest.raises(ValueError, match="managed upload root"):
asyncio.run(
storage.save_upload_stream(
filename="outside.wav",
upload=Upload(),
max_bytes=1024,
directory=tmp_path,
)
)


def test_mock_generate_creates_wav_and_metadata() -> None:
response = client.post(
"/generate",
Expand Down
Loading