From 516ab5056173d5b1e1bc00e365df2f8fe0c58788 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 8 Sep 2026 03:41:19 +0000 Subject: [PATCH 1/2] fix: guard malformed lyric segments and fix LRC timestamp/header bugs - /export raised UnicodeEncodeError (500) for any title/artist with a character outside Latin-1 (CJK, Cyrillic, emoji, ...), because Starlette encodes Content-Disposition header values as Latin-1 and the legacy filename= fallback was never folded to ASCII. Extracted the fold already used by the karaoke plugin into _ascii_safe_filename_component() and applied it here too. - _format_lrc / _format_lrc_word_level computed minutes/seconds independently (int(t // 60), f"{t % 60:05.2f}"), so a seconds remainder that rounds up to 60.00 under :05.2f (e.g. 59.996) printed an invalid timestamp like [01:60.00] instead of rolling into the next minute. New _lrc_timestamp() rounds to whole centiseconds first, then splits into minutes/seconds, so the carry happens before formatting. - Both formatters, and /save's segment-to-lyrics conversion, indexed seg["start"]/seg["text"]/seg["end"] directly, so a malformed segment (missing key, non-numeric start/end, a non-dict entry) raised KeyError/TypeError and 500'd the whole request instead of being skipped (/export) or reported as a clear 400 (/save). - Bumped plugin.json to 1.1.2 (bug fixes affecting real behavior). Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01HVxQShyx8Mrqe1GKNstjHy --- plugin.json | 2 +- routes.py | 111 ++++++++++++++++++++++++++++++++++-------- tests/test_helpers.py | 52 ++++++++++++++++++++ 3 files changed, 144 insertions(+), 21 deletions(-) diff --git a/plugin.json b/plugin.json index f293d90..d2ff310 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "id": "lyrics_sync", "name": "Lyrics Sync", - "version": "1.1.1", + "version": "1.1.2", "private": false, "nav": { "label": "Lyrics Sync", diff --git a/routes.py b/routes.py index 1b2f1b9..5801cf0 100644 --- a/routes.py +++ b/routes.py @@ -2,6 +2,7 @@ import json import os +import re import shutil import zipfile from pathlib import Path, PurePosixPath, PureWindowsPath @@ -163,14 +164,55 @@ def _find_vocals_stem(filename: str) -> Path | None: return None +def _ascii_safe_filename_component(name: str) -> str: + """Fold `name` to printable ASCII for use in the legacy `filename=` + Content-Disposition fallback. + + Starlette/Werkzeug-style header encoding treats header VALUES as + Latin-1 (RFC 7230), so any character above U+00FF (CJK, Cyrillic, + emoji, ...) raises UnicodeEncodeError at response-send time if it + reaches that header raw — turning a perfectly ordinary title/artist + into a 500. The `filename*=` RFC 5987 form (built separately, from the + unfolded name) still carries the real UTF-8 name via percent-encoding + regardless, so this fallback only needs to be non-crashing, not exact. + """ + return re.sub(r"[^\x20-\x7e]", "_", name) + + +def _lrc_timestamp(t: float) -> str: + """Format a time in seconds as an LRC "mm:ss.xx" timestamp. + + Computing minutes/seconds separately with `int(t // 60)` / + `f"{t % 60:05.2f}"` looks right but isn't: `:05.2f` rounds its operand, + so a seconds remainder like 59.996 prints as "60.00" instead of rolling + into the next minute — e.g. t=119.999 produced the invalid + "[01:60.00]" rather than "[02:00.00]". Round to whole centiseconds + FIRST, then split into minutes/seconds, so the rollover happens before + formatting rather than during it. + """ + total_centis = round(max(0.0, float(t)) * 100) + minutes, centis = divmod(total_centis, 6000) + return f"{minutes:02d}:{centis / 100:05.2f}" + + def _format_lrc(segments: list[dict]) -> str: - """Convert alignment segments to standard LRC format.""" + """Convert alignment segments to standard LRC format. + + Segments come from the alignment server's JSON response (or, for + /export, straight from the request body) — parseable JSON, but not + guaranteed to carry the keys this needs. A malformed segment (missing + `start`, a non-numeric `start`) is skipped rather than raising + KeyError/TypeError and 500ing the whole export. + """ lines = [] for seg in segments: - t = seg["start"] - minutes = int(t // 60) - seconds = t % 60 - lines.append(f"[{minutes:02d}:{seconds:05.2f}]{seg['text']}") + if not isinstance(seg, dict): + continue + try: + t = float(seg["start"]) + except (KeyError, TypeError, ValueError): + continue + lines.append(f"[{_lrc_timestamp(t)}]{seg.get('text', '')}") return "\n".join(lines) + "\n" @@ -178,20 +220,26 @@ def _format_lrc_word_level(segments: list[dict]) -> str: """Convert word-level alignment segments to enhanced LRC format.""" lines = [] for seg in segments: - t = seg["start"] - minutes = int(t // 60) - seconds = t % 60 - text = seg["text"] + if not isinstance(seg, dict): + continue + try: + t = float(seg["start"]) + except (KeyError, TypeError, ValueError): + continue + text = seg.get("text", "") # Word-level: include inline timestamps for each word if "words" in seg: word_parts = [] for w in seg["words"]: - wt = w["start"] - wm = int(wt // 60) - ws = wt % 60 - word_parts.append(f"<{wm:02d}:{ws:05.2f}>{w['text']}") + if not isinstance(w, dict): + continue + try: + wt = float(w["start"]) + except (KeyError, TypeError, ValueError): + continue + word_parts.append(f"<{_lrc_timestamp(wt)}>{w.get('text', '')}") text = " ".join(word_parts) - lines.append(f"[{minutes:02d}:{seconds:05.2f}]{text}") + lines.append(f"[{_lrc_timestamp(t)}]{text}") return "\n".join(lines) + "\n" @@ -381,11 +429,11 @@ def ls_export(data: dict): Returns: LRC file download. """ segments = data.get("segments", []) - if not segments: + if not isinstance(segments, list) or not segments: return JSONResponse({"error": "No segments provided"}, 400) - title = data.get("title", "") - artist = data.get("artist", "") + title = data.get("title", "") if isinstance(data.get("title", ""), str) else "" + artist = data.get("artist", "") if isinstance(data.get("artist", ""), str) else "" # Build LRC header + body header_lines = [] @@ -406,7 +454,11 @@ def ls_export(data: dict): # title-artist can't corrupt or break out of the header value. # The `\` escape is a no-op today (safe_name already stripped `\` # above) but guards this line if that stripping ever changes. - ascii_name = safe_name.replace("\\", "\\\\").replace('"', '\\"') + # _ascii_safe_filename_component folds anything outside printable + # ASCII to `_` in the legacy fallback only; `filename*=` below still + # carries the real UTF-8 name via percent-encoding regardless. + ascii_safe_name = _ascii_safe_filename_component(safe_name) + ascii_name = ascii_safe_name.replace("\\", "\\\\").replace('"', '\\"') encoded_name = quote(f"{safe_name}.lrc", safe="") return Response( @@ -436,6 +488,25 @@ def ls_save(data: dict): if not filename or not segments: return JSONResponse({"error": "filename and segments required"}, 400) + if not isinstance(segments, list): + return JSONResponse({"error": "segments must be a list"}, 400) + + # Validate up front: the loop below indexes seg["text"]/["start"]/["end"] + # and peeks segments[i + 1] for the granularity-aware line-break logic, + # so a malformed segment (missing key, non-numeric start/end, a + # non-dict entry — e.g. a truncated /align response, or a hand-crafted + # request) would otherwise raise KeyError/TypeError/AttributeError and + # 500 the whole save instead of reporting a clear 400. + for i, seg in enumerate(segments): + if not isinstance(seg, dict): + return JSONResponse({"error": f"segment {i} is not an object"}, 400) + if not isinstance(seg.get("text"), str): + return JSONResponse({"error": f"segment {i} is missing a string 'text'"}, 400) + try: + float(seg["start"]) + float(seg["end"]) + except (KeyError, TypeError, ValueError): + return JSONResponse({"error": f"segment {i} has a non-numeric start/end"}, 400) resolved = _resolve_sloppak(filename) if resolved is None: @@ -468,8 +539,8 @@ def ls_save(data: dict): if is_line_end and not text.endswith("+"): text = text + "+" lyrics_data.append({ - "t": round(seg["start"], 3), - "d": round(seg["end"] - seg["start"], 3), + "t": round(float(seg["start"]), 3), + "d": round(float(seg["end"]) - float(seg["start"]), 3), "w": text, }) diff --git a/tests/test_helpers.py b/tests/test_helpers.py index ee957bc..8debdbb 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -212,6 +212,19 @@ def test_format_lrc_empty_segments_yields_trailing_newline_only(): assert routes._format_lrc([]) == "\n" +def test_ascii_safe_filename_component_folds_non_latin1_chars(): + # Starlette encodes header values as Latin-1; anything above U+00FF must + # be folded before it reaches a raw `filename=` fallback or the response + # raises UnicodeEncodeError at send time. + folded = routes._ascii_safe_filename_component("\u7c73\u6d25\u7384\u5e2b - Lemon") + assert folded == "____ - Lemon" + folded.encode("latin-1") # must not raise + + +def test_ascii_safe_filename_component_leaves_ascii_untouched(): + assert routes._ascii_safe_filename_component("My Song - Artist") == "My Song - Artist" + + def test_format_lrc_word_level_inlines_word_timestamps(): segments = [ {"start": 0.0, "text": "Hello World", "words": [ @@ -221,3 +234,42 @@ def test_format_lrc_word_level_inlines_word_timestamps(): ] lrc = routes._format_lrc_word_level(segments) assert lrc == "[00:00.00]<00:00.00>Hello <00:00.50>World\n" + + +def test_lrc_timestamp_rolls_seconds_into_next_minute_on_rounding(): + # int(t // 60) + f"{t % 60:05.2f}" independently truncates the minute and + # rounds the seconds, so a value like 119.999 used to print the invalid + # "01:60.00" instead of rolling over to "02:00.00". Round to whole + # centiseconds first, then split, so the carry happens before formatting. + assert routes._lrc_timestamp(119.999) == "02:00.00" + assert routes._lrc_timestamp(59.996) == "01:00.00" + assert routes._lrc_timestamp(65.0) == "01:05.00" + assert routes._lrc_timestamp(0.0) == "00:00.00" + + +def test_format_lrc_skips_malformed_segments_instead_of_raising(): + segments = [ + {"start": 1.0, "text": "kept"}, + {"text": "missing start"}, + "not a dict", + {"start": "not a number", "text": "bad start"}, + None, + ] + assert routes._format_lrc(segments) == "[00:01.00]kept\n" + + +def test_format_lrc_missing_text_defaults_to_empty_string(): + assert routes._format_lrc([{"start": 1.0}]) == "[00:01.00]\n" + + +def test_format_lrc_word_level_skips_malformed_words(): + segments = [ + {"start": 0.0, "text": "Hello World", "words": [ + {"start": 0.0, "text": "Hello"}, + {"text": "no start, dropped"}, + "not a dict", + {"start": 0.5, "text": "World"}, + ]}, + ] + lrc = routes._format_lrc_word_level(segments) + assert lrc == "[00:00.00]<00:00.00>Hello <00:00.50>World\n" From bd4b088995c361577ad7452165f8fb7ac4ef2cee Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 8 Sep 2026 22:39:46 +0000 Subject: [PATCH 2/2] fix: reject non-finite start/end and null words instead of crashing/corrupting Infinity/NaN (via literal "Infinity"/"nan" or an overflowing literal like 1e999) parsed fine as floats and slipped past every existing malformed- segment guard: - /export: _lrc_timestamp's round(inf * 100) raised OverflowError, 500ing the whole export. - /save: the same values passed validation and were persisted as literal Infinity/NaN in lyrics.json (json.dumps' default allow_nan=True) -- unreadable by both the frontend's JSON.parse and ls_get_lyrics' own allow_nan=False serializer, corrupting the song. Added math.isfinite checks alongside the existing float() conversions in _format_lrc, _format_lrc_word_level, and ls_save's /save validation. Also hardened _format_lrc_word_level against "words": null -- iterating it directly raised TypeError outside any try/except. Checking isinstance(seg.get("words"), list) rejects None the same way it already rejected any other non-list shape. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01HVxQShyx8Mrqe1GKNstjHy --- plugin.json | 2 +- routes.py | 17 ++++++++++++----- tests/test_helpers.py | 39 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 6 deletions(-) diff --git a/plugin.json b/plugin.json index d2ff310..b9569e0 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "id": "lyrics_sync", "name": "Lyrics Sync", - "version": "1.1.2", + "version": "1.1.3", "private": false, "nav": { "label": "Lyrics Sync", diff --git a/routes.py b/routes.py index 5801cf0..3394c75 100644 --- a/routes.py +++ b/routes.py @@ -1,6 +1,7 @@ """Lyrics Sync plugin — author, time-align, and hand-edit synced lyrics.""" import json +import math import os import re import shutil @@ -212,6 +213,8 @@ def _format_lrc(segments: list[dict]) -> str: t = float(seg["start"]) except (KeyError, TypeError, ValueError): continue + if not math.isfinite(t): + continue lines.append(f"[{_lrc_timestamp(t)}]{seg.get('text', '')}") return "\n".join(lines) + "\n" @@ -226,9 +229,11 @@ def _format_lrc_word_level(segments: list[dict]) -> str: t = float(seg["start"]) except (KeyError, TypeError, ValueError): continue + if not math.isfinite(t): + continue text = seg.get("text", "") # Word-level: include inline timestamps for each word - if "words" in seg: + if isinstance(seg.get("words"), list): word_parts = [] for w in seg["words"]: if not isinstance(w, dict): @@ -237,6 +242,8 @@ def _format_lrc_word_level(segments: list[dict]) -> str: wt = float(w["start"]) except (KeyError, TypeError, ValueError): continue + if not math.isfinite(wt): + continue word_parts.append(f"<{_lrc_timestamp(wt)}>{w.get('text', '')}") text = " ".join(word_parts) lines.append(f"[{_lrc_timestamp(t)}]{text}") @@ -503,10 +510,12 @@ def ls_save(data: dict): if not isinstance(seg.get("text"), str): return JSONResponse({"error": f"segment {i} is missing a string 'text'"}, 400) try: - float(seg["start"]) - float(seg["end"]) + seg_start = float(seg["start"]) + seg_end = float(seg["end"]) except (KeyError, TypeError, ValueError): return JSONResponse({"error": f"segment {i} has a non-numeric start/end"}, 400) + if not (math.isfinite(seg_start) and math.isfinite(seg_end)): + return JSONResponse({"error": f"segment {i} has a non-finite start/end"}, 400) resolved = _resolve_sloppak(filename) if resolved is None: @@ -647,8 +656,6 @@ def ls_save_lyrics(data: dict): if not isinstance(raw_lyrics, list): return JSONResponse({"error": "lyrics must be a list"}, 400) - import math - lyrics_data = [] for item in raw_lyrics: if not isinstance(item, dict): diff --git a/tests/test_helpers.py b/tests/test_helpers.py index 8debdbb..2265822 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -273,3 +273,42 @@ def test_format_lrc_word_level_skips_malformed_words(): ] lrc = routes._format_lrc_word_level(segments) assert lrc == "[00:00.00]<00:00.00>Hello <00:00.50>World\n" + + +def test_format_lrc_word_level_tolerates_null_words_field(): + # "words": null iterated directly (`for w in seg["words"]`) raises + # TypeError outside any try/except -- a 500 on otherwise well-formed + # input. `isinstance(seg.get("words"), list)` must reject None the + # same way it rejects any other non-list shape. + segments = [{"start": 0.0, "text": "Hello", "words": None}] + assert routes._format_lrc_word_level(segments) == "[00:00.00]Hello\n" + + +def test_format_lrc_skips_non_finite_start_instead_of_raising(): + # float("inf")/float("nan") parse without raising, so the existing + # KeyError/TypeError/ValueError guard doesn't catch them -- they used + # to reach _lrc_timestamp's `round(inf * 100)`, which raises + # OverflowError ("cannot convert float infinity to integer") and 500s + # the export. Same for the numeric-literal overflow case (1e999 is inf). + segments = [ + {"start": 1.0, "text": "kept"}, + {"start": float("inf"), "text": "inf dropped"}, + {"start": float("-inf"), "text": "-inf dropped"}, + {"start": float("nan"), "text": "nan dropped"}, + {"start": 1e999, "text": "overflow-literal dropped"}, + ] + assert routes._format_lrc(segments) == "[00:01.00]kept\n" + + +def test_format_lrc_word_level_skips_non_finite_start_and_word_start(): + segments = [ + {"start": float("inf"), "text": "seg dropped", "words": [ + {"start": 0.0, "text": "irrelevant"}, + ]}, + {"start": 0.0, "text": "kept", "words": [ + {"start": float("nan"), "text": "word dropped"}, + {"start": 0.5, "text": "kept-word"}, + ]}, + ] + lrc = routes._format_lrc_word_level(segments) + assert lrc == "[00:00.00]<00:00.50>kept-word\n"