From e6c031a537a5b6189eb9154e71ba9f981ee8d608 Mon Sep 17 00:00:00 2001 From: Kazoku Date: Sun, 13 Sep 2026 03:55:59 +0700 Subject: [PATCH 01/26] refactor(addon): use exact frame bridge endpoints --- addon/js/background/content-ports.js | 17 +- addon/js/background/index.js | 8 - addon/js/background/messages.js | 470 ++++++++++++------ addon/js/background/nm.js | 91 +++- addon/js/background/state.js | 7 +- addon/js/background/state_ops.js | 78 ++- .../js/content/isolated/bootstrap-lifetime.js | 202 -------- addon/js/content/isolated/bridge.js | 376 ++++++-------- addon/js/content/main/index.js | 90 ++-- addon/manifest.chromium.json | 3 +- addon/manifest.json | 20 +- addon/manifest.v2.json | 4 +- tests/e2e/nm-runtime-port.spec.ts | 19 +- tests/unit/bootstrap-lifetime.test.js | 397 --------------- tests/unit/frame-endpoint-topology.test.js | 44 ++ tests/unit/state-ops.test.js | 37 +- 16 files changed, 725 insertions(+), 1138 deletions(-) delete mode 100644 addon/js/content/isolated/bootstrap-lifetime.js delete mode 100644 tests/unit/bootstrap-lifetime.test.js create mode 100644 tests/unit/frame-endpoint-topology.test.js diff --git a/addon/js/background/content-ports.js b/addon/js/background/content-ports.js index 9746170..ae9233a 100644 --- a/addon/js/background/content-ports.js +++ b/addon/js/background/content-ports.js @@ -28,6 +28,19 @@ } return reached } - - webhid.export('content-ports', { registerContentPort, postToContentPorts }) + /** + * Sends one message to a registered exact endpoint. + * @param {object} port + * @param {object} message + * @returns {void} + */ + function postToContentPort(port, message) { + if (!ports.has(port)) return + try { + port.postMessage(message) + } catch { + ports.delete(port) + } + } + webhid.export('content-ports', { registerContentPort, postToContentPorts, postToContentPort }) })() diff --git a/addon/js/background/index.js b/addon/js/background/index.js index 6742cf7..aedb1e5 100644 --- a/addon/js/background/index.js +++ b/addon/js/background/index.js @@ -262,14 +262,6 @@ else shadowArms.set(key, { count: existing.count - 1, at: existing.at }) }) - /** - * Hides page actions from every open tab. - * @returns {void} - */ - function hidePageActions() { - pageActionVisibility.setHidden(true).catch((e) => logger.debug('pageAction.hide failed', e)) - } - browser.storage.onChanged.addListener((changes, area) => { if (area !== 'local') return let hasSiteChange = false diff --git a/addon/js/background/messages.js b/addon/js/background/messages.js index c245e64..fae4f18 100644 --- a/addon/js/background/messages.js +++ b/addon/js/background/messages.js @@ -1,16 +1,16 @@ ;(function () { const webhid = globalThis.webhid - const { registerContentPort } = webhid.import('content-ports') + const { registerContentPort, postToContentPort } = webhid.import('content-ports') const http = webhid.import('http') const logger = webhid.import('logger') const isChromium = webhid.import('isChromium') - const globalSettingKey = webhid.import('globalSettingKey') const decodeDeviceCollections = webhid.import('decodeDeviceCollections') const { deviceCache, pendingPicker, permissionsPolicy, frameDelegations, + frameEndpoints, pageActionVisibility } = webhid.import('bgState') const { @@ -35,8 +35,6 @@ registerFrameLifetime, isFrameLifetimeActive, purgeFrame, - purgeBridge, - forTabsOfOrigin, collectDeviceSessionsForOrigin, getDeviceSessionOwner, closeForCleanup @@ -52,6 +50,111 @@ /** @type {object|null} */ let actionApi = null + let nextEndpointId = 0 + /** + * Registers one browser-owned exact frame endpoint. + * @param {object} port + * @returns {object|null} + */ + function registerFrameEndpoint(port) { + const sender = port.sender || {} + const tabId = sender.tab?.id + const frameId = Number.isInteger(sender.frameId) ? sender.frameId : null + const documentId = + typeof sender.documentId === 'string' && sender.documentId ? sender.documentId : null + const origin = urlOrigin(sender.url || '') + if (tabId == null || frameId == null || !origin) return null + const endpoint = { + id: 'endpoint-' + ++nextEndpointId, + port, + tabId, + frameId, + documentId, + origin, + url: sender.url, + frameKey: 'endpoint-' + nextEndpointId + } + frameEndpoints.set(port, endpoint) + if (!registerFrameLifetime(tabId, endpoint.frameKey)) { + frameEndpoints.delete(port) + return null + } + return endpoint + } + /** + * @param {object} port + * @returns {object|null} + */ + function endpointForPort(port) { + return (port && frameEndpoints.get(port)) || null + } + /** + * @param {object} sender + * @param {object} port + * @returns {object|null} + */ + function endpointForRequest(sender, port) { + return endpointForPort(port) + } + const delegationPending = new Map() + let nextDelegationId = 0 + /** + * Resolves the parent endpoint for an exact child document. + * @param {object} endpoint + * @returns {object|null} + */ + function parentEndpointFor(endpoint) { + const entry = policyEntryForDocument( + endpoint.tabId, + endpoint.frameId, + endpoint.documentId, + endpoint.origin + ) + const parentFrameId = entry && entry.parentFrameId >= 0 ? entry.parentFrameId : 0 + const parentDocumentId = entry && entry.parentDocumentId + if (endpoint.frameId === 0) return null + for (const candidate of frameEndpoints.values()) { + if ( + candidate.tabId === endpoint.tabId && + candidate.frameId === parentFrameId && + (!parentDocumentId || candidate.documentId === parentDocumentId) && + candidate.documentId && + candidate.port !== endpoint.port + ) + return candidate + } + return null + } + /** + * Queries the exact parent endpoint for iframe delegation. + * @param {object} endpoint + * @returns {Promise} + */ + function queryFrameDelegation(endpoint) { + const parent = parentEndpointFor(endpoint) + if (!parent) return Promise.resolve(false) + const requestId = 'delegation:' + ++nextDelegationId + return new Promise((resolve) => { + delegationPending.set(requestId, { endpoint, parent, resolve }) + postToContentPort(parent.port, { + action: 'frameDelegationQuery', + requestId, + childFrameId: endpoint.frameId, + childDocumentId: endpoint.documentId + }) + }) + } + /** + * Sends an origin-scoped event to every registered exact frame endpoint. + * @param {string} origin + * @param {object} message + * @returns {void} + */ + function postToOriginEndpoints(origin, message) { + for (const endpoint of frameEndpoints.values()) { + if (endpoint.origin === origin) postToContentPort(endpoint.port, message) + } + } /** * Replaces the in-memory device cache with `devices` (decoded), persisting * them afterwards. @@ -71,11 +174,7 @@ * @returns {Promise} */ async function notifyAllowedDevicesChanged(origin, deviceIds) { - await forTabsOfOrigin(null, (tab) => - browser.tabs - .sendMessage(tab.id, { action: 'allowedDevicesChanged', origin, deviceIds }) - .catch(() => {}) - ) + postToOriginEndpoints(origin, { action: 'allowedDevicesChanged', origin, deviceIds }) } /** @@ -101,19 +200,13 @@ } await deleteGrantGroups(memberGroups.map((g) => g.id)) const deviceIds = await getAllowedDevices(origin) - await forTabsOfOrigin(null, (tab) => { - for (const deviceId of toRevoke) { - browser.tabs - .sendMessage(tab.id, { - action: 'webhidDeviceEvent', - event: { eventType: 'revoked', deviceId, origin } - }) - .catch(() => {}) - } - browser.tabs - .sendMessage(tab.id, { action: 'allowedDevicesChanged', origin, deviceIds }) - .catch(() => {}) - }) + for (const deviceId of toRevoke) { + postToOriginEndpoints(origin, { + action: 'webhidDeviceEvent', + event: { eventType: 'revoked', deviceId, origin } + }) + } + postToOriginEndpoints(origin, { action: 'allowedDevicesChanged', origin, deviceIds }) } /** @@ -284,20 +377,21 @@ * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse + * @param {object} port * @returns {boolean} */ - function handleOpen(request, sender, sendResponse) { - const tabId = sender.tab != null ? sender.tab.id : undefined - const ownerFrameKey = request.frameKey || 'tab:' + tabId - if (tabId == null) { + function handleOpen(request, sender, sendResponse, port) { + const endpoint = endpointForRequest(sender, port) + if (!endpoint) { sendResponse({ s: 403 }) return true } - if (!registerFrameLifetime(tabId, ownerFrameKey)) { + const { tabId, origin, frameKey } = endpoint + if (!isFrameLifetimeActive(tabId, frameKey)) { sendResponse({ s: 503 }) return true } - getAllowedDevices(request.origin) + getAllowedDevices(origin) .then((deviceIds) => { if (!deviceIds.includes(request.deviceId)) { sendResponse({ s: 403 }) @@ -307,21 +401,13 @@ .then(async (response) => { if (typeof response.P === 'number') lastHidPermission = response.P if (http.isOk(response.s) && response.i) { - const stillAllowed = (await getAllowedDevices(request.origin)).includes( - request.deviceId - ) - const ownerStillAlive = isFrameLifetimeActive(tabId, ownerFrameKey) + const stillAllowed = (await getAllowedDevices(origin)).includes(request.deviceId) + const ownerStillAlive = isFrameLifetimeActive(tabId, frameKey) if (!stillAllowed || !ownerStillAlive) { - logger.warn( - 'open for device', - request.deviceId, - !stillAllowed ? 'revoked while in flight' : 'owner died while in flight' - ) - if (response.t) { + if (response.t) await closeForCleanup(response.i, response.t, (id, token) => NativeMessaging.closeDevice(id, token) ) - } sendResponse({ s: ownerStillAlive ? 403 : 503 }) return } @@ -329,18 +415,19 @@ if (response.t) { sessionRegistered = registerDeviceSession(response.i, response.t, { tabId, - origin: request.origin, - frameKey: ownerFrameKey, - bridgeInstanceId: request.bridgeInstanceId, + frameId: endpoint.frameId, + documentId: endpoint.documentId, + origin, + frameKey, + port, clientKey: request.clientKey }) } if (!sessionRegistered) { - if (response.t) { + if (response.t) await closeForCleanup(response.i, response.t, (id, token) => NativeMessaging.closeDevice(id, token) ) - } sendResponse({ s: 503 }) return } @@ -368,12 +455,13 @@ * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse + * @param {object} port * @returns {boolean} */ - function handleClose(request, sender, sendResponse) { - const tabId = sender.tab != null ? sender.tab.id : undefined - const frame = request.frameKey || 'tab:' + tabId - if (!isTabAuthorizedForDevice(tabId, request.deviceId)) { + function handleClose(request, sender, sendResponse, port) { + const endpoint = endpointForRequest(sender, port) + const tabId = endpoint?.tabId + if (!endpoint || !isTabAuthorizedForDevice(tabId, request.deviceId)) { sendResponse({ s: 403 }) return true } @@ -382,10 +470,11 @@ !isSessionOwnedBy( request.deviceId, request.T, - request.origin, - tabId, - frame, - request.clientKey + endpoint.origin, + endpoint.tabId, + endpoint.frameKey, + request.clientKey, + port ) ) { sendResponse({ s: 403 }) @@ -404,29 +493,22 @@ } /** - * Closes all sessions owned by one bridge document lifetime. + * Closes all sessions owned by one exact bridge endpoint. * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse + * @param {object} port * @returns {boolean} */ - async function handleFrameDestroyed(request, sender, sendResponse) { - const tabId = sender.tab != null ? sender.tab.id : undefined - await purgeFrame(tabId, request.frameKey, (deviceId, token) => - NativeMessaging.closeDevice(deviceId, token) - ) - const frameId = - Number.isInteger(request.frameId) && request.frameId >= 0 ? request.frameId : sender.frameId - const documentId = - typeof request.documentId === 'string' && request.documentId - ? request.documentId - : frameId === sender.frameId - ? sender.documentId - : null - if (tabId != null && Number.isInteger(frameId) && documentId) { - const key = documentFrameKey(tabId, frameId, documentId) - frameDelegations.delete(key) - permissionsPolicy.delete(key) + async function handleFrameDestroyed(request, sender, sendResponse, port) { + const endpoint = endpointForRequest(sender, port) + if (endpoint) { + await purgeFrame(endpoint.tabId, endpoint.frameKey, (deviceId, token) => + NativeMessaging.closeDevice(deviceId, token) + ) + const exactKey = documentFrameKey(endpoint.tabId, endpoint.frameId, endpoint.documentId) + frameDelegations.delete(exactKey) + permissionsPolicy.delete(exactKey) } sendResponse({ s: 204 }) return true @@ -484,29 +566,29 @@ * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse + * @param {object} port * @returns {boolean} */ - function handleSetDataPlane(request, sender, sendResponse) { - if (!tabAllowsDevice(sender, request.deviceId)) { + function handleSetDataPlane(request, sender, sendResponse, port) { + const endpoint = endpointForRequest(sender, port) + if (!endpoint || !tabAllowsDevice(sender, request.deviceId)) { sendResponse({ s: 403 }) return true } - if (request.sessionToken) { - const tabId = sender.tab != null ? sender.tab.id : undefined - const frame = request.frameKey || 'tab:' + tabId - if ( - !isSessionOwnedBy( - request.deviceId, - request.sessionToken, - request.origin, - tabId, - frame, - request.clientKey - ) - ) { - sendResponse({ s: 403 }) - return true - } + if ( + request.sessionToken && + !isSessionOwnedBy( + request.deviceId, + request.sessionToken, + endpoint.origin, + endpoint.tabId, + endpoint.frameKey, + request.clientKey, + port + ) + ) { + sendResponse({ s: 403 }) + return true } NativeMessaging.sendRequest({ a: bgPacked.ACT.sdp, @@ -761,7 +843,11 @@ sendResponse(null) return false } - const origin = urlOrigin(request.origin || (sender.tab && sender.tab.url) || '') + const origin = urlOrigin(sender.url || '') + if (!origin) { + sendResponse(null) + return false + } const key = `csp:${frameKey(tabId, sender.frameId ?? 0, origin)}` browser.storage.session .get(key) @@ -784,11 +870,18 @@ sendResponse({ origins: [] }) return false } - browser.tabs - .sendMessage(tabId, { action: 'getFrameOrigins' }) - .then((r) => sendResponse({ origins: (r && r.origins) || [] })) - .catch(() => sendResponse({ origins: [] })) - return true + const origins = [] + const seen = new Set() + const endpoints = [...frameEndpoints.values()] + .filter((endpoint) => endpoint.tabId === tabId) + .sort((a, b) => a.frameId - b.frameId) + for (const endpoint of endpoints) { + if (seen.has(endpoint.origin)) continue + seen.add(endpoint.origin) + origins.push(endpoint.origin) + } + sendResponse({ origins }) + return false } /** @@ -911,28 +1004,73 @@ * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse + * @param {object} port * @returns {boolean} */ - function handleShowPicker(request, sender, sendResponse) { - const tabId = sender.tab != null ? sender.tab.id : undefined - if (tabId == null) { - sendResponse({ error: 'no tab' }) + function handleShowPicker(request, sender, sendResponse, port) { + const endpoint = endpointForRequest(sender, port) + const tabId = endpoint?.tabId + if (!endpoint) { + sendResponse({ error: 'no frame endpoint' }) return false } const req = { requestId: request.requestId, tabId, + port, filters: request.filters || [], exclusionFilters: request.exclusionFilters || [], - origin: request.origin, + origin: endpoint.origin, mode: request.mode || 'pageAction' } - pendingPicker.set(tabId, req) - if (req.mode === 'window') { - openPickerWindow() + if (req.mode === 'modal') { + const top = [...frameEndpoints.values()].find( + (candidate) => candidate.tabId === tabId && candidate.frameId === 0 + ) + if (!top) { + sendResponse({ error: 'top frame endpoint unavailable' }) + return false + } + req.uiPort = top.port + pendingPicker.set(tabId, req) + postToContentPort(top.port, { + action: 'showInlinePicker', + requestId: req.requestId, + filters: req.filters, + exclusionFilters: req.exclusionFilters + }) } else { - openPickerPageAction(tabId, request.origin) + pendingPicker.set(tabId, req) + if (req.mode === 'window') openPickerWindow() + else openPickerPageAction(tabId, endpoint.origin) + } + sendResponse({ ok: true }) + return false + } + + /** + * Accepts a picker result from the registered top-frame UI host. + * @param {object} request + * @param {object} sender + * @param {function(*): void} sendResponse + * @param {object} port + * @returns {boolean} + */ + function handleInlinePickerResult(request, sender, sendResponse, port) { + const req = [...pendingPicker.values()].find( + (candidate) => candidate.requestId === request.requestId + ) + if (!req || req.uiPort !== port) { + sendResponse({ ok: false }) + return false } + pendingPicker.delete(req.tabId) + postToContentPort(req.port, { + action: 'pickerResult', + requestId: req.requestId, + selected: request.selected === true, + devices: request.selected === true ? request.devices : null + }) sendResponse({ ok: true }) return false } @@ -979,17 +1117,9 @@ */ function policyForRequest(request, sender) { const tabId = sender.tab?.id - const frameId = - Number.isInteger(request.frameId) && request.frameId >= 0 - ? request.frameId - : sender.frameId - const documentId = - typeof request.documentId === 'string' && request.documentId - ? request.documentId - : frameId === sender.frameId - ? sender.documentId - : null - const requestedOrigin = urlOrigin(request.origin || '') + const frameId = Number.isInteger(sender.frameId) ? sender.frameId : null + const documentId = typeof sender.documentId === 'string' ? sender.documentId : null + const requestedOrigin = urlOrigin(sender.url || '') if (tabId == null || frameId == null || !documentId || !requestedOrigin) { return { policy: { hid: 'none' } } } @@ -1016,14 +1146,35 @@ * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse + * @param {object} port * @returns {boolean} */ - function handleGetPolicy(request, sender, sendResponse) { + async function handleGetPolicy(request, sender, sendResponse, port) { + const endpoint = endpointForRequest(sender, port) + if (endpoint) { + const key = documentFrameKey(endpoint.tabId, endpoint.frameId, endpoint.documentId) + const entry = policyEntryForDocument( + endpoint.tabId, + endpoint.frameId, + endpoint.documentId, + endpoint.origin + ) + if ( + entry && + endpoint.frameId !== 0 && + entry.parentFrameId >= 0 && + entry.parentKey && + permissionsPolicy.get(entry.parentKey)?.origin !== entry.origin + ) { + const delegated = await queryFrameDelegation(endpoint) + frameDelegations.set(key, delegated) + } + } sendResponse(policyForRequest(request, sender)) return false } /** - * Records exact iframe delegation observed by the top isolated bridge. + * Records delegation for this browser-authenticated frame document. * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse @@ -1031,26 +1182,10 @@ */ function handleSetFrameDelegation(request, sender, sendResponse) { const tabId = sender.tab?.id - const frameId = - Number.isInteger(request.frameId) && request.frameId >= 0 - ? request.frameId - : sender.frameId - const documentId = - typeof request.documentId === 'string' && request.documentId - ? request.documentId - : frameId === sender.frameId - ? sender.documentId - : null - const origin = urlOrigin(request.origin || '') - if ( - typeof request.bridgeInstanceId !== 'string' || - tabId == null || - !Number.isInteger(frameId) || - frameId < 0 || - typeof documentId !== 'string' || - !documentId || - !origin - ) { + const frameId = Number.isInteger(sender.frameId) ? sender.frameId : null + const documentId = typeof sender.documentId === 'string' ? sender.documentId : null + const origin = urlOrigin(sender.url || '') + if (tabId == null || frameId == null || !documentId || !origin) { sendResponse({ ok: false }) return false } @@ -1064,7 +1199,6 @@ sendResponse({ ok: true }) return false } - /** * Arms the shadow-URL interception for the next worker script request from * the given tab+document, so the polyfill's own data-worker spawn is @@ -1123,15 +1257,14 @@ if (browser.notifications) browser.notifications.clear('webhid-picker').catch(() => {}) } if (request.windowId != null) browser.windows.remove(request.windowId).catch(() => {}) - if (tabId != null) - browser.tabs - .sendMessage(tabId, { - action: 'pickerResult', - requestId, - selected, - devices: selected ? devices : null - }) - .catch(() => {}) + if (req?.port) { + postToContentPort(req.port, { + action: 'pickerResult', + requestId, + selected, + devices: selected ? devices : null + }) + } sendResponse({ ok: true }) return false } @@ -1173,7 +1306,8 @@ getPolicy: handleGetPolicy, armShadowSpawn: handleArmShadowSpawn, unarmShadowSpawn: handleUnarmShadowSpawn, - pickerResult: handlePickerResult + pickerResult: handlePickerResult, + inlinePickerResult: handleInlinePickerResult } /** @@ -1190,15 +1324,16 @@ }) browser.runtime.onConnect.addListener((port) => { registerContentPort(port) - let bridgeInstanceId = null + const endpoint = port.name === 'webhid-control' ? registerFrameEndpoint(port) : null port.onMessage.addListener((request) => { + if (request.action === 'frameDelegationResult') { + const pending = delegationPending.get(request.requestId) + if (!pending || pending.parent.port !== port) return + delegationPending.delete(request.requestId) + pending.resolve(request.delegated === true) + return + } const handler = HANDLERS[request.action] - if ( - port.name === 'webhid-control' && - bridgeInstanceId === null && - typeof request.bridgeInstanceId === 'string' - ) - bridgeInstanceId = request.bridgeInstanceId if (!handler) return let responded = false const sendPortResponse = (response) => { @@ -1206,10 +1341,14 @@ responded = true const responseMessage = { ...(response || {}) } if (request.reqId != null) responseMessage.reqId = request.reqId - port.postMessage(responseMessage) + try { + port.postMessage(responseMessage) + } catch { + void 0 + } } try { - const result = handler(request, port.sender, sendPortResponse) + const result = handler(request, port.sender, sendPortResponse, port) if (result && typeof result.then === 'function') { result.catch(() => sendPortResponse({ s: 500 })) } else if (result !== true && !responded) { @@ -1219,13 +1358,22 @@ sendPortResponse({ s: 500 }) } }) - if (port.name === 'webhid-control') { + if (endpoint) { port.onDisconnect.addListener(() => { - const tabId = port.sender && port.sender.tab ? port.sender.tab.id : undefined - if (!bridgeInstanceId || tabId == null) return - purgeBridge(tabId, bridgeInstanceId, (deviceId, token) => + if (frameEndpoints.get(port) !== endpoint) return + frameEndpoints.delete(port) + for (const [tabId, request] of pendingPicker) { + if (request.port !== port && request.uiPort !== port) continue + pendingPicker.delete(tabId) + } + for (const [requestId, pending] of delegationPending) { + if (pending.endpoint !== endpoint && pending.parent !== endpoint) continue + delegationPending.delete(requestId) + pending.resolve(false) + } + purgeFrame(endpoint.tabId, endpoint.frameKey, (deviceId, token) => NativeMessaging.closeDevice(deviceId, token) - ).catch((e) => logger.debug('bridge session cleanup failed', e)) + ).catch((e) => logger.debug('frame endpoint cleanup failed', e)) }) } }) diff --git a/addon/js/background/nm.js b/addon/js/background/nm.js index ba3c30f..7362fb7 100644 --- a/addon/js/background/nm.js +++ b/addon/js/background/nm.js @@ -14,16 +14,28 @@ const { saveDeviceInfo } = webhid.import('bgStorage') const { tabsForEvent, + collectDeviceSessionOwners, broadcastGlobalReset, clearAuthorityOwnership, clearDeviceOwnership, forTabsOfOrigin } = webhid.import('bgStateOps') const http = webhid.import('http') - const { postToContentPorts } = webhid.import('content-ports') - + const { postToContentPorts, postToContentPort } = webhid.import('content-ports') const NM_HOST_FORWARDER = 'webhid.forwarder_nm_host' const NM_HOST_DAEMON = 'webhid.daemon_nm_host' + /** + * Sends one authority reset to every exact frame endpoint. + * @returns {void} + */ + function broadcastExactGlobalReset() { + const message = { action: 'globalReset' } + const reached = postToContentPorts(null, message, 'webhid-control') + forTabsOfOrigin(null, (tab) => { + if (reached.has(tab.id)) return + return browser.tabs.sendMessage(tab.id, message).catch(() => {}) + }).catch((e) => logger.debug('broadcastGlobalReset failed', e)) + } const NativeMessaging = { port: null, @@ -147,7 +159,6 @@ }, /** - * Retires one exact Native Messaging port and its authority lifetime. * @param {object} port * @returns {boolean} */ @@ -157,7 +168,7 @@ for (const [, p] of this.pending) p.resolve({ s: 503 }) this.pending.clear() clearAuthorityOwnership() - broadcastGlobalReset() + broadcastGlobalReset(broadcastExactGlobalReset) return true }, @@ -297,8 +308,12 @@ try { if (bin.length < 8 || bin[0] !== PKG_INPUT_REPORT) return const deviceId = (bin[1] | (bin[2] << 8) | (bin[3] << 16) | (bin[4] << 24)) >>> 0 - const targets = tabsForEvent({ i: deviceId }) - if (!targets) return + const targets = new Set( + collectDeviceSessionOwners(deviceId) + .map((owner) => owner.port) + .filter((port) => port != null) + ) + if (targets.size === 0) return let offset = 5 while (offset + 3 <= bin.length) { const reportId = bin[offset] @@ -314,13 +329,12 @@ reportId, data: payload } - const message = { action: 'webhidDeviceEvent', event } - const reached = postToContentPorts(targets, message, `webhid-data:${deviceId}`) - for (const tabId of targets) { - if (reached.has(tabId)) continue - browser.tabs - .sendMessage(tabId, message) - .catch((e) => logger.debug('event forward to target tab failed', e)) + for (const port of targets) { + const copy = payloadLen > 0 ? new Uint8Array(payload) : payload + postToContentPort(port, { + action: 'webhidDeviceEvent', + event: { ...event, data: copy } + }) } } } catch (e) { @@ -347,20 +361,36 @@ }) .catch((e) => logger.debug('enumerateDevices failed', e)) } - if (message.e === EVT_DISCONNECT) clearDeviceOwnership(message.i) const normalized = { eventType: message.e === EVT_CONNECT ? 'connect' : 'disconnect', deviceId: message.i, device: message.v || null } + const owners = + message.e === EVT_DISCONNECT + ? new Set( + collectDeviceSessionOwners(message.i) + .map((owner) => owner.port) + .filter((port) => port != null) + ) + : null + if (message.e === EVT_DISCONNECT) clearDeviceOwnership(message.i) browser.runtime .sendMessage({ action: 'webhidDeviceEvent', event: normalized }) .catch((e) => logger.debug('event forward to runtime failed', e)) - forTabsOfOrigin(null, (tab) => - browser.tabs - .sendMessage(tab.id, { action: 'webhidDeviceEvent', event: normalized }) - .catch((e) => logger.debug('event forward to all tabs failed', e)) - ).catch((e) => logger.debug('tabs.query failed', e)) + if (owners && owners.size > 0) { + const eventMessage = { action: 'webhidDeviceEvent', event: normalized } + for (const port of owners) postToContentPort(port, eventMessage) + } else { + forTabsOfOrigin(null, (tab) => { + const eventMessage = { action: 'webhidDeviceEvent', event: normalized } + const reached = postToContentPorts([tab.id], eventMessage, 'webhid-control') + if (reached.has(tab.id)) return + return browser.tabs + .sendMessage(tab.id, eventMessage) + .catch((e) => logger.debug('event forward to all tabs failed', e)) + }).catch((e) => logger.debug('tabs.query failed', e)) + } }, onControlEvent(message) { @@ -369,13 +399,24 @@ this.handleDeviceConnectionEvent(message) return } + const owners = new Set( + collectDeviceSessionOwners(message.i) + .map((owner) => owner.port) + .filter((port) => port != null) + ) + const eventMessage = { action: 'webhidDeviceEvent', event: message } + if (owners.size > 0) { + for (const port of owners) postToContentPort(port, eventMessage) + return + } const targets = tabsForEvent(message) - if (targets) { - for (const tabId of targets) { - browser.tabs - .sendMessage(tabId, { action: 'webhidDeviceEvent', event: message }) - .catch((e) => logger.debug('event forward to target tab failed', e)) - } + if (!targets) return + const reached = postToContentPorts(targets, eventMessage, 'webhid-control') + for (const tabId of targets) { + if (reached.has(tabId)) continue + browser.tabs + .sendMessage(tabId, eventMessage) + .catch((e) => logger.debug('event forward to target tab failed', e)) } } } diff --git a/addon/js/background/state.js b/addon/js/background/state.js index 3894285..c7a1ebe 100644 --- a/addon/js/background/state.js +++ b/addon/js/background/state.js @@ -13,6 +13,8 @@ const permissionsPolicy = new Map() const frameDelegations = new Map() const pendingPicker = new Map() + /** @type {Map} */ + const frameEndpoints = new Map() const workerPolyfillSites = new Set() const shadowArms = new Map() const pageActionVisibility = { @@ -38,7 +40,9 @@ const visible = pageActionDesired(tabId) try { await browser.pageAction[visible ? 'show' : 'hide'](tabId) - } catch {} + } catch { + void 0 + } if (pageActionDesired(tabId) === visible) return } }) @@ -79,6 +83,7 @@ orphanCleanup, permissionsPolicy, frameDelegations, + frameEndpoints, pageActionVisibility, pendingPicker, workerPolyfillSites, diff --git a/addon/js/background/state_ops.js b/addon/js/background/state_ops.js index 5871ae4..5df6f25 100644 --- a/addon/js/background/state_ops.js +++ b/addon/js/background/state_ops.js @@ -131,17 +131,19 @@ } /** - * Records one daemon session token with its owner. - * `deviceSessions` is `deviceId -> Map` . + * Records one daemon session token with its browser-owned endpoint. * @param {number} deviceId * @param {string} token - * @param {{tabId: number, origin: string, frameKey?: string, bridgeInstanceId?: string, clientKey?: string}} owner + * @param {{tabId: number, origin: string, frameKey?: string, clientKey?: string, frameId?: number, documentId?: string, port?: object}} owner * @returns {boolean} */ function registerDeviceSession(deviceId, token, owner) { if (!deviceId || !token || !owner || owner.tabId == null || !owner.origin) return false const frameKey = owner.frameKey || 'tab:' + owner.tabId - if (!isFrameLifetimeActive(owner.tabId, frameKey) && !registerFrameLifetime(owner.tabId, frameKey)) { + if ( + !isFrameLifetimeActive(owner.tabId, frameKey) && + !registerFrameLifetime(owner.tabId, frameKey) + ) { return false } let byToken = deviceSessions.get(deviceId) @@ -151,10 +153,12 @@ } byToken.set(token, { tabId: owner.tabId, + frameId: owner.frameId, + documentId: owner.documentId || null, origin: owner.origin, frameKey, - bridgeInstanceId: owner.bridgeInstanceId || '', - clientKey: owner.clientKey || '' + clientKey: owner.clientKey || '', + port: owner.port || null }) logger.debug('register session device ' + deviceId + ' tab ' + owner.tabId) return true @@ -174,6 +178,16 @@ if (byToken.size === 0) deviceSessions.delete(deviceId) } + /** + * Returns browser-owned endpoints for every live session of a device. + * @param {number} deviceId + * @returns {object[]} + */ + function collectDeviceSessionOwners(deviceId) { + const byToken = deviceSessions.get(deviceId) + if (!byToken) return [] + return [...byToken.values()] + } /** * Collects session tokens for a device owned by `origin` (revocation). * @param {number} deviceId @@ -327,20 +341,18 @@ return !!tabs && (tabs.get(tabId) || 0) > 0 } - /** - * Whether `token` is the exact daemon session opened by `origin`, frame, - * and (when given) tab. Principal-aware checks use this so a sibling frame - * or origin can never operate on someone else's session. + * Whether `token` is the exact daemon session opened by its endpoint. * @param {number} deviceId * @param {string} token * @param {string} origin * @param {number} [tabId] * @param {string} [frameKey] * @param {string} [clientKey] + * @param {object} [port] * @returns {boolean} */ - function isSessionOwnedBy(deviceId, token, origin, tabId, frameKey, clientKey) { + function isSessionOwnedBy(deviceId, token, origin, tabId, frameKey, clientKey, port) { const byToken = deviceSessions.get(deviceId) if (!byToken) return false const owner = byToken.get(token) @@ -349,6 +361,7 @@ if (tabId != null && owner.tabId !== tabId) return false if (frameKey != null && owner.frameKey !== frameKey) return false if (clientKey != null && owner.clientKey !== clientKey) return false + if (port != null && owner.port !== port) return false return true } @@ -375,38 +388,6 @@ } await Promise.all(pending) } - /** - * Retires all frame lifetimes and sessions owned by one bridge instance. - * @param {number} tabId - * @param {string} bridgeInstanceId - * @param {Function} closeDeviceFn - * @returns {Promise} - */ - async function purgeBridge(tabId, bridgeInstanceId, closeDeviceFn) { - if (tabId == null || !bridgeInstanceId) return - const frames = frameLifetimes.get(tabId) - const prefix = bridgeInstanceId + '/' - if (frames) { - for (const frameKey of frames.keys()) { - if (frameKey.startsWith(prefix)) frames.set(frameKey, 0) - } - } - const deviceIds = new Set([...deviceSessions.keys(), ...deviceTabMap.keys()]) - const pending = [] - for (const deviceId of deviceIds) { - const byToken = deviceSessions.get(deviceId) - if (byToken) { - for (const [token, owner] of byToken) { - if (owner.tabId !== tabId || owner.bridgeInstanceId !== bridgeInstanceId) continue - unregisterDeviceTab(deviceId, tabId) - pending.push(closeForCleanup(deviceId, token, closeDeviceFn)) - } - } - const tabs = deviceTabMap.get(deviceId) - if (tabs && tabs.size === 0) deviceTabMap.delete(deviceId) - } - await Promise.all(pending) - } /** * Moves a session whose daemon close failed into the orphan retry queue. @@ -487,10 +468,15 @@ } /** - * Sends a globalReset message to all tabs. + * Sends one authority reset through the exact endpoint route. + * @param {Function} [exactRoute] * @returns {void} */ - function broadcastGlobalReset() { + function broadcastGlobalReset(exactRoute) { + if (exactRoute) { + exactRoute() + return + } forTabsOfOrigin(null, (tab) => browser.tabs.sendMessage(tab.id, { action: 'globalReset' }).catch(() => {}) ).catch((e) => logger.debug('broadcastGlobalReset failed', e)) @@ -525,6 +511,7 @@ registerDeviceSession, unregisterDeviceSession, collectDeviceSessions, + collectDeviceSessionOwners, collectDeviceSessionsForOrigin, collectDeviceSessionsForTab, collectDeviceSessionsForFrame, @@ -542,7 +529,6 @@ isFrameLifetimeActive, retireFrameLifetime, purgeFrame, - purgeBridge, purgeTab, broadcastGlobalReset, clearAuthorityOwnership, diff --git a/addon/js/content/isolated/bootstrap-lifetime.js b/addon/js/content/isolated/bootstrap-lifetime.js deleted file mode 100644 index e4108be..0000000 --- a/addon/js/content/isolated/bootstrap-lifetime.js +++ /dev/null @@ -1,202 +0,0 @@ -;(function () { - 'use strict' - - /** - * Creates the one-time bootstrap gate for a bridge's document contexts. - * @param {object} deps - * @returns {(event: MessageEvent) => void} - */ - function createBootstrapGate(deps) { - const { - getReservation, - setReservation, - deleteReservation, - getContext, - getIdentity, - getCurrentIdentity, - hasLifetime, - sameLifetime, - accept, - accepted, - destroy, - reject, - createChallenge, - schedule, - cancel, - probeTimeoutMs - } = deps - - function closeCandidate(candidate) { - if (candidate.closed) return - candidate.closed = true - if (candidate.deadlineHandle != null) cancel(candidate.deadlineHandle) - candidate.deadlineHandle = null - candidate.port.onmessage = null - reject(candidate.port) - } - - function closeCandidates(transition) { - for (const candidate of transition.candidates) closeCandidate(candidate) - transition.candidates.length = 0 - } - - function failTransition(source, transition) { - if (transition.failed) return - transition.failed = true - closeCandidates(transition) - if (getReservation(source) === transition) deleteReservation(source) - } - - function tryPromote(source, transition) { - if (transition.failed || getReservation(source) !== transition) return - while (transition.candidates.length > 0) { - const head = transition.candidates[0] - if (head.expired) { - transition.candidates.shift() - closeCandidate(head) - continue - } - if (!head.live || !transition.cleanupComplete) return - const currentIdentity = getCurrentIdentity(source) - if (!hasLifetime(currentIdentity)) { - failTransition(source, transition) - return - } - if (!sameLifetime(transition.targetIdentity, currentIdentity)) { - closeCandidates(transition) - transition.targetIdentity = currentIdentity - return - } - if (!sameLifetime(head.identity, transition.targetIdentity)) { - transition.candidates.shift() - closeCandidate(head) - continue - } - transition.candidates.shift() - if (head.deadlineHandle != null) cancel(head.deadlineHandle) - head.deadlineHandle = null - head.port.onmessage = null - let acceptedContext = null - try { - acceptedContext = accept(head.port, source, head.origin, head.identity) - accepted(head.port) - for (const candidate of transition.candidates) closeCandidate(candidate) - transition.candidates.length = 0 - deleteReservation(source) - } catch { - if (acceptedContext) destroy(acceptedContext).catch(() => {}) - reject(head.port) - failTransition(source, transition) - } - return - } - } - - function addCandidate(source, transition, port, origin, identity) { - const candidate = { - sequence: transition.nextSequence++, - port, - origin, - identity, - challenge: createChallenge(), - live: false, - expired: false, - closed: false, - deadlineHandle: null - } - transition.candidates.push(candidate) - port.onmessage = (messageEvent) => { - const data = messageEvent.data - if ( - !candidate.expired && - data && - data.type === 'bootstrapProbeResponse' && - data.challenge === candidate.challenge - ) { - candidate.live = true - if (candidate.deadlineHandle != null) cancel(candidate.deadlineHandle) - candidate.deadlineHandle = null - tryPromote(source, transition) - } - } - if (typeof port.start === 'function') port.start() - candidate.deadlineHandle = schedule(() => { - if (candidate.expired || candidate.live || candidate.closed) return - candidate.expired = true - closeCandidate(candidate) - tryPromote(source, transition) - }, probeTimeoutMs) - try { - port.postMessage({ type: 'bootstrapProbe', challenge: candidate.challenge }) - } catch { - candidate.expired = true - closeCandidate(candidate) - tryPromote(source, transition) - } - } - - function startTransition(source, port, origin, identity, previous) { - const transition = { - previous, - targetIdentity: identity, - cleanupComplete: previous == null, - candidates: [], - nextSequence: 0, - failed: false - } - setReservation(source, transition) - addCandidate(source, transition, port, origin, identity) - if (!previous) return - destroy(previous).then( - () => { - if (getReservation(source) !== transition || transition.failed) return - transition.cleanupComplete = true - tryPromote(source, transition) - }, - () => failTransition(source, transition) - ) - } - - return (event) => { - const ports = event.ports != null ? Array.from(event.ports) : [] - if (event.data !== null || ports.length !== 1 || !event.source) { - for (const port of ports) reject(port) - return - } - const port = ports[0] - const source = event.source - const identity = getIdentity(source) - if (!hasLifetime(identity)) { - reject(port) - return - } - const transition = getReservation(source) - if (transition) { - if (sameLifetime(transition.targetIdentity, identity)) { - if (transition.candidates.some((candidate) => candidate.live)) { - reject(port) - return - } - addCandidate(source, transition, port, event.origin, identity) - return - } - closeCandidates(transition) - transition.targetIdentity = identity - addCandidate(source, transition, port, event.origin, identity) - return - } - const previous = getContext(source) - if (previous && sameLifetime(previous, identity)) { - reject(port) - return - } - if (previous && (!hasLifetime(previous) || !hasLifetime(identity))) { - reject(port) - return - } - startTransition(source, port, event.origin, identity, previous || null) - } - } - - webhid.export('createBootstrapGate', createBootstrapGate) -})() diff --git a/addon/js/content/isolated/bridge.js b/addon/js/content/isolated/bridge.js index d44d3c3..09ad7a9 100644 --- a/addon/js/content/isolated/bridge.js +++ b/addon/js/content/isolated/bridge.js @@ -11,23 +11,29 @@ const loadSiteSettings = webhid.import('loadSiteSettings') const parseSettingsKey = webhid.import('parseSettingsKey') const WebHidDevicePicker = webhid.import('WebHidDevicePicker') - const createBootstrapGate = webhid.import('createBootstrapGate') logger.initLogger('bridge') if (typeof pristine.host.cryptoRandomUUID !== 'function') throw new Error('WebHID bridge requires pristine crypto.randomUUID') - const bridgeInstanceId = 'bridge-' + pristine.host.cryptoRandomUUID() - const BOOTSTRAP_PROBE_TIMEOUT_MS = 1000 + const frameInstanceId = 'frame-' + pristine.host.cryptoRandomUUID() const controlPort = browser.runtime.connect({ name: 'webhid-control' }) + const pageChannel = new MessageChannel() + if (isChromium) window.postMessage(null, '*', [pageChannel.port2]) + else + window.wrappedJSObject.webhid = globalThis.cloneInto(pageChannel.port2, window, { + wrapReflectors: true + }) + const pagePort = pageChannel.port1 const controlQueue = [] let controlPending = null let nextHandshakeReqId = 0 const handshakePending = new Map() + const pickerResultHandlers = new Map() /** @returns {void} */ function pumpControlQueue() { if (controlPending || controlQueue.length === 0) return controlPending = controlQueue.shift() try { - controlPort.postMessage({ ...controlPending.request, bridgeInstanceId }) + controlPort.postMessage(controlPending.request) } catch (error) { controlPending.reject(error) controlPending = null @@ -54,7 +60,7 @@ const reqId = 'handshake:' + ++nextHandshakeReqId handshakePending.set(reqId, { resolve, reject }) try { - controlPort.postMessage({ action: 'handshake', reqId, bridgeInstanceId }) + controlPort.postMessage({ action: 'handshake', reqId }) } catch (error) { handshakePending.delete(reqId) reject(error) @@ -62,6 +68,34 @@ }) } controlPort.onMessage.addListener((message) => { + if (message && message.action === 'pickerResult') { + const handler = pickerResultHandlers.get(message.requestId) + if (handler) handler(message) + return + } + if (message && message.action === 'frameDelegationQuery') { + controlPort.postMessage({ + action: 'frameDelegationResult', + requestId: message.requestId, + delegated: frameDelegationForChild(message) + }) + return + } + if (message && message.action === 'showInlinePicker') { + if (!devicePicker) return + devicePicker + .show(message.filters || [], message.exclusionFilters || []) + .then((result) => + controlPort.postMessage({ + action: 'inlinePickerResult', + requestId: message.requestId, + selected: !!(result.devices && result.devices.length), + devices: result.devices || null + }) + ) + .catch((e) => logger.debug('inline picker failed', e)) + return + } if (message && message.action === 'globalReset') { handleGlobalReset() return @@ -104,8 +138,8 @@ controlQueue.length = 0 handleGlobalReset() }) - const devicePicker = new WebHidDevicePicker() - document.documentElement.appendChild(devicePicker.host) + const devicePicker = window === window.top ? new WebHidDevicePicker() : null + if (devicePicker) document.documentElement.appendChild(devicePicker.host) const PAGE_BLOCKED_ACTIONS = new Set([ 'pairDevice', @@ -147,44 +181,32 @@ } /** - * A trusted browser document lifetime owned by this tab bridge. + * The exact browser document represented by this bridge instance. * @typedef {object} FrameContext * @property {string} key * @property {number} generation * @property {MessagePort} port - * @property {Window|null} source + * @property {Window} source * @property {string} origin * @property {number|null} frameId * @property {string|null} documentId * @property {boolean} destroyed * @property {Map} sessions */ - /** @type {Map} */ - const frameContexts = new Map() + /** @type {FrameContext|null} */ + let frameContext = null /** @type {Map} */ const frameContextByPort = new Map() /** @type {Map>} */ const clientSessions = new Map() /** @type {Map} */ const clientKeysByPort = new Map() - /** @type {Map} */ - const frameContextBySource = new Map() - /** - * @typedef {object} BootstrapReservation - * @property {FrameContext|null} previous - * @property {{frameId: number|null, documentId: string|null}} targetIdentity - * @property {Array} candidates - * @property {boolean} cleanupComplete - * @property {number} nextSequence - * @property {boolean} failed - */ - /** @type {Map} */ - const bootstrapReservations = new Map() + /** @type {Map} */ + const requestPortMap = new Map() let nextFrameGeneration = 0 /** - * Reads browser-authenticated identity for a window represented by the - * bootstrap event. + * Reads browser-authenticated identity for this exact document. * @param {Window} source * @returns {{frameId: number|null, documentId: string|null}} */ @@ -194,48 +216,22 @@ try { const getFrameId = browser.runtime.getFrameId if (typeof getFrameId === 'function') frameId = getFrameId(source) - } catch {} + } catch { + void 0 + } try { const getDocumentId = browser.runtime.getDocumentId if (typeof getDocumentId === 'function') documentId = getDocumentId(source) - } catch {} + } catch { + void 0 + } return { frameId: Number.isInteger(frameId) && frameId >= 0 ? frameId : null, documentId: typeof documentId === 'string' && documentId ? documentId : null } } /** - * @param {MessagePort} port - * @returns {void} - */ - function rejectBootstrapPort(port) { - try { - port.close() - } catch (e) { - logger.debug('duplicate bootstrap port close failed', e) - } - } - /** - * @param {FrameContext} context - * @param {{frameId: number|null, documentId: string|null}} identity - * @returns {boolean} - */ - function sameBrowserLifetime(context, identity) { - return ( - context.frameId != null && - context.documentId != null && - context.frameId === identity.frameId && - context.documentId === identity.documentId - ) - } - /** - * @param {{frameId: number|null, documentId: string|null}} identity - * @returns {boolean} - */ - function hasBrowserLifetime(identity) { - return identity.frameId != null && identity.documentId != null - } - /** + * Installs the exact same-document page endpoint. * @param {MessagePort} port * @param {Window} source * @param {string} origin @@ -244,9 +240,6 @@ */ function acceptBootstrapPort(port, source, origin, identity) { const context = createFrameContext(port, source, origin, identity) - pagePorts.set(source, port) - pageSourceByPort.set(port, source) - portOrigin.set(port, origin) port.onmessage = (event) => { const data = event.data if (!data) return @@ -257,23 +250,20 @@ } dispatchPortMessage(port, event, source) } - logger.debug( - '[bridge] page port established for', - source === window ? 'window' : 'child', - context.key - ) + if (typeof port.start === 'function') port.start() + logger.debug('[bridge] exact page port established', context.key) return context } /** * @param {MessagePort} port - * @param {Window|null} source + * @param {Window} source * @param {string} origin * @param {{frameId: number|null, documentId: string|null}} identity * @returns {FrameContext} */ function createFrameContext(port, source, origin, identity) { const context = { - key: bridgeInstanceId + '/frame-' + ++nextFrameGeneration, + key: frameInstanceId + '/exact-' + ++nextFrameGeneration, generation: nextFrameGeneration, port, source, @@ -283,13 +273,18 @@ destroyed: false, sessions: new Map() } - frameContexts.set(context.key, context) + frameContext = context frameContextByPort.set(port, context) clientSessions.set(port, context.sessions) clientKeysByPort.set(port, 'window') - if (source) frameContextBySource.set(source, context) return context } + frameContext = acceptBootstrapPort( + pagePort, + window, + window.location.origin, + browserFrameIdentity(window) + ) /** * @param {MessagePort} port @@ -325,7 +320,8 @@ */ function contextForPlaneKey(key) { const separator = key.indexOf('\u0000') - return separator >= 0 ? frameContexts.get(key.slice(0, separator)) || null : null + if (!frameContext || separator < 0) return null + return frameContext.key === key.slice(0, separator) ? frameContext : null } /** @@ -429,8 +425,15 @@ browser.runtime.onMessage.addListener((request, sender, sendResponse) => { const origin = typeof request.origin === 'string' ? request.origin : '' const knownOrigin = !origin || collectFrameOrigins().includes(origin) - if (!knownOrigin && (request.action === 'getOpenDeviceIds' || request.action === 'getDataPlaneStatus')) { - sendResponse(request.action === 'getOpenDeviceIds' ? { ids: [] } : { planes: [], defaultPlane: webhid.import('GLOBAL_DEFAULTS').dataPlane }) + if ( + !knownOrigin && + (request.action === 'getOpenDeviceIds' || request.action === 'getDataPlaneStatus') + ) { + sendResponse( + request.action === 'getOpenDeviceIds' + ? { ids: [] } + : { planes: [], defaultPlane: webhid.import('GLOBAL_DEFAULTS').dataPlane } + ) return true } if (request.action === 'getFrameOrigins') { @@ -661,14 +664,6 @@ return load } installSettingsListeners(window.location.origin, settings) - /** @type {Map} */ - const pagePorts = new Map() - /** @type {Map} */ - const pageSourceByPort = new Map() - /** @type {Map} */ - const requestPortMap = new Map() - /** @type {Map} */ - const portOrigin = new Map() /** @type {Map} */ const spawnGen = new Map() /** @@ -1262,7 +1257,7 @@ }) generation = spawnGen.get(key) } - if (context.destroyed || !frameContexts.has(context.key) || spawnGen.get(key) !== generation) + if (context.destroyed || frameContext !== context || spawnGen.get(key) !== generation) return null ensureRuntimeDataPort(deviceId) let response @@ -1286,7 +1281,7 @@ } return null } - if (context.destroyed || !frameContexts.has(context.key) || spawnGen.get(key) !== generation) { + if (context.destroyed || frameContext !== context || spawnGen.get(key) !== generation) { if (spawnGen.get(key) === generation) await despawnDataPlane(context, deviceId, { clientKey, clientPort }) return null @@ -1366,7 +1361,7 @@ */ function waitForPlaneReady(context, deviceId, clientKey, generation, sessionToken) { const key = planeKeyForClient(context, deviceId, clientKey) - if (context.destroyed || !frameContexts.has(context.key)) + if (context.destroyed || frameContext !== context) return Promise.resolve({ ok: false, destroyed: true }) if (spawnGen.get(key) !== generation) return Promise.resolve({ ok: false, stale: true }) if (readyGenerations.get(key) === generation) return Promise.resolve({ ok: true }) @@ -1442,7 +1437,6 @@ } })() - /** * @param {object} msg * @param {ArrayBuffer[]} [transfer] @@ -1458,7 +1452,11 @@ } } if (msg != null && (msg.type === 'event' || msg.type === 'settings')) { - for (const port of pagePorts.values()) port.postMessage(msg, transfer) + try { + frameContext.port.postMessage(msg, transfer) + } catch (e) { + logger.debug('page event delivery failed', e) + } } } @@ -1546,7 +1544,7 @@ unavailableReason: 'data plane recovery' }) const generation = spawnGen.get(key) - if (context.destroyed || !frameContexts.has(context.key)) return null + if (context.destroyed || frameContext !== context) return null const originSettings = settingsForOrigin(context.origin) if (originSettings.dataPlane === 'nm') { return fallbackToNm(context, deviceId, token, clientKey, generation, { @@ -1623,25 +1621,6 @@ ), frameDestroyed: handleFrameDestroyedMessage } - const handleBootstrap = createBootstrapGate({ - getReservation: (source) => bootstrapReservations.get(source) || null, - setReservation: (source, reservation) => bootstrapReservations.set(source, reservation), - deleteReservation: (source) => bootstrapReservations.delete(source), - getContext: (source) => frameContextBySource.get(source) || null, - getIdentity: browserFrameIdentity, - getCurrentIdentity: browserFrameIdentity, - hasLifetime: hasBrowserLifetime, - sameLifetime: sameBrowserLifetime, - accept: acceptBootstrapPort, - accepted: (port) => port.postMessage({ type: 'bootstrapAccepted' }), - destroy: destroyFrameContext, - reject: rejectBootstrapPort, - createChallenge: () => pristine.host.cryptoRandomUUID(), - schedule: (callback, delay) => setTimeout(callback, delay), - cancel: (handle) => clearTimeout(handle), - probeTimeoutMs: BOOTSTRAP_PROBE_TIMEOUT_MS - }) - window.addEventListener('message', handleBootstrap) /** * @param {object} data @@ -1649,30 +1628,16 @@ */ function getRequestOrigin(data) { const port = requestPortMap.get(data.id) - return port ? portOrigin.get(port) : window.location.origin + return frameContextForPort(port)?.origin || window.location.origin } /** - * Distinct http(s) origins of every frame running the polyfill in this tab, - * top-level first. Origins come from the engine-set `event.origin` of each - * page port, never from page-visible state. + * Returns this exact document's origin for local settings and UI requests. * @returns {string[]} */ function collectFrameOrigins() { - const seen = new Set() - const origins = [] - const topOrigin = window.location.origin - if (topOrigin && (topOrigin.startsWith('http:') || topOrigin.startsWith('https:'))) { - seen.add(topOrigin) - origins.push(topOrigin) - } - for (const o of portOrigin.values()) { - if (!o || seen.has(o)) continue - if (!(o.startsWith('http:') || o.startsWith('https:'))) continue - seen.add(o) - origins.push(o) - } - return origins + const origin = frameContext.origin + return origin && (origin.startsWith('http:') || origin.startsWith('https:')) ? [origin] : [] } /** @@ -1709,7 +1674,6 @@ workerPagePorts.set(context, workerPorts) } workerPorts.add(p) - portOrigin.set(p, context.origin) p.onmessage = (event) => dispatchPortMessage(p, event, null) if (typeof p.start === 'function') p.start() requestPort.postMessage({ @@ -1854,21 +1818,32 @@ } } /** - * @param {FrameContext} context + * @param {{childFrameId: number, childDocumentId: string}} query * @returns {boolean} */ - function hasHidDelegation(context) { - if (!context.source || context.source === window) return true + function frameDelegationForChild(query) { try { - const frames = document.querySelectorAll('iframe,frame') - for (const frame of frames) { - if (frame.contentWindow !== context.source) continue + const getFrameId = browser.runtime.getFrameId + const getDocumentId = browser.runtime.getDocumentId + if (typeof getFrameId !== 'function' || typeof getDocumentId !== 'function') return false + for (const frame of document.querySelectorAll('iframe,frame')) { + if (getFrameId(frame) !== query.childFrameId) continue + if (getDocumentId(frame) !== query.childDocumentId) continue const allow = frame.getAttribute('allow') || '' return allow.split(';').some((directive) => /^\s*hid(?:\s|$)/i.test(directive)) } - } catch {} + } catch { + void 0 + } return false } + /** + * @param {FrameContext} context + * @returns {boolean} + */ + function hasHidDelegation(context) { + return context.frameId === 0 + } /** * @param {object} data * @param {MessagePort[]} _ports @@ -1882,22 +1857,16 @@ return } try { - const delegation = hasHidDelegation(context) - const delegationResponse = await sendBackgroundRequest({ - action: 'setFrameDelegation', - origin: context.origin, - frameId: context.frameId, - documentId: context.documentId, - delegated: delegation - }) - const response = delegationResponse?.ok - ? await sendBackgroundRequest({ - action: 'getPolicy', - origin: context.origin, - frameId: context.frameId, - documentId: context.documentId - }) - : null + let response = null + if (hasHidDelegation(context)) { + const delegationResponse = await sendBackgroundRequest({ + action: 'setFrameDelegation', + delegated: true + }) + if (delegationResponse?.ok) response = await sendBackgroundRequest({ action: 'getPolicy' }) + } else { + response = await sendBackgroundRequest({ action: 'getPolicy' }) + } replyToPage({ type: 'response', id: data.id, @@ -1943,59 +1912,47 @@ ? 'modal' : originSettings.devicePickerMode - if (pickerMode === 'pageAction' || pickerMode === 'window') { + sendBackgroundRequest({ + action: 'showPicker', + requestId: data.id, + filters, + exclusionFilters, + mode: pickerMode, + origin + }).catch((e) => logger.debug('showPicker send failed', e)) + const pickerTimeout = setTimeout(() => { + pickerResultHandlers.delete(data.id) sendBackgroundRequest({ - action: 'showPicker', - requestId: data.id, - filters, - exclusionFilters, - mode: pickerMode, - origin, - }).catch((e) => logger.debug('showPicker send failed', e)) - const pickerTimeout = setTimeout(() => { - browser.runtime.onMessage.removeListener(onPickerResult) - sendBackgroundRequest({ - action: 'cancelPicker', - requestId: data.id - }).catch((e) => logger.debug('cancelPicker send failed', e)) + action: 'cancelPicker', + requestId: data.id + }).catch((e) => logger.debug('cancelPicker send failed', e)) + replyToPage({ + type: 'response', + id: data.id, + result: { cancelled: true } + }) + }, 30000) + const onPickerResult = async (msg) => { + if (msg.action !== 'pickerResult' || msg.requestId !== data.id) return + clearTimeout(pickerTimeout) + pickerResultHandlers.delete(data.id) + if (msg.selected && msg.devices) { + await grantSelectedDevices(getRequestOrigin(data), msg.devices) + replyToPage({ + type: 'response', + id: data.id, + result: { devices: msg.devices } + }) + } else { replyToPage({ type: 'response', id: data.id, result: { cancelled: true } }) - }, 30000) - const onPickerResult = async (msg) => { - if (msg.action !== 'pickerResult' || msg.requestId !== data.id) return - clearTimeout(pickerTimeout) - browser.runtime.onMessage.removeListener(onPickerResult) - if (msg.selected && msg.devices) { - await grantSelectedDevices(getRequestOrigin(data), msg.devices) - replyToPage({ - type: 'response', - id: data.id, - result: { devices: msg.devices } - }) - } else { - replyToPage({ - type: 'response', - id: data.id, - result: { cancelled: true } - }) - } } - browser.runtime.onMessage.addListener(onPickerResult) - return - } - - const result = await devicePicker.show(filters, exclusionFilters) - if (result.devices && result.devices.length) { - await grantSelectedDevices(getRequestOrigin(data), result.devices) } - replyToPage({ - type: 'response', - id: data.id, - result: result.devices.length ? { devices: result.devices } : { cancelled: true } - }) + pickerResultHandlers.set(data.id, onPickerResult) + return } /** @@ -2011,7 +1968,7 @@ if ( !context || context.destroyed || - !frameContexts.has(context.key) || + frameContext !== context || !client || client.sessions !== sessions ) @@ -2147,7 +2104,7 @@ const currentClient = clientForPort(context, requestPort) if ( context.destroyed || - !frameContexts.has(context.key) || + frameContext !== context || frameContextForPort(requestPort) !== context || !currentClient || currentClient.port !== client.port || @@ -2224,7 +2181,6 @@ } catch { if (action === 'open' && nmOpenAttempt) { releaseNmOpenAttempt(key) - nmOpenAttempt = false } if (action === 'open') { if (sessions) sessions.delete(deviceId) @@ -2281,7 +2237,6 @@ clientSessions.delete(workerPort) clientKeysByPort.delete(workerPort) frameContextByPort.delete(workerPort) - portOrigin.delete(workerPort) try { workerPort.onmessage = null workerPort.close() @@ -2336,7 +2291,7 @@ * @returns {Promise} */ async function destroyFrameContext(context, { close = true, notify = false } = {}) { - if (!context || context.destroyed || !frameContexts.has(context.key)) return + if (!context || context.destroyed || frameContext !== context) return const clientRecords = sessionsForContext(context).map(({ port, sessions, clientKey }) => ({ port, sessions, @@ -2376,11 +2331,6 @@ } context.destroyed = true - frameContexts.delete(context.key) - if (frameContextBySource.get(context.source) === context) { - frameContextBySource.delete(context.source) - pagePorts.delete(context.source) - } const workerPorts = new Set(workerPagePorts.get(context) || []) const allClientPorts = new Set(clientRecords.map(({ port }) => port)) for (const port of workerPorts) allClientPorts.add(port) @@ -2388,8 +2338,6 @@ frameContextByPort.delete(port) clientSessions.delete(port) clientKeysByPort.delete(port) - portOrigin.delete(port) - pageSourceByPort.delete(port) for (const [id, mappedPort] of requestPortMap) { if (mappedPort === port) requestPortMap.delete(id) } @@ -2439,6 +2387,7 @@ } catch (e) { logger.debug('frame page port cleanup failed', e) } + if (frameContext === context) frameContext = null } /** @@ -2446,7 +2395,7 @@ * @returns {Promise} */ async function resetAuthorityState() { - const contexts = [...frameContexts.values()] + const contexts = frameContext ? [frameContext] : [] for (const context of contexts) { const clientSessionsForFrame = sessionsForContext(context) const deviceIds = new Set() @@ -2513,7 +2462,7 @@ */ function forwardInputReportToPage(messageEvent) { let handled = false - for (const context of frameContexts.values()) { + for (const context of frameContext ? [frameContext] : []) { for (const { port, sessions, clientKey } of sessionsForContext(context)) { if (!sessions.has(messageEvent.deviceId)) continue const key = planeKeyForClient(context, messageEvent.deviceId, clientKey) @@ -2545,16 +2494,15 @@ return } if (messageEvent.eventType === 'disconnect') { - const contexts = [...frameContexts.values()] + const contexts = frameContext ? [frameContext] : [] for (const context of contexts) { reconcileFrameDevice(context, messageEvent.deviceId, messageEvent).catch((e) => logger.debug('disconnect reconciliation failed', e) ) } } else if (messageEvent.eventType === 'revoked') { - const contexts = [...frameContexts.values()].filter( - (context) => context.origin === messageEvent.origin - ) + const contexts = + frameContext && frameContext.origin === messageEvent.origin ? [frameContext] : [] for (const context of contexts) { reconcileFrameDevice(context, messageEvent.deviceId, messageEvent).catch((e) => logger.debug('revoke reconciliation failed', e) @@ -2672,7 +2620,7 @@ */ function respawnPlanesForMode(dp, origin) { if (dp !== 'ws' && dp !== 'wt') return - for (const context of frameContexts.values()) { + for (const context of frameContext ? [frameContext] : []) { if (context.origin !== origin) continue for (const { sessions } of sessionsForContext(context)) { const clientKey = clientKeyForSessions(sessions) @@ -2700,7 +2648,7 @@ */ async function applyDataPlane(dp, origin) { const active = [] - for (const context of frameContexts.values()) { + for (const context of frameContext ? [frameContext] : []) { if (context.origin !== origin) continue for (const { sessions } of sessionsForContext(context)) { const clientKey = clientKeyForSessions(sessions) diff --git a/addon/js/content/main/index.js b/addon/js/content/main/index.js index 14d89e1..2659442 100644 --- a/addon/js/content/main/index.js +++ b/addon/js/content/main/index.js @@ -16,6 +16,7 @@ } const http = webhid.import('http') + const isChromium = webhid.import('isChromium') const GLOBAL_DEFAULTS = webhid.import('GLOBAL_DEFAULTS') const createSettingsStore = webhid.import('createSettingsStore') const isValidFilter = webhid.import('isValidFilter') @@ -59,7 +60,6 @@ const nativeWorkerAddEventListener = types.Worker ? types.Worker.getDescriptor('addEventListener').value : null - const nativeWindowPostMessage = !isWorker ? host.windowPostMessageMethod : null const nativeWorkerTerminate = types.Worker ? types.Worker.getDescriptor('terminate').value : null const nativeWindowAddEventListener = host.windowAddEventListener const nativeWindowRemoveEventListener = host.windowRemoveEventListener @@ -76,9 +76,7 @@ const Object = NativeObject const arrayIsArray = types.Array.getStaticDescriptor('isArray').value const arrayOps = types.Array.proto.methods - const nativeArrayIterator = nativeSymbolIterator - ? arrayOps[nativeSymbolIterator] - : null + const nativeArrayIterator = nativeSymbolIterator ? arrayOps[nativeSymbolIterator] : null const stringOps = types.String.proto.methods const nativeClearTimeout = host.timers.clearTimeout const nativeCreateTrustedTypePolicy = host.trustedTypesCreatePolicy @@ -735,32 +733,51 @@ /** @type {string} */ const frameNonce = nativeCryptoRandomUUID() - /** @type {(() => void)|null} */ - let resolveBridgeReady = null - let bridgeReadySettled = false /** @type {MessagePort|null} */ let bridgePort = null const bridgeReady = isWorker ? (() => { - bridgeReadySettled = true const ch = new NativeMessageChannel() bridgePort = ch.port1 setupBridgePort() if (nativeSelfPostMessage) nativeSelfPostMessage(null, makePristineIterable([ch.port2])) return Promise.resolve() })() - : new Promise((resolve) => { - resolveBridgeReady = () => { - if (bridgeReadySettled) return - bridgeReadySettled = true - resolve() - } - const target = windowObject === windowObject.top ? windowObject : windowObject.top - const channel = new NativeMessageChannel() - bridgePort = channel.port1 - setupBridgePort() - callNative(nativeWindowPostMessage, target, null, '*', makePristineIterable([channel.port2])) - }) + : isChromium + ? new Promise((resolve) => { + const onBridgeMessage = (event) => { + if ( + event.source !== windowObject || + event.data !== null || + !event.ports || + event.ports.length !== 1 + ) + return + nativeWindowRemoveEventListener(windowObject, 'message', onBridgeMessage) + bridgePort = event.ports[0] + setupBridgePort() + resolve() + } + nativeWindowAddEventListener(windowObject, 'message', onBridgeMessage) + }) + : new Promise((resolve) => { + const capturePageBridge = (candidate) => { + if (!candidate || typeof candidate.postMessage !== 'function') return + reflect.deleteProperty(globalThis, 'webhid') + bridgePort = candidate + setupBridgePort() + resolve() + } + try { + capturePageBridge(windowObject.webhid) + } catch { + void 0 + } + object.defineProperty(windowObject, 'webhid', { + configurable: true, + set: capturePageBridge + }) + }) if (!isWorker) setupTrustedTypesSharing() /** @returns {void} */ @@ -793,7 +810,12 @@ promiseOps.then(handleSpawnWorkerRequest(data), (r) => { const msg = { type: 'spawnWorkerResponse', id: data.id, result: r.result } if (r.transfer) { - callNative(nativeMessagePortPostMessage, bridgePort, msg, makePristineIterable([r.transfer])) + callNative( + nativeMessagePortPostMessage, + bridgePort, + msg, + makePristineIterable([r.transfer]) + ) } else { callNative(nativeMessagePortPostMessage, bridgePort, msg) } @@ -812,25 +834,8 @@ } } - /** - * @param {object} data - * @returns {void} - */ - function handleBootstrapProbe(data) { - if (typeof data.challenge !== 'string' || !bridgePort) return - callNative(nativeMessagePortPostMessage, bridgePort, { - type: 'bootstrapProbeResponse', - challenge: data.challenge - }) - } - /** @returns {void} */ - function handleBootstrapAccepted() { - if (resolveBridgeReady) resolveBridgeReady() - } /** @type {object} */ const BRIDGE_MESSAGE_HANDLERS = { - bootstrapProbe: handleBootstrapProbe, - bootstrapAccepted: handleBootstrapAccepted, dataPlaneConnect: handleDataPlaneConnect, dataPlaneDisconnect: handleDataPlaneDisconnect, dataPlaneReady: handleDataPlaneReady, @@ -1450,7 +1455,8 @@ detail.data.byteLength ) : new NativeDataView(new NativeArrayBuffer(0)) - eventTargetOps.dispatchEvent(devState.get(device).eventTarget, + eventTargetOps.dispatchEvent( + devState.get(device).eventTarget, new HIDInputReportEvent('inputreport', { device: device, reportId: detail.reportId, @@ -1684,7 +1690,11 @@ deviceInfoCache = null reconcileAuthoritativeLifetime(state) const device = state.self - if (device) eventTargetOps.dispatchEvent(state.eventTarget, new HIDConnectionEvent('disconnect', { device: device })) + if (device) + eventTargetOps.dispatchEvent( + state.eventTarget, + new HIDConnectionEvent('disconnect', { device: device }) + ) } /** @type {object} */ diff --git a/addon/manifest.chromium.json b/addon/manifest.chromium.json index 0c5fea6..e7c9ce4 100644 --- a/addon/manifest.chromium.json +++ b/addon/manifest.chromium.json @@ -36,7 +36,8 @@ "matches": [""], "js": ["isolated-world.js"], "world": "ISOLATED", - "run_at": "document_start" + "run_at": "document_start", + "all_frames": true } ], "web_accessible_resources": [], diff --git a/addon/manifest.json b/addon/manifest.json index 6f84ef6..0fa5332 100644 --- a/addon/manifest.json +++ b/addon/manifest.json @@ -15,9 +15,7 @@ "notifications", "theme" ], - "host_permissions": [ - "" - ], + "host_permissions": [""], "background": { "scripts": [ "js/utils/bootstrap.js", @@ -57,9 +55,7 @@ }, "content_scripts": [ { - "matches": [ - "" - ], + "matches": [""], "js": [ "js/utils/bootstrap.js", "js/utils/http.js", @@ -75,9 +71,7 @@ "all_frames": true }, { - "matches": [ - "" - ], + "matches": [""], "js": [ "js/utils/bootstrap.js", "js/utils/i18n.js", @@ -90,11 +84,11 @@ "js/utils/theme-sync.js", "js/content/isolated/picker/index.js", "js/utils/input-report.js", - "js/content/isolated/bootstrap-lifetime.js", "js/content/isolated/bridge.js" ], "world": "ISOLATED", - "run_at": "document_start" + "run_at": "document_start", + "all_frames": true } ], "web_accessible_resources": [], @@ -102,9 +96,7 @@ "gecko": { "id": "webhid@k4zoku.dev", "data_collection_permissions": { - "required": [ - "websiteContent" - ], + "required": ["websiteContent"], "optional": [] } } diff --git a/addon/manifest.v2.json b/addon/manifest.v2.json index d15b280..671d998 100644 --- a/addon/manifest.v2.json +++ b/addon/manifest.v2.json @@ -82,10 +82,10 @@ "js/utils/settings.js", "js/utils/theme-sync.js", "js/content/isolated/picker/index.js", - "js/content/isolated/bootstrap-lifetime.js", "js/content/isolated/bridge.js" ], - "run_at": "document_start" + "run_at": "document_start", + "all_frames": true } ], "web_accessible_resources": [], diff --git a/tests/e2e/nm-runtime-port.spec.ts b/tests/e2e/nm-runtime-port.spec.ts index 67dbeb8..6da9e86 100644 --- a/tests/e2e/nm-runtime-port.spec.ts +++ b/tests/e2e/nm-runtime-port.spec.ts @@ -5,8 +5,8 @@ import { sendInput } from '../helpers/e2e-process.js' const VENDOR = mockIdFor('vendor') const PACKET = [0x10, 0x20, 0x30, 0x40, 0x50].concat(new Array(59).fill(0)) -test.describe.serial('NM runtime port topology', () => { - test('shared NM port survives one frame teardown', async ({ +test.describe.serial('Exact frame endpoint fanout', () => { + test('background fanout survives one frame teardown', async ({ sharedPage, backgroundPage, vendorDevice @@ -30,7 +30,10 @@ test.describe.serial('NM runtime port topology', () => { waitUntil: 'domcontentloaded' }) await sharedPage.evaluate(() => { - window.postMessage({ type: 'startFanout', iframeCount: 1, includeWorker: false }, location.origin) + window.postMessage( + { type: 'startFanout', iframeCount: 1, includeWorker: false }, + location.origin + ) }) await sharedPage.waitForFunction( () => { @@ -78,10 +81,12 @@ test.describe.serial('NM runtime port topology', () => { }, { timeout: 15000 } ) - await expect(sharedPage.evaluate(() => window.tests?.results?.fanoutCounts)).resolves.toEqual({ - page: 2, - 'iframe-0': 1 - }) + await expect(sharedPage.evaluate(() => window.tests?.results?.fanoutCounts)).resolves.toEqual( + { + page: 2, + 'iframe-0': 1 + } + ) } finally { await sharedPage.evaluate(async () => { for (const device of await navigator.hid.getDevices()) { diff --git a/tests/unit/bootstrap-lifetime.test.js b/tests/unit/bootstrap-lifetime.test.js deleted file mode 100644 index 818574d..0000000 --- a/tests/unit/bootstrap-lifetime.test.js +++ /dev/null @@ -1,397 +0,0 @@ -import assert from 'node:assert/strict' -import { readFileSync } from 'node:fs' -import vm from 'node:vm' -import { test } from 'node:test' - -const source = readFileSync('addon/js/content/isolated/bootstrap-lifetime.js', 'utf8') -const manifest = JSON.parse(readFileSync('addon/manifest.json', 'utf8')) -const manifestV2 = JSON.parse(readFileSync('addon/manifest.v2.json', 'utf8')) -const chromiumManifest = JSON.parse(readFileSync('addon/manifest.chromium.json', 'utf8')) -const mainSource = readFileSync('addon/js/content/main/index.js', 'utf8') -const bridgeSource = readFileSync('addon/js/content/isolated/bridge.js', 'utf8') - -test('bootstrap topology uses one structural DOM transfer', () => { - assert.match(mainSource, /nativeWindowPostMessage, target, null/) - assert.doesNotMatch(mainSource, /webhidBridgeRequest|webhidBridgeReady/) - assert.doesNotMatch(bridgeSource, /webhidBridgeRequest|framePolicyResponse/) - assert.equal(manifest.content_scripts.filter((entry) => entry.world === 'ISOLATED').length, 1) - assert.equal(manifestV2.content_scripts.length, 2) - assert.equal( - chromiumManifest.content_scripts.filter((entry) => entry.world === 'ISOLATED').length, - 1 - ) - const isolatedEntry = manifest.content_scripts.find((entry) => entry.world === 'ISOLATED') - assert.ok(isolatedEntry.js.includes('js/content/isolated/bootstrap-lifetime.js')) - assert.equal( - [ - ...manifest.content_scripts, - ...manifestV2.content_scripts, - ...chromiumManifest.content_scripts - ].some((entry) => entry.js.includes('frame-identity.js')), - false - ) -}) - -function loadGate(deps) { - let createBootstrapGate - const context = vm.createContext({ - webhid: { - export(name, value) { - if (name === 'createBootstrapGate') createBootstrapGate = value - } - } - }) - vm.runInContext(source, context) - return createBootstrapGate(deps) -} - -function port() { - return { - closed: false, - messages: [], - onmessage: null, - close() { - this.closed = true - this.onmessage = null - }, - start() {}, - postMessage(message) { - this.messages.push(message) - } - } -} - -function identity(documentId) { - return { frameId: 7, documentId } -} - -function makeState(cleanup, nextDocumentId, currentDocumentId = nextDocumentId) { - return { - contexts: new Map(), - reservations: new Map(), - accepted: [], - rejected: [], - destroyed: [], - timers: [], - challengeSequence: 0, - cleanup, - nextIdentity: identity(nextDocumentId), - currentIdentity: identity(currentDocumentId) - } -} - -function dependencies(state) { - return { - getReservation: (source) => state.reservations.get(source), - setReservation: (source, value) => state.reservations.set(source, value), - deleteReservation: (source) => state.reservations.delete(source), - getContext: (source) => state.contexts.get(source), - getIdentity: (_source) => state.nextIdentity, - getCurrentIdentity: (_source) => state.currentIdentity, - hasLifetime: (value) => value.frameId != null && value.documentId != null, - sameLifetime: (context, value) => - context.frameId === value.frameId && context.documentId === value.documentId, - accept: (newPort, source, origin, value) => { - state.accepted.push(newPort) - state.contexts.set(source, { - port: newPort, - source, - origin, - frameId: value.frameId, - documentId: value.documentId, - destroyed: false - }) - }, - accepted: (newPort) => newPort.postMessage({ type: 'bootstrapAccepted' }), - destroy: (context) => { - state.destroyed.push(context) - return state.cleanup - }, - reject: (newPort) => { - state.rejected.push(newPort) - newPort.close() - }, - createChallenge: () => 'challenge-' + ++state.challengeSequence, - schedule: (callback, delay) => { - const handle = { callback, delay, cancelled: false } - state.timers.push(handle) - return handle - }, - cancel: (handle) => { - handle.cancelled = true - }, - probeTimeoutMs: 1000 - } -} - -function bindOldContext(state, source) { - const oldContext = { - port: port(), - source, - frameId: 7, - documentId: 'document-a', - destroyed: false - } - state.contexts.set(source, oldContext) - return oldContext -} - -function respond(candidate) { - const challenge = candidate.messages.find( - (message) => message.type === 'bootstrapProbe' - )?.challenge - assert.equal(typeof challenge, 'string') - candidate.onmessage({ data: { type: 'bootstrapProbeResponse', challenge } }) -} - -function fireNextDeadline(state) { - const handle = state.timers.find((candidate) => !candidate.cancelled) - assert.ok(handle) - handle.callback() -} - -async function finishCleanup(state, oldContext, releaseCleanup) { - oldContext.destroyed = true - releaseCleanup() - await state.cleanup - await Promise.resolve() -} - -test('bootstrap gate enforces one structural port per document', () => { - const state = makeState(Promise.resolve(), 'document-a') - const source = {} - const gate = loadGate(dependencies(state)) - const valid = port() - gate({ data: null, ports: [valid], source, origin: 'https://page.test' }) - assert.deepEqual(state.accepted, []) - respond(valid) - assert.deepEqual(state.accepted, [valid]) - - const nonNull = port() - gate({ data: { bootstrap: true }, ports: [nonNull], source, origin: 'https://page.test' }) - const zero = port() - gate({ data: null, ports: [], source, origin: 'https://page.test' }) - const first = port() - const second = port() - gate({ data: null, ports: [first, second], source, origin: 'https://page.test' }) - - assert.equal(nonNull.closed, true) - assert.equal(first.closed, true) - assert.equal(second.closed, true) - assert.equal(zero.closed, false) - assert.deepEqual(state.accepted, [valid]) -}) -test('wrong challenge, type, and malformed responses do not go live', () => { - const state = makeState(Promise.resolve(), 'document-a') - const source = {} - const gate = loadGate(dependencies(state)) - const candidate = port() - gate({ data: null, ports: [candidate], source, origin: 'https://page.test' }) - const challenge = candidate.messages[0].challenge - candidate.onmessage({ data: { type: 'bootstrapProbeResponse', challenge: 'wrong' } }) - candidate.onmessage({ data: { type: 'unexpected', challenge } }) - candidate.onmessage({ data: { type: 'bootstrapProbeResponse' } }) - assert.deepEqual(state.accepted, []) - assert.equal(candidate.closed, false) - candidate.onmessage({ data: { type: 'bootstrapProbeResponse', challenge } }) - assert.deepEqual(state.accepted, [candidate]) -}) - -test('A to B rejects a same-lifetime duplicate and promotes B', async () => { - let releaseCleanup - const cleanup = new Promise((resolve) => { - releaseCleanup = resolve - }) - const state = makeState(cleanup, 'document-b') - const source = {} - const oldContext = bindOldContext(state, source) - const gate = loadGate(dependencies(state)) - const reserved = port() - gate({ data: null, ports: [reserved], source, origin: 'https://page.test' }) - respond(reserved) - const duplicate = port() - gate({ data: null, ports: [duplicate], source, origin: 'https://page.test' }) - - assert.equal(duplicate.closed, true) - assert.deepEqual(state.accepted, []) - assert.deepEqual(state.destroyed, [oldContext]) - assert.equal(state.reservations.get(source).candidates[0].port, reserved) - - await finishCleanup(state, oldContext, releaseCleanup) - assert.deepEqual(state.accepted, [reserved]) - assert.equal(state.reservations.has(source), false) -}) - -test('A to B to C keeps only C while A cleanup is pending', async () => { - let releaseCleanup - const cleanup = new Promise((resolve) => { - releaseCleanup = resolve - }) - const state = makeState(cleanup, 'document-b') - const source = {} - const oldContext = bindOldContext(state, source) - const gate = loadGate(dependencies(state)) - const candidateB = port() - gate({ data: null, ports: [candidateB], source, origin: 'https://page.test' }) - respond(candidateB) - - state.nextIdentity = identity('document-c') - state.currentIdentity = identity('document-c') - const candidateC = port() - gate({ data: null, ports: [candidateC], source, origin: 'https://page.test' }) - respond(candidateC) - - assert.equal(candidateB.closed, true) - assert.equal(candidateC.closed, false) - assert.deepEqual(state.destroyed, [oldContext]) - assert.equal(state.reservations.get(source).candidates[0].port, candidateC) - - await finishCleanup(state, oldContext, releaseCleanup) - assert.deepEqual(state.accepted, [candidateC]) - assert.equal(state.reservations.has(source), false) -}) - -test('A to B to C to D promotes only the latest candidate', async () => { - let releaseCleanup - const cleanup = new Promise((resolve) => { - releaseCleanup = resolve - }) - const state = makeState(cleanup, 'document-b') - const source = {} - const oldContext = bindOldContext(state, source) - const gate = loadGate(dependencies(state)) - const candidates = [port(), port(), port()] - gate({ data: null, ports: [candidates[0]], source, origin: 'https://page.test' }) - respond(candidates[0]) - for (const documentId of ['document-c', 'document-d']) { - state.nextIdentity = identity(documentId) - state.currentIdentity = identity(documentId) - const candidate = candidates[documentId === 'document-c' ? 1 : 2] - gate({ data: null, ports: [candidate], source, origin: 'https://page.test' }) - respond(candidate) - } - - assert.equal(candidates[0].closed, true) - assert.equal(candidates[1].closed, true) - assert.equal(candidates[2].closed, false) - assert.deepEqual(state.destroyed, [oldContext]) - - await finishCleanup(state, oldContext, releaseCleanup) - assert.deepEqual(state.accepted, [candidates[2]]) - assert.equal(state.reservations.has(source), false) -}) - -test('identity change before promotion rejects the stale candidate', async () => { - let releaseCleanup - const cleanup = new Promise((resolve) => { - releaseCleanup = resolve - }) - const state = makeState(cleanup, 'document-b') - const source = {} - const oldContext = bindOldContext(state, source) - const gate = loadGate(dependencies(state)) - const candidateB = port() - gate({ data: null, ports: [candidateB], source, origin: 'https://page.test' }) - respond(candidateB) - state.currentIdentity = identity('document-c') - - await finishCleanup(state, oldContext, releaseCleanup) - assert.equal(candidateB.closed, true) - assert.deepEqual(state.accepted, []) - assert.equal(state.reservations.has(source), true) - assert.equal(state.reservations.get(source).candidates.length, 0) -}) - -test('stale candidate expires before a later live candidate', () => { - const state = makeState(Promise.resolve(), 'document-c') - const source = {} - const gate = loadGate(dependencies(state)) - const stale = port() - const legitimate = port() - gate({ data: null, ports: [stale], source, origin: 'https://page.test' }) - gate({ data: null, ports: [legitimate], source, origin: 'https://page.test' }) - respond(legitimate) - assert.deepEqual(state.accepted, []) - fireNextDeadline(state) - assert.deepEqual(state.accepted, [legitimate]) - assert.equal(stale.closed, true) -}) -test('non-head timeout closes its port while the head is still pending', () => { - const state = makeState(Promise.resolve(), 'document-c') - const source = {} - const gate = loadGate(dependencies(state)) - const head = port() - const later = port() - gate({ data: null, ports: [head], source, origin: 'https://page.test' }) - gate({ data: null, ports: [later], source, origin: 'https://page.test' }) - state.timers[1].callback() - assert.equal(later.closed, true) - assert.deepEqual(state.accepted, []) - respond(head) - assert.deepEqual(state.accepted, [head]) -}) - -test('earliest live candidate wins over a faster later response', () => { - const state = makeState(Promise.resolve(), 'document-c') - const source = {} - const gate = loadGate(dependencies(state)) - const legitimate = port() - const hostile = port() - gate({ data: null, ports: [legitimate], source, origin: 'https://page.test' }) - gate({ data: null, ports: [hostile], source, origin: 'https://page.test' }) - respond(hostile) - assert.deepEqual(state.accepted, []) - respond(legitimate) - assert.deepEqual(state.accepted, [legitimate]) - assert.equal(hostile.closed, true) -}) -test('stale B, legitimate C, and hostile C select legitimate C', () => { - const state = makeState(Promise.resolve(), 'document-c') - const source = {} - const gate = loadGate(dependencies(state)) - const staleB = port() - const legitimateC = port() - const hostileC = port() - gate({ data: null, ports: [staleB], source, origin: 'https://page.test' }) - gate({ data: null, ports: [legitimateC], source, origin: 'https://page.test' }) - gate({ data: null, ports: [hostileC], source, origin: 'https://page.test' }) - respond(hostileC) - respond(legitimateC) - assert.deepEqual(state.accepted, []) - fireNextDeadline(state) - assert.deepEqual(state.accepted, [legitimateC]) - assert.equal(staleB.closed, true) - assert.equal(hostileC.closed, true) -}) - -test('same-lifetime duplicate preserves the original reserved port', () => { - const state = makeState(new Promise(() => {}), 'document-b') - const source = {} - bindOldContext(state, source) - const gate = loadGate(dependencies(state)) - const reserved = port() - gate({ data: null, ports: [reserved], source, origin: 'https://page.test' }) - respond(reserved) - const duplicate = port() - gate({ data: null, ports: [duplicate], source, origin: 'https://page.test' }) - - assert.equal(duplicate.closed, true) - assert.equal(reserved.closed, false) - assert.equal(state.reservations.get(source).candidates[0].port, reserved) -}) -test('cleanup rejection closes all candidates and removes transition', async () => { - const state = makeState(Promise.reject(new Error('cleanup failed')), 'document-b') - const source = {} - bindOldContext(state, source) - const gate = loadGate(dependencies(state)) - const first = port() - const second = port() - gate({ data: null, ports: [first], source, origin: 'https://page.test' }) - gate({ data: null, ports: [second], source, origin: 'https://page.test' }) - await Promise.resolve() - await Promise.resolve() - assert.equal(first.closed, true) - assert.equal(second.closed, true) - assert.equal(state.reservations.has(source), false) - assert.deepEqual(state.accepted, []) -}) diff --git a/tests/unit/frame-endpoint-topology.test.js b/tests/unit/frame-endpoint-topology.test.js new file mode 100644 index 0000000..947d6a0 --- /dev/null +++ b/tests/unit/frame-endpoint-topology.test.js @@ -0,0 +1,44 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { test } from 'node:test' + +const read = (path) => readFileSync(path, 'utf8') +const manifest = JSON.parse(read('addon/manifest.json')) +const manifestV2 = JSON.parse(read('addon/manifest.v2.json')) +const manifestChromium = JSON.parse(read('addon/manifest.chromium.json')) +const bridge = read('addon/js/content/isolated/bridge.js') +const main = read('addon/js/content/main/index.js') +const messages = read('addon/js/background/messages.js') +const nm = read('addon/js/background/nm.js') + +function isolatedEntry(value) { + return ( + value.content_scripts.find((entry) => entry.world === 'ISOLATED') || value.content_scripts[1] + ) +} + +test('every production isolated bridge runs in every frame', () => { + assert.equal(isolatedEntry(manifest).all_frames, true) + assert.equal(isolatedEntry(manifestV2).all_frames, true) + assert.equal(isolatedEntry(manifestChromium).all_frames, true) +}) + +test('bridge is exact-frame and uses same-document capability handoff', () => { + assert.match(bridge, /wrappedJSObject\.webhid/) + assert.match(bridge, /wrapReflectors: true/) + assert.doesNotMatch(bridge, /createBootstrapGate|bootstrapReservations|frameContextBySource/) + assert.doesNotMatch(bridge, /pagePorts|pageSourceByPort|portOrigin/) +}) + +test('background owns endpoint registry and exact input fanout', () => { + assert.match(messages, /frameEndpoints/) + assert.match(messages, /postToContentPort\(req\.port/) + assert.match(nm, /collectDeviceSessionOwners\(deviceId\)/) + assert.match(nm, /postToContentPort\(port/) +}) + +test('MAIN does not bootstrap through a top WindowProxy', () => { + assert.doesNotMatch(main, /nativeWindowPostMessage/) + assert.doesNotMatch(main, /windowObject\.top/) + assert.match(main, /reflect\.deleteProperty\(globalThis, 'webhid'\)/) +}) diff --git a/tests/unit/state-ops.test.js b/tests/unit/state-ops.test.js index 4a65a18..d2f38e5 100644 --- a/tests/unit/state-ops.test.js +++ b/tests/unit/state-ops.test.js @@ -3,7 +3,10 @@ import { readFileSync } from 'node:fs' import test from 'node:test' import { runInNewContext } from 'node:vm' -const source = readFileSync(new URL('../../addon/js/background/state_ops.js', import.meta.url), 'utf8') +const source = readFileSync( + new URL('../../addon/js/background/state_ops.js', import.meta.url), + 'utf8' +) function loadStateOps() { let exported @@ -38,7 +41,13 @@ async function flush() { test('tab cleanup preserves sibling sessions and retains failed closes', async () => { const { ops, deviceTabMap, deviceSessions, orphanCleanup } = loadStateOps() - deviceTabMap.set(7, new Map([[11, 1], [22, 1]])) + deviceTabMap.set( + 7, + new Map([ + [11, 1], + [22, 1] + ]) + ) deviceSessions.set( 7, new Map([ @@ -266,34 +275,26 @@ test('physical ownership reset removes every session for one device', () => { assert.equal(ops.isFrameLifetimeActive(11, 'frame-a'), true) assert.equal(ops.isFrameLifetimeActive(11, 'frame-b'), true) }) -test('bridge cleanup cannot retire a newer bridge lifetime', async () => { +test('exact endpoint cleanup cannot retire a replacement lifetime', async () => { const { ops, deviceSessions, deviceTabMap } = loadStateOps() - ops.registerFrameLifetime(11, 'bridge-old/frame-1') - ops.registerFrameLifetime(11, 'bridge-new/frame-1') + ops.registerFrameLifetime(11, 'endpoint-old') + ops.registerFrameLifetime(11, 'endpoint-new') ops.registerDeviceTab(7, 11) ops.registerDeviceTab(7, 11) ops.registerDeviceSession(7, 'session-old', { tabId: 11, origin: 'https://a.test', - frameKey: 'bridge-old/frame-1', - bridgeInstanceId: 'bridge-old' + frameKey: 'endpoint-old' }) ops.registerDeviceSession(7, 'session-new', { tabId: 11, origin: 'https://a.test', - frameKey: 'bridge-new/frame-1', - bridgeInstanceId: 'bridge-new' - }) - const { promise, resolve } = Promise.withResolvers() - const cleanup = ops.purgeBridge(11, 'bridge-old', async () => { - await promise - return { s: 204 } + frameKey: 'endpoint-new' }) - resolve() - await cleanup + await ops.purgeFrame(11, 'endpoint-old', async () => ({ s: 204 })) - assert.equal(ops.isFrameLifetimeActive(11, 'bridge-old/frame-1'), false) - assert.equal(ops.isFrameLifetimeActive(11, 'bridge-new/frame-1'), true) + assert.equal(ops.isFrameLifetimeActive(11, 'endpoint-old'), false) + assert.equal(ops.isFrameLifetimeActive(11, 'endpoint-new'), true) assert.deepEqual([...deviceSessions.get(7).keys()], ['session-new']) assert.equal(deviceTabMap.get(7).get(11), 1) }) From 8f3edefdbc6ee23ef1b98a19f18db919e8bbd9b4 Mon Sep 17 00:00:00 2001 From: Kazoku Date: Sun, 13 Sep 2026 10:36:11 +0700 Subject: [PATCH 02/26] fix(addon): aggregate frame state in background --- addon/js/background/messages.js | 117 +++++++++++++++++--- addon/js/background/nm.js | 30 +++++- addon/js/background/state_ops.js | 51 +++++++++ addon/js/content/isolated/bridge.js | 132 ++++++++++------------- addon/js/internal/pages/popup/index.js | 6 +- tests/browser/page-action.spec.ts | 65 +++++------ tests/browser/permissions-policy.spec.ts | 24 +++++ tests/e2e/input-report-fanout.spec.ts | 1 + tests/unit/nm-lifetime.test.js | 96 +++++++++++++++-- tests/unit/state-ops.test.js | 51 +++++++++ 10 files changed, 435 insertions(+), 138 deletions(-) diff --git a/addon/js/background/messages.js b/addon/js/background/messages.js index fae4f18..b975713 100644 --- a/addon/js/background/messages.js +++ b/addon/js/background/messages.js @@ -37,6 +37,9 @@ purgeFrame, collectDeviceSessionsForOrigin, getDeviceSessionOwner, + setDeviceSessionPlane, + collectDevicePlaneStatuses, + collectOpenDeviceIdsForTab, closeForCleanup } = webhid.import('bgStateOps') const { urlOrigin, frameKey, documentFrameKey } = webhid.import('bgCsp') @@ -62,7 +65,8 @@ const frameId = Number.isInteger(sender.frameId) ? sender.frameId : null const documentId = typeof sender.documentId === 'string' && sender.documentId ? sender.documentId : null - const origin = urlOrigin(sender.url || '') + const origin = typeof sender.origin === 'string' && sender.origin ? sender.origin : null + const url = typeof sender.url === 'string' ? sender.url : '' if (tabId == null || frameId == null || !origin) return null const endpoint = { id: 'endpoint-' + ++nextEndpointId, @@ -71,7 +75,7 @@ frameId, documentId, origin, - url: sender.url, + url, frameKey: 'endpoint-' + nextEndpointId } frameEndpoints.set(port, endpoint) @@ -732,6 +736,88 @@ } /** + * Returns tab-wide open devices from authoritative background sessions. + * @param {object} request + * @param {object} sender + * @param {function(*): void} sendResponse + * @returns {boolean} + */ + function handleGetOpenDeviceIds(request, sender, sendResponse) { + const tabId = Number.isInteger(request.tabId) ? request.tabId : sender.tab?.id + sendResponse({ + ids: tabId == null ? [] : collectOpenDeviceIdsForTab(tabId, request.origin) + }) + return false + } + + /** + * Returns tab-wide data-plane state from authoritative session owners. + * @param {object} request + * @param {object} sender + * @param {function(*): void} sendResponse + * @returns {boolean} + */ + function handleGetDataPlaneStatus(request, sender, sendResponse) { + const tabId = Number.isInteger(request.tabId) ? request.tabId : sender.tab?.id + const statuses = tabId == null ? [] : collectDevicePlaneStatuses(tabId, request.origin) + sendResponse({ + planes: statuses.map(({ deviceId, plane, mode, generation, ready }) => ({ + deviceId, + plane, + mode, + generation, + ready: ready === true + })), + defaultPlane: webhid.import('GLOBAL_DEFAULTS').dataPlane + }) + return false + } + + /** + * Updates one exact session's data-plane status. + * @param {object} request + * @param {object} sender + * @param {function(*): void} sendResponse + * @param {object} port + * @returns {boolean} + */ + function handleSetDataPlaneStatus(request, sender, sendResponse, port) { + const endpoint = endpointForRequest(sender, port) + const deviceId = Number(request.deviceId) + const ok = + endpoint && + Number.isInteger(deviceId) && + typeof request.sessionToken === 'string' && + isSessionOwnedBy( + deviceId, + request.sessionToken, + endpoint.origin, + endpoint.tabId, + endpoint.frameKey, + request.clientKey, + port + ) + if (!ok) { + sendResponse({ s: 403 }) + return false + } + const plane = + request.plane == null + ? null + : { + plane: request.plane, + mode: request.mode == null ? null : request.mode, + generation: request.generation, + ready: request.ready === true + } + sendResponse({ + s: setDeviceSessionPlane(deviceId, request.sessionToken, port, plane) ? 204 : 403 + }) + return false + } + + /** + * Updates the tab badge from all exact frame/session owners. * @param {object} request * @param {object} sender * @returns {boolean} @@ -739,11 +825,13 @@ function handleDeviceCountChanged(request, sender) { if (actionApi) { const tabId = sender.tab != null ? sender.tab.id : undefined - if (tabId != null) + if (tabId != null) { + const count = collectOpenDeviceIdsForTab(tabId).length actionApi.setBadgeText({ - text: request.count > 0 ? String(request.count) : '', + text: count > 0 ? String(count) : '', tabId }) + } } return false } @@ -843,12 +931,13 @@ sendResponse(null) return false } - const origin = urlOrigin(sender.url || '') - if (!origin) { + const authorityOrigin = typeof sender.origin === 'string' ? sender.origin : '' + const documentUrlOrigin = urlOrigin(sender.url || '') + if (!authorityOrigin || !documentUrlOrigin) { sendResponse(null) return false } - const key = `csp:${frameKey(tabId, sender.frameId ?? 0, origin)}` + const key = `csp:${frameKey(tabId, sender.frameId ?? 0, documentUrlOrigin)}` browser.storage.session .get(key) .then((r) => sendResponse(r[key] ?? null)) @@ -1119,7 +1208,7 @@ const tabId = sender.tab?.id const frameId = Number.isInteger(sender.frameId) ? sender.frameId : null const documentId = typeof sender.documentId === 'string' ? sender.documentId : null - const requestedOrigin = urlOrigin(sender.url || '') + const requestedOrigin = typeof sender.origin === 'string' ? sender.origin : '' if (tabId == null || frameId == null || !documentId || !requestedOrigin) { return { policy: { hid: 'none' } } } @@ -1184,7 +1273,7 @@ const tabId = sender.tab?.id const frameId = Number.isInteger(sender.frameId) ? sender.frameId : null const documentId = typeof sender.documentId === 'string' ? sender.documentId : null - const origin = urlOrigin(sender.url || '') + const origin = typeof sender.origin === 'string' ? sender.origin : '' if (tabId == null || frameId == null || !documentId || !origin) { sendResponse({ ok: false }) return false @@ -1291,6 +1380,9 @@ pairDevice: handlePairDevice, unpairDevice: handleUnpairDevice, getAllowedDevices: handleGetAllowedDevices, + getOpenDeviceIds: handleGetOpenDeviceIds, + getDataPlaneStatus: handleGetDataPlaneStatus, + setDataPlaneStatus: handleSetDataPlaneStatus, deviceCountChanged: handleDeviceCountChanged, showPageAction: handleShowPageAction, getDeviceCache: handleGetDeviceCache, @@ -1333,14 +1425,15 @@ pending.resolve(request.delegated === true) return } - const handler = HANDLERS[request.action] + const effectiveRequest = endpoint ? { ...request, origin: endpoint.origin } : request + const handler = HANDLERS[effectiveRequest.action] if (!handler) return let responded = false const sendPortResponse = (response) => { if (responded) return responded = true const responseMessage = { ...(response || {}) } - if (request.reqId != null) responseMessage.reqId = request.reqId + if (effectiveRequest.reqId != null) responseMessage.reqId = effectiveRequest.reqId try { port.postMessage(responseMessage) } catch { @@ -1348,7 +1441,7 @@ } } try { - const result = handler(request, port.sender, sendPortResponse, port) + const result = handler(effectiveRequest, port.sender, sendPortResponse, port) if (result && typeof result.then === 'function') { result.catch(() => sendPortResponse({ s: 500 })) } else if (result !== true && !responded) { diff --git a/addon/js/background/nm.js b/addon/js/background/nm.js index 7362fb7..3e24154 100644 --- a/addon/js/background/nm.js +++ b/addon/js/background/nm.js @@ -45,6 +45,9 @@ reconnectDelay: 1000, nmHostName: NM_HOST_FORWARDER, lastError: null, + handshakePromise: null, + handshakePort: null, + handshakeResult: null, /** Per-request deadline for NM requests (see sendFrame). */ REQUEST_TIMEOUT_MS: 30000, @@ -165,6 +168,9 @@ retirePort(port) { if (this.port !== port) return false this.port = null + this.handshakePromise = null + this.handshakePort = null + this.handshakeResult = null for (const [, p] of this.pending) p.resolve({ s: 503 }) this.pending.clear() clearAuthorityOwnership() @@ -274,8 +280,28 @@ if (sessionToken) req.T = sessionToken return await this.sendRequest(req) }, - async handshake() { - return await this.sendRequest({ a: ACT.hs }) + handshake() { + const port = this.port + if (port && this.handshakePort === port && this.handshakeResult) { + return Promise.resolve(this.handshakeResult) + } + if (port && this.handshakePort === port && this.handshakePromise) { + return this.handshakePromise + } + const promise = this.sendRequest({ a: ACT.hs }) + .then((response) => { + if (this.port === port && http.isOk(response && response.s)) { + this.handshakePort = port + this.handshakeResult = response + } + return response + }) + .finally(() => { + if (this.handshakePromise === promise) this.handshakePromise = null + }) + this.handshakePort = port + this.handshakePromise = promise + return promise }, async sendReport(deviceId, reportId, data) { return await this.sendPacked((reqId) => diff --git a/addon/js/background/state_ops.js b/addon/js/background/state_ops.js index 5df6f25..430ec98 100644 --- a/addon/js/background/state_ops.js +++ b/addon/js/background/state_ops.js @@ -229,6 +229,54 @@ function getDeviceSessionOwner(deviceId, token) { return deviceSessions.get(deviceId)?.get(token) || null } + /** + * Updates the data-plane state for one exact session endpoint. + * @param {number} deviceId + * @param {string} token + * @param {object} port + * @param {object|null} plane + * @returns {boolean} + */ + function setDeviceSessionPlane(deviceId, token, port, plane) { + const owner = deviceSessions.get(deviceId)?.get(token) + if (!owner || owner.port !== port) return false + owner.plane = plane + return true + } + /** + * Collects tab-wide plane state from authoritative session owners. + * @param {number} tabId + * @param {string} [origin] + * @returns {object[]} + */ + function collectDevicePlaneStatuses(tabId, origin) { + const statuses = [] + for (const [deviceId, byToken] of deviceSessions) { + for (const [token, owner] of byToken) { + if (owner.tabId !== tabId || (origin && owner.origin !== origin) || !owner.plane) continue + statuses.push({ deviceId, token, ...owner.plane }) + } + } + return statuses + } + /** + * Collects open device IDs from authoritative tab session ownership. + * @param {number} tabId + * @param {string} [origin] + * @returns {string[]} + */ + function collectOpenDeviceIdsForTab(tabId, origin) { + const ids = new Set() + for (const [deviceId, byToken] of deviceSessions) { + for (const owner of byToken.values()) { + if (owner.tabId === tabId && (!origin || owner.origin === origin)) { + ids.add(String(deviceId)) + break + } + } + } + return [...ids] + } /** * Collects session tokens for one trusted frame generation. @@ -516,6 +564,9 @@ collectDeviceSessionsForTab, collectDeviceSessionsForFrame, getDeviceSessionOwner, + setDeviceSessionPlane, + collectDevicePlaneStatuses, + collectOpenDeviceIdsForTab, clearDeviceSessions, clearDeviceSessionsForOrigin, clearDeviceSessionsForTab, diff --git a/addon/js/content/isolated/bridge.js b/addon/js/content/isolated/bridge.js index 09ad7a9..985c419 100644 --- a/addon/js/content/isolated/bridge.js +++ b/addon/js/content/isolated/bridge.js @@ -347,20 +347,6 @@ return clientSeparator < 0 ? 'window' : rest.slice(clientSeparator + 1) } - /** - * @param {string} [origin] - * @returns {Set} - */ - function getOpenDeviceIds(origin) { - const ids = new Set() - for (const [port, context] of frameContextByPort) { - if (origin && context.origin !== origin) continue - const sessions = clientSessions.get(port) - if (!sessions) continue - for (const deviceId of sessions.keys()) ids.add(deviceId) - } - return ids - } /** * @param {FrameContext} context * @returns {Array<{port: MessagePort, sessions: Map, clientKey: string}>} @@ -423,57 +409,19 @@ } browser.runtime.onMessage.addListener((request, sender, sendResponse) => { - const origin = typeof request.origin === 'string' ? request.origin : '' - const knownOrigin = !origin || collectFrameOrigins().includes(origin) if ( - !knownOrigin && - (request.action === 'getOpenDeviceIds' || request.action === 'getDataPlaneStatus') - ) { - sendResponse( - request.action === 'getOpenDeviceIds' - ? { ids: [] } - : { planes: [], defaultPlane: webhid.import('GLOBAL_DEFAULTS').dataPlane } - ) - return true - } - if (request.action === 'getFrameOrigins') { - sendResponse({ origins: collectFrameOrigins() }) - return true - } - if (request.action === 'getDataPlaneStatus') { - const planes = [] - const statusFor = (key, plane, mode) => ({ - deviceId: deviceIdForPlaneKey(key), - plane, - mode, - generation: spawnGen.get(key), - ready: readyGenerations.get(key) === spawnGen.get(key) - }) - for (const [key, transport] of deviceTransports) { - const context = contextForPlaneKey(key) - if (!context || (origin && context.origin !== origin)) continue - if (workers.has(key)) planes.push(statusFor(key, transport, 'worker')) - } - for (const key of inPageDevices) { - const context = contextForPlaneKey(key) - if (!context || (origin && context.origin !== origin)) continue - planes.push(statusFor(key, 'wt', 'inpage')) - } - for (const key of nmPlanes) { - const context = contextForPlaneKey(key) - if (!context || (origin && context.origin !== origin)) continue - planes.push(statusFor(key, 'nm', null)) - } - loadSettingsForOrigin(origin || window.location.origin) - .then((store) => sendResponse({ planes, defaultPlane: store.dataPlane })) - .catch(() => - sendResponse({ - planes, - defaultPlane: webhid.import('GLOBAL_DEFAULTS').dataPlane - }) - ) - return true - } + request.action !== 'getOpenDeviceIds' && + request.action !== 'getDataPlaneStatus' && + request.action !== 'getFrameOrigins' + ) + return false + sendBackgroundRequest({ + action: request.action, + origin: typeof request.origin === 'string' ? request.origin : undefined + }) + .then(sendResponse) + .catch(() => sendResponse({ ids: [], planes: [], origins: [] })) + return true }) /** * @param {string} deviceId @@ -748,6 +696,7 @@ if (!context) return const client = clientForKey(context, clientKeyForPlaneKey(key)) if (!client) return + notifyBackgroundPlaneStatus(key, generation, true) try { client.port.postMessage({ type: 'dataPlaneReady', @@ -758,6 +707,39 @@ logger.debug('data plane ready notification failed', e) } } + /** + * Publishes exact session plane state for background aggregation. + * @param {string} key + * @param {number} generation + * @param {boolean} ready + * @param {boolean} [available] + * @returns {void} + */ + function notifyBackgroundPlaneStatus(key, generation, ready, available = true) { + const context = contextForPlaneKey(key) + if (!context) return + const clientKey = clientKeyForPlaneKey(key) + const client = clientForKey(context, clientKey) + const deviceId = Number(deviceIdForPlaneKey(key)) + const token = client?.sessions.get(deviceId) + if (!token) return + const plane = nmPlanes.has(key) + ? 'nm' + : inPageDevices.has(key) + ? 'wt' + : deviceTransports.get(key) || settingsForOrigin(context.origin).dataPlane + const mode = plane === 'nm' ? null : inPageDevices.has(key) ? 'inpage' : 'worker' + sendBackgroundRequest({ + action: 'setDataPlaneStatus', + deviceId, + sessionToken: token, + clientKey, + plane: available ? plane : null, + mode, + generation, + ready + }).catch((e) => logger.debug('data plane status update failed', e)) + } /** * @param {string} key @@ -771,6 +753,7 @@ if (!context) return const client = clientForKey(context, clientKeyForPlaneKey(key)) if (!client) return + notifyBackgroundPlaneStatus(key, generation, false, true) try { client.port.postMessage({ type: 'dataPlaneUnavailable', @@ -1984,10 +1967,9 @@ const clientKey = client.clientKey const clientPort = client.port sessions.set(deviceId, response.t) - sendBackgroundRequest({ - action: 'deviceCountChanged', - count: getOpenDeviceIds().size - }).catch((e) => logger.debug('deviceCountChanged (open) failed', e)) + sendBackgroundRequest({ action: 'deviceCountChanged' }).catch((e) => + logger.debug('deviceCountChanged (open) failed', e) + ) logger.debug('open ok deviceId=' + deviceId + ' wsPort=' + response.w) const key = planeKeyForClient(context, deviceId, clientKey) const dataPlane = settingsForOrigin(context.origin).dataPlane @@ -2018,6 +2000,7 @@ } } if (generation == null) return { accepted: false, error: 'data plane authority setup failed' } + notifyBackgroundPlaneStatus(key, generation, readyGenerations.get(key) === generation) response.clientPlaneGeneration = generation return { accepted: true } } @@ -2035,10 +2018,9 @@ logger.debug('close deviceId=' + deviceId) sessions.delete(deviceId) await despawnDataPlane(context, deviceId, { clientKey }) - sendBackgroundRequest({ - action: 'deviceCountChanged', - count: getOpenDeviceIds().size - }).catch((e) => logger.debug('deviceCountChanged (close) failed', e)) + sendBackgroundRequest({ action: 'deviceCountChanged' }).catch((e) => + logger.debug('deviceCountChanged (close) failed', e) + ) } /** * @@ -2429,11 +2411,11 @@ logger.warn('global reset: clearing daemon state') resetAuthorityState() .catch((e) => logger.debug('authority reset failed', e)) - .finally(() => { - sendBackgroundRequest({ action: 'deviceCountChanged', count: 0 }).catch((e) => + .finally(() => + sendBackgroundRequest({ action: 'deviceCountChanged' }).catch((e) => logger.debug('deviceCountChanged (reset) failed', e) ) - }) + ) } /** diff --git a/addon/js/internal/pages/popup/index.js b/addon/js/internal/pages/popup/index.js index cab6fa7..8cb56da 100644 --- a/addon/js/internal/pages/popup/index.js +++ b/addon/js/internal/pages/popup/index.js @@ -349,8 +349,9 @@ let planes = [] if (origin && tab && tab.id != null) { try { - const r = await browser.tabs.sendMessage(tab.id, { + const r = await browser.runtime.sendMessage({ action: 'getDataPlaneStatus', + tabId: tab.id, origin }) planes = (r && r.planes) || [] @@ -548,8 +549,9 @@ /** @type {Set} */ let openIds = new Set() try { - const r = await browser.tabs.sendMessage(tab.id, { + const r = await browser.runtime.sendMessage({ action: 'getOpenDeviceIds', + tabId: tab.id, origin }) const rIds = r != null ? r.ids : undefined diff --git a/tests/browser/page-action.spec.ts b/tests/browser/page-action.spec.ts index 4bdb807..f813e64 100644 --- a/tests/browser/page-action.spec.ts +++ b/tests/browser/page-action.spec.ts @@ -165,40 +165,35 @@ test.describe('extension action surfaces', () => { const activeOrigin = new URL(pageUrl('/')).origin const selectedOrigin = `${activeOrigin}-selected` await sharedPage.goto(pageUrl('/test-page.html'), { waitUntil: 'domcontentloaded' }) - await page.addInitScript((origin) => { - const calls: Array<{ action: string; origin: unknown }> = [] - Object.defineProperty(globalThis, '__popupStatusCalls', { value: calls }) - const runtimeSendMessage = browser.runtime.sendMessage as unknown as ( - message: unknown - ) => Promise - const tabsSendMessage = browser.tabs.sendMessage as unknown as ( - tabId: number, - message: unknown - ) => Promise - browser.runtime.sendMessage = async (message) => { - const request = message as { action?: unknown } - if (request.action === 'getFrameOrigins') - return { origins: [origin.active, origin.selected] } - if (request.action === 'getBackendStatus') - return { nmConnected: true, daemonReachable: true, hidPermission: 0 } - if (request.action === 'getPairedDevices') return { success: true, hashes: ['1'] } - return runtimeSendMessage(message) - } - browser.tabs.sendMessage = async (tabId, message) => { - const request = message as { action?: unknown; origin?: unknown } - const action = typeof request.action === 'string' ? request.action : '' - if (action === 'getDataPlaneStatus' || action === 'getOpenDeviceIds') - calls.push({ action, origin: request.origin }) - if (action === 'getDataPlaneStatus') { - return request.origin === origin.selected - ? { planes: [{ deviceId: '1', plane: 'ws', mode: 'worker' }], defaultPlane: 'nm' } - : { planes: [], defaultPlane: 'nm' } + await page.addInitScript( + (origin) => { + const calls: Array<{ action: string; origin: unknown }> = [] + Object.defineProperty(globalThis, '__popupStatusCalls', { value: calls }) + const runtimeSendMessage = browser.runtime.sendMessage as unknown as ( + message: unknown + ) => Promise + browser.runtime.sendMessage = async (message) => { + const request = message as { action?: unknown; origin?: unknown } + if (request.action === 'getFrameOrigins') + return { origins: [origin.active, origin.selected] } + if (request.action === 'getBackendStatus') + return { nmConnected: true, daemonReachable: true, hidPermission: 0 } + if (request.action === 'getPairedDevices') return { success: true, hashes: ['1'] } + if (request.action === 'getDataPlaneStatus') { + calls.push({ action: 'getDataPlaneStatus', origin: request.origin }) + return request.origin === origin.selected + ? { planes: [{ deviceId: '1', plane: 'ws', mode: 'worker' }], defaultPlane: 'nm' } + : { planes: [], defaultPlane: 'nm' } + } + if (request.action === 'getOpenDeviceIds') { + calls.push({ action: 'getOpenDeviceIds', origin: request.origin }) + return request.origin === origin.selected ? { ids: ['1'] } : { ids: [] } + } + return runtimeSendMessage(message) } - if (action === 'getOpenDeviceIds') - return request.origin === origin.selected ? { ids: ['1'] } : { ids: [] } - return tabsSendMessage(tabId, message) - } - }, { active: activeOrigin, selected: selectedOrigin }) + }, + { active: activeOrigin, selected: selectedOrigin } + ) const popupUrl = await backgroundPage.evaluate(() => browser.runtime.getURL('js/internal/pages/popup/index.html') ) @@ -232,9 +227,7 @@ test.describe('extension action surfaces', () => { ) const calls = await page.evaluate(() => { const value = (globalThis as unknown as { __popupStatusCalls?: unknown }).__popupStatusCalls - return Array.isArray(value) - ? (value as Array<{ action: string; origin: unknown }>) - : [] + return Array.isArray(value) ? (value as Array<{ action: string; origin: unknown }>) : [] }) const afterSelection = calls.slice(before) expect(afterSelection).toEqual( diff --git a/tests/browser/permissions-policy.spec.ts b/tests/browser/permissions-policy.spec.ts index 0de95fe..8b3951b 100644 --- a/tests/browser/permissions-policy.spec.ts +++ b/tests/browser/permissions-policy.spec.ts @@ -213,6 +213,30 @@ test.describe('Cross-origin iframe', () => { expect(raw!.hidUndefined).toBe(false) }) + test('sandboxed iframe keeps an opaque security origin', async ({ page, pageUrl, crossUrl }) => { + await page.goto(pageUrl('/iframe-parent'), { + waitUntil: 'domcontentloaded', + timeout: 15000 + }) + await page.evaluate(() => { + document.documentElement.dataset.opaqueOrigin = '' + window.addEventListener('message', (event) => { + if (event.data === 'opaque-origin-probe') + document.documentElement.dataset.opaqueOrigin = event.origin + }) + }) + await page.evaluate((src) => { + const frame = document.createElement('iframe') + frame.id = 'opaque-sandbox' + frame.setAttribute('sandbox', 'allow-scripts') + frame.src = src + '/iframe-child-no-allow' + document.body.appendChild(frame) + }, crossUrl('')) + const frame = await frameWithId(page, 'opaque-sandbox', '/iframe-child-no-allow') + await frame.evaluate(() => window.parent.postMessage('opaque-origin-probe', '*')) + await expect.poll(() => page.locator('html').getAttribute('data-opaque-origin')).toBe('null') + expect((await readFrameResult(frame))?.queryHid).toBe('denied') + }) test('B2: top-level hid=() denies a delegated cross-origin child', async ({ page, pageUrl, diff --git a/tests/e2e/input-report-fanout.spec.ts b/tests/e2e/input-report-fanout.spec.ts index 49bf047..58ded7a 100644 --- a/tests/e2e/input-report-fanout.spec.ts +++ b/tests/e2e/input-report-fanout.spec.ts @@ -272,6 +272,7 @@ test.describe.serial('Public input report fan-out', () => { value: () => reports }) }) + await waitForPlaneCount(backgroundPage, 2) sendInput(vendorDevice, 1, PACKET) await sharedPage.waitForFunction( () => (window as typeof window & { __getReports?: () => number }).__getReports?.() === 1, diff --git a/tests/unit/nm-lifetime.test.js b/tests/unit/nm-lifetime.test.js index 30416d6..59943b1 100644 --- a/tests/unit/nm-lifetime.test.js +++ b/tests/unit/nm-lifetime.test.js @@ -5,20 +5,44 @@ import { runInNewContext } from 'node:vm' const source = readFileSync(new URL('../../addon/js/background/nm.js', import.meta.url), 'utf8') -function loadNativeMessaging() { +function loadNativeMessaging({ deferHandshake = false } = {}) { const exports = {} const ports = [] const ownership = { cleared: 0, broadcasts: 0 } const context = { globalThis: null, + setTimeout, + clearTimeout, browser: { runtime: { connectNative(name) { const disconnectListeners = [] + const messageListeners = [] const port = { name, - onMessage: { addListener() {} }, - onDisconnect: { addListener(listener) { disconnectListeners.push(listener) } }, + postMessage(message) { + if (message.n == null) return + port.handshakeCalls += 1 + port.lastHandshake = message + if (!deferHandshake) port.respondHandshake() + }, + handshakeCalls: 0, + lastHandshake: null, + onMessage: { + addListener(listener) { + messageListeners.push(listener) + } + }, + onDisconnect: { + addListener(listener) { + disconnectListeners.push(listener) + } + }, + respondHandshake() { + for (const listener of messageListeners) { + listener({ n: port.lastHandshake.n, s: 200, w: 123, N: 'nonce' }) + } + }, disconnect() { for (const listener of disconnectListeners) listener() } @@ -40,22 +64,51 @@ function loadNativeMessaging() { PKG_SEND_FEATURE_REPORT: 4, EVT_CONNECT: 1, EVT_DISCONNECT: 2, - buildPackedSend() { return { toBase64() { return '' } } } + buildPackedSend() { + return { + toBase64() { + return '' + } + } + } } } if (name === 'bgState') return { deviceCache: [] } if (name === 'bgStorage') return { saveDeviceInfo() {} } if (name === 'bgStateOps') { return { - tabsForEvent() { return null }, - broadcastGlobalReset() { ownership.broadcasts++ }, - clearAuthorityOwnership() { ownership.cleared++ }, + tabsForEvent() { + return null + }, + collectDeviceSessionOwners() { + return [] + }, + broadcastGlobalReset() { + ownership.broadcasts++ + }, + clearAuthorityOwnership() { + ownership.cleared++ + }, clearDeviceOwnership() {}, - forTabsOfOrigin() { return Promise.resolve() } + forTabsOfOrigin() { + return Promise.resolve() + } + } + } + if (name === 'http') + return { + isOk() { + return true + } + } + if (name === 'content-ports') { + return { + postToContentPorts() { + return new Set() + }, + postToContentPort() {} } } - if (name === 'http') return { isOk() { return true } } - if (name === 'content-ports') return { postToContentPorts() { return new Set() } } throw new Error('unexpected import: ' + name) }, export(name, value) { @@ -73,7 +126,11 @@ test('host switch retires authority once and ignores stale disconnect', async () await nativeMessaging.connect() const oldPort = ports[0] let pendingResult - nativeMessaging.pending.set(1, { resolve(value) { pendingResult = value } }) + nativeMessaging.pending.set(1, { + resolve(value) { + pendingResult = value + } + }) nativeMessaging.reconnectWithNewHost() @@ -87,3 +144,20 @@ test('host switch retires authority once and ignores stale disconnect', async () assert.equal(ownership.cleared, 1) assert.equal(ownership.broadcasts, 1) }) + +test('handshake shares cached authority across frame requests', async () => { + const { nativeMessaging, ports } = loadNativeMessaging({ deferHandshake: true }) + await nativeMessaging.connect() + + const first = nativeMessaging.handshake() + const second = nativeMessaging.handshake() + assert.equal(ports[0].port.handshakeCalls, 1) + + ports[0].port.respondHandshake() + assert.deepEqual(await Promise.all([first, second]), [ + { n: 1, s: 200, w: 123, N: 'nonce' }, + { n: 1, s: 200, w: 123, N: 'nonce' } + ]) + await nativeMessaging.handshake() + assert.equal(ports[0].port.handshakeCalls, 1) +}) diff --git a/tests/unit/state-ops.test.js b/tests/unit/state-ops.test.js index d2f38e5..5c73184 100644 --- a/tests/unit/state-ops.test.js +++ b/tests/unit/state-ops.test.js @@ -275,6 +275,57 @@ test('physical ownership reset removes every session for one device', () => { assert.equal(ops.isFrameLifetimeActive(11, 'frame-a'), true) assert.equal(ops.isFrameLifetimeActive(11, 'frame-b'), true) }) +test('tab aggregation spans exact frame endpoints', () => { + const { ops } = loadStateOps() + const topPort = {} + const childPort = {} + ops.registerFrameLifetime(11, 'frame-top') + ops.registerFrameLifetime(11, 'frame-child') + ops.registerDeviceSession(7, 'session-top', { + tabId: 11, + origin: 'https://a.test', + frameKey: 'frame-top', + port: topPort + }) + ops.registerDeviceSession(7, 'session-child', { + tabId: 11, + origin: 'https://a.test', + frameKey: 'frame-child', + port: childPort + }) + ops.setDeviceSessionPlane(7, 'session-top', topPort, { + plane: 'nm', + mode: null, + generation: 1, + ready: true + }) + ops.setDeviceSessionPlane(7, 'session-child', childPort, { + plane: 'ws', + mode: 'worker', + generation: 2, + ready: true + }) + + assert.equal(JSON.stringify(ops.collectOpenDeviceIdsForTab(11)), JSON.stringify(['7'])) + assert.equal( + JSON.stringify(ops.collectOpenDeviceIdsForTab(11, 'https://a.test')), + JSON.stringify(['7']) + ) + assert.equal( + JSON.stringify(ops.collectDevicePlaneStatuses(11, 'https://a.test')), + JSON.stringify([ + { deviceId: 7, token: 'session-top', plane: 'nm', mode: null, generation: 1, ready: true }, + { + deviceId: 7, + token: 'session-child', + plane: 'ws', + mode: 'worker', + generation: 2, + ready: true + } + ]) + ) +}) test('exact endpoint cleanup cannot retire a replacement lifetime', async () => { const { ops, deviceSessions, deviceTabMap } = loadStateOps() ops.registerFrameLifetime(11, 'endpoint-old') From 8c8306bd429cd239b3dfbaacb1acb7c1c4a82758 Mon Sep 17 00:00:00 2001 From: Kazoku Date: Sun, 13 Sep 2026 18:47:56 +0700 Subject: [PATCH 03/26] fix(addon): harden frame authority lifetimes --- addon/js/background/messages.js | 36 +++++--- addon/js/background/nm.js | 22 ++--- addon/js/background/state_ops.js | 36 +++++++- addon/js/content/isolated/bridge.js | 98 ++++++++++++++++------ addon/js/content/main/index.js | 39 +++++++-- tests/unit/frame-endpoint-topology.test.js | 7 ++ tests/unit/nm-lifetime.test.js | 22 ++++- tests/unit/state-ops.test.js | 3 + 8 files changed, 198 insertions(+), 65 deletions(-) diff --git a/addon/js/background/messages.js b/addon/js/background/messages.js index b975713..37b2f18 100644 --- a/addon/js/background/messages.js +++ b/addon/js/background/messages.js @@ -40,6 +40,7 @@ setDeviceSessionPlane, collectDevicePlaneStatuses, collectOpenDeviceIdsForTab, + setBadgeRefresh, closeForCleanup } = webhid.import('bgStateOps') const { urlOrigin, frameKey, documentFrameKey } = webhid.import('bgCsp') @@ -52,6 +53,16 @@ /** @type {object|null} */ let actionApi = null + /** + * Projects authoritative tab session ownership onto the badge. + * @param {number} tabId + * @returns {void} + */ + function refreshTabDeviceBadge(tabId) { + if (!actionApi || tabId == null) return + const count = collectOpenDeviceIdsForTab(tabId).length + actionApi.setBadgeText({ text: count > 0 ? String(count) : '', tabId }) + } let nextEndpointId = 0 /** @@ -83,6 +94,19 @@ frameEndpoints.delete(port) return null } + try { + port.postMessage({ + action: 'endpointMetadata', + endpointId: endpoint.id, + tabId: endpoint.tabId, + frameId: endpoint.frameId, + documentId: endpoint.documentId, + origin: endpoint.origin, + url: endpoint.url + }) + } catch { + void 0 + } return endpoint } /** @@ -823,16 +847,7 @@ * @returns {boolean} */ function handleDeviceCountChanged(request, sender) { - if (actionApi) { - const tabId = sender.tab != null ? sender.tab.id : undefined - if (tabId != null) { - const count = collectOpenDeviceIdsForTab(tabId).length - actionApi.setBadgeText({ - text: count > 0 ? String(count) : '', - tabId - }) - } - } + refreshTabDeviceBadge(sender.tab?.id) return false } @@ -1409,6 +1424,7 @@ */ function registerMessageHandlers(deps) { actionApi = deps.actionApi + setBadgeRefresh(refreshTabDeviceBadge) browser.runtime.onMessage.addListener((request, sender, sendResponse) => { const handler = HANDLERS[request.action] if (!handler) return false diff --git a/addon/js/background/nm.js b/addon/js/background/nm.js index 3e24154..7794818 100644 --- a/addon/js/background/nm.js +++ b/addon/js/background/nm.js @@ -47,7 +47,6 @@ lastError: null, handshakePromise: null, handshakePort: null, - handshakeResult: null, /** Per-request deadline for NM requests (see sendFrame). */ REQUEST_TIMEOUT_MS: 30000, @@ -170,7 +169,6 @@ this.port = null this.handshakePromise = null this.handshakePort = null - this.handshakeResult = null for (const [, p] of this.pending) p.resolve({ s: 503 }) this.pending.clear() clearAuthorityOwnership() @@ -282,23 +280,15 @@ }, handshake() { const port = this.port - if (port && this.handshakePort === port && this.handshakeResult) { - return Promise.resolve(this.handshakeResult) - } if (port && this.handshakePort === port && this.handshakePromise) { return this.handshakePromise } - const promise = this.sendRequest({ a: ACT.hs }) - .then((response) => { - if (this.port === port && http.isOk(response && response.s)) { - this.handshakePort = port - this.handshakeResult = response - } - return response - }) - .finally(() => { - if (this.handshakePromise === promise) this.handshakePromise = null - }) + const promise = this.sendRequest({ a: ACT.hs }).finally(() => { + if (this.handshakePromise === promise) { + this.handshakePromise = null + this.handshakePort = null + } + }) this.handshakePort = port this.handshakePromise = promise return promise diff --git a/addon/js/background/state_ops.js b/addon/js/background/state_ops.js index 430ec98..fd4c4b0 100644 --- a/addon/js/background/state_ops.js +++ b/addon/js/background/state_ops.js @@ -3,6 +3,23 @@ const { deviceTabMap, deviceSessions, frameLifetimes, orphanCleanup } = webhid.import('bgState') const CLEANUP_ALREADY_GONE = 404 + /** @type {((tabId: number) => void)|null} */ + let badgeRefresh = null + /** + * Installs the background badge projection callback. + * @param {(tabId: number) => void} callback + * @returns {void} + */ + function setBadgeRefresh(callback) { + badgeRefresh = callback + } + /** + * @param {number|null|undefined} tabId + * @returns {void} + */ + function refreshBadge(tabId) { + if (badgeRefresh && tabId != null) badgeRefresh(tabId) + } /** * Whether a daemon close response proves that a session is no longer live. @@ -143,9 +160,8 @@ if ( !isFrameLifetimeActive(owner.tabId, frameKey) && !registerFrameLifetime(owner.tabId, frameKey) - ) { + ) return false - } let byToken = deviceSessions.get(deviceId) if (!byToken) { byToken = new Map() @@ -160,6 +176,7 @@ clientKey: owner.clientKey || '', port: owner.port || null }) + refreshBadge(owner.tabId) logger.debug('register session device ' + deviceId + ' tab ' + owner.tabId) return true } @@ -174,8 +191,10 @@ if (!deviceId || !token) return const byToken = deviceSessions.get(deviceId) if (!byToken) return + const owner = byToken.get(token) byToken.delete(token) if (byToken.size === 0) deviceSessions.delete(deviceId) + refreshBadge(owner?.tabId) } /** @@ -535,10 +554,17 @@ * @returns {void} */ function clearAuthorityOwnership() { + const tabs = new Set() + for (const byToken of deviceSessions.values()) { + for (const owner of byToken.values()) { + if (owner.tabId != null) tabs.add(owner.tabId) + } + } deviceTabMap.clear() deviceSessions.clear() frameLifetimes.clear() orphanCleanup.clear() + for (const tabId of tabs) refreshBadge(tabId) } /** @@ -547,13 +573,19 @@ * @returns {void} */ function clearDeviceOwnership(deviceId) { + const tabs = new Set() + for (const owner of deviceSessions.get(deviceId)?.values() || []) { + if (owner.tabId != null) tabs.add(owner.tabId) + } deviceTabMap.delete(deviceId) deviceSessions.delete(deviceId) for (const [token, entry] of orphanCleanup) { if (entry.deviceId === deviceId) orphanCleanup.delete(token) } + for (const tabId of tabs) refreshBadge(tabId) } webhid.export('bgStateOps', { + setBadgeRefresh, tabsForEvent, registerDeviceTab, registerDeviceSession, diff --git a/addon/js/content/isolated/bridge.js b/addon/js/content/isolated/bridge.js index 985c419..4d5af86 100644 --- a/addon/js/content/isolated/bridge.js +++ b/addon/js/content/isolated/bridge.js @@ -28,6 +28,12 @@ let nextHandshakeReqId = 0 const handshakePending = new Map() const pickerResultHandlers = new Map() + let authorityOrigin = '' + let authorityFailed = false + let resolveAuthorityReady = null + const authorityReady = new Promise((resolve) => { + resolveAuthorityReady = resolve + }) /** @returns {void} */ function pumpControlQueue() { if (controlPending || controlQueue.length === 0) return @@ -68,6 +74,10 @@ }) } controlPort.onMessage.addListener((message) => { + if (message && message.action === 'endpointMetadata') { + initializeAuthorityMetadata(message) + return + } if (message && message.action === 'pickerResult') { const handler = pickerResultHandlers.get(message.requestId) if (handler) handler(message) @@ -101,7 +111,7 @@ return } if (message && message.action === 'allowedDevicesChanged') { - const origin = message.origin || window.location.origin + const origin = message.origin || authorityOrigin allowedByOrigin.set(origin, new Set(message.deviceIds || [])) loadedOrigins.add(origin) flushAllowedDeviceIdsQueue(origin) @@ -128,6 +138,8 @@ }) controlPort.onDisconnect.addListener(() => { const error = new Error('background port disconnected') + authorityFailed = true + settleAuthorityReady() for (const pending of handshakePending.values()) pending.reject(error) handshakePending.clear() if (controlPending) { @@ -172,7 +184,7 @@ * Marks the current tab as using WebHID so its page action becomes visible. * @returns {void} */ - function markPageActionUsed(origin = window.location.origin) { + function markPageActionUsed(origin = authorityOrigin) { if (pageActionMarked || settingsForOrigin(origin).hidePageAction) return pageActionMarked = true sendBackgroundRequest({ action: 'showPageAction' }).catch(() => { @@ -282,7 +294,7 @@ frameContext = acceptBootstrapPort( pagePort, window, - window.location.origin, + authorityOrigin || '', browserFrameIdentity(window) ) @@ -577,7 +589,7 @@ /** @type {import("./types.js").SettingsStore} */ const settings = createSettingsStore(webhid.import('GLOBAL_DEFAULTS')) /** @type {Map} */ - const settingsByOrigin = new Map([[window.location.origin, settings]]) + const settingsByOrigin = new Map() /** @type {Map>} */ const settingsLoads = new Map() /** @@ -611,7 +623,31 @@ settingsLoads.set(origin, load) return load } - installSettingsListeners(window.location.origin, settings) + /** @returns {void} */ + function settleAuthorityReady() { + if (!resolveAuthorityReady) return + resolveAuthorityReady() + resolveAuthorityReady = null + } + /** + * Applies browser-authenticated endpoint metadata before origin-sensitive work. + * @param {object} metadata + * @returns {void} + */ + function initializeAuthorityMetadata(metadata) { + if (authorityOrigin || !metadata || typeof metadata.origin !== 'string' || !metadata.origin) + return + authorityOrigin = metadata.origin + if (frameContext) { + frameContext.origin = authorityOrigin + if (Number.isInteger(metadata.frameId)) frameContext.frameId = metadata.frameId + if (typeof metadata.documentId === 'string' && metadata.documentId) + frameContext.documentId = metadata.documentId + } + settingsByOrigin.set(authorityOrigin, settings) + installSettingsListeners(authorityOrigin, settings) + settleAuthorityReady() + } /** @type {Map} */ const spawnGen = new Map() /** @@ -1399,25 +1435,30 @@ } ;(async () => { + let resp = null try { - const resp = await sendHandshakeRequest() - if (http.isOk(resp.s) && resp.w) { - wsPort = resp.w - wsNonce = resp.N || null - wtPort = resp.W || null - wtCertHash = resp.H || null - if (!wsNonce) { - logger.warn( - 'handshake: daemon did not send ws_nonce (old version?); ' + - 'WS data plane will fall back to NM' - ) - } - await loadSettingsForOrigin(window.location.origin) - loadAllowedDeviceIds(window.location.origin) - } + resp = await sendHandshakeRequest() } catch (e) { logger.warn('handshake failed:', e.message) } + await authorityReady + if (!authorityOrigin || authorityFailed) { + logger.warn('endpoint authority metadata unavailable') + return + } + if (!http.isOk(resp && resp.s) || !resp.w) return + wsPort = resp.w + wsNonce = resp.N || null + wtPort = resp.W || null + wtCertHash = resp.H || null + if (!wsNonce) { + logger.warn( + 'handshake: daemon did not send ws_nonce (old version?); ' + + 'WS data plane will fall back to NM' + ) + } + await loadSettingsForOrigin(authorityOrigin) + loadAllowedDeviceIds(authorityOrigin) })() /** @@ -1611,7 +1652,7 @@ */ function getRequestOrigin(data) { const port = requestPortMap.get(data.id) - return frameContextForPort(port)?.origin || window.location.origin + return frameContextForPort(port)?.origin || authorityOrigin } /** @@ -1888,7 +1929,7 @@ const filters = payload.filters || [] const exclusionFilters = payload.exclusionFilters || [] const context = frameContextForPort(requestPort) - const origin = context ? context.origin : window.location.origin + const origin = context ? context.origin : authorityOrigin const originSettings = await loadSettingsForOrigin(origin) const pickerMode = isChromium && originSettings.devicePickerMode === 'pageAction' @@ -2252,11 +2293,16 @@ */ async function handleRequest(data, ports, _source, requestPort) { if (!data || data.id === undefined) return + await authorityReady + if (authorityFailed || !authorityOrigin) { + replyToPage({ type: 'response', id: data.id, result: { s: 503 } }) + return + } logger.debug('req action=' + data.action + ' id=' + data.id) const requestContext = frameContextForPort(requestPort) if (PAGE_ACTION_API_ACTIONS.has(data.action)) { - markPageActionUsed(requestContext ? requestContext.origin : window.location.origin) + markPageActionUsed(requestContext ? requestContext.origin : authorityOrigin) } const handler = REQUEST_HANDLERS[data.action] @@ -2734,15 +2780,15 @@ if (!parsed) continue if (parsed.scope === 'global') { for (const store of settingsByOrigin.values()) store.set({ [parsed.name]: change.newValue }) - } else { - settingsForOrigin(parsed.origin).set({ [parsed.name]: change.newValue }) + } else if (authorityOrigin && parsed.origin === authorityOrigin) { + settingsForOrigin(authorityOrigin).set({ [parsed.name]: change.newValue }) } } }) browser.runtime.onMessage.addListener((message) => { if (message.action === 'allowedDevicesChanged' && Array.isArray(message.deviceIds)) { - const origin = message.origin || window.location.origin + const origin = message.origin || authorityOrigin allowedByOrigin.set(origin, new Set(message.deviceIds)) loadedOrigins.add(origin) flushAllowedDeviceIdsQueue(origin) diff --git a/addon/js/content/main/index.js b/addon/js/content/main/index.js index 2659442..4ffa9d0 100644 --- a/addon/js/content/main/index.js +++ b/addon/js/content/main/index.js @@ -845,6 +845,7 @@ response: handleResponseMessage, settings: (data) => { settings.set(data.settings || {}) + markSettingsReady() }, event: (data) => { dispatchDeviceEvent(data.event) @@ -934,17 +935,38 @@ const defs = GLOBAL_DEFAULTS const settings = createSettingsStore(defs) - + let resolveSettingsReady = null + let settingsReadySettled = false + const settingsReady = new NativePromise((resolve) => { + resolveSettingsReady = resolve + }) + /** @returns {void} */ + function markSettingsReady() { + if (settingsReadySettled) return + settingsReadySettled = true + if (resolveSettingsReady) resolveSettingsReady() + resolveSettingsReady = null + } settings.on('dataPlane', (v) => logger.info('data plane changed: ' + v)) logger.bindSettings(settings) - promiseOps.then(bridgeReady, () => { - promiseOps.then(sendRequest('getSettings', {}), (result) => { - if (!result) return - settings.set(result) - logger.info('data plane: ' + settings.dataPlane) - }) - }) + promiseOps.then( + bridgeReady, + () => { + promiseOps.then( + sendRequest('getSettings', {}), + (result) => { + if (result) { + settings.set(result) + logger.info('data plane: ' + settings.dataPlane) + } + markSettingsReady() + }, + markSettingsReady + ) + }, + markSettingsReady + ) /** @returns {object} */ function getPolicyContext() { return {} @@ -1983,6 +2005,7 @@ if (isWorker) { throw new NativeDOMException('Not allowed in worker context', 'NotSupportedError') } + await settingsReady const policy = await getPolicy() if (policy && policy.hid === 'none') { throw new NativeDOMException( diff --git a/tests/unit/frame-endpoint-topology.test.js b/tests/unit/frame-endpoint-topology.test.js index 947d6a0..74173bd 100644 --- a/tests/unit/frame-endpoint-topology.test.js +++ b/tests/unit/frame-endpoint-topology.test.js @@ -36,6 +36,13 @@ test('background owns endpoint registry and exact input fanout', () => { assert.match(nm, /collectDeviceSessionOwners\(deviceId\)/) assert.match(nm, /postToContentPort\(port/) }) +test('authority metadata gates local origin-sensitive state', () => { + assert.match(messages, /action: 'endpointMetadata'/) + assert.match(messages, /typeof sender\.origin/) + assert.match(bridge, /initializeAuthorityMetadata/) + assert.match(bridge, /await authorityReady/) + assert.match(main, /await settingsReady/) +}) test('MAIN does not bootstrap through a top WindowProxy', () => { assert.doesNotMatch(main, /nativeWindowPostMessage/) diff --git a/tests/unit/nm-lifetime.test.js b/tests/unit/nm-lifetime.test.js index 59943b1..b25d8d5 100644 --- a/tests/unit/nm-lifetime.test.js +++ b/tests/unit/nm-lifetime.test.js @@ -145,7 +145,7 @@ test('host switch retires authority once and ignores stale disconnect', async () assert.equal(ownership.broadcasts, 1) }) -test('handshake shares cached authority across frame requests', async () => { +test('handshake coalesces concurrent calls but refreshes later', async () => { const { nativeMessaging, ports } = loadNativeMessaging({ deferHandshake: true }) await nativeMessaging.connect() @@ -158,6 +158,22 @@ test('handshake shares cached authority across frame requests', async () => { { n: 1, s: 200, w: 123, N: 'nonce' }, { n: 1, s: 200, w: 123, N: 'nonce' } ]) - await nativeMessaging.handshake() - assert.equal(ports[0].port.handshakeCalls, 1) + const third = nativeMessaging.handshake() + assert.equal(ports[0].port.handshakeCalls, 2) + ports[0].port.respondHandshake() + assert.deepEqual(await third, { n: 2, s: 200, w: 123, N: 'nonce' }) +}) + +test('handshake after port replacement uses the new port', async () => { + const { nativeMessaging, ports } = loadNativeMessaging({ deferHandshake: true }) + await nativeMessaging.connect() + const first = nativeMessaging.handshake() + ports[0].port.respondHandshake() + await first + ports[0].port.disconnect() + await nativeMessaging.connect() + const second = nativeMessaging.handshake() + assert.equal(ports[1].port.handshakeCalls, 1) + ports[1].port.respondHandshake() + assert.deepEqual(await second, { n: 2, s: 200, w: 123, N: 'nonce' }) }) diff --git a/tests/unit/state-ops.test.js b/tests/unit/state-ops.test.js index 5c73184..f608a5e 100644 --- a/tests/unit/state-ops.test.js +++ b/tests/unit/state-ops.test.js @@ -277,8 +277,10 @@ test('physical ownership reset removes every session for one device', () => { }) test('tab aggregation spans exact frame endpoints', () => { const { ops } = loadStateOps() + const refreshed = [] const topPort = {} const childPort = {} + ops.setBadgeRefresh((tabId) => refreshed.push(tabId)) ops.registerFrameLifetime(11, 'frame-top') ops.registerFrameLifetime(11, 'frame-child') ops.registerDeviceSession(7, 'session-top', { @@ -293,6 +295,7 @@ test('tab aggregation spans exact frame endpoints', () => { frameKey: 'frame-child', port: childPort }) + assert.deepEqual(refreshed, [11, 11]) ops.setDeviceSessionPlane(7, 'session-top', topPort, { plane: 'nm', mode: null, From ea91da4bf16c889fb049652d688148eec5c441ae Mon Sep 17 00:00:00 2001 From: Kazoku Date: Sun, 13 Sep 2026 20:44:50 +0700 Subject: [PATCH 04/26] fix(addon): partition opaque frame persistence --- addon/js/background/messages.js | 173 ++++++++++++++++++++-------- addon/js/background/state_ops.js | 5 +- addon/js/background/storage.js | 16 ++- addon/js/content/isolated/bridge.js | 91 +++++++++++---- addon/js/utils/settings.js | 35 +++++- tests/unit/settings.test.js | 33 +++++- tests/unit/storage-origin.test.js | 48 ++++++++ 7 files changed, 321 insertions(+), 80 deletions(-) create mode 100644 tests/unit/storage-origin.test.js diff --git a/addon/js/background/messages.js b/addon/js/background/messages.js index 37b2f18..24c7233 100644 --- a/addon/js/background/messages.js +++ b/addon/js/background/messages.js @@ -5,6 +5,7 @@ const logger = webhid.import('logger') const isChromium = webhid.import('isChromium') const decodeDeviceCollections = webhid.import('decodeDeviceCollections') + const persistentSiteScope = webhid.import('persistentSiteScope') const { deviceCache, pendingPicker, @@ -65,6 +66,63 @@ } let nextEndpointId = 0 + /** + * Returns the registered top-frame endpoint for a tab. + * @param {number} tabId + * @returns {object|null} + */ + function topEndpointForTab(tabId) { + for (const endpoint of frameEndpoints.values()) { + if (endpoint.tabId === tabId && endpoint.frameId === 0) return endpoint + } + return null + } + /** + * Sends browser-authenticated endpoint metadata to its exact bridge. + * @param {object} endpoint + * @returns {void} + */ + function sendEndpointMetadata(endpoint) { + try { + endpoint.port.postMessage({ + action: 'endpointMetadata', + endpointId: endpoint.id, + tabId: endpoint.tabId, + frameId: endpoint.frameId, + documentId: endpoint.documentId, + origin: endpoint.origin, + url: endpoint.url, + persistentOrigin: endpoint.persistentOrigin + }) + } catch { + void 0 + } + } + /** + * Refreshes persistence partitions after a top-frame endpoint changes. + * @param {number} tabId + * @returns {void} + */ + function refreshEndpointPersistence(tabId) { + const top = topEndpointForTab(tabId) + for (const endpoint of frameEndpoints.values()) { + if (endpoint.tabId !== tabId) continue + const persistentOrigin = persistentSiteScope(endpoint.origin, endpoint.url, top?.origin) + if (endpoint.persistentOrigin === persistentOrigin) continue + endpoint.persistentOrigin = persistentOrigin + sendEndpointMetadata(endpoint) + } + } + /** + * Selects the trusted persistence partition for one request. + * @param {object} request + * @returns {string|null} + */ + function persistenceOriginForRequest(request) { + return Object.prototype.hasOwnProperty.call(request, 'persistentOrigin') + ? request.persistentOrigin + : request.origin || null + } /** * Registers one browser-owned exact frame endpoint. * @param {object} port @@ -87,6 +145,7 @@ documentId, origin, url, + persistentOrigin: undefined, frameKey: 'endpoint-' + nextEndpointId } frameEndpoints.set(port, endpoint) @@ -94,19 +153,7 @@ frameEndpoints.delete(port) return null } - try { - port.postMessage({ - action: 'endpointMetadata', - endpointId: endpoint.id, - tabId: endpoint.tabId, - frameId: endpoint.frameId, - documentId: endpoint.documentId, - origin: endpoint.origin, - url: endpoint.url - }) - } catch { - void 0 - } + refreshEndpointPersistence(tabId) return endpoint } /** @@ -197,27 +244,32 @@ } /** - * @param {string} origin + * @param {string} authorityOrigin + * @param {string|null} persistentOrigin * @param {number[]} deviceIds * @returns {Promise} */ - async function notifyAllowedDevicesChanged(origin, deviceIds) { - postToOriginEndpoints(origin, { action: 'allowedDevicesChanged', origin, deviceIds }) + async function notifyAllowedDevicesChanged(authorityOrigin, persistentOrigin, deviceIds) { + postToOriginEndpoints(authorityOrigin, { + action: 'allowedDevicesChanged', + origin: authorityOrigin, + persistentOrigin, + deviceIds + }) } /** - * Unpairs the devices in `toRevoke` from `origin`, closes them in the - * daemon, deletes their grant groups, and tells matching tabs. - * @param {string} origin + * @param {string|null} persistentOrigin + * @param {string} authorityOrigin * @param {Set} toRevoke * @param {object[]} memberGroups * @returns {Promise} */ - async function revokeDevices(origin, toRevoke, memberGroups) { + async function revokeDevices(persistentOrigin, authorityOrigin, toRevoke, memberGroups) { for (const deviceId of toRevoke) { - await removeAllowedDevice(origin, deviceId) + await removeAllowedDevice(persistentOrigin, deviceId) removeDeviceInfo(deviceId) - const tokens = collectDeviceSessionsForOrigin(deviceId, origin) + const tokens = collectDeviceSessionsForOrigin(deviceId, persistentOrigin) for (const token of tokens) { const owner = getDeviceSessionOwner(deviceId, token) if (owner) unregisterDeviceTab(deviceId, owner.tabId) @@ -227,14 +279,14 @@ } } await deleteGrantGroups(memberGroups.map((g) => g.id)) - const deviceIds = await getAllowedDevices(origin) + const deviceIds = await getAllowedDevices(persistentOrigin) for (const deviceId of toRevoke) { - postToOriginEndpoints(origin, { + postToOriginEndpoints(authorityOrigin, { action: 'webhidDeviceEvent', - event: { eventType: 'revoked', deviceId, origin } + event: { eventType: 'revoked', deviceId, origin: authorityOrigin } }) } - postToOriginEndpoints(origin, { action: 'allowedDevicesChanged', origin, deviceIds }) + notifyAllowedDevicesChanged(authorityOrigin, persistentOrigin, deviceIds) } /** @@ -269,7 +321,7 @@ * @returns {boolean} */ function handleEnumeratePaired(request, sender, sendResponse) { - const origin = request.origin || '' + const origin = persistenceOriginForRequest(request) NativeMessaging.enumerateDevices() .then(async (response) => { if (http.isOk(response.s) && response.D) { @@ -336,11 +388,12 @@ function handleRecordGrantGroup(request, sender, sendResponse) { ;(async () => { try { - if (!request.origin || !Array.isArray(request.deviceIds)) { + const origin = persistenceOriginForRequest(request) + if (!origin || !Array.isArray(request.deviceIds)) { sendResponse({ success: false }) return } - await recordGrantGroup(request.origin, request.deviceIds) + await recordGrantGroup(origin, request.deviceIds) sendResponse({ success: true }) } catch (e) { sendResponse({ success: false, error: e.message }) @@ -358,7 +411,7 @@ function handleGetGrantGroups(request, sender, sendResponse) { ;(async () => { try { - const groups = await getGrantGroupsForOrigin(request.origin) + const groups = await getGrantGroupsForOrigin(persistenceOriginForRequest(request)) sendResponse({ success: true, groups }) } catch { sendResponse({ success: false, groups: [] }) @@ -414,12 +467,14 @@ sendResponse({ s: 403 }) return true } - const { tabId, origin, frameKey } = endpoint - if (!isFrameLifetimeActive(tabId, frameKey)) { - sendResponse({ s: 503 }) + const { tabId, frameKey } = endpoint + const authorityOrigin = endpoint.origin + const persistentOrigin = endpoint.persistentOrigin + if (!persistentOrigin || !isFrameLifetimeActive(tabId, frameKey)) { + sendResponse({ s: 403 }) return true } - getAllowedDevices(origin) + getAllowedDevices(persistentOrigin) .then((deviceIds) => { if (!deviceIds.includes(request.deviceId)) { sendResponse({ s: 403 }) @@ -429,7 +484,9 @@ .then(async (response) => { if (typeof response.P === 'number') lastHidPermission = response.P if (http.isOk(response.s) && response.i) { - const stillAllowed = (await getAllowedDevices(origin)).includes(request.deviceId) + const stillAllowed = (await getAllowedDevices(persistentOrigin)).includes( + request.deviceId + ) const ownerStillAlive = isFrameLifetimeActive(tabId, frameKey) if (!stillAllowed || !ownerStillAlive) { if (response.t) @@ -445,7 +502,8 @@ tabId, frameId: endpoint.frameId, documentId: endpoint.documentId, - origin, + origin: authorityOrigin, + persistentOrigin, frameKey, port, clientKey: request.clientKey @@ -565,8 +623,9 @@ function handleRevokeDevice(request, sender, sendResponse) { ;(async () => { try { - const origin = request.origin - if (!origin) { + const persistentOrigin = persistenceOriginForRequest(request) + const authorityOrigin = request.origin || '' + if (!persistentOrigin || !authorityOrigin) { sendResponse({ success: false, error: 'no origin' }) return } @@ -574,14 +633,14 @@ Array.isArray(request.deviceIds) && request.deviceIds.length ? request.deviceIds.map((id) => Number(id)) : [Number(request.deviceId)] - const groups = await getGrantGroupsForOrigin(origin) + const groups = await getGrantGroupsForOrigin(persistentOrigin) const memberGroups = groups.filter((g) => g.deviceIds.some((id) => targetIds.includes(id))) /** @type {Set} */ const toRevoke = new Set(targetIds) for (const g of memberGroups) { for (const id of g.deviceIds) toRevoke.add(Number(id)) } - await revokeDevices(origin, toRevoke, memberGroups) + await revokeDevices(persistentOrigin, authorityOrigin, toRevoke, memberGroups) sendResponse({ success: true }) } catch (e) { sendResponse({ success: false, error: e.message }) @@ -687,7 +746,7 @@ function handleGetPairedDevices(request, sender, sendResponse) { ;(async () => { try { - const deviceIds = await getAllowedDevices(request.origin) + const deviceIds = await getAllowedDevices(persistenceOriginForRequest(request)) sendResponse({ success: true, hashes: deviceIds }) } catch (e) { sendResponse({ success: false, error: e.message, hashes: [] }) @@ -705,9 +764,14 @@ function handlePairDevice(request, sender, sendResponse) { ;(async () => { try { - await addAllowedDevice(request.origin, request.device.deviceId) - const deviceIds = await getAllowedDevices(request.origin) - await notifyAllowedDevicesChanged(request.origin, deviceIds) + const origin = persistenceOriginForRequest(request) + if (!origin || !request.device) { + sendResponse({ success: false, hashes: [] }) + return + } + await addAllowedDevice(origin, request.device.deviceId) + const deviceIds = await getAllowedDevices(origin) + await notifyAllowedDevicesChanged(request.origin, origin, deviceIds) sendResponse({ success: true, hashes: deviceIds }) } catch (e) { sendResponse({ success: false, error: e.message, hashes: [] }) @@ -725,14 +789,17 @@ function handleUnpairDevice(request, sender, sendResponse) { ;(async () => { try { - if (request.deviceId) { - await removeAllowedDevice(request.origin, request.deviceId) - removeDeviceInfo(request.deviceId) + const origin = persistenceOriginForRequest(request) + if (!origin) { + sendResponse({ success: false, hashes: [] }) + return } - const deviceIds = await getAllowedDevices(request.origin) if (request.deviceId) { - await notifyAllowedDevicesChanged(request.origin, deviceIds) + await removeAllowedDevice(origin, request.deviceId) + removeDeviceInfo(request.deviceId) } + const deviceIds = await getAllowedDevices(origin) + if (request.deviceId) await notifyAllowedDevicesChanged(request.origin, origin, deviceIds) sendResponse({ success: true, hashes: deviceIds }) } catch (e) { sendResponse({ success: false, error: e.message }) @@ -750,7 +817,7 @@ function handleGetAllowedDevices(request, sender, sendResponse) { ;(async () => { try { - const deviceIds = await getAllowedDevices(request.origin) + const deviceIds = await getAllowedDevices(persistenceOriginForRequest(request)) sendResponse({ deviceIds }) } catch { sendResponse({ deviceIds: [] }) @@ -980,6 +1047,7 @@ .filter((endpoint) => endpoint.tabId === tabId) .sort((a, b) => a.frameId - b.frameId) for (const endpoint of endpoints) { + if (!/^https?:$/.test(new URL(endpoint.origin).protocol)) continue if (seen.has(endpoint.origin)) continue seen.add(endpoint.origin) origins.push(endpoint.origin) @@ -1441,7 +1509,9 @@ pending.resolve(request.delegated === true) return } - const effectiveRequest = endpoint ? { ...request, origin: endpoint.origin } : request + const effectiveRequest = endpoint + ? { ...request, origin: endpoint.origin, persistentOrigin: endpoint.persistentOrigin } + : request const handler = HANDLERS[effectiveRequest.action] if (!handler) return let responded = false @@ -1471,6 +1541,7 @@ port.onDisconnect.addListener(() => { if (frameEndpoints.get(port) !== endpoint) return frameEndpoints.delete(port) + refreshEndpointPersistence(endpoint.tabId) for (const [tabId, request] of pendingPicker) { if (request.port !== port && request.uiPort !== port) continue pendingPicker.delete(tabId) diff --git a/addon/js/background/state_ops.js b/addon/js/background/state_ops.js index fd4c4b0..69b765d 100644 --- a/addon/js/background/state_ops.js +++ b/addon/js/background/state_ops.js @@ -151,7 +151,7 @@ * Records one daemon session token with its browser-owned endpoint. * @param {number} deviceId * @param {string} token - * @param {{tabId: number, origin: string, frameKey?: string, clientKey?: string, frameId?: number, documentId?: string, port?: object}} owner + * @param {{tabId: number, origin: string, persistentOrigin?: string|null, frameKey?: string, clientKey?: string, frameId?: number, documentId?: string, port?: object}} owner * @returns {boolean} */ function registerDeviceSession(deviceId, token, owner) { @@ -172,6 +172,7 @@ frameId: owner.frameId, documentId: owner.documentId || null, origin: owner.origin, + persistentOrigin: owner.persistentOrigin || null, frameKey, clientKey: owner.clientKey || '', port: owner.port || null @@ -218,7 +219,7 @@ if (!byToken || !origin) return [] const tokens = [] for (const [token, owner] of byToken) { - if (owner.origin === origin) tokens.push(token) + if ((owner.persistentOrigin || owner.origin) === origin) tokens.push(token) } return tokens } diff --git a/addon/js/background/storage.js b/addon/js/background/storage.js index 790b8ac..1be9d3c 100644 --- a/addon/js/background/storage.js +++ b/addon/js/background/storage.js @@ -1,6 +1,14 @@ ;(function () { const logger = webhid.import('logger') const { deviceCache } = webhid.import('bgState') + /** + * Persistent HID grants require a non-opaque security origin. + * @param {string} origin + * @returns {boolean} + */ + function isPersistentGrantOrigin(origin) { + return typeof origin === 'string' && origin.length > 0 && origin !== 'null' + } const DB_NAME = 'webhid-store' const DB_VERSION = 2 @@ -131,6 +139,7 @@ * @returns {Promise} */ async function getAllowedDevices(origin) { + if (!isPersistentGrantOrigin(origin)) return [] const db = await openDb() const tx = db.transaction('origins', 'readonly') const range = IDBKeyRange.bound([origin, -Infinity], [origin, Infinity]) @@ -148,6 +157,7 @@ * @returns {Promise} */ async function addAllowedDevice(origin, deviceId) { + if (!isPersistentGrantOrigin(origin)) return const db = await openDb() const tx = db.transaction('origins', 'readwrite') tx.objectStore('origins').put({ origin, deviceId: Number(deviceId) }) @@ -161,6 +171,7 @@ * @returns {Promise} */ async function removeAllowedDevice(origin, deviceId) { + if (!isPersistentGrantOrigin(origin)) return const db = await openDb() const tx = db.transaction('origins', 'readwrite') tx.objectStore('origins').delete([origin, Number(deviceId)]) @@ -176,7 +187,8 @@ * @returns {Promise} */ async function recordGrantGroup(origin, deviceIds) { - if (!origin || !Array.isArray(deviceIds) || deviceIds.length < 2) return + if (!isPersistentGrantOrigin(origin) || !Array.isArray(deviceIds) || deviceIds.length < 2) + return try { const db = await openDb() const tx = db.transaction('grantGroups', 'readwrite') @@ -197,6 +209,7 @@ * @returns {Promise>} */ async function getGrantGroupsForOrigin(origin) { + if (!isPersistentGrantOrigin(origin)) return [] try { const db = await openDb() const tx = db.transaction('grantGroups', 'readonly') @@ -243,6 +256,7 @@ }) const map = new Map() for (const row of rows) { + if (!isPersistentGrantOrigin(row.origin)) continue if (!map.has(row.origin)) map.set(row.origin, []) map.get(row.origin).push(row.deviceId) } diff --git a/addon/js/content/isolated/bridge.js b/addon/js/content/isolated/bridge.js index 4d5af86..8637c0c 100644 --- a/addon/js/content/isolated/bridge.js +++ b/addon/js/content/isolated/bridge.js @@ -29,6 +29,7 @@ const handshakePending = new Map() const pickerResultHandlers = new Map() let authorityOrigin = '' + let persistentOrigin = null let authorityFailed = false let resolveAuthorityReady = null const authorityReady = new Promise((resolve) => { @@ -111,7 +112,7 @@ return } if (message && message.action === 'allowedDevicesChanged') { - const origin = message.origin || authorityOrigin + const origin = message.persistentOrigin || message.origin || authorityOrigin allowedByOrigin.set(origin, new Set(message.deviceIds || [])) loadedOrigins.add(origin) flushAllowedDeviceIdsQueue(origin) @@ -200,6 +201,7 @@ * @property {MessagePort} port * @property {Window} source * @property {string} origin + * @property {string|null} persistentOrigin * @property {number|null} frameId * @property {string|null} documentId * @property {boolean} destroyed @@ -282,6 +284,7 @@ origin, frameId: identity.frameId, documentId: identity.documentId, + persistentOrigin: null, destroyed: false, sessions: new Map() } @@ -593,13 +596,18 @@ /** @type {Map>} */ const settingsLoads = new Map() /** + * Maps authority identity to its persistent settings partition. * @param {string} origin - * @returns {import("./types.js").SettingsStore} + * @returns {string} */ + function settingsScopeForOrigin(origin) { + return origin === authorityOrigin ? persistentOrigin || '' : origin + } function settingsForOrigin(origin) { - if (settingsByOrigin.has(origin)) return settingsByOrigin.get(origin) + const scope = settingsScopeForOrigin(origin) + if (settingsByOrigin.has(scope)) return settingsByOrigin.get(scope) const store = createSettingsStore(webhid.import('GLOBAL_DEFAULTS')) - settingsByOrigin.set(origin, store) + settingsByOrigin.set(scope, store) installSettingsListeners(origin, store) return store } @@ -608,19 +616,20 @@ * @returns {Promise} */ function loadSettingsForOrigin(origin) { - const existing = settingsLoads.get(origin) + const scope = settingsScopeForOrigin(origin) + const existing = settingsLoads.get(scope) if (existing) return existing - const load = loadEffectiveSettings(origin) + const load = loadEffectiveSettings(scope) .then((values) => { const store = settingsForOrigin(origin) store.set(values) return store }) .catch((error) => { - logger.warn('load settings failed for', origin, ':', error.message) + logger.warn('load settings failed for', scope, ':', error.message) return settingsForOrigin(origin) }) - settingsLoads.set(origin, load) + settingsLoads.set(scope, load) return load } /** @returns {void} */ @@ -635,17 +644,36 @@ * @returns {void} */ function initializeAuthorityMetadata(metadata) { - if (authorityOrigin || !metadata || typeof metadata.origin !== 'string' || !metadata.origin) - return + if (!metadata || typeof metadata.origin !== 'string' || !metadata.origin) return + if (authorityOrigin && authorityOrigin !== metadata.origin) return + const nextPersistentOrigin = + typeof metadata.persistentOrigin === 'string' && metadata.persistentOrigin + ? metadata.persistentOrigin + : null + const firstInitialization = !authorityOrigin + const previousPersistentOrigin = persistentOrigin + const scopeChanged = persistentOrigin !== nextPersistentOrigin authorityOrigin = metadata.origin + persistentOrigin = nextPersistentOrigin if (frameContext) { frameContext.origin = authorityOrigin + frameContext.persistentOrigin = persistentOrigin if (Number.isInteger(metadata.frameId)) frameContext.frameId = metadata.frameId if (typeof metadata.documentId === 'string' && metadata.documentId) frameContext.documentId = metadata.documentId } - settingsByOrigin.set(authorityOrigin, settings) - installSettingsListeners(authorityOrigin, settings) + if (firstInitialization || scopeChanged) { + settingsByOrigin.clear() + settingsLoads.clear() + settingsByOrigin.set(persistentOrigin || '', settings) + installSettingsListeners(authorityOrigin, settings) + if (scopeChanged) { + allowedByOrigin.delete(previousPersistentOrigin || '') + loadedOrigins.delete(previousPersistentOrigin || '') + loadAllowedDeviceIds(persistentOrigin || '') + } + if (!firstInitialization) void loadSettingsForOrigin(authorityOrigin) + } settleAuthorityReady() } /** @type {Map} */ @@ -808,6 +836,14 @@ /** @type {Map>} */ const allowedLoads = new Map() const allowedDeviceIdsQueue = [] + /** + * Returns whether an origin may own persistent HID grant state. + * @param {string} origin + * @returns {boolean} + */ + function isPersistentGrantOrigin(origin) { + return typeof origin === 'string' && origin.length > 0 && origin !== 'null' + } /** * Resolves all queued isDeviceAllowed promises for `origin`. @@ -824,7 +860,6 @@ } } } - /** * Checks whether a device is in the allowed set for `origin`, loading that * origin lazily when necessary. @@ -834,6 +869,7 @@ */ function isDeviceAllowed(deviceId, origin) { if (!origin) return Promise.resolve(false) + if (!isPersistentGrantOrigin(origin)) return Promise.resolve(false) if (loadedOrigins.has(origin)) { return Promise.resolve((allowedByOrigin.get(origin) || new Set()).has(deviceId)) } @@ -853,6 +889,12 @@ * @returns {Promise} */ async function loadAllowedDeviceIds(origin) { + if (!isPersistentGrantOrigin(origin)) { + allowedByOrigin.set(origin, new Set()) + loadedOrigins.add(origin) + flushAllowedDeviceIdsQueue(origin) + return + } try { const resp = await sendBackgroundRequest({ action: 'getAllowedDevices', @@ -992,8 +1034,9 @@ return 'blob' } let mode = originSettings.workerSpawnMode - if (origin) { - const site = await loadSiteSettings(origin) + const settingsScope = settingsScopeForOrigin(origin) + if (settingsScope) { + const site = await loadSiteSettings(settingsScope) if (site.workerSpawnMode !== undefined) mode = site.workerSpawnMode } if (mode === 'blob') { @@ -1457,8 +1500,8 @@ 'WS data plane will fall back to NM' ) } - await loadSettingsForOrigin(authorityOrigin) - loadAllowedDeviceIds(authorityOrigin) + await loadSettingsForOrigin(persistentOrigin || '') + loadAllowedDeviceIds(persistentOrigin || '') })() /** @@ -1652,7 +1695,7 @@ */ function getRequestOrigin(data) { const port = requestPortMap.get(data.id) - return frameContextForPort(port)?.origin || authorityOrigin + return frameContextForPort(port)?.persistentOrigin || persistentOrigin || '' } /** @@ -1733,7 +1776,7 @@ } return } - const allowed = await isDeviceAllowed(deviceId, context.origin) + const allowed = await isDeviceAllowed(deviceId, context.persistentOrigin || '') if (!allowed) { logger.warn('data-port: not authorized for device', deviceId) try { @@ -1929,7 +1972,7 @@ const filters = payload.filters || [] const exclusionFilters = payload.exclusionFilters || [] const context = frameContextForPort(requestPort) - const origin = context ? context.origin : authorityOrigin + const origin = context ? context.persistentOrigin || '' : persistentOrigin || '' const originSettings = await loadSettingsForOrigin(origin) const pickerMode = isChromium && originSettings.devicePickerMode === 'pageAction' @@ -2085,7 +2128,7 @@ deviceIds: devices.map((device) => device.deviceId) }).catch((e) => logger.debug('recordGrantGroup failed', e)) } - await loadAllowedDeviceIds(origin) + await loadAllowedDeviceIds(persistentOrigin || '') } /** @@ -2099,7 +2142,7 @@ const context = frameContextForPort(requestPort) const client = context && clientForPort(context, requestPort) const sessions = client && client.sessions - const origin = context ? context.origin : getRequestOrigin(data) + const origin = context ? context.persistentOrigin || '' : getRequestOrigin(data) let nmOpenAttempt = false let response = null const deviceId = payload && payload.deviceId @@ -2780,7 +2823,7 @@ if (!parsed) continue if (parsed.scope === 'global') { for (const store of settingsByOrigin.values()) store.set({ [parsed.name]: change.newValue }) - } else if (authorityOrigin && parsed.origin === authorityOrigin) { + } else if (persistentOrigin && parsed.origin === persistentOrigin) { settingsForOrigin(authorityOrigin).set({ [parsed.name]: change.newValue }) } } @@ -2788,7 +2831,7 @@ browser.runtime.onMessage.addListener((message) => { if (message.action === 'allowedDevicesChanged' && Array.isArray(message.deviceIds)) { - const origin = message.origin || authorityOrigin + const origin = message.persistentOrigin || message.origin || authorityOrigin allowedByOrigin.set(origin, new Set(message.deviceIds)) loadedOrigins.add(origin) flushAllowedDeviceIdsQueue(origin) diff --git a/addon/js/utils/settings.js b/addon/js/utils/settings.js index 1144717..2018b43 100644 --- a/addon/js/utils/settings.js +++ b/addon/js/utils/settings.js @@ -240,6 +240,35 @@ if (parts.length === 3) return { scope: 'site', origin: parts[1], name: parts[2] } return null } + /** + * Returns whether a serialized origin can be a persistent site scope. + * @param {string} origin + * @returns {boolean} + */ + function isPersistentSiteOrigin(origin) { + return typeof origin === 'string' && origin.length > 0 && origin !== 'null' + } + /** + * Derives the persistent partition for one browser-authenticated document. + * @param {string} authorityOrigin + * @param {string} documentUrl + * @param {string|null|undefined} topAuthorityOrigin + * @returns {string|null} + */ + function persistentSiteScope(authorityOrigin, documentUrl, topAuthorityOrigin) { + if (isPersistentSiteOrigin(authorityOrigin)) return authorityOrigin + if (authorityOrigin !== 'null') return null + let sourceOrigin = '' + try { + sourceOrigin = new URL(documentUrl).origin + } catch { + void 0 + } + if (!sourceOrigin || !topAuthorityOrigin || topAuthorityOrigin === 'null') return null + return ( + 'opaque|' + encodeURIComponent(topAuthorityOrigin) + '|' + encodeURIComponent(sourceOrigin) + ) + } /** * Loads all global settings from storage, applying defaults for missing keys. @@ -265,6 +294,7 @@ * @returns {Promise} */ async function loadSiteSettings(origin) { + if (!isPersistentSiteOrigin(origin)) return {} const keys = [] for (let i = 0; i < SITE_SETTING_NAMES.length; i++) { arrayOps.push(keys, siteSettingKey(origin, SITE_SETTING_NAMES[i])) @@ -286,7 +316,7 @@ */ async function loadEffectiveSettings(origin) { const global = await loadGlobalSettings() - if (!origin) return global + if (!isPersistentSiteOrigin(origin)) return global const site = await loadSiteSettings(origin) const entries = object.entries(site) for (let i = 0; i < entries.length; i++) { @@ -316,10 +346,13 @@ * @returns {Promise} */ async function saveSiteSetting(origin, name, value) { + if (!isPersistentSiteOrigin(origin)) return await browser.storage.local.set({ [siteSettingKey(origin, name)]: value }) } webhid.export('SETTING_NAMES', SETTING_NAMES) + webhid.export('isPersistentSiteOrigin', isPersistentSiteOrigin) + webhid.export('persistentSiteScope', persistentSiteScope) webhid.export('globalSettingKey', globalSettingKey) webhid.export('siteSettingKey', siteSettingKey) webhid.export('parseSettingsKey', parseSettingsKey) diff --git a/tests/unit/settings.test.js b/tests/unit/settings.test.js index 9cd839d..83f22fa 100644 --- a/tests/unit/settings.test.js +++ b/tests/unit/settings.test.js @@ -6,6 +6,7 @@ import { test } from 'node:test' function loadSettings() { const exports = {} const sandbox = { + URL, browser: { runtime: { getManifest: () => ({ manifest_version: 3 }) }, storage: { local: { get: async () => ({}) } } @@ -79,7 +80,14 @@ test('settings updates and overlays survive a poisoned array iterator', async () } const changed = store.set({ value: 2 }) const effective = await settingsExports.loadEffectiveSettings('https://example.test') - return { changed, changes, value: store.value, effective } + const global = await settingsExports.loadGlobalSettings() + const opaque = await settingsExports.loadEffectiveSettings('null') + const opaqueScope = settingsExports.persistentSiteScope( + 'null', + 'https://widget.example/app', + 'https://host.example' + ) + return { changed, changes, value: store.value, global, effective, opaque, opaqueScope } } )()`, context @@ -87,4 +95,27 @@ test('settings updates and overlays survive a poisoned array iterator', async () assert.equal(result.value, 2) assert.equal(result.changes[0], 2) assert.equal(result.effective.dataPlane, 'ws') + assert.equal(result.opaque.dataPlane, result.global.dataPlane) + assert.equal(result.opaqueScope, 'opaque|https%3A%2F%2Fhost.example|https%3A%2F%2Fwidget.example') + assert.equal(exports.isPersistentSiteOrigin('null'), false) + assert.equal(exports.isPersistentSiteOrigin(result.opaqueScope), true) +}) +test('opaque persistence partitions use trusted embedder and source origins', () => { + const { exports } = loadSettings() + const scope = (topOrigin, sourceOrigin) => + exports.persistentSiteScope('null', sourceOrigin + '/app', topOrigin) + + assert.notEqual( + scope('https://host-a.example', 'https://widget.example'), + scope('https://host-b.example', 'https://widget.example') + ) + assert.notEqual( + scope('https://host.example', 'https://widget-a.example'), + scope('https://host.example', 'https://widget-b.example') + ) + assert.equal( + scope('https://host.example', 'https://widget.example'), + scope('https://host.example', 'https://widget.example') + ) + assert.equal(exports.persistentSiteScope('null', 'https://widget.example/app', null), null) }) diff --git a/tests/unit/storage-origin.test.js b/tests/unit/storage-origin.test.js new file mode 100644 index 0000000..892a9d8 --- /dev/null +++ b/tests/unit/storage-origin.test.js @@ -0,0 +1,48 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import test from 'node:test' +import { runInNewContext } from 'node:vm' + +const source = readFileSync( + new URL('../../addon/js/background/storage.js', import.meta.url), + 'utf8' +) + +function loadStorage() { + const exports = {} + let openCalls = 0 + const context = { + globalThis: null, + indexedDB: { + open() { + openCalls++ + throw new Error('opaque origin must not open IndexedDB') + } + }, + webhid: { + import(name) { + if (name === 'logger') return { debug() {} } + if (name === 'bgState') return { deviceCache: [] } + throw new Error('unexpected import: ' + name) + }, + export(name, value) { + exports[name] = value + } + } + } + context.globalThis = context + runInNewContext(source, context) + return { exports, getOpenCalls: () => openCalls } +} + +test('opaque origin cannot read or persist HID grants', async () => { + const { exports, getOpenCalls } = loadStorage() + + const storage = exports.bgStorage + assert.equal(JSON.stringify(await storage.getAllowedDevices('null')), '[]') + await storage.addAllowedDevice('null', 7) + await storage.removeAllowedDevice('null', 7) + await storage.recordGrantGroup('null', [7, 8]) + assert.equal(JSON.stringify(await storage.getGrantGroupsForOrigin('null')), '[]') + assert.equal(getOpenCalls(), 0) +}) From d69df430824348f21dce5797c442b45a88654d7d Mon Sep 17 00:00:00 2001 From: Kazoku Date: Sun, 13 Sep 2026 20:45:24 +0700 Subject: [PATCH 05/26] fix(addon): gate activation policy on settings snapshot --- addon/js/content/main/index.js | 1 - tests/unit/frame-endpoint-topology.test.js | 6 ++++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/addon/js/content/main/index.js b/addon/js/content/main/index.js index 4ffa9d0..2c557d3 100644 --- a/addon/js/content/main/index.js +++ b/addon/js/content/main/index.js @@ -845,7 +845,6 @@ response: handleResponseMessage, settings: (data) => { settings.set(data.settings || {}) - markSettingsReady() }, event: (data) => { dispatchDeviceEvent(data.event) diff --git a/tests/unit/frame-endpoint-topology.test.js b/tests/unit/frame-endpoint-topology.test.js index 74173bd..f1aec2b 100644 --- a/tests/unit/frame-endpoint-topology.test.js +++ b/tests/unit/frame-endpoint-topology.test.js @@ -43,6 +43,12 @@ test('authority metadata gates local origin-sensitive state', () => { assert.match(bridge, /await authorityReady/) assert.match(main, /await settingsReady/) }) +test('MAIN settings readiness waits for the initial snapshot', () => { + const liveSettings = main.match(/settings: \(data\) => \{[\s\S]*?\n \},/) + assert.ok(liveSettings) + assert.doesNotMatch(liveSettings[0], /markSettingsReady/) + assert.match(main, /sendRequest\('getSettings', \{\}\)[\s\S]*markSettingsReady/) +}) test('MAIN does not bootstrap through a top WindowProxy', () => { assert.doesNotMatch(main, /nativeWindowPostMessage/) From 3c64ebbdd4ba7a35c75333308717d7c0db44a336 Mon Sep 17 00:00:00 2001 From: Kazoku Date: Sun, 13 Sep 2026 21:23:41 +0700 Subject: [PATCH 06/26] fix(addon): isolate opaque permission events --- addon/js/background/messages.js | 26 ++++++++++++++++++---- addon/js/content/isolated/bridge.js | 24 +++++++++++++++----- tests/unit/frame-endpoint-topology.test.js | 12 ++++++++++ 3 files changed, 52 insertions(+), 10 deletions(-) diff --git a/addon/js/background/messages.js b/addon/js/background/messages.js index 24c7233..ecc4775 100644 --- a/addon/js/background/messages.js +++ b/addon/js/background/messages.js @@ -230,6 +230,19 @@ if (endpoint.origin === origin) postToContentPort(endpoint.port, message) } } + /** + * Sends a persistence-scope event only to endpoints owning that scope. + * @param {string|null} persistentOrigin + * @param {object} message + * @returns {void} + */ + function postToPersistentOriginEndpoints(persistentOrigin, message) { + if (!persistentOrigin) return + for (const endpoint of frameEndpoints.values()) { + if (endpoint.persistentOrigin === persistentOrigin) + postToContentPort(endpoint.port, message) + } + } /** * Replaces the in-memory device cache with `devices` (decoded), persisting * them afterwards. @@ -250,7 +263,7 @@ * @returns {Promise} */ async function notifyAllowedDevicesChanged(authorityOrigin, persistentOrigin, deviceIds) { - postToOriginEndpoints(authorityOrigin, { + postToPersistentOriginEndpoints(persistentOrigin, { action: 'allowedDevicesChanged', origin: authorityOrigin, persistentOrigin, @@ -281,9 +294,14 @@ await deleteGrantGroups(memberGroups.map((g) => g.id)) const deviceIds = await getAllowedDevices(persistentOrigin) for (const deviceId of toRevoke) { - postToOriginEndpoints(authorityOrigin, { + postToPersistentOriginEndpoints(persistentOrigin, { action: 'webhidDeviceEvent', - event: { eventType: 'revoked', deviceId, origin: authorityOrigin } + event: { + eventType: 'revoked', + deviceId, + origin: authorityOrigin, + persistentOrigin + } }) } notifyAllowedDevicesChanged(authorityOrigin, persistentOrigin, deviceIds) @@ -1047,7 +1065,7 @@ .filter((endpoint) => endpoint.tabId === tabId) .sort((a, b) => a.frameId - b.frameId) for (const endpoint of endpoints) { - if (!/^https?:$/.test(new URL(endpoint.origin).protocol)) continue + if (!(endpoint.origin.startsWith('http:') || endpoint.origin.startsWith('https:'))) continue if (seen.has(endpoint.origin)) continue seen.add(endpoint.origin) origins.push(endpoint.origin) diff --git a/addon/js/content/isolated/bridge.js b/addon/js/content/isolated/bridge.js index 8637c0c..17949b3 100644 --- a/addon/js/content/isolated/bridge.js +++ b/addon/js/content/isolated/bridge.js @@ -111,9 +111,14 @@ handleGlobalReset() return } - if (message && message.action === 'allowedDevicesChanged') { - const origin = message.persistentOrigin || message.origin || authorityOrigin - allowedByOrigin.set(origin, new Set(message.deviceIds || [])) + if ( + message && + message.action === 'allowedDevicesChanged' && + Array.isArray(message.deviceIds) && + message.persistentOrigin === persistentOrigin + ) { + const origin = message.persistentOrigin + allowedByOrigin.set(origin, new Set(message.deviceIds)) loadedOrigins.add(origin) flushAllowedDeviceIdsQueue(origin) return @@ -2573,7 +2578,10 @@ } } else if (messageEvent.eventType === 'revoked') { const contexts = - frameContext && frameContext.origin === messageEvent.origin ? [frameContext] : [] + messageEvent.persistentOrigin && + messageEvent.persistentOrigin === frameContext?.persistentOrigin + ? [frameContext] + : [] for (const context of contexts) { reconcileFrameDevice(context, messageEvent.deviceId, messageEvent).catch((e) => logger.debug('revoke reconciliation failed', e) @@ -2830,8 +2838,12 @@ }) browser.runtime.onMessage.addListener((message) => { - if (message.action === 'allowedDevicesChanged' && Array.isArray(message.deviceIds)) { - const origin = message.persistentOrigin || message.origin || authorityOrigin + if ( + message.action === 'allowedDevicesChanged' && + Array.isArray(message.deviceIds) && + message.persistentOrigin === persistentOrigin + ) { + const origin = message.persistentOrigin allowedByOrigin.set(origin, new Set(message.deviceIds)) loadedOrigins.add(origin) flushAllowedDeviceIdsQueue(origin) diff --git a/tests/unit/frame-endpoint-topology.test.js b/tests/unit/frame-endpoint-topology.test.js index f1aec2b..98eb519 100644 --- a/tests/unit/frame-endpoint-topology.test.js +++ b/tests/unit/frame-endpoint-topology.test.js @@ -36,6 +36,18 @@ test('background owns endpoint registry and exact input fanout', () => { assert.match(nm, /collectDeviceSessionOwners\(deviceId\)/) assert.match(nm, /postToContentPort\(port/) }) +test('persistent permission events cannot cross opaque partitions', () => { + assert.match(messages, /function postToPersistentOriginEndpoints/) + assert.match(messages, /endpoint\.persistentOrigin === persistentOrigin/) + assert.match(bridge, /messageEvent\.persistentOrigin === frameContext\?\.persistentOrigin/) + assert.match(bridge, /message\.persistentOrigin === persistentOrigin/) +}) + +test('normal frame origin listing skips opaque authorities safely', () => { + assert.match(messages, /endpoint\.origin\.startsWith\('http:'\)/) + assert.match(messages, /endpoint\.origin\.startsWith\('https:'\)/) + assert.doesNotMatch(messages, /new URL\(endpoint\.origin\)\.protocol/) +}) test('authority metadata gates local origin-sensitive state', () => { assert.match(messages, /action: 'endpointMetadata'/) assert.match(messages, /typeof sender\.origin/) From 8058af5f0266fbd92e8190ce0cbc87427b68a4cc Mon Sep 17 00:00:00 2001 From: Kazoku Date: Sun, 13 Sep 2026 21:28:46 +0700 Subject: [PATCH 07/26] fix(addon): scope permission events by partition --- addon/js/background/messages.js | 32 ++++++++++++++++------ tests/unit/frame-endpoint-topology.test.js | 5 ++++ 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/addon/js/background/messages.js b/addon/js/background/messages.js index ecc4775..423d661 100644 --- a/addon/js/background/messages.js +++ b/addon/js/background/messages.js @@ -239,8 +239,7 @@ function postToPersistentOriginEndpoints(persistentOrigin, message) { if (!persistentOrigin) return for (const endpoint of frameEndpoints.values()) { - if (endpoint.persistentOrigin === persistentOrigin) - postToContentPort(endpoint.port, message) + if (endpoint.persistentOrigin === persistentOrigin) postToContentPort(endpoint.port, message) } } /** @@ -1056,21 +1055,38 @@ function handleGetFrameOrigins(request, sender, sendResponse) { const tabId = request.tabId != null ? request.tabId : sender.tab ? sender.tab.id : undefined if (tabId == null) { - sendResponse({ origins: [] }) + sendResponse({ origins: [], targets: [] }) return false } const origins = [] + const targets = [] const seen = new Set() const endpoints = [...frameEndpoints.values()] .filter((endpoint) => endpoint.tabId === tabId) .sort((a, b) => a.frameId - b.frameId) for (const endpoint of endpoints) { - if (!(endpoint.origin.startsWith('http:') || endpoint.origin.startsWith('https:'))) continue - if (seen.has(endpoint.origin)) continue - seen.add(endpoint.origin) - origins.push(endpoint.origin) + const isHttp = endpoint.origin.startsWith('http:') || endpoint.origin.startsWith('https:') + if (isHttp) { + if (seen.has(endpoint.origin)) continue + seen.add(endpoint.origin) + origins.push(endpoint.origin) + targets.push({ + kind: 'origin', + label: endpoint.origin, + origin: endpoint.origin, + persistentOrigin: endpoint.persistentOrigin + }) + } else if (endpoint.persistentOrigin && !seen.has(endpoint.persistentOrigin)) { + seen.add(endpoint.persistentOrigin) + targets.push({ + kind: 'opaque', + label: 'Opaque iframe', + origin: endpoint.origin, + persistentOrigin: endpoint.persistentOrigin + }) + } } - sendResponse({ origins }) + sendResponse({ origins, targets }) return false } diff --git a/tests/unit/frame-endpoint-topology.test.js b/tests/unit/frame-endpoint-topology.test.js index 98eb519..b863eb8 100644 --- a/tests/unit/frame-endpoint-topology.test.js +++ b/tests/unit/frame-endpoint-topology.test.js @@ -48,6 +48,11 @@ test('normal frame origin listing skips opaque authorities safely', () => { assert.match(messages, /endpoint\.origin\.startsWith\('https:'\)/) assert.doesNotMatch(messages, /new URL\(endpoint\.origin\)\.protocol/) }) +test('frame-origin API preserves opaque persistent target metadata', () => { + assert.match(messages, /targets\.push/) + assert.match(messages, /kind: 'opaque'/) + assert.match(messages, /persistentOrigin: endpoint\.persistentOrigin/) +}) test('authority metadata gates local origin-sensitive state', () => { assert.match(messages, /action: 'endpointMetadata'/) assert.match(messages, /typeof sender\.origin/) From 4b8b362e7e2f71038c937c04954c06dc4b1d863f Mon Sep 17 00:00:00 2001 From: Kazoku Date: Sun, 13 Sep 2026 21:53:41 +0700 Subject: [PATCH 08/26] feat(addon): expose persistent settings targets --- addon/js/background/state_ops.js | 12 ++- addon/js/internal/pages/popup/index.js | 97 +++++++++++++++--------- tests/browser/page-action.spec.ts | 38 +++++++--- tests/browser/permissions-policy.spec.ts | 41 ++++++++++ tests/unit/state-ops.test.js | 53 ++++++++++--- 5 files changed, 180 insertions(+), 61 deletions(-) diff --git a/addon/js/background/state_ops.js b/addon/js/background/state_ops.js index 69b765d..290ac12 100644 --- a/addon/js/background/state_ops.js +++ b/addon/js/background/state_ops.js @@ -273,7 +273,12 @@ const statuses = [] for (const [deviceId, byToken] of deviceSessions) { for (const [token, owner] of byToken) { - if (owner.tabId !== tabId || (origin && owner.origin !== origin) || !owner.plane) continue + if ( + owner.tabId !== tabId || + (origin && (owner.persistentOrigin || owner.origin) !== origin) || + !owner.plane + ) + continue statuses.push({ deviceId, token, ...owner.plane }) } } @@ -289,7 +294,10 @@ const ids = new Set() for (const [deviceId, byToken] of deviceSessions) { for (const owner of byToken.values()) { - if (owner.tabId === tabId && (!origin || owner.origin === origin)) { + if ( + owner.tabId === tabId && + (!origin || (owner.persistentOrigin || owner.origin) === origin) + ) { ids.add(String(deviceId)) break } diff --git a/addon/js/internal/pages/popup/index.js b/addon/js/internal/pages/popup/index.js index 8cb56da..d22b121 100644 --- a/addon/js/internal/pages/popup/index.js +++ b/addon/js/internal/pages/popup/index.js @@ -25,6 +25,8 @@ let tab /** @type {string} */ let origin = '' + /** @type {string|null} */ + let persistentOrigin = null /** * Resolves the active tab and its http(s) origin. When the popup itself is @@ -61,35 +63,53 @@ const originList = document.getElementById('origin-list') /** - * Collects every distinct http(s) origin in the tab from the bridge's page - * ports, top-level first. Frames that never run the polyfill are absent. - * @returns {Promise} + * @typedef {{kind: string, label: string, origin: string, persistentOrigin: string|null}} SiteTarget + */ + /** + * Collects addressable settings targets in the active tab. + * @returns {Promise} */ async function loadFrameOrigins() { - if (!tab || tab.id == null) return origin ? [origin] : [] + const fallback = origin + ? [{ kind: 'origin', label: origin, origin, persistentOrigin: origin }] + : [] + if (!tab || tab.id == null) return fallback try { const resp = await browser.runtime.sendMessage({ action: 'getFrameOrigins', tabId: tab.id }) - const origins = (resp && resp.origins) || [] - return origins.length ? origins : origin ? [origin] : [] + const targets = Array.isArray(resp?.targets) ? resp.targets : [] + if (targets.length) return targets + const origins = Array.isArray(resp?.origins) ? resp.origins : [] + return origins.length + ? origins.map((value) => ({ + kind: 'origin', + label: value, + origin: value, + persistentOrigin: value + })) + : fallback } catch (e) { logger.debug('getFrameOrigins failed', e) - return origin ? [origin] : [] + return fallback } } - /** @type {string[]} */ - let frameOrigins = [] + /** @type {SiteTarget[]} */ + let frameTargets = [] + + /** @returns {SiteTarget|undefined} */ + function selectedTarget() { + return frameTargets.find((target) => target.persistentOrigin === persistentOrigin) + } /** - * Renders the selected origin on the dropdown button and closes the list. * @returns {void} */ function renderSiteLabel() { - siteLabel.textContent = origin || t('popupNoSite') - siteButton.classList.toggle('has-list', frameOrigins.length > 1) + siteLabel.textContent = selectedTarget()?.label || origin || t('popupNoSite') + siteButton.classList.toggle('has-list', frameTargets.length > 1) siteButton.setAttribute('aria-expanded', 'false') originList.hidden = true } @@ -98,16 +118,15 @@ * @returns {void} */ function openOriginList() { - if (frameOrigins.length < 2) return + if (frameTargets.length < 2) return for (const li of originList.children) { - const selected = li.dataset.origin === origin + const selected = li.dataset.persistentOrigin === persistentOrigin li.classList.toggle('selected', selected) li.setAttribute('aria-selected', String(selected)) } originList.hidden = false siteButton.setAttribute('aria-expanded', 'true') } - /** * @returns {void} */ @@ -117,13 +136,14 @@ } /** - * Switches the origin the popup operates on and re-renders for it. - * @param {string} o + * Switches the popup to one authority/persistence target. + * @param {SiteTarget} target * @returns {Promise} */ - async function selectOrigin(o) { - if (o === origin || !frameOrigins.includes(o)) return - origin = o + async function selectTarget(target) { + if (!target || target.persistentOrigin === persistentOrigin) return + origin = target.origin + persistentOrigin = target.persistentOrigin renderSiteLabel() settings = await loadSettings() applySettingsToUI() @@ -132,19 +152,18 @@ } /** - * Rebuilds the dropdown options for the current frameOrigins. * @returns {void} */ function buildOriginList() { originList.textContent = '' - for (const o of frameOrigins) { + for (const target of frameTargets) { const li = document.createElement('li') li.className = 'origin-picker-option' li.setAttribute('role', 'option') li.setAttribute('tabindex', '-1') - li.dataset.origin = o - li.textContent = o - li.addEventListener('click', () => selectOrigin(o)) + li.dataset.persistentOrigin = target.persistentOrigin || '' + li.textContent = target.label + li.addEventListener('click', () => selectTarget(target)) originList.appendChild(li) } renderSiteLabel() @@ -170,7 +189,7 @@ }) originList.addEventListener('keydown', (e) => { const items = [...originList.children] - const idx = items.findIndex((li) => li.dataset.origin === origin) + const idx = items.findIndex((li) => li.dataset.persistentOrigin === persistentOrigin) if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault() const next = (idx + (e.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length @@ -178,7 +197,12 @@ } else if (e.key === 'Enter' || e.key === ' ') { e.preventDefault() const li = e.target.closest('li') - if (li) selectOrigin(li.dataset.origin) + if (li) { + const target = frameTargets.find( + (item) => item.persistentOrigin === li.dataset.persistentOrigin + ) + if (target) selectTarget(target) + } } else if (e.key === 'Escape') { closeOriginList() siteButton.focus() @@ -202,8 +226,9 @@ if (token !== refreshToken) return tab = resolved.tab origin = resolved.origin + persistentOrigin = origin || null siteLabel.textContent = origin || t('popupNoSite') - frameOrigins = await loadFrameOrigins() + frameTargets = await loadFrameOrigins() if (token !== refreshToken) return buildOriginList() settings = await loadSettings() @@ -218,7 +243,7 @@ * @returns {Promise} */ async function loadSettings() { - return loadEffectiveSettings(origin) + return loadEffectiveSettings(persistentOrigin || origin) } /** @@ -228,8 +253,8 @@ * @returns {Promise} */ async function saveSetting(key, value) { - if (!origin) return - await saveSiteSetting(origin, key, value) + if (!persistentOrigin) return + await saveSiteSetting(persistentOrigin, key, value) } let settings @@ -347,12 +372,12 @@ } /** @type {Array<{deviceId: string, plane: string, mode: (string|null)}>} */ let planes = [] - if (origin && tab && tab.id != null) { + if (persistentOrigin && tab && tab.id != null) { try { const r = await browser.runtime.sendMessage({ action: 'getDataPlaneStatus', tabId: tab.id, - origin + origin: persistentOrigin }) planes = (r && r.planes) || [] } catch (e) { @@ -386,11 +411,11 @@ /** @returns {Promise} */ async function loadDevices() { - if (!origin) return [] + if (!persistentOrigin) return [] try { const resp = await browser.runtime.sendMessage({ action: 'getPairedDevices', - origin + origin: persistentOrigin }) return resp && resp.success ? resp.hashes : [] } catch { @@ -552,7 +577,7 @@ const r = await browser.runtime.sendMessage({ action: 'getOpenDeviceIds', tabId: tab.id, - origin + origin: persistentOrigin }) const rIds = r != null ? r.ids : undefined if (rIds) openIds = new Set(rIds.map((id) => Number(id))) diff --git a/tests/browser/page-action.spec.ts b/tests/browser/page-action.spec.ts index f813e64..da43176 100644 --- a/tests/browser/page-action.spec.ts +++ b/tests/browser/page-action.spec.ts @@ -163,10 +163,10 @@ test.describe('extension action surfaces', () => { pageUrl }) => { const activeOrigin = new URL(pageUrl('/')).origin - const selectedOrigin = `${activeOrigin}-selected` + const selectedPersistent = 'opaque|https%3A%2F%2Fhost.example|https%3A%2F%2Fwidget.example' await sharedPage.goto(pageUrl('/test-page.html'), { waitUntil: 'domcontentloaded' }) await page.addInitScript( - (origin) => { + (target) => { const calls: Array<{ action: string; origin: unknown }> = [] Object.defineProperty(globalThis, '__popupStatusCalls', { value: calls }) const runtimeSendMessage = browser.runtime.sendMessage as unknown as ( @@ -174,25 +174,41 @@ test.describe('extension action surfaces', () => { ) => Promise browser.runtime.sendMessage = async (message) => { const request = message as { action?: unknown; origin?: unknown } - if (request.action === 'getFrameOrigins') - return { origins: [origin.active, origin.selected] } + if (request.action === 'getFrameOrigins') { + return { + targets: [ + { + kind: 'origin', + label: target.active, + origin: target.active, + persistentOrigin: target.active + }, + { + kind: 'opaque', + label: 'Opaque iframe', + origin: 'null', + persistentOrigin: target.persistent + } + ] + } + } if (request.action === 'getBackendStatus') return { nmConnected: true, daemonReachable: true, hidPermission: 0 } if (request.action === 'getPairedDevices') return { success: true, hashes: ['1'] } if (request.action === 'getDataPlaneStatus') { calls.push({ action: 'getDataPlaneStatus', origin: request.origin }) - return request.origin === origin.selected + return request.origin === target.persistent ? { planes: [{ deviceId: '1', plane: 'ws', mode: 'worker' }], defaultPlane: 'nm' } : { planes: [], defaultPlane: 'nm' } } if (request.action === 'getOpenDeviceIds') { calls.push({ action: 'getOpenDeviceIds', origin: request.origin }) - return request.origin === origin.selected ? { ids: ['1'] } : { ids: [] } + return request.origin === target.persistent ? { ids: ['1'] } : { ids: [] } } return runtimeSendMessage(message) } }, - { active: activeOrigin, selected: selectedOrigin } + { active: activeOrigin, persistent: selectedPersistent } ) const popupUrl = await backgroundPage.evaluate(() => browser.runtime.getURL('js/internal/pages/popup/index.html') @@ -204,7 +220,7 @@ test.describe('extension action surfaces', () => { }) await page.locator('#site-name').click() await page.locator('#origin-list li').nth(1).click() - await expect(page.locator('#site-name-text')).toHaveText(selectedOrigin) + await expect(page.locator('#site-name-text')).toHaveText('Opaque iframe') await expect(page.locator('#status')).toHaveClass(/state-warn/) await page.waitForFunction( ({ start, origin }) => { @@ -222,7 +238,7 @@ test.describe('extension action surfaces', () => { }) ) }, - { start: before, origin: selectedOrigin }, + { start: before, origin: selectedPersistent }, { timeout: 15000 } ) const calls = await page.evaluate(() => { @@ -232,8 +248,8 @@ test.describe('extension action surfaces', () => { const afterSelection = calls.slice(before) expect(afterSelection).toEqual( expect.arrayContaining([ - { action: 'getDataPlaneStatus', origin: selectedOrigin }, - { action: 'getOpenDeviceIds', origin: selectedOrigin } + { action: 'getDataPlaneStatus', origin: selectedPersistent }, + { action: 'getOpenDeviceIds', origin: selectedPersistent } ]) ) }) diff --git a/tests/browser/permissions-policy.spec.ts b/tests/browser/permissions-policy.spec.ts index 8b3951b..94dab70 100644 --- a/tests/browser/permissions-policy.spec.ts +++ b/tests/browser/permissions-policy.spec.ts @@ -237,6 +237,47 @@ test.describe('Cross-origin iframe', () => { await expect.poll(() => page.locator('html').getAttribute('data-opaque-origin')).toBe('null') expect((await readFrameResult(frame))?.queryHid).toBe('denied') }) + test('background preserves distinct opaque settings targets', async ({ + page, + pageUrl, + crossUrl, + backgroundPage + }) => { + await page.goto(pageUrl('/iframe-parent'), { + waitUntil: 'domcontentloaded', + timeout: 15000 + }) + await page.evaluate( + ({ mainSrc, crossSrc }) => { + for (const [id, src] of [ + ['opaque-a', mainSrc], + ['opaque-b', crossSrc] + ]) { + const frame = document.createElement('iframe') + frame.id = id + frame.setAttribute('sandbox', 'allow-scripts') + frame.src = src + '/iframe-child-no-allow' + document.body.appendChild(frame) + } + }, + { mainSrc: pageUrl(''), crossSrc: crossUrl('') } + ) + await frameWithId(page, 'opaque-a', '/iframe-child-no-allow') + await frameWithId(page, 'opaque-b', '/iframe-child-no-allow') + const targets = (await backgroundPage.evaluate(async () => { + const tabs = await browser.tabs.query({ active: true, currentWindow: true }) + const tab = tabs[0] + if (!tab || tab.id == null) return [] + const raw: unknown = await browser.tabs.sendMessage(tab.id, { action: 'getFrameOrigins' }) + const response = raw as { + targets?: Array<{ kind: string; persistentOrigin: string | null }> + } + return response.targets || [] + })) as Array<{ kind: string; persistentOrigin: string | null }> + const opaqueTargets = targets.filter((target) => target.kind === 'opaque') + expect(opaqueTargets).toHaveLength(2) + expect(opaqueTargets[0].persistentOrigin).not.toBe(opaqueTargets[1].persistentOrigin) + }) test('B2: top-level hid=() denies a delegated cross-origin child', async ({ page, pageUrl, diff --git a/tests/unit/state-ops.test.js b/tests/unit/state-ops.test.js index f608a5e..34ade4d 100644 --- a/tests/unit/state-ops.test.js +++ b/tests/unit/state-ops.test.js @@ -296,18 +296,24 @@ test('tab aggregation spans exact frame endpoints', () => { port: childPort }) assert.deepEqual(refreshed, [11, 11]) - ops.setDeviceSessionPlane(7, 'session-top', topPort, { - plane: 'nm', - mode: null, - generation: 1, - ready: true - }) - ops.setDeviceSessionPlane(7, 'session-child', childPort, { - plane: 'ws', - mode: 'worker', - generation: 2, - ready: true - }) + assert.equal( + ops.setDeviceSessionPlane(7, 'session-top', topPort, { + plane: 'nm', + mode: null, + generation: 1, + ready: true + }), + true + ) + assert.equal( + ops.setDeviceSessionPlane(7, 'session-child', childPort, { + plane: 'ws', + mode: 'worker', + generation: 2, + ready: true + }), + true + ) assert.equal(JSON.stringify(ops.collectOpenDeviceIdsForTab(11)), JSON.stringify(['7'])) assert.equal( @@ -329,6 +335,29 @@ test('tab aggregation spans exact frame endpoints', () => { ]) ) }) +test('opaque persistence scopes keep tab aggregation isolated', () => { + const { ops } = loadStateOps() + const scopeA = 'opaque|host-a|widget' + const scopeB = 'opaque|host-b|widget' + ops.registerFrameLifetime(12, 'opaque-a') + ops.registerFrameLifetime(12, 'opaque-b') + ops.registerDeviceSession(9, 'token-a', { + tabId: 12, + origin: 'null', + persistentOrigin: scopeA, + frameKey: 'opaque-a' + }) + ops.registerDeviceSession(9, 'token-b', { + tabId: 12, + origin: 'null', + persistentOrigin: scopeB, + frameKey: 'opaque-b' + }) + + assert.equal(JSON.stringify(ops.collectOpenDeviceIdsForTab(12, scopeA)), JSON.stringify(['9'])) + assert.equal(JSON.stringify(ops.collectOpenDeviceIdsForTab(12, scopeB)), JSON.stringify(['9'])) + assert.equal(JSON.stringify(ops.collectOpenDeviceIdsForTab(12, 'null')), JSON.stringify([])) +}) test('exact endpoint cleanup cannot retire a replacement lifetime', async () => { const { ops, deviceSessions, deviceTabMap } = loadStateOps() ops.registerFrameLifetime(11, 'endpoint-old') From dcfe8eae02bbcb61dd495573bcfde489aa726234 Mon Sep 17 00:00:00 2001 From: Kazoku Date: Sun, 13 Sep 2026 22:09:05 +0700 Subject: [PATCH 09/26] test(addon): cover opaque target isolation --- addon/js/background/messages.js | 11 ++++++++--- tests/browser/page-action.spec.ts | 22 ++++++++++++++++++++++ tests/browser/permissions-policy.spec.ts | 20 ++++++++++++++++++++ 3 files changed, 50 insertions(+), 3 deletions(-) diff --git a/addon/js/background/messages.js b/addon/js/background/messages.js index 423d661..09a0478 100644 --- a/addon/js/background/messages.js +++ b/addon/js/background/messages.js @@ -234,13 +234,17 @@ * Sends a persistence-scope event only to endpoints owning that scope. * @param {string|null} persistentOrigin * @param {object} message - * @returns {void} + * @returns {number} */ function postToPersistentOriginEndpoints(persistentOrigin, message) { - if (!persistentOrigin) return + if (!persistentOrigin) return 0 + let delivered = 0 for (const endpoint of frameEndpoints.values()) { - if (endpoint.persistentOrigin === persistentOrigin) postToContentPort(endpoint.port, message) + if (endpoint.persistentOrigin !== persistentOrigin) continue + postToContentPort(endpoint.port, message) + delivered++ } + return delivered } /** * Replaces the in-memory device cache with `devices` (decoded), persisting @@ -1593,5 +1597,6 @@ }) } + webhid.export('backgroundEventFanout', { postToPersistentOriginEndpoints }) webhid.export('registerMessageHandlers', registerMessageHandlers) })() diff --git a/tests/browser/page-action.spec.ts b/tests/browser/page-action.spec.ts index da43176..8fcb8ff 100644 --- a/tests/browser/page-action.spec.ts +++ b/tests/browser/page-action.spec.ts @@ -169,6 +169,13 @@ test.describe('extension action surfaces', () => { (target) => { const calls: Array<{ action: string; origin: unknown }> = [] Object.defineProperty(globalThis, '__popupStatusCalls', { value: calls }) + const saved: unknown[] = [] + Object.defineProperty(globalThis, '__popupSaved', { value: saved }) + const storageSet = browser.storage.local.set.bind(browser.storage.local) + browser.storage.local.set = async (value) => { + saved.push(value) + return storageSet(value) + } const runtimeSendMessage = browser.runtime.sendMessage as unknown as ( message: unknown ) => Promise @@ -221,6 +228,21 @@ test.describe('extension action surfaces', () => { await page.locator('#site-name').click() await page.locator('#origin-list li').nth(1).click() await expect(page.locator('#site-name-text')).toHaveText('Opaque iframe') + await page.locator('#btn-settings').click() + await page + .locator('input[name="dataPlane"][value="nm"]') + .evaluate((el) => (el as HTMLInputElement).click()) + await expect + .poll(() => + page.evaluate( + (key) => + (globalThis as unknown as { __popupSaved?: unknown[] }).__popupSaved?.some( + (entry) => entry != null && typeof entry === 'object' && key in entry + ) || false, + `settings :: ${selectedPersistent} :: dataPlane` + ) + ) + .toBe(true) await expect(page.locator('#status')).toHaveClass(/state-warn/) await page.waitForFunction( ({ start, origin }) => { diff --git a/tests/browser/permissions-policy.spec.ts b/tests/browser/permissions-policy.spec.ts index 94dab70..b22dc3c 100644 --- a/tests/browser/permissions-policy.spec.ts +++ b/tests/browser/permissions-policy.spec.ts @@ -277,6 +277,26 @@ test.describe('Cross-origin iframe', () => { const opaqueTargets = targets.filter((target) => target.kind === 'opaque') expect(opaqueTargets).toHaveLength(2) expect(opaqueTargets[0].persistentOrigin).not.toBe(opaqueTargets[1].persistentOrigin) + const scope = opaqueTargets[0].persistentOrigin + if (typeof scope !== 'string') throw new Error('opaque target has no persistent scope') + const delivered = await backgroundPage.evaluate((persistentScope) => { + const fanout = ( + globalThis as unknown as { + webhid: { + import(name: string): { + postToPersistentOriginEndpoints(scope: string, message: object): number + } + } + } + ).webhid.import('backgroundEventFanout') + return fanout.postToPersistentOriginEndpoints(persistentScope, { + action: 'allowedDevicesChanged', + origin: 'null', + persistentOrigin: persistentScope, + deviceIds: [] + }) + }, scope) + expect(delivered).toBe(1) }) test('B2: top-level hid=() denies a delegated cross-origin child', async ({ page, From 1614bc109410a8fd0202808b9ce7134bde7dd449 Mon Sep 17 00:00:00 2001 From: Kazoku Date: Sun, 13 Sep 2026 22:14:22 +0700 Subject: [PATCH 10/26] fix(addon): preserve opaque sibling sessions --- addon/js/background/state_ops.js | 7 +++++-- tests/unit/state-ops.test.js | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/addon/js/background/state_ops.js b/addon/js/background/state_ops.js index 290ac12..81584d2 100644 --- a/addon/js/background/state_ops.js +++ b/addon/js/background/state_ops.js @@ -342,12 +342,15 @@ function clearDeviceSessionsForOrigin(deviceId, origin) { const byToken = deviceSessions.get(deviceId) if (!byToken || !origin) return + const tabs = new Set() for (const [token, owner] of byToken) { - if (owner.origin === origin) byToken.delete(token) + if ((owner.persistentOrigin || owner.origin) !== origin) continue + byToken.delete(token) + if (owner.tabId != null) tabs.add(owner.tabId) } if (byToken.size === 0) deviceSessions.delete(deviceId) + for (const tabId of tabs) refreshBadge(tabId) } - /** * Drops the session records owned by `tabId` for a device. * @param {number} deviceId diff --git a/tests/unit/state-ops.test.js b/tests/unit/state-ops.test.js index 34ade4d..6908a01 100644 --- a/tests/unit/state-ops.test.js +++ b/tests/unit/state-ops.test.js @@ -358,6 +358,25 @@ test('opaque persistence scopes keep tab aggregation isolated', () => { assert.equal(JSON.stringify(ops.collectOpenDeviceIdsForTab(12, scopeB)), JSON.stringify(['9'])) assert.equal(JSON.stringify(ops.collectOpenDeviceIdsForTab(12, 'null')), JSON.stringify([])) }) +test('opaque scope cleanup preserves sibling session ownership', () => { + const { ops, deviceSessions } = loadStateOps() + ops.registerFrameLifetime(13, 'opaque-a') + ops.registerFrameLifetime(13, 'opaque-b') + ops.registerDeviceSession(10, 'token-a', { + tabId: 13, + origin: 'null', + persistentOrigin: 'opaque|host-a|widget', + frameKey: 'opaque-a' + }) + ops.registerDeviceSession(10, 'token-b', { + tabId: 13, + origin: 'null', + persistentOrigin: 'opaque|host-b|widget', + frameKey: 'opaque-b' + }) + ops.clearDeviceSessionsForOrigin(10, 'opaque|host-a|widget') + assert.equal(JSON.stringify([...deviceSessions.get(10).keys()]), JSON.stringify(['token-b'])) +}) test('exact endpoint cleanup cannot retire a replacement lifetime', async () => { const { ops, deviceSessions, deviceTabMap } = loadStateOps() ops.registerFrameLifetime(11, 'endpoint-old') From 8d764fb1337efc215a1ca930dd889b5184089647 Mon Sep 17 00:00:00 2001 From: Kazoku Date: Sun, 13 Sep 2026 22:46:35 +0700 Subject: [PATCH 11/26] fix(addon): stabilize settings listeners and revoke scopes --- addon/js/content/isolated/bridge.js | 57 ++++++++++++++-------- addon/js/internal/pages/popup/index.js | 5 +- tests/unit/frame-endpoint-topology.test.js | 5 ++ 3 files changed, 44 insertions(+), 23 deletions(-) diff --git a/addon/js/content/isolated/bridge.js b/addon/js/content/isolated/bridge.js index 17949b3..fdeec5f 100644 --- a/addon/js/content/isolated/bridge.js +++ b/addon/js/content/isolated/bridge.js @@ -2793,35 +2793,50 @@ logger.info('data plane changed:', dp, 'open devices:', active.length) } + /** @type {Array<(() => void)|undefined>} */ + let settingsListenerDisposers = [] + /** + * Removes the active settings side-effect listeners. + * @returns {void} + */ + function clearSettingsListeners() { + for (const dispose of settingsListenerDisposers) { + if (typeof dispose === 'function') dispose() + } + settingsListenerDisposers = [] + } /** * @param {string} origin * @param {import("./types.js").SettingsStore} store * @returns {void} */ function installSettingsListeners(origin, store) { + clearSettingsListeners() logger.bindSettings(store) - store.on('hidePageAction', (hidden) => { - if (!hidden) pageActionMarked = false - }) - store.on('dataPlane', (dp) => applyDataPlane(dp, origin)) - store.on('workerSpawnMode', () => { - cachedSpawnModes.delete(origin) - applyDataPlane(store.dataPlane, origin) - }) - store.on('useWorker', () => applyDataPlane(store.dataPlane, origin)) - store.on(['dataPlane', 'logLevel'], () => { - const all = store.getAll() - const patch = { dataPlane: all.dataPlane, logLevel: all.logLevel } - for (const [port, context] of frameContextByPort) { - if (context.origin === origin) port.postMessage({ type: 'settings', settings: patch }) - } - for (const [key, entry] of workers) { - const context = contextForPlaneKey(key) - if (context && context.origin === origin && entry.worker) { - entry.worker.postMessage({ type: 'settings', ...patch }) + settingsListenerDisposers = [ + store.on('hidePageAction', (hidden) => { + if (!hidden) pageActionMarked = false + }), + store.on('dataPlane', (dp) => applyDataPlane(dp, origin)), + store.on('workerSpawnMode', () => { + cachedSpawnModes.delete(origin) + applyDataPlane(store.dataPlane, origin) + }), + store.on('useWorker', () => applyDataPlane(store.dataPlane, origin)), + store.on(['dataPlane', 'logLevel'], () => { + const all = store.getAll() + const patch = { dataPlane: all.dataPlane, logLevel: all.logLevel } + for (const [port, context] of frameContextByPort) { + if (context.origin === origin) port.postMessage({ type: 'settings', settings: patch }) } - } - }) + for (const [key, entry] of workers) { + const context = contextForPlaneKey(key) + if (context && context.origin === origin && entry.worker) { + entry.worker.postMessage({ type: 'settings', ...patch }) + } + } + }) + ] } browser.storage.onChanged.addListener((changes, area) => { diff --git a/addon/js/internal/pages/popup/index.js b/addon/js/internal/pages/popup/index.js index d22b121..cbf0553 100644 --- a/addon/js/internal/pages/popup/index.js +++ b/addon/js/internal/pages/popup/index.js @@ -428,12 +428,13 @@ * @returns {Promise} */ async function removeDevice(deviceIds) { - if (!origin || !deviceIds || !deviceIds.length) return + if (!persistentOrigin || !deviceIds || !deviceIds.length) return try { await browser.runtime.sendMessage({ action: 'revokeDevice', deviceIds, - origin + origin, + persistentOrigin }) } catch (e) { logger.debug('revokeDevice failed', e) diff --git a/tests/unit/frame-endpoint-topology.test.js b/tests/unit/frame-endpoint-topology.test.js index b863eb8..9ce20ac 100644 --- a/tests/unit/frame-endpoint-topology.test.js +++ b/tests/unit/frame-endpoint-topology.test.js @@ -53,6 +53,11 @@ test('frame-origin API preserves opaque persistent target metadata', () => { assert.match(messages, /kind: 'opaque'/) assert.match(messages, /persistentOrigin: endpoint\.persistentOrigin/) }) +test('settings scope transitions keep one listener subscription set', () => { + assert.match(bridge, /settingsListenerDisposers/) + assert.match(bridge, /clearSettingsListeners\(\)/) + assert.match(bridge, /settingsListenerDisposers = \[/) +}) test('authority metadata gates local origin-sensitive state', () => { assert.match(messages, /action: 'endpointMetadata'/) assert.match(messages, /typeof sender\.origin/) From 970c218ece867ea1de9245605378c6e7b9bf59db Mon Sep 17 00:00:00 2001 From: Kazoku Date: Sun, 13 Sep 2026 22:54:48 +0700 Subject: [PATCH 12/26] test(addon): cover partition-aware popup revoke --- tests/browser/page-action.spec.ts | 77 +++++++++++++++++++++++++++---- 1 file changed, 69 insertions(+), 8 deletions(-) diff --git a/tests/browser/page-action.spec.ts b/tests/browser/page-action.spec.ts index 8fcb8ff..2ccf150 100644 --- a/tests/browser/page-action.spec.ts +++ b/tests/browser/page-action.spec.ts @@ -167,10 +167,15 @@ test.describe('extension action surfaces', () => { await sharedPage.goto(pageUrl('/test-page.html'), { waitUntil: 'domcontentloaded' }) await page.addInitScript( (target) => { - const calls: Array<{ action: string; origin: unknown }> = [] - Object.defineProperty(globalThis, '__popupStatusCalls', { value: calls }) + const calls: Array<{ + action: string + origin: unknown + persistentOrigin?: unknown + deviceIds?: unknown + }> = [] + Object.defineProperty(globalThis, 'popupStatusCalls', { value: calls }) const saved: unknown[] = [] - Object.defineProperty(globalThis, '__popupSaved', { value: saved }) + Object.defineProperty(globalThis, 'popupSaved', { value: saved }) const storageSet = browser.storage.local.set.bind(browser.storage.local) browser.storage.local.set = async (value) => { saved.push(value) @@ -208,6 +213,15 @@ test.describe('extension action surfaces', () => { ? { planes: [{ deviceId: '1', plane: 'ws', mode: 'worker' }], defaultPlane: 'nm' } : { planes: [], defaultPlane: 'nm' } } + if (request.action === 'revokeDevice') { + calls.push({ + action: 'revokeDevice', + origin: request.origin, + persistentOrigin: (request as { persistentOrigin?: unknown }).persistentOrigin, + deviceIds: (request as { deviceIds?: unknown }).deviceIds + }) + return { success: true } + } if (request.action === 'getOpenDeviceIds') { calls.push({ action: 'getOpenDeviceIds', origin: request.origin }) return request.origin === target.persistent ? { ids: ['1'] } : { ids: [] } @@ -222,7 +236,7 @@ test.describe('extension action surfaces', () => { ) await page.goto(popupUrl, { waitUntil: 'domcontentloaded', timeout: 15000 }) const before = await page.evaluate(() => { - const value = (globalThis as unknown as { __popupStatusCalls?: unknown }).__popupStatusCalls + const value = (globalThis as unknown as { popupStatusCalls?: unknown }).popupStatusCalls return Array.isArray(value) ? value.length : 0 }) await page.locator('#site-name').click() @@ -236,17 +250,39 @@ test.describe('extension action surfaces', () => { .poll(() => page.evaluate( (key) => - (globalThis as unknown as { __popupSaved?: unknown[] }).__popupSaved?.some( + (globalThis as unknown as { popupSaved?: unknown[] }).popupSaved?.some( (entry) => entry != null && typeof entry === 'object' && key in entry ) || false, `settings :: ${selectedPersistent} :: dataPlane` ) ) .toBe(true) - await expect(page.locator('#status')).toHaveClass(/state-warn/) + await page.locator('#btn-settings').click() + await page.locator('.btn-revoke').first().click() + await expect + .poll(() => + page.evaluate(() => { + const calls = + (globalThis as unknown as { + popupStatusCalls?: Array<{ + action?: string + origin?: unknown + persistentOrigin?: unknown + deviceIds?: unknown + }> + }).popupStatusCalls || [] + return calls.find((entry) => entry.action === 'revokeDevice') || null + }) + ) + .toMatchObject({ + action: 'revokeDevice', + origin: 'null', + persistentOrigin: selectedPersistent, + deviceIds: [1] + }) await page.waitForFunction( ({ start, origin }) => { - const calls = (globalThis as unknown as { __popupStatusCalls?: unknown }).__popupStatusCalls + const calls = (globalThis as unknown as { popupStatusCalls?: unknown }).popupStatusCalls if (!Array.isArray(calls)) return false const after = calls.slice(start) return ( @@ -264,7 +300,7 @@ test.describe('extension action surfaces', () => { { timeout: 15000 } ) const calls = await page.evaluate(() => { - const value = (globalThis as unknown as { __popupStatusCalls?: unknown }).__popupStatusCalls + const value = (globalThis as unknown as { popupStatusCalls?: unknown }).popupStatusCalls return Array.isArray(value) ? (value as Array<{ action: string; origin: unknown }>) : [] }) const afterSelection = calls.slice(before) @@ -274,6 +310,31 @@ test.describe('extension action surfaces', () => { { action: 'getOpenDeviceIds', origin: selectedPersistent } ]) ) + await page.locator('#site-name').click() + await page.locator('#origin-list li').first().click() + await expect(page.locator('#site-name-text')).toHaveText(activeOrigin) + await page.locator('.btn-revoke').first().click() + await expect + .poll(() => + page.evaluate(() => { + const calls = + (globalThis as unknown as { + popupStatusCalls?: Array<{ + action?: string + origin?: unknown + persistentOrigin?: unknown + deviceIds?: unknown + }> + }).popupStatusCalls || [] + return [...calls].reverse().find((entry) => entry.action === 'revokeDevice') || null + }) + ) + .toMatchObject({ + action: 'revokeDevice', + origin: activeOrigin, + persistentOrigin: activeOrigin, + deviceIds: [1] + }) }) test('hidden page action stays visible during its pending picker', async ({ backgroundPage, From c3a1a357b37f3ef4da2c04350debf3d20b7acb3b Mon Sep 17 00:00:00 2001 From: Kazoku Date: Sun, 13 Sep 2026 23:05:58 +0700 Subject: [PATCH 13/26] fix(addon): make settings listeners disposable --- addon/js/content/isolated/bridge.js | 66 +++++++++++----------- addon/js/utils/settings.js | 23 ++++++++ tests/unit/frame-endpoint-topology.test.js | 6 +- tests/unit/settings.test.js | 15 +++++ 4 files changed, 73 insertions(+), 37 deletions(-) diff --git a/addon/js/content/isolated/bridge.js b/addon/js/content/isolated/bridge.js index fdeec5f..6c8736e 100644 --- a/addon/js/content/isolated/bridge.js +++ b/addon/js/content/isolated/bridge.js @@ -7,6 +7,7 @@ const isChromium = webhid.import('isChromium') const http = webhid.import('http') const createSettingsStore = webhid.import('createSettingsStore') + const createSettingsListenerSet = webhid.import('createSettingsListenerSet') const loadEffectiveSettings = webhid.import('loadEffectiveSettings') const loadSiteSettings = webhid.import('loadSiteSettings') const parseSettingsKey = webhid.import('parseSettingsKey') @@ -2793,50 +2794,47 @@ logger.info('data plane changed:', dp, 'open devices:', active.length) } - /** @type {Array<(() => void)|undefined>} */ - let settingsListenerDisposers = [] - /** - * Removes the active settings side-effect listeners. - * @returns {void} - */ - function clearSettingsListeners() { - for (const dispose of settingsListenerDisposers) { - if (typeof dispose === 'function') dispose() - } - settingsListenerDisposers = [] - } + const settingsListenerSet = createSettingsListenerSet() /** * @param {string} origin * @param {import("./types.js").SettingsStore} store * @returns {void} */ function installSettingsListeners(origin, store) { - clearSettingsListeners() logger.bindSettings(store) - settingsListenerDisposers = [ - store.on('hidePageAction', (hidden) => { - if (!hidden) pageActionMarked = false - }), - store.on('dataPlane', (dp) => applyDataPlane(dp, origin)), - store.on('workerSpawnMode', () => { - cachedSpawnModes.delete(origin) - applyDataPlane(store.dataPlane, origin) - }), - store.on('useWorker', () => applyDataPlane(store.dataPlane, origin)), - store.on(['dataPlane', 'logLevel'], () => { - const all = store.getAll() - const patch = { dataPlane: all.dataPlane, logLevel: all.logLevel } - for (const [port, context] of frameContextByPort) { - if (context.origin === origin) port.postMessage({ type: 'settings', settings: patch }) + settingsListenerSet.install(store, [ + [ + 'hidePageAction', + (hidden) => { + if (!hidden) pageActionMarked = false + } + ], + ['dataPlane', (dp) => applyDataPlane(dp, origin)], + [ + 'workerSpawnMode', + () => { + cachedSpawnModes.delete(origin) + applyDataPlane(store.dataPlane, origin) } - for (const [key, entry] of workers) { - const context = contextForPlaneKey(key) - if (context && context.origin === origin && entry.worker) { - entry.worker.postMessage({ type: 'settings', ...patch }) + ], + ['useWorker', () => applyDataPlane(store.dataPlane, origin)], + [ + ['dataPlane', 'logLevel'], + () => { + const all = store.getAll() + const patch = { dataPlane: all.dataPlane, logLevel: all.logLevel } + for (const [port, context] of frameContextByPort) { + if (context.origin === origin) port.postMessage({ type: 'settings', settings: patch }) + } + for (const [key, entry] of workers) { + const context = contextForPlaneKey(key) + if (context && context.origin === origin && entry.worker) { + entry.worker.postMessage({ type: 'settings', ...patch }) + } } } - }) - ] + ] + ]) } browser.storage.onChanged.addListener((changes, area) => { diff --git a/addon/js/utils/settings.js b/addon/js/utils/settings.js index 2018b43..4f5ca7b 100644 --- a/addon/js/utils/settings.js +++ b/addon/js/utils/settings.js @@ -196,9 +196,32 @@ } }) } + /** + * Creates an idempotent subscription set for a long-lived settings store. + * @returns {{install: Function, dispose: Function}} + */ + function createSettingsListenerSet() { + let disposers = [] + function dispose() { + for (const disposer of disposers) { + if (typeof disposer === 'function') disposer() + } + disposers = [] + } + return { + install(store, registrations) { + dispose() + disposers = registrations + .map(([keys, callback]) => store.on(keys, callback)) + .filter((disposer) => typeof disposer === 'function') + }, + dispose + } + } webhid.export('GLOBAL_DEFAULTS', GLOBAL_DEFAULTS) webhid.export('createSettingsStore', createSettingsStore) + webhid.export('createSettingsListenerSet', createSettingsListenerSet) const SETTING_NAMES = object.keys(GLOBAL_DEFAULTS) diff --git a/tests/unit/frame-endpoint-topology.test.js b/tests/unit/frame-endpoint-topology.test.js index 9ce20ac..99ce6ca 100644 --- a/tests/unit/frame-endpoint-topology.test.js +++ b/tests/unit/frame-endpoint-topology.test.js @@ -54,9 +54,9 @@ test('frame-origin API preserves opaque persistent target metadata', () => { assert.match(messages, /persistentOrigin: endpoint\.persistentOrigin/) }) test('settings scope transitions keep one listener subscription set', () => { - assert.match(bridge, /settingsListenerDisposers/) - assert.match(bridge, /clearSettingsListeners\(\)/) - assert.match(bridge, /settingsListenerDisposers = \[/) + assert.match(bridge, /createSettingsListenerSet/) + assert.match(bridge, /settingsListenerSet\.install/) + assert.match(bridge, /logger\.bindSettings/) }) test('authority metadata gates local origin-sensitive state', () => { assert.match(messages, /action: 'endpointMetadata'/) diff --git a/tests/unit/settings.test.js b/tests/unit/settings.test.js index 83f22fa..d8aa685 100644 --- a/tests/unit/settings.test.js +++ b/tests/unit/settings.test.js @@ -119,3 +119,18 @@ test('opaque persistence partitions use trusted embedder and source origins', () ) assert.equal(exports.persistentSiteScope('null', 'https://widget.example/app', null), null) }) +test('settings listener set replaces disposed subscriptions', () => { + const { exports } = loadSettings() + const store = exports.createSettingsStore({ dataPlane: 'nm' }) + const listenerSet = exports.createSettingsListenerSet() + let changes = 0 + listenerSet.install(store, [['dataPlane', () => changes++]]) + store.set({ dataPlane: 'ws' }) + assert.equal(changes, 1) + listenerSet.install(store, [['dataPlane', () => changes++]]) + store.set({ dataPlane: 'nm' }) + assert.equal(changes, 2) + listenerSet.dispose() + store.set({ dataPlane: 'ws' }) + assert.equal(changes, 2) +}) From 25dcf7bab37c9a224453f6bd5b58897910bccd65 Mon Sep 17 00:00:00 2001 From: Kazoku Date: Sun, 13 Sep 2026 23:44:19 +0700 Subject: [PATCH 14/26] fix(addon): use canonical opaque persistence keys --- addon/js/internal/pages/popup/index.js | 17 +++++++- addon/js/utils/settings.js | 4 +- tests/browser/page-action.spec.ts | 42 ++++++++++--------- tests/browser/permissions-policy.spec.ts | 51 ++++++++++++++---------- tests/unit/settings.test.js | 2 +- 5 files changed, 71 insertions(+), 45 deletions(-) diff --git a/addon/js/internal/pages/popup/index.js b/addon/js/internal/pages/popup/index.js index cbf0553..88e508e 100644 --- a/addon/js/internal/pages/popup/index.js +++ b/addon/js/internal/pages/popup/index.js @@ -103,12 +103,25 @@ function selectedTarget() { return frameTargets.find((target) => target.persistentOrigin === persistentOrigin) } + /** + * Derives opaque target labels from the canonical persistence identity. + * @param {SiteTarget|undefined} target + * @returns {string} + */ + function labelForTarget(target) { + if (!target) return origin || t('popupNoSite') + if (target.kind !== 'opaque' || !target.persistentOrigin) return target.label + const parts = target.persistentOrigin.split('|') + return parts.length === 3 && parts[0] === 'opaque' + ? `${parts[2]} (Opaque iframe)` + : target.label + } /** * @returns {void} */ function renderSiteLabel() { - siteLabel.textContent = selectedTarget()?.label || origin || t('popupNoSite') + siteLabel.textContent = labelForTarget(selectedTarget()) siteButton.classList.toggle('has-list', frameTargets.length > 1) siteButton.setAttribute('aria-expanded', 'false') originList.hidden = true @@ -162,7 +175,7 @@ li.setAttribute('role', 'option') li.setAttribute('tabindex', '-1') li.dataset.persistentOrigin = target.persistentOrigin || '' - li.textContent = target.label + li.textContent = labelForTarget(target) li.addEventListener('click', () => selectTarget(target)) originList.appendChild(li) } diff --git a/addon/js/utils/settings.js b/addon/js/utils/settings.js index 4f5ca7b..1f4ad42 100644 --- a/addon/js/utils/settings.js +++ b/addon/js/utils/settings.js @@ -288,9 +288,7 @@ void 0 } if (!sourceOrigin || !topAuthorityOrigin || topAuthorityOrigin === 'null') return null - return ( - 'opaque|' + encodeURIComponent(topAuthorityOrigin) + '|' + encodeURIComponent(sourceOrigin) - ) + return `opaque|${topAuthorityOrigin}|${sourceOrigin}` } /** diff --git a/tests/browser/page-action.spec.ts b/tests/browser/page-action.spec.ts index 2ccf150..4d1205c 100644 --- a/tests/browser/page-action.spec.ts +++ b/tests/browser/page-action.spec.ts @@ -163,7 +163,7 @@ test.describe('extension action surfaces', () => { pageUrl }) => { const activeOrigin = new URL(pageUrl('/')).origin - const selectedPersistent = 'opaque|https%3A%2F%2Fhost.example|https%3A%2F%2Fwidget.example' + const selectedPersistent = 'opaque|https://host.example|https://widget.example' await sharedPage.goto(pageUrl('/test-page.html'), { waitUntil: 'domcontentloaded' }) await page.addInitScript( (target) => { @@ -241,7 +241,9 @@ test.describe('extension action surfaces', () => { }) await page.locator('#site-name').click() await page.locator('#origin-list li').nth(1).click() - await expect(page.locator('#site-name-text')).toHaveText('Opaque iframe') + await expect(page.locator('#site-name-text')).toHaveText( + 'https://widget.example (Opaque iframe)' + ) await page.locator('#btn-settings').click() await page .locator('input[name="dataPlane"][value="nm"]') @@ -263,14 +265,16 @@ test.describe('extension action surfaces', () => { .poll(() => page.evaluate(() => { const calls = - (globalThis as unknown as { - popupStatusCalls?: Array<{ - action?: string - origin?: unknown - persistentOrigin?: unknown - deviceIds?: unknown - }> - }).popupStatusCalls || [] + ( + globalThis as unknown as { + popupStatusCalls?: Array<{ + action?: string + origin?: unknown + persistentOrigin?: unknown + deviceIds?: unknown + }> + } + ).popupStatusCalls || [] return calls.find((entry) => entry.action === 'revokeDevice') || null }) ) @@ -318,14 +322,16 @@ test.describe('extension action surfaces', () => { .poll(() => page.evaluate(() => { const calls = - (globalThis as unknown as { - popupStatusCalls?: Array<{ - action?: string - origin?: unknown - persistentOrigin?: unknown - deviceIds?: unknown - }> - }).popupStatusCalls || [] + ( + globalThis as unknown as { + popupStatusCalls?: Array<{ + action?: string + origin?: unknown + persistentOrigin?: unknown + deviceIds?: unknown + }> + } + ).popupStatusCalls || [] return [...calls].reverse().find((entry) => entry.action === 'revokeDevice') || null }) ) diff --git a/tests/browser/permissions-policy.spec.ts b/tests/browser/permissions-policy.spec.ts index b22dc3c..01da8c5 100644 --- a/tests/browser/permissions-policy.spec.ts +++ b/tests/browser/permissions-policy.spec.ts @@ -250,13 +250,14 @@ test.describe('Cross-origin iframe', () => { await page.evaluate( ({ mainSrc, crossSrc }) => { for (const [id, src] of [ - ['opaque-a', mainSrc], - ['opaque-b', crossSrc] + ['opaque-a', mainSrc + '/iframe-child-no-allow?path=a'], + ['opaque-b', crossSrc + '/iframe-child-no-allow?path=b'], + ['opaque-c', mainSrc + '/iframe-child-no-allow?path=c'] ]) { const frame = document.createElement('iframe') frame.id = id frame.setAttribute('sandbox', 'allow-scripts') - frame.src = src + '/iframe-child-no-allow' + frame.src = src document.body.appendChild(frame) } }, @@ -264,6 +265,7 @@ test.describe('Cross-origin iframe', () => { ) await frameWithId(page, 'opaque-a', '/iframe-child-no-allow') await frameWithId(page, 'opaque-b', '/iframe-child-no-allow') + await frameWithId(page, 'opaque-c', '/iframe-child-no-allow') const targets = (await backgroundPage.evaluate(async () => { const tabs = await browser.tabs.query({ active: true, currentWindow: true }) const tab = tabs[0] @@ -277,26 +279,33 @@ test.describe('Cross-origin iframe', () => { const opaqueTargets = targets.filter((target) => target.kind === 'opaque') expect(opaqueTargets).toHaveLength(2) expect(opaqueTargets[0].persistentOrigin).not.toBe(opaqueTargets[1].persistentOrigin) - const scope = opaqueTargets[0].persistentOrigin - if (typeof scope !== 'string') throw new Error('opaque target has no persistent scope') - const delivered = await backgroundPage.evaluate((persistentScope) => { - const fanout = ( - globalThis as unknown as { - webhid: { - import(name: string): { - postToPersistentOriginEndpoints(scope: string, message: object): number + const scopeA = opaqueTargets[0].persistentOrigin + const scopeB = opaqueTargets[1].persistentOrigin + if (typeof scopeA !== 'string' || typeof scopeB !== 'string') + throw new Error('opaque target has no persistent scope') + const delivered = await backgroundPage.evaluate( + ({ scopeA, scopeB }) => { + const fanout = ( + globalThis as unknown as { + webhid: { + import(name: string): { + postToPersistentOriginEndpoints(scope: string, message: object): number + } } } - } - ).webhid.import('backgroundEventFanout') - return fanout.postToPersistentOriginEndpoints(persistentScope, { - action: 'allowedDevicesChanged', - origin: 'null', - persistentOrigin: persistentScope, - deviceIds: [] - }) - }, scope) - expect(delivered).toBe(1) + ).webhid.import('backgroundEventFanout') + const send = (scope: string) => + fanout.postToPersistentOriginEndpoints(scope, { + action: 'allowedDevicesChanged', + origin: 'null', + persistentOrigin: scope, + deviceIds: [] + }) + return { scopeA: send(scopeA), scopeB: send(scopeB) } + }, + { scopeA, scopeB } + ) + expect(delivered).toEqual({ scopeA: 2, scopeB: 1 }) }) test('B2: top-level hid=() denies a delegated cross-origin child', async ({ page, diff --git a/tests/unit/settings.test.js b/tests/unit/settings.test.js index d8aa685..4c0fa81 100644 --- a/tests/unit/settings.test.js +++ b/tests/unit/settings.test.js @@ -96,7 +96,7 @@ test('settings updates and overlays survive a poisoned array iterator', async () assert.equal(result.changes[0], 2) assert.equal(result.effective.dataPlane, 'ws') assert.equal(result.opaque.dataPlane, result.global.dataPlane) - assert.equal(result.opaqueScope, 'opaque|https%3A%2F%2Fhost.example|https%3A%2F%2Fwidget.example') + assert.equal(result.opaqueScope, 'opaque|https://host.example|https://widget.example') assert.equal(exports.isPersistentSiteOrigin('null'), false) assert.equal(exports.isPersistentSiteOrigin(result.opaqueScope), true) }) From dfc666913f2a163d965d54d951544f667ec2f6c7 Mon Sep 17 00:00:00 2001 From: Kazoku Date: Mon, 14 Sep 2026 00:29:33 +0700 Subject: [PATCH 15/26] fix(addon): resync MAIN after scope changes --- addon/js/content/isolated/bridge.js | 19 ++++++++++++++++++- addon/js/content/main/index.js | 5 +++++ tests/unit/frame-endpoint-topology.test.js | 8 ++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/addon/js/content/isolated/bridge.js b/addon/js/content/isolated/bridge.js index 6c8736e..4465494 100644 --- a/addon/js/content/isolated/bridge.js +++ b/addon/js/content/isolated/bridge.js @@ -31,6 +31,7 @@ const pickerResultHandlers = new Map() let authorityOrigin = '' let persistentOrigin = null + let scopeLoadGeneration = 0 let authorityFailed = false let resolveAuthorityReady = null const authorityReady = new Promise((resolve) => { @@ -678,7 +679,23 @@ loadedOrigins.delete(previousPersistentOrigin || '') loadAllowedDeviceIds(persistentOrigin || '') } - if (!firstInitialization) void loadSettingsForOrigin(authorityOrigin) + } + if (scopeChanged && !firstInitialization) { + const expectedScope = persistentOrigin + const generation = ++scopeLoadGeneration + void loadSettingsForOrigin(authorityOrigin).then((store) => { + if ( + generation !== scopeLoadGeneration || + persistentOrigin !== expectedScope || + !frameContext || + frameContext.destroyed + ) + return + frameContext.port.postMessage({ + type: 'persistentScopeChanged', + settings: store.getAll() + }) + }) } settleAuthorityReady() } diff --git a/addon/js/content/main/index.js b/addon/js/content/main/index.js index 2c557d3..b577686 100644 --- a/addon/js/content/main/index.js +++ b/addon/js/content/main/index.js @@ -846,6 +846,11 @@ settings: (data) => { settings.set(data.settings || {}) }, + persistentScopeChanged: (data) => { + settings.set(data.settings || {}) + pairedDevices = null + deviceInfoCache = null + }, event: (data) => { dispatchDeviceEvent(data.event) } diff --git a/tests/unit/frame-endpoint-topology.test.js b/tests/unit/frame-endpoint-topology.test.js index 99ce6ca..01c2288 100644 --- a/tests/unit/frame-endpoint-topology.test.js +++ b/tests/unit/frame-endpoint-topology.test.js @@ -65,6 +65,14 @@ test('authority metadata gates local origin-sensitive state', () => { assert.match(bridge, /await authorityReady/) assert.match(main, /await settingsReady/) }) +test('scope changes resync full MAIN settings and invalidate paired devices', () => { + assert.match(bridge, /type: 'persistentScopeChanged'/) + assert.match(bridge, /scopeLoadGeneration/) + assert.match(bridge, /generation !== scopeLoadGeneration/) + assert.match(main, /persistentScopeChanged: \(data\)/) + assert.match(main, /pairedDevices = null/) + assert.match(main, /deviceInfoCache = null/) +}) test('MAIN settings readiness waits for the initial snapshot', () => { const liveSettings = main.match(/settings: \(data\) => \{[\s\S]*?\n \},/) assert.ok(liveSettings) From 1c88bf912cc3c1dc15647abb6fc5bb0c39883caa Mon Sep 17 00:00:00 2001 From: Kazoku Date: Mon, 14 Sep 2026 00:33:41 +0700 Subject: [PATCH 16/26] fix(addon): derive opaque target labels in popup --- addon/js/background/messages.js | 1 - tests/unit/frame-endpoint-topology.test.js | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/addon/js/background/messages.js b/addon/js/background/messages.js index 09a0478..d1a51fd 100644 --- a/addon/js/background/messages.js +++ b/addon/js/background/messages.js @@ -1084,7 +1084,6 @@ seen.add(endpoint.persistentOrigin) targets.push({ kind: 'opaque', - label: 'Opaque iframe', origin: endpoint.origin, persistentOrigin: endpoint.persistentOrigin }) diff --git a/tests/unit/frame-endpoint-topology.test.js b/tests/unit/frame-endpoint-topology.test.js index 01c2288..08c0d90 100644 --- a/tests/unit/frame-endpoint-topology.test.js +++ b/tests/unit/frame-endpoint-topology.test.js @@ -52,6 +52,7 @@ test('frame-origin API preserves opaque persistent target metadata', () => { assert.match(messages, /targets\.push/) assert.match(messages, /kind: 'opaque'/) assert.match(messages, /persistentOrigin: endpoint\.persistentOrigin/) + assert.doesNotMatch(messages, /kind: 'opaque',\s+label:/) }) test('settings scope transitions keep one listener subscription set', () => { assert.match(bridge, /createSettingsListenerSet/) From 104d30d6762d24618a1707f271a6d7b693d4dbc2 Mon Sep 17 00:00:00 2001 From: Kazoku Date: Mon, 14 Sep 2026 00:59:02 +0700 Subject: [PATCH 17/26] fix(addon): bind scope loads to captured identities --- addon/js/content/isolated/bridge.js | 28 +++++++------------ addon/js/internal/pages/popup/index.js | 7 +++-- addon/js/utils/settings.js | 38 ++++++++++++++++++++++++++ tests/unit/settings.test.js | 31 +++++++++++++++++++++ 4 files changed, 83 insertions(+), 21 deletions(-) diff --git a/addon/js/content/isolated/bridge.js b/addon/js/content/isolated/bridge.js index 4465494..8770251 100644 --- a/addon/js/content/isolated/bridge.js +++ b/addon/js/content/isolated/bridge.js @@ -8,6 +8,7 @@ const http = webhid.import('http') const createSettingsStore = webhid.import('createSettingsStore') const createSettingsListenerSet = webhid.import('createSettingsListenerSet') + const createScopedSettingsLoader = webhid.import('createScopedSettingsLoader') const loadEffectiveSettings = webhid.import('loadEffectiveSettings') const loadSiteSettings = webhid.import('loadSiteSettings') const parseSettingsKey = webhid.import('parseSettingsKey') @@ -600,8 +601,6 @@ const settings = createSettingsStore(webhid.import('GLOBAL_DEFAULTS')) /** @type {Map} */ const settingsByOrigin = new Map() - /** @type {Map>} */ - const settingsLoads = new Map() /** * Maps authority identity to its persistent settings partition. * @param {string} origin @@ -618,26 +617,19 @@ installSettingsListeners(origin, store) return store } + const settingsLoader = createScopedSettingsLoader( + loadEffectiveSettings, + settingsScopeForOrigin, + settingsForOrigin, + () => authorityOrigin, + (error, scope) => logger.warn('load settings failed for', scope, ':', error.message) + ) /** * @param {string} origin * @returns {Promise} */ function loadSettingsForOrigin(origin) { - const scope = settingsScopeForOrigin(origin) - const existing = settingsLoads.get(scope) - if (existing) return existing - const load = loadEffectiveSettings(scope) - .then((values) => { - const store = settingsForOrigin(origin) - store.set(values) - return store - }) - .catch((error) => { - logger.warn('load settings failed for', scope, ':', error.message) - return settingsForOrigin(origin) - }) - settingsLoads.set(scope, load) - return load + return settingsLoader.load(origin) } /** @returns {void} */ function settleAuthorityReady() { @@ -671,7 +663,7 @@ } if (firstInitialization || scopeChanged) { settingsByOrigin.clear() - settingsLoads.clear() + settingsLoader.clear() settingsByOrigin.set(persistentOrigin || '', settings) installSettingsListeners(authorityOrigin, settings) if (scopeChanged) { diff --git a/addon/js/internal/pages/popup/index.js b/addon/js/internal/pages/popup/index.js index 88e508e..20975e5 100644 --- a/addon/js/internal/pages/popup/index.js +++ b/addon/js/internal/pages/popup/index.js @@ -63,7 +63,7 @@ const originList = document.getElementById('origin-list') /** - * @typedef {{kind: string, label: string, origin: string, persistentOrigin: string|null}} SiteTarget + * @typedef {{kind: string, label?: string, origin: string, persistentOrigin: string|null}} SiteTarget */ /** * Collects addressable settings targets in the active tab. @@ -110,11 +110,12 @@ */ function labelForTarget(target) { if (!target) return origin || t('popupNoSite') - if (target.kind !== 'opaque' || !target.persistentOrigin) return target.label + if (target.kind !== 'opaque' || !target.persistentOrigin) + return target.label || target.origin const parts = target.persistentOrigin.split('|') return parts.length === 3 && parts[0] === 'opaque' ? `${parts[2]} (Opaque iframe)` - : target.label + : target.label || target.origin } /** diff --git a/addon/js/utils/settings.js b/addon/js/utils/settings.js index 1f4ad42..1defcb4 100644 --- a/addon/js/utils/settings.js +++ b/addon/js/utils/settings.js @@ -218,10 +218,48 @@ dispose } } + /** + * Binds an async settings load to the scope it started for. + * @param {(scope: string) => Promise} loadValues + * @param {(origin: string) => string} getScope + * @param {(origin: string) => object} getStore + * @param {() => string} getCurrentOrigin + * @param {(error: Error, scope: string) => void} [onError] + * @returns {{load: (origin: string) => Promise, clear: () => void}} + */ + function createScopedSettingsLoader(loadValues, getScope, getStore, getCurrentOrigin, onError) { + const loads = new Map() + function load(origin) { + const scope = getScope(origin) + const existing = loads.get(scope) + if (existing) return existing + const promise = Promise.resolve(loadValues(scope)) + .then((values) => { + if (getScope(origin) !== scope) return load(getCurrentOrigin()) + const store = getStore(origin) + store.set(values) + return store + }) + .catch((error) => { + if (onError) onError(error, scope) + if (getScope(origin) !== scope) return load(getCurrentOrigin()) + return getStore(origin) + }) + loads.set(scope, promise) + return promise + } + return { + load, + clear() { + loads.clear() + } + } + } webhid.export('GLOBAL_DEFAULTS', GLOBAL_DEFAULTS) webhid.export('createSettingsStore', createSettingsStore) webhid.export('createSettingsListenerSet', createSettingsListenerSet) + webhid.export('createScopedSettingsLoader', createScopedSettingsLoader) const SETTING_NAMES = object.keys(GLOBAL_DEFAULTS) diff --git a/tests/unit/settings.test.js b/tests/unit/settings.test.js index 4c0fa81..b6de315 100644 --- a/tests/unit/settings.test.js +++ b/tests/unit/settings.test.js @@ -134,3 +134,34 @@ test('settings listener set replaces disposed subscriptions', () => { store.set({ dataPlane: 'ws' }) assert.equal(changes, 2) }) +test('stale scoped loads cannot mutate the newer scope', async () => { + const { exports } = loadSettings() + const stores = { + A: exports.createSettingsStore({ dataPlane: 'nm' }), + B: exports.createSettingsStore({ dataPlane: 'nm' }) + } + let currentScope = 'A' + let resolveA + let resolveB + const loader = exports.createScopedSettingsLoader( + (scope) => + new Promise((resolve) => { + if (scope === 'A') resolveA = resolve + else resolveB = resolve + }), + () => currentScope, + () => stores[currentScope], + () => 'authority' + ) + const first = loader.load('authority') + currentScope = 'B' + loader.clear() + const second = loader.load('authority') + resolveB({ dataPlane: 'ws' }) + await second + resolveA({ dataPlane: 'nm' }) + await first + + assert.equal(stores.B.dataPlane, 'ws') + assert.equal(stores.A.dataPlane, 'nm') +}) From c3765f66c978e0942bc9bf15dbc5b5ef36adb7ae Mon Sep 17 00:00:00 2001 From: Kazoku Date: Mon, 14 Sep 2026 23:26:39 +0700 Subject: [PATCH 18/26] fix(addon): enforce exact document policy authority --- addon/js/background/messages.js | 396 ++++++++++++++++----- addon/js/background/state_ops.js | 27 +- addon/js/content/isolated/bridge.js | 91 ++++- tests/browser/permissions-policy.spec.ts | 168 +++++++++ tests/e2e/nm-runtime-port.spec.ts | 115 ++++++ tests/unit/frame-endpoint-topology.test.js | 20 ++ tests/unit/state-ops.test.js | 33 +- 7 files changed, 742 insertions(+), 108 deletions(-) diff --git a/addon/js/background/messages.js b/addon/js/background/messages.js index d1a51fd..9f278ea 100644 --- a/addon/js/background/messages.js +++ b/addon/js/background/messages.js @@ -42,7 +42,8 @@ collectDevicePlaneStatuses, collectOpenDeviceIdsForTab, setBadgeRefresh, - closeForCleanup + closeForCleanup, + closeFrameSessions } = webhid.import('bgStateOps') const { urlOrigin, frameKey, documentFrameKey } = webhid.import('bgCsp') const NativeMessaging = webhid.import('NativeMessaging') @@ -67,13 +68,14 @@ let nextEndpointId = 0 /** - * Returns the registered top-frame endpoint for a tab. + * Returns the registered live top-frame endpoint for a tab. * @param {number} tabId * @returns {object|null} */ function topEndpointForTab(tabId) { for (const endpoint of frameEndpoints.values()) { - if (endpoint.tabId === tabId && endpoint.frameId === 0) return endpoint + if (endpoint.tabId === tabId && endpoint.frameId === 0 && endpointDocumentIsLive(endpoint)) + return endpoint } return null } @@ -107,12 +109,58 @@ const top = topEndpointForTab(tabId) for (const endpoint of frameEndpoints.values()) { if (endpoint.tabId !== tabId) continue - const persistentOrigin = persistentSiteScope(endpoint.origin, endpoint.url, top?.origin) + const persistentOrigin = top + ? persistentSiteScope(endpoint.origin, endpoint.url, top.origin) + : null if (endpoint.persistentOrigin === persistentOrigin) continue + const previousPersistentOrigin = endpoint.persistentOrigin endpoint.persistentOrigin = persistentOrigin + if (previousPersistentOrigin !== undefined) { + void closeFrameSessions(endpoint.tabId, endpoint.frameKey, (deviceId, token) => + NativeMessaging.closeDevice(deviceId, token) + ).catch((e) => logger.debug('scope transition cleanup failed', e)) + } sendEndpointMetadata(endpoint) } } + /** + * @param {object} endpoint + * @returns {void} + */ + function retireEndpoint(endpoint) { + if (frameEndpoints.get(endpoint.port) !== endpoint) return + frameEndpoints.delete(endpoint.port) + cancelEndpointDelegations(endpoint) + const exactKey = documentFrameKey(endpoint.tabId, endpoint.frameId, endpoint.documentId) + frameDelegations.delete(exactKey) + permissionsPolicy.delete(exactKey) + void purgeFrame(endpoint.tabId, endpoint.frameKey, (deviceId, token) => + NativeMessaging.closeDevice(deviceId, token) + ).catch((e) => logger.debug('frame endpoint cleanup failed', e)) + } + /** + * @param {object} endpoint + * @param {object} port + * @param {string|null|undefined} persistentOrigin + * @returns {boolean} + */ + function endpointAuthorityIsCurrent(endpoint, port, persistentOrigin) { + return ( + frameEndpoints.get(port) === endpoint && + isFrameLifetimeActive(endpoint.tabId, endpoint.frameKey) && + endpoint.persistentOrigin === persistentOrigin + ) + } + /** + * @param {object} endpoint + * @returns {boolean} + */ + function endpointDocumentIsLive(endpoint) { + return ( + frameEndpoints.get(endpoint.port) === endpoint && + isFrameLifetimeActive(endpoint.tabId, endpoint.frameKey) + ) + } /** * Selects the trusted persistence partition for one request. * @param {object} request @@ -123,6 +171,33 @@ ? request.persistentOrigin : request.origin || null } + /** + * Captures the browser-owned persistence authority for one request. + * @param {object} request + * @param {object} _sender + * @param {object|undefined} port + * @returns {{endpoint: object|null, port: object|undefined, persistentOrigin: string}|null} + */ + function scopeAuthorityForRequest(request, _sender, port) { + const endpoint = port ? endpointForPort(port) : null + if (port && !endpoint) return null + const persistentOrigin = endpoint + ? endpoint.persistentOrigin + : persistenceOriginForRequest(request) + if (!persistentOrigin) return null + if (endpoint && !endpointAuthorityIsCurrent(endpoint, port, persistentOrigin)) return null + return { endpoint, port, persistentOrigin } + } + /** + * @param {{endpoint: object|null, port: object|undefined, persistentOrigin: string}} authority + * @returns {boolean} + */ + function scopeAuthorityIsCurrent(authority) { + return ( + !authority.endpoint || + endpointAuthorityIsCurrent(authority.endpoint, authority.port, authority.persistentOrigin) + ) + } /** * Registers one browser-owned exact frame endpoint. * @param {object} port @@ -137,6 +212,10 @@ const origin = typeof sender.origin === 'string' && sender.origin ? sender.origin : null const url = typeof sender.url === 'string' ? sender.url : '' if (tabId == null || frameId == null || !origin) return null + for (const candidate of [...frameEndpoints.values()]) { + if (candidate.tabId === tabId && (frameId === 0 || candidate.frameId === frameId)) + retireEndpoint(candidate) + } const endpoint = { id: 'endpoint-' + ++nextEndpointId, port, @@ -215,19 +294,22 @@ action: 'frameDelegationQuery', requestId, childFrameId: endpoint.frameId, - childDocumentId: endpoint.documentId + childDocumentId: endpoint.documentId, + childOrigin: endpoint.origin, + parentOrigin: parent.origin }) }) } /** - * Sends an origin-scoped event to every registered exact frame endpoint. - * @param {string} origin - * @param {object} message + * Cancels delegation queries involving a retired endpoint. + * @param {object} endpoint * @returns {void} */ - function postToOriginEndpoints(origin, message) { - for (const endpoint of frameEndpoints.values()) { - if (endpoint.origin === origin) postToContentPort(endpoint.port, message) + function cancelEndpointDelegations(endpoint) { + for (const [requestId, pending] of delegationPending) { + if (pending.endpoint !== endpoint && pending.parent !== endpoint) continue + delegationPending.delete(requestId) + pending.resolve(false) } } /** @@ -279,11 +361,20 @@ * @param {string} authorityOrigin * @param {Set} toRevoke * @param {object[]} memberGroups - * @returns {Promise} + * @param {() => boolean} [isCurrent] + * @returns {Promise} */ - async function revokeDevices(persistentOrigin, authorityOrigin, toRevoke, memberGroups) { + async function revokeDevices( + persistentOrigin, + authorityOrigin, + toRevoke, + memberGroups, + isCurrent = () => true + ) { for (const deviceId of toRevoke) { + if (!isCurrent()) return false await removeAllowedDevice(persistentOrigin, deviceId) + if (!isCurrent()) return false removeDeviceInfo(deviceId) const tokens = collectDeviceSessionsForOrigin(deviceId, persistentOrigin) for (const token of tokens) { @@ -292,10 +383,14 @@ await closeForCleanup(deviceId, token, (id, sessionToken) => NativeMessaging.closeDevice(id, sessionToken) ) + if (!isCurrent()) return false } } + if (!isCurrent()) return false await deleteGrantGroups(memberGroups.map((g) => g.id)) + if (!isCurrent()) return false const deviceIds = await getAllowedDevices(persistentOrigin) + if (!isCurrent()) return false for (const deviceId of toRevoke) { postToPersistentOriginEndpoints(persistentOrigin, { action: 'webhidDeviceEvent', @@ -308,6 +403,7 @@ }) } notifyAllowedDevicesChanged(authorityOrigin, persistentOrigin, deviceIds) + return true } /** @@ -339,14 +435,28 @@ * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse + * @param {object} port * @returns {boolean} */ - function handleEnumeratePaired(request, sender, sendResponse) { - const origin = persistenceOriginForRequest(request) + function handleEnumeratePaired(request, sender, sendResponse, port) { + const authority = scopeAuthorityForRequest(request, sender, port) + const origin = authority?.persistentOrigin + if (!authority || !origin) { + sendResponse({ s: 403 }) + return true + } NativeMessaging.enumerateDevices() .then(async (response) => { + if (!scopeAuthorityIsCurrent(authority)) { + sendResponse({ s: 503 }) + return + } if (http.isOk(response.s) && response.D) { const ids = await getAllowedDevices(origin) + if (!scopeAuthorityIsCurrent(authority)) { + sendResponse({ s: 503 }) + return + } const paired = response.D.filter((d) => ids.includes(d.deviceId)) decodeDeviceCollections(paired) sendResponse({ s: response.s, D: paired }) @@ -404,17 +514,23 @@ * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse + * @param {object} port * @returns {boolean} */ - function handleRecordGrantGroup(request, sender, sendResponse) { + function handleRecordGrantGroup(request, sender, sendResponse, port) { ;(async () => { try { - const origin = persistenceOriginForRequest(request) - if (!origin || !Array.isArray(request.deviceIds)) { + const authority = scopeAuthorityForRequest(request, sender, port) + const origin = authority?.persistentOrigin + if (!authority || !origin || !Array.isArray(request.deviceIds)) { sendResponse({ success: false }) return } await recordGrantGroup(origin, request.deviceIds) + if (!scopeAuthorityIsCurrent(authority)) { + sendResponse({ success: false, error: 'stale frame authority' }) + return + } sendResponse({ success: true }) } catch (e) { sendResponse({ success: false, error: e.message }) @@ -427,13 +543,23 @@ * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse + * @param {object} port * @returns {boolean} */ - function handleGetGrantGroups(request, sender, sendResponse) { + function handleGetGrantGroups(request, sender, sendResponse, port) { ;(async () => { try { - const groups = await getGrantGroupsForOrigin(persistenceOriginForRequest(request)) - sendResponse({ success: true, groups }) + const authority = scopeAuthorityForRequest(request, sender, port) + if (!authority) { + sendResponse({ success: false, groups: [] }) + return + } + const groups = await getGrantGroupsForOrigin(authority.persistentOrigin) + sendResponse( + scopeAuthorityIsCurrent(authority) + ? { success: true, groups } + : { success: false, groups: [] } + ) } catch { sendResponse({ success: false, groups: [] }) } @@ -483,20 +609,21 @@ * @returns {boolean} */ function handleOpen(request, sender, sendResponse, port) { - const endpoint = endpointForRequest(sender, port) - if (!endpoint) { + const authority = scopeAuthorityForRequest(request, sender, port) + const endpoint = authority?.endpoint + const persistentOrigin = authority?.persistentOrigin + if (!authority || !endpoint || !persistentOrigin) { sendResponse({ s: 403 }) return true } const { tabId, frameKey } = endpoint const authorityOrigin = endpoint.origin - const persistentOrigin = endpoint.persistentOrigin - if (!persistentOrigin || !isFrameLifetimeActive(tabId, frameKey)) { - sendResponse({ s: 403 }) - return true - } getAllowedDevices(persistentOrigin) .then((deviceIds) => { + if (!scopeAuthorityIsCurrent(authority)) { + sendResponse({ s: 503 }) + return + } if (!deviceIds.includes(request.deviceId)) { sendResponse({ s: 403 }) return @@ -508,13 +635,13 @@ const stillAllowed = (await getAllowedDevices(persistentOrigin)).includes( request.deviceId ) - const ownerStillAlive = isFrameLifetimeActive(tabId, frameKey) - if (!stillAllowed || !ownerStillAlive) { + const ownerStillCurrent = scopeAuthorityIsCurrent(authority) + if (!stillAllowed || !ownerStillCurrent) { if (response.t) await closeForCleanup(response.i, response.t, (id, token) => NativeMessaging.closeDevice(id, token) ) - sendResponse({ s: ownerStillAlive ? 403 : 503 }) + sendResponse({ s: ownerStillCurrent ? 403 : 503 }) return } let sessionRegistered = true @@ -610,12 +737,15 @@ async function handleFrameDestroyed(request, sender, sendResponse, port) { const endpoint = endpointForRequest(sender, port) if (endpoint) { - await purgeFrame(endpoint.tabId, endpoint.frameKey, (deviceId, token) => - NativeMessaging.closeDevice(deviceId, token) - ) + frameEndpoints.delete(port) + cancelEndpointDelegations(endpoint) const exactKey = documentFrameKey(endpoint.tabId, endpoint.frameId, endpoint.documentId) frameDelegations.delete(exactKey) permissionsPolicy.delete(exactKey) + await purgeFrame(endpoint.tabId, endpoint.frameKey, (deviceId, token) => + NativeMessaging.closeDevice(deviceId, token) + ) + refreshEndpointPersistence(endpoint.tabId) } sendResponse({ s: 204 }) return true @@ -639,14 +769,16 @@ * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse + * @param {object} port * @returns {boolean} */ - function handleRevokeDevice(request, sender, sendResponse) { + function handleRevokeDevice(request, sender, sendResponse, port) { ;(async () => { try { - const persistentOrigin = persistenceOriginForRequest(request) - const authorityOrigin = request.origin || '' - if (!persistentOrigin || !authorityOrigin) { + const authority = scopeAuthorityForRequest(request, sender, port) + const persistentOrigin = authority?.persistentOrigin + const authorityOrigin = authority?.endpoint?.origin || request.origin || '' + if (!authority || !persistentOrigin || !authorityOrigin) { sendResponse({ success: false, error: 'no origin' }) return } @@ -655,14 +787,28 @@ ? request.deviceIds.map((id) => Number(id)) : [Number(request.deviceId)] const groups = await getGrantGroupsForOrigin(persistentOrigin) + if (!scopeAuthorityIsCurrent(authority)) { + sendResponse({ success: false, error: 'stale frame authority' }) + return + } const memberGroups = groups.filter((g) => g.deviceIds.some((id) => targetIds.includes(id))) /** @type {Set} */ const toRevoke = new Set(targetIds) for (const g of memberGroups) { for (const id of g.deviceIds) toRevoke.add(Number(id)) } - await revokeDevices(persistentOrigin, authorityOrigin, toRevoke, memberGroups) - sendResponse({ success: true }) + const completed = await revokeDevices( + persistentOrigin, + authorityOrigin, + toRevoke, + memberGroups, + () => scopeAuthorityIsCurrent(authority) + ) + sendResponse( + completed && scopeAuthorityIsCurrent(authority) + ? { success: true } + : { success: false, error: 'stale frame authority' } + ) } catch (e) { sendResponse({ success: false, error: e.message }) } @@ -762,13 +908,23 @@ * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse + * @param {object} port * @returns {boolean} */ - function handleGetPairedDevices(request, sender, sendResponse) { + function handleGetPairedDevices(request, sender, sendResponse, port) { ;(async () => { try { - const deviceIds = await getAllowedDevices(persistenceOriginForRequest(request)) - sendResponse({ success: true, hashes: deviceIds }) + const authority = scopeAuthorityForRequest(request, sender, port) + if (!authority) { + sendResponse({ success: false, hashes: [] }) + return + } + const deviceIds = await getAllowedDevices(authority.persistentOrigin) + sendResponse( + scopeAuthorityIsCurrent(authority) + ? { success: true, hashes: deviceIds } + : { success: false, hashes: [] } + ) } catch (e) { sendResponse({ success: false, error: e.message, hashes: [] }) } @@ -780,20 +936,34 @@ * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse + * @param {object} port * @returns {boolean} */ - function handlePairDevice(request, sender, sendResponse) { + function handlePairDevice(request, sender, sendResponse, port) { ;(async () => { try { - const origin = persistenceOriginForRequest(request) - if (!origin || !request.device) { + const authority = scopeAuthorityForRequest(request, sender, port) + const origin = authority?.persistentOrigin + if (!authority || !origin || !request.device) { sendResponse({ success: false, hashes: [] }) return } await addAllowedDevice(origin, request.device.deviceId) + if (!scopeAuthorityIsCurrent(authority)) { + sendResponse({ success: false, hashes: [] }) + return + } const deviceIds = await getAllowedDevices(origin) + if (!scopeAuthorityIsCurrent(authority)) { + sendResponse({ success: false, hashes: [] }) + return + } await notifyAllowedDevicesChanged(request.origin, origin, deviceIds) - sendResponse({ success: true, hashes: deviceIds }) + sendResponse( + scopeAuthorityIsCurrent(authority) + ? { success: true, hashes: deviceIds } + : { success: false, hashes: [] } + ) } catch (e) { sendResponse({ success: false, error: e.message, hashes: [] }) } @@ -805,23 +975,37 @@ * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse + * @param {object} port * @returns {boolean} */ - function handleUnpairDevice(request, sender, sendResponse) { + function handleUnpairDevice(request, sender, sendResponse, port) { ;(async () => { try { - const origin = persistenceOriginForRequest(request) - if (!origin) { + const authority = scopeAuthorityForRequest(request, sender, port) + const origin = authority?.persistentOrigin + if (!authority || !origin) { sendResponse({ success: false, hashes: [] }) return } if (request.deviceId) { await removeAllowedDevice(origin, request.deviceId) + if (!scopeAuthorityIsCurrent(authority)) { + sendResponse({ success: false, hashes: [] }) + return + } removeDeviceInfo(request.deviceId) } const deviceIds = await getAllowedDevices(origin) + if (!scopeAuthorityIsCurrent(authority)) { + sendResponse({ success: false, hashes: [] }) + return + } if (request.deviceId) await notifyAllowedDevicesChanged(request.origin, origin, deviceIds) - sendResponse({ success: true, hashes: deviceIds }) + sendResponse( + scopeAuthorityIsCurrent(authority) + ? { success: true, hashes: deviceIds } + : { success: false, hashes: [] } + ) } catch (e) { sendResponse({ success: false, error: e.message }) } @@ -833,13 +1017,19 @@ * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse + * @param {object} port * @returns {boolean} */ - function handleGetAllowedDevices(request, sender, sendResponse) { + function handleGetAllowedDevices(request, sender, sendResponse, port) { ;(async () => { try { - const deviceIds = await getAllowedDevices(persistenceOriginForRequest(request)) - sendResponse({ deviceIds }) + const authority = scopeAuthorityForRequest(request, sender, port) + if (!authority) { + sendResponse({ deviceIds: [] }) + return + } + const deviceIds = await getAllowedDevices(authority.persistentOrigin) + sendResponse(scopeAuthorityIsCurrent(authority) ? { deviceIds } : { deviceIds: [] }) } catch { sendResponse({ deviceIds: [] }) } @@ -1318,8 +1508,56 @@ return entry && entry.origin === origin ? entry : null } /** - * Computes the effective `hid` policy for one browser-authenticated frame - * document. + * Ensures every cross-origin container edge in the exact ancestry has a + * browser-authenticated delegation result. + * @param {object} endpoint + * @returns {Promise} + */ + async function ensureFrameDelegations(endpoint) { + let child = endpoint + const visited = new Set() + while (child && child.frameId !== 0) { + const key = documentFrameKey(child.tabId, child.frameId, child.documentId) + if (visited.has(key)) return false + visited.add(key) + const entry = policyEntryForDocument( + child.tabId, + child.frameId, + child.documentId, + child.origin + ) + if (!entry || !entry.parentKey) return false + const parent = parentEndpointFor(child) + const parentEntry = permissionsPolicy.get(entry.parentKey) + if (!parent || !parentEntry || !parentEntry.origin) return false + const delegated = await queryFrameDelegation(child) + if (!endpointDocumentIsLive(child)) return false + frameDelegations.set(key, delegated) + child = parent + } + return !!child + } + /** + * @param {object} entry + * @param {Set} visited + * @returns {boolean} + */ + function effectivePolicyAllowsEntry(entry, visited = new Set()) { + if (!entry || entry.effective.kind === 'none') return false + const key = documentFrameKey(entry.tabId, entry.frameId, entry.documentId) + if (visited.has(key)) return false + visited.add(key) + if (entry.parentKey) { + const parent = permissionsPolicy.get(entry.parentKey) + if (!parent || !effectivePolicyAllowsEntry(parent, visited)) return false + if (frameDelegations.get(key) !== true) return false + } + return ( + entry.effective.kind === 'all' || + (entry.effective.kind === 'list' && entry.effective.origins.includes(entry.origin)) + ) + } + /** * @param {object} request * @param {object} sender * @returns {{policy: {hid: string}}} @@ -1332,24 +1570,10 @@ if (tabId == null || frameId == null || !documentId || !requestedOrigin) { return { policy: { hid: 'none' } } } - const exactKey = documentFrameKey(tabId, frameId, documentId) const entry = policyEntryForDocument(tabId, frameId, documentId, requestedOrigin) - if (!entry || entry.effective.kind === 'none') { - return { policy: { hid: 'none' } } - } - if (entry.parentFrameId >= 0) { - if (!entry.parentKey) return { policy: { hid: 'none' } } - const parent = permissionsPolicy.get(entry.parentKey) - if (!parent || !parent.origin) return { policy: { hid: 'none' } } - if (parent.origin !== entry.origin && frameDelegations.get(exactKey) !== true) { - return { policy: { hid: 'none' } } - } - } - const eff = entry.effective - if (eff.kind === 'all' || (eff.kind === 'list' && eff.origins.includes(entry.origin))) { - return { policy: { hid: 'allowed' } } - } - return { policy: { hid: 'none' } } + return effectivePolicyAllowsEntry(entry) + ? { policy: { hid: 'allowed' } } + : { policy: { hid: 'none' } } } /** * @param {object} request @@ -1360,30 +1584,18 @@ */ async function handleGetPolicy(request, sender, sendResponse, port) { const endpoint = endpointForRequest(sender, port) - if (endpoint) { - const key = documentFrameKey(endpoint.tabId, endpoint.frameId, endpoint.documentId) - const entry = policyEntryForDocument( - endpoint.tabId, - endpoint.frameId, - endpoint.documentId, - endpoint.origin - ) - if ( - entry && - endpoint.frameId !== 0 && - entry.parentFrameId >= 0 && - entry.parentKey && - permissionsPolicy.get(entry.parentKey)?.origin !== entry.origin - ) { - const delegated = await queryFrameDelegation(endpoint) - frameDelegations.set(key, delegated) - } + if ( + !endpoint || + !(await ensureFrameDelegations(endpoint)) || + !endpointDocumentIsLive(endpoint) + ) { + sendResponse({ policy: { hid: 'none' } }) + return false } sendResponse(policyForRequest(request, sender)) return false } /** - * Records delegation for this browser-authenticated frame document. * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse diff --git a/addon/js/background/state_ops.js b/addon/js/background/state_ops.js index 81584d2..6b60124 100644 --- a/addon/js/background/state_ops.js +++ b/addon/js/background/state_ops.js @@ -467,6 +467,28 @@ } await Promise.all(pending) } + /** + * Closes sessions owned by one live frame when its persistence scope changes. + * @param {number} tabId + * @param {string} frameKey + * @param {Function} closeDeviceFn + * @returns {Promise} + */ + async function closeFrameSessions(tabId, frameKey, closeDeviceFn) { + if (tabId == null || !frameKey) return + const deviceIds = new Set([...deviceSessions.keys(), ...deviceTabMap.keys()]) + const pending = [] + for (const deviceId of deviceIds) { + const tokens = collectDeviceSessionsForFrame(deviceId, tabId, frameKey) + for (const token of tokens) { + unregisterDeviceTab(deviceId, tabId) + pending.push(closeForCleanup(deviceId, token, closeDeviceFn)) + } + const tabs = deviceTabMap.get(deviceId) + if (tabs && tabs.size === 0) deviceTabMap.delete(deviceId) + } + await Promise.all(pending) + } /** * Moves a session whose daemon close failed into the orphan retry queue. @@ -562,7 +584,8 @@ } /** - * Clears all browser ownership derived from one dead NM authority lifetime. + * Clears browser ownership derived from one dead NM authority lifetime. + * Document lifetimes remain tied to their browser-authenticated endpoints. * @returns {void} */ function clearAuthorityOwnership() { @@ -574,7 +597,6 @@ } deviceTabMap.clear() deviceSessions.clear() - frameLifetimes.clear() orphanCleanup.clear() for (const tabId of tabs) refreshBadge(tabId) } @@ -625,6 +647,7 @@ retireFrameLifetime, purgeFrame, purgeTab, + closeFrameSessions, broadcastGlobalReset, clearAuthorityOwnership, clearDeviceOwnership, diff --git a/addon/js/content/isolated/bridge.js b/addon/js/content/isolated/bridge.js index 8770251..a3534b6 100644 --- a/addon/js/content/isolated/bridge.js +++ b/addon/js/content/isolated/bridge.js @@ -1713,15 +1713,6 @@ return frameContextForPort(port)?.persistentOrigin || persistentOrigin || '' } - /** - * Returns this exact document's origin for local settings and UI requests. - * @returns {string[]} - */ - function collectFrameOrigins() { - const origin = frameContext.origin - return origin && (origin.startsWith('http:') || origin.startsWith('https:')) ? [origin] : [] - } - /** * Dispatches one message arriving on a request port: maps its request id to * the port and routes it to the request handler. @@ -1900,19 +1891,93 @@ } } /** - * @param {{childFrameId: number, childDocumentId: string}} query + * @param {string} token + * @returns {string|null} + */ + function delegationToken(token) { + if (!token) return null + const first = token[0] + const last = token[token.length - 1] + if (first === "'" || first === '"') { + if (last !== first || token.length < 2) return null + return token.slice(1, -1) + } + if (last === "'" || last === '"') return null + return token + } + /** + * @param {string} value + * @param {string} [base] + * @returns {string|null} + */ + function originFromDelegationUrl(value, base) { + try { + const urlType = pristine.types.URL + const url = urlType.construct(base ? [value, base] : [value]) + const origin = urlType.proto.getters.origin(url) + return typeof origin === 'string' && origin !== 'null' ? origin : null + } catch { + return null + } + } + /** + * @param {Element} frame + * @param {{childOrigin: string, parentOrigin: string}} query + * @param {string[]} tokens + * @returns {boolean} + */ + function allowHidDirective(frame, query, tokens) { + if (tokens.length === 0) { + const src = frame.getAttribute('src') || '' + const sourceOrigin = src ? originFromDelegationUrl(src, document.baseURI) : query.parentOrigin + return sourceOrigin === query.childOrigin + } + for (const rawToken of tokens) { + const token = delegationToken(rawToken) + if (token === null) return false + if (token === 'none') return false + if (token === '*') return true + if (token === 'self' && query.childOrigin === query.parentOrigin) return true + if (token === 'src') { + const src = frame.getAttribute('src') || '' + const sourceOrigin = src + ? originFromDelegationUrl(src, document.baseURI) + : query.parentOrigin + if (sourceOrigin === query.childOrigin) return true + continue + } + if (originFromDelegationUrl(token) === query.childOrigin) return true + } + return false + } + /** + * @param {{childFrameId: number, childDocumentId: string, childOrigin: string, parentOrigin: string}} query * @returns {boolean} */ function frameDelegationForChild(query) { try { const getFrameId = browser.runtime.getFrameId const getDocumentId = browser.runtime.getDocumentId - if (typeof getFrameId !== 'function' || typeof getDocumentId !== 'function') return false + if ( + typeof getFrameId !== 'function' || + typeof getDocumentId !== 'function' || + typeof query.childOrigin !== 'string' || + typeof query.parentOrigin !== 'string' + ) + return false for (const frame of document.querySelectorAll('iframe,frame')) { if (getFrameId(frame) !== query.childFrameId) continue if (getDocumentId(frame) !== query.childDocumentId) continue - const allow = frame.getAttribute('allow') || '' - return allow.split(';').some((directive) => /^\s*hid(?:\s|$)/i.test(directive)) + const directives = (frame.getAttribute('allow') || '') + .split(';') + .filter((directive) => directive.trim().toLowerCase().startsWith('hid')) + if (directives.length === 0) return query.childOrigin === query.parentOrigin + for (const directive of directives) { + const tokens = directive.trim().split(/\s+/) + if (tokens.shift()?.toLowerCase() !== 'hid') return false + if (!allowHidDirective(frame, query, tokens)) return false + } + return true } } catch { void 0 diff --git a/tests/browser/permissions-policy.spec.ts b/tests/browser/permissions-policy.spec.ts index 01da8c5..9388d04 100644 --- a/tests/browser/permissions-policy.spec.ts +++ b/tests/browser/permissions-policy.spec.ts @@ -196,6 +196,54 @@ test.describe('Cross-origin iframe', () => { expect(raw!.hidUndefined).toBe(false) }) + test('iframe hid allowlists are origin and document exact', async ({ + page, + pageUrl, + crossUrl + }) => { + await page.goto(pageUrl('/iframe-parent'), { + waitUntil: 'domcontentloaded', + timeout: 15000 + }) + await page.evaluate( + ({ main, cross, pageUrlForTest }) => { + const add = (id: string, src: string, allow: string) => { + const frame = document.createElement('iframe') + frame.id = id + frame.src = src + frame.allow = allow + document.body.appendChild(frame) + } + add('allow-none', cross + '/iframe-child-no-allow', "hid 'none'") + add('allow-other', cross + '/iframe-child-no-allow', `hid ${main}`) + add('allow-self', pageUrlForTest, "hid 'self'") + add('allow-bare', cross + '/iframe-child-no-allow', 'hid') + }, + { main: pageUrl(''), cross: crossUrl(''), pageUrlForTest: pageUrl('/iframe-child-no-allow') } + ) + await expect + .poll( + () => page.frames().filter((frame) => frame.url().includes('/iframe-child-no-allow')).length + ) + .toBe(4) + expect( + (await readFrameResult(await frameWithId(page, 'allow-none', 'iframe-child')))?.queryHid + ).toBe('denied') + expect( + (await readFrameResult(await frameWithId(page, 'allow-other', 'iframe-child')))?.queryHid + ).toBe('denied') + expect( + (await readFrameResult(await frameWithId(page, 'allow-self', 'iframe-child')))?.queryHid + ).toBe('granted') + const bare = await frameWithId(page, 'allow-bare', 'iframe-child') + expect((await readFrameResult(bare))?.queryHid).toBe('granted') + await bare.evaluate((url) => { + window.location.href = url + }, pageUrl('/iframe-child-no-allow')) + const navigated = await frameWithId(page, 'allow-bare', 'iframe-child') + expect((await readFrameResult(navigated))?.queryHid).toBe('denied') + }) + test('cross-origin iframe cannot forge a sibling allow="hid" src', async ({ sharedPage, crossUrl @@ -307,6 +355,53 @@ test.describe('Cross-origin iframe', () => { ) expect(delivered).toEqual({ scopeA: 2, scopeB: 1 }) }) + + test('top navigation retires old opaque persistence authorities', async ({ + page, + pageUrl, + crossUrl, + backgroundPage + }) => { + await page.goto(pageUrl('/iframe-parent'), { + waitUntil: 'domcontentloaded', + timeout: 15000 + }) + await page.evaluate((src) => { + const frame = document.createElement('iframe') + frame.id = 'old-opaque' + frame.setAttribute('sandbox', 'allow-scripts') + frame.src = src + document.body.appendChild(frame) + }, pageUrl('/iframe-child-no-allow')) + await frameWithId(page, 'old-opaque', '/iframe-child-no-allow') + await page.goto(crossUrl('/iframe-parent'), { + waitUntil: 'domcontentloaded', + timeout: 15000 + }) + await page.evaluate((src) => { + const frame = document.createElement('iframe') + frame.id = 'new-opaque' + frame.setAttribute('sandbox', 'allow-scripts') + frame.src = src + document.body.appendChild(frame) + }, pageUrl('/iframe-child-no-allow')) + await frameWithId(page, 'new-opaque', '/iframe-child-no-allow') + const targets = (await backgroundPage.evaluate(async () => { + const tabs = await browser.tabs.query({ active: true, currentWindow: true }) + const tab = tabs[0] + if (!tab || tab.id == null) return [] + const raw: unknown = await browser.tabs.sendMessage(tab.id, { action: 'getFrameOrigins' }) + return ( + (raw as { targets?: Array<{ kind: string; persistentOrigin: string | null }> }).targets || + [] + ) + })) as Array<{ kind: string; persistentOrigin: string | null }> + const opaque = targets.filter((target) => target.kind === 'opaque') + expect(opaque).toHaveLength(1) + expect(opaque[0].persistentOrigin).toBe( + `opaque|${new URL(crossUrl('')).origin}|${new URL(pageUrl('')).origin}` + ) + }) test('B2: top-level hid=() denies a delegated cross-origin child', async ({ page, pageUrl, @@ -332,6 +427,79 @@ test.describe('Cross-origin iframe', () => { expect(raw!.hidUndefined).toBe(false) }) + test('ancestor container denial cannot be re-enabled by descendants', async ({ + page, + pageUrl, + crossUrl + }) => { + await page.goto(pageUrl('/iframe-parent'), { + waitUntil: 'domcontentloaded', + timeout: 15000 + }) + await page.evaluate((src) => { + for (const id of ['nested-denied-same', 'nested-denied-cross']) { + const frame = document.createElement('iframe') + frame.id = id + frame.src = src + document.body.appendChild(frame) + } + }, crossUrl('/iframe-child-no-allow')) + const deniedSameParent = await frameWithId(page, 'nested-denied-same', 'iframe-child') + const deniedCrossParent = await frameWithId(page, 'nested-denied-cross', 'iframe-child') + await deniedSameParent.evaluate((src) => { + const child = document.createElement('iframe') + child.id = 'nested-denied-same-child' + child.src = src + child.allow = 'hid' + document.body.appendChild(child) + }, crossUrl('/iframe-child-no-allow')) + await deniedCrossParent.evaluate((src) => { + const child = document.createElement('iframe') + child.id = 'nested-denied-cross-child' + child.src = src + child.allow = 'hid' + document.body.appendChild(child) + }, pageUrl('/iframe-child-no-allow')) + expect( + (await readFrameResult(await frameWithId(page, 'nested-denied-same-child', 'iframe-child'))) + ?.queryHid + ).toBe('denied') + expect( + (await readFrameResult(await frameWithId(page, 'nested-denied-cross-child', 'iframe-child'))) + ?.queryHid + ).toBe('denied') + }) + + test('delegation remains available through an allowed nested topology', async ({ + page, + pageUrl, + crossUrl + }) => { + await page.goto(pageUrl('/iframe-parent'), { + waitUntil: 'domcontentloaded', + timeout: 15000 + }) + await page.evaluate((src) => { + const parent = document.createElement('iframe') + parent.id = 'nested-allowed-parent' + parent.src = src + parent.allow = 'hid' + document.body.appendChild(parent) + }, crossUrl('/iframe-child-no-allow')) + const parent = await frameWithId(page, 'nested-allowed-parent', 'iframe-child') + await parent.evaluate((src) => { + const child = document.createElement('iframe') + child.id = 'nested-allowed-child' + child.src = src + child.allow = 'hid' + document.body.appendChild(child) + }, crossUrl('/iframe-child-no-allow')) + expect( + (await readFrameResult(await frameWithId(page, 'nested-allowed-child', 'iframe-child'))) + ?.queryHid + ).toBe('granted') + }) + test('cross-origin iframe worker cannot bypass policy without delegation', async ({ page, pageUrl, diff --git a/tests/e2e/nm-runtime-port.spec.ts b/tests/e2e/nm-runtime-port.spec.ts index 6da9e86..cd825d0 100644 --- a/tests/e2e/nm-runtime-port.spec.ts +++ b/tests/e2e/nm-runtime-port.spec.ts @@ -110,4 +110,119 @@ test.describe.serial('Exact frame endpoint fanout', () => { await sharedPage.goto(`${origin}/tests/test-page.html`, { waitUntil: 'domcontentloaded' }) } }) + + test('pending open cannot publish after top document replacement', async ({ + sharedPage, + backgroundPage, + vendorDevice + }) => { + const origin = new URL(sharedPage.url()).origin + const settingKey = `settings :: ${origin} :: dataPlane` + await vendorDevice.ready + const previous = await backgroundPage.evaluate( + (key: string) => browser.storage.local.get(key), + settingKey + ) + await backgroundPage.evaluate( + (key: string) => browser.storage.local.set({ [key]: 'nm' }), + settingKey + ) + try { + await sharedPage.goto(`${origin}/tests/test-page.html`, { waitUntil: 'domcontentloaded' }) + await sharedPage.waitForFunction(() => typeof navigator.hid !== 'undefined', { + timeout: 15000 + }) + await grantDevicePermission(sharedPage, [VENDOR]) + await backgroundPage.evaluate(() => { + const state = globalThis as unknown as { + webhid: { + import(name: string): { + openDevice: (deviceId: number) => Promise + closeDevice: (deviceId: number, token: string) => Promise + } + } + __originalOpenDevice?: (deviceId: number) => Promise + __originalCloseDevice?: (deviceId: number, token: string) => Promise + __openEntered?: boolean + __releaseOpen?: () => void + } + const nm = state.webhid.import('NativeMessaging') + state.__originalOpenDevice = nm.openDevice.bind(nm) + state.__originalCloseDevice = nm.closeDevice.bind(nm) + state.__openEntered = false + nm.openDevice = async (deviceId: number) => { + state.__openEntered = true + await new Promise((resolve) => { + state.__releaseOpen = resolve + }) + return { s: 200, i: deviceId, t: 'stale-open' } + } + nm.closeDevice = () => Promise.resolve({ s: 204 }) + }) + await sharedPage.evaluate(() => { + const state = window as unknown as { pendingOpen?: Promise } + state.pendingOpen = (async () => { + const devices = await navigator.hid.getDevices() + if (!devices[0]) throw new Error('paired device missing') + try { + await devices[0].open() + } catch { + return + } + })() + }) + await expect + .poll(() => + backgroundPage.evaluate( + () => (globalThis as unknown as { __openEntered?: boolean }).__openEntered === true + ) + ) + .toBe(true) + await sharedPage.goto(`${origin}/tests/test-page.html`, { waitUntil: 'domcontentloaded' }) + await sharedPage.waitForFunction(() => typeof navigator.hid !== 'undefined', { + timeout: 15000 + }) + await backgroundPage.evaluate(() => { + ;(globalThis as unknown as { __releaseOpen?: () => void }).__releaseOpen?.() + }) + await expect + .poll( + () => + backgroundPage.evaluate(async () => { + const tabs = await browser.tabs.query({ active: true, currentWindow: true }) + const tab = tabs[0] + if (!tab || tab.id == null) return [] + const raw = (await browser.tabs.sendMessage(tab.id, { + action: 'getOpenDeviceIds' + })) as { ids?: string[] } | null + return raw?.ids || [] + }), + { timeout: 15000 } + ) + .toEqual([]) + } finally { + await backgroundPage.evaluate(() => { + const state = globalThis as unknown as { + webhid: { + import(name: string): { + openDevice: (deviceId: number) => Promise + closeDevice: (deviceId: number, token: string) => Promise + } + } + __originalOpenDevice?: (deviceId: number) => Promise + __originalCloseDevice?: (deviceId: number, token: string) => Promise + } + const nm = state.webhid.import('NativeMessaging') + if (state.__originalOpenDevice) nm.openDevice = state.__originalOpenDevice + if (state.__originalCloseDevice) nm.closeDevice = state.__originalCloseDevice + }) + await backgroundPage.evaluate( + ({ key, values }) => + browser.storage.local + .remove(!(key in values) ? [key] : []) + .then(() => (key in values ? browser.storage.local.set(values) : undefined)), + { key: settingKey, values: previous } + ) + } + }) }) diff --git a/tests/unit/frame-endpoint-topology.test.js b/tests/unit/frame-endpoint-topology.test.js index 08c0d90..aeacb2e 100644 --- a/tests/unit/frame-endpoint-topology.test.js +++ b/tests/unit/frame-endpoint-topology.test.js @@ -86,3 +86,23 @@ test('MAIN does not bootstrap through a top WindowProxy', () => { assert.doesNotMatch(main, /windowObject\.top/) assert.match(main, /reflect\.deleteProperty\(globalThis, 'webhid'\)/) }) + +test('endpoint replacement retires prior document authorities', () => { + assert.match(messages, /frameId === 0 \|\| candidate\.frameId === frameId/) + assert.match(messages, /frameEndpoints\.delete\(port\)/) + assert.match(messages, /endpointAuthorityIsCurrent/) + assert.match(messages, /closeFrameSessions/) +}) + +test('missing top endpoint fails child persistence closed', () => { + assert.match(messages, /const persistentOrigin = top[\s\S]*: null/) + assert.doesNotMatch(messages, /const top = topEndpointForTab\(tabId\)\s+if \(!top\) return/) +}) + +test('iframe delegation is not a presence-only grant', () => { + assert.match(bridge, /function delegationToken/) + assert.match(bridge, /token === 'none'/) + assert.match(bridge, /token === 'self'/) + assert.match(bridge, /token === 'src'/) + assert.doesNotMatch(bridge, /some\(\(directive\) => \^\\\\s\*hid/) +}) diff --git a/tests/unit/state-ops.test.js b/tests/unit/state-ops.test.js index 6908a01..d20d44e 100644 --- a/tests/unit/state-ops.test.js +++ b/tests/unit/state-ops.test.js @@ -154,6 +154,37 @@ test('frame cleanup retains failed authority without affecting siblings', async assert.equal(ops.isFrameLifetimeActive(11, 'frame-b'), true) }) +test('scope transition closes old frame sessions without retiring the frame', async () => { + const { ops, deviceSessions, orphanCleanup } = loadStateOps() + ops.registerFrameLifetime(11, 'frame-a') + ops.registerFrameLifetime(11, 'frame-b') + ops.registerDeviceTab(7, 11) + ops.registerDeviceTab(7, 11) + ops.registerDeviceSession(7, 'session-a', { + tabId: 11, + origin: 'null', + persistentOrigin: 'opaque|host-a|widget', + frameKey: 'frame-a' + }) + ops.registerDeviceSession(7, 'session-b', { + tabId: 11, + origin: 'https://b.test', + frameKey: 'frame-b' + }) + const { promise: close, resolve: finishClose } = Promise.withResolvers() + const cleanup = ops.closeFrameSessions(11, 'frame-a', async () => { + await close + return { s: 204 } + }) + assert.equal(ops.isFrameLifetimeActive(11, 'frame-a'), true) + assert.deepEqual([...deviceSessions.get(7).keys()], ['session-a', 'session-b']) + finishClose() + await cleanup + assert.equal(ops.isFrameLifetimeActive(11, 'frame-a'), true) + assert.deepEqual([...deviceSessions.get(7).keys()], ['session-b']) + assert.equal(orphanCleanup.has('session-a'), false) +}) + test('authority and physical resets clear derived ownership', () => { const { ops, deviceTabMap, deviceSessions, orphanCleanup } = loadStateOps() ops.registerFrameLifetime(11, 'frame-a') @@ -175,7 +206,7 @@ test('authority and physical resets clear derived ownership', () => { assert.equal(deviceTabMap.size, 0) assert.equal(deviceSessions.size, 0) assert.equal(orphanCleanup.size, 0) - assert.equal(ops.isFrameLifetimeActive(11, 'frame-a'), false) + assert.equal(ops.isFrameLifetimeActive(11, 'frame-a'), true) }) test('retired frame generations cannot publish late sessions', async () => { From fb650e8618a3ee7eb7331155a1c20d1be0bc4325 Mon Sep 17 00:00:00 2001 From: Kazoku Date: Mon, 14 Sep 2026 23:52:41 +0700 Subject: [PATCH 19/26] fix(addon): clean picker state on endpoint retirement --- addon/js/background/messages.js | 46 ++-- .../unit/messages-endpoint-lifecycle.test.js | 242 ++++++++++++++++++ 2 files changed, 263 insertions(+), 25 deletions(-) create mode 100644 tests/unit/messages-endpoint-lifecycle.test.js diff --git a/addon/js/background/messages.js b/addon/js/background/messages.js index 9f278ea..9f569e1 100644 --- a/addon/js/background/messages.js +++ b/addon/js/background/messages.js @@ -124,17 +124,31 @@ } } /** + * Removes picker requests owned by an endpoint. * @param {object} endpoint * @returns {void} */ + function clearPendingPickerForEndpoint(endpoint) { + for (const [tabId, request] of pendingPicker) { + if (request.port !== endpoint.port && request.uiPort !== endpoint.port) continue + pendingPicker.delete(tabId) + } + } + /** + * Retires one endpoint and all state owned by its document lifetime. + * @param {object} endpoint + * @returns {Promise|null} + */ function retireEndpoint(endpoint) { - if (frameEndpoints.get(endpoint.port) !== endpoint) return - frameEndpoints.delete(endpoint.port) + clearPendingPickerForEndpoint(endpoint) + if (endpoint.retired) return null + endpoint.retired = true + if (frameEndpoints.get(endpoint.port) === endpoint) frameEndpoints.delete(endpoint.port) cancelEndpointDelegations(endpoint) const exactKey = documentFrameKey(endpoint.tabId, endpoint.frameId, endpoint.documentId) frameDelegations.delete(exactKey) permissionsPolicy.delete(exactKey) - void purgeFrame(endpoint.tabId, endpoint.frameKey, (deviceId, token) => + return purgeFrame(endpoint.tabId, endpoint.frameKey, (deviceId, token) => NativeMessaging.closeDevice(deviceId, token) ).catch((e) => logger.debug('frame endpoint cleanup failed', e)) } @@ -737,15 +751,9 @@ async function handleFrameDestroyed(request, sender, sendResponse, port) { const endpoint = endpointForRequest(sender, port) if (endpoint) { - frameEndpoints.delete(port) - cancelEndpointDelegations(endpoint) - const exactKey = documentFrameKey(endpoint.tabId, endpoint.frameId, endpoint.documentId) - frameDelegations.delete(exactKey) - permissionsPolicy.delete(exactKey) - await purgeFrame(endpoint.tabId, endpoint.frameKey, (deviceId, token) => - NativeMessaging.closeDevice(deviceId, token) - ) + const cleanup = retireEndpoint(endpoint) refreshEndpointPersistence(endpoint.tabId) + if (cleanup) await cleanup } sendResponse({ s: 204 }) return true @@ -1788,21 +1796,9 @@ }) if (endpoint) { port.onDisconnect.addListener(() => { - if (frameEndpoints.get(port) !== endpoint) return - frameEndpoints.delete(port) + const cleanup = retireEndpoint(endpoint) refreshEndpointPersistence(endpoint.tabId) - for (const [tabId, request] of pendingPicker) { - if (request.port !== port && request.uiPort !== port) continue - pendingPicker.delete(tabId) - } - for (const [requestId, pending] of delegationPending) { - if (pending.endpoint !== endpoint && pending.parent !== endpoint) continue - delegationPending.delete(requestId) - pending.resolve(false) - } - purgeFrame(endpoint.tabId, endpoint.frameKey, (deviceId, token) => - NativeMessaging.closeDevice(deviceId, token) - ).catch((e) => logger.debug('frame endpoint cleanup failed', e)) + if (cleanup) void cleanup }) } }) diff --git a/tests/unit/messages-endpoint-lifecycle.test.js b/tests/unit/messages-endpoint-lifecycle.test.js new file mode 100644 index 0000000..9a2f3ee --- /dev/null +++ b/tests/unit/messages-endpoint-lifecycle.test.js @@ -0,0 +1,242 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { runInNewContext } from 'node:vm' +import test from 'node:test' + +const source = readFileSync( + new URL('../../addon/js/background/messages.js', import.meta.url), + 'utf8' +) + +function loadMessages() { + let registerMessageHandlers + const frameEndpoints = new Map() + const pendingPicker = new Map() + const permissionsPolicy = new Map() + const frameDelegations = new Map() + const frameLifetimes = new Map() + const ports = [] + let purgeCalls = 0 + const onConnect = [] + const onMessage = [] + const persistentSiteScope = (origin) => origin + const documentFrameKey = (tabId, frameId, documentId) => `${tabId}:${frameId}:${documentId || ''}` + const stateOps = { + registerFrameLifetime(tabId, frameKey) { + let frames = frameLifetimes.get(tabId) + if (!frames) { + frames = new Map() + frameLifetimes.set(tabId, frames) + } + if (frames.get(frameKey) === 0) return false + frames.set(frameKey, (frames.get(frameKey) || 0) + 1) + return true + }, + isFrameLifetimeActive(tabId, frameKey) { + return frameLifetimes.get(tabId)?.get(frameKey) > 0 + }, + purgeFrame() { + purgeCalls++ + return Promise.resolve() + }, + closeForCleanup: () => Promise.resolve(true), + setBadgeRefresh() {}, + registerDeviceTab() {}, + registerDeviceSession() { + return true + }, + unregisterDeviceSession() {}, + unregisterDeviceTab() {}, + isTabAuthorizedForDevice() { + return false + }, + isSessionOwnedBy() { + return false + }, + getDeviceSessionOwner() { + return null + }, + setDeviceSessionPlane() { + return false + }, + collectDevicePlaneStatuses() { + return [] + }, + collectOpenDeviceIdsForTab() { + return [] + }, + collectDeviceSessionsForOrigin() { + return [] + }, + clearDeviceSessionsForOrigin() {}, + purgeTab() {} + } + const browser = { + runtime: { + onConnect: { + addListener(listener) { + onConnect.push(listener) + } + }, + onMessage: { + addListener(listener) { + onMessage.push(listener) + } + }, + getURL(path) { + return 'moz-extension://test/' + path + } + }, + tabs: { + query: async () => [], + sendMessage: async () => ({}) + }, + windows: { remove: async () => {} }, + notifications: { clear: async () => {} }, + storage: { session: { get: async () => ({}) } } + } + const nativeMessaging = { + port: {}, + enumerateDevices: async () => ({ s: 200, D: [] }), + handshake: async () => ({ s: 200 }), + closeDevice: async () => ({ s: 204 }), + openDevice: async () => ({ s: 403 }) + } + const imports = { + 'content-ports': { + registerContentPort() {}, + postToContentPort() {} + }, + http: { isOk: (status) => status >= 200 && status < 300 }, + logger: { debug() {}, warn() {}, error() {} }, + isChromium: false, + decodeDeviceCollections() {}, + persistentSiteScope, + bgState: { + deviceCache: [], + pendingPicker, + permissionsPolicy, + frameDelegations, + frameEndpoints, + pageActionVisibility: {} + }, + bgStorage: { + saveDeviceInfoBatch() {}, + getDeviceInfo: async () => null, + getAllowedDevices: async () => [], + addAllowedDevice: async () => {}, + removeAllowedDevice: async () => {}, + removeDeviceInfo() {}, + recordGrantGroup: async () => {}, + getGrantGroupsForOrigin: async () => [], + deleteGrantGroups: async () => {}, + getAllAllowedByOrigin: async () => new Map() + }, + bgStateOps: stateOps, + bgCsp: { + urlOrigin: (url) => new URL(url).origin, + frameKey: (tabId, frameId, origin) => `${tabId}:${frameId}:${origin}`, + documentFrameKey + }, + NativeMessaging: nativeMessaging, + bgPacked: { ACT: {} }, + bgBundle: { ensureWorkerBundle: async () => null }, + GLOBAL_DEFAULTS: { dataPlane: 'nm' }, + armShadowSpawn() {}, + unarmShadowSpawn() {} + } + const context = { + globalThis: null, + browser, + webhid: { + import(name) { + if (!(name in imports)) throw new Error('unexpected import: ' + name) + return imports[name] + }, + export(name, value) { + if (name === 'registerMessageHandlers') registerMessageHandlers = value + } + } + } + context.globalThis = context + runInNewContext(source, context) + registerMessageHandlers({ actionApi: null }) + + function connect(sender) { + const messageListeners = [] + const disconnectListeners = [] + const port = { + name: 'webhid-control', + sender, + onMessage: { + addListener(listener) { + messageListeners.push(listener) + } + }, + onDisconnect: { + addListener(listener) { + disconnectListeners.push(listener) + } + }, + postMessage() {}, + disconnect() { + for (const listener of disconnectListeners) listener() + } + } + ports.push(port) + for (const listener of onConnect) listener(port) + return port + } + + return { connect, pendingPicker, frameEndpoints, ports, getPurgeCalls: () => purgeCalls } +} + +const sender = (frameId, documentId) => ({ + tab: { id: 1 }, + frameId, + documentId, + origin: 'https://frame-' + frameId + '.test', + url: 'https://frame-' + frameId + '.test/' +}) + +test('proactive retirement clears picker requests owned by request port', () => { + const state = loadMessages() + const oldPort = state.connect(sender(0, 'old')) + state.pendingPicker.set(1, { port: oldPort, uiPort: null }) + state.connect(sender(0, 'new')) + assert.equal(state.pendingPicker.size, 0) + assert.equal(state.getPurgeCalls(), 1) +}) + +test('proactive retirement clears modal pickers owned by UI port', () => { + const state = loadMessages() + const oldUiPort = state.connect(sender(0, 'old')) + const requestPort = state.connect(sender(1, 'request')) + state.pendingPicker.set(1, { port: requestPort, uiPort: oldUiPort }) + state.connect(sender(0, 'new')) + assert.equal(state.pendingPicker.size, 0) +}) + +test('retiring an unrelated sibling leaves the picker intact', () => { + const state = loadMessages() + const requestPort = state.connect(sender(1, 'request')) + const uiPort = state.connect(sender(0, 'ui')) + state.pendingPicker.set(1, { port: requestPort, uiPort }) + const sibling = state.connect(sender(2, 'sibling')) + state.connect(sender(2, 'replacement')) + assert.equal(state.pendingPicker.size, 1) + assert.equal(state.pendingPicker.get(1).port, requestPort) + assert.equal(sibling.name, 'webhid-control') +}) + +test('disconnect after proactive retirement is idempotent', () => { + const state = loadMessages() + const oldPort = state.connect(sender(0, 'old')) + const sibling = state.connect(sender(1, 'sibling')) + state.pendingPicker.set(1, { port: sibling, uiPort: oldPort }) + state.connect(sender(0, 'new')) + assert.equal(state.pendingPicker.size, 0) + const purgeCalls = state.getPurgeCalls() + assert.doesNotThrow(() => oldPort.disconnect()) + assert.equal(state.getPurgeCalls(), purgeCalls) +}) From 4ef434183453f6ab5975cf7b8c11ace26aa55d1d Mon Sep 17 00:00:00 2001 From: Kazoku Date: Tue, 15 Sep 2026 00:53:13 +0700 Subject: [PATCH 20/26] fix(addon): restore per-origin data-plane status --- addon/js/background/messages.js | 39 +++++++++++++++++++++++++---- addon/js/content/isolated/bridge.js | 33 +++++++++++++++++++----- tests/browser/worker-spawn.spec.ts | 10 +++++--- 3 files changed, 68 insertions(+), 14 deletions(-) diff --git a/addon/js/background/messages.js b/addon/js/background/messages.js index 9f569e1..276acb7 100644 --- a/addon/js/background/messages.js +++ b/addon/js/background/messages.js @@ -5,6 +5,7 @@ const logger = webhid.import('logger') const isChromium = webhid.import('isChromium') const decodeDeviceCollections = webhid.import('decodeDeviceCollections') + const loadEffectiveSettings = webhid.import('loadEffectiveSettings') const persistentSiteScope = webhid.import('persistentSiteScope') const { deviceCache, @@ -1065,12 +1066,28 @@ * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse + * @param {object} [port] * @returns {boolean} */ - function handleGetDataPlaneStatus(request, sender, sendResponse) { + function handleGetDataPlaneStatus(request, sender, sendResponse, port) { const tabId = Number.isInteger(request.tabId) ? request.tabId : sender.tab?.id - const statuses = tabId == null ? [] : collectDevicePlaneStatuses(tabId, request.origin) - sendResponse({ + const endpoint = endpointForRequest(sender, port) + const requestedOrigin = + typeof request.statusOrigin === 'string' ? request.statusOrigin : null + const endpointOrigin = endpoint ? endpoint.persistentOrigin || endpoint.origin : '' + const origin = + endpoint && requestedOrigin + ? [...frameEndpoints.values()].some( + (candidate) => + candidate.tabId === endpoint.tabId && + (candidate.persistentOrigin || candidate.origin) === requestedOrigin && + endpointDocumentIsLive(candidate) + ) + ? requestedOrigin + : endpointOrigin + : endpointOrigin || request.origin + const statuses = tabId == null ? [] : collectDevicePlaneStatuses(tabId, origin) + const response = () => ({ planes: statuses.map(({ deviceId, plane, mode, generation, ready }) => ({ deviceId, plane, @@ -1080,7 +1097,10 @@ })), defaultPlane: webhid.import('GLOBAL_DEFAULTS').dataPlane }) - return false + loadEffectiveSettings(origin || '') + .then((settings) => sendResponse({ ...response(), defaultPlane: settings.dataPlane })) + .catch(() => sendResponse(response())) + return true } /** @@ -1722,6 +1742,7 @@ getAllowedDevices: handleGetAllowedDevices, getOpenDeviceIds: handleGetOpenDeviceIds, getDataPlaneStatus: handleGetDataPlaneStatus, + getDataPlaneStatusForOrigin: handleGetDataPlaneStatus, setDataPlaneStatus: handleSetDataPlaneStatus, deviceCountChanged: handleDeviceCountChanged, showPageAction: handleShowPageAction, @@ -1767,7 +1788,15 @@ return } const effectiveRequest = endpoint - ? { ...request, origin: endpoint.origin, persistentOrigin: endpoint.persistentOrigin } + ? { + ...request, + origin: endpoint.origin, + persistentOrigin: endpoint.persistentOrigin, + ...(request.action === 'getDataPlaneStatusForOrigin' && + typeof request.statusOrigin === 'string' + ? { statusOrigin: request.statusOrigin } + : {}) + } : request const handler = HANDLERS[effectiveRequest.action] if (!handler) return diff --git a/addon/js/content/isolated/bridge.js b/addon/js/content/isolated/bridge.js index a3534b6..071191b 100644 --- a/addon/js/content/isolated/bridge.js +++ b/addon/js/content/isolated/bridge.js @@ -432,17 +432,38 @@ } browser.runtime.onMessage.addListener((request, sender, sendResponse) => { + const isStatusRequest = + request.action === 'getDataPlaneStatus' || request.action === 'getDataPlaneStatusForOrigin' if ( request.action !== 'getOpenDeviceIds' && - request.action !== 'getDataPlaneStatus' && + !isStatusRequest && request.action !== 'getFrameOrigins' ) return false - sendBackgroundRequest({ - action: request.action, - origin: typeof request.origin === 'string' ? request.origin : undefined - }) - .then(sendResponse) + const trustedOriginRequest = + request.action === 'getDataPlaneStatusForOrigin' && + sender?.id === browser.runtime.id && + typeof request.origin === 'string' + const origin = trustedOriginRequest + ? request.origin + : frameContext?.persistentOrigin || frameContext?.origin || window.location.origin + const backgroundRequest = { + action: trustedOriginRequest ? 'getDataPlaneStatusForOrigin' : request.action, + ...(request.action === 'getDataPlaneStatus' + ? {} + : trustedOriginRequest + ? { statusOrigin: origin } + : { origin }) + } + sendBackgroundRequest(backgroundRequest) + .then(async (response) => { + if (!isStatusRequest) { + sendResponse(response) + return + } + const settings = await loadSettingsForOrigin(origin) + sendResponse({ ...response, defaultPlane: settings.dataPlane }) + }) .catch(() => sendResponse({ ids: [], planes: [], origins: [] })) return true }) diff --git a/tests/browser/worker-spawn.spec.ts b/tests/browser/worker-spawn.spec.ts index d41e0ec..7624995 100644 --- a/tests/browser/worker-spawn.spec.ts +++ b/tests/browser/worker-spawn.spec.ts @@ -708,21 +708,25 @@ test('site settings stay isolated across frame origins', async ({ const tab = tabs.find((entry) => entry.url?.startsWith(topUrl)) if (!tab?.id) return null return { + current: await browser.tabs.sendMessage(tab.id, { + action: 'getDataPlaneStatus' + }), top: await browser.tabs.sendMessage(tab.id, { - action: 'getDataPlaneStatus', + action: 'getDataPlaneStatusForOrigin', origin: topOrigin }), child: await browser.tabs.sendMessage(tab.id, { - action: 'getDataPlaneStatus', + action: 'getDataPlaneStatusForOrigin', origin: childOrigin }), unknown: await browser.tabs.sendMessage(tab.id, { - action: 'getDataPlaneStatus', + action: 'getDataPlaneStatusForOrigin', origin: 'http://unknown.invalid' }) } }, { topUrl, topOrigin, childOrigin }) expect(statuses).toEqual({ + current: expect.objectContaining({ defaultPlane: 'nm' }), top: expect.objectContaining({ defaultPlane: 'nm' }), child: expect.objectContaining({ defaultPlane: 'ws' }), unknown: expect.objectContaining({ planes: [], defaultPlane: expect.any(String) }) From 069462f249d1bdeace20d85da86c37a8ae7c009d Mon Sep 17 00:00:00 2001 From: Kazoku Date: Tue, 15 Sep 2026 00:57:02 +0700 Subject: [PATCH 21/26] test(e2e): isolate sequential consent scenarios --- tests/e2e/e2e.spec.ts | 6 +++--- tests/e2e/picker-bypass.spec.ts | 9 +++++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/tests/e2e/e2e.spec.ts b/tests/e2e/e2e.spec.ts index 39d97b8..bd63c28 100644 --- a/tests/e2e/e2e.spec.ts +++ b/tests/e2e/e2e.spec.ts @@ -99,11 +99,11 @@ test.describe.serial('WebHID E2E', () => { sharedPage, vendorDevice }) => { - await grantDevicePermission(sharedPage, [VENDOR]) await sharedPage.evaluate(async (ctx: VendorCtx) => { const ds = await navigator.hid.getDevices() - const d = ds.find((x) => x.vendorId === ctx.f.vendorId && x.productId === ctx.f.productId)! - await d.open() + const d = ds.find((x) => x.vendorId === ctx.f.vendorId && x.productId === ctx.f.productId) + if (!d) throw new Error('vendor device missing after initial grant') + if (!d.opened) await d.open() }, VENDOR_CTX) const outputPromise = waitForOutputReport(vendorDevice) const opened = await sharedPage.evaluate(async (ctx: VendorCtx) => { diff --git a/tests/e2e/picker-bypass.spec.ts b/tests/e2e/picker-bypass.spec.ts index 37a28dd..914a8fa 100644 --- a/tests/e2e/picker-bypass.spec.ts +++ b/tests/e2e/picker-bypass.spec.ts @@ -7,6 +7,15 @@ const VENDOR = mockIdFor('vendor') const VENDOR_INPUT_SIZE = 64 test.describe.serial('picker consent bypass', () => { + test.beforeAll(async ({ sharedPage }) => { + await sharedPage.evaluate(async () => { + for (const device of await navigator.hid.getDevices()) { + if (device.vendorId !== 0x16c0 || device.productId !== 0x0001) continue + if (device.opened) await device.close() + await device.forget() + } + }) + }) test('baseline: vendor device is not granted before the bypass', async ({ sharedPage }) => { const vendorCount = await sharedPage.evaluate(async () => { const ds = await navigator.hid.getDevices() From 3353c2e60b67b46eede945e1bb208cf45df10bd8 Mon Sep 17 00:00:00 2001 From: Kazoku Date: Tue, 15 Sep 2026 04:00:21 +0700 Subject: [PATCH 22/26] fix(addon): receive ack response --- addon/js/content/isolated/bridge.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/addon/js/content/isolated/bridge.js b/addon/js/content/isolated/bridge.js index 071191b..492da97 100644 --- a/addon/js/content/isolated/bridge.js +++ b/addon/js/content/isolated/bridge.js @@ -100,7 +100,7 @@ devicePicker .show(message.filters || [], message.exclusionFilters || []) .then((result) => - controlPort.postMessage({ + sendBackgroundRequest({ action: 'inlinePickerResult', requestId: message.requestId, selected: !!(result.devices && result.devices.length), From a89a5b9f6feb2020183033129883dc5b6edb5ba0 Mon Sep 17 00:00:00 2001 From: Kazoku Date: Wed, 16 Sep 2026 02:16:56 +0700 Subject: [PATCH 23/26] refactor(mock): expose uhid backend as library --- crates/webhid-mock/src/lib.rs | 104 +++++++++++++++++++++++++++++++++ crates/webhid-mock/src/main.rs | 102 +------------------------------- 2 files changed, 107 insertions(+), 99 deletions(-) create mode 100644 crates/webhid-mock/src/lib.rs diff --git a/crates/webhid-mock/src/lib.rs b/crates/webhid-mock/src/lib.rs new file mode 100644 index 0000000..f18cdcc --- /dev/null +++ b/crates/webhid-mock/src/lib.rs @@ -0,0 +1,104 @@ +//! Library surface of `webhid-mock`, shared between the CLI binary and +//! cross-crate tests (the daemon's uhid identity regression tests create +//! virtual devices directly through the platform backends). + +#[cfg(target_os = "linux")] +pub mod linux; +#[cfg(target_os = "macos")] +pub mod macos; + +#[cfg(not(target_os = "windows"))] +use anyhow::Context as _; + +/// Options for spawning one virtual HID device. +#[cfg(not(target_os = "windows"))] +pub struct SpawnOpts { + pub vid: u16, + pub pid: u16, + pub name: String, + pub descriptor_path: String, + pub usage_page: Option, + pub usage: Option, + pub bus: u16, + pub version: u16, + pub country: u8, +} + +/// A spawned virtual HID device. Platform backends implement this in +/// `linux.rs` / `macos.rs`; the JSON command handler only needs input +/// injection, everything else (event echoing) is backend-specific. +#[cfg(not(target_os = "windows"))] +pub trait MockDevice { + /// Inject an input report into the host. `payload` must already include + /// the report ID as its first byte for numbered-report devices. + fn send_input(&self, payload: &[u8]) -> anyhow::Result<()>; +} + +#[cfg(not(target_os = "windows"))] +#[derive(PartialEq)] +pub enum LoopAction { + Continue, + Exit, +} + +/// Handle one JSON command line. Shared by all platform event loops. +#[cfg(not(target_os = "windows"))] +pub fn handle_command(dev: &dyn MockDevice, line: &str) -> anyhow::Result { + #[derive(serde::Deserialize)] + #[serde(tag = "cmd")] + enum Cmd { + #[serde(rename = "input")] + Input { + #[serde(rename = "reportId")] + report_id: Option, + data: Option>, + }, + #[serde(rename = "destroy")] + Destroy, + #[serde(rename = "ping")] + Ping, + } + + let cmd: Cmd = serde_json::from_str(line).context("failed to parse JSON command")?; + match cmd { + Cmd::Input { report_id, data } => { + let payload = match (report_id, data) { + (Some(rid), Some(mut d)) => { + let mut buf = Vec::with_capacity(1 + d.len()); + buf.push(rid); + buf.append(&mut d); + buf + } + (Some(rid), None) => vec![rid], + (None, Some(d)) => d, + (None, None) => Vec::new(), + }; + if payload.is_empty() { + anyhow::bail!("input command requires either reportId or data"); + } + dev.send_input(&payload)?; + emit_stdout(&serde_json::json!({ + "event": "input_sent", + "reportId": report_id.unwrap_or(0), + "size": payload.len(), + })); + } + Cmd::Destroy => { + return Ok(LoopAction::Exit); + } + Cmd::Ping => { + emit_stdout(&serde_json::json!({"event": "pong"})); + } + } + Ok(LoopAction::Continue) +} + +/// Emit one JSON event line on stdout. Safe to call from multiple threads +/// (each call takes the stdout lock for the whole line). +#[cfg(not(target_os = "windows"))] +pub fn emit_stdout(value: &serde_json::Value) { + use std::io::Write as _; + let mut stdout = std::io::stdout().lock(); + let _ = writeln!(stdout, "{}", value); + let _ = stdout.flush(); +} diff --git a/crates/webhid-mock/src/main.rs b/crates/webhid-mock/src/main.rs index f9aa928..44936ea 100644 --- a/crates/webhid-mock/src/main.rs +++ b/crates/webhid-mock/src/main.rs @@ -17,12 +17,7 @@ #![cfg_attr(target_os = "windows", allow(dead_code, unused_imports))] #[cfg(not(target_os = "windows"))] -use std::io::Write; - -#[cfg(target_os = "linux")] -mod linux; -#[cfg(target_os = "macos")] -mod macos; +use webhid_mock::SpawnOpts; #[cfg(not(target_os = "windows"))] use anyhow::Context as _; @@ -60,12 +55,12 @@ fn try_main() -> anyhow::Result<()> { #[cfg(target_os = "linux")] fn run_spawn(opts: SpawnOpts) -> anyhow::Result<()> { - linux::run_spawn(opts) + webhid_mock::linux::run_spawn(opts) } #[cfg(target_os = "macos")] fn run_spawn(opts: SpawnOpts) -> anyhow::Result<()> { - macos::run_spawn(opts) + webhid_mock::macos::run_spawn(opts) } #[cfg(not(target_os = "windows"))] @@ -78,19 +73,6 @@ enum Command { Spawn(SpawnOpts), } -#[cfg(not(target_os = "windows"))] -struct SpawnOpts { - vid: u16, - pid: u16, - name: String, - descriptor_path: String, - usage_page: Option, - usage: Option, - bus: u16, - version: u16, - country: u8, -} - #[cfg(not(target_os = "windows"))] struct ArgState { vid: Option, @@ -248,81 +230,3 @@ fn print_usage() { eprintln!("OS events (output reports, get/set report queries) are echoed to stdout"); eprintln!("as JSON. On stdin EOF, the device is destroyed and the process exits."); } - -/// A spawned virtual HID device. Platform backends implement this in -/// `linux.rs` / `macos.rs`; the JSON command handler only needs input -/// injection, everything else (event echoing) is backend-specific. -#[cfg(not(target_os = "windows"))] -trait MockDevice { - /// Inject an input report into the host. `payload` must already include - /// the report ID as its first byte for numbered-report devices. - fn send_input(&self, payload: &[u8]) -> anyhow::Result<()>; -} - -#[cfg(not(target_os = "windows"))] -#[derive(PartialEq)] -enum LoopAction { - Continue, - Exit, -} - -/// Handle one JSON command line. Shared by all platform event loops. -#[cfg(not(target_os = "windows"))] -fn handle_command(dev: &dyn MockDevice, line: &str) -> anyhow::Result { - #[derive(serde::Deserialize)] - #[serde(tag = "cmd")] - enum Cmd { - #[serde(rename = "input")] - Input { - #[serde(rename = "reportId")] - report_id: Option, - data: Option>, - }, - #[serde(rename = "destroy")] - Destroy, - #[serde(rename = "ping")] - Ping, - } - - let cmd: Cmd = serde_json::from_str(line).context("failed to parse JSON command")?; - match cmd { - Cmd::Input { report_id, data } => { - let payload = match (report_id, data) { - (Some(rid), Some(mut d)) => { - let mut buf = Vec::with_capacity(1 + d.len()); - buf.push(rid); - buf.append(&mut d); - buf - } - (Some(rid), None) => vec![rid], - (None, Some(d)) => d, - (None, None) => Vec::new(), - }; - if payload.is_empty() { - anyhow::bail!("input command requires either reportId or data"); - } - dev.send_input(&payload)?; - emit_stdout(&serde_json::json!({ - "event": "input_sent", - "reportId": report_id.unwrap_or(0), - "size": payload.len(), - })); - } - Cmd::Destroy => { - return Ok(LoopAction::Exit); - } - Cmd::Ping => { - emit_stdout(&serde_json::json!({"event": "pong"})); - } - } - Ok(LoopAction::Continue) -} - -/// Emit one JSON event line on stdout. Safe to call from multiple threads -/// (each call takes the stdout lock for the whole line). -#[cfg(not(target_os = "windows"))] -fn emit_stdout(value: &serde_json::Value) { - let mut stdout = std::io::stdout().lock(); - let _ = writeln!(stdout, "{}", value); - let _ = stdout.flush(); -} From 285182ef973ff92d0df1225d32ef74f9e9322b2d Mon Sep 17 00:00:00 2001 From: Kazoku Date: Wed, 16 Sep 2026 02:17:13 +0700 Subject: [PATCH 24/26] fix(daemon): disambiguate uhid sibling open identities --- AGENTS.md | 4 + crates/Cargo.lock | 1 + crates/webhid-daemon/Cargo.toml | 5 + crates/webhid-daemon/src/dump.rs | 2 +- crates/webhid-daemon/src/hid.rs | 147 ++++++++++++---- crates/webhid-daemon/src/tests/hid.rs | 91 ++++++++++ .../webhid-daemon/src/tests/uhid_siblings.rs | 158 ++++++++++++++++++ 7 files changed, 370 insertions(+), 38 deletions(-) create mode 100644 crates/webhid-daemon/src/tests/uhid_siblings.rs diff --git a/AGENTS.md b/AGENTS.md index a15cd85..deaf243 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -79,6 +79,10 @@ Two layers, always-on like Chromium: 1. Device-level (`hid.rs`): FIDO usage page 0xF1D0 + per-product security-key list (Chromium `kStaticEntries`); hidden from enumeration. 2. Report-level (`blocklist.rs`/`report_blocking.rs`): WICG `blocklist.txt` entry-for-entry (FIDO, GD Mouse/Keyboard/Keypad/SystemControl, Jabra, OnlyKey). Any-match per (report_id, type) over a report→collection map where each report carries every ancestor collection's usage (a Mouse report in a Physical child IS blocked); plus hardcoded always-protected usages (page 0x07; GD Pointer/Mouse/Keyboard/Keypad; GD SystemControl 0x80-0x8f, 0xa0-0xb6); plus an undocumented-report-ID fallback (blocks when the device has an always-protected top-level). Unparseable/empty descriptors fail closed: the device is hidden from enumeration and `open()` refuses it, since there is no collection tree to classify reports against (2026-08-20 audit fix; the `dump` subcommand still lists it with the parse error). Input dropped at the reader; output/feature rejected; sends pre-checked like Chromium's `HidConnection::Write` / `GetFeatureReport` / `SendFeatureReport` gates (a report type the descriptor does not declare, `max_*_report_size() == 0`, is rejected). Blocked reports pruned from page-visible `collections` (`prune_device_info`); all-empty devices hidden. SayoDevice config uses distinct report IDs, so only its keyboard report 1 is blocked. Keep fixtures off Mouse/Keyboard/Keypad usages if they must receive reports. +### Device identity (2026-09-16) + +The daemon's `device_id` (u32 FNV-1a) is the hash of a per-logical-interface identity string. On Linux that string is the canonical sysfs path of the HID interface; since every interface of a real USB or Bluetooth device canonicalizes to its own stable parent (`.../1-7:1.2`), real hardware needs nothing else. UHID is special: all virtual devices share one parent (`/sys/devices/virtual/misc/uhid`) and the hid device directory name is `bus:vid:pid.instance`, where the instance suffix is a kernel-wide counter reassigned at every device creation. Hashing the full path would change the id at every mock reconnect, while stripping the suffix (the previous behavior) collapsed concurrent sibling interfaces that share bus:vid:pid into one ambiguous id, so `open(device_id)` could pick the wrong hidraw node (observed with two sayo-style UHID devices at hidraw7/hidraw8). The uhid identity therefore keeps the stable `bus:vid:pid` base and mixes in the raw report descriptor (`crates/webhid-daemon/src/hid.rs`, `identity_string`): a recreated virtual device keeps its descriptor and its id (hotplug continuity and persisted grants survive), siblings with different descriptors get different ids, and siblings sharing every observable attribute are indistinguishable and merge into one identity (deduped at enumeration). Invariant: every enumerated logical HID interface has a unique device_id, and `open(device_id)` resolves to that exact interface; genuine 32-bit hash collisions still fail closed (hidden at enumeration, refused at open). Compat: persisted device ids for UHID devices from before the fix no longer match; affected origins must re-pair those devices once. Real USB/Bluetooth hardware ids are unchanged. Regression tests: pure identity tests in `crates/webhid-daemon/src/tests/hid.rs` and real-device tests in `crates/webhid-daemon/src/tests/uhid_siblings.rs` (require `/dev/uhid` access; the mock's protocol layer is a lib target since this change). + ### Consent model (2026-08-06) A page cannot grant itself a device or see the full inventory. `pairDevice`/`recordGrantGroup`/`getGrantGroups`/`getAllPairedDevices`/`revokeDevice`/`getDeviceCache`/`getDeviceInfo`/`showPicker`/`pickerResult` are blocked from page ports (`PAGE_BLOCKED_ACTIONS`, 403). Page `enumerate` is rewritten to `enumeratePaired`; the background filters the daemon inventory by the requesting origin's stored grants. Chooser and extension pages call unmodified `enumerate` for chooser data. Pairing runs in the bridge after chooser selection (`grantSelectedDevices`); `pickerResult` is accepted only from the extension picker page. Devices granted together form a grant group (IndexedDB `grantGroups`); revoking any member cascades to the group and closes that origin's daemon sessions. diff --git a/crates/Cargo.lock b/crates/Cargo.lock index 41e7990..699f67e 100644 --- a/crates/Cargo.lock +++ b/crates/Cargo.lock @@ -1644,6 +1644,7 @@ dependencies = [ "tokio-tungstenite", "udev 0.8.0", "webhid", + "webhid-mock", "wtransport", ] diff --git a/crates/webhid-daemon/Cargo.toml b/crates/webhid-daemon/Cargo.toml index 5fdc737..a2b5bf4 100644 --- a/crates/webhid-daemon/Cargo.toml +++ b/crates/webhid-daemon/Cargo.toml @@ -34,6 +34,11 @@ udev = "0.8" libc = "0.2" hidapi = { version = "2.6", default-features = false, features = ["linux-native"] } +[dev-dependencies] +# The uhid identity regression tests create real virtual devices through +# the mock's platform backend instead of shelling out to the CLI. +webhid-mock = { path = "../webhid-mock" } + [target.'cfg(target_os = "macos")'.dependencies] hidapi = { version = "2.6", default-features = false, features = ["macos-shared-device"] } core-foundation-sys = "0.8" diff --git a/crates/webhid-daemon/src/dump.rs b/crates/webhid-daemon/src/dump.rs index 41803bd..0d54754 100644 --- a/crates/webhid-daemon/src/dump.rs +++ b/crates/webhid-daemon/src/dump.rs @@ -173,7 +173,7 @@ fn dump_entry(api: &HidApi, info: &HidDeviceInfo, hex_descriptor: bool) -> DumpE && prune_device_info(device_info).is_some(); DumpEntry { - device_id: hid::make_device_id(info), + device_id: hid::make_device_id(info, &desc), vendor_id: info.vendor_id(), product_id: info.product_id(), product_name: info.product_string().map(String::from).unwrap_or_default(), diff --git a/crates/webhid-daemon/src/hid.rs b/crates/webhid-daemon/src/hid.rs index ead7a53..33f0bc7 100644 --- a/crates/webhid-daemon/src/hid.rs +++ b/crates/webhid-daemon/src/hid.rs @@ -9,29 +9,81 @@ thread_local! { static READ_BUF: RefCell> = RefCell::new(Vec::with_capacity(256)); } -/// Generate a stable `u32` device identifier from the device path. +/// Generate a stable `u32` device identifier for one logical HID interface. /// -/// Uses FNV-1a 32-bit hash of the platform-specific device path -/// (Linux: `/dev/hidraw0` / syspath; Windows: device interface path; -/// macOS: IOService path). Same device in same port → same hash across -/// reboots. Two devices with identical vid/pid/serial but different +/// Uses FNV-1a 32-bit hash of a per-interface identity string (Linux: +/// canonical sysfs path of the HID interface; Windows: device interface +/// path; macOS: IOService path). Same device in same port → same hash +/// across reboots. Two devices with identical vid/pid/serial but different /// physical ports have different paths → different hashes. -pub fn make_device_id(info: &HidDeviceInfo) -> u32 { +/// +/// Linux UHID needs one extra ingredient. Every virtual device lives under +/// `/sys/devices/virtual/misc/uhid/.`, and the +/// instance suffix is a kernel-wide counter reassigned at every device +/// creation. Hashing the full path would change the id at every reconnect, +/// while stripping the suffix collapses concurrent sibling interfaces that +/// share bus:vid:pid into one ambiguous id (open() could pick the wrong +/// sibling). The uhid identity therefore keeps the stable +/// `` base and mixes in the report descriptor: a recreated +/// virtual device keeps its descriptor and its id, siblings with different +/// descriptors get different ids, and siblings sharing every attribute are +/// indistinguishable and merge as one identity. +/// +/// `descriptor` is the raw report descriptor of the interface; it only +/// participates for Linux uhid devices and may be empty when it could not +/// be read (the identity then degrades to the base path). +pub fn make_device_id(info: &HidDeviceInfo, descriptor: &[u8]) -> u32 { let path = info.path().to_string_lossy(); #[cfg(target_os = "linux")] { - if let Some(syspath) = resolve_linux_syspath(&path) { - return webhid::hash_device_id(&syspath); + if let Some(base) = resolve_linux_syspath(&path) { + return webhid::hash_device_id(&identity_string(&base, descriptor)); } } + let _ = descriptor; webhid::hash_device_id(&path) } +/// The per-interface identity string whose FNV-1a hash is the device id. +/// Also used as the physical-device bucket key (`physical_identity`), so +/// uhid siblings with different report descriptors count as distinct +/// physical devices for collision detection. +#[cfg(target_os = "linux")] +fn identity_string(base: &str, descriptor: &[u8]) -> String { + if base.contains("/misc/uhid/") && !descriptor.is_empty() { + format!("{base}+{}", hex::encode(descriptor)) + } else { + base.to_owned() + } +} + +/// Whether the interface's identity needs its report descriptor (Linux +/// uhid devices only, see `make_device_id`). +#[cfg(target_os = "linux")] +fn identity_needs_descriptor(info: &HidDeviceInfo) -> bool { + let path = info.path().to_string_lossy(); + resolve_linux_syspath(&path).is_some_and(|base| base.contains("/misc/uhid/")) +} + #[cfg(target_os = "linux")] fn resolve_linux_syspath(devnode: &str) -> Option { let name = std::path::Path::new(devnode).file_name()?.to_str()?; let syslink = format!("/sys/class/hidraw/{name}/device"); let realpath = std::fs::canonicalize(&syslink).ok()?; + sysfs_base_from_realpath(&realpath) +} + +/// Pure core of `resolve_linux_syspath`, testable without sysfs: the +/// stable identity base for a canonicalized HID device sysfs path. +/// Real buses (USB, Bluetooth…) place each interface under its own stable +/// parent (`.../1-7:1.2/0003:046D:C52B.0009`), so the parent of the hid +/// device directory is the interface identity. All uhid devices share one +/// parent (`/sys/devices/virtual/misc/uhid`), so the stable `bus:vid:pid` +/// prefix of the hid device directory name is appended while the kernel +/// instance suffix (`.NNNN`) is dropped; descriptor mixing in +/// `identity_string` keeps sibling uhid interfaces apart. +#[cfg(target_os = "linux")] +fn sysfs_base_from_realpath(realpath: &std::path::Path) -> Option { let parent = realpath.parent()?; let mut base = parent.to_string_lossy().into_owned(); @@ -61,38 +113,43 @@ pub fn enumerate() -> anyhow::Result> { /// Stable physical-device identity used to keep two distinct no-serial /// devices apart while still merging multiple interfaces of one device. /// On Linux the syspath base already identifies the physical device (all -/// of its interfaces canonicalize to the same path); elsewhere the hidapi -/// path is the best available per-interface identity. -fn physical_identity(info: &HidDeviceInfo) -> String { +/// of its interfaces canonicalize to the same path); uhid devices mix in +/// their report descriptor instead, since every uhid device is its own +/// physical device and only the descriptor separates same-vid/pid +/// siblings stably (see `make_device_id`). Elsewhere the hidapi path is +/// the best available per-interface identity. +fn physical_identity(info: &HidDeviceInfo, descriptor: &[u8]) -> String { let path = info.path().to_string_lossy(); #[cfg(target_os = "linux")] { - if let Some(syspath) = resolve_linux_syspath(&path) { - return syspath; + if let Some(base) = resolve_linux_syspath(&path) { + return identity_string(&base, descriptor); } } + let _ = descriptor; path.into_owned() } /// Key that identifies one physical device across hidapi entries: the /// serial number when present, the platform physical identity otherwise. /// Used to detect 32-bit device-id hash collisions. -fn physical_key(info: &HidDeviceInfo) -> String { +fn physical_key(info: &HidDeviceInfo, descriptor: &[u8]) -> String { let serial = info.serial_number().unwrap_or(""); if serial.is_empty() { - physical_identity(info) + physical_identity(info, descriptor) } else { format!("serial:{serial}") } } -/// Number of distinct physical devices among `entries`. More than one means -/// the entries' shared 32-bit device id is ambiguous and must not be used -/// as an authority (opening the id could select the wrong physical device). -fn distinct_physical_count(entries: &[&HidDeviceInfo]) -> usize { +/// Number of distinct physical devices among `(entry, descriptor)` pairs. +/// More than one means the entries' shared 32-bit device id is ambiguous +/// and must not be used as an authority (opening the id could select the +/// wrong physical device). +fn distinct_physical_count(entries: &[(&HidDeviceInfo, Vec)]) -> usize { let mut seen = std::collections::HashSet::new(); - for info in entries { - seen.insert(physical_key(info)); + for (info, desc) in entries { + seen.insert(physical_key(info, desc)); } seen.len() } @@ -104,7 +161,7 @@ pub fn enumerate_with_filter(filter: Option<&EnumerateFilter>) -> anyhow::Result type PhysKey = String; let api = HidApi::new()?; - let mut groups: std::collections::HashMap> = + let mut groups: std::collections::HashMap)>> = std::collections::HashMap::new(); // device_id -> distinct physical devices hashing to it; used to drop // colliding ids from enumeration entirely (fail closed). @@ -123,24 +180,29 @@ pub fn enumerate_with_filter(filter: Option<&EnumerateFilter>) -> anyhow::Result if is_blocked_pub(info) { continue; } + // Read the descriptor before ids and physical keys are computed: + // uhid identities mix the report descriptor in, so every entry + // needs it here. Entries reaching the grouping loop had their + // descriptor read anyway, so this moves the read, not duplicates it. + let desc = read_raw_report_descriptor_with_api(&api, info); let serial = info.serial_number().unwrap_or("").to_string(); // When the device has no serial number, distinct physical devices // with identical vid/pid must not be merged. Bucket by physical // identity instead; with a serial, the serial already separates // devices and every interface of one device shares one bucket. let phys = if serial.is_empty() { - physical_identity(info) + physical_identity(info, &desc) } else { String::new() }; id_physical - .entry(make_device_id(info)) + .entry(make_device_id(info, &desc)) .or_default() - .insert(physical_key(info)); + .insert(physical_key(info, &desc)); groups .entry((info.vendor_id(), info.product_id(), serial)) .or_default() - .push((phys, info)); + .push((phys, info, desc)); } let mut devices = Vec::new(); @@ -149,8 +211,7 @@ pub fn enumerate_with_filter(filter: Option<&EnumerateFilter>) -> anyhow::Result &String, std::collections::HashSet>, > = std::collections::HashMap::new(); - for (phys, info) in ifaces { - let desc = read_raw_report_descriptor_with_api(&api, info); + for (phys, info, desc) in ifaces { if !seen_descriptors .entry(phys) .or_default() @@ -158,7 +219,7 @@ pub fn enumerate_with_filter(filter: Option<&EnumerateFilter>) -> anyhow::Result { continue; } - if let Some(d) = info_from_hidapi_pub_with_desc(info, desc) { + if let Some(d) = info_from_hidapi_pub_with_desc(info, desc.clone()) { if is_blocked_by_vendor_product(&d) { continue; } @@ -225,7 +286,7 @@ pub(crate) fn build_device_info( serial_number: info.serial_number().map(String::from), usage_page: Some(info.usage_page()), usage: Some(info.usage()), - device_id: make_device_id(info), + device_id: make_device_id(info, &raw_descriptor), descriptor_parse_failed: collections.is_empty(), collections, max_input_report_size, @@ -344,25 +405,37 @@ pub fn is_blocked_by_vendor_product(info: &webhid::DeviceInfo) -> bool { crate::blocklist::device_is_blocked(rules, info.vendor_id, info.product_id) } -/// Open a device by its stable `device_id` (u32 FNV-1a hash of path). +/// Open a device by its stable `device_id` (u32 FNV-1a hash of the +/// interface identity, see `make_device_id`). /// Returns (DeviceInfo, uses_numbered_reports, HidDevice) for I/O. /// When the 32-bit id is shared by more than one distinct physical device, /// the id is ambiguous and opening it is refused: the permission could /// otherwise resolve to the wrong physical device. pub fn open_by_device_id(device_id: u32) -> anyhow::Result<(DeviceInfo, bool, HidDevice)> { let api = HidApi::new()?; - let matches: Vec<&HidDeviceInfo> = api - .device_list() - .filter(|info| !is_blocked_pub(info) && make_device_id(info) == device_id) - .collect(); + // Descriptors are read for every candidate whose identity can depend + // on them (Linux uhid devices mix the descriptor into the id); all + // other entries are matched by the cheap path-only id first. + let mut matches: Vec<(&HidDeviceInfo, Vec)> = Vec::new(); + for info in api.device_list() { + if is_blocked_pub(info) { + continue; + } + if !identity_needs_descriptor(info) && make_device_id(info, &[]) != device_id { + continue; + } + let desc = read_raw_report_descriptor_with_api(&api, info); + if make_device_id(info, &desc) == device_id { + matches.push((info, desc)); + } + } if distinct_physical_count(&matches) > 1 { return Err(anyhow::anyhow!( "device_id '{device_id:#x}' is ambiguous ({} distinct physical devices hash to it); refusing to open", distinct_physical_count(&matches) )); } - for info in matches { - let desc = read_raw_report_descriptor_with_api(&api, info); + for (info, desc) in matches { let device_info = info_from_hidapi_pub_with_desc(info, desc.clone()) .ok_or_else(|| anyhow::anyhow!("failed to build DeviceInfo"))?; if is_blocked_by_vendor_product(&device_info) { diff --git a/crates/webhid-daemon/src/tests/hid.rs b/crates/webhid-daemon/src/tests/hid.rs index fd28191..7e046fc 100644 --- a/crates/webhid-daemon/src/tests/hid.rs +++ b/crates/webhid-daemon/src/tests/hid.rs @@ -1,5 +1,96 @@ use super::uses_numbered_reports; +#[cfg(target_os = "linux")] +mod identity { + + use super::super::{identity_string, sysfs_base_from_realpath}; + use webhid::hash_device_id; + + /// Regression: two UHID interfaces sharing one normalized base path + /// (`/sys/devices/virtual/misc/uhid/0005:1D50:615E`) with different + /// kernel instance suffixes and different report descriptors must get + /// distinct device ids, and each id must be stable across repeated + /// computation (re-enumeration, hot-plug, open). + #[test] + fn uhid_siblings_same_base_different_descriptors_get_distinct_ids() { + let node_a = std::path::Path::new("/sys/devices/virtual/misc/uhid/0005:1D50:615E.004B"); + let node_b = std::path::Path::new("/sys/devices/virtual/misc/uhid/0005:1D50:615E.004C"); + + let base_a = sysfs_base_from_realpath(node_a).expect("uhid base resolves"); + let base_b = sysfs_base_from_realpath(node_b).expect("uhid base resolves"); + // Both interfaces normalize to the same base: the descriptor must + // be what separates their identities. + assert_eq!(base_a, base_b); + assert_eq!(base_a, "/sys/devices/virtual/misc/uhid/0005:1D50:615E"); + + let desc_a = [0x05, 0x01, 0x09, 0x04, 0xA1, 0x01, 0xC0]; + let desc_b = [0x05, 0x01, 0x09, 0x02, 0xA1, 0x01, 0x85, 0x01, 0xC0]; + + let id_a = hash_device_id(&identity_string(&base_a, &desc_a)); + let id_b = hash_device_id(&identity_string(&base_b, &desc_b)); + assert_ne!(id_a, id_b, "distinct descriptors must not share an id"); + + // Stability: recomputing the id of the same interface yields the + // same value (persistence and open lookups rely on this). + assert_eq!(id_a, hash_device_id(&identity_string(&base_a, &desc_a))); + assert_eq!(id_b, hash_device_id(&identity_string(&base_b, &desc_b))); + } + + /// A recreated UHID device keeps its report descriptor, so it keeps + /// its identity even though the kernel assigns a fresh instance + /// suffix. + #[test] + fn uhid_recreation_keeps_identity() { + let before = std::path::Path::new("/sys/devices/virtual/misc/uhid/0003:16C0:0001.004B"); + let after = std::path::Path::new("/sys/devices/virtual/misc/uhid/0003:16C0:0001.0100"); + let desc = [0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0xC0]; + + let base_before = sysfs_base_from_realpath(before).unwrap(); + let base_after = sysfs_base_from_realpath(after).unwrap(); + assert_eq!( + hash_device_id(&identity_string(&base_before, &desc)), + hash_device_id(&identity_string(&base_after, &desc)), + "instance suffix must not leak into the identity" + ); + } + + /// Non-uhid sysfs paths keep their interface-specific base untouched + /// and ignore the descriptor. + #[test] + fn non_uhid_base_ignores_descriptor() { + let node = std::path::Path::new( + "/sys/devices/pci0000:00/0000:00:14.0/usb1/1-7/1-7:1.2/0003:046D:C52B.0009", + ); + let base = sysfs_base_from_realpath(node).expect("usb base resolves"); + assert_eq!( + base, "/sys/devices/pci0000:00/0000:00:14.0/usb1/1-7/1-7:1.2", + "usb interface path is used as-is" + ); + assert_eq!( + identity_string(&base, &[1, 2, 3]), + base, + "descriptor must not participate for non-uhid paths" + ); + } + + /// An unreadable descriptor degrades the uhid identity to the base + /// path instead of failing. + #[test] + fn uhid_empty_descriptor_falls_back_to_base() { + let base = "/sys/devices/virtual/misc/uhid/0005:1D50:615E"; + assert_eq!(identity_string(base, &[]), base); + assert_ne!( + identity_string(base, &[0]), + base, + "a known descriptor must be mixed in" + ); + } +} + +#[cfg(target_os = "linux")] +#[path = "uhid_siblings.rs"] +mod uhid_siblings; + #[test] fn test_uses_numbered_reports_empty() { assert!(!uses_numbered_reports(&[])); diff --git a/crates/webhid-daemon/src/tests/uhid_siblings.rs b/crates/webhid-daemon/src/tests/uhid_siblings.rs new file mode 100644 index 0000000..720e967 --- /dev/null +++ b/crates/webhid-daemon/src/tests/uhid_siblings.rs @@ -0,0 +1,158 @@ +//! Real-device regression tests for the UHID identity model. +//! +//! Each test creates actual virtual HID devices through `/dev/uhid` (via +//! the `webhid-mock` platform backend) so the full identity pipeline runs: +//! sysfs canonicalization, base normalization, descriptor mixing, +//! enumeration dedup, and `open_by_device_id` path resolution. +//! +//! The tests are serialized with a process-wide lock because they all +//! spawn devices with the same test VID/PID and `enumerate()` sees every +//! device in the process. Requires `/dev/uhid` write access (root or a +//! udev rule). + +use std::os::unix::io::RawFd; +use std::sync::{LazyLock, Mutex, MutexGuard}; +use std::time::{Duration, Instant}; + +use webhid_mock::linux::{build_create_event, build_destroy_event, open_uhid, write_event}; + +/// Obscure test-only identity: two sibling virtual devices that share one +/// normalized sysfs base (`/sys/devices/virtual/misc/uhid/0003:F00D:BA5E`) +/// exactly like the reported hidraw7/hidraw8 collision. +const VID: u16 = 0xF00D; +const PID: u16 = 0xBA5E; + +static UHID_TEST_LOCK: LazyLock> = LazyLock::new(|| Mutex::new(())); + +fn uhid_lock() -> MutexGuard<'static, ()> { + UHID_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// `/dev/uhid` allows one virtual device per open fd, so each test device +/// is its own fd; dropping it destroys the device. +struct UhidDevice(RawFd); + +impl Drop for UhidDevice { + fn drop(&mut self) { + let _ = write_event(self.0, &build_destroy_event()); + unsafe { + libc::close(self.0); + } + } +} + +fn create_uhid_device(name: &str, descriptor: &[u8]) -> UhidDevice { + let fd = match open_uhid() { + Ok(fd) => fd, + Err(e) => { + panic!("cannot open /dev/uhid (needs root or the 'webhid' udev group): {e}"); + } + }; + // bus 0x03 = USB, matching the default of the webhid-mock CLI. + let event = build_create_event(name, descriptor, VID, PID, 0, 0, 0x03) + .expect("build UHID_CREATE2 event"); + write_event(fd, &event).expect("write UHID_CREATE2 event"); + UhidDevice(fd) +} + +fn fixture(name: &str) -> Vec { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../tests/fixtures/descriptors") + .join(name); + std::fs::read(&path).unwrap_or_else(|e| panic!("read fixture {}: {e}", path.display())) +} + +/// Poll `enumerate()` until `expected` test-vid/pid devices are visible. +fn wait_for_enumeration(expected: usize) -> Vec { + let start = Instant::now(); + loop { + if let Ok(devs) = crate::hid::enumerate() { + let mine: Vec = devs + .into_iter() + .filter(|d| d.vendor_id == VID && d.product_id == PID) + .collect(); + if mine.len() >= expected { + return mine; + } + } + if start.elapsed() > Duration::from_secs(10) { + panic!("uhid test devices did not enumerate within 10s (expected {expected})"); + } + std::thread::sleep(Duration::from_millis(50)); + } +} + +/// Regression: two UHID interfaces sharing one normalized base path but +/// with different instance suffixes and different report descriptors must +/// enumerate as distinct WebHID devices, and open(device_id) must resolve +/// each id to its own underlying hidapi interface, never to an arbitrary +/// sibling. +#[test] +fn uhid_sibling_interfaces_get_distinct_ids_and_open_their_own_interface() { + let _guard = uhid_lock(); + let desc_a = fixture("vendor.bin"); + let desc_b = fixture("gamepad.bin"); + assert_ne!(desc_a, desc_b, "fixtures must differ for this test"); + + let _dev_a = create_uhid_device("webhid-uhid-test A", &desc_a); + let _dev_b = create_uhid_device("webhid-uhid-test B", &desc_b); + + let mine = wait_for_enumeration(2); + assert_eq!(mine.len(), 2, "both sibling interfaces must enumerate"); + + let id_a = mine + .iter() + .find(|d| d.raw_descriptor == desc_a) + .expect("interface A enumerated") + .device_id; + let id_b = mine + .iter() + .find(|d| d.raw_descriptor == desc_b) + .expect("interface B enumerated") + .device_id; + assert_ne!(id_a, id_b, "siblings must not share an open identity"); + + // Opening each enumerated device must select that exact interface. The + // raw descriptor is the strongest identity proof: the bug opened the + // first hidapi sibling, which would surface interface A's descriptor + // for an open of interface B. + let (info_a, _, _dev_a_open) = + crate::hid::open_by_device_id(id_a).expect("open interface A by device_id"); + assert_eq!( + info_a.raw_descriptor, desc_a, + "open(interface A id) must select interface A" + ); + let (info_b, _, _dev_b_open) = + crate::hid::open_by_device_id(id_b).expect("open interface B by device_id"); + assert_eq!( + info_b.raw_descriptor, desc_b, + "open(interface B id) must select interface B" + ); +} + +/// Genuine duplicates: two hidapi entries that share the normalized base +/// path, the descriptor, and every other observable attribute (the same +/// logical interface) still merge into one enumerated device identity, and +/// that identity opens successfully. +#[test] +fn uhid_genuine_duplicates_merge_into_one_identity() { + let _guard = uhid_lock(); + let desc = fixture("vendor.bin"); + + let _dev_1 = create_uhid_device("webhid-uhid-test twin", &desc); + let _dev_2 = create_uhid_device("webhid-uhid-test twin", &desc); + + let mine = wait_for_enumeration(1); + assert_eq!( + mine.len(), + 1, + "indistinguishable duplicate entries must merge into one identity" + ); + let id = mine[0].device_id; + let (info, _, _opened) = + crate::hid::open_by_device_id(id).expect("open merged identity by device_id"); + assert_eq!( + info.raw_descriptor, desc, + "open(merged id) must select one of the identical interfaces" + ); +} From f26cb567250e7d931f444bcefd5671c5d8982338 Mon Sep 17 00:00:00 2001 From: Kazoku Date: Wed, 16 Sep 2026 02:17:36 +0700 Subject: [PATCH 25/26] test(e2e): match paired vendor by vid/pid not list position --- tests/e2e/e2e.spec.ts | 10 +++++++--- tests/pages/input-report-fanout-frame.html | 9 ++++++++- tests/pages/input-report-fanout-worker.js | 7 ++++++- tests/pages/input-report-fanout.html | 8 +++++++- 4 files changed, 28 insertions(+), 6 deletions(-) diff --git a/tests/e2e/e2e.spec.ts b/tests/e2e/e2e.spec.ts index bd63c28..1375a2c 100644 --- a/tests/e2e/e2e.spec.ts +++ b/tests/e2e/e2e.spec.ts @@ -286,15 +286,19 @@ test.describe.serial('WebHID E2E', () => { }) test('device disconnect closes opened HIDDevice state', async ({ sharedPage, vendorDevice }) => { - const disconnected = sharedPage.evaluate(async () => { - const device = (await navigator.hid.getDevices())[0] + const disconnected = sharedPage.evaluate(async (f: DeviceFilter) => { + // Granted devices sort by numeric deviceId, so the vendor must be + // found by vid/pid, not by list position. + const device = (await navigator.hid.getDevices()).find( + (x) => x.vendorId === f.vendorId && x.productId === f.productId + ) if (!device) throw new Error('vendor device missing before disconnect') if (!device.opened) await device.open() const { promise, resolve, reject } = Promise.withResolvers() navigator.hid.addEventListener('disconnect', () => resolve(device.opened === false)) setTimeout(() => reject(new Error('disconnect event not received within 10s')), 10000) return promise - }) + }, VENDOR) vendorDevice.process.stdin!.write('{"cmd":"destroy"}\n') expect(await disconnected).toBe(true) diff --git a/tests/pages/input-report-fanout-frame.html b/tests/pages/input-report-fanout-frame.html index 17bcb02..2502d0b 100644 --- a/tests/pages/input-report-fanout-frame.html +++ b/tests/pages/input-report-fanout-frame.html @@ -7,6 +7,11 @@