Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(review-2.5.5): self-review of the 2.5.5 diff — 1 critical + 1 high + 7 med/low

purplefb288544a6fd
diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rs
index 4529646e..b5b1858b 100644
--- a/src-tauri/src/commands/remote.rs
+++ b/src-tauri/src/commands/remote.rs
@@ -3699,12 +3699,27 @@ async fn handle_get_permissions(AxumState(state): AxumState<RemoteState>) -> Jso
Json(perms.clone())
}
+/// Merge a remote-supplied permissions update over the current state. The
+/// `shell` (RCE-equivalent) permission is NEVER raised here — only the trusted
+/// desktop `set_remote_permissions` command may grant it — so an authenticated
+/// client can't `POST {"shell":true}` and self-escalate to arbitrary command
+/// execution, which would defeat the desktop's OFF-by-default toggle.
+fn merge_remote_permissions(current: &RemotePermissions, body: RemotePermissions) -> RemotePermissions {
+ RemotePermissions {
+ filesystem: body.filesystem,
+ downloads: body.downloads,
+ process_control: body.process_control,
+ shell: current.shell, // desktop-controlled only — ignore whatever the client sent
+ }
+}
+
async fn handle_set_permissions(
AxumState(state): AxumState<RemoteState>,
Json(body): Json<RemotePermissions>,
) -> StatusCode {
let mut perms = state.permissions.lock().await;
- *perms = body;
+ let merged = merge_remote_permissions(&perms, body);
+ *perms = merged;
StatusCode::OK
}
@@ -4622,4 +4637,26 @@ mod remote_path_tests {
serde_json::from_str(r#"{"filesystem":true,"downloads":true,"process_control":true}"#).unwrap();
assert!(!p.shell);
}
+
+ #[test]
+ fn remote_cannot_raise_shell_via_permissions_endpoint() {
+ // SECURITY: an authenticated client POSTing {"shell":true} must NOT be
+ // able to self-grant the RCE-class shell permission.
+ let current = super::RemotePermissions { filesystem: false, downloads: false, process_control: false, shell: false };
+ let body = super::RemotePermissions { filesystem: true, downloads: true, process_control: true, shell: true };
+ let merged = super::merge_remote_permissions(&current, body);
+ assert!(merged.filesystem && merged.downloads && merged.process_control, "non-RCE perms apply");
+ assert!(!merged.shell, "remote bridge must NOT be able to grant shell");
+ }
+
+ #[test]
+ fn remote_merge_preserves_desktop_set_shell() {
+ // Desktop enabled shell; a later remote update that omits/clears it must
+ // NOT silently revoke the desktop's choice (shell is desktop-controlled).
+ let current = super::RemotePermissions { filesystem: false, downloads: false, process_control: false, shell: true };
+ let body = super::RemotePermissions { filesystem: true, downloads: false, process_control: false, shell: false };
+ let merged = super::merge_remote_permissions(&current, body);
+ assert!(merged.shell, "desktop-set shell must survive a remote update");
+ assert!(merged.filesystem, "non-RCE perms still apply");
+ }
}
diff --git a/src/api/agents/__tests__/side-effect-key.test.ts b/src/api/agents/__tests__/side-effect-key.test.ts
index 04b279ed..7460f128 100644
--- a/src/api/agents/__tests__/side-effect-key.test.ts
+++ b/src/api/agents/__tests__/side-effect-key.test.ts
@@ -44,8 +44,12 @@ describe('side-effect-key', () => {
expect(deriveSideEffectKey('code_execute', { code: '1' })).toBe('exec')
})
- it('image_generate and run_workflow share the "comfyui" queue', () => {
+ it('image_generate, video_generate and run_workflow share the "comfyui" queue', () => {
expect(deriveSideEffectKey('image_generate', { prompt: 'x' })).toBe('comfyui')
+ // video_generate MUST serialize with image_generate (same GPU + VRAM
+ // hand-off); when it was missing it ran in parallel and a back-to-back gen
+ // could survive Stop.
+ expect(deriveSideEffectKey('video_generate', { prompt: 'x' })).toBe('comfyui')
expect(deriveSideEffectKey('run_workflow', { name: 'x' })).toBe('comfyui')
})
diff --git a/src/api/agents/side-effect-key.ts b/src/api/agents/side-effect-key.ts
index 3cf23841..9922f20e 100644
--- a/src/api/agents/side-effect-key.ts
+++ b/src/api/agents/side-effect-key.ts
@@ -18,9 +18,9 @@
* shell command touches, so batch all exec-class calls onto a single
* queue.
*
- * - image_generate, run_workflow → key 'comfyui'. ComfyUI serializes
- * internally and workflows do heavy I/O; running in parallel provides
- * no win and competes for the GPU.
+ * - image_generate, video_generate, run_workflow → key 'comfyui'. ComfyUI
+ * serializes internally and workflows do heavy I/O; running in parallel
+ * provides no win and competes for the GPU + the VRAM hand-off.
*/
export function deriveSideEffectKey(
@@ -36,7 +36,11 @@ export function deriveSideEffectKey(
case 'code_execute':
return 'exec'
case 'image_generate':
+ case 'video_generate':
case 'run_workflow':
+ // All ComfyUI work shares one GPU + one VRAM hand-off. video_generate was
+ // missing here, so an image+video in the same turn ran concurrently —
+ // both queued on the hand-off and a back-to-back gen could survive Stop.
return 'comfyui'
default:
// file_read, file_list, file_search, web_search, web_fetch,
diff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.ts
index a63950ff..baa0b3af 100644
--- a/src/api/vram-handoff.ts
+++ b/src/api/vram-handoff.ts
@@ -507,6 +507,18 @@ let _cancelNotify: (() => void) | null = null
// poll doesn't accumulate thousands of derived `.then` promises on it.
let _cancelSignal: Promise<typeof CANCELLED> = new Promise<typeof CANCELLED>(() => { /* until reset */ })
+// Monotonic generation sequence + cancel epoch (back-to-back Stop fix). Each
+// vramHandoffGenerate() claims a seq when CREATED (before it parks on the
+// previous gen). requestGenerationCancel records the highest seq seen so far as
+// "cancelled-through"; a gen queued at/before the Stop bails the instant it
+// dequeues — its per-run resetCancel() clears the flag, but the epoch persists.
+let _genSeq = 0
+let _cancelledThrough = 0
+// Count of runHandoff bodies actually executing. Lets a Stop on a PLAIN text
+// chat (no media gen in flight) skip the ComfyUI /interrupt + full /queue-clear
+// that would otherwise nuke an unrelated Create-tab render or another client.
+let _activeHandoffs = 0
+
/** Re-arm the cancel channel at the start of each generation. */
function resetCancel(): void {
_genCancelRequested = false
@@ -525,9 +537,15 @@ function raceCancel<T>(p: Promise<T>): Promise<T | typeof CANCELLED> {
export function requestGenerationCancel(): void {
_genCancelRequested = true
- _cancelNotify?.() // wake every pending raceCancel immediately
- void cancelGeneration() // /interrupt the running job (no-op mid model-load)
- void clearComfyQueue() // drop anything still queued so it can't start next
+ _cancelledThrough = _genSeq // cancel every gen created so far (running + queued)
+ _cancelNotify?.() // wake every pending raceCancel immediately
+ // Only touch ComfyUI when a chat-initiated generation is actually running.
+ // A plain text-chat Stop must NOT /interrupt + clear the ENTIRE queue (that
+ // would kill an unrelated Create-tab render or another client's job).
+ if (_activeHandoffs > 0) {
+ void cancelGeneration() // /interrupt the running job (no-op mid model-load)
+ void clearComfyQueue() // drop anything still queued so it can't start next
+ }
}
// Last image LU actually produced this session. Small models routinely pass a
@@ -565,9 +583,10 @@ export async function vramHandoffGenerate(kind: 'image' | 'video', args: VramHan
// Serialise. We park on the previous call's settled promise (success OR
// failure — `.catch` swallows so a prior error doesn't reject our chain),
// then run our own body and expose it as the new tail.
+ const seq = ++_genSeq
const run = _inFlight
.catch(() => {})
- .then(() => runHandoff(kind, args))
+ .then(() => runHandoff(kind, args, seq))
// Defensive: runHandoff is written to always RETURN a string (the finally
// block never rethrows), but if anything unexpected slips through we still
// hand the agent a clean tool message instead of rejecting the chain.
@@ -576,10 +595,15 @@ export async function vramHandoffGenerate(kind: 'image' | 'video', args: VramHan
return run
}
-async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs): Promise<string> {
+async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs, seq: number): Promise<string> {
// Fresh run — re-arm the cancel channel (clears any flag/notify left over from
// a previous cancelled gen).
resetCancel()
+ // If Stop arrived while THIS gen was still queued behind another (its seq was
+ // created at/before the cancel), bail now. resetCancel() above just cleared the
+ // per-run flag, but the cancel epoch persists — without this, a back-to-back
+ // gen survives the user's Stop.
+ if (seq <= _cancelledThrough) return `${label(kind)} generation cancelled.`
// Robustness for small local models (gemma4:e4b live): they frequently emit a
// snake_case `input_image` alias and sometimes omit `prompt` on a video call.
// Normalize the alias so the I2V path still finds the source image.
@@ -609,6 +633,9 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs): Promi
let targetModel: string
let videoBackend: VideoBackend = 'none'
try {
+ // A chat-initiated ComfyUI gen is now in flight — gates the ComfyUI
+ // /interrupt in requestGenerationCancel (paired 1:1 with the finally below).
+ _activeHandoffs++
if (kind === 'image') {
const models = await getImageModels()
if (models.length === 0) {
@@ -844,6 +871,7 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs): Promi
if (result === CANCELLED) return `${label(kind)} generation cancelled.`
return result
} finally {
+ _activeHandoffs-- // paired with the increment at the top of the try above
// ── (d) HANDOFF-BACK — ALWAYS (success, failure, timeout) ──────
// Free ComfyUI's VRAM first (so the text model has room to reload), then
// best-effort reload the text model. The reload is non-fatal: if it throws,
diff --git a/src/components/chat/TokenCounter.tsx b/src/components/chat/TokenCounter.tsx
index 40b908a6..3eae9de0 100644
--- a/src/components/chat/TokenCounter.tsx
+++ b/src/components/chat/TokenCounter.tsx
@@ -41,19 +41,23 @@ export function TokenCounter() {
tokens += 4 // role overhead
return sum + tokens
}, 0)
- const usedTokens = realMax > 0
+ const rawUsed = realMax > 0
? Math.max(realMax, lastUsage?.totalTokens ?? 0)
: (lastUsage ? lastUsage.totalTokens : estimated)
- // "Real" = the model reported it AND that's the number we're showing. If a
- // larger provisional estimate is on top we display it but don't claim it's the
- // model's exact count.
- const isReal = realMax > 0 && usedTokens === realMax
if (!activeConversationId || messages.length === 0) return null
// Resolved real context window; fall back to the VRAM-safe default only while
// the provider probe is still in flight (ctx not resolved yet).
const maxTokens = ctx.contextWindow > 0 ? ctx.contextWindow : 16384
+ // Cap the numerator at the active window. The anti-jump high-water (realMax)
+ // is per-conversation, not per-model, so switching to a SMALLER-context model
+ // mid-chat would otherwise pin the bar above 100% forever (e.g. a 20k chat on
+ // an 8k model → "20k/8k" red). Showing "8.0k/8.0k" (full) is honest.
+ const usedTokens = Math.min(rawUsed, maxTokens)
+ // "Real" = the model reported it AND that exact number is what we're showing
+ // (not capped down, no larger provisional estimate on top).
+ const isReal = realMax > 0 && rawUsed === realMax && usedTokens === rawUsed
const ratio = maxTokens > 0 ? usedTokens / maxTokens : 0
const color = ratio > 0.8 ? 'text-red-400' : ratio > 0.5 ? 'text-amber-400' : 'text-gray-500'
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index acf600c9..44b3f2f7 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -503,7 +503,10 @@ export function useAgentChat() {
// shows only in the chat whose turn is in flight (David 2026-06-12).
useGenerationStore.getState().setGenerating(convId, true)
// Register so deleting/closing this chat stops the agent loop (Bug C).
- useGenerationStore.getState().registerAborter(convId, () => { runningRef.current = false; abort.abort() })
+ // requestGenerationCancel too, so a ComfyUI gen the agent kicked off is
+ // interrupted when the chat is deleted mid-generation (gated to a no-op when
+ // nothing is in flight).
+ useGenerationStore.getState().registerAborter(convId, () => { runningRef.current = false; abort.abort(); requestGenerationCancel() })
contentRef.current = ''
thinkingRef.current = ''
blocksRef.current = []
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index a6f00ff6..8393a61e 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -224,7 +224,11 @@ export function useChat() {
const abort = new AbortController()
abortRef.current = abort
// Register so deleting/closing this chat aborts the in-flight stream (Bug C).
- useGenerationStore.getState().registerAborter(convId, () => abort.abort())
+ // Also requestGenerationCancel so a running ComfyUI job is interrupted when
+ // the chat goes away mid-generation (the _activeHandoffs gate makes it a
+ // no-op when no media gen is in flight). Without it a long video kept
+ // rendering after the chat was deleted.
+ useGenerationStore.getState().registerAborter(convId, () => { abort.abort(); requestGenerationCancel() })
setIsGenerating(true)
// Bind the generating flag to THIS conversation so the typing indicator
// only shows in the chat whose turn is in flight — not in every other chat
diff --git a/src/lib/__tests__/vision-multimodal.test.ts b/src/lib/__tests__/vision-multimodal.test.ts
index 28c9bb73..1d2df520 100644
--- a/src/lib/__tests__/vision-multimodal.test.ts
+++ b/src/lib/__tests__/vision-multimodal.test.ts
@@ -19,6 +19,14 @@ describe('isVisionCompatible', () => {
it('accepts dashed / community gemma variants via normalizeFamily', () => {
expect(isVisionCompatible('hf.co/mradermacher/Gemma-4-31B-it-abliterated-GGUF:Q4_K_M')).toBe(true)
})
+ it('accepts GLM-4V (normalizes to glm4v) and versioned InternVL tags', () => {
+ // glm-4v → normalizeFamily collapses glm-4→glm4 → "glm4v"; the family list
+ // must hold the post-normalize form or these false-warn "can't read images".
+ expect(isVisionCompatible('glm-4v:9b')).toBe(true)
+ expect(isVisionCompatible('internvl2:8b')).toBe(true)
+ expect(isVisionCompatible('internvl2.5:8b')).toBe(true)
+ expect(isVisionCompatible('internvl3:14b')).toBe(true)
+ })
it('rejects text-only local models', () => {
expect(isVisionCompatible('llama3.1:8b')).toBe(false)
expect(isVisionCompatible('mistral:7b')).toBe(false)
@@ -52,6 +60,11 @@ describe('isMultimodalUnsupportedError', () => {
expect(isMultimodalUnsupportedError(null)).toBe(false)
expect(isMultimodalUnsupportedError(undefined)).toBe(false)
})
+ it('does NOT misfire on an image-GENERATION refusal (it is about image INPUT)', () => {
+ expect(isMultimodalUnsupportedError('This model does not support image generation')).toBe(false)
+ // but a real image-INPUT refusal still matches
+ expect(isMultimodalUnsupportedError('this model does not support images')).toBe(true)
+ })
it('exposes actionable, vision-oriented copy', () => {
expect(MULTIMODAL_UNSUPPORTED_MESSAGE).toMatch(/vision/i)
})
diff --git a/src/lib/model-compatibility.ts b/src/lib/model-compatibility.ts
index 6fddf4cb..ca389673 100644
--- a/src/lib/model-compatibility.ts
+++ b/src/lib/model-compatibility.ts
@@ -179,7 +179,12 @@ const VISION_COMPATIBLE = [
'qwen2.5-vl', 'qwen3-vl', 'qwen-vl', 'qwen3.6',
'minicpm-v', 'moondream', 'pixtral',
'mistral-small3.1', 'mistral-small3.2',
- 'granite3.2-vision', 'internvl', 'glm-4v',
+ // Entries must be in POST-normalizeFamily form. `glm-4v` normalizes to
+ // `glm4v` (the `glm-4`→`glm4` dash-collapse), so the dashed literal never
+ // matched a real GLM-4V tag → false "can't read images" hint. `internvl`
+ // alone misses the real `internvl2` / `internvl2.5` / `internvl3` tags
+ // (trailing digit breaks the word boundary), so list those prefixes.
+ 'granite3.2-vision', 'internvl', 'internvl2', 'internvl3', 'glm4v',
]
/**
diff --git a/src/lib/ollama-errors.ts b/src/lib/ollama-errors.ts
index e3c2882f..e359e09f 100644
--- a/src/lib/ollama-errors.ts
+++ b/src/lib/ollama-errors.ts
@@ -164,7 +164,9 @@ export function chatStyleMessage(parsed: ParsedOllamaError): string {
* multimodal requests." with no guidance. Match the common phrasings.
*/
const MULTIMODAL_UNSUPPORTED_RE =
- /multimodal data provided|does not support multimodal|not multimodal|does not support image|image input is not supported|no vision support|vision is not supported/i
+ // `does not support image(?! generation)` so a model REFUSING image GENERATION
+ // ("does not support image generation") isn't misread as "can't read images".
+ /multimodal data provided|does not support multimodal|not multimodal|does not support image(?! gen)|image input is not supported|no vision support|vision is not supported/i
export function isMultimodalUnsupportedError(raw: string | null | undefined): boolean {
return typeof raw === 'string' && MULTIMODAL_UNSUPPORTED_RE.test(raw)
diff --git a/src/stores/__tests__/providerStore.keychain.test.ts b/src/stores/__tests__/providerStore.keychain.test.ts
index d329aef9..54d13981 100644
--- a/src/stores/__tests__/providerStore.keychain.test.ts
+++ b/src/stores/__tests__/providerStore.keychain.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
// H5: provider API keys move to the OS keychain on Win/macOS, with a
// localStorage fallback (Linux + web build). These tests mock the Rust
@@ -25,19 +25,23 @@ async function freshStore() {
const obf = (k: string) => btoa(k.split('').reverse().join(''))
-// The default vitest env here is 'node' (no DOM). zustand persist needs a
-// localStorage; install a minimal Map-backed one BEFORE the store module loads
-// (createJSONStorage reads it at import time, which freshStore triggers).
+// The default vitest env here is 'node' (no DOM). zustand persist reads
+// `window.localStorage` (createJSONStorage default), so install a Map-backed
+// store on BOTH `localStorage` and `window.localStorage` (same map) BEFORE the
+// store module loads — otherwise persist silently no-ops and the localStorage
+// assertions below pass trivially.
function installLocalStorage() {
const map = new Map<string, string>()
- vi.stubGlobal('localStorage', {
+ const ls = {
getItem: (k: string) => (map.has(k) ? map.get(k)! : null),
setItem: (k: string, v: string) => { map.set(k, String(v)) },
removeItem: (k: string) => { map.delete(k) },
clear: () => { map.clear() },
key: (i: number) => [...map.keys()][i] ?? null,
get length() { return map.size },
- })
+ }
+ vi.stubGlobal('localStorage', ls)
+ vi.stubGlobal('window', { localStorage: ls })
}
describe('providerStore keychain (H5)', () => {
@@ -48,6 +52,10 @@ describe('providerStore keychain (H5)', () => {
installLocalStorage()
})
+ afterEach(() => {
+ vi.unstubAllGlobals() // restore window/localStorage so other test files are unaffected
+ })
+
it('no keychain (secret_get rejects on first probe) → stays on localStorage, never writes the vault', async () => {
secretGet.mockRejectedValue(new Error('keychain unavailable (web build)'))
const useStore = await freshStore()
@@ -111,4 +119,19 @@ describe('providerStore keychain (H5)', () => {
useStore.getState().resetProvider('anthropic')
expect(secretDelete).toHaveBeenCalledWith('anthropic')
})
+
+ it('keeps the obfuscated key in localStorage when the vault WRITE fails (no silent loss on restart)', async () => {
+ secretGet.mockResolvedValue(null) // keychain usable but empty
+ secretSet.mockRejectedValue(new Error('credential store locked'))
+ const useStore = await freshStore()
+ await useStore.getState().hydrateProviderKeys() // keychainReady = true
+
+ useStore.getState().setProviderApiKey('anthropic', 'sk-fail-fallback')
+ // let the fire-and-forget secretSet rejection + the fallback re-persist settle
+ await new Promise((r) => setTimeout(r, 0))
+
+ const raw = localStorage.getItem('lu-providers') || ''
+ expect(raw).toContain(obf('sk-fail-fallback')) // retained as fallback, NOT stripped
+ expect(useStore.getState().getProviderApiKey('anthropic')).toBe('sk-fail-fallback')
+ })
})
diff --git a/src/stores/providerStore.ts b/src/stores/providerStore.ts
index 8d24773b..dc2ce656 100644
--- a/src/stores/providerStore.ts
+++ b/src/stores/providerStore.ts
@@ -45,6 +45,10 @@ function deobfuscate(encoded: string): string {
// before. Module-level so the static `partialize` can read it.
let keychainReady = false
const PROVIDER_IDS: ProviderId[] = ['ollama', 'openai', 'anthropic']
+// Providers whose OS-vault WRITE failed this session. partialize keeps their
+// obfuscated key in localStorage as a fallback so a flaky/locked credential
+// store can't silently drop the key on the next restart.
+const _keychainFailed = new Set<ProviderId>()
// ── Default provider configs ───────────────────────────────────
@@ -123,11 +127,17 @@ export const useProviderStore = create<ProviderState>()(
[id]: { ...state.providers[id], apiKey: obfuscate(key) },
},
}))
- // When the OS vault is active, store the real key there; partialize
- // keeps it out of localStorage. Fire-and-forget — the in-memory
- // obfuscated value already serves this session's reads.
+ // When the OS vault is active, store the real key there; partialize then
+ // keeps it out of localStorage. If the vault WRITE fails (locked / policy
+ // / full), mark this id so partialize RETAINS the obfuscated key in
+ // localStorage — otherwise it would vanish on the next restart with no
+ // trace (the in-memory value only serves this session).
if (keychainReady) {
- void secretSet(id, key).catch(() => { /* vault write best-effort */ })
+ _keychainFailed.delete(id)
+ secretSet(id, key).catch(() => {
+ _keychainFailed.add(id)
+ set((s) => ({ providers: { ...s.providers } })) // re-persist with the fallback retained
+ })
}
clearProviderCache()
},
@@ -177,7 +187,9 @@ export const useProviderStore = create<ProviderState>()(
// (an upgrading user) into the vault, once.
const existing = deobfuscate(next[id]?.apiKey || '')
if (existing) {
- try { await secretSet(id, existing) } catch { /* migrate best-effort */ }
+ // Migrate the old localStorage key into the vault. If the write
+ // fails, mark it so partialize keeps the localStorage copy (no loss).
+ try { await secretSet(id, existing) } catch { _keychainFailed.add(id) }
}
}
} catch {
@@ -203,7 +215,11 @@ export const useProviderStore = create<ProviderState>()(
partialize: (state) => ({
providers: keychainReady
? (Object.fromEntries(
- Object.entries(state.providers).map(([id, p]) => [id, { ...p, apiKey: '' }])
+ Object.entries(state.providers).map(([id, p]) =>
+ // Strip the key (it lives in the vault) UNLESS the vault write
+ // failed for this id — then keep the obfuscated fallback.
+ _keychainFailed.has(id as ProviderId) ? [id, p] : [id, { ...p, apiKey: '' }]
+ )
) as Record<ProviderId, ProviderConfig>)
: state.providers,
hideBackendSelector: state.hideBackendSelector,
diff --git a/vite.config.ts b/vite.config.ts
index b9866985..0e1de20a 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -43,8 +43,17 @@ function isBlockedIp(ip: string): boolean {
if (lc === '::1' || lc === '::') return true // loopback / unspecified
if (lc.startsWith('fe80')) return true // link-local
if (lc.startsWith('fc') || lc.startsWith('fd')) return true // ULA fc00::/7
- const mapped = lc.match(/::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)
- if (mapped) return isBlockedIp(mapped[1]) // IPv4-mapped IPv6
+ if (lc.startsWith('64:ff9b:')) return true // NAT64 (embeds an IPv4 — block)
+ // IPv4-mapped IPv6 in BOTH the dotted (::ffff:127.0.0.1) and the hex
+ // (::ffff:7f00:1) forms — decode the embedded IPv4 and re-check it.
+ const dotted = lc.match(/::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)
+ if (dotted) return isBlockedIp(dotted[1])
+ const hex = lc.match(/::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/)
+ if (hex) {
+ const hi = parseInt(hex[1], 16)
+ const lo = parseInt(hex[2], 16)
+ return isBlockedIp(`${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`)
+ }
return false
}
return false // not an IP literal — caller resolves DNS and re-checks
@@ -525,8 +534,11 @@ function comfyLauncher(): Plugin {
const proto = u.protocol === 'https:' ? https : http
proto.get(imgUrl, { headers: { 'User-Agent': 'Mozilla/5.0' } }, (upstream) => {
if (upstream.statusCode && upstream.statusCode >= 300 && upstream.statusCode < 400 && upstream.headers.location) {
- const loc = upstream.headers.location
upstream.resume() // drain the redirect body
+ // Resolve relative redirects against the current hop (imgUrl was
+ // already validated) before re-validating + following.
+ let loc: string
+ try { loc = new URL(upstream.headers.location, imgUrl).toString() } catch { deny(); return }
assertPublicUrl(loc).then((lu) => {
const lproto = lu.protocol === 'https:' ? https : http
lproto.get(loc, { headers: { 'User-Agent': 'Mozilla/5.0' } }, (redir) => {
@@ -570,7 +582,11 @@ function comfyLauncher(): Plugin {
protocol.get(targetUrl, { headers: { 'User-Agent': 'LocallyUncensored/1.0' } }, (upstream) => {
if (upstream.statusCode && upstream.statusCode >= 300 && upstream.statusCode < 400 && upstream.headers.location) {
upstream.resume()
- fetchUrl(upstream.headers.location, redirectCount + 1)
+ // Resolve relative redirects against the current hop (targetUrl
+ // was already validated) before the next hop re-validates.
+ let nextUrl: string
+ try { nextUrl = new URL(upstream.headers.location, targetUrl).toString() } catch { res.writeHead(502); res.end(); return }
+ fetchUrl(nextUrl, redirectCount + 1)
return
}
res.writeHead(upstream.statusCode || 200, {