Skip to content

Phase 1: security & CWS hygiene fixes#4

Merged
froggychips merged 2 commits into
mainfrom
review/phase-1-security-hygiene
May 19, 2026
Merged

Phase 1: security & CWS hygiene fixes#4
froggychips merged 2 commits into
mainfrom
review/phase-1-security-hygiene

Conversation

@froggychips

Copy link
Copy Markdown
Owner

Summary

Первая партия правок по итогам кодревью. Точечные исправления безопасности и подготовка к Chrome Web Store submission — без рефакторинга поведения. Остальные фазы (i18n, provider abstraction, options split, selectors fallback, tooling, docs) пойдут отдельными PR-ами.

Что изменилось

# Файл Что
1.1 background.js Gemini API-ключ передаётся через x-goog-api-key header вместо ?key= в URL — чтобы не утекал в performance-логи браузера и логи прокси
1.2 background.js chrome.runtime.onMessage валидирует sender: разрешены только страницы самого расширения и фреймы *.x.com / *.twitter.com. До этого любой iframe мог дёргать TTA_*
1.3 manifest.json http://localhost/* и http://127.0.0.1/* перенесены в optional_host_permissions — CWS-листинг чище, MCP-разрешение запрашивается runtime'ом
1.4 content_script.js Три копии document.execCommand('insertText') свёрнуты в один helper ttaInsertText() с цепью InputEvent → execCommand → direct assignment
1.5 options.js Persona hint рендерится через DOM API (replaceChildren/textContent), а не innerHTML — закрыт потенциальный XSS, если hint когда-либо станет user-controlled
1.7 dev-logger.js Убраны URL-флаг ?tta_debug=1 и localStorage 'tta_debug' как триггеры — оба контролируются страницей x.com и могли быть взведены вредоносной ссылкой
1.8 content_script.js boot() запускается только в top-frame; манифест по-прежнему all_frames: true, но MutationObserver и подписки больше не множатся в nested iframes

Что НЕ трогалось в этом PR

  • Provider abstraction (callOpenAI/Grok/Gemini duplication) — отдельный PR
  • Options split на модули — отдельный PR
  • i18n / _locales/ — отдельный PR (объёмный)
  • Selectors fallback + DOM-outdated banner — отдельный PR
  • Tooling: esbuild, eslint, prettier, release workflow — отдельный PR
  • Документация: CHANGELOG, ARCHITECTURE, CONTRIBUTING — отдельный PR

Test plan

  • Загрузить unpacked в Chrome → расширение поднимается без ошибок в chrome://extensions
  • Открыть DevTools Network на x.com → запрос к Gemini идёт на …/generateContent (без ?key= в URL); ключ в заголовке x-goog-api-key
  • Открыть DevTools на x.com → попытаться из консоли вкладки про-сторонний chrome.runtime.sendMessage('<extension-id>', {type:'TTA_GET_PREFS'}) — должно отказать с sender_not_allowed
  • Reply / DM compose: вставка текста через TweAI работает (InputEvent или execCommand fallback)
  • Persona hint в options отображается корректно (символы, перенос строки)
  • dev-logger overlay не появляется при открытии x.com/?tta_debug=1 (если пользователь не включал его явно через options)
  • Внутри nested iframe на x.com (если такие есть) MutationObserver не дублируется
  • chrome.storage.local.set({ttaDebugLogs:true}) → overlay появляется (canonical path работает)

🤖 Generated with Claude Code

Точечные правки безопасности и CWS-гигиены без рефакторинга поведения:

- Gemini API-ключ передаётся заголовком x-goog-api-key вместо ?key= в URL,
  чтобы он не попадал в performance-логи браузера и логи прокси.
- chrome.runtime.onMessage теперь валидирует sender: разрешены только
  собственные страницы расширения и фреймы x.com/twitter.com. До этого
  любой iframe из all_frames=true мог дёргать TTA_* команды.
- http://localhost/* и http://127.0.0.1/* перенесены из host_permissions в
  optional_host_permissions: дефолтный CWS-листинг чище, MCP-разрешение
  запрашивается runtime'ом только когда пользователь включит фичу.
- document.execCommand('insertText') трижды дублировался; вынесен в один
  helper ttaInsertText() с цепью: InputEvent (modern) → execCommand
  (legacy) → прямое присваивание value/textContent.
- options.js: persona hint рендерится через DOM API (replaceChildren +
  textContent), а не innerHTML — убирает XSS-вектор если hint когда-либо
  будет содержать user-controlled данные.
- dev-logger.js: удалены URL-флаг ?tta_debug=1 и localStorage 'tta_debug'
  как источники включения; оба контролируются страницей x.com и могли
  быть взведены вредоносной ссылкой. Остался только chrome.storage и
  isDevBuild.
- content_script.js: boot() запускается только в top-frame. Манифест
  по-прежнему all_frames=true ради совместимости с возможными nested
  фреймами X, но MutationObserver и подписки больше не множатся.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3451f7fb81

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread manifest.json
Comment on lines +23 to +26
"optional_host_permissions": [
"http://127.0.0.1/*",
"http://localhost/*"
],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Request localhost permission before MCP fetches

When MCP is configured to http://127.0.0.1:* or http://localhost:*, moving these origins into optional_host_permissions means they are no longer granted at install time, but I found no chrome.permissions.request path for the saved mcpUrl (rg "permissions.request|chrome.permissions" returns none). In MV3 the background fetch(url + path) used by TTA_MCP_STATUS, profile, and tweets therefore loses the host permission for existing/new users unless it was granted some other way, causing the MCP features to report offline despite a valid local gateway.

Useful? React with 👍 / 👎.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@froggychips froggychips merged commit 51eb6cf into main May 19, 2026
1 check failed
@froggychips froggychips deleted the review/phase-1-security-hygiene branch May 19, 2026 07:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant