+ +
diff --git a/packages/flow/chrome_extension/sidepanel.js b/packages/flow/chrome_extension/sidepanel.js index 821d686e92..636236667f 100644 --- a/packages/flow/chrome_extension/sidepanel.js +++ b/packages/flow/chrome_extension/sidepanel.js @@ -34,11 +34,15 @@ const statusLineEl = document.getElementById('status-line'); const runMetaEl = document.getElementById('run-meta'); const errorBannerEl = document.getElementById('error-banner'); + const authPauseContainerEl = document.getElementById('auth-pause-container'); + const popupBannerContainerEl = document.getElementById('popup-banner-container'); const receiptContainerEl = document.getElementById('receipt-container'); const haltsContainerEl = document.getElementById('halts-container'); const emptyStateEl = document.getElementById('empty-state'); let currentState = null; + let currentAuthPause = null; + let currentPopupState = null; let lastRenderedStateKey = '__uninitialized__'; let syncInFlight = false; @@ -69,7 +73,10 @@ }); } - function deriveStatusBadge(state) { + function deriveStatusBadge(state, authPause) { + if (authPause && authPause.paused) { + return { text: 'Sign-In Paused', status: 'auth_paused' }; + } if (!state) { return { text: 'Idle', status: 'idle' }; } @@ -511,15 +518,147 @@ runMetaEl.hidden = false; } - function renderState(state) { - const serialized = JSON.stringify(state || null); + function renderAuthPauseCard(authPause) { + if (!authPauseContainerEl) return; + authPauseContainerEl.textContent = ''; + if (!authPause || !authPause.paused) { + authPauseContainerEl.hidden = true; + return; + } + + const card = document.createElement('article'); + card.id = 'auth-pause-card'; + card.className = 'auth-pause-card'; + card.setAttribute('data-auth-kind', String(authPause.kind || 'sign_in')); + + const header = document.createElement('div'); + header.className = 'auth-pause-header'; + const badge = document.createElement('span'); + badge.className = 'auth-pause-badge'; + const hostAcked = Boolean(authPause.hostAcked); + badge.textContent = hostAcked + ? authPause.kind === 'mfa' + ? 'MFA Capture Paused' + : 'Sign-In Capture Paused' + : 'Sign-In Notice (Local Only)'; + header.appendChild(badge); + card.appendChild(header); + + const title = document.createElement('h2'); + title.className = 'auth-pause-title'; + title.textContent = 'Sign in directly in Chrome to continue'; + card.appendChild(title); + + const body = document.createElement('p'); + body.className = 'auth-pause-copy'; + body.textContent = hostAcked + ? 'Browser evidence and network capture are paused on this tab, and the local OpenAdapt host recorded the sign-in pause. Complete sign-in in Chrome, then click Resume.' + : 'Browser evidence and network capture are paused locally on this tab (the local OpenAdapt host is not attached). Sign in normally in Chrome, then dismiss or reconnect.'; + card.appendChild(body); + + const actions = document.createElement('div'); + actions.className = 'halt-actions'; + const resumeBtn = document.createElement('button'); + resumeBtn.type = 'button'; + resumeBtn.id = 'auth-resume-btn'; + resumeBtn.className = 'action-btn btn-primary'; + resumeBtn.setAttribute('data-action', 'auth_resume'); + resumeBtn.textContent = hostAcked ? 'I Signed In — Resume' : 'Dismiss Notice'; + resumeBtn.addEventListener('click', async () => { + resumeBtn.disabled = true; + const resp = await sendRuntimeMessage({ + type: 'COPILOT_AUTH_RESUME', + tabId: Number.isInteger(authPause.tabId) ? authPause.tabId : undefined, + }); + resumeBtn.disabled = false; + if (!resp || resp.ok !== true) { + showCardFeedback( + card, + `Could not resume: ${(resp && resp.error) || 'native host rejected resume'}`, + true + ); + return; + } + lastRenderedStateKey = '__force_rerender__'; + void syncState({ forceScroll: false }); + }); + actions.appendChild(resumeBtn); + card.appendChild(actions); + + authPauseContainerEl.appendChild(card); + authPauseContainerEl.hidden = false; + } + + function renderPopupBanner(popupState) { + if (!popupBannerContainerEl) return; + popupBannerContainerEl.textContent = ''; + if (!popupState || !Number.isInteger(popupState.childTabId)) { + popupBannerContainerEl.hidden = true; + return; + } + + const card = document.createElement('article'); + card.id = 'popup-banner-card'; + card.className = 'popup-banner-card'; + card.setAttribute('data-child-tab-id', String(popupState.childTabId)); + if (Number.isInteger(popupState.parentTabId)) { + card.setAttribute('data-parent-tab-id', String(popupState.parentTabId)); + } + + const title = document.createElement('div'); + title.className = 'popup-banner-title'; + title.textContent = 'Estimator / Child Pop-Up Active'; + card.appendChild(title); + + const copy = document.createElement('p'); + copy.className = 'popup-banner-copy'; + const originText = popupState.childOrigin ? ` (${popupState.childOrigin})` : ''; + copy.textContent = + `Tracking child window${originText}. Closing it returns focus to your parent quoting tab automatically.`; + card.appendChild(copy); + + const actions = document.createElement('div'); + actions.className = 'halt-actions'; + const returnBtn = document.createElement('button'); + returnBtn.type = 'button'; + returnBtn.id = 'popup-return-btn'; + returnBtn.className = 'action-btn'; + returnBtn.setAttribute('data-action', 'return_to_parent'); + returnBtn.textContent = 'Return to Parent Tab'; + returnBtn.addEventListener('click', async () => { + returnBtn.disabled = true; + await sendRuntimeMessage({ + type: 'COPILOT_RETURN_TO_PARENT', + childTabId: popupState.childTabId, + }); + returnBtn.disabled = false; + lastRenderedStateKey = '__force_rerender__'; + void syncState({ forceScroll: false }); + }); + actions.appendChild(returnBtn); + card.appendChild(actions); + + popupBannerContainerEl.appendChild(card); + popupBannerContainerEl.hidden = false; + } + + function renderState(state, extras) { + const authPause = extras && extras.authPause ? extras.authPause : null; + const popupState = extras && extras.popupState ? extras.popupState : null; + const serialized = JSON.stringify({ + state: state || null, + authPause, + popupState, + }); if (serialized === lastRenderedStateKey) { return; } lastRenderedStateKey = serialized; currentState = state || null; + currentAuthPause = authPause; + currentPopupState = popupState; - const badge = deriveStatusBadge(currentState); + const badge = deriveStatusBadge(currentState, currentAuthPause); statusPillEl.textContent = badge.text; statusPillEl.setAttribute('data-status', badge.status); @@ -531,11 +670,16 @@ const pct = total > 0 ? Math.min(100, Math.round((filled / total) * 100)) : 0; progressFillEl.style.width = `${pct}%`; - statusLineEl.textContent = currentState - ? String(currentState.status_line || '') - : 'Waiting for an active local form session.'; + statusLineEl.textContent = + currentAuthPause && currentAuthPause.paused + ? 'Capture paused on sign-in / MFA screen. Sign in in Chrome, then click Resume.' + : currentState + ? String(currentState.status_line || '') + : 'Waiting for an active local form session.'; renderRunMeta(currentState); + renderAuthPauseCard(currentAuthPause); + renderPopupBanner(currentPopupState); renderReceiptCard(currentState); haltsContainerEl.textContent = ''; @@ -545,8 +689,13 @@ haltsContainerEl.appendChild(renderHaltCard(halt)); } + const hasAuthPause = Boolean(currentAuthPause && currentAuthPause.paused); + const hasPopup = Boolean(currentPopupState && Number.isInteger(currentPopupState.childTabId)); const showEmpty = - halts.length === 0 && (!currentState || currentState.outcome !== 'verified_done'); + halts.length === 0 && + !hasAuthPause && + !hasPopup && + (!currentState || currentState.outcome !== 'verified_done'); emptyStateEl.hidden = !showEmpty; } @@ -569,18 +718,22 @@ type: 'COPILOT_SYNC_STATE', forceScroll, }); + const extras = { + authPause: resp && resp.authPause ? resp.authPause : null, + popupState: resp && resp.popupState ? resp.popupState : null, + }; if (!resp || !resp.ok) { if (resp && resp.error === 'no_recording_dir') { setErrorBanner(''); - renderState(null); + renderState(null, extras); } else { setErrorBanner((resp && resp.error) || 'unavailable'); - if (!currentState) renderState(null); + renderState(currentState, extras); } return; } setErrorBanner(''); - renderState(resp.state || null); + renderState(resp.state || null, extras); } finally { syncInFlight = false; } diff --git a/packages/flow/tests/test_chrome_extension_cws.py b/packages/flow/tests/test_chrome_extension_cws.py new file mode 100644 index 0000000000..e0b57fefdf --- /dev/null +++ b/packages/flow/tests/test_chrome_extension_cws.py @@ -0,0 +1,932 @@ +"""Tests for the Chrome Web Store-ready MV3 OpenAdapt Co-Pilot Extension. + +Covers: +1. MV3 manifest, icon PNG dimensions, CSP (no inline scripts/eval), and + STORE_LISTING.md permission/privacy documentation. +2. Deterministic CWS zip packaging via ``scripts/package_chrome_extension.py``. +3. Pop-up window / estimator return handling in ``background.js`` (Node VM). +4. Operator-owned sign-in / MFA interstitial pause & resume in ``content.js`` + and ``background.js`` with strict zero-credential-capture proof (Node VM). +5. Side panel UI contracts for auth-pause and pop-up return controls. +""" + +from __future__ import annotations + +import importlib.util +import json +import shutil +import subprocess +import zipfile +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[3] +EXT_DIR = REPO_ROOT / "packages" / "flow" / "chrome_extension" +PACKAGER_SCRIPT = REPO_ROOT / "scripts" / "package_chrome_extension.py" + + +def _load_packager(): + spec = importlib.util.spec_from_file_location( + "package_chrome_extension", PACKAGER_SCRIPT + ) + assert spec is not None and spec.loader is not None + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def _run_node(script: str) -> dict: + node = shutil.which("node") + if not node: + pytest.skip("node not installed") + proc = subprocess.run( + [node, "-e", script], + capture_output=True, + text=True, + timeout=15, + check=False, + ) + assert proc.returncode == 0, ( + f"node failed:\nSTDOUT:\n{proc.stdout}\nSTDERR:\n{proc.stderr}" + ) + return json.loads(proc.stdout.strip()) + + +def test_manifest_and_extension_pass_cws_validation() -> None: + packager = _load_packager() + errors = packager.validate_extension_dir(EXT_DIR) + assert errors == [], f"Unexpected CWS validation errors: {errors}" + + manifest = json.loads((EXT_DIR / "manifest.json").read_text(encoding="utf-8")) + assert manifest["manifest_version"] == 3 + assert int(manifest["minimum_chrome_version"]) >= 116 + assert len(manifest["description"]) <= 132 + assert manifest["side_panel"]["default_path"] == "sidepanel.html" + assert "sidePanel" in manifest["permissions"] + assert "storage" in manifest["permissions"] + # Least privilege: unused scripting, redundant activeTab, and redundant tabs must not be declared. + assert "scripting" not in manifest["permissions"] + assert "activeTab" not in manifest["permissions"] + assert "tabs" not in manifest["permissions"] + + +def test_store_listing_covers_every_permission_and_zero_egress() -> None: + listing_path = EXT_DIR / "STORE_LISTING.md" + assert listing_path.is_file() + text = listing_path.read_text(encoding="utf-8") + + manifest = json.loads((EXT_DIR / "manifest.json").read_text(encoding="utf-8")) + for perm in manifest["permissions"]: + assert f"`{perm}`" in text, ( + f"Permission {perm!r} missing justification in STORE_LISTING.md" + ) + for host in manifest.get("host_permissions", []): + assert f"`{host}`" in text, ( + f"Host permission {host!r} missing in STORE_LISTING.md" + ) + + assert manifest["description"] in text + assert "Single Purpose Statement" in text + assert "Privacy Policy" in text + assert "Zero Credential Capture" in text + assert "https://openadapt.ai/privacy-policy" in text + assert "hello@openadapt.ai" in text + assert "non-secret form values" in text + assert "### `scripting`" not in text + assert "### `activeTab`" not in text + assert "### `tabs`" not in text + + # Ensure user-facing Store Listing Copy section avoids implementation jargon + section1 = text.split("## 1. Store Listing Copy")[1].split("## 2. Single Purpose")[ + 0 + ] + for jargon in ("Manifest V3", "service worker", "content script", "chrome.storage"): + assert jargon.lower() not in section1.lower(), ( + f"Implementation jargon {jargon!r} found in user-facing store listing copy" + ) + + +def test_cws_zip_packager_produces_clean_archive(tmp_path: Path) -> None: + packager = _load_packager() + out_zip = tmp_path / "openadapt-copilot-cws.zip" + members = packager.build_cws_zip(EXT_DIR, out_zip) + + assert out_zip.is_file() + assert "manifest.json" in members + assert "background.js" in members + assert "content.js" in members + assert "sidepanel.html" in members + assert "sidepanel.js" in members + assert "sidepanel.css" in members + assert "network_redact.js" in members + assert "icons/icon16.png" in members + assert "icons/icon48.png" in members + assert "icons/icon128.png" in members + + # Must exclude developer / store docs and native host scripts + for forbidden in ("STORE_LISTING.md", "README.md"): + assert forbidden not in members + assert not any(m.startswith("native_host/") for m in members) + + # Verify archive integrity + with zipfile.ZipFile(out_zip, "r") as zf: + assert zf.testzip() is None + assert sorted(zf.namelist()) == sorted(members) + + +def test_background_popup_tracking_and_return_to_parent() -> None: + bg_path = str(EXT_DIR / "background.js") + script = f""" +const fs = require('fs'); +const vm = require('vm'); + +const listeners = {{ + onMessage: [], + tabsCreated: [], + tabsRemoved: [], + windowsRemoved: [], + windowsFocusChanged: [], +}}; +const sessionStore = {{}}; +const tabsUpdated = []; +const windowsUpdated = []; +const tabsById = {{ + 10: {{ id: 10, windowId: 1, url: 'https://carrier.example.com/quote' }}, + 25: {{ id: 25, windowId: 2, openerTabId: 10, url: 'https://estimator.example.com/calc' }}, +}}; + +const chromeMock = {{ + runtime: {{ + lastError: null, + getURL: (p) => 'chrome-extension://testext/' + p, + onMessage: {{ addListener: (fn) => listeners.onMessage.push(fn) }}, + onInstalled: {{ addListener: () => {{}} }}, + connectNative: () => {{ throw new Error('offline'); }}, + }}, + action: {{ + onClicked: {{ addListener: () => {{}} }}, + setBadgeText: () => {{}}, + setBadgeBackgroundColor: () => {{}}, + setTitle: () => {{}}, + }}, + sidePanel: {{ + setPanelBehavior: () => Promise.resolve(), + }}, + storage: {{ + session: {{ + get: (keys, cb) => cb && cb(Object.assign({{}}, sessionStore)), + set: (obj, cb) => {{ Object.assign(sessionStore, obj); if (cb) cb(); }}, + remove: (key, cb) => {{ delete sessionStore[key]; if (cb) cb(); }}, + }}, + }}, + tabs: {{ + onCreated: {{ addListener: (fn) => listeners.tabsCreated.push(fn) }}, + onRemoved: {{ addListener: (fn) => listeners.tabsRemoved.push(fn) }}, + get: (tabId, cb) => {{ const t = tabsById[tabId] || null; if (cb) cb(t); return Promise.resolve(t); }}, + query: (q, cb) => cb(Object.values(tabsById)), + update: (tabId, props, cb) => {{ tabsUpdated.push({{ tabId, props }}); if (cb) cb(); }}, + sendMessage: (tabId, msg, cb) => {{ if (cb) cb(); }}, + }}, + windows: {{ + onRemoved: {{ addListener: (fn) => listeners.windowsRemoved.push(fn) }}, + onFocusChanged: {{ addListener: (fn) => listeners.windowsFocusChanged.push(fn) }}, + update: (windowId, props, cb) => {{ windowsUpdated.push({{ windowId, props }}); if (cb) cb(); }}, + }}, + webRequest: {{ + onBeforeRequest: {{ addListener: () => {{}} }}, + onBeforeSendHeaders: {{ addListener: () => {{}} }}, + onCompleted: {{ addListener: () => {{}} }}, + onErrorOccurred: {{ addListener: () => {{}} }}, + }}, +}}; + +const ctx = vm.createContext({{ + chrome: chromeMock, + globalThis: {{}}, + importScripts: () => {{}}, + URL, + Date, + Map, + Set, + Promise, + setTimeout, + clearTimeout, +}}); +ctx.globalThis = ctx; +vm.runInContext(fs.readFileSync({json.dumps(bg_path)}, 'utf8'), ctx); + +async function sendMsg(msg, senderUrl) {{ + return new Promise((resolve) => {{ + listeners.onMessage[0](msg, {{ url: senderUrl }}, resolve); + }}); +}} + +(async () => {{ + // 0. Outside an active run, child tabs must NOT be tracked or steal focus + listeners.tabsCreated[0](tabsById[25]); + await new Promise((r) => setTimeout(r, 20)); + const outsideRunPopup = await sendMsg( + {{ type: 'COPILOT_GET_POPUP_STATE' }}, + 'chrome-extension://testext/sidepanel.html' + ); + + // Activate run on tab 10; child tab opened from unrelated tab 99 must be ignored + ctx.__openadaptExtensionBackground.setActiveRunTab(10); + listeners.tabsCreated[0]({{ id: 30, windowId: 3, openerTabId: 99, url: 'https://other.example.com' }}); + await new Promise((r) => setTimeout(r, 20)); + const unrelatedOpenerPopup = await sendMsg( + {{ type: 'COPILOT_GET_POPUP_STATE' }}, + 'chrome-extension://testext/sidepanel.html' + ); + + // 1. Child popup tab opens from active run's parent quoting tab 10 + listeners.tabsCreated[0](tabsById[25]); + await new Promise((r) => setTimeout(r, 20)); + + // 2. Non-sidepanel sender is rejected + const rejected = await sendMsg({{ type: 'COPILOT_GET_POPUP_STATE' }}, 'https://evil.example.com/'); + + // 3. Side panel queries popup state + const stateResp = await sendMsg( + {{ type: 'COPILOT_GET_POPUP_STATE' }}, + 'chrome-extension://testext/sidepanel.html' + ); + + // 4. Operator clicks Return to Parent Tab + const manualReturn = await sendMsg( + {{ type: 'COPILOT_RETURN_TO_PARENT', childTabId: 25 }}, + 'chrome-extension://testext/sidepanel.html' + ); + + // 5. Child popup closes -> auto-returns focus to parent tab 10 / window 1 + listeners.tabsRemoved[0](25); + await new Promise((r) => setTimeout(r, 20)); + + const afterClose = await sendMsg( + {{ type: 'COPILOT_GET_POPUP_STATE' }}, + 'chrome-extension://testext/sidepanel.html' + ); + + console.log(JSON.stringify({{ + outsideRunPopup: outsideRunPopup.popup, + unrelatedOpenerPopup: unrelatedOpenerPopup.popup, + rejected, + popupBeforeClose: stateResp.popup, + manualReturnOk: manualReturn.ok, + afterClosePopup: afterClose.popup, + tabsUpdated, + windowsUpdated, + persistedKeys: Object.keys(sessionStore), + }})); +}})(); +""" + out = _run_node(script) + assert out["outsideRunPopup"] is None + assert out["unrelatedOpenerPopup"] is None + assert out["rejected"]["ok"] is False + assert out["rejected"]["error"] == "copilot_requires_sidepanel" + assert out["popupBeforeClose"]["childTabId"] == 25 + assert out["popupBeforeClose"]["parentTabId"] == 10 + assert out["popupBeforeClose"]["childOrigin"] == "https://estimator.example.com" + assert out["manualReturnOk"] is True + assert out["afterClosePopup"] is None + assert len(out["tabsUpdated"]) >= 2 + assert out["tabsUpdated"][-1] == {"tabId": 10, "props": {"active": True}} + assert out["windowsUpdated"][-1] == {"windowId": 1, "props": {"focused": True}} + + +def test_auth_interstitial_detection_and_pause_never_reads_credentials() -> None: + content_path = str(EXT_DIR / "content.js") + bg_path = str(EXT_DIR / "background.js") + script = f""" +const fs = require('fs'); +const vm = require('vm'); + +// Part A: Test content.js detectAuthInterstitial with a trapping .value getter +let valueReadCount = 0; +function makeInput(attrs) {{ + const el = {{ + tagName: 'INPUT', + getAttribute: (k) => (k in attrs ? attrs[k] : null), + }}; + Object.defineProperty(el, 'value', {{ + get() {{ + valueReadCount += 1; + throw new Error('SECURITY VIOLATION: .value must never be read during auth detection'); + }}, + }}); + Object.defineProperty(el, 'defaultValue', {{ + get() {{ + valueReadCount += 1; + throw new Error('SECURITY VIOLATION: .defaultValue must never be read'); + }}, + }}); + return el; +}} + +const sentToRuntime = []; +const contentCtx = vm.createContext({{ + chrome: {{ + runtime: {{ + onMessage: {{ addListener: () => {{}} }}, + sendMessage: (msg, cb) => {{ sentToRuntime.push(msg); if (cb) cb({{ ok: true }}); }}, + }}, + }}, + window: {{ + addEventListener: () => {{}}, + location: {{ href: 'https://portal.example.com/login?token=secret', origin: 'https://portal.example.com', pathname: '/login' }}, + innerWidth: 1280, + innerHeight: 800, + scrollX: 0, + scrollY: 0, + }}, + document: {{ + addEventListener: () => {{}}, + readyState: 'complete', + querySelectorAll: () => [], + head: null, + documentElement: null, + }}, + location: {{ href: 'https://portal.example.com/login?token=secret', origin: 'https://portal.example.com', pathname: '/login' }}, + Element: function() {{}}, + URL, + Date, + Map, + Set, + WeakSet, + WeakMap, +}}); +contentCtx.globalThis = contentCtx; +vm.runInContext(fs.readFileSync({json.dumps(content_path)}, 'utf8'), contentCtx); + +const {{ detectAuthInterstitial }} = contentCtx.__openadaptExtensionContent; + +// 1. MFA / OTP screen +const mfaInput = makeInput({{ type: 'text', autocomplete: 'one-time-code', name: 'mfa_code' }}); +const mfaDoc = {{ + querySelectorAll: (sel) => (sel === 'input' ? [mfaInput] : []), +}}; +const mfaResult = detectAuthInterstitial(mfaDoc); + +// 2. Password sign-in screen +const pwdInput = makeInput({{ type: 'password', autocomplete: 'current-password', name: 'pass' }}); +const pwdDoc = {{ + querySelectorAll: (sel) => (sel === 'input' ? [pwdInput] : []), +}}; +const pwdResult = detectAuthInterstitial(pwdDoc); + +// 3. Normal non-auth form screen +const normalInput = makeInput({{ type: 'text', name: 'applicant_name' }}); +const normalDoc = {{ + querySelectorAll: (sel) => (sel === 'input' ? [normalInput] : []), +}}; +const normalResult = detectAuthInterstitial(normalDoc); + +// Part B: Feed detection into background.js with native host ack + fail-closed resume + per-tab clearing +const bgListeners = []; +const tabUpdatedListeners = []; +const tabRemovedListeners = []; +const badgeHistory = []; +const sessionStore = {{}}; +const nativeMessages = []; +let rejectNextResume = true; + +function makeMockNativePort() {{ + const msgListeners = []; + const disconnectListeners = []; + return {{ + onMessage: {{ addListener: (fn) => msgListeners.push(fn) }}, + onDisconnect: {{ addListener: (fn) => disconnectListeners.push(fn) }}, + postMessage: (payload) => {{ + nativeMessages.push(payload); + let reply = {{ ok: true, request_id: payload.request_id }}; + if (payload.type === 'COPILOT_AUTH_PAUSED') {{ + reply = {{ ok: true, type: 'COPILOT_AUTH_PAUSED_ACK', paused: true, tab_id: payload.tab_id, request_id: payload.request_id }}; + }} else if (payload.type === 'COPILOT_AUTH_RESUMED') {{ + if (rejectNextResume) {{ + rejectNextResume = false; + reply = {{ ok: false, error: 'copilot_auth_resume_rejected', request_id: payload.request_id }}; + }} else {{ + // Inject a stale late COPILOT_STATE reply before the real ack to prove + // request_id matching ignores mismatched/late replies. + setTimeout(() => {{ + for (const fn of msgListeners) {{ + fn({{ ok: true, type: 'COPILOT_STATE', state: null, request_id: 'req_stale_999' }}); + }} + }}, 1); + reply = {{ ok: true, type: 'COPILOT_AUTH_RESUMED_ACK', paused: false, resumed: true, request_id: payload.request_id }}; + }} + }} else if (payload.type === 'COPILOT_GET_STATE') {{ + reply = {{ ok: true, type: 'COPILOT_STATE', state: {{ run_id: 'run_1', outcome: 'halted_needs_human', halts: [] }}, request_id: payload.request_id }}; + }} + setTimeout(() => {{ + for (const fn of msgListeners) fn(reply); + }}, 5); + }}, + disconnect: () => {{}}, + }}; +}} + +const tabMessages = []; +const webReqListeners = {{}}; +const bgCtx = vm.createContext({{ + chrome: {{ + runtime: {{ + lastError: null, + getURL: (p) => 'chrome-extension://testext/' + p, + onMessage: {{ addListener: (fn) => bgListeners.push(fn) }}, + onInstalled: {{ addListener: () => {{}} }}, + connectNative: () => makeMockNativePort(), + }}, + action: {{ + onClicked: {{ addListener: () => {{}} }}, + setBadgeText: (o) => badgeHistory.push(o.text), + setBadgeBackgroundColor: () => {{}}, + setTitle: () => {{}}, + }}, + sidePanel: {{ setPanelBehavior: () => Promise.resolve() }}, + storage: {{ + session: {{ + get: (k, cb) => cb && cb(Object.assign({{}}, sessionStore)), + set: (o, cb) => {{ Object.assign(sessionStore, o); if (cb) cb(); }}, + remove: (k, cb) => {{ delete sessionStore[k]; if (cb) cb(); }}, + }}, + }}, + tabs: {{ + onCreated: {{ addListener: () => {{}} }}, + onUpdated: {{ addListener: (fn) => tabUpdatedListeners.push(fn) }}, + onRemoved: {{ addListener: (fn) => tabRemovedListeners.push(fn) }}, + query: (q, cb) => cb([{{ id: 42, active: true, url: 'https://portal.example.com/quote' }}]), + sendMessage: (id, m, cb) => {{ tabMessages.push({{ tabId: id, msg: m }}); if (cb) cb(); }}, + }}, + windows: {{ + onRemoved: {{ addListener: () => {{}} }}, + onFocusChanged: {{ addListener: () => {{}} }}, + }}, + webRequest: {{ + onBeforeRequest: {{ addListener: (fn) => {{ webReqListeners.before = fn; }} }}, + onBeforeSendHeaders: {{ addListener: (fn) => {{ webReqListeners.headers = fn; }} }}, + onCompleted: {{ addListener: (fn) => {{ webReqListeners.completed = fn; }} }}, + onErrorOccurred: {{ addListener: (fn) => {{ webReqListeners.error = fn; }} }}, + }}, + }}, + importScripts: () => {{}}, + URL, + Date, + Map, + Set, + Promise, + setTimeout, + clearTimeout, +}}); +bgCtx.globalThis = bgCtx; +vm.runInContext(fs.readFileSync({json.dumps(bg_path)}, 'utf8'), bgCtx); + +function sendBg(msg, sender) {{ + return new Promise((resolve) => bgListeners[0](msg, sender, resolve)); +}} + +(async () => {{ + // 0. SET_RECORDING rejects content-script/tab senders, allows sidepanel + const badSetRec = await sendBg( + {{ type: 'SET_RECORDING', active: true }}, + {{ tab: {{ id: 42 }}, url: 'https://portal.example.com/quote' }} + ); + const okSetRec = await sendBg( + {{ type: 'SET_RECORDING', active: true }}, + {{ url: 'chrome-extension://testext/sidepanel.html' }} + ); + + // 1. Missing tab sender is rejected; subframe & idle-tab detections are ignored + const missingTabResp = await sendBg( + {{ type: 'AUTH_INTERSTITIAL_DETECTED', kind: 'mfa', signals: ['mfa_input'] }}, + {{ origin: 'https://portal.example.com' }} + ); + const idleResp = await sendBg( + {{ type: 'AUTH_INTERSTITIAL_DETECTED', kind: 'mfa', signals: ['mfa_input'] }}, + {{ tab: {{ id: 42 }}, frameId: 0, origin: 'https://portal.example.com' }} + ); + + // 2. Real COPILOT_SYNC_STATE wires activeRunTabId=42 from active tab and broadcasts SET_RUN_ACTIVE + const initialSync = await sendBg( + {{ type: 'COPILOT_SYNC_STATE' }}, + {{ url: 'chrome-extension://testext/sidepanel.html' }} + ); + const wiredRunTabId = bgCtx.__openadaptExtensionBackground.activeRunTabId; + const subframeResp = await sendBg( + {{ type: 'AUTH_INTERSTITIAL_DETECTED', kind: 'mfa', signals: ['mfa_input'] }}, + {{ tab: {{ id: 42 }}, frameId: 2, origin: 'https://ad.example.com' }} + ); + + // 3. Top-frame detection on active run tab 42 sends COPILOT_AUTH_PAUSED, + // notifies content script SET_AUTH_PAUSED(true), and pauses capture + const detectResp = await sendBg( + {{ + type: 'AUTH_INTERSTITIAL_DETECTED', + kind: mfaResult.kind, + signals: mfaResult.signals, + }}, + {{ tab: {{ id: 42 }}, frameId: 0, origin: 'https://portal.example.com' }} + ); + + // Evidence and webRequest capture for paused tab 42 MUST be dropped + const pausedEvResp = await sendBg( + {{ type: 'EXTENSION_EVIDENCE', evidence: {{ kind: 'target', event: 'input' }} }}, + {{ tab: {{ id: 42 }}, frameId: 0, origin: 'https://portal.example.com' }} + ); + webReqListeners.before({{ + requestId: 'r_paused', + method: 'POST', + url: 'https://portal.example.com/login', + tabId: 42, + frameId: 0, + timeStamp: Date.now(), + }}); + const pendingWhilePaused = bgCtx.__openadaptExtensionBackground.pendingSaves; + + const syncResp = await sendBg( + {{ type: 'COPILOT_SYNC_STATE' }}, + {{ url: 'chrome-extension://testext/sidepanel.html' }} + ); + + // 4. Host rejects first resume -> fail closed, authPause MUST remain active + const rejectedResume = await sendBg( + {{ type: 'COPILOT_AUTH_RESUME', tabId: 42 }}, + {{ url: 'chrome-extension://testext/sidepanel.html' }} + ); + const afterRejectedResume = await sendBg( + {{ type: 'COPILOT_GET_AUTH_STATE', tabId: 42 }}, + {{ url: 'chrome-extension://testext/sidepanel.html' }} + ); + + // 5. Host acks second resume (with stale COPILOT_STATE injected) -> clears authPause + const acceptedResume = await sendBg( + {{ type: 'COPILOT_AUTH_RESUME', tabId: 42 }}, + {{ url: 'chrome-extension://testext/sidepanel.html' }} + ); + const afterAcceptedResume = await sendBg( + {{ type: 'COPILOT_GET_AUTH_STATE', tabId: 42 }}, + {{ url: 'chrome-extension://testext/sidepanel.html' }} + ); + + // 6. Per-tab auth state clears on navigation (tabs.onUpdated) AND notifies native host + await sendBg( + {{ type: 'AUTH_INTERSTITIAL_DETECTED', kind: 'signin', signals: ['password_input'] }}, + {{ tab: {{ id: 42 }}, frameId: 0, origin: 'https://portal.example.com' }} + ); + const resumedCountBeforeNav = nativeMessages.filter((m) => m.type === 'COPILOT_AUTH_RESUMED').length; + tabUpdatedListeners[0](42, {{ status: 'loading', url: 'https://portal.example.com/dashboard' }}); + await new Promise((r) => setTimeout(r, 20)); + const resumedCountAfterNav = nativeMessages.filter((m) => m.type === 'COPILOT_AUTH_RESUMED').length; + const afterNavClear = await sendBg( + {{ type: 'COPILOT_GET_AUTH_STATE', tabId: 42 }}, + {{ url: 'chrome-extension://testext/sidepanel.html' }} + ); + + console.log(JSON.stringify({{ + valueReadCount, + mfaResult, + pwdResult, + normalResult, + badSetRec, + okSetRec, + initialSyncOk: initialSync.ok, + wiredRunTabId, + sentRunActiveToTab42: tabMessages.some((m) => m.tabId === 42 && m.msg.type === 'SET_RUN_ACTIVE' && m.msg.active === true), + sentAuthPausedToTab42: tabMessages.some((m) => m.tabId === 42 && m.msg.type === 'SET_AUTH_PAUSED' && m.msg.paused === true), + pausedEvResp, + pendingWhilePaused, + missingTabResp, + idleResp, + subframeResp, + detectAuthPause: detectResp.authPause, + syncAuthPause: syncResp.authPause, + badgeHistory, + rejectedResume, + stillPausedAfterReject: Boolean(afterRejectedResume.authPause && afterRejectedResume.authPause.paused), + acceptedResume, + afterAcceptedResume: afterAcceptedResume.authPause, + afterNavClear: afterNavClear.authPause, + navNotifiedHost: resumedCountAfterNav === resumedCountBeforeNav + 1, + nativeTypes: nativeMessages.map((m) => m.type), + allHaveRequestId: nativeMessages.every((m) => typeof m.request_id === 'string' && m.request_id.startsWith('req_')), + }})); +}})(); +""" + out = _run_node(script) + assert out["valueReadCount"] == 0, "Credential input .value must NEVER be accessed" + assert out["mfaResult"]["detected"] is True + assert out["mfaResult"]["kind"] == "mfa" + assert out["pwdResult"]["detected"] is True + assert out["pwdResult"]["kind"] == "signin" + assert out["normalResult"]["detected"] is False + + assert out["badSetRec"]["ok"] is False + assert out["badSetRec"]["error"] == "recording_requires_sidepanel" + assert out["okSetRec"]["ok"] is True + assert out["initialSyncOk"] is True + assert out["wiredRunTabId"] == 42 + assert out["sentRunActiveToTab42"] is True + assert out["sentAuthPausedToTab42"] is True + assert out["pausedEvResp"]["paused"] is True + assert out["pendingWhilePaused"] == 0 + assert out["missingTabResp"]["ok"] is False + assert out["idleResp"]["ignored"] is True + assert out["subframeResp"]["ignored"] is True + assert out["detectAuthPause"]["paused"] is True + assert out["detectAuthPause"]["hostAcked"] is True + assert out["detectAuthPause"]["mode"] == "capture_paused_host_acked" + assert out["syncAuthPause"]["paused"] is True + assert "REC" in out["badgeHistory"] + # Fail-closed resume: host rejection must NOT clear pause state + assert out["rejectedResume"]["ok"] is False + assert out["stillPausedAfterReject"] is True + # Host-acked resume clears pause state cleanly + assert out["acceptedResume"]["ok"] is True + assert out["acceptedResume"]["resumed"] is True + assert out["afterAcceptedResume"] is None + assert out["afterNavClear"] is None + assert out["navNotifiedHost"] is True + assert out["allHaveRequestId"] is True + assert "COPILOT_AUTH_PAUSED" in out["nativeTypes"] + assert "COPILOT_AUTH_RESUMED" in out["nativeTypes"] + + +def test_native_host_handles_auth_pause_and_resume_real_handler(tmp_path: Path) -> None: + """Exercise the real native_host/openadapt_extension_host.py subprocess over stdio.""" + import struct + import sys + + host_script = EXT_DIR / "native_host" / "openadapt_extension_host.py" + assert host_script.is_file() + + def encode(obj: dict) -> bytes: + raw = json.dumps(obj).encode("utf-8") + return struct.pack(" list[dict]: + out_msgs: list[dict] = [] + pos = 0 + while pos + 4 <= len(buf): + (length,) = struct.unpack(" None: + """Every MFA field pattern (verification_code, totp, mfa_code, 2fa, otp, pin) is redacted.""" + content_path = str(EXT_DIR / "content.js") + redact_path = str(EXT_DIR / "network_redact.js") + script = f""" +const fs = require('fs'); +const vm = require('vm'); + +const contentCtx = vm.createContext({{ + chrome: {{ + runtime: {{ + onMessage: {{ addListener: () => {{}} }}, + sendMessage: (m, cb) => {{ if (cb) cb({{ ok: true }}); }}, + }}, + }}, + window: {{ addEventListener: () => {{}}, removeEventListener: () => {{}} }}, + document: {{ + addEventListener: () => {{}}, + removeEventListener: () => {{}}, + readyState: 'complete', + querySelectorAll: () => [], + }}, + location: {{ href: 'https://portal.example.com/verify', origin: 'https://portal.example.com' }}, + URL, + Date, + Map, + Set, +}}); +contentCtx.globalThis = contentCtx; +vm.runInContext(fs.readFileSync({json.dumps(content_path)}, 'utf8'), contentCtx); + +const {{ targetEvidence, isSecretField, setRecording, setAuthPaused }} = contentCtx.__openadaptExtensionContent; + +const mfaFieldNames = ['verification_code', 'totp', 'mfa_code', '2fa', 'one-time-code', 'otp', 'pin']; +const contentResults = {{}}; +for (const fieldName of mfaFieldNames) {{ + const el = {{ + nodeType: 1, + tagName: 'INPUT', + id: fieldName, + value: '839201', + getAttribute: (k) => (k === 'name' || k === 'id' ? fieldName : k === 'type' ? 'text' : null), + getRootNode: () => contentCtx.document, + parentElement: null, + }}; + const ev = targetEvidence(el, 'input'); + contentResults[fieldName] = {{ + isSecret: isSecretField(el), + secret_field: ev.secret_field, + value: ev.value, + }}; +}} + +// Verify setAuthPaused detaches content listeners while recording is active +setRecording(true); +const attachedWhenRecording = contentCtx.__openadaptExtensionContent.attached.document; +setAuthPaused(true); +const attachedWhenPaused = contentCtx.__openadaptExtensionContent.attached.document; +setAuthPaused(false); +const attachedWhenResumed = contentCtx.__openadaptExtensionContent.attached.document; + +// Verify network_redact.js redacts verification_code, totp, mfa_code, 2fa, one-time-code, otp, pin +const redactCtx = vm.createContext({{ + URL, + URLSearchParams, + TextDecoder, + TextEncoder, + Uint8Array, + Date, + Set, + Map, + atob: (s) => Buffer.from(s, 'base64').toString('binary'), +}}); +redactCtx.globalThis = redactCtx; +vm.runInContext(fs.readFileSync({json.dumps(redact_path)}, 'utf8'), redactCtx); +const {{ redactNetworkSave }} = redactCtx.OpenAdaptNetworkRedact; + +const bodyObj = {{ + applicant: 'Jane Doe', + verification_code: '741852', + totp: '963258', + mfa_code: '159753', + '2fa': '456123', + 'one-time-code': '321654', + otp: '654987', + pin: '4321', +}}; +const rawBytes = new TextEncoder().encode(JSON.stringify(bodyObj)); +const redacted = redactNetworkSave({{ + method: 'POST', + url: 'https://portal.example.com/api/verify', + type: 'xmlhttprequest', + tabId: 42, + frameId: 0, + timeStamp: Date.now(), + statusCode: 200, + requestHeaders: [{{ name: 'Content-Type', value: 'application/json' }}], + responseHeaders: [], + requestBody: {{ raw: [{{ bytes: rawBytes }}] }}, +}}); + +console.log(JSON.stringify({{ + contentResults, + attachedWhenRecording, + attachedWhenPaused, + attachedWhenResumed, + redactedBody: redacted && redacted.request_body, +}})); +""" + out = _run_node(script) + for field_name in ( + "verification_code", + "totp", + "mfa_code", + "2fa", + "one-time-code", + "otp", + "pin", + ): + assert out["contentResults"][field_name]["isSecret"] is True, field_name + assert out["contentResults"][field_name]["secret_field"] is True, field_name + assert out["contentResults"][field_name]["value"] == "", field_name + assert out["redactedBody"][field_name] == "", field_name + + assert out["redactedBody"]["applicant"] == "Jane Doe" + assert out["attachedWhenRecording"] == 3 + assert out["attachedWhenPaused"] == 0 + assert out["attachedWhenResumed"] == 3 + + +def test_sidepanel_wires_auth_pause_and_popup_return_controls() -> None: + html = (EXT_DIR / "sidepanel.html").read_text(encoding="utf-8") + js = (EXT_DIR / "sidepanel.js").read_text(encoding="utf-8") + + assert 'id="auth-pause-container"' in html + assert 'id="popup-banner-container"' in html + assert "COPILOT_AUTH_RESUME" in js + assert "COPILOT_RETURN_TO_PARENT" in js + assert "I Signed In" in js + assert "Return to Parent Tab" in js diff --git a/scripts/package_chrome_extension.py b/scripts/package_chrome_extension.py new file mode 100644 index 0000000000..f11023888f --- /dev/null +++ b/scripts/package_chrome_extension.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 +"""Validate and package the OpenAdapt Chrome MV3 Co-Pilot extension for Chrome Web Store. + +Usage: + python3 scripts/package_chrome_extension.py + python3 scripts/package_chrome_extension.py --out dist/openadapt-copilot-cws.zip + python3 scripts/package_chrome_extension.py --check-only +""" + +from __future__ import annotations + +import argparse +import json +import re +import struct +import sys +import zipfile +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +DEFAULT_EXT_DIR = REPO_ROOT / "packages" / "flow" / "chrome_extension" +DEFAULT_OUT_ZIP = REPO_ROOT / "dist" / "openadapt-copilot-cws.zip" + +# Files/directories inside packages/flow/chrome_extension/ that must NOT be +# shipped in the Chrome Web Store upload zip. +EXCLUDED_TOP_LEVEL = { + "STORE_LISTING.md", + "README.md", + "native_host", + "__pycache__", + ".DS_Store", +} +EXCLUDED_SUFFIXES = {".pyc", ".pyo", ".zip", ".map", ".md"} + +MAX_DESCRIPTION_LEN = 132 +REQUIRED_ICON_SIZES = (16, 48, 128) +PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" + +INLINE_SCRIPT_RE = re.compile(r"]*\bsrc=)[^>]*>", re.IGNORECASE) +INLINE_HANDLER_RE = re.compile(r"\son[a-z]+\s*=", re.IGNORECASE) +EVAL_RE = re.compile(r"\b(?:eval|new\s+Function)\s*\(") + + +def _read_png_dimensions(path: Path) -> tuple[int, int]: + data = path.read_bytes() + if len(data) < 24 or data[:8] != PNG_SIGNATURE or data[12:16] != b"IHDR": + raise ValueError(f"{path} is not a valid PNG file") + width, height = struct.unpack(">II", data[16:24]) + return width, height + + +def validate_extension_dir(ext_dir: Path) -> list[str]: + """Validate MV3 & Chrome Web Store readiness. Returns list of error strings.""" + errors: list[str] = [] + manifest_path = ext_dir / "manifest.json" + if not manifest_path.is_file(): + return [f"Missing manifest.json in {ext_dir}"] + + try: + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + except json.JSONDecodeError as exc: + return [f"Invalid manifest.json JSON: {exc}"] + + if manifest.get("manifest_version") != 3: + errors.append("manifest_version must be 3") + + name = manifest.get("name", "") + if not isinstance(name, str) or not name.strip(): + errors.append("manifest.name must be a non-empty string") + elif len(name) > 75: + errors.append(f"manifest.name exceeds 75 chars ({len(name)})") + + desc = manifest.get("description", "") + if not isinstance(desc, str) or not desc.strip(): + errors.append("manifest.description must be a non-empty string") + elif len(desc) > MAX_DESCRIPTION_LEN: + errors.append( + f"manifest.description exceeds {MAX_DESCRIPTION_LEN} chars ({len(desc)})" + ) + + version = manifest.get("version", "") + if not isinstance(version, str) or not re.fullmatch(r"\d+(?:\.\d+){0,3}", version): + errors.append( + f"manifest.version must be 1-4 dot-separated integers: {version!r}" + ) + + # Verify background service worker exists + bg = manifest.get("background") or {} + sw_rel = bg.get("service_worker") + if not isinstance(sw_rel, str) or not (ext_dir / sw_rel).is_file(): + errors.append(f"background.service_worker missing: {sw_rel!r}") + + # Verify side_panel.default_path exists + sp = manifest.get("side_panel") or {} + sp_rel = sp.get("default_path") + if not isinstance(sp_rel, str) or not (ext_dir / sp_rel).is_file(): + errors.append(f"side_panel.default_path missing: {sp_rel!r}") + + # Verify icons exist and match exact declared PNG pixel dimensions + icons = manifest.get("icons") or {} + for size in REQUIRED_ICON_SIZES: + rel = icons.get(str(size)) + if not isinstance(rel, str): + errors.append(f"manifest.icons missing required size {size}") + continue + icon_path = ext_dir / rel + if not icon_path.is_file(): + errors.append(f"Icon file missing for size {size}: {rel}") + continue + try: + w, h = _read_png_dimensions(icon_path) + if (w, h) != (size, size): + errors.append( + f"Icon {rel} dimensions are {w}x{h}, expected {size}x{size}" + ) + except ValueError as exc: + errors.append(str(exc)) + + # Verify content scripts exist + for idx, cs in enumerate(manifest.get("content_scripts") or []): + for js_rel in cs.get("js") or []: + if not (ext_dir / js_rel).is_file(): + errors.append(f"content_scripts[{idx}] missing js file: {js_rel}") + + # CSP / MV3 static checks on packaged HTML & JS files + for rel_path in collect_package_files(ext_dir): + full_path = ext_dir / rel_path + if rel_path.suffix.lower() == ".html": + text = full_path.read_text(encoding="utf-8") + if INLINE_SCRIPT_RE.search(text): + errors.append(f"Inline