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) --- README.md | 93 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 README.md (limited to 'README.md') diff --git a/README.md b/README.md new file mode 100644 index 0000000..8c16128 --- /dev/null +++ b/README.md @@ -0,0 +1,93 @@ +# Ollama Translations + +Firefox用WebExtension(Manifest V3)。Webページ上で選択した文字列を、ローカルで動作するOllama LLMで翻訳し、選択箇所付近の小型ポップオーバーへストリーミング表示します。 + +## 特徴 + +- 文字列選択後、選択範囲付近に翻訳アイコンを表示(押すまでOllamaへは一切通信しません) +- Ollama REST API(`POST /api/chat`)+ NDJSONストリーミングで逐次表示 +- 会話履歴なしの1-shot翻訳。同時実行は1件で、新規要求時に旧要求を自動Abort +- Shadow DOMベースのUIでページCSSの影響を受けません +- 翻訳結果はプレーンテキストとして描画(HTML評価なし) +- コピー / 再生成 / 閉じる操作に対応 +- 詳細な生成パラメータ設定(temperature / context length / seed / top_k 等) + +## セキュリティ方針 + +- 依存パッケージゼロ(npm / Node.js 不要)。すべてバニラJS +- Ollama通信はBackgroundのみ。Content Scriptからは直接fetchしません +- 接続先は `http://localhost:` / `http://127.0.0.1:` のみ許可(validator + client側の二重防御) +- LLM出力・ページ文字列は `textContent` のみで描画(innerHTML不使用) +- `eval` / `new Function` / リモートコード不使用 +- 権限は `storage` + localhost系host permissionのみ + +詳細は `doc/Security.md` を参照してください。 + +## ビルド + +Node.js不要。PowerShellのみでパッケージ化できます。 + +```powershell +# アイコン生成(初回のみ、既に生成済みなら不要) +pwsh -NoProfile -File tools/make-icons.ps1 + +# パッケージ (dist/ollama-translations.zip) +pwsh -NoProfile -File build.ps1 +``` + +## Firefoxへのロード(一時アドオン) + +1. Firefoxで `about:debugging#/runtime/this-firefox` を開く +2. 「一時的なアドオンを読み込む…」をクリック +3. 本リポジトリの `manifest.json` を選択 + +## Ollamaの準備 + +1. [Ollama](https://ollama.com/) をインストールし、`ollama serve`(またはアプリを起動)で `http://localhost:11434` を立ち上げる +2. 翻訳用モデルをpullする(例): + +```powershell +ollama pull llama3.2 +``` + +3. 拡張機能のオプション画面(ツールバーアイコン → 「詳細設定を開く」)でモデルを選択して保存 + +## テスト + +ブラウザで `tests/test.html` を開くと単体・結合テスト(71件)が実行されます。オプション画面下部の「開発者向け: テストを実行」リンクからも開けます。 + +テストは npm / Node.js を使わず、自作ランナーでブラウザ内実行されます。 + +## 使用WebExtensions API一覧 + +| API | 用途 | +|---|---| +| `storage.local` | 設定の保存・復元 | +| `storage.onChanged` | 設定変更通知(Content/Background同期) | +| `runtime.connect` / `runtime.Port` | 翻訳ストリーミング通信 | +| `runtime.sendMessage` / `onMessage` | モデル一覧取得(popup/options) | +| `runtime.openOptionsPage` | オプション画面起動 | +| `content_scripts`(manifest宣言) | ページへの注入 | + +## 要求permissionsと理由 + +| 権限 | 理由 | +|---|---| +| `storage` | 設定の永続化(EN-01/Spec §5) | +| `http://localhost/*`, `http://127.0.0.1/*` | ローカルOllamaへのfetch。Firefoxはmatch patternでポート番号指定不可(bug 1362809/1468162)のため任意ポート一致とし、実際の接続先はアプリ側validatorでlocalhost/127.0.0.1のみに制限 | + +## 既知の制限(初期版) + +- iframe内の選択文字列には非対応 +- Firefox内蔵PDF Viewer・Reader View・about:系ページには非対応 +- 翻訳履歴・チャットUIなし +- Markdown/HTMLリッチレンダリングなし(プレーンテキストのみ) +- Chrome/Edge非対応(Firefox優先) +- `tfs_z` / `mirostat*` オプション未対応 + +## ドキュメント + +- `doc/Specifications.md` — 機能仕様 +- `doc/Design.md` — 設計 +- `doc/Security.md` — セキュリティ規定 +- `doc/Testing-Results.md` — テスト実行結果 \ No newline at end of file -- cgit v1.2.3