From 118dde5ab4eb2e7517eb75ad124aa51049a3f430 Mon Sep 17 00:00:00 2001 From: faber Date: Sat, 11 Jul 2026 19:19:02 -0400 Subject: [PATCH] fix: deep XSS paths, import validation, image URL sanitization MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Liquid XSS (version history modal): - All LLM-derived fields (label, grade, improvements) now escaped via escapeHtml() before innerHTML insertion - score/delta coerced to finite numbers - improvements filtered to string[], bounded to 10 items x 200 chars Refiner JSON normalization: - Parse result now strictly validated: numbers clamped [0,100], improvements filtered/bounded, refinedContent typed as string - Malformed LLM output can no longer inject HTML via stored versions Backup import hardening: - Validate-then-commit: build candidate state, check size, sanitize, THEN apply to live state — rejected imports no longer corrupt state - Sanitize imageDataUrl: only data:image/ prefixed URLs survive import - Sanitize liquidVersions: improvements bounded, label/grade truncated, score/delta forced to finite numbers - Imported API key increments _apiKeyGeneration Image URL render-time guard: - Inline image rendering now validates data:image/ prefix before inserting into src attribute — existing stored payloads blocked Co-Authored-By: Claude Opus 4.6 --- index.html | 124 +++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 88 insertions(+), 36 deletions(-) diff --git a/index.html b/index.html index 5fbb70f..4a99755 100644 --- a/index.html +++ b/index.html @@ -10127,17 +10127,27 @@ Analyze and refine. Output ONLY the JSON object:` } break; } - // Parse the JSON response + // Parse and strictly normalize the JSON response let result; try { - // Extract JSON from potential markdown code blocks const jsonMatch = refinerOutput.match(/\{[\s\S]*\}/); if (!jsonMatch) throw new Error('No JSON found in refiner output'); - result = JSON.parse(jsonMatch[0]); + const raw = JSON.parse(jsonMatch[0]); + // Normalize: clamp numbers, bound strings, filter arrays + result = { + currentScore: Math.max(0, Math.min(100, Number(raw.currentScore) || 0)), + refinedScore: Math.max(0, Math.min(100, Number(raw.refinedScore) || 0)), + qualityDelta: Math.max(-100, Math.min(100, Number(raw.qualityDelta) || 0)), + converged: !!raw.converged, + refinedContent: typeof raw.refinedContent === 'string' ? raw.refinedContent : '', + improvements: (Array.isArray(raw.improvements) ? raw.improvements : []) + .filter(x => typeof x === 'string') + .slice(0, 10) + .map(s => s.slice(0, 200)), + }; } catch (parseErr) { console.error('[LIQUID] Failed to parse refiner output:', parseErr.message); console.error('[LIQUID] Raw output:', refinerOutput.slice(0, 500)); - // Don't break on first parse failure — try next iteration continue; } @@ -10751,28 +10761,36 @@ Analyze and refine. Output ONLY the JSON object:` }
- ${versions.map((v, i) => ` + ${versions.map((v, i) => { + const safeLabel = escapeHtml(String(v.label || `Refinement ${i}`).slice(0, 60)); + const safeGrade = escapeHtml(String(v.grade || '').slice(0, 20)); + const safeDelta = Number.isFinite(v.delta) ? v.delta : 0; + const safeScore = Number.isFinite(v.score) ? v.score : 0; + const safeImprovements = Array.isArray(v.improvements) + ? v.improvements.filter(x => typeof x === 'string').slice(0, 3) + : []; + return `
+ onclick="revertToLiquidVersion(${Number(messageIdx)}, ${Number(i)}); this.closest('.version-history-modal').remove();">
- ${i === 0 ? '📄 Original' : i === versions.length - 1 ? '✨ ' + v.label + ' (Latest)' : '📝 ' + v.label} + ${i === 0 ? '📄 Original' : i === versions.length - 1 ? '✨ ' + safeLabel + ' (Latest)' : '📝 ' + safeLabel} - ${v.score}/100 + ${safeScore}/100
- ${v.grade} - ${v.delta ? `+${v.delta}%` : ''} + ${safeGrade} + ${safeDelta ? `+${safeDelta}%` : ''} ${formatTimeAgo(v.timestamp)}
- ${v.improvements && v.improvements.length > 0 ? ` + ${safeImprovements.length > 0 ? `
- ${v.improvements.slice(0, 2).map(imp => `${imp.slice(0, 30)}${imp.length > 30 ? '...' : ''}`).join('')} + ${safeImprovements.slice(0, 2).map(imp => `${escapeHtml(imp.slice(0, 30))}${imp.length > 30 ? '...' : ''}`).join('')}
` : ''} -
${escapeHtml(v.content.slice(0, 150))}${v.content.length > 150 ? '...' : ''}
+
${escapeHtml((v.content || '').slice(0, 150))}${(v.content || '').length > 150 ? '...' : ''}
- `).join('')} + `;}).join('')}
`; @@ -12798,8 +12816,9 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; ` : ''; // Image thumbnail for user messages with attached images - const imageThumb = (isUser && msg.imageDataUrl) - ? `${escapeHtml(msg.imageName || 'image')}` + const safeImageUrl = (msg.imageDataUrl && /^data:image\//.test(msg.imageDataUrl)) ? msg.imageDataUrl : ''; + const imageThumb = (isUser && safeImageUrl) + ? `${escapeHtml(msg.imageName || 'image')}` : ''; // Vision badge — only when vision analysis actually ran @@ -16579,41 +16598,74 @@ Ignoring conversation history will cause you to LOSE the evaluation.`; if (!_pendingImportData) return; const imported = _pendingImportData; - // Merge into state — only overwrite keys that exist in the import + // Build a candidate state WITHOUT mutating live state const allowed = ['conversations', 'currentId', 'apiKey', 'model', 'persona', 'customSystemPrompt', 'customSystemPromptEnabled', 'strategyLogs', 'autoTuneEnabled', 'liquidEnabled', 'ultraplinianEnabled', 'ultraplinianTier', 'noLogMode']; + const candidate = JSON.parse(JSON.stringify(state)); for (const key of allowed) { - if (imported[key] !== undefined) state[key] = imported[key]; + if (imported[key] !== undefined) candidate[key] = imported[key]; } - // Enforce hard caps before saving (same caps as normal save) - enforceDataCaps(); + // Sanitize conversations: strip dangerous image URLs, validate structure + if (Array.isArray(candidate.conversations)) { + for (const conv of candidate.conversations) { + if (!Array.isArray(conv.messages)) { conv.messages = []; continue; } + for (const msg of conv.messages) { + // Only allow data:image/ URLs for inline images + if (msg.imageDataUrl && !/^data:image\//.test(msg.imageDataUrl)) { + delete msg.imageDataUrl; + } + // Sanitize liquid version improvements + if (Array.isArray(msg.liquidVersions)) { + for (const v of msg.liquidVersions) { + if (Array.isArray(v.improvements)) { + v.improvements = v.improvements + .filter(x => typeof x === 'string') + .slice(0, 10) + .map(s => s.slice(0, 200)); + } + if (typeof v.label === 'string') v.label = v.label.slice(0, 60); + if (typeof v.grade === 'string') v.grade = v.grade.slice(0, 20); + if (!Number.isFinite(v.score)) v.score = 0; + if (!Number.isFinite(v.delta)) v.delta = 0; + } + } + } + } + } - // Pre-flight: check if the merged state will fit in localStorage (~5 MB) - const { apiKey: _ak, ...stateWithoutKey } = state; - const testPayload = JSON.stringify(stateWithoutKey); + // Enforce caps on candidate + if (Array.isArray(candidate.conversations) && candidate.conversations.length > MAX_CONVERSATIONS) { + candidate.conversations = candidate.conversations.slice(-MAX_CONVERSATIONS); + } + if (Array.isArray(candidate.strategyLogs) && candidate.strategyLogs.length > 500) { + candidate.strategyLogs = candidate.strategyLogs.slice(-500); + } + + // Pre-flight: check if the candidate will fit in localStorage (~5 MB) + const { apiKey: _ak, ...candidateWithoutKey } = candidate; + const testPayload = JSON.stringify(candidateWithoutKey); const estimatedBytes = new Blob([testPayload]).size; const maxBytes = 5 * 1024 * 1024; if (estimatedBytes > maxBytes * 0.95) { - // Too large even after caps — try trimming, then warn - trimOldData(); - const retryPayload = JSON.stringify((() => { const { apiKey: _k, ...rest } = state; return rest; })()); - const retryBytes = new Blob([retryPayload]).size; - if (retryBytes > maxBytes * 0.95) { - showImportStatus('error', - 'Backup is too large for browser storage (' + (retryBytes / 1024 / 1024).toFixed(1) + ' MB / ~5 MB limit). ' + - 'Try exporting fewer conversations or clearing existing data first.'); - _pendingImportData = null; - document.getElementById('importConfirm').style.display = 'none'; - return; - } + showImportStatus('error', + 'Backup is too large for browser storage (' + (estimatedBytes / 1024 / 1024).toFixed(1) + ' MB / ~5 MB limit). ' + + 'Try exporting fewer conversations or clearing existing data first.'); + _pendingImportData = null; + document.getElementById('importConfirm').style.display = 'none'; + return; } - // Report if caps trimmed anything + // Commit: apply validated candidate to live state const importedConvCount = imported.conversations?.length ?? 0; + for (const key of allowed) { + if (candidate[key] !== undefined) state[key] = candidate[key]; + } + if (candidate.apiKey) _apiKeyGeneration++; + const actualConvCount = state.conversations?.length ?? 0; let capWarning = ''; if (importedConvCount > actualConvCount) {