bd8d5d07c0
* fix(playlist): synchronize Playlist for concurrent plugin/UI access Lua plugin callbacks run on goroutines (hooks, timers, keybinds) and read playlist state through StateProvider closures, while the Bubbletea loop mutates the same *Playlist. The struct had no synchronization, so reads of p.tracks/p.order/p.pos raced with Next/Prev/Add/Remove/shuffle, and Current()'s unguarded p.tracks[idx] could panic on a stale index. Add a sync.Mutex and guard every exported method. Reads and writes are now serialized; no exported method calls another, so defer-unlock cannot deadlock. Fixes the high-severity track/player getter race and the playlist-mutation data race. * fix(luaplugin): block SSRF in cliamp.http doHTTP passed plugin-supplied URLs straight to the HTTP client with no validation, letting a plugin reach loopback, RFC1918, and link-local 169.254.169.254 (cloud metadata), and follow redirects into those targets. Add an ssrfGuard on the dialer Control hook so every connection attempt (including redirects and DNS-rebound hosts) is checked against the resolved IP and rejected if non-public, and reject non-http(s) schemes up front. A per-plugin network permission gate remains a possible follow-up; it is omitted here to avoid breaking existing plugins that legitimately use http. * fix(pluginmgr): sandbox plugin VM during metadata extraction extractMetadata ran DoFile on the entire plugin file with full stdlib, so any top-level os.execute/io call ran unsandboxed the moment a user listed installed plugins. Apply the same luaplugin.Sandbox used by the runtime before executing the file. Exports luaplugin.Sandbox for reuse. * fix(luaplugin): error on oversized fs.read instead of silent truncation fs.read used os.ReadFile (whole file into memory) then sliced to 1MB, returning a silently truncated value as success and not bounding memory for huge files. Stream through io.LimitReader(maxSize+1) and return an explicit error when the file exceeds the limit. * fix(luaplugin): make write allowlist symlink-safe isWriteAllowed validated paths lexically: the strings.Contains(abs, "..") check was dead (filepath.Abs already cleans "..", and it false-positived on filenames like "..bar"), and a symlink planted inside an allowed dir could redirect a write outside it. Resolve symlinks on the deepest existing ancestor of the target and on the allow dirs themselves before the prefix check. Also fixes the same gap in the exec cwd check, which reuses this function. * fix(luaplugin): bound timer callbacks with hookTimeout timer.after/every called CallByParam directly with no context timeout, so a runaway callback held the plugin mutex forever, blocking every other hook, keybind, and visualizer for that plugin. Add a shared callBounded helper that applies hookTimeout (mirroring invokeHook) and use it from both timer paths. * fix(luaplugin): bound visualizer render/init/destroy with hookTimeout RenderVis runs on the UI render loop and called CallByParam with no timeout while holding the plugin mutex; a hanging render() froze the UI with no escape. InitVis/DestroyVis had the same gap. Route all three through callBounded so a misbehaving visualizer times out and render falls back to the previous frame. * fix(luaplugin): wait for async hook goroutines before closing LStates Emit spawned untracked goroutines that call CallByParam on a plugin LState. Close stopped timers/execs then closed every LState without waiting, so a UI event dispatched just before shutdown could run against an already-closed LState (p.L.Close does not take the plugin mutex). Track Emit goroutines in a WaitGroup, set a closing flag under mu to reject late dispatch, and Wait before closing the LStates. * fix(ui): guard spectrum visualizers against zero-width panel renderFirework/renderBubbles/renderSakura compute dotCols = PanelWidth*2 and then mod by dotCols/dotRows/len(bands); on a narrow terminal PanelWidth can be 0, so seed % uint64(dotCols) panicked and crashed the TUI. Add the same dotRows<4 || dotCols<4 early-out the braille-grid renderers already use. * fix(history): do not clobber history on a transient load error Record discarded loadLocked's error and proceeded as if history were empty, so a one-off read failure (permission/I-O glitch) made saveLocked atomically rewrite the file with only the new entry, destroying all prior rows. Propagate the error instead, leaving the on-disk file untouched. * fix(history): detect write errors before committing history file saveLocked ignored errors from writeEntry's formatted writes, so a failure mid-write (e.g. ENOSPC) could still rename a truncated temp file over the real history. Thread writes through an errWriter and abort the rename when a write fails. * fix(lyrics): stop cleanQuery from erasing titles with label words The noise regex matched official/lyric/audio/video as bare substrings followed by .*, so 'Videotape', 'Audioslave', and 'Video Games' were cleaned to empty or truncated queries, breaking lyric lookups. Restrict bare-label stripping to genuine trailing labels (dash suffix, or 'official video/audio' and 'lyric(s) video' phrases). Add regression test cases. * fix(jellyfin,emby): synchronize client token/userID/album cache Client.token, userID, and albumCache were lazily read and written from concurrent tea.Cmd goroutines (Playlists, album browse, SearchTracks all run in their own goroutines) with no synchronization, a data race on the lazy auth writes and the cached slice. Add a mutex guarding those fields, taken only around field access and never across network I/O, with double-checked auth so at most a redundant (not racy) auth can occur. * fix(ipc): close in-flight connections on shutdown handleConn's read loop only observed the 60s per-request read deadline, never s.done, and Close closed only the listener. A still-connected client (e.g. a vis-bands polling client) kept its handler goroutine alive, so Close blocked on wg.Wait for up to 60s. Track live connections and close them in Close so their scanner.Scan unblocks immediately; addConn shares the conn mutex with the done check to close the accept-during-shutdown race. * refactor(ipc): route all reply-waits through waitReply The reply/timeout/shutdown select was open-coded in load/theme/vis/bands/ status and waitReply was used elsewhere with a generic 'timeout' message. Parameterize waitReply with a label and timeout and use it everywhere, which also gives the previously-generic commands specific timeout messages. * fix(ipc): handle accept errors instead of spinning silently acceptLoop swallowed every non-shutdown Accept error and retried at 10/s, treating a permanently closed listener as transient. Return on net.ErrClosed and log other errors before backing off. * fix(ui): notify Lua plugins on jump-to-time seek The jump enter handler called notifyPlayback (MPRIS only) plus notifier.Seeked, skipping plugin notification. Use finishSeek, which calls notifyAll, so a jump seek emits the playback-state event to plugins like every other completed seek. Seek stays synchronous (immediate seek), matching the existing test. * fix(resolve): bound startup feed sniff with a short timeout Args runs on the startup path and called sniffFeedURL, which did a HEAD on the 30s feed/M3U client, so one slow CDN could stall cliamp startup for up to 30s during pure URL classification. Give the sniff a dedicated 5s client. * fix(pluginmgr): reject empty download body An empty 200 response left download returning a non-nil empty slice, so Install wrote a 0-byte plugin file. Treat an empty body as a download error so the next candidate URL is tried (or the install fails cleanly). * fix(pluginmgr): reject raw URLs with no usable filename A raw URL ending in '/' made path.Base yield '.' or '/', producing a degenerate plugin filename. Return a clear error instead. * fix(config): let --low-power=false override config-enabled low power The override only set LowPower when the flag was true, so --low-power=false could not disable a config.toml low_power=true. Assign the flag value directly, matching the other boolean overrides. * fix(main): log MPRIS/NowPlaying init failure instead of dropping it wireMediaCtl's error was silently discarded in TUI mode, so a dbus/MPRIS setup failure left media-control silently disabled with no trace. Log it to the app log (not stderr, which would corrupt the TUI). * docs(plugins): remove unimplemented player getters cliamp.player.eq_preset(), visualizer(), and theme() were documented but never registered in the player API (calling them errors). Implementing them would require exposing model state to plugin goroutines, which would add a data race; remove them from the docs so the reference matches the API. * fix(luaplugin): reject partial bands table in set_eq_preset A bands table missing entries silently zeroed the unset bands. Require all 10 values and raise an arg error otherwise so partial input can't corrupt the EQ curve. * fix(luaplugin): track EmitKey goroutines and gate on shutdown EmitKey spawned fire-and-forget goroutines per keypress that were untracked and not gated on shutdown, so a keypress during Close could call into a closed LState. Track them in the manager WaitGroup and skip dispatch once closing, matching Emit. * fix(mediactl): apply MPRIS volume changes in order Each volume Change spawned its own goroutine to send SetVolumeMsg, so rapid changes could be delivered out of order and an older volume win. send (prog.Send) is goroutine-safe and non-blocking, so call it directly. * fix(mediactl): reject stale-track MPRIS SetPosition trackid was a fixed constant for every track, so SetPosition ignored its trackID argument and would seek whatever track became current after the client read its position. Assign a unique track object path per track change and ignore SetPosition when its trackID does not match the current track. * fix(radio): write favorites atomically save() truncated the real favorites file with os.Create and ignored every write error, so a partial write could lose all favorites. Build the content in memory, write a temp file, and rename so a failed write can't corrupt the existing file and the error surfaces to the caller. * fix(radio): propagate save errors from ToggleFavorite ToggleFavorite discarded the error from Add/Remove (which persist favorites), so a failed save was silently swallowed. Return it to the caller. * refactor(spotify): drop pointless lock around local slice append The mutex around appending the Your Music entry only touched the function-local 'all' slice, guarding nothing shared (the other locks in the loop legitimately guard trackCache). * fix(spotify): return cloned playlist list, not the cache slice Playlists returned the cached slice directly (both on cache hit and after building it), so a caller mutating the result corrupted the cache. Return a clone on both paths. * fix(spotify): return cloned cached tracks Tracks handed out the cached track slice directly, so a caller mutating it corrupted the per-playlist cache. Clone on both the cache-hit and freshly built return paths. (The snapshot-based invalidation within the playlist-list TTL is an intentional caching tradeoff and is left as-is.) * fix(spotify): don't sleep before giving up on rate limit On the final retry the loop slept the full backoff (up to 128s) and then returned the rate-limited error without making another request. Break out immediately on the last attempt. * fix(jellyfin): guard AlbumList against negative offset A negative offset passed the offset>=len check and then panicked at out[offset:end]. Clamp offset to 0 first, matching the Emby client. * docs(playlist): correct MoveQueue comment MoveQueue swaps any two positions, not only adjacent ones. * refactor(ui): simplify dead math.Min in flame tier mapping math.Min(0.65, 0.55) is a constant 0.55; replace with the literal and drop the now-unused math import. * refactor(netease): compare app code against its own constant resp.Code is NetEase's application-level status, not an HTTP status; it was compared against http.StatusOK which only coincidentally shares the value 200. Introduce neteaseCodeOK and use it at all four comparison sites. * fix(resolve): strip audio extension from derived title humanizeBasename left a trailing extension (e.g. .mp3) in the title derived from a URL basename. Drop a recognized audio extension first, leaving non-media dotted suffixes untouched. * fix(resolve): bound RSS feed read size resolveFeed decoded the response body with no size limit. Wrap it in an io.LimitReader (32 MB) so an oversized or malicious feed can't exhaust memory. * fix(navidrome): return cloned cache slices Playlists and Tracks handed out the internal cached slices, so a caller mutating the result corrupted the cache. Return slices.Clone on the cache-hit and freshly built return paths. * fix(player): include ffmpeg stderr in decode error decodeFFmpeg wrapped the exec error but dropped ffmpeg's stderr, where the actual failure reason is written. Surface ExitError.Stderr in the message. * refactor(player): forward speedStreamer.Err directly beep.Streamer already declares Err() error, so the local errorer type assertion was redundant. Call ss.s.Err() directly, matching the eq and volume streamers. * fix(ui): don't drop queued seek/lyric cmds on reconnect When the scheduled stream reconnect fired, the tick handler returned early with only playTrack + tick, discarding the seekCmd/lyricCmd computed earlier in the same tick. Fold them into the reconnect batch. * fix(ui): nav list footer counts reflect committed filter The footer only showed the filtered count while the search input bar was open (searching); once a filter was committed with Enter it fell back to the full count. Add navFilteredTotal and use the filtered count whenever a query is active, across the artist, album, and track footers. * refactor: remove dead internal/control package internal/control duplicated the message types in internal/playback and had no importers (only its own test); the live code uses internal/playback. Remove it. * fix(providers): implement Refresh for self-hosted providers Navidrome, Plex, Jellyfin, and Emby cache playlist/track (and album) data but none implemented playlist.Refresher, so the UI refresh key was a silent no-op for them. Add Refresh to clear the caches (including the jellyfin/emby client album cache) so the next fetch hits the server. * refactor: share minimal-TOML section parser The [[section]] parse loop was duplicated three times (radio loadStations, radio loadFavoriteStations, local loadTOML). Extract tomlutil.ParseSections and rewrite all three against it. Behavior is preserved, including the single-section-type assumption of the original parsers. * refactor: extract shared Emby/Jellyfin client into internal/embyapi The emby and jellyfin clients were ~95% identical (~700 duplicated lines) and had already drifted (jellyfin lacked the negative-offset guard and error wrapping). Extract one shared Client into internal/embyapi, isolating the real differences behind a dialect: auth header scheme (Emby Authorization vs Jellyfin X-Emby-Authorization), ping endpoint, user-id discovery, error prefix, and metadata key. emby and jellyfin become thin wrappers (NewClient, IsStreamURL, type aliases) plus their providers. Client tests are consolidated in embyapi: shared behavior once, dialect specifics per dialect. The client now uses a per- instance http.Client (SetHTTPClient) instead of a package global, which is what makes it testable from the provider packages.
273 lines
7.5 KiB
Go
273 lines
7.5 KiB
Go
package luaplugin
|
|
|
|
import (
|
|
"context"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
lua "github.com/yuin/gopher-lua"
|
|
)
|
|
|
|
// SetReservedKeys records the set of keys owned by cliamp's core UI. Plugins
|
|
// attempting to bind one of these keys get a logged warning and their bind
|
|
// call returns false. Called once during startup from main.go.
|
|
func (m *Manager) SetReservedKeys(keys map[string]bool) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.reservedKeys = keys
|
|
}
|
|
|
|
// KeyBinding describes a plugin-registered keybinding for the Ctrl+K overlay.
|
|
type KeyBinding struct {
|
|
Key string
|
|
Plugin string
|
|
Description string
|
|
}
|
|
|
|
// KeyBindings returns a snapshot of every plugin-registered keybinding that
|
|
// has a description, sorted by key for stable overlay ordering. Bindings
|
|
// registered without a description are omitted — plugins can opt out of
|
|
// surfacing a key simply by skipping the description argument.
|
|
//
|
|
// Called once per Ctrl+K overlay open, so the sort cost is noise.
|
|
func (m *Manager) KeyBindings() []KeyBinding {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
out := make([]KeyBinding, 0, len(m.keyBindDescs))
|
|
for _, b := range m.keyBindDescs {
|
|
out = append(out, b)
|
|
}
|
|
sort.Slice(out, func(i, j int) bool { return out[i].Key < out[j].Key })
|
|
return out
|
|
}
|
|
|
|
// EmitKey invokes every plugin callback registered for the given key string.
|
|
// Returns true if at least one callback fired. Called by the UI's main key
|
|
// dispatcher for keys the core doesn't handle.
|
|
func (m *Manager) EmitKey(key string) bool {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
if m.closing {
|
|
return false
|
|
}
|
|
hooks := m.keyBinds[key]
|
|
if len(hooks) == 0 {
|
|
return false
|
|
}
|
|
|
|
label := "keybind " + key
|
|
for _, h := range hooks {
|
|
// Tracked in wg and gated on closing (same as Emit) so a keypress
|
|
// during shutdown can't call into a closed LState.
|
|
m.wg.Add(1)
|
|
go func(h *luaHook) {
|
|
defer m.wg.Done()
|
|
m.invokeHook(h, label, lua.LString(key))
|
|
}(h)
|
|
}
|
|
return true
|
|
}
|
|
|
|
// normalizeKey lowercases and strips whitespace so "Ctrl+X" and "ctrl+x"
|
|
// collide at registration and dispatch.
|
|
func normalizeKey(key string) string {
|
|
return strings.ToLower(strings.TrimSpace(key))
|
|
}
|
|
|
|
// registerKeymapAPI attaches :bind() / :unbind() to the plugin object returned
|
|
// by plugin.register(). Gated on permissions = {"keymap"}.
|
|
func (m *Manager) registerKeymapAPI(L *lua.LState, obj *lua.LTable, p *Plugin) {
|
|
warned := false
|
|
guard := func() bool {
|
|
if p.perms[PermKeymap] {
|
|
return true
|
|
}
|
|
if !warned && m.logger != nil {
|
|
m.logger.log(p.Name, "warn", "plugin:bind requires permissions = {\"keymap\"} — further warnings suppressed")
|
|
warned = true
|
|
}
|
|
return false
|
|
}
|
|
|
|
// p:bind(key, fn) → no entry in Ctrl+K overlay
|
|
// p:bind(key, description, fn) → with description (shown in overlay)
|
|
// Returns true on success; false, reason on failure.
|
|
L.SetField(obj, "bind", L.NewFunction(func(L *lua.LState) int {
|
|
key := normalizeKey(L.CheckString(2))
|
|
|
|
// Lua has no function overloading, so disambiguate by inspecting arg 3:
|
|
// function → old 2-arg form; anything else → (key, description, fn).
|
|
var description string
|
|
var fn *lua.LFunction
|
|
if L.Get(3).Type() == lua.LTFunction {
|
|
fn = L.CheckFunction(3)
|
|
} else {
|
|
description = strings.TrimSpace(L.CheckString(3))
|
|
fn = L.CheckFunction(4)
|
|
}
|
|
|
|
if !guard() {
|
|
L.Push(lua.LFalse)
|
|
L.Push(lua.LString("keymap permission required"))
|
|
return 2
|
|
}
|
|
if key == "" {
|
|
L.Push(lua.LFalse)
|
|
L.Push(lua.LString("empty key"))
|
|
return 2
|
|
}
|
|
|
|
m.mu.Lock()
|
|
if m.reservedKeys[key] {
|
|
m.mu.Unlock()
|
|
if m.logger != nil {
|
|
m.logger.log(p.Name, "warn", "refusing to bind %q: reserved by cliamp core", key)
|
|
}
|
|
L.Push(lua.LFalse)
|
|
L.Push(lua.LString("key reserved by cliamp: " + key))
|
|
return 2
|
|
}
|
|
m.keyBinds[key] = append(m.keyBinds[key], &luaHook{plugin: p, fn: fn})
|
|
if description != "" {
|
|
m.keyBindDescs[key] = KeyBinding{Key: key, Plugin: p.Name, Description: description}
|
|
}
|
|
m.mu.Unlock()
|
|
|
|
L.Push(lua.LTrue)
|
|
return 1
|
|
}))
|
|
|
|
// p:unbind(key)
|
|
L.SetField(obj, "unbind", L.NewFunction(func(L *lua.LState) int {
|
|
key := normalizeKey(L.CheckString(2))
|
|
m.mu.Lock()
|
|
m.keyBinds[key] = filterOutPlugin(m.keyBinds[key], p)
|
|
if len(m.keyBinds[key]) == 0 {
|
|
delete(m.keyBinds, key)
|
|
}
|
|
if desc, ok := m.keyBindDescs[key]; ok && desc.Plugin == p.Name {
|
|
delete(m.keyBindDescs, key)
|
|
}
|
|
m.mu.Unlock()
|
|
return 0
|
|
}))
|
|
}
|
|
|
|
// EmitCommand dispatches a plugin command invoked over IPC and blocks up to
|
|
// commandTimeout for the handler to return a result. A missing plugin/command
|
|
// returns ("", err); a handler error returns ("", err); success returns
|
|
// (result, nil). The result is whatever the handler returned as a string
|
|
// (nil or false stringifies to "").
|
|
func (m *Manager) EmitCommand(pluginName, cmdName string, args []string) (string, error) {
|
|
m.mu.RLock()
|
|
plugCmds, ok := m.commands[pluginName]
|
|
var hook *luaHook
|
|
if ok {
|
|
hook = plugCmds[cmdName]
|
|
}
|
|
m.mu.RUnlock()
|
|
if hook == nil {
|
|
return "", errCommandNotFound(pluginName, cmdName)
|
|
}
|
|
|
|
type result struct {
|
|
out string
|
|
err error
|
|
}
|
|
done := make(chan result, 1)
|
|
|
|
go func() {
|
|
hook.plugin.mu.Lock()
|
|
defer hook.plugin.mu.Unlock()
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), commandTimeout)
|
|
defer cancel()
|
|
hook.plugin.L.SetContext(ctx)
|
|
defer hook.plugin.L.RemoveContext()
|
|
|
|
argsTbl := hook.plugin.L.NewTable()
|
|
for i, a := range args {
|
|
argsTbl.RawSetInt(i+1, lua.LString(a))
|
|
}
|
|
|
|
err := hook.plugin.L.CallByParam(lua.P{
|
|
Fn: hook.fn,
|
|
NRet: 1,
|
|
Protect: true,
|
|
}, argsTbl)
|
|
if err != nil {
|
|
done <- result{err: err}
|
|
return
|
|
}
|
|
ret := hook.plugin.L.Get(-1)
|
|
hook.plugin.L.Pop(1)
|
|
done <- result{out: luaValueToString(ret)}
|
|
}()
|
|
|
|
select {
|
|
case r := <-done:
|
|
return r.out, r.err
|
|
case <-time.After(commandTimeout + time.Second):
|
|
return "", errCommandTimeout(pluginName, cmdName)
|
|
}
|
|
}
|
|
|
|
// CommandList returns a flat list of "<plugin> <command>" strings. Used by
|
|
// `cliamp plugin commands`. Order is unspecified.
|
|
func (m *Manager) CommandList() []string {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
var out []string
|
|
for plug, cmds := range m.commands {
|
|
for cmd := range cmds {
|
|
out = append(out, plug+" "+cmd)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// commandTimeout caps how long a plugin command handler may run before we
|
|
// return an error to the IPC client. Five minutes is generous — enough for
|
|
// yt-dlp downloads — while ensuring the socket client doesn't hang forever.
|
|
const commandTimeout = 5 * time.Minute
|
|
|
|
func errCommandNotFound(plug, cmd string) error {
|
|
return &commandError{msg: "no such plugin command: " + plug + " " + cmd}
|
|
}
|
|
func errCommandTimeout(plug, cmd string) error {
|
|
return &commandError{msg: "plugin command timed out: " + plug + " " + cmd}
|
|
}
|
|
|
|
type commandError struct{ msg string }
|
|
|
|
func (e *commandError) Error() string { return e.msg }
|
|
|
|
func luaValueToString(v lua.LValue) string {
|
|
if v == lua.LNil || v == lua.LFalse {
|
|
return ""
|
|
}
|
|
return v.String()
|
|
}
|
|
|
|
// registerCommandAPI attaches :command() to the plugin object. Unlike keymap,
|
|
// commands don't need a permission — they're user-initiated from the shell.
|
|
func (m *Manager) registerCommandAPI(L *lua.LState, obj *lua.LTable, p *Plugin) {
|
|
// p:command(name, fn) — fn(args) -> optional result string
|
|
L.SetField(obj, "command", L.NewFunction(func(L *lua.LState) int {
|
|
name := strings.TrimSpace(L.CheckString(2))
|
|
fn := L.CheckFunction(3)
|
|
if name == "" {
|
|
L.ArgError(2, "empty command name")
|
|
return 0
|
|
}
|
|
m.mu.Lock()
|
|
if m.commands[p.Name] == nil {
|
|
m.commands[p.Name] = make(map[string]*luaHook)
|
|
}
|
|
m.commands[p.Name][name] = &luaHook{plugin: p, fn: fn}
|
|
m.mu.Unlock()
|
|
return 0
|
|
}))
|
|
}
|