summaryrefslogtreecommitdiff
path: root/src/background/message-router.js
diff options
context:
space:
mode:
authortanaka takashi <isazaka@gmail.com>2026-09-01 20:10:20 +0900
committertanaka takashi <isazaka@gmail.com>2026-09-01 20:10:20 +0900
commit55e581bab9b600e7c070ec596d3109fc897d2d86 (patch)
tree15ca196a1858696c216946dc9608fae613ad6e5f /src/background/message-router.js
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)
Diffstat (limited to 'src/background/message-router.js')
-rw-r--r--src/background/message-router.js177
1 files changed, 177 insertions, 0 deletions
diff --git a/src/background/message-router.js b/src/background/message-router.js
new file mode 100644
index 0000000..c93fc9d
--- /dev/null
+++ b/src/background/message-router.js
@@ -0,0 +1,177 @@
+/**
+ * Message router (background).
+ *
+ * - runtime.Port ('translation-stream'): translate / cancel requests from
+ * the content script, streaming started/chunk/completed/error back.
+ * - runtime.onMessage: one-shot listModels request for popup/options.
+ *
+ * All inbound messages are validated; invalid ones are discarded
+ * (Specifications.md SEC-06, Design.md §8.4).
+ */
+
+import {
+ CONTENT_TO_BG,
+ BG_TO_CONTENT,
+ RUNTIME_MESSAGES,
+ MAX_SELECTION_LENGTH,
+ ERROR_CODES
+} from '../shared/constants.js';
+import { isValidTranslateRequest, isValidCancelRequest, isTrustedSender } from '../shared/messages.js';
+import { getSettings } from './settings-service.js';
+import { TranslationSession } from './translation-session.js';
+import { chatStream, listModels } from './ollama-client.js';
+import { buildSystemPrompt } from '../shared/prompt.js';
+import { buildOptions, toApiThinking } from '../shared/settings-schema.js';
+
+const session = new TranslationSession();
+
+/** User-facing messages per error code (kept minimal; no stack traces). */
+const ERROR_MESSAGES = {
+ [ERROR_CODES.INVALID_REQUEST]: '要求が不正です。',
+ [ERROR_CODES.TEXT_EMPTY]: '選択文字列が空です。',
+ [ERROR_CODES.TEXT_TOO_LONG]: `選択文字列が長すぎます(上限 ${MAX_SELECTION_LENGTH} 文字)。`,
+ [ERROR_CODES.OLLAMA_UNAVAILABLE]: 'Ollamaに接続できません。Ollamaが起動しているか確認してください。',
+ [ERROR_CODES.MODEL_NOT_FOUND]: '指定されたモデルが見つかりません。',
+ [ERROR_CODES.INVALID_SETTINGS]: '設定値が不正です。設定画面を確認してください。',
+ [ERROR_CODES.REQUEST_ABORTED]: '翻訳を中断しました。',
+ [ERROR_CODES.STREAM_ERROR]: '翻訳中にエラーが発生しました。',
+ [ERROR_CODES.UNKNOWN_ERROR]: '不明なエラーが発生しました。'
+};
+
+/**
+ * Handle one content-script port connection.
+ * @param {object} port runtime.Port
+ */
+export function handleConnection(port) {
+ if (!port || port.name !== 'translation-stream') return;
+
+ port.onMessage.addListener((message) => {
+ if (!isTrustedSender(port.sender)) return;
+
+ if (isValidTranslateRequest(message)) {
+ void runTranslation(port, message.requestId, message.text);
+ return;
+ }
+ if (isValidCancelRequest(message)) {
+ if (session.isActive(message.requestId)) {
+ session.clear(message.requestId);
+ }
+ return;
+ }
+ // Invalid message: discard silently (do not echo details to the page).
+ });
+
+ port.onDisconnect.addListener(() => {
+ // If the tab goes away, abort the translation owned by this port.
+ if (session.hasActive() && session.active.port === port) {
+ const requestId = session.active.requestId;
+ session.clear(requestId);
+ }
+ });
+}
+
+/**
+ * Run one translation: settings -> prompt -> Ollama stream -> port messages.
+ * @param {object} port
+ * @param {string} requestId
+ * @param {string} text
+ */
+async function runTranslation(port, requestId, text) {
+ const settings = await getSettings();
+
+ if (!settings.enabled) {
+ postError(port, requestId, ERROR_CODES.INVALID_REQUEST, 'Translation is disabled');
+ return;
+ }
+ if (!settings.model) {
+ postError(port, requestId, ERROR_CODES.INVALID_SETTINGS, 'No model configured');
+ return;
+ }
+
+ const controller = session.start(requestId, port);
+
+ port.postMessage({ type: BG_TO_CONTENT.STARTED, requestId, model: settings.model });
+
+ try {
+ await chatStream({
+ host: settings.ollamaHost,
+ model: settings.model,
+ messages: [
+ { role: 'system', content: buildSystemPrompt(settings) },
+ { role: 'user', content: text }
+ ],
+ think: toApiThinking(settings),
+ options: buildOptions(settings),
+ signal: controller.signal,
+ onChunk: (content) => {
+ // Drop chunks if a newer request took over.
+ if (!session.isActive(requestId)) return;
+ port.postMessage({ type: BG_TO_CONTENT.CHUNK, requestId, text: content });
+ }
+ });
+ if (session.isActive(requestId)) {
+ port.postMessage({ type: BG_TO_CONTENT.COMPLETED, requestId });
+ }
+ } catch (error) {
+ const code = (error && error.code) || ERROR_CODES.UNKNOWN_ERROR;
+ // Aborted requests are reported by TranslationSession.abortActive();
+ // avoid a duplicate error for the same requestId.
+ if (code !== ERROR_CODES.REQUEST_ABORTED && session.isActive(requestId)) {
+ postError(port, requestId, code, error && error.message ? error.message : '');
+ }
+ } finally {
+ session.clear(requestId);
+ }
+}
+
+/**
+ * @param {object} port
+ * @param {string} requestId
+ * @param {string} code
+ * @param {string} message
+ */
+function postError(port, requestId, code, message) {
+ try {
+ port.postMessage({ type: BG_TO_CONTENT.ERROR, requestId, code, message: ERROR_MESSAGES[code] || ERROR_MESSAGES[ERROR_CODES.UNKNOWN_ERROR] });
+ } catch {
+ // port may be disconnected
+ }
+}
+
+/**
+ * Register one-shot message handling (popup / options).
+ * @param {object} browserApi injectable for tests
+ */
+export function registerRuntimeMessageHandler(browserApi) {
+ const b = browserApi || globalThis.browser;
+ b.runtime.onMessage.addListener((message, sender) => {
+ if (!isTrustedSender(sender)) return Promise.resolve({ ok: false, error: ERROR_CODES.INVALID_REQUEST });
+ if (message && message.type === RUNTIME_MESSAGES.LIST_MODELS) {
+ return (async () => {
+ try {
+ const settings = await getSettings(browserApi);
+ const models = await listModels(settings.ollamaHost);
+ return { ok: true, models };
+ } catch (error) {
+ return { ok: false, error: (error && error.code) || ERROR_CODES.OLLAMA_UNAVAILABLE, message: (error && error.message) || '' };
+ }
+ })();
+ }
+ return Promise.resolve({ ok: false, error: ERROR_CODES.INVALID_REQUEST });
+ });
+}
+
+/**
+ * Test-only hook: inject a browser API so the router can be exercised
+ * outside a real extension context. Not used at runtime.
+ * @param {object} browserApi
+ * @visibleForTesting
+ */
+export function __setBrowserApiForTests(browserApi) {
+ testBrowserApi = browserApi;
+ browserApi.runtime.onConnect.addListener(handleConnection);
+ registerRuntimeMessageHandler(browserApi);
+}
+
+/** @type {object|null} test-injected browser api */
+let testBrowserApi = null; \ No newline at end of file