From 55e581bab9b600e7c070ec596d3109fc897d2d86 Mon Sep 17 00:00:00 2001 From: tanaka takashi Date: Tue, 1 Sep 2026 20:10:20 +0900 Subject: feat: Firefox selection translation extension with local Ollama (initial version) Implement the complete initial version of a Firefox WebExtension (Manifest V3) that translates selected text on web pages using a local Ollama LLM and shows the result in a small popover near the selection. Specification alignment (Phase 0) - Unified Specifications.md / Design.md / Security.md on the same approach: Ollama REST API + Fetch API + NDJSON streaming (no ollama-js SDK dependency) - Fixed host_permissions to http://localhost/* and http://127.0.0.1/* because Firefox match patterns do not support port numbers (bug 1362809/1468162); the actual connection target is restricted to localhost/127.0.0.1 + any port by application-side validation (defense in depth, OLL-09) - Clipboard: use navigator.clipboard.writeText() only inside the copy button click (user activation); no deprecated execCommand fallback Implementation (zero dependencies, vanilla JS, no npm/Node required) - manifest.json: MV3, background.scripts + type:module (event page, no service_worker), action popup, options_ui, content_scripts for http/https, permissions: storage + localhost host permissions only - src/shared: constants (ports, limits, presets, error codes), message validation, settings schema (defaults / merge / sanitize / buildOptions / toApiThinking), system prompt builder (fixed prompt first + user prompt) - src/background: message-router (runtime.Port streaming + runtime.onMessage for model list), translation-session (single active request, abort previous on new request, stale chunk suppression), ollama-client (fetch against /api/tags and /api/chat with buffering NDJSON line parser tolerant to chunk boundaries inside JSON objects, AbortController, host re-validation before every request, HTTP status to error-code mapping), settings-service (storage.local load/save with validation and fallback to defaults) - src/content/content.js: single classic script (Firefox does not support ES modules in content scripts) with selection detection (selectionchange + mouseup + keyup, debounced), Shadow DOM action button, Shadow DOM popover with HIDDEN/LOADING/STREAMING/COMPLETED/ERROR state machine, port client with requestId-based stale chunk filtering, enabled-state sync via storage.onChanged; all dynamic text rendered via textContent only - src/popup + src/options: full settings UI (enable toggle, Ollama host, model list from Ollama with saved-model warning, target language, thinking mode, temperature slider 0.0-2.0 step 0.1, context length presets 4k/8k/16k/32k/128k/256k, seed random/fixed with integer value, user system prompt, advanced numeric options with steppers, stop sequences textarea) - icons generated by tools/make-icons.ps1 (System.Drawing, no external tools) - build.ps1 packages manifest.json + icons/ + src/ into dist zip, excluding tests/, doc/, ollama-js/ and tools/ Tests (71 passed, 0 failed) - In-browser test runner (tests/test.html) with custom describe/it/assert framework; no npm, no Node.js - Unit: constants sync between content mirror and shared module, Ollama host validation (localhost/127.0.0.1 + any port only; rejects external hosts, LAN IPs, https, credentials, paths), settings schema defaults and fallback, temperature 0.1-step validation, context length presets, seed modes, advanced option types, buildOptions omission of unset values and absence of tfs_z/mirostat fields, system prompt composition order, message validation with selection length boundary values - Integration: NDJSON streaming across awkward byte boundaries, thinking chunk forwarding, malformed line tolerance, error payload mapping, think/ options inclusion rules, model list, TranslationSession abort semantics, settings round-trip with storage.onChanged cache refresh, full port flow (started/chunk/completed), newer request aborts older with stale chunk discard, malformed message rejection, OLLAMA_UNAVAILABLE and INVALID_SETTINGS error paths, untrusted sender rejection Security audit (Design.md section 24 checklist: all pass) - No innerHTML/outerHTML/document.write/eval/new Function/localStorage - No remote JS/CSS/fonts/CDN resources; no inline scripts in extension pages - Ollama access limited to background; content scripts never fetch Ollama - Background validates message type/length/requestId; single concurrent translation enforced - Clipboard API only (no execCommand fallback) - Minimal permissions: storage + localhost host permissions Docs - README.md with build/load/usage instructions, API list, permission rationale - doc/Testing-Results.md with automated test results, security audit results, and a 14-item manual Firefox verification checklist (to be executed on a real Firefox + Ollama environment) --- src/background/ollama-client.js | 194 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 194 insertions(+) create mode 100644 src/background/ollama-client.js (limited to 'src/background/ollama-client.js') diff --git a/src/background/ollama-client.js b/src/background/ollama-client.js new file mode 100644 index 0000000..0286230 --- /dev/null +++ b/src/background/ollama-client.js @@ -0,0 +1,194 @@ +/** + * Ollama REST API client (background only). + * + * Uses the browser Fetch API directly against the Ollama REST API. + * - GET {host}/api/tags : list installed models + * - POST {host}/api/chat : streaming chat completion (NDJSON) + * + * Security rules implemented here (Security.md ยง4): + * - the host is re-validated immediately before each request; + * - NDJSON is parsed with a buffering line reader that tolerates chunk + * boundaries falling inside a JSON object; + * - requests can be aborted via AbortController. + */ + +import { isValidOllamaHost } from '../shared/settings-schema.js'; +import { ERROR_CODES } from '../shared/constants.js'; + +/** + * Translate a fetch/HTTP failure into a stable error code. + * @param {Response|undefined} response + * @returns {string} error code + */ +function statusCodeToError(status) { + if (status === 404) return ERROR_CODES.MODEL_NOT_FOUND; + if (status === 400 || status === 403) return ERROR_CODES.INVALID_SETTINGS; + if (status >= 500) return ERROR_CODES.STREAM_ERROR; + return ERROR_CODES.STREAM_ERROR; +} + +/** + * Assert that the host is allowed. Throws Error with code attached. + * @param {string} host + */ +function assertAllowedHost(host) { + if (!isValidOllamaHost(host)) { + const error = new Error('Invalid Ollama host'); + error.code = ERROR_CODES.INVALID_SETTINGS; + throw error; + } +} + +/** + * Normalize an error thrown by fetch into an extension error code. + * @param {*} error + * @param {{aborted?: boolean, code?: string}} [options] + * @returns {Error} + */ +export function toExtensionError(error, { aborted = false, code = ERROR_CODES.OLLAMA_UNAVAILABLE } = {}) { + if (error && error.name === 'AbortError') { + const e = new Error('Request aborted'); + e.code = ERROR_CODES.REQUEST_ABORTED; + return e; + } + if (error && error.code) return error; + // fetch() rejects on network failures (Ollama not running etc.) + const e = new Error(error instanceof Error ? error.message : 'Unknown Ollama error'); + e.code = aborted ? ERROR_CODES.REQUEST_ABORTED : code; + return e; +} + +/** + * List models installed in Ollama. + * @param {string} host validated host + * @param {AbortSignal} [signal] + * @returns {Promise} model names + */ +export async function listModels(host, signal) { + assertAllowedHost(host); + let response; + try { + response = await fetch(`${host}/api/tags`, { method: 'GET', signal }); + } catch (error) { + throw toExtensionError(error); + } + if (!response.ok) { + const e = new Error(`Ollama /api/tags failed: ${response.status}`); + e.code = response.status === 404 ? ERROR_CODES.MODEL_NOT_FOUND : ERROR_CODES.STREAM_ERROR; + throw e; + } + const data = await response.json(); + if (!data || !Array.isArray(data.models)) return []; + return data.models.map((m) => (m && typeof m.name === 'string' ? m.name : '')).filter((name) => name.length > 0); +} + +/** + * Stream a chat completion. Calls handlers for each incremental text chunk. + * + * @param {object} params + * @param {string} params.host validated Ollama host + * @param {string} params.model + * @param {Array<{role: string, content: string}>} params.messages + * @param {boolean|string} [params.think] true | 'low' | 'medium' | 'high'; omit when off + * @param {object} params.options Ollama options object + * @param {(text: string, thinking: string) => void} params.onChunk + * @param {AbortSignal} [params.signal] + * @returns {Promise} resolves when the stream completes + */ +export async function chatStream({ host, model, messages, think, options, onChunk, signal }) { + assertAllowedHost(host); + + const body = { model, messages, stream: true }; + if (think !== undefined) { + body.think = think; + } + if (options && Object.keys(options).length > 0) { + body.options = options; + } + + let response; + try { + response = await fetch(`${host}/api/chat`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + signal + }); + } catch (error) { + throw toExtensionError(error, { aborted: isAbortError(error) }); + } + + if (!response.ok) { + const e = new Error(`Ollama /api/chat failed: ${response.status}`); + e.code = + response.status === 404 + ? ERROR_CODES.MODEL_NOT_FOUND + : response.status === 400 || response.status === 403 + ? ERROR_CODES.INVALID_SETTINGS + : ERROR_CODES.STREAM_ERROR; + throw e; + } + if (!response.body) { + const e = new Error('Ollama response has no body'); + e.code = ERROR_CODES.STREAM_ERROR; + throw e; + } + + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ''; + + const processLine = (line) => { + if (!line) return; + let parsed; + try { + parsed = JSON.parse(line); + } catch { + // Malformed line: skip it rather than crashing the stream. + return; + } + if (parsed === null || typeof parsed !== 'object') return; + if (parsed.error) { + const e = new Error(String(parsed.error)); + e.code = typeof parsed.error === 'string' && /not found/i.test(parsed.error) ? ERROR_CODES.MODEL_NOT_FOUND : ERROR_CODES.STREAM_ERROR; + throw e; + } + const content = parsed.message && typeof parsed.message.content === 'string' ? parsed.message.content : ''; + const thinking = parsed.message && typeof parsed.message.thinking === 'string' ? parsed.message.thinking : ''; + if (content || thinking) { + onChunk(content, thinking); + } + }; + + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + buffer += decoder.decode(value, { stream: true }); + let newlineIndex; + while ((newlineIndex = buffer.indexOf('\n')) !== -1) { + const line = buffer.slice(0, newlineIndex).replace(/\r$/, ''); + buffer = buffer.slice(newlineIndex + 1); + processLine(line); + } + } + // Flush any remaining buffered line. + const tail = buffer.replace(/\r$/, ''); + if (tail) processLine(tail); + } catch (error) { + if (isAbortError(error)) { + const e = new Error('Request aborted'); + e.code = ERROR_CODES.REQUEST_ABORTED; + throw e; + } + throw error && error.code ? error : toExtensionError(error, { code: ERROR_CODES.STREAM_ERROR }); + } +} + +/** + * @param {*} error + * @returns {boolean} + */ +function isAbortError(error) { + return Boolean(error && (error.name === 'AbortError' || error.code === ERROR_CODES.REQUEST_ABORTED)); +} \ No newline at end of file -- cgit v1.2.3