diff --git a/src/main/browser/browser-manager-grab.test.ts b/src/main/browser/browser-manager-grab.test.ts new file mode 100644 index 000000000..6272ae951 --- /dev/null +++ b/src/main/browser/browser-manager-grab.test.ts @@ -0,0 +1,502 @@ +/* eslint-disable max-lines -- Why: grab operation tests cover authorization, +lifecycle (arm/await/cancel/teardown), navigation/destruction auto-cancel, and +main-side payload validation. Splitting across files would scatter the shared +mock setup and make it harder to verify the grab contract holistically. */ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { + webContentsFromIdMock, + guestOnMock, + guestOffMock, + guestSetBackgroundThrottlingMock, + guestSetWindowOpenHandlerMock, + guestExecuteJavaScriptMock, + guestIsDestroyedMock, + guestGetZoomFactorMock, + guestCapturePageMock, + menuBuildFromTemplateMock +} = vi.hoisted(() => ({ + webContentsFromIdMock: vi.fn(), + guestOnMock: vi.fn(), + guestOffMock: vi.fn(), + guestSetBackgroundThrottlingMock: vi.fn(), + guestSetWindowOpenHandlerMock: vi.fn(), + guestExecuteJavaScriptMock: vi.fn(), + guestIsDestroyedMock: vi.fn(() => false), + guestGetZoomFactorMock: vi.fn(() => 1), + guestCapturePageMock: vi.fn(), + menuBuildFromTemplateMock: vi.fn() +})) + +vi.mock('electron', () => ({ + clipboard: { writeText: vi.fn() }, + shell: { openExternal: vi.fn() }, + Menu: { buildFromTemplate: menuBuildFromTemplateMock }, + webContents: { fromId: webContentsFromIdMock } +})) + +import { browserManager } from './browser-manager' + +function makeGuest(id: number) { + return { + id, + isDestroyed: guestIsDestroyedMock, + getType: vi.fn(() => 'webview'), + setBackgroundThrottling: guestSetBackgroundThrottlingMock, + setWindowOpenHandler: guestSetWindowOpenHandlerMock, + on: guestOnMock, + off: guestOffMock, + openDevTools: vi.fn(), + executeJavaScript: guestExecuteJavaScriptMock, + getZoomFactor: guestGetZoomFactorMock, + capturePage: guestCapturePageMock, + getURL: vi.fn(() => 'https://example.com/') + } as unknown as Electron.WebContents +} + +describe('browserManager grab operations', () => { + const rendererWebContentsId = 5001 + let guest: Electron.WebContents + + beforeEach(() => { + vi.clearAllMocks() + guestIsDestroyedMock.mockReturnValue(false) + guestExecuteJavaScriptMock.mockResolvedValue(true) + browserManager.unregisterAll() + + guest = makeGuest(101) + webContentsFromIdMock.mockReturnValue(guest) + + browserManager.attachGuestPolicies(guest) + browserManager.registerGuest({ + browserTabId: 'tab-1', + webContentsId: 101, + rendererWebContentsId + }) + }) + + describe('getAuthorizedGuest', () => { + it('returns guest for authorized caller', () => { + const result = browserManager.getAuthorizedGuest('tab-1', rendererWebContentsId) + expect(result).toBe(guest) + }) + + it('returns null for unauthorized caller', () => { + const result = browserManager.getAuthorizedGuest('tab-1', 9999) + expect(result).toBeNull() + }) + + it('returns null for unregistered tab', () => { + const result = browserManager.getAuthorizedGuest('unknown-tab', rendererWebContentsId) + expect(result).toBeNull() + }) + + it('returns null and cleans up if guest is destroyed', () => { + guestIsDestroyedMock.mockReturnValue(true) + const result = browserManager.getAuthorizedGuest('tab-1', rendererWebContentsId) + expect(result).toBeNull() + }) + }) + + describe('setGrabMode', () => { + it('injects overlay when enabling grab mode', async () => { + const result = await browserManager.setGrabMode('tab-1', true, guest) + expect(result).toBe(true) + expect(guestExecuteJavaScriptMock).toHaveBeenCalledTimes(1) + expect(guestExecuteJavaScriptMock.mock.calls[0][0]).toContain('__orca-grab-host') + }) + + it('cancels active grab op when disabling', async () => { + // Start a grab op first + guestExecuteJavaScriptMock.mockImplementation(() => new Promise(() => {})) + const selectionPromise = browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + + // Disable grab mode + const result = await browserManager.setGrabMode('tab-1', false, guest) + expect(result).toBe(true) + + const selection = await selectionPromise + expect(selection.kind).toBe('cancelled') + expect(selection.opId).toBe('op-1') + }) + + it('returns false if injection fails', async () => { + guestExecuteJavaScriptMock.mockRejectedValue(new Error('Injection failed')) + const result = await browserManager.setGrabMode('tab-1', true, guest) + expect(result).toBe(false) + }) + }) + + describe('hasActiveGrabOp', () => { + it('returns false when no grab is active', () => { + expect(browserManager.hasActiveGrabOp('tab-1')).toBe(false) + }) + + it('returns true when a grab is active', () => { + guestExecuteJavaScriptMock.mockImplementation(() => new Promise(() => {})) + void browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + expect(browserManager.hasActiveGrabOp('tab-1')).toBe(true) + }) + }) + + describe('awaitGrabSelection', () => { + it('resolves with selected payload when guest returns data', async () => { + const mockPayload = { + page: { + sanitizedUrl: 'https://example.com/', + title: 'Example', + viewportWidth: 1280, + viewportHeight: 720, + scrollX: 0, + scrollY: 0, + devicePixelRatio: 2, + capturedAt: '2026-04-10T00:00:00.000Z' + }, + target: { + tagName: 'button', + selector: 'button', + textSnippet: 'Click me', + htmlSnippet: '', + attributes: {}, + accessibility: { + role: 'button', + accessibleName: 'Click me', + ariaLabel: null, + ariaLabelledBy: null + }, + rectViewport: { x: 0, y: 0, width: 100, height: 40 }, + rectPage: { x: 0, y: 0, width: 100, height: 40 }, + computedStyles: { + display: 'block', + position: 'static', + width: '100px', + height: '40px', + margin: '0', + padding: '0', + color: '#000', + backgroundColor: '#fff', + border: 'none', + borderRadius: '0', + fontFamily: 'sans-serif', + fontSize: '14px', + fontWeight: '400', + lineHeight: '20px', + textAlign: 'left', + zIndex: 'auto' + } + }, + nearbyText: [], + ancestorPath: ['div', 'body'], + screenshot: null + } + + // The awaitClick script returns a Promise; simulate it resolving + guestExecuteJavaScriptMock.mockResolvedValueOnce(mockPayload) + + const result = await browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + expect(result.kind).toBe('selected') + expect(result.opId).toBe('op-1') + if (result.kind === 'selected') { + expect(result.payload.target.tagName).toBe('button') + } + }) + + it('resolves with cancelled when guest returns null', async () => { + guestExecuteJavaScriptMock.mockResolvedValueOnce(null) + + const result = await browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + expect(result.kind).toBe('cancelled') + }) + + it('resolves with error when executeJavaScript throws', async () => { + guestExecuteJavaScriptMock.mockRejectedValueOnce(new Error('Script failed')) + + const result = await browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + expect(result.kind).toBe('error') + if (result.kind === 'error') { + expect(result.reason).toContain('Script failed') + } + }) + + it('resolves with error when guest returns structurally invalid payload', async () => { + // Missing required 'target' field + guestExecuteJavaScriptMock.mockResolvedValueOnce({ page: { title: 'test' } }) + + const result = await browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + expect(result.kind).toBe('error') + if (result.kind === 'error') { + expect(result.reason).toContain('invalid payload') + } + }) + + it('main-side clamp redacts secret-bearing attribute values', async () => { + const mockPayload = { + page: { + sanitizedUrl: 'https://example.com/', + title: 'Example', + viewportWidth: 1280, + viewportHeight: 720, + scrollX: 0, + scrollY: 0, + devicePixelRatio: 2, + capturedAt: '2026-04-10T00:00:00.000Z' + }, + target: { + tagName: 'div', + selector: 'div', + textSnippet: '', + htmlSnippet: '
', + attributes: { + id: 'safe-value', + class: 'access_token=secret123', + href: 'https://example.com/callback?access_token=abc', + src: 'https://example.com/img?size=large&color=blue', + 'aria-label': 'password is hunter2' + }, + accessibility: { + role: 'generic', + accessibleName: null, + ariaLabel: null, + ariaLabelledBy: null + }, + rectViewport: { x: 0, y: 0, width: 100, height: 40 }, + rectPage: { x: 0, y: 0, width: 100, height: 40 }, + computedStyles: { + display: 'block', + position: 'static', + width: '100px', + height: '40px', + margin: '0', + padding: '0', + color: '#000', + backgroundColor: '#fff', + border: 'none', + borderRadius: '0', + fontFamily: 'sans-serif', + fontSize: '14px', + fontWeight: '400', + lineHeight: '20px', + textAlign: 'left', + zIndex: 'auto' + } + }, + nearbyText: [], + ancestorPath: [], + screenshot: null + } + + guestExecuteJavaScriptMock.mockResolvedValueOnce(mockPayload) + const result = await browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + expect(result.kind).toBe('selected') + if (result.kind === 'selected') { + const attrs = result.payload.target.attributes + // Safe value passes through + expect(attrs.id).toBe('safe-value') + // Class with secret pattern is redacted + expect(attrs.class).toBe('[redacted]') + // href containing a secret pattern is redacted (secret check takes + // priority over URL sanitization for defense in depth) + expect(attrs.href).toBe('[redacted]') + // src with non-secret query params is sanitized (query stripped) + expect(attrs.src).toBe('https://example.com/img') + // aria-label with secret pattern is redacted + expect(attrs['aria-label']).toBe('[redacted]') + } + }) + + it('main-side clamp re-sanitizes page URL with query strings', async () => { + const mockPayload = { + page: { + sanitizedUrl: 'https://example.com/page?access_token=secret&foo=bar#hash', + title: 'Test', + viewportWidth: 1280, + viewportHeight: 720, + scrollX: 0, + scrollY: 0, + devicePixelRatio: 1, + capturedAt: '2026-04-10T00:00:00.000Z' + }, + target: { + tagName: 'div', + selector: 'div', + textSnippet: '', + htmlSnippet: '
', + attributes: {}, + accessibility: { + role: null, + accessibleName: null, + ariaLabel: null, + ariaLabelledBy: null + }, + rectViewport: { x: 0, y: 0, width: 10, height: 10 }, + rectPage: { x: 0, y: 0, width: 10, height: 10 }, + computedStyles: { + display: 'block', + position: 'static', + width: '10px', + height: '10px', + margin: '0', + padding: '0', + color: '#000', + backgroundColor: '#fff', + border: 'none', + borderRadius: '0', + fontFamily: 'sans-serif', + fontSize: '14px', + fontWeight: '400', + lineHeight: '20px', + textAlign: 'left', + zIndex: 'auto' + } + }, + nearbyText: [], + ancestorPath: [], + screenshot: null + } + + guestExecuteJavaScriptMock.mockResolvedValueOnce(mockPayload) + const result = await browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + expect(result.kind).toBe('selected') + if (result.kind === 'selected') { + // Query string and hash should be stripped by main-side sanitization + expect(result.payload.page.sanitizedUrl).toBe('https://example.com/page') + } + }) + + it('cancels previous op when starting a new one on same tab', async () => { + guestExecuteJavaScriptMock.mockImplementation(() => new Promise(() => {})) + + const promise1 = browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + + // Start a second grab op on same tab + guestExecuteJavaScriptMock.mockImplementation(() => new Promise(() => {})) + void browserManager.awaitGrabSelection('tab-1', 'op-2', guest) + + const result1 = await promise1 + expect(result1.kind).toBe('cancelled') + expect(result1.opId).toBe('op-1') + }) + + it('replacement op skips teardown injection to preserve overlay', async () => { + // Why: when replacing an op, the old op's cleanup must NOT inject the + // teardown script because the new op reuses the already-armed overlay. + guestExecuteJavaScriptMock.mockImplementation(() => new Promise(() => {})) + + void browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + + // Record call count before replacement + const callCountBefore = guestExecuteJavaScriptMock.mock.calls.length + + // Replace with a new op + guestExecuteJavaScriptMock.mockImplementation(() => new Promise(() => {})) + void browserManager.awaitGrabSelection('tab-1', 'op-2', guest) + + // The only new executeJavaScript call should be the awaitClick for op-2. + // No teardown should have been injected for op-1's cleanup. + // Why: distinguish teardown from awaitClick — both contain 'cancelAwait', + // but only the teardown script contains 'if (!grab) return true;'. + const newCalls = guestExecuteJavaScriptMock.mock.calls.slice(callCountBefore) + const teardownCalls = newCalls.filter(([script]) => + (script as string).includes('if (!grab) return true;') + ) + expect(teardownCalls).toHaveLength(0) + }) + }) + + describe('cancelGrabOp', () => { + it('resolves active grab with cancelled reason', async () => { + guestExecuteJavaScriptMock.mockImplementation(() => new Promise(() => {})) + + const promise = browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + browserManager.cancelGrabOp('tab-1', 'user') + + const result = await promise + expect(result).toEqual({ opId: 'op-1', kind: 'cancelled', reason: 'user' }) + }) + + it('is a no-op when no grab is active', () => { + // Should not throw + browserManager.cancelGrabOp('tab-1', 'user') + }) + + it('supports different cancellation reasons', async () => { + guestExecuteJavaScriptMock.mockImplementation(() => new Promise(() => {})) + + const promise = browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + browserManager.cancelGrabOp('tab-1', 'navigation') + + const result = await promise + expect(result.kind).toBe('cancelled') + if (result.kind === 'cancelled') { + expect(result.reason).toBe('navigation') + } + }) + }) + + describe('unregisterGuest cancels grab', () => { + it('cancels active grab on unregister', async () => { + guestExecuteJavaScriptMock.mockImplementation(() => new Promise(() => {})) + + const promise = browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + browserManager.unregisterGuest('tab-1') + + const result = await promise + expect(result).toEqual({ opId: 'op-1', kind: 'cancelled', reason: 'evicted' }) + }) + }) + + describe('navigation auto-cancel', () => { + it('cancels grab when guest navigates in main frame', async () => { + guestExecuteJavaScriptMock.mockImplementation(() => new Promise(() => {})) + + const promise = browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + + // Find the did-start-navigation handler and trigger it with isMainFrame=true + const navHandler = guestOnMock.mock.calls.find( + ([event]) => event === 'did-start-navigation' + )?.[1] as ((...args: unknown[]) => void) | undefined + + expect(navHandler).toBeTypeOf('function') + navHandler?.(null, 'https://example.com/new', false, true) + + const result = await promise + expect(result).toEqual({ opId: 'op-1', kind: 'cancelled', reason: 'navigation' }) + }) + + it('does not cancel grab on subframe navigation', async () => { + guestExecuteJavaScriptMock.mockImplementation(() => new Promise(() => {})) + + void browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + + // Trigger did-start-navigation with isMainFrame=false (subframe) + const navHandler = guestOnMock.mock.calls.find( + ([event]) => event === 'did-start-navigation' + )?.[1] as ((...args: unknown[]) => void) | undefined + + expect(navHandler).toBeTypeOf('function') + navHandler?.(null, 'https://ads.example.com/', false, false) + + // Grab should still be active + expect(browserManager.hasActiveGrabOp('tab-1')).toBe(true) + }) + }) + + describe('destruction auto-cancel', () => { + it('cancels grab when guest is destroyed', async () => { + guestExecuteJavaScriptMock.mockImplementation(() => new Promise(() => {})) + + const promise = browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + + // Find the destroyed handler and trigger it + const destroyedHandler = guestOnMock.mock.calls.find( + ([event]) => event === 'destroyed' + )?.[1] as (() => void) | undefined + + expect(destroyedHandler).toBeTypeOf('function') + destroyedHandler?.() + + const result = await promise + expect(result).toEqual({ opId: 'op-1', kind: 'cancelled', reason: 'evicted' }) + }) + }) +}) diff --git a/src/main/browser/browser-manager.ts b/src/main/browser/browser-manager.ts index 5c4a4a7e9..c2769e56e 100644 --- a/src/main/browser/browser-manager.ts +++ b/src/main/browser/browser-manager.ts @@ -1,8 +1,25 @@ +/* eslint-disable max-lines -- Why: BrowserManager is the single owner of guest +lifecycle, context menus, and grab operations. Splitting these into separate +modules would scatter the guest authorization and tab-lookup logic that must +stay consistent when new privileged operations are added. */ import { clipboard, Menu, shell, webContents } from 'electron' import { normalizeBrowserNavigationUrl, normalizeExternalBrowserUrl } from '../../shared/browser-url' +import type { + BrowserGrabCancelReason, + BrowserGrabPayload, + BrowserGrabRect, + BrowserGrabResult, + BrowserGrabScreenshot +} from '../../shared/browser-grab-types' +import { + GRAB_BUDGET, + GRAB_SAFE_ATTRIBUTE_NAMES, + GRAB_SECRET_PATTERNS +} from '../../shared/browser-grab-types' +import { buildGuestOverlayScript } from './grab-guest-script' export type BrowserGuestRegistration = { browserTabId: string @@ -10,6 +27,197 @@ export type BrowserGuestRegistration = { rendererWebContentsId: number } +/** Tracks the lifecycle of a single grab operation on one browser tab. */ +type ActiveGrabOp = { + opId: string + browserTabId: string + guestWebContentsId: number + resolve: (result: BrowserGrabResult) => void + /** Cleanup listeners and optionally inject teardown. + * @param preserveOverlay When true, skip teardown injection so the guest + * overlay stays visible (used when a selection succeeds and the copy menu + * is shown). */ + cleanup: (preserveOverlay?: boolean) => void + /** When true, cleanup skips the teardown injection. Set by awaitGrabSelection + * when replacing an existing op so the freshly-armed overlay is preserved. */ + skipTeardown?: boolean +} + +/** Hard timeout for an armed grab operation to prevent indefinite hangs. */ +const GRAB_OP_TIMEOUT_MS = 120_000 + +/** + * Re-validate and clamp all string, array, and budget fields in a grab payload + * before forwarding to the renderer. This is the main-side safety net: even if + * the guest runtime is compromised, the payload that reaches renderer chrome + * respects the documented budgets. + * + * Returns null if the payload is structurally invalid (missing required fields). + */ +function clampGrabPayload(raw: unknown): BrowserGrabPayload | null { + // Why: the guest payload is completely untrusted. A compromised or + // malfunctioning guest could return anything. Validate structural shape + // before accessing nested properties to avoid unhandled TypeErrors. + if (!raw || typeof raw !== 'object') { + return null + } + const obj = raw as Record + if (!obj.page || typeof obj.page !== 'object') { + return null + } + if (!obj.target || typeof obj.target !== 'object') { + return null + } + + const page = obj.page as Record + const target = obj.target as Record + + const clampStr = (s: unknown, max: number): string => { + const str = typeof s === 'string' ? s : '' + if (str.length <= max) { + return str + } + return `${str.slice(0, max)} (truncated)` + } + + const clampArray = (arr: unknown, maxEntries: number, maxEntryLength: number): string[] => { + const items = Array.isArray(arr) ? arr : [] + return items.slice(0, maxEntries).map((item) => clampStr(item, maxEntryLength)) + } + + const safeStr = (s: unknown, max = 500): string => clampStr(s, max) + + const safeNum = (n: unknown, fallback = 0): number => + typeof n === 'number' && Number.isFinite(n) ? n : fallback + + // Why: mirror the guest-side secret detection on the main side so a + // compromised guest cannot smuggle secret-bearing values through attributes + // or URLs. This is the defense-in-depth layer. + const containsSecret = (val: string): boolean => { + const lower = val.toLowerCase() + return GRAB_SECRET_PATTERNS.some((p) => lower.includes(p)) + } + + // Why: mirror the guest-side URL sanitization. Strip query strings and + // fragments to prevent token leakage even if the guest is compromised. + const sanitizeUrl = (raw: unknown): string => { + const str = typeof raw === 'string' ? raw : '' + if (!str) { + return '' + } + try { + const u = new URL(str) + u.search = '' + u.hash = '' + return u.toString() + } catch { + // Why: returning the raw string on parse failure could preserve + // javascript: URIs or other non-http schemes. Return empty. + return '' + } + } + + // Why: re-filter attributes on the main side so a compromised guest cannot + // smuggle unsafe attribute names (e.g., event handlers) or secret-bearing + // values into the payload that reaches the renderer. + const safeAttributes = (attrs: unknown): Record => { + if (!attrs || typeof attrs !== 'object') { + return {} + } + const filtered: Record = {} + for (const [key, value] of Object.entries(attrs as Record)) { + const name = key.toLowerCase() + const isAria = name.startsWith('aria-') + const isSafe = GRAB_SAFE_ATTRIBUTE_NAMES.has(name) + if (!isAria && !isSafe) { + continue + } + const strValue = safeStr(value, 2000) + if (containsSecret(strValue)) { + filtered[name] = '[redacted]' + } else if ((name === 'href' || name === 'src' || name === 'action') && strValue) { + filtered[name] = sanitizeUrl(strValue) + } else if (name === 'class') { + filtered[name] = safeStr(value, 200) + } else { + filtered[name] = safeStr(value, 500) + } + } + return filtered + } + + const safeRect = (r: unknown): BrowserGrabRect => { + if (!r || typeof r !== 'object') { + return { x: 0, y: 0, width: 0, height: 0 } + } + const rect = r as Record + return { + x: safeNum(rect.x), + y: safeNum(rect.y), + width: safeNum(rect.width), + height: safeNum(rect.height) + } + } + + const accessibility = target.accessibility as Record | null | undefined + const computedStyles = target.computedStyles as Record | null | undefined + + return { + page: { + // Why: re-sanitize the URL main-side so a compromised guest cannot + // pass through query strings containing tokens or secrets. + sanitizedUrl: sanitizeUrl(page.sanitizedUrl), + title: safeStr(page.title, 500), + viewportWidth: safeNum(page.viewportWidth), + viewportHeight: safeNum(page.viewportHeight), + scrollX: safeNum(page.scrollX), + scrollY: safeNum(page.scrollY), + devicePixelRatio: safeNum(page.devicePixelRatio, 1), + capturedAt: safeStr(page.capturedAt, 100) + }, + target: { + tagName: safeStr(target.tagName, 50), + selector: safeStr(target.selector, 500), + textSnippet: clampStr(target.textSnippet, GRAB_BUDGET.textSnippetMaxLength), + htmlSnippet: clampStr(target.htmlSnippet, GRAB_BUDGET.htmlSnippetMaxLength), + attributes: safeAttributes(target.attributes), + accessibility: { + role: safeStr(accessibility?.role) || null, + accessibleName: safeStr(accessibility?.accessibleName) || null, + ariaLabel: safeStr(accessibility?.ariaLabel) || null, + ariaLabelledBy: safeStr(accessibility?.ariaLabelledBy) || null + }, + rectViewport: safeRect(target.rectViewport), + rectPage: safeRect(target.rectPage), + computedStyles: { + display: safeStr(computedStyles?.display), + position: safeStr(computedStyles?.position), + width: safeStr(computedStyles?.width), + height: safeStr(computedStyles?.height), + margin: safeStr(computedStyles?.margin), + padding: safeStr(computedStyles?.padding), + color: safeStr(computedStyles?.color), + backgroundColor: safeStr(computedStyles?.backgroundColor), + border: safeStr(computedStyles?.border), + borderRadius: safeStr(computedStyles?.borderRadius), + fontFamily: safeStr(computedStyles?.fontFamily), + fontSize: safeStr(computedStyles?.fontSize), + fontWeight: safeStr(computedStyles?.fontWeight), + lineHeight: safeStr(computedStyles?.lineHeight), + textAlign: safeStr(computedStyles?.textAlign), + zIndex: safeStr(computedStyles?.zIndex) + } + }, + nearbyText: clampArray( + obj.nearbyText, + GRAB_BUDGET.nearbyTextMaxEntries, + GRAB_BUDGET.nearbyTextEntryMaxLength + ), + ancestorPath: clampArray(obj.ancestorPath, GRAB_BUDGET.ancestorPathMaxEntries, 200), + screenshot: null + } +} + class BrowserManager { private readonly webContentsIdByTabId = new Map() private readonly rendererWebContentsIdByTabId = new Map() @@ -19,6 +227,7 @@ class BrowserManager { number, { code: number; description: string; validatedUrl: string } >() + private readonly activeGrabOps = new Map() private openValidatedExternal(rawUrl: string): void { const externalUrl = normalizeExternalBrowserUrl(rawUrl) @@ -112,6 +321,11 @@ class BrowserManager { } unregisterGuest(browserTabId: string): void { + // Why: unregistering a guest while a grab is active means the guest is + // being torn down. Cancel the grab so the renderer gets a clean signal + // instead of a dangling Promise. + this.cancelGrabOp(browserTabId, 'evicted') + const cleanup = this.contextMenuCleanupByTabId.get(browserTabId) if (cleanup) { cleanup() @@ -122,6 +336,10 @@ class BrowserManager { } unregisterAll(): void { + // Cancel all active grab ops before tearing down registrations + for (const browserTabId of this.activeGrabOps.keys()) { + this.cancelGrabOp(browserTabId, 'evicted') + } for (const browserTabId of this.webContentsIdByTabId.keys()) { this.unregisterGuest(browserTabId) } @@ -150,6 +368,319 @@ class BrowserManager { return true } + // --------------------------------------------------------------------------- + // Browser Context Grab — main-owned operations + // --------------------------------------------------------------------------- + + /** + * Validates that a caller (identified by sender webContentsId) owns the + * given browserTabId. Returns the guest WebContents or null. + */ + getAuthorizedGuest( + browserTabId: string, + senderWebContentsId: number + ): Electron.WebContents | null { + const registeredRenderer = this.rendererWebContentsIdByTabId.get(browserTabId) + if (registeredRenderer == null || registeredRenderer !== senderWebContentsId) { + return null + } + const guestId = this.webContentsIdByTabId.get(browserTabId) + if (guestId == null) { + return null + } + const guest = webContents.fromId(guestId) + if (!guest || guest.isDestroyed()) { + this.webContentsIdByTabId.delete(browserTabId) + return null + } + return guest + } + + /** Returns true if a grab operation is currently active for this tab. */ + hasActiveGrabOp(browserTabId: string): boolean { + return this.activeGrabOps.has(browserTabId) + } + + /** + * Enable or disable grab mode for a browser tab. When enabled, injects the + * overlay runtime into the guest. When disabled, cancels any active grab op. + */ + async setGrabMode( + browserTabId: string, + enabled: boolean, + guest: Electron.WebContents + ): Promise { + if (!enabled) { + this.cancelGrabOp(browserTabId, 'user') + return true + } + // Why: injecting the overlay runtime eagerly on arm lets the hover UI + // appear instantly when the user starts moving the pointer, rather than + // adding a visible delay between "click Grab" and "overlay appears". + // The runtime is idempotent — re-injection on the same page is safe. + try { + await guest.executeJavaScript(buildGuestOverlayScript('arm')) + return true + } catch { + return false + } + } + + /** + * Await a single grab selection on the given tab. Returns a Promise that + * resolves exactly once when the user clicks, cancels, or an error occurs. + * + * Why the click is handled in-guest rather than via main-side interception: + * Electron's `before-input-event` only fires for keyboard events, not mouse + * events on guest webContents. The design doc anticipated a main-owned + * interceptor, but the spike showed this API gap. The fallback (documented + * in the design doc) is to let the guest overlay's full-viewport hit-catcher + * consume the click. The overlay calls `stopPropagation()` and + * `preventDefault()` so the page underneath does not receive the event. + * This is not a perfect guarantee (capture-phase listeners on window may + * still fire), but it covers the vast majority of sites. + */ + awaitGrabSelection( + browserTabId: string, + opId: string, + guest: Electron.WebContents + ): Promise { + // Why: only one active grab operation per tab prevents race conditions + // where a late click from a previous operation resolves the wrong Promise. + const existing = this.activeGrabOps.get(browserTabId) + if (existing) { + // Why: skip teardown injection when replacing an op. The new op will + // reuse the already-armed overlay. If we injected teardown here, it + // would race with the new awaitClick script in the guest's JS queue + // and destroy the overlay before the click handler is installed. + existing.skipTeardown = true + existing.resolve({ opId: existing.opId, kind: 'cancelled', reason: 'user' }) + } + + return new Promise((resolve) => { + const guestWebContentsId = guest.id + let settled = false + + const settleOnce = (result: BrowserGrabResult): void => { + if (settled) { + return + } + settled = true + clearTimeout(timeoutId) + // Why: when the user successfully selects an element, keep the guest + // overlay visible so the highlight box persists while the renderer + // shows the copy menu. Teardown happens later when the renderer calls + // setGrabMode(false) or re-arms with a fresh armAndAwait cycle. + op.cleanup(result.kind === 'selected') + this.activeGrabOps.delete(browserTabId) + resolve(result) + } + + // Why: the guest overlay runtime handles the click in-page and calls + // __orcaGrabResolve() which is wired by the 'awaitClick' script to + // resolve the executeJavaScript Promise with the extracted payload. + // Main just needs to run that script and await its result. + const awaitGuestClick = async (): Promise => { + try { + const rawPayload = await guest.executeJavaScript(buildGuestOverlayScript('awaitClick')) + if (!rawPayload || typeof rawPayload !== 'object') { + settleOnce({ opId, kind: 'cancelled', reason: 'user' }) + return + } + const payload = clampGrabPayload(rawPayload) + if (!payload) { + settleOnce({ opId, kind: 'error', reason: 'Guest returned invalid payload structure' }) + return + } + settleOnce({ opId, kind: 'selected', payload }) + } catch (err) { + const message = err instanceof Error ? err.message : 'Selection failed' + // Distinguish cancellation from errors + if (message.includes('cancelled')) { + settleOnce({ opId, kind: 'cancelled', reason: 'user' }) + } else { + settleOnce({ opId, kind: 'error', reason: message }) + } + } + } + + // --- Auto-cancel on top-level navigation --- + // Why: only cancel on main-frame navigations. Subframe navigations + // (e.g., iframe ads loading) should not spuriously cancel the grab. + const handleNavigation = ( + _event: unknown, + _url: unknown, + _isInPlace: unknown, + isMainFrame: boolean + ): void => { + if (isMainFrame) { + settleOnce({ opId, kind: 'cancelled', reason: 'navigation' }) + } + } + + // --- Auto-cancel on guest destruction --- + const handleDestroyed = (): void => { + settleOnce({ opId, kind: 'cancelled', reason: 'evicted' }) + } + + // --- Hard timeout --- + const timeoutId = setTimeout(() => { + settleOnce({ opId, kind: 'cancelled', reason: 'timeout' }) + }, GRAB_OP_TIMEOUT_MS) + + // Install listeners + guest.on('did-start-navigation', handleNavigation) + guest.on('destroyed', handleDestroyed) + + const cleanup = (preserveOverlay?: boolean): void => { + try { + guest.off('did-start-navigation', handleNavigation) + guest.off('destroyed', handleDestroyed) + } catch { + // Why: the guest may already be destroyed during teardown. + // Cleanup is best-effort. + } + // Why: skip teardown injection when (a) the op is being replaced by a + // new op (skipTeardown), or (b) the selection succeeded and the overlay + // should stay visible while the copy menu is shown (preserveOverlay). + if (op.skipTeardown || preserveOverlay) { + return + } + // Tell the guest to remove the overlay + try { + if (!guest.isDestroyed()) { + void guest.executeJavaScript(buildGuestOverlayScript('teardown')) + } + } catch { + // Best-effort overlay removal + } + } + + const op: ActiveGrabOp = { + opId, + browserTabId, + guestWebContentsId, + resolve: settleOnce, + cleanup + } + this.activeGrabOps.set(browserTabId, op) + + // Start awaiting the click in the guest + void awaitGuestClick() + }) + } + + /** + * Cancel an active grab operation for the given tab. + */ + cancelGrabOp(browserTabId: string, reason: BrowserGrabCancelReason): void { + const op = this.activeGrabOps.get(browserTabId) + if (!op) { + return + } + // Why: settleOnce (op.resolve) already calls op.cleanup() and deletes the + // map entry. Calling them again here would double-inject the teardown script. + op.resolve({ opId: op.opId, kind: 'cancelled', reason }) + } + + /** + * Capture a screenshot of the guest surface and optionally crop it to + * the given CSS-pixel rect. + */ + async captureSelectionScreenshot( + _browserTabId: string, + rect: BrowserGrabRect, + guest: Electron.WebContents + ): Promise { + try { + // Why: the rect comes from the renderer via IPC. Validate that all fields + // are finite numbers before using them in arithmetic, so NaN cannot reach + // Electron's image.crop() and cause undefined behavior. + const safeN = (n: unknown, fallback = 0): number => + typeof n === 'number' && Number.isFinite(n) ? n : fallback + const safeRect = { + x: safeN(rect.x), + y: safeN(rect.y), + width: safeN(rect.width), + height: safeN(rect.height) + } + + const image = await guest.capturePage() + if (image.isEmpty()) { + return null + } + + const bitmapSize = image.getSize() + // Why: capturePage returns a bitmap in physical pixels. The grab rect is + // in CSS pixels. To map between them we need the combined scale factor + // (zoomFactor * deviceScaleFactor). Rather than using the primary display + // (which is wrong on multi-monitor setups with mixed DPI), we derive the + // scale factor empirically: ask the guest for its CSS viewport width, then + // compute scaleFactor = bitmapWidth / viewportCSSWidth. This is correct + // regardless of which display the window is on. + const viewportCSSWidth: number = await guest.executeJavaScript('window.innerWidth') + if (!viewportCSSWidth || viewportCSSWidth <= 0) { + return null + } + const scaleFactor = bitmapSize.width / viewportCSSWidth + + // Map CSS-pixel rect to bitmap coordinates + const cropX = Math.max(0, Math.round(safeRect.x * scaleFactor)) + const cropY = Math.max(0, Math.round(safeRect.y * scaleFactor)) + const cropW = Math.min(bitmapSize.width - cropX, Math.round(safeRect.width * scaleFactor)) + const cropH = Math.min(bitmapSize.height - cropY, Math.round(safeRect.height * scaleFactor)) + + if (cropW <= 0 || cropH <= 0) { + return null + } + + const cropped = image.crop({ x: cropX, y: cropY, width: cropW, height: cropH }) + const pngBuffer = cropped.toPNG() + + // Enforce screenshot byte budget + if (pngBuffer.byteLength > GRAB_BUDGET.screenshotMaxBytes) { + // Why: downscaling would add complexity for v1. Fail closed to + // "no screenshot" rather than send an oversized payload. + return null + } + + const dataUrl = `data:image/png;base64,${pngBuffer.toString('base64')}` + // Why: cropW/cropH are in physical pixels (bitmap coordinates) but the + // rest of the grab payload uses CSS pixels. Divide by scaleFactor so the + // screenshot dimensions are consistent with rectViewport/rectPage. + return { + mimeType: 'image/png', + dataUrl, + width: Math.round(cropW / scaleFactor), + height: Math.round(cropH / scaleFactor) + } + } catch { + // Why: screenshot capture can fail if the guest is being torn down + // or the compositor surface is not available. Fail closed. + return null + } + } + + /** + * Extract the payload for the currently hovered element without disrupting + * the active grab overlay or awaitClick listener. Used by keyboard shortcuts + * that let the user copy content while hovering, before clicking. + */ + async extractHoverPayload( + _browserTabId: string, + guest: Electron.WebContents + ): Promise { + try { + const rawPayload = await guest.executeJavaScript(buildGuestOverlayScript('extractHover')) + if (!rawPayload || typeof rawPayload !== 'object') { + return null + } + return clampGrabPayload(rawPayload) + } catch { + return null + } + } + private setupContextMenu(browserTabId: string, guest: Electron.WebContents): void { const handler = (_event: Electron.Event, params: Electron.ContextMenuParams): void => { const pageUrl = guest.getURL() diff --git a/src/main/browser/grab-guest-script.test.ts b/src/main/browser/grab-guest-script.test.ts new file mode 100644 index 000000000..2a4ae803d --- /dev/null +++ b/src/main/browser/grab-guest-script.test.ts @@ -0,0 +1,122 @@ +import { describe, expect, it } from 'vitest' +import { buildGuestOverlayScript } from './grab-guest-script' + +describe('buildGuestOverlayScript', () => { + it('returns a non-empty string for arm action', () => { + const script = buildGuestOverlayScript('arm') + expect(script).toBeTruthy() + expect(typeof script).toBe('string') + expect(script.length).toBeGreaterThan(100) + }) + + it('returns a non-empty string for awaitClick action', () => { + const script = buildGuestOverlayScript('awaitClick') + expect(script).toBeTruthy() + expect(typeof script).toBe('string') + }) + + it('returns a non-empty string for finalize action', () => { + const script = buildGuestOverlayScript('finalize') + expect(script).toBeTruthy() + expect(typeof script).toBe('string') + }) + + it('returns a non-empty string for teardown action', () => { + const script = buildGuestOverlayScript('teardown') + expect(script).toBeTruthy() + expect(typeof script).toBe('string') + }) + + it('arm script contains shadow DOM setup', () => { + const script = buildGuestOverlayScript('arm') + expect(script).toContain('attachShadow') + expect(script).toContain('__orca-grab-host') + expect(script).toContain('__orcaGrab') + }) + + it('arm script contains budget constants matching shared types', () => { + const script = buildGuestOverlayScript('arm') + expect(script).toContain('textSnippetMaxLength: 200') + expect(script).toContain('nearbyTextMaxEntries: 10') + expect(script).toContain('htmlSnippetMaxLength: 4096') + }) + + it('arm script contains secret pattern redaction', () => { + const script = buildGuestOverlayScript('arm') + expect(script).toContain('access_token') + expect(script).toContain('api_key') + expect(script).toContain('password') + expect(script).toContain('secret') + expect(script).toContain('[redacted]') + }) + + it('arm script strips script tags from HTML snippets', () => { + const script = buildGuestOverlayScript('arm') + expect(script).toContain("querySelectorAll('script')") + }) + + it('arm script only allows safe attributes', () => { + const script = buildGuestOverlayScript('arm') + expect(script).toContain('SAFE_ATTRS') + expect(script).toContain("'id'") + expect(script).toContain("'class'") + expect(script).toContain("'role'") + }) + + it('awaitClick script returns a Promise', () => { + const script = buildGuestOverlayScript('awaitClick') + expect(script).toContain('new Promise') + expect(script).toContain('resolve') + expect(script).toContain('reject') + }) + + it('awaitClick script freezes highlight on selection instead of cleanup', () => { + const script = buildGuestOverlayScript('awaitClick') + expect(script).toContain('freezeHighlight') + expect(script).not.toContain('grab.cleanup();\n resolve') + }) + + it('arm script defines freezeHighlight method', () => { + const script = buildGuestOverlayScript('arm') + expect(script).toContain('freezeHighlight') + expect(script).toContain("pointerEvents = 'none'") + }) + + it('awaitClick script blocks right-click', () => { + const script = buildGuestOverlayScript('awaitClick') + expect(script).toContain('contextmenu') + expect(script).toContain('preventDefault') + }) + + it('teardown script cleans up the overlay', () => { + const script = buildGuestOverlayScript('teardown') + expect(script).toContain('cleanup') + expect(script).toContain('__orcaGrab') + }) + + it('teardown script cancels pending awaitClick', () => { + const script = buildGuestOverlayScript('teardown') + expect(script).toContain('cancelAwait') + }) + + it('arm script uses full-viewport overlay as click catcher', () => { + const script = buildGuestOverlayScript('arm') + expect(script).toContain('pointer-events:all') + expect(script).toContain('cursor:crosshair') + expect(script).toContain('100vw') + expect(script).toContain('100vh') + }) + + it('arm script sanitizes URLs by stripping query strings', () => { + const script = buildGuestOverlayScript('arm') + expect(script).toContain('sanitizeUrl') + expect(script).toContain("u.search = ''") + expect(script).toContain("u.hash = ''") + }) + + it('arm script sanitizeUrl returns empty string on parse failure', () => { + const script = buildGuestOverlayScript('arm') + // The catch block should return '' not the raw URL + expect(script).toContain("return '';") + }) +}) diff --git a/src/main/browser/grab-guest-script.ts b/src/main/browser/grab-guest-script.ts new file mode 100644 index 000000000..8f64e6b2d --- /dev/null +++ b/src/main/browser/grab-guest-script.ts @@ -0,0 +1,506 @@ +/* eslint-disable max-lines -- Why: the guest overlay runtime is a single +self-contained JS string template that must be injected atomically into the +guest page. Splitting it across modules would require a string concatenation +build step that adds complexity without improving auditability. */ +// --------------------------------------------------------------------------- +// Browser Context Grab — guest overlay runtime builder +// +// This module produces self-contained JavaScript strings that main injects into +// browser guests via executeJavaScript(). The guest runtime is intentionally +// ephemeral: it installs on arm, resolves once on finalize, and fully removes +// itself on teardown. +// +// Why a string builder rather than a bundled file: Orca's browser guests have +// no preload and no Node access. The injected code must be a plain JS string +// that runs in the page's own world. Keeping it as a template here lets main +// version it alongside the rest of the grab lifecycle. +// --------------------------------------------------------------------------- + +type GuestScriptAction = 'arm' | 'awaitClick' | 'finalize' | 'extractHover' | 'teardown' + +/** + * Build a self-contained JS script for the given grab lifecycle action. + * + * - `arm`: install the shadow-root overlay, hover listeners, and extraction logic + * - `awaitClick`: return a Promise that resolves with the payload when the user clicks + * - `finalize`: extract the payload for the currently hovered element and return it + * - `extractHover`: extract the payload for the currently hovered element WITHOUT cleanup + * - `teardown`: remove the overlay and all listeners + */ +export function buildGuestOverlayScript(action: GuestScriptAction): string { + switch (action) { + case 'arm': + return ARM_SCRIPT + case 'awaitClick': + return AWAIT_CLICK_SCRIPT + case 'finalize': + return FINALIZE_SCRIPT + case 'extractHover': + return EXTRACT_HOVER_SCRIPT + case 'teardown': + return TEARDOWN_SCRIPT + } +} + +// --------------------------------------------------------------------------- +// The arm script installs the overlay container and hover tracking. +// It stores state on window.__orcaGrab so finalize/teardown can access it. +// --------------------------------------------------------------------------- +const ARM_SCRIPT = `(function() { + 'use strict'; + + // Why: always tear down any pre-existing state before arming. A malicious + // guest page could predefine window.__orcaGrab with a fake extractPayload + // function. By tearing down unconditionally we ensure our freshly installed + // extraction logic is the only code that runs. + if (window.__orcaGrab) { + try { + if (typeof window.__orcaGrab.cleanup === 'function') { + window.__orcaGrab.cleanup(); + } + } catch(e) {} + delete window.__orcaGrab; + } + + // --- Budget constants (mirrored from shared types) --- + var BUDGET = { + textSnippetMaxLength: 200, + nearbyTextEntryMaxLength: 200, + nearbyTextMaxEntries: 10, + htmlSnippetMaxLength: 4096, + ancestorPathMaxEntries: 10 + }; + + // --- Safe attribute names --- + var SAFE_ATTRS = new Set([ + 'id', 'class', 'name', 'type', 'role', 'href', 'src', 'alt', + 'title', 'placeholder', 'for', 'action', 'method' + ]); + + var SECRET_PATTERNS = [ + 'access_token', 'auth_token', 'api_key', 'apikey', 'client_secret', + 'oauth_state', 'x-amz-', 'session_id', 'sessionid', 'csrf', + 'secret', 'password', 'passwd' + ]; + + var STYLE_PROPS = [ + 'display', 'position', 'width', 'height', 'margin', 'padding', + 'color', 'backgroundColor', 'border', 'borderRadius', 'fontFamily', + 'fontSize', 'fontWeight', 'lineHeight', 'textAlign', 'zIndex' + ]; + + // --- Helpers --- + function clampStr(s, max) { + if (!s || typeof s !== 'string') return ''; + if (s.length <= max) return s; + return s.slice(0, max) + ' (truncated)'; + } + + function containsSecret(value) { + if (!value) return false; + var lower = value.toLowerCase(); + for (var i = 0; i < SECRET_PATTERNS.length; i++) { + if (lower.indexOf(SECRET_PATTERNS[i]) !== -1) return true; + } + return false; + } + + function sanitizeUrl(url) { + try { + var u = new URL(url); + u.search = ''; + u.hash = ''; + return u.toString(); + } catch (e) { + // Why: returning the raw URL on parse failure could preserve javascript: + // URIs or other non-http schemes. Return empty string instead. + return ''; + } + } + + function getTextSnippet(el) { + var text = (el.textContent || '').trim().replace(/\\s+/g, ' '); + return clampStr(text, BUDGET.textSnippetMaxLength); + } + + function getHtmlSnippet(el) { + var clone = el.cloneNode(true); + // Strip script tags for safety + var scripts = clone.querySelectorAll('script'); + for (var i = 0; i < scripts.length; i++) { + scripts[i].remove(); + } + var html = clone.outerHTML || ''; + return clampStr(html, BUDGET.htmlSnippetMaxLength); + } + + function getSafeAttributes(el) { + var attrs = {}; + for (var i = 0; i < el.attributes.length; i++) { + var attr = el.attributes[i]; + var name = attr.name.toLowerCase(); + var isAria = name.indexOf('aria-') === 0; + if (!SAFE_ATTRS.has(name) && !isAria) continue; + var value = attr.value; + // Redact secret-looking values + if (containsSecret(value)) { + attrs[name] = '[redacted]'; + } else if ((name === 'href' || name === 'src' || name === 'action') && value) { + // Strip query strings and fragments from URL-bearing attributes + attrs[name] = sanitizeUrl(value); + } else if (name === 'class') { + // Cap class list length + attrs[name] = clampStr(value, 200); + } else { + attrs[name] = value; + } + } + return attrs; + } + + function getAccessibility(el) { + var role = el.getAttribute('role') || el.tagName.toLowerCase(); + var ariaLabel = el.getAttribute('aria-label') || null; + var ariaLabelledBy = el.getAttribute('aria-labelledby') || null; + var accessibleName = null; + // Attempt to derive accessible name + if (ariaLabel) { + accessibleName = ariaLabel; + } else if (ariaLabelledBy) { + var parts = ariaLabelledBy.split(/\\s+/); + var names = []; + for (var i = 0; i < parts.length; i++) { + var ref = document.getElementById(parts[i]); + if (ref) names.push((ref.textContent || '').trim()); + } + if (names.length) accessibleName = names.join(' '); + } else { + // Fall back to text content for buttons/links + var tag = el.tagName.toLowerCase(); + if (tag === 'button' || tag === 'a' || tag === 'label') { + accessibleName = clampStr((el.textContent || '').trim(), 100); + } else if (el.getAttribute('title')) { + accessibleName = el.getAttribute('title'); + } else if (el.getAttribute('alt')) { + accessibleName = el.getAttribute('alt'); + } + } + return { + role: role, + accessibleName: accessibleName, + ariaLabel: ariaLabel, + ariaLabelledBy: ariaLabelledBy + }; + } + + function getComputedStyleSubset(el) { + var cs = window.getComputedStyle(el); + var result = {}; + for (var i = 0; i < STYLE_PROPS.length; i++) { + result[STYLE_PROPS[i]] = cs.getPropertyValue( + STYLE_PROPS[i].replace(/[A-Z]/g, function(m) { return '-' + m.toLowerCase(); }) + ) || ''; + } + return result; + } + + function buildSelector(el) { + var parts = []; + var current = el; + while (current && current !== document.body && parts.length < 10) { + var tag = current.tagName.toLowerCase(); + var id = current.id; + if (id) { + parts.unshift(tag + '#' + CSS.escape(id)); + break; + } + var parent = current.parentElement; + if (parent) { + var siblings = Array.from(parent.children).filter( + function(c) { return c.tagName === current.tagName; } + ); + if (siblings.length > 1) { + var index = siblings.indexOf(current) + 1; + parts.unshift(tag + ':nth-of-type(' + index + ')'); + } else { + parts.unshift(tag); + } + } else { + parts.unshift(tag); + } + current = parent; + } + return parts.join(' > ') || el.tagName.toLowerCase(); + } + + function getNearbyText(el) { + var results = []; + var parent = el.parentElement; + if (!parent) return results; + var siblings = parent.children; + for (var i = 0; i < siblings.length && results.length < BUDGET.nearbyTextMaxEntries; i++) { + if (siblings[i] === el) continue; + var text = (siblings[i].textContent || '').trim().replace(/\\s+/g, ' '); + if (text) { + results.push(clampStr(text, BUDGET.nearbyTextEntryMaxLength)); + } + } + return results; + } + + function getAncestorPath(el) { + var path = []; + var current = el.parentElement; + while (current && current !== document.documentElement && path.length < BUDGET.ancestorPathMaxEntries) { + var tag = current.tagName.toLowerCase(); + var role = current.getAttribute('role'); + path.push(role ? tag + '[role=' + role + ']' : tag); + current = current.parentElement; + } + return path; + } + + // --- Build full payload for an element --- + function extractPayload(el) { + var rect = el.getBoundingClientRect(); + return { + page: { + sanitizedUrl: sanitizeUrl(window.location.href), + title: document.title || '', + viewportWidth: window.innerWidth, + viewportHeight: window.innerHeight, + scrollX: window.scrollX, + scrollY: window.scrollY, + devicePixelRatio: window.devicePixelRatio || 1, + capturedAt: new Date().toISOString() + }, + target: { + tagName: el.tagName.toLowerCase(), + selector: buildSelector(el), + textSnippet: getTextSnippet(el), + htmlSnippet: getHtmlSnippet(el), + attributes: getSafeAttributes(el), + accessibility: getAccessibility(el), + rectViewport: { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height + }, + rectPage: { + x: rect.x + window.scrollX, + y: rect.y + window.scrollY, + width: rect.width, + height: rect.height + }, + computedStyles: getComputedStyleSubset(el) + }, + nearbyText: getNearbyText(el), + ancestorPath: getAncestorPath(el), + screenshot: null + }; + } + + // --- Overlay UI --- + // Why: the host element is a full-viewport overlay with pointer-events:all + // so it acts as a click catcher. This prevents the page from receiving the + // selection click. The overlay uses elementFromPoint (with itself temporarily + // hidden) to identify the element underneath the pointer. + var host = document.createElement('div'); + host.id = '__orca-grab-host'; + host.style.cssText = 'position:fixed;top:0;left:0;width:100vw;height:100vh;z-index:2147483647;pointer-events:all;cursor:crosshair;'; + document.documentElement.appendChild(host); + + var shadow = host.attachShadow({ mode: 'closed' }); + + // Visual container for highlight/label — pointer-events:none so clicks go to host + var overlay = document.createElement('div'); + overlay.style.cssText = 'position:fixed;top:0;left:0;width:100vw;height:100vh;pointer-events:none;z-index:2147483647;'; + shadow.appendChild(overlay); + + // Why: the highlight uses a white border with a dark outer shadow so it + // reads well on both light and dark page backgrounds. + var highlightBox = document.createElement('div'); + highlightBox.style.cssText = 'position:fixed;border:2px solid rgba(255,255,255,0.9);border-radius:3px;pointer-events:none;transition:all 0.05s ease-out;display:none;background:rgba(255,255,255,0.08);box-shadow:0 0 0 1px rgba(0,0,0,0.3),0 2px 8px rgba(0,0,0,0.15);'; + overlay.appendChild(highlightBox); + + // Hover label — dark neutral pill + var hoverLabel = document.createElement('div'); + hoverLabel.style.cssText = 'position:fixed;padding:3px 8px;background:rgba(30,30,30,0.92);color:#e5e5e5;font:11px/1.4 -apple-system,BlinkMacSystemFont,system-ui,sans-serif;border-radius:4px;pointer-events:none;white-space:nowrap;display:none;max-width:300px;overflow:hidden;text-overflow:ellipsis;box-shadow:0 2px 8px rgba(0,0,0,0.3);'; + overlay.appendChild(hoverLabel); + + var currentEl = null; + + function updateHighlight(el) { + if (!el || el === document.documentElement || el === document.body) { + highlightBox.style.display = 'none'; + hoverLabel.style.display = 'none'; + currentEl = null; + return; + } + currentEl = el; + var rect = el.getBoundingClientRect(); + highlightBox.style.left = rect.x + 'px'; + highlightBox.style.top = rect.y + 'px'; + highlightBox.style.width = rect.width + 'px'; + highlightBox.style.height = rect.height + 'px'; + highlightBox.style.display = 'block'; + + // Build label text + var tag = el.tagName.toLowerCase(); + var role = el.getAttribute('role'); + var text = (el.textContent || '').trim().replace(/\\s+/g, ' '); + if (text.length > 40) text = text.slice(0, 37) + '...'; + var w = Math.round(rect.width); + var h = Math.round(rect.height); + var parts = [tag]; + if (role) parts.push('role=' + role); + if (text) parts.push('"' + text + '"'); + parts.push(w + 'x' + h); + hoverLabel.textContent = parts.join(' '); + + // Position label below the element, or above if near bottom + var labelY = rect.bottom + 6; + if (labelY + 28 > window.innerHeight) { + labelY = rect.top - 28; + } + hoverLabel.style.left = Math.max(4, rect.x) + 'px'; + hoverLabel.style.top = labelY + 'px'; + hoverLabel.style.display = 'block'; + } + + function onPointerMove(e) { + // Temporarily hide the overlay to hit-test the element underneath + host.style.pointerEvents = 'none'; + var el = document.elementFromPoint(e.clientX, e.clientY); + host.style.pointerEvents = 'all'; + if (el) { + requestAnimationFrame(function() { updateHighlight(el); }); + } + } + + // Why: mousemove on the host (not document) because the host is the + // full-viewport click catcher that receives all pointer events. + host.addEventListener('mousemove', onPointerMove); + + // Store state for awaitClick/finalize/teardown access + window.__orcaGrab = { + host: host, + extractPayload: extractPayload, + getCurrentElement: function() { return currentEl; }, + // Why: freeze the highlight so the selected element stays outlined while + // the renderer shows the copy menu. Disabling pointer-events on the host + // lets the cursor return to normal and prevents the crosshair from showing + // over the dropdown menu's area in the webview. + freezeHighlight: function() { + host.removeEventListener('mousemove', onPointerMove); + host.style.pointerEvents = 'none'; + host.style.cursor = 'default'; + }, + cleanup: function() { + host.removeEventListener('mousemove', onPointerMove); + try { host.remove(); } catch(e) {} + delete window.__orcaGrab; + } + }; + + return true; +})()` + +// --------------------------------------------------------------------------- +// The awaitClick script returns a Promise that resolves when the user clicks +// on the full-viewport overlay. The click never reaches the page because the +// overlay host has pointer-events:all and the handler calls stopPropagation. +// --------------------------------------------------------------------------- +const AWAIT_CLICK_SCRIPT = `new Promise(function(resolve, reject) { + 'use strict'; + var grab = window.__orcaGrab; + if (!grab) { + reject(new Error('Grab not armed')); + return; + } + + function onClick(e) { + e.preventDefault(); + e.stopPropagation(); + e.stopImmediatePropagation(); + grab.host.removeEventListener('click', onClick, true); + grab.host.removeEventListener('contextmenu', onContext, true); + var el = grab.getCurrentElement(); + if (!el) { + grab.cleanup(); + reject(new Error('cancelled')); + return; + } + var payload = grab.extractPayload(el); + // Why: freeze the highlight instead of removing it so the user sees + // which element was selected while the copy menu is shown. Teardown + // happens later when the renderer calls setGrabMode(false) or re-arms. + grab.freezeHighlight(); + resolve(payload); + } + + function onContext(e) { + // Block right-click while armed + e.preventDefault(); + e.stopPropagation(); + e.stopImmediatePropagation(); + } + + grab.host.addEventListener('click', onClick, true); + grab.host.addEventListener('contextmenu', onContext, true); + + // Store cancel hook so teardown can reject the Promise + grab.cancelAwait = function() { + grab.host.removeEventListener('click', onClick, true); + grab.host.removeEventListener('contextmenu', onContext, true); + grab.cleanup(); + reject(new Error('cancelled')); + }; +})` + +// --------------------------------------------------------------------------- +// The finalize script extracts the payload for the currently hovered element. +// --------------------------------------------------------------------------- +const FINALIZE_SCRIPT = `(function() { + 'use strict'; + var grab = window.__orcaGrab; + if (!grab) return null; + var el = grab.getCurrentElement(); + if (!el) return null; + var payload = grab.extractPayload(el); + grab.cleanup(); + return payload; +})()` + +// --------------------------------------------------------------------------- +// The extractHover script reads the payload for the currently hovered element +// WITHOUT cleaning up. The overlay and awaitClick listener stay active so the +// user can continue picking elements. Used by keyboard shortcuts (C/S) that +// copy the hovered element without requiring a click first. +// --------------------------------------------------------------------------- +const EXTRACT_HOVER_SCRIPT = `(function() { + 'use strict'; + var grab = window.__orcaGrab; + if (!grab) return null; + var el = grab.getCurrentElement(); + if (!el) return null; + return grab.extractPayload(el); +})()` + +// --------------------------------------------------------------------------- +// The teardown script removes the overlay and cleans up all state. +// --------------------------------------------------------------------------- +const TEARDOWN_SCRIPT = `(function() { + 'use strict'; + var grab = window.__orcaGrab; + if (!grab) return true; + // If there's an active awaitClick Promise, cancel it so the + // executeJavaScript call in main rejects and settles the grab op. + if (grab.cancelAwait) { + grab.cancelAwait(); + } else { + grab.cleanup(); + } + return true; +})()` diff --git a/src/main/ipc/browser.ts b/src/main/ipc/browser.ts index 1d412fabc..806265615 100644 --- a/src/main/ipc/browser.ts +++ b/src/main/ipc/browser.ts @@ -1,5 +1,16 @@ import { ipcMain } from 'electron' import { browserManager } from '../browser/browser-manager' +import type { + BrowserSetGrabModeArgs, + BrowserSetGrabModeResult, + BrowserAwaitGrabSelectionArgs, + BrowserGrabResult, + BrowserCancelGrabArgs, + BrowserCaptureSelectionScreenshotArgs, + BrowserCaptureSelectionScreenshotResult, + BrowserExtractHoverArgs, + BrowserExtractHoverResult +} from '../../shared/browser-grab-types' let trustedBrowserRendererWebContentsId: number | null = null @@ -31,6 +42,11 @@ export function registerBrowserHandlers(): void { ipcMain.removeHandler('browser:registerGuest') ipcMain.removeHandler('browser:unregisterGuest') ipcMain.removeHandler('browser:openDevTools') + ipcMain.removeHandler('browser:setGrabMode') + ipcMain.removeHandler('browser:awaitGrabSelection') + ipcMain.removeHandler('browser:cancelGrab') + ipcMain.removeHandler('browser:captureSelectionScreenshot') + ipcMain.removeHandler('browser:extractHoverPayload') ipcMain.handle( 'browser:registerGuest', @@ -60,4 +76,96 @@ export function registerBrowserHandlers(): void { } return browserManager.openDevTools(args.browserTabId) }) + + // --- Browser Context Grab IPC --- + + ipcMain.handle( + 'browser:setGrabMode', + async (event, args: BrowserSetGrabModeArgs): Promise => { + if (!isTrustedBrowserRenderer(event.sender)) { + return { ok: false, reason: 'not-authorized' } + } + const guest = browserManager.getAuthorizedGuest(args.browserTabId, event.sender.id) + if (!guest) { + return { ok: false, reason: 'not-ready' } + } + const success = await browserManager.setGrabMode(args.browserTabId, args.enabled, guest) + return success ? { ok: true } : { ok: false, reason: 'not-ready' } + } + ) + + ipcMain.handle( + 'browser:awaitGrabSelection', + async (event, args: BrowserAwaitGrabSelectionArgs): Promise => { + if (!isTrustedBrowserRenderer(event.sender)) { + return { opId: args.opId, kind: 'error', reason: 'Not authorized' } + } + const guest = browserManager.getAuthorizedGuest(args.browserTabId, event.sender.id) + if (!guest) { + return { opId: args.opId, kind: 'error', reason: 'Guest not ready' } + } + // Why: no hasActiveGrabOp guard here — awaitGrabSelection already handles + // the conflict by cancelling the previous op. Blocking at the IPC layer + // would create a race window where rearm() fails if the previous IPC call + // hasn't fully resolved yet. + return browserManager.awaitGrabSelection(args.browserTabId, args.opId, guest) + } + ) + + ipcMain.handle('browser:cancelGrab', (event, args: BrowserCancelGrabArgs): boolean => { + if (!isTrustedBrowserRenderer(event.sender)) { + return false + } + // Why: verify the sender actually owns this tab, consistent with the + // authorization check in setGrabMode/awaitGrabSelection/captureScreenshot. + const guest = browserManager.getAuthorizedGuest(args.browserTabId, event.sender.id) + if (!guest) { + return false + } + browserManager.cancelGrabOp(args.browserTabId, 'user') + return true + }) + + ipcMain.handle( + 'browser:captureSelectionScreenshot', + async ( + event, + args: BrowserCaptureSelectionScreenshotArgs + ): Promise => { + if (!isTrustedBrowserRenderer(event.sender)) { + return { ok: false, reason: 'Not authorized' } + } + const guest = browserManager.getAuthorizedGuest(args.browserTabId, event.sender.id) + if (!guest) { + return { ok: false, reason: 'Guest not ready' } + } + const screenshot = await browserManager.captureSelectionScreenshot( + args.browserTabId, + args.rect, + guest + ) + if (!screenshot) { + return { ok: false, reason: 'Screenshot capture failed' } + } + return { ok: true, screenshot } + } + ) + + ipcMain.handle( + 'browser:extractHoverPayload', + async (event, args: BrowserExtractHoverArgs): Promise => { + if (!isTrustedBrowserRenderer(event.sender)) { + return { ok: false, reason: 'Not authorized' } + } + const guest = browserManager.getAuthorizedGuest(args.browserTabId, event.sender.id) + if (!guest) { + return { ok: false, reason: 'Guest not ready' } + } + const payload = await browserManager.extractHoverPayload(args.browserTabId, guest) + if (!payload) { + return { ok: false, reason: 'No element hovered' } + } + return { ok: true, payload } + } + ) } diff --git a/src/main/window/attach-main-window-services.ts b/src/main/window/attach-main-window-services.ts index bdc1201a6..c3b9b1854 100644 --- a/src/main/window/attach-main-window-services.ts +++ b/src/main/window/attach-main-window-services.ts @@ -1,4 +1,4 @@ -import { app, clipboard, ipcMain, session } from 'electron' +import { app, clipboard, ipcMain, nativeImage, session } from 'electron' import type { BrowserWindow } from 'electron' import type { Store } from '../persistence' import type { CreateWorktreeResult } from '../../shared/types' @@ -127,9 +127,23 @@ function registerFileDropRelay(mainWindow: BrowserWindow): void { export function registerClipboardHandlers(): void { ipcMain.removeHandler('clipboard:readText') ipcMain.removeHandler('clipboard:writeText') + ipcMain.removeHandler('clipboard:writeImage') ipcMain.handle('clipboard:readText', () => clipboard.readText()) ipcMain.handle('clipboard:writeText', (_event, text: string) => clipboard.writeText(text)) + ipcMain.handle('clipboard:writeImage', (_event, dataUrl: string) => { + // Why: only accept validated PNG data URIs to prevent writing arbitrary + // data to the clipboard. The renderer already validates the prefix, but + // defense-in-depth applies here too. + if (typeof dataUrl !== 'string' || !dataUrl.startsWith('data:image/png;base64,')) { + return + } + const image = nativeImage.createFromDataURL(dataUrl) + if (image.isEmpty()) { + return + } + clipboard.writeImage(image) + }) } export function registerUpdaterHandlers(_store: Store): void { diff --git a/src/preload/api-types.d.ts b/src/preload/api-types.d.ts index cbe183adb..14cd761ad 100644 --- a/src/preload/api-types.d.ts +++ b/src/preload/api-types.d.ts @@ -26,6 +26,17 @@ import type { WorktreeSetupLaunch, WorkspaceSessionState } from '../../shared/types' +import type { + BrowserSetGrabModeArgs, + BrowserSetGrabModeResult, + BrowserAwaitGrabSelectionArgs, + BrowserGrabResult, + BrowserCancelGrabArgs, + BrowserCaptureSelectionScreenshotArgs, + BrowserCaptureSelectionScreenshotResult, + BrowserExtractHoverArgs, + BrowserExtractHoverResult +} from '../../shared/browser-grab-types' import type { CliInstallStatus } from '../../shared/cli-install-types' import type { RuntimeStatus, RuntimeSyncWindowGraph } from '../../shared/runtime-types' import type { @@ -56,6 +67,13 @@ export type BrowserApi = { onGuestLoadFailed: ( callback: (args: { browserTabId: string; loadError: BrowserLoadError }) => void ) => () => void + setGrabMode: (args: BrowserSetGrabModeArgs) => Promise + awaitGrabSelection: (args: BrowserAwaitGrabSelectionArgs) => Promise + cancelGrab: (args: BrowserCancelGrabArgs) => Promise + captureSelectionScreenshot: ( + args: BrowserCaptureSelectionScreenshotArgs + ) => Promise + extractHoverPayload: (args: BrowserExtractHoverArgs) => Promise } export type PreflightStatus = { @@ -322,6 +340,7 @@ export type PreloadApi = { onTerminalZoom: (callback: (direction: 'in' | 'out' | 'reset') => void) => () => void readClipboardText: () => Promise writeClipboardText: (text: string) => Promise + writeClipboardImage: (dataUrl: string) => Promise onFileDrop: ( callback: (data: { path: string; target: 'editor' | 'terminal' }) => void ) => () => void diff --git a/src/preload/index.ts b/src/preload/index.ts index b4a7a3a0f..08c18c55d 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -330,7 +330,30 @@ const api = { ) => callback(data) ipcRenderer.on('browser:guest-load-failed', listener) return () => ipcRenderer.removeListener('browser:guest-load-failed', listener) - } + }, + + setGrabMode: (args: { + browserTabId: string + enabled: boolean + }): Promise<{ ok: true } | { ok: false; reason: string }> => + ipcRenderer.invoke('browser:setGrabMode', args), + + awaitGrabSelection: (args: { browserTabId: string; opId: string }): Promise => + ipcRenderer.invoke('browser:awaitGrabSelection', args), + + cancelGrab: (args: { browserTabId: string }): Promise => + ipcRenderer.invoke('browser:cancelGrab', args), + + captureSelectionScreenshot: (args: { + browserTabId: string + rect: { x: number; y: number; width: number; height: number } + }): Promise<{ ok: true; screenshot: unknown } | { ok: false; reason: string }> => + ipcRenderer.invoke('browser:captureSelectionScreenshot', args), + + extractHoverPayload: (args: { + browserTabId: string + }): Promise<{ ok: true; payload: unknown } | { ok: false; reason: string }> => + ipcRenderer.invoke('browser:extractHoverPayload', args) }, hooks: { @@ -546,6 +569,8 @@ const api = { readClipboardText: (): Promise => ipcRenderer.invoke('clipboard:readText'), writeClipboardText: (text: string): Promise => ipcRenderer.invoke('clipboard:writeText', text), + writeClipboardImage: (dataUrl: string): Promise => + ipcRenderer.invoke('clipboard:writeImage', dataUrl), onFileDrop: ( callback: (data: { path: string; target: 'editor' | 'terminal' }) => void ): (() => void) => { diff --git a/src/renderer/src/components/browser-pane/BrowserPane.tsx b/src/renderer/src/components/browser-pane/BrowserPane.tsx index cce9f303c..1dd844bc9 100644 --- a/src/renderer/src/components/browser-pane/BrowserPane.tsx +++ b/src/renderer/src/components/browser-pane/BrowserPane.tsx @@ -3,14 +3,26 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { ArrowLeft, ArrowRight, + Copy, + Crosshair, ExternalLink, Globe, + Image, Loader2, RefreshCw, SquareCode } from 'lucide-react' +import { toast } from 'sonner' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuShortcut, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu' import { ORCA_BROWSER_BLANK_URL, ORCA_BROWSER_PARTITION } from '../../../../shared/constants' import type { BrowserLoadError, BrowserTab as BrowserTabState } from '../../../../shared/types' import { @@ -23,6 +35,12 @@ import { markEvictedBrowserTab, rememberLiveBrowserUrl } from './browser-runtime' +import type { + BrowserGrabPayload, + BrowserGrabScreenshot +} from '../../../../shared/browser-grab-types' +import { useGrabMode } from './useGrabMode' +import { formatGrabPayloadAsText } from './GrabConfirmationSheet' type BrowserTabPageState = Partial< Pick< @@ -241,6 +259,8 @@ export default function BrowserPane({ }): React.JSX.Element { const containerRef = useRef(null) const webviewRef = useRef(null) + const browserTabIdRef = useRef(browserTab.id) + browserTabIdRef.current = browserTab.id const faviconUrlRef = useRef(browserTab.faviconUrl) const initialBrowserUrlRef = useRef(browserTab.url) const browserTabUrlRef = useRef(browserTab.url) @@ -251,6 +271,7 @@ export default function BrowserPane({ const [addressBarValue, setAddressBarValue] = useState(browserTab.url) const addressBarValueRef = useRef(browserTab.url) const [resourceNotice, setResourceNotice] = useState(null) + const grab = useGrabMode(browserTab.id) useEffect(() => { setAddressBarValue(toDisplayUrl(browserTab.url)) @@ -573,6 +594,123 @@ export default function BrowserPane({ return () => window.clearInterval(intervalId) }, [browserTab.id, browserTab.loading]) + // CmdOrCtrl+Shift+G toggles grab mode + useEffect(() => { + const handleKeyDown = (e: KeyboardEvent): void => { + const isMod = navigator.userAgent.includes('Mac') ? e.metaKey : e.ctrlKey + if (isMod && e.shiftKey && e.key.toLowerCase() === 'g') { + e.preventDefault() + grab.toggle() + } + } + window.addEventListener('keydown', handleKeyDown) + return () => window.removeEventListener('keydown', handleKeyDown) + }, [grab]) + + // Why: single-key shortcuts (C / S) let the user copy the hovered element + // without clicking. During 'armed'/'awaiting' state, the shortcut calls the + // extractHoverPayload IPC to read the currently hovered element directly. + // During 'confirming' state, it uses the already-captured payload instead. + // The shortcuts only fire when grab mode is active, so they don't interfere + // with normal typing elsewhere. + const grabPayloadRef = useRef(grab.payload) + grabPayloadRef.current = grab.payload + useEffect(() => { + if (grab.state === 'idle' || grab.state === 'error') { + return + } + const handleKeyDown = (e: KeyboardEvent): void => { + // Ignore if modifier keys are held — user may be doing Cmd+C etc. + if (e.metaKey || e.ctrlKey || e.altKey) { + return + } + const key = e.key.toLowerCase() + if (key !== 'c' && key !== 's') { + return + } + e.preventDefault() + e.stopPropagation() + + const copyFromPayload = (payload: BrowserGrabPayload): void => { + if (key === 'c') { + const text = formatGrabPayloadAsText(payload) + void window.api.ui.writeClipboardText(text) + toast.success('Copied element context to clipboard') + } else { + const dataUrl = payload.screenshot?.dataUrl + if (dataUrl?.startsWith('data:image/png;base64,')) { + void window.api.ui.writeClipboardImage(dataUrl) + toast.success('Copied screenshot to clipboard') + } else { + toast.error('No screenshot available') + } + } + } + + if (grab.state === 'confirming') { + // Already have the payload from the click selection + const currentPayload = grabPayloadRef.current + if (currentPayload) { + copyFromPayload(currentPayload) + } + grab.rearm() + } else { + // armed/awaiting — extract hovered element via IPC without clicking + void (async () => { + const result = await window.api.browser.extractHoverPayload({ + browserTabId: browserTabIdRef.current + }) + if (!result.ok) { + toast.error('No element hovered') + return + } + const payload = result.payload as BrowserGrabPayload + + // For screenshot shortcut, also capture the screenshot + if (key === 's') { + try { + const ssResult = await window.api.browser.captureSelectionScreenshot({ + browserTabId: browserTabIdRef.current, + rect: payload.target.rectViewport + }) + if (ssResult.ok) { + payload.screenshot = ssResult.screenshot as BrowserGrabScreenshot + } + } catch { + // Screenshot failure is non-fatal for the copy flow + } + } + + copyFromPayload(payload) + })() + } + } + window.addEventListener('keydown', handleKeyDown, true) + return () => window.removeEventListener('keydown', handleKeyDown, true) + }, [grab]) + + // Why: the copy handlers do NOT call grab.rearm() themselves. Rearm is + // triggered by onOpenChange(false) when the dropdown menu closes after + // item selection. This prevents a double-rearm race that would cause the + // second grab selection's dropdown to fail to appear. + const handleGrabCopy = useCallback(() => { + if (!grab.payload) { + return + } + const text = formatGrabPayloadAsText(grab.payload) + void window.api.ui.writeClipboardText(text) + toast.success('Copied element context to clipboard') + }, [grab]) + + const handleGrabCopyScreenshot = useCallback(() => { + const dataUrl = grab.payload?.screenshot?.dataUrl + if (!dataUrl?.startsWith('data:image/png;base64,')) { + return + } + void window.api.ui.writeClipboardImage(dataUrl) + toast.success('Copied screenshot to clipboard') + }, [grab]) + const submitAddressBar = (): void => { const nextUrl = normalizeBrowserNavigationUrl(addressBarValue) if (!nextUrl) { @@ -683,6 +821,17 @@ export default function BrowserPane({ /> + + + + ) : null}
) : null} + {/* Why: the grab copy menu appears at the selected element's location + inside the webview, like a right-click context menu. A hidden trigger + is positioned at the element's center (translated from guest viewport + coordinates to renderer coordinates using the webview's offset). */} + { + if (!open && grab.state === 'confirming') { + grab.rearm() + } + }} + > + + ', + attributes: { class: 'primary', type: 'button' }, + accessibility: { + role: 'button', + accessibleName: 'Start free trial', + ariaLabel: null, + ariaLabelledBy: null + }, + rectViewport: { x: 400, y: 300, width: 148, height: 44 }, + rectPage: { x: 400, y: 300, width: 148, height: 44 }, + computedStyles: { + display: 'inline-flex', + position: 'relative', + width: '148px', + height: '44px', + margin: '0px', + padding: '12px 24px', + color: 'rgb(255, 255, 255)', + backgroundColor: 'rgb(99, 102, 241)', + border: '0px none', + borderRadius: '8px', + fontFamily: 'Inter, sans-serif', + fontSize: '16px', + fontWeight: '600', + lineHeight: '20px', + textAlign: 'center', + zIndex: 'auto' + } + }, + nearbyText: ['Pro', '$29/month', 'Unlimited projects'], + ancestorPath: ['section', 'main', 'body'], + screenshot: null, + ...overrides + } +} + +describe('formatGrabPayloadAsText', () => { + it('formats a complete payload with all sections', () => { + const text = formatGrabPayloadAsText(makeTestPayload()) + + expect(text).toContain('Attached browser context from https://example.com/pricing') + expect(text).toContain('Selected element:') + expect(text).toContain('button') + expect(text).toContain('Accessible name: "Start free trial"') + expect(text).toContain('Selector: main section:nth-of-type(2) button.primary') + expect(text).toContain('148x44') + expect(text).toContain('Nearby context:') + expect(text).toContain('- Pro') + expect(text).toContain('- $29/month') + expect(text).toContain('HTML:') + expect(text).toContain('') + }) + + it('omits nearby context section when empty', () => { + const text = formatGrabPayloadAsText(makeTestPayload({ nearbyText: [] })) + expect(text).not.toContain('Nearby context:') + }) + + it('omits text content section when empty', () => { + const payload = makeTestPayload() + payload.target.textSnippet = '' + const text = formatGrabPayloadAsText(payload) + expect(text).not.toContain('Text content:') + }) + + it('includes computed styles that differ from defaults', () => { + const text = formatGrabPayloadAsText(makeTestPayload()) + expect(text).toContain('Computed styles:') + expect(text).toContain('display: inline-flex') + expect(text).toContain('position: relative') + expect(text).toContain('font-size: 16px') + }) + + it('includes ancestor path', () => { + const text = formatGrabPayloadAsText(makeTestPayload()) + expect(text).toContain('Ancestor path: section > main > body') + }) + + it('handles payload with no accessible name', () => { + const payload = makeTestPayload() + payload.target.accessibility.accessibleName = null + const text = formatGrabPayloadAsText(payload) + expect(text).not.toContain('Accessible name:') + }) +}) diff --git a/src/renderer/src/components/browser-pane/GrabConfirmationSheet.tsx b/src/renderer/src/components/browser-pane/GrabConfirmationSheet.tsx new file mode 100644 index 000000000..3dcd2945c --- /dev/null +++ b/src/renderer/src/components/browser-pane/GrabConfirmationSheet.tsx @@ -0,0 +1,250 @@ +import { Copy, Image, MessageSquarePlus, X } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { ScrollArea } from '@/components/ui/scroll-area' +import type { BrowserGrabPayload } from '../../../../shared/browser-grab-types' + +// --------------------------------------------------------------------------- +// Grab payload → human-readable prompt context +// --------------------------------------------------------------------------- + +export function formatGrabPayloadAsText(payload: BrowserGrabPayload): string { + const lines: string[] = [] + + lines.push(`Attached browser context from ${payload.page.sanitizedUrl}`) + lines.push('') + + // Selected element summary + lines.push('Selected element:') + lines.push(payload.target.tagName) + if (payload.target.accessibility.accessibleName) { + lines.push(`Accessible name: "${payload.target.accessibility.accessibleName}"`) + } + if (payload.target.accessibility.role) { + lines.push(`Role: ${payload.target.accessibility.role}`) + } + lines.push(`Selector: ${payload.target.selector}`) + const { rectViewport } = payload.target + lines.push(`Dimensions: ${Math.round(rectViewport.width)}x${Math.round(rectViewport.height)}`) + lines.push('') + + // Text snippet + if (payload.target.textSnippet) { + lines.push('Text content:') + lines.push(payload.target.textSnippet) + lines.push('') + } + + // Nearby context + if (payload.nearbyText.length > 0) { + lines.push('Nearby context:') + for (const text of payload.nearbyText) { + lines.push(`- ${text}`) + } + lines.push('') + } + + // Computed styles + const styles = payload.target.computedStyles + const styleLines: string[] = [] + if (styles.display && styles.display !== 'inline') { + styleLines.push(`display: ${styles.display}`) + } + if (styles.position && styles.position !== 'static') { + styleLines.push(`position: ${styles.position}`) + } + if (styles.fontSize) { + styleLines.push(`font-size: ${styles.fontSize}`) + } + if (styles.color) { + styleLines.push(`color: ${styles.color}`) + } + if (styles.backgroundColor && styles.backgroundColor !== 'rgba(0, 0, 0, 0)') { + styleLines.push(`background: ${styles.backgroundColor}`) + } + if (styleLines.length > 0) { + lines.push('Computed styles:') + for (const sl of styleLines) { + lines.push(` ${sl}`) + } + lines.push('') + } + + // HTML snippet + if (payload.target.htmlSnippet) { + lines.push('HTML:') + lines.push(payload.target.htmlSnippet) + lines.push('') + } + + // Ancestor path + if (payload.ancestorPath.length > 0) { + lines.push(`Ancestor path: ${payload.ancestorPath.join(' > ')}`) + } + + return lines.join('\n').trimEnd() +} + +// --------------------------------------------------------------------------- +// Security: all page-derived strings are rendered as escaped plain text. +// No innerHTML, no markdown rendering, no auto-linking. +// --------------------------------------------------------------------------- + +function EscapedText({ text, className }: { text: string; className?: string }): React.JSX.Element { + return {text} +} + +// --------------------------------------------------------------------------- +// Confirmation Sheet Component +// --------------------------------------------------------------------------- + +export default function GrabConfirmationSheet({ + payload, + onCopy, + onCopyScreenshot, + onAttach, + onCancel +}: { + payload: BrowserGrabPayload + onCopy: () => void + onCopyScreenshot: (() => void) | null + onAttach: () => void + onCancel: () => void +}): React.JSX.Element { + const { target, page, nearbyText } = payload + + return ( +
+ {/* Header */} +
+
+
+ Grab +
+ + Review before attaching. Captured page context may include visible site content. + +
+ +
+ + {/* Content */} + +
+ {/* Screenshot preview — only render if dataUrl is a valid PNG data URI. + Why: the design doc requires screenshots be image/png only. Validating + the prefix prevents a crafted payload from injecting non-image URIs. */} + {payload.screenshot?.dataUrl?.startsWith('data:image/png;base64,') ? ( +
+ Selected element screenshot +
+ ) : null} + + {/* Element summary */} +
+

+ Selected Element +

+
+
+ + `} /> + + {target.accessibility.role ? ( + + role= + + + ) : null} +
+ {target.accessibility.accessibleName ? ( +
+ " + + " +
+ ) : null} +
+ +
+
+ {Math.round(target.rectViewport.width)}x{Math.round(target.rectViewport.height)} +
+
+
+ + {/* Page info */} +
+

+ Page +

+
+
+ +
+
+ +
+
+
+ + {/* HTML snippet */} + {target.htmlSnippet ? ( +
+

+ HTML +

+
+                
+              
+
+ ) : null} + + {/* Nearby text */} + {nearbyText.length > 0 ? ( +
+

+ Nearby Context +

+
+
    + {nearbyText.map((text, i) => ( +
  • + +
  • + ))} +
+
+
+ ) : null} +
+
+ + {/* Actions */} +
+ + + {onCopyScreenshot ? ( + + ) : null} + +
+
+ ) +} diff --git a/src/renderer/src/components/browser-pane/useGrabMode.ts b/src/renderer/src/components/browser-pane/useGrabMode.ts new file mode 100644 index 000000000..fc271f99e --- /dev/null +++ b/src/renderer/src/components/browser-pane/useGrabMode.ts @@ -0,0 +1,196 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import type { + BrowserGrabPayload, + BrowserGrabScreenshot +} from '../../../../shared/browser-grab-types' + +// --------------------------------------------------------------------------- +// Grab mode state machine +// --------------------------------------------------------------------------- + +export type GrabModeState = 'idle' | 'armed' | 'awaiting' | 'confirming' | 'error' + +export type GrabModeHook = { + state: GrabModeState + payload: BrowserGrabPayload | null + error: string | null + toggle: () => void + cancel: () => void + /** Called after Copy — re-arms grab for another pick. */ + rearm: () => void + /** Called after Attach to AI — exits grab mode entirely. */ + exit: () => void +} + +let opIdCounter = 0 +function nextOpId(): string { + return `grab-${++opIdCounter}-${Date.now()}` +} + +/** + * Hook that drives the browser grab lifecycle for a single browser tab. + * + * The state machine: idle → armed → awaiting → confirming → idle/armed + * ↘ error → idle + */ +export function useGrabMode(browserTabId: string): GrabModeHook { + const [state, setState] = useState('idle') + const [payload, setPayload] = useState(null) + const [error, setError] = useState(null) + const activeOpIdRef = useRef(null) + const browserTabIdRef = useRef(browserTabId) + + useEffect(() => { + browserTabIdRef.current = browserTabId + }, [browserTabId]) + + // Why: when the browser tab changes while grab is active, cancel the + // current grab operation so stale overlays don't survive tab switches. + useEffect(() => { + return () => { + if (activeOpIdRef.current) { + void window.api.browser.cancelGrab({ browserTabId }) + activeOpIdRef.current = null + } + } + }, [browserTabId]) + + const armAndAwait = useCallback(async () => { + const tabId = browserTabIdRef.current + + // Enable grab mode — injects the overlay + const setResult = await window.api.browser.setGrabMode({ + browserTabId: tabId, + enabled: true + }) + if (!setResult.ok) { + setState('error') + setError(`Cannot enable grab mode: ${setResult.reason}`) + return + } + + setState('armed') + + // Generate opId and await selection + const opId = nextOpId() + activeOpIdRef.current = opId + + setState('awaiting') + const result = await window.api.browser.awaitGrabSelection({ + browserTabId: tabId, + opId + }) + + // Ignore stale results + if (activeOpIdRef.current !== opId) { + return + } + + activeOpIdRef.current = null + + if (result.kind === 'selected') { + // Capture screenshot for the selected element + let screenshot: BrowserGrabScreenshot | null = null + try { + const ssResult = await window.api.browser.captureSelectionScreenshot({ + browserTabId: tabId, + rect: result.payload.target.rectViewport + }) + if (ssResult.ok) { + screenshot = ssResult.screenshot as BrowserGrabScreenshot + } + } catch { + // Screenshot failure is non-fatal + } + + setPayload({ ...result.payload, screenshot }) + setState('confirming') + } else if (result.kind === 'cancelled') { + setState('idle') + setPayload(null) + } else { + setState('error') + setError(result.reason) + } + }, []) + + const toggle = useCallback(() => { + if (state === 'idle' || state === 'error') { + setError(null) + setPayload(null) + void armAndAwait() + } else { + // Disable grab mode + void window.api.browser.setGrabMode({ + browserTabId: browserTabIdRef.current, + enabled: false + }) + if (activeOpIdRef.current) { + void window.api.browser.cancelGrab({ + browserTabId: browserTabIdRef.current + }) + activeOpIdRef.current = null + } + setState('idle') + setPayload(null) + setError(null) + } + }, [state, armAndAwait]) + + const cancel = useCallback(() => { + void window.api.browser.setGrabMode({ + browserTabId: browserTabIdRef.current, + enabled: false + }) + if (activeOpIdRef.current) { + void window.api.browser.cancelGrab({ + browserTabId: browserTabIdRef.current + }) + activeOpIdRef.current = null + } + setState('idle') + setPayload(null) + setError(null) + }, []) + + // Why: Copy re-arms so the user can quickly pick another element without + // re-clicking the toolbar button. Attach to AI exits because the user's + // intent is to continue in the chat, not keep selecting. + const rearm = useCallback(() => { + // Why: set state to 'armed' immediately so the dropdown menu closes + // before armAndAwait starts its async IPC calls. Without this, the state + // stays 'confirming' during the gap, causing the dropdown to flash. + setState('armed') + setPayload(null) + setError(null) + void armAndAwait() + }, [armAndAwait]) + + const exit = useCallback(() => { + void window.api.browser.setGrabMode({ + browserTabId: browserTabIdRef.current, + enabled: false + }) + // Why: clear the active opId so that any in-flight result from the + // previous operation is ignored by the stale-opId check in armAndAwait. + activeOpIdRef.current = null + setState('idle') + setPayload(null) + setError(null) + }, []) + + // Keyboard shortcut: Esc cancels grab mode + useEffect(() => { + const handleKeyDown = (e: KeyboardEvent): void => { + if (e.key === 'Escape' && state !== 'idle') { + e.preventDefault() + e.stopPropagation() + cancel() + } + } + window.addEventListener('keydown', handleKeyDown, true) + return () => window.removeEventListener('keydown', handleKeyDown, true) + }, [state, cancel]) + + return { state, payload, error, toggle, cancel, rearm, exit } +} diff --git a/src/shared/browser-grab-types.test.ts b/src/shared/browser-grab-types.test.ts new file mode 100644 index 000000000..e1ebd5af1 --- /dev/null +++ b/src/shared/browser-grab-types.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, it } from 'vitest' +import { + GRAB_BUDGET, + GRAB_SAFE_ATTRIBUTE_NAMES, + GRAB_SECRET_PATTERNS, + GRAB_STYLE_PROPERTIES, + isAriaAttribute +} from './browser-grab-types' + +describe('browser-grab-types', () => { + describe('GRAB_BUDGET', () => { + it('defines all required budget fields', () => { + expect(GRAB_BUDGET.textSnippetMaxLength).toBe(200) + expect(GRAB_BUDGET.nearbyTextEntryMaxLength).toBe(200) + expect(GRAB_BUDGET.nearbyTextMaxEntries).toBe(10) + expect(GRAB_BUDGET.htmlSnippetMaxLength).toBe(4096) + expect(GRAB_BUDGET.ancestorPathMaxEntries).toBe(10) + expect(GRAB_BUDGET.screenshotMaxBytes).toBe(2 * 1024 * 1024) + }) + }) + + describe('isAriaAttribute', () => { + it('returns true for aria- prefixed attributes', () => { + expect(isAriaAttribute('aria-label')).toBe(true) + expect(isAriaAttribute('aria-labelledby')).toBe(true) + expect(isAriaAttribute('aria-hidden')).toBe(true) + }) + + it('returns false for non-aria attributes', () => { + expect(isAriaAttribute('class')).toBe(false) + expect(isAriaAttribute('id')).toBe(false) + expect(isAriaAttribute('notaria-label')).toBe(false) + }) + }) + + describe('GRAB_SAFE_ATTRIBUTE_NAMES', () => { + it('includes core safe attributes', () => { + expect(GRAB_SAFE_ATTRIBUTE_NAMES.has('id')).toBe(true) + expect(GRAB_SAFE_ATTRIBUTE_NAMES.has('class')).toBe(true) + expect(GRAB_SAFE_ATTRIBUTE_NAMES.has('role')).toBe(true) + expect(GRAB_SAFE_ATTRIBUTE_NAMES.has('type')).toBe(true) + }) + + it('does not include unsafe attributes', () => { + expect(GRAB_SAFE_ATTRIBUTE_NAMES.has('onclick')).toBe(false) + expect(GRAB_SAFE_ATTRIBUTE_NAMES.has('style')).toBe(false) + expect(GRAB_SAFE_ATTRIBUTE_NAMES.has('data-secret')).toBe(false) + }) + }) + + describe('GRAB_SECRET_PATTERNS', () => { + it('includes precise secret patterns', () => { + expect(GRAB_SECRET_PATTERNS).toContain('access_token') + expect(GRAB_SECRET_PATTERNS).toContain('api_key') + expect(GRAB_SECRET_PATTERNS).toContain('password') + expect(GRAB_SECRET_PATTERNS).toContain('secret') + expect(GRAB_SECRET_PATTERNS).toContain('session_id') + expect(GRAB_SECRET_PATTERNS).toContain('csrf') + }) + + it('does not include overly broad patterns', () => { + // Why: 'code' and 'state' match normal CSS classes like 'source-code' + // and 'stateful', causing false positive redactions on most sites. + expect(GRAB_SECRET_PATTERNS).not.toContain('code') + expect(GRAB_SECRET_PATTERNS).not.toContain('state') + expect(GRAB_SECRET_PATTERNS).not.toContain('auth') + expect(GRAB_SECRET_PATTERNS).not.toContain('token') + }) + }) + + describe('GRAB_STYLE_PROPERTIES', () => { + it('includes the curated subset of computed styles', () => { + expect(GRAB_STYLE_PROPERTIES).toContain('display') + expect(GRAB_STYLE_PROPERTIES).toContain('fontSize') + expect(GRAB_STYLE_PROPERTIES).toContain('backgroundColor') + expect(GRAB_STYLE_PROPERTIES).toContain('zIndex') + }) + + it('has exactly 16 properties matching the type', () => { + expect(GRAB_STYLE_PROPERTIES).toHaveLength(16) + }) + }) +}) diff --git a/src/shared/browser-grab-types.ts b/src/shared/browser-grab-types.ts new file mode 100644 index 000000000..6fe1c191a --- /dev/null +++ b/src/shared/browser-grab-types.ts @@ -0,0 +1,221 @@ +// --------------------------------------------------------------------------- +// Browser Context Grab — shared types +// +// These types define the contract between main, preload, and renderer for the +// browser grab feature. The payload shape follows the design doc's extracted +// content model, including redaction and budget constraints. +// --------------------------------------------------------------------------- + +/** Page-level metadata captured at selection time. */ +export type BrowserGrabPageContext = { + sanitizedUrl: string + title: string + viewportWidth: number + viewportHeight: number + scrollX: number + scrollY: number + devicePixelRatio: number + capturedAt: string +} + +/** Accessibility metadata for the selected element. */ +export type BrowserGrabAccessibility = { + role: string | null + accessibleName: string | null + ariaLabel: string | null + ariaLabelledBy: string | null +} + +/** Curated subset of computed styles. */ +export type BrowserGrabComputedStyles = { + display: string + position: string + width: string + height: string + margin: string + padding: string + color: string + backgroundColor: string + border: string + borderRadius: string + fontFamily: string + fontSize: string + fontWeight: string + lineHeight: string + textAlign: string + zIndex: string +} + +/** Viewport-relative or page-relative rectangle in CSS pixels. */ +export type BrowserGrabRect = { + x: number + y: number + width: number + height: number +} + +/** The selected element's extracted data. */ +export type BrowserGrabTarget = { + tagName: string + selector: string + textSnippet: string + htmlSnippet: string + attributes: Record + accessibility: BrowserGrabAccessibility + rectViewport: BrowserGrabRect + rectPage: BrowserGrabRect + computedStyles: BrowserGrabComputedStyles +} + +/** Screenshot attachment — always PNG, either a data URL or a temp file path. */ +export type BrowserGrabScreenshot = { + mimeType: 'image/png' + dataUrl: string + width: number + height: number +} + +/** The full payload extracted from a browser grab selection. */ +export type BrowserGrabPayload = { + page: BrowserGrabPageContext + target: BrowserGrabTarget + nearbyText: string[] + ancestorPath: string[] + screenshot: BrowserGrabScreenshot | null +} + +// --------------------------------------------------------------------------- +// Grab operation lifecycle +// --------------------------------------------------------------------------- + +/** Why a grab operation was cancelled before the user selected an element. */ +export type BrowserGrabCancelReason = 'user' | 'tab-inactive' | 'navigation' | 'evicted' | 'timeout' + +/** Discriminated union for the result of a single grab operation. */ +export type BrowserGrabResult = + | { opId: string; kind: 'selected'; payload: BrowserGrabPayload } + | { opId: string; kind: 'cancelled'; reason: BrowserGrabCancelReason } + | { opId: string; kind: 'error'; reason: string } + +// --------------------------------------------------------------------------- +// IPC argument and result types +// --------------------------------------------------------------------------- + +export type BrowserSetGrabModeArgs = { + browserTabId: string + enabled: boolean +} + +/** Why a grab IPC call was rejected before the operation could start. */ +export type BrowserGrabRejectReason = 'not-ready' | 'not-authorized' | 'already-active' + +export type BrowserSetGrabModeResult = { ok: true } | { ok: false; reason: BrowserGrabRejectReason } + +export type BrowserAwaitGrabSelectionArgs = { + browserTabId: string + opId: string +} + +export type BrowserCancelGrabArgs = { + browserTabId: string +} + +export type BrowserCaptureSelectionScreenshotArgs = { + browserTabId: string + rect: BrowserGrabRect +} + +export type BrowserCaptureSelectionScreenshotResult = + | { ok: true; screenshot: BrowserGrabScreenshot } + | { ok: false; reason: string } + +export type BrowserExtractHoverArgs = { + browserTabId: string +} + +export type BrowserExtractHoverResult = + | { ok: true; payload: BrowserGrabPayload } + | { ok: false; reason: string } + +// --------------------------------------------------------------------------- +// Payload budgets — enforced in both guest and main +// --------------------------------------------------------------------------- + +export const GRAB_BUDGET = { + textSnippetMaxLength: 200, + nearbyTextEntryMaxLength: 200, + nearbyTextMaxEntries: 10, + htmlSnippetMaxLength: 4096, + ancestorPathMaxEntries: 10, + /** Hard byte budget for screenshot PNG data URL before we omit the screenshot. */ + screenshotMaxBytes: 2 * 1024 * 1024 +} as const + +// --------------------------------------------------------------------------- +// Attribute allowlist for safe preview +// --------------------------------------------------------------------------- + +/** Only these attribute names are included in the payload by default. */ +export const GRAB_SAFE_ATTRIBUTE_NAMES = new Set([ + 'id', + 'class', + 'name', + 'type', + 'role', + 'href', + 'src', + 'alt', + 'title', + 'placeholder', + 'for', + 'action', + 'method' +]) + +/** Attribute names matching aria-* are always included. */ +export function isAriaAttribute(name: string): boolean { + return name.startsWith('aria-') +} + +/** + * Patterns in attribute values that indicate secrets — these values get + * redacted. Why tighter patterns than broad words like 'code' or 'state': + * those match normal CSS class names (e.g. 'source-code', 'stateful') and + * would visibly degrade extraction quality on most real-world sites. The + * intent is to catch OAuth callback params and credential-like values. + */ +export const GRAB_SECRET_PATTERNS = [ + 'access_token', + 'auth_token', + 'api_key', + 'apikey', + 'client_secret', + 'oauth_state', + 'x-amz-', + 'session_id', + 'sessionid', + 'csrf', + 'secret', + 'password', + 'passwd' +] + +/** Computed style properties to extract — matches BrowserGrabComputedStyles keys. */ +export const GRAB_STYLE_PROPERTIES: readonly (keyof BrowserGrabComputedStyles)[] = [ + 'display', + 'position', + 'width', + 'height', + 'margin', + 'padding', + 'color', + 'backgroundColor', + 'border', + 'borderRadius', + 'fontFamily', + 'fontSize', + 'fontWeight', + 'lineHeight', + 'textAlign', + 'zIndex' +]