From e127cce77ea0fcb272851a2de43c4e8d41a44233 Mon Sep 17 00:00:00 2001 From: topkoa Date: Sun, 19 Jul 2026 00:35:08 -0400 Subject: [PATCH 1/4] fix: drive sliders from the song's actual stems The mixer rendered six hardcoded sliders for every song: dead sliders on songs without stems (drags silently no-oped), and no slider at all for stems outside the six known ids, which played at full volume with no control. Track per-song availability (stems:state provider-ready when the stems plugin is loaded, the bootstrap poll otherwise; null until either reports) and render slider rows from it: only the song's stems get rows, a stem-less song gets a "No stems available" notice, unknown availability keeps the old six. Unknown stem ids are now first-class: sanitizeState keeps their levels (so they persist and survive profiles), the audio-map gains exact id detection from data-stem and /stems/ paths, and the legacy gain-node wiring and level pushes follow the dynamic list. Co-Authored-By: Claude Fable 5 Signed-off-by: topkoa --- README.md | 11 +-- plugin.json | 2 +- screen.js | 216 ++++++++++++++++++++++++++++++++------------ tests/state.test.js | 40 ++++++++ 4 files changed, 204 insertions(+), 65 deletions(-) diff --git a/README.md b/README.md index 0a5bc5d..80592af 100644 --- a/README.md +++ b/README.md @@ -6,13 +6,10 @@ ## Features -- Per-stem volume controls for: - - Guitar - - Bass - - Voice - - Drums - - Piano - - Other +- Per-stem volume controls, matching the stems the current song actually has + (Guitar, Bass, Voice, Drums, Piano, Other — plus any other stem id found in + the song, e.g. Strings or Synth). Songs without stems show a "No stems + available" notice instead of dead sliders. - 8-band graphic EQ. - EQ profiles with dropdown selection. - `Output autolevel` toggle to keep output loudness more consistent. diff --git a/plugin.json b/plugin.json index e65fc6b..58dca9e 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "id": "stem_mixer", "name": "Stem Mixer", - "version": "1.2.1", + "version": "1.3.0", "private": false, "nav": { "label": "Stem Mixer", diff --git a/screen.js b/screen.js index c250b4b..f0966d2 100644 --- a/screen.js +++ b/screen.js @@ -96,6 +96,11 @@ let appliedLevels = Object.create(null); let lastUiUpdateAt = 0; const tokenReCache = Object.create(null); + // The current song's stem ids. Three-valued: null = not known yet (render the + // default six, exactly the pre-availability behavior), [] = known to have no + // stems (render the "no stems" message), non-empty = render exactly these. + let availableStems = null; + let onStemsStateEvent = null; function invalidateAudioCaches() { stemAudioMapCache = null; @@ -122,6 +127,16 @@ next.levels[stem] = Number.isFinite(n) ? Math.max(0, Math.min(1, n)) : 1; }); + // Songs can carry stems beyond the six known ids ("strings", "synth", …). + // Their levels live in the same map; keep them or every reload silently + // resets those stems to full volume. + Object.keys((rawState.levels && typeof rawState.levels === 'object') ? rawState.levels : {}).forEach((key) => { + const canonical = canonicalStemId(key); + if (!canonical || canonical === 'full' || canonical in next.levels) return; + const n = Number(rawState.levels[key]); + if (Number.isFinite(n)) next.levels[canonical] = Math.max(0, Math.min(1, n)); + }); + EQ_BANDS.forEach((_, idx) => { const n = Number(rawState.eq && rawState.eq[idx]); next.eq[idx] = Number.isFinite(n) ? Math.max(-12, Math.min(12, n)) : 0; @@ -204,6 +219,31 @@ return STEM_ALIASES[String(stemId || '').toLowerCase()] || String(stemId || '').toLowerCase(); } + // Canonical, deduped stem ids from whatever shape the source hands us — + // string arrays (stems:state stemIds), object arrays (stems.getState() rows). + // The reserved "full" mixdown is not a mixable stem and is dropped. + function normalizeAvailableStems(ids) { + const out = []; + (Array.isArray(ids) ? ids : []).forEach((entry) => { + const raw = (entry && typeof entry === 'object') ? entry.id : entry; + const canonical = canonicalStemId(raw); + if (canonical && canonical !== 'full' && !out.includes(canonical)) out.push(canonical); + }); + return out; + } + + function setAvailableStems(ids) { + const next = ids == null ? null : normalizeAvailableStems(ids); + if (JSON.stringify(next) === JSON.stringify(availableStems)) return; + availableStems = next; + queueUiUpdate(); + } + + // What the slider surfaces should show right now. + function displayStems() { + return Array.isArray(availableStems) ? availableStems : STEM_KEYS; + } + function safeDecodeUrl(url) { const src = String(url || ''); if (!src) return ''; @@ -287,6 +327,12 @@ const dataStem = String((audio.dataset && audio.dataset.stem) || '').toLowerCase(); const joined = `${id} ${cls} ${src} ${srcDecoded} ${dataStem}`; + // Exact-id detection first: data-stem or a /stems/. path names + // the stem outright, whatever the id — including ones outside STEM_KEYS. + // The token heuristics below stay as a fallback for the six known ids. + const exact = canonicalStemId(dataStem) || stemIdFromUrl(srcDecoded) || stemIdFromUrl(src); + if (exact && exact !== 'full' && !map[exact]) map[exact] = audio; + STEM_KEYS.forEach((stem) => { const stemAlias = stem === 'vocals' ? ['voice', 'vocals', 'vocal'] : [stem]; const byDataAttr = stemAlias.some(alias => dataStem === alias); @@ -395,7 +441,7 @@ if (!ctx || !filterChain.length) return; const map = getStemAudioMap(); - STEM_KEYS.forEach((stem) => { + Object.keys(map).forEach((stem) => { const audio = map[stem]; if (!audio) return; @@ -508,13 +554,31 @@ // produce a value that is only used once the stems are reachable. Read it // in the branch that actually needs it. if (stemsReachable()) { + // Record what this song actually has. getState() is authoritative + // when non-empty; the bridge/audio-map keys are heuristic-derived, + // so they only fill in when nothing better has reported yet. + let reported = null; + if (window.stems && typeof window.stems.getState === 'function') { + try { reported = window.stems.getState(); } catch (e) { reported = null; } + } + if (Array.isArray(reported) && reported.length > 0) { + setAvailableStems(reported); + } else if (availableStems === null) { + const bridged = Object.keys(stemsBridgeByStem); + const mapped = bridged.length ? bridged : Object.keys(getStemAudioMap()); + if (mapped.length) setAvailableStems(mapped); + } + const state = getCurrentState(); // Force the write (skipSave, and past the appliedLevels // idempotence guard) — the audio is new, so whatever that guard // thinks was already applied was applied to the PREVIOUS song's // nodes. appliedLevels = Object.create(null); - STEM_KEYS.forEach((stem) => setStemVolume(stem, state.levels[stem], true)); + displayStems().forEach((stem) => { + const level = state.levels[stem] !== undefined ? state.levels[stem] : 1; + setStemVolume(stem, level, true); + }); if (landed) return; // second successful push — settled, stop. // Schedule the confirmation pass and return WITHOUT touching the @@ -529,7 +593,15 @@ } waited += INTERVAL_MS; - if (waited >= MAX_WAIT_MS) return; // no stems in this song; give up quietly + if (waited >= MAX_WAIT_MS) { + // No stems ever became reachable. If nothing (e.g. a stems:state + // event) established the list either, this is our only signal that + // the song is stem-less — flip unknown to known-empty so the UI + // shows the message instead of six dead sliders. Never overwrite + // an event-established list. + if (availableStems === null) setAvailableStems([]); + return; + } stemBootstrapTimers.push(setTimeout(tick, INTERVAL_MS)); }; @@ -632,17 +704,16 @@ } function applyStateToUi(state) { - STEM_KEYS.forEach((stem) => { - if (stemInputs[stem]) { - const val = Math.round((state.levels[stem] || 0) * 100); - stemInputs[stem].value = String(val); - if (stemInputs[stem]._pctTag) stemInputs[stem]._pctTag.textContent = `${val}%`; - } - if (pluginStemInputs[stem]) { - const val = Math.round((state.levels[stem] || 0) * 100); - pluginStemInputs[stem].value = String(val); - if (pluginStemInputs[stem]._pctTag) pluginStemInputs[stem]._pctTag.textContent = `${val}%`; - } + // Iterate the inputs that exist, not STEM_KEYS — the rendered sliders are + // per-song and can include ids outside the six known ones. + [stemInputs, pluginStemInputs].forEach((registry) => { + Object.keys(registry).forEach((stem) => { + if (!registry[stem]) return; + const level = state.levels[stem] !== undefined ? state.levels[stem] : 1; + const val = Math.round(level * 100); + registry[stem].value = String(val); + if (registry[stem]._pctTag) registry[stem]._pctTag.textContent = `${val}%`; + }); }); EQ_BANDS.forEach((_, idx) => { @@ -667,14 +738,15 @@ const state = getCurrentState(); if (!isStemsPluginActive()) ensureAudioContext(); ensureStemNodes(); - STEM_KEYS.forEach((stem) => { + displayStems().forEach((stem) => { + const level = state.levels[stem] !== undefined ? state.levels[stem] : 1; // Idempotence: skip stems whose level was already pushed. Without // this, every UI-update pass re-wrote button classes/aria in the // stems plugin (via stems.setVolume), whose DOM mutations re-armed // our own MutationObserver — a self-sustaining ~12 Hz loop. // appliedLevels is cleared on song load, so new songs re-push. - if (appliedLevels[stem] === state.levels[stem]) return; - setStemVolume(stem, state.levels[stem], true); + if (appliedLevels[stem] === level) return; + setStemVolume(stem, level, true); }); applyEqToGraph(state.eq); setAutolevelEnabled(state.autolevel, true); @@ -801,12 +873,12 @@ }); } - function makeSliderRow(stem, current) { + function makeSliderRow(stem, current, registry) { const row = document.createElement('label'); row.style.cssText = 'display:grid;grid-template-columns:58px 1fr 42px;gap:10px;align-items:center;'; const name = document.createElement('span'); - name.textContent = STEM_LABELS[stem]; + name.textContent = STEM_LABELS[stem] || (stem.charAt(0).toUpperCase() + stem.slice(1)); name.style.cssText = 'font-size:11px;color:#b5bfd5;'; const input = document.createElement('input'); @@ -826,7 +898,7 @@ setStemVolume(stem, level); }); input._pctTag = pct; - stemInputs[stem] = input; + (registry || stemInputs)[stem] = input; row.appendChild(name); row.appendChild(input); @@ -834,6 +906,40 @@ return row; } + // (Re)build one slider host from the current song's stem list. Cheap to call + // from every UI sweep: the rendered list is stashed on the host and an + // unchanged list is a single string compare, no DOM work. + function renderStemRowsInto(host, registry) { + const list = displayStems(); + const key = JSON.stringify(list); + if (host.dataset.stemMixerRows === key) return; + host.dataset.stemMixerRows = key; + + Object.keys(registry).forEach((k) => { delete registry[k]; }); + host.innerHTML = ''; + + if (list.length === 0) { + const msg = document.createElement('div'); + msg.textContent = 'No stems available for this song.'; + msg.style.cssText = 'font-size:11px;line-height:1.35;color:#8b95aa;padding:6px 0;'; + host.appendChild(msg); + return; + } + + const state = getCurrentState(); + list.forEach((stem) => { + const current = state.levels[stem] !== undefined ? Number(state.levels[stem]) : 1; + host.appendChild(makeSliderRow(stem, current, registry)); + }); + } + + function renderStemRows() { + const panelHost = panelEl('stem-mixer-rows'); + if (panelHost) renderStemRowsInto(panelHost, stemInputs); + const pluginHost = document.getElementById('stem-mixer-plugin-stem-rows'); + if (pluginHost) renderStemRowsInto(pluginHost, pluginStemInputs); + } + function makeEqBand(idx, freq, current) { const wrap = document.createElement('label'); wrap.style.cssText = 'display:flex;flex-direction:column;align-items:center;gap:5px;width:28px;'; @@ -866,40 +972,9 @@ if (!rowsHost || !stemRowsHost) return; const state = getCurrentState(); + // Stem slider rows are per-song and rendered by renderStemRows() from the + // UI sweep — only the one-shot EQ/controls build lives behind this gate. if (rowsHost.dataset.stemMixerBuilt !== '1') { - STEM_KEYS.forEach((stem) => { - const row = document.createElement('label'); - row.style.cssText = 'display:grid;grid-template-columns:58px 1fr 42px;gap:10px;align-items:center;'; - - const name = document.createElement('span'); - name.textContent = STEM_LABELS[stem]; - name.style.cssText = 'font-size:11px;color:#b5bfd5;'; - - const input = document.createElement('input'); - input.type = 'range'; - input.min = '0'; - input.max = '100'; - input.step = '1'; - input.value = String(Math.round((state.levels[stem] || 0) * 100)); - input.style.cssText = 'width:100%;accent-color:#6ea8ff;'; - input.addEventListener('input', () => { - const level = parseInt(input.value, 10) / 100; - value.textContent = `${input.value}%`; - setStemVolume(stem, level); - }); - pluginStemInputs[stem] = input; - - const value = document.createElement('span'); - value.textContent = `${input.value}%`; - value.style.cssText = 'font-size:10px;color:#8b95aa;text-align:right;'; - input._valueTag = value; - - row.appendChild(name); - row.appendChild(input); - row.appendChild(value); - stemRowsHost.appendChild(row); - }); - EQ_BANDS.forEach((freq, idx) => { const band = document.createElement('div'); band.style.cssText = 'display:flex;flex-direction:column;align-items:center;gap:4px;min-width:28px;'; @@ -1190,10 +1265,11 @@ const state = getCurrentState(); - STEM_KEYS.forEach((stem) => { - const current = state.levels[stem] !== undefined ? Number(state.levels[stem]) : 1; - mixerPanel.appendChild(makeSliderRow(stem, current)); - }); + // Slider rows are per-song; renderStemRows() (re)fills this container. + const rowsWrap = document.createElement('div'); + rowsWrap.id = 'stem-mixer-rows'; + rowsWrap.style.cssText = 'display:flex;flex-direction:column;gap:8px;'; + mixerPanel.appendChild(rowsWrap); if (SHOW_EQ_UI) { const eqTitle = document.createElement('div'); @@ -1243,6 +1319,9 @@ mixerPanel.appendChild(hint); document.body.appendChild(mixerPanel); + // Fill the rows now: the panel is built lazily on first click, which can + // land between UI sweeps. + renderStemRows(); syncUiForCompatibilityMode(); applyStateToUi(state); setAutolevelEnabled(state.autolevel, true); @@ -1310,6 +1389,7 @@ // in particular must wait for the panel to exist before it has anything // to attach to. registerPane(); + renderStemRows(); syncUiForCompatibilityMode(); hideDefaultStemButtons(); hideStemsSettingsOptions(); @@ -1489,13 +1569,31 @@ STEM_KEYS, EQ_BANDS, DEFAULT_STATE, STEM_ALIASES, sanitizeState, cloneState, canonicalStemId, safeDecodeUrl, stemIdFromUrl, loadState, saveState, loadProfiles, saveProfiles, + normalizeAvailableStems, }; return; } + // The stems plugin announces each song's stem list the moment it knows it + // (plugins/stems/src/main.js, emitStemsState): stem-less songs get + // { event: 'provider-ready', stemCount: 0 }, stemmed songs get stemIds. + // This is the authoritative, instant availability source; the bootstrap + // poll below stays as the fallback for hosts without the stems plugin. + onStemsStateEvent = (e) => { + const d = e && e.detail; + if (!d || d.event !== 'provider-ready') return; + if (Array.isArray(d.stemIds)) setAvailableStems(d.stemIds); + else if (Number(d.stemCount) === 0) setAvailableStems([]); + }; + window.addEventListener('stems:state', onStemsStateEvent); + const originalPlaySong = window.playSong; if (typeof originalPlaySong === 'function') { window.playSong = async function (...args) { + // Reset BEFORE the await: the stems plugin can announce the new + // song's stems (provider-ready) while playSong is still in flight, + // and resetting afterwards would erase that fresh answer. + availableStems = null; const result = await originalPlaySong.apply(this, args); // New song: audio elements and stems-plugin gain nodes are // recreated, so every cached mapping and pushed level is stale. @@ -1548,6 +1646,10 @@ window.__stemMixerInstance = { destroy() { try { if (obs) { obs.disconnect(); obs = null; } } catch (e) { /* ignore */ } + if (onStemsStateEvent) { + try { window.removeEventListener('stems:state', onStemsStateEvent); } catch (e) { /* ignore */ } + onStemsStateEvent = null; + } try { clearStemBootstrapTimers(); } catch (e) { /* ignore */ } clearTimeout(uiUpdateTimer); if (autolevelTimer) { clearInterval(autolevelTimer); autolevelTimer = null; } diff --git a/tests/state.test.js b/tests/state.test.js index 13361e7..7558178 100644 --- a/tests/state.test.js +++ b/tests/state.test.js @@ -122,6 +122,46 @@ test('loadProfiles sanitizes each entry and drops blank-named ones', () => { assert.equal(profiles.Rock.levels.guitar, 1); }); +test('sanitizeState preserves dynamic (non-STEM_KEYS) levels, canonicalized and clamped', () => { + const { sanitizeState } = freshPlugin(); + const s = sanitizeState({ levels: { strings: 0.5, Synth: 7, kazoo: -1, full: 0.2, bad: 'x' } }); + assert.equal(s.levels.strings, 0.5); + assert.equal(s.levels.synth, 1); // clamped high + assert.equal(s.levels.kazoo, 0); // clamped low + assert.equal('full' in s.levels, false); // reserved mixdown id dropped + assert.equal('bad' in s.levels, false); // non-finite dropped + // The six known keys keep their defaults. + assert.equal(s.levels.guitar, 1); +}); + +test('sanitizeState folds aliased dynamic keys into the canonical known key', () => { + const { sanitizeState } = freshPlugin(); + // "voice" canonicalizes to "vocals", which the STEM_KEYS pass already set — + // the alias must not create a duplicate key or overwrite it. + const s = sanitizeState({ levels: { vocals: 0.4, voice: 0.9 } }); + assert.equal(s.levels.vocals, 0.4); + assert.equal('voice' in s.levels, false); +}); + +test('dynamic levels round-trip through localStorage', () => { + const { loadState, saveState } = freshPlugin(); + saveState({ levels: { guitar: 0.3, strings: 0.6 } }); + const reloaded = loadState(); + assert.equal(reloaded.levels.guitar, 0.3); + assert.equal(reloaded.levels.strings, 0.6); +}); + +test('normalizeAvailableStems canonicalizes, dedupes, drops full/blank, handles objects', () => { + const { normalizeAvailableStems } = freshPlugin(); + assert.deepEqual( + normalizeAvailableStems(['Voice', 'drums', 'vocal', 'full', '', null, 'strings']), + ['vocals', 'drums', 'strings'] + ); + assert.deepEqual(normalizeAvailableStems([{ id: 'Guitar' }, { id: 'bass' }, { id: 'guitar' }]), ['guitar', 'bass']); + assert.deepEqual(normalizeAvailableStems('nope'), []); + assert.deepEqual(normalizeAvailableStems([]), []); +}); + test('loadProfiles tolerates corrupt storage and non-object payloads', () => { const { loadProfiles } = freshPlugin(); global.localStorage.setItem('stem_mixer:profiles', '{not json'); From 36fd85daa7401664b34089cb944229544f721be2 Mon Sep 17 00:00:00 2001 From: topkoa Date: Sun, 19 Jul 2026 00:44:13 -0400 Subject: [PATCH 2/4] fix: harden dynamic level keys and clear stale bootstrap timers on song change Review follow-ups: own-key lookups everywhere a dynamic stem id indexes a plain object (STEM_ALIASES, STEM_LABELS, levels dedup), drop __proto__ outright, and kill the previous song's bootstrap timers at the top of the playSong wrapper so a leftover tick can't report the old song's stems or flip the new song to 'no stems' mid-load. Co-Authored-By: Claude Fable 5 Signed-off-by: topkoa --- screen.js | 26 +++++++++++++++++++++----- tests/state.test.js | 11 +++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/screen.js b/screen.js index f0966d2..72ce2f7 100644 --- a/screen.js +++ b/screen.js @@ -132,7 +132,12 @@ // resets those stems to full volume. Object.keys((rawState.levels && typeof rawState.levels === 'object') ? rawState.levels : {}).forEach((key) => { const canonical = canonicalStemId(key); - if (!canonical || canonical === 'full' || canonical in next.levels) return; + // Own-key check, not `in`: next.levels is a plain object, so `in` + // would see inherited names ('constructor', …) and wrongly skip a + // stem that happens to use one. '__proto__' is the one key plain + // assignment can't shadow — drop it outright. + if (!canonical || canonical === 'full' || canonical === '__proto__' || + Object.prototype.hasOwnProperty.call(next.levels, canonical)) return; const n = Number(rawState.levels[key]); if (Number.isFinite(n)) next.levels[canonical] = Math.max(0, Math.min(1, n)); }); @@ -216,7 +221,10 @@ } function canonicalStemId(stemId) { - return STEM_ALIASES[String(stemId || '').toLowerCase()] || String(stemId || '').toLowerCase(); + const lower = String(stemId || '').toLowerCase(); + // Own-key lookup: ids like 'constructor' would otherwise resolve to + // values inherited from Object.prototype. + return Object.prototype.hasOwnProperty.call(STEM_ALIASES, lower) ? STEM_ALIASES[lower] : lower; } // Canonical, deduped stem ids from whatever shape the source hands us — @@ -227,7 +235,7 @@ (Array.isArray(ids) ? ids : []).forEach((entry) => { const raw = (entry && typeof entry === 'object') ? entry.id : entry; const canonical = canonicalStemId(raw); - if (canonical && canonical !== 'full' && !out.includes(canonical)) out.push(canonical); + if (canonical && canonical !== 'full' && canonical !== '__proto__' && !out.includes(canonical)) out.push(canonical); }); return out; } @@ -878,7 +886,11 @@ row.style.cssText = 'display:grid;grid-template-columns:58px 1fr 42px;gap:10px;align-items:center;'; const name = document.createElement('span'); - name.textContent = STEM_LABELS[stem] || (stem.charAt(0).toUpperCase() + stem.slice(1)); + // Own-key lookup: a dynamic id like 'constructor' would otherwise pull + // an inherited value off the labels object. + name.textContent = Object.prototype.hasOwnProperty.call(STEM_LABELS, stem) + ? STEM_LABELS[stem] + : (stem.charAt(0).toUpperCase() + stem.slice(1)); name.style.cssText = 'font-size:11px;color:#b5bfd5;'; const input = document.createElement('input'); @@ -1592,7 +1604,11 @@ window.playSong = async function (...args) { // Reset BEFORE the await: the stems plugin can announce the new // song's stems (provider-ready) while playSong is still in flight, - // and resetting afterwards would erase that fresh answer. + // and resetting afterwards would erase that fresh answer. Kill the + // previous song's bootstrap timers with it — a leftover tick firing + // during the await would report the OLD song's stems (or its 12s + // timeout would flip the new song to "no stems"). + clearStemBootstrapTimers(); availableStems = null; const result = await originalPlaySong.apply(this, args); // New song: audio elements and stems-plugin gain nodes are diff --git a/tests/state.test.js b/tests/state.test.js index 7558178..a07d974 100644 --- a/tests/state.test.js +++ b/tests/state.test.js @@ -151,6 +151,17 @@ test('dynamic levels round-trip through localStorage', () => { assert.equal(reloaded.levels.strings, 0.6); }); +test('sanitizeState resists prototype pollution and inherited-name collisions', () => { + const { sanitizeState } = freshPlugin(); + const s = sanitizeState(JSON.parse('{"levels": {"__proto__": 0.1, "constructor": 0.2, "toString": 0.3}}')); + assert.equal(Object.prototype.hasOwnProperty.call(s.levels, '__proto__'), false); + assert.equal(({}).polluted, undefined); + // Inherited names are legal stem ids — kept as OWN keys (canonicalized to + // lowercase), not skipped via `in` or resolved through the prototype. + assert.equal(s.levels.constructor, 0.2); + assert.equal(s.levels.tostring, 0.3); +}); + test('normalizeAvailableStems canonicalizes, dedupes, drops full/blank, handles objects', () => { const { normalizeAvailableStems } = freshPlugin(); assert.deepEqual( From dad4c91ab5b54159f413ccd9fd38bd5a997f993b Mon Sep 17 00:00:00 2001 From: topkoa Date: Sun, 19 Jul 2026 00:51:15 -0400 Subject: [PATCH 3/4] fix: reject array levels payloads and reserved id in audio-map detection Review follow-ups: an array smuggled into persisted levels no longer leaks its numeric indices in as stem ids, and getStemAudioMap's exact-id detection drops __proto__ like every other dynamic-id path. Co-Authored-By: Claude Fable 5 Signed-off-by: topkoa --- screen.js | 8 +++++--- tests/state.test.js | 5 +++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/screen.js b/screen.js index 72ce2f7..5ec9fad 100644 --- a/screen.js +++ b/screen.js @@ -130,7 +130,9 @@ // Songs can carry stems beyond the six known ids ("strings", "synth", …). // Their levels live in the same map; keep them or every reload silently // resets those stems to full volume. - Object.keys((rawState.levels && typeof rawState.levels === 'object') ? rawState.levels : {}).forEach((key) => { + const rawLevels = (rawState.levels && typeof rawState.levels === 'object' && !Array.isArray(rawState.levels)) + ? rawState.levels : {}; + Object.keys(rawLevels).forEach((key) => { const canonical = canonicalStemId(key); // Own-key check, not `in`: next.levels is a plain object, so `in` // would see inherited names ('constructor', …) and wrongly skip a @@ -138,7 +140,7 @@ // assignment can't shadow — drop it outright. if (!canonical || canonical === 'full' || canonical === '__proto__' || Object.prototype.hasOwnProperty.call(next.levels, canonical)) return; - const n = Number(rawState.levels[key]); + const n = Number(rawLevels[key]); if (Number.isFinite(n)) next.levels[canonical] = Math.max(0, Math.min(1, n)); }); @@ -339,7 +341,7 @@ // the stem outright, whatever the id — including ones outside STEM_KEYS. // The token heuristics below stay as a fallback for the six known ids. const exact = canonicalStemId(dataStem) || stemIdFromUrl(srcDecoded) || stemIdFromUrl(src); - if (exact && exact !== 'full' && !map[exact]) map[exact] = audio; + if (exact && exact !== 'full' && exact !== '__proto__' && !map[exact]) map[exact] = audio; STEM_KEYS.forEach((stem) => { const stemAlias = stem === 'vocals' ? ['voice', 'vocals', 'vocal'] : [stem]; diff --git a/tests/state.test.js b/tests/state.test.js index a07d974..d1b8ed3 100644 --- a/tests/state.test.js +++ b/tests/state.test.js @@ -162,6 +162,11 @@ test('sanitizeState resists prototype pollution and inherited-name collisions', assert.equal(s.levels.tostring, 0.3); }); +test('sanitizeState ignores an array levels payload instead of copying its indices', () => { + const { sanitizeState, DEFAULT_STATE } = freshPlugin(); + assert.deepEqual(sanitizeState({ levels: [0.5, 0.7] }), DEFAULT_STATE); +}); + test('normalizeAvailableStems canonicalizes, dedupes, drops full/blank, handles objects', () => { const { normalizeAvailableStems } = freshPlugin(); assert.deepEqual( From f4ec4a420f905608a1bc7777aa04c8aaff76c19f Mon Sep 17 00:00:00 2001 From: topkoa Date: Sun, 19 Jul 2026 01:01:50 -0400 Subject: [PATCH 4/4] fix: fold alias-only levels into canonical stems, own-key level lookups CodeRabbit: the dynamic-levels dedup checked next.levels, which already owns all six defaulted STEM_KEYS, so an alias-only payload (voice with no vocals) could never reach its canonical stem - dedup against the raw payload instead, with exact canonical keys still winning over aliases. Copilot: reading state.levels[stem] with a bare !== undefined resolved inherited names (constructor) to prototype values for dynamic ids - new levelFor() helper does an own-key, finite, clamped lookup with default 1, used at all four read sites. Co-Authored-By: Claude Fable 5 Signed-off-by: topkoa --- screen.js | 34 ++++++++++++++++++++++++---------- tests/state.test.js | 19 +++++++++++++++++++ 2 files changed, 43 insertions(+), 10 deletions(-) diff --git a/screen.js b/screen.js index 5ec9fad..1e9d55b 100644 --- a/screen.js +++ b/screen.js @@ -134,12 +134,15 @@ ? rawState.levels : {}; Object.keys(rawLevels).forEach((key) => { const canonical = canonicalStemId(key); - // Own-key check, not `in`: next.levels is a plain object, so `in` - // would see inherited names ('constructor', …) and wrongly skip a - // stem that happens to use one. '__proto__' is the one key plain - // assignment can't shadow — drop it outright. + // Dedup against the RAW payload, not next.levels — next.levels + // already owns all six STEM_KEYS (defaulted) before this loop, so + // checking it would block an alias-only value (e.g. only "voice", + // no "vocals") from ever reaching its canonical stem. Own-key + // check, not `in`: inherited names ('constructor', …) are legal + // stem ids. '__proto__' is the one key plain assignment can't + // shadow — drop it outright. if (!canonical || canonical === 'full' || canonical === '__proto__' || - Object.prototype.hasOwnProperty.call(next.levels, canonical)) return; + (canonical !== key && Object.prototype.hasOwnProperty.call(rawLevels, canonical))) return; const n = Number(rawLevels[key]); if (Number.isFinite(n)) next.levels[canonical] = Math.max(0, Math.min(1, n)); }); @@ -254,6 +257,17 @@ return Array.isArray(availableStems) ? availableStems : STEM_KEYS; } + // Stored level for a stem, defaulting to full volume. Own-key lookup: a + // dynamic id like 'constructor' would otherwise resolve to a value + // inherited from Object.prototype and poison the gain math with NaN. + function levelFor(levels, stem) { + if (levels && Object.prototype.hasOwnProperty.call(levels, stem)) { + const n = Number(levels[stem]); + if (Number.isFinite(n)) return Math.max(0, Math.min(1, n)); + } + return 1; + } + function safeDecodeUrl(url) { const src = String(url || ''); if (!src) return ''; @@ -586,7 +600,7 @@ // nodes. appliedLevels = Object.create(null); displayStems().forEach((stem) => { - const level = state.levels[stem] !== undefined ? state.levels[stem] : 1; + const level = levelFor(state.levels, stem); setStemVolume(stem, level, true); }); if (landed) return; // second successful push — settled, stop. @@ -719,7 +733,7 @@ [stemInputs, pluginStemInputs].forEach((registry) => { Object.keys(registry).forEach((stem) => { if (!registry[stem]) return; - const level = state.levels[stem] !== undefined ? state.levels[stem] : 1; + const level = levelFor(state.levels, stem); const val = Math.round(level * 100); registry[stem].value = String(val); if (registry[stem]._pctTag) registry[stem]._pctTag.textContent = `${val}%`; @@ -749,7 +763,7 @@ if (!isStemsPluginActive()) ensureAudioContext(); ensureStemNodes(); displayStems().forEach((stem) => { - const level = state.levels[stem] !== undefined ? state.levels[stem] : 1; + const level = levelFor(state.levels, stem); // Idempotence: skip stems whose level was already pushed. Without // this, every UI-update pass re-wrote button classes/aria in the // stems plugin (via stems.setVolume), whose DOM mutations re-armed @@ -942,7 +956,7 @@ const state = getCurrentState(); list.forEach((stem) => { - const current = state.levels[stem] !== undefined ? Number(state.levels[stem]) : 1; + const current = levelFor(state.levels, stem); host.appendChild(makeSliderRow(stem, current, registry)); }); } @@ -1583,7 +1597,7 @@ STEM_KEYS, EQ_BANDS, DEFAULT_STATE, STEM_ALIASES, sanitizeState, cloneState, canonicalStemId, safeDecodeUrl, stemIdFromUrl, loadState, saveState, loadProfiles, saveProfiles, - normalizeAvailableStems, + normalizeAvailableStems, levelFor, }; return; } diff --git a/tests/state.test.js b/tests/state.test.js index d1b8ed3..dd24649 100644 --- a/tests/state.test.js +++ b/tests/state.test.js @@ -162,6 +162,25 @@ test('sanitizeState resists prototype pollution and inherited-name collisions', assert.equal(s.levels.tostring, 0.3); }); +test('sanitizeState folds an alias-only payload into the canonical known key', () => { + const { sanitizeState } = freshPlugin(); + // Legacy/externally-written state: only the alias, no canonical key. + const s = sanitizeState({ levels: { voice: 0.9 } }); + assert.equal(s.levels.vocals, 0.9); + assert.equal('voice' in s.levels, false); +}); + +test('levelFor uses own keys only and defaults inherited/missing/invalid to 1', () => { + const { levelFor } = freshPlugin(); + assert.equal(levelFor({ guitar: 0.3 }, 'guitar'), 0.3); + assert.equal(levelFor({ guitar: 5 }, 'guitar'), 1); // clamped + assert.equal(levelFor({ guitar: -2 }, 'guitar'), 0); // clamped + assert.equal(levelFor({}, 'strings'), 1); // missing + assert.equal(levelFor({}, 'constructor'), 1); // inherited name, no own key + assert.equal(levelFor({ constructor: 0.4 }, 'constructor'), 0.4); + assert.equal(levelFor(null, 'guitar'), 1); +}); + test('sanitizeState ignores an array levels payload instead of copying its indices', () => { const { sanitizeState, DEFAULT_STATE } = freshPlugin(); assert.deepEqual(sanitizeState({ levels: [0.5, 0.7] }), DEFAULT_STATE);