diff --git a/AGENTS.md b/AGENTS.md index a15cd85f..deaf2435 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/addon/js/background/content-ports.js b/addon/js/background/content-ports.js index 97461703..ae9233a1 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 6742cf74..aedb1e56 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 c245e643..276acb7e 100644 --- a/addon/js/background/messages.js +++ b/addon/js/background/messages.js @@ -1,16 +1,18 @@ ;(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 loadEffectiveSettings = webhid.import('loadEffectiveSettings') + const persistentSiteScope = webhid.import('persistentSiteScope') const { deviceCache, pendingPicker, permissionsPolicy, frameDelegations, + frameEndpoints, pageActionVisibility } = webhid.import('bgState') const { @@ -35,11 +37,14 @@ registerFrameLifetime, isFrameLifetimeActive, purgeFrame, - purgeBridge, - forTabsOfOrigin, collectDeviceSessionsForOrigin, getDeviceSessionOwner, - closeForCleanup + setDeviceSessionPlane, + collectDevicePlaneStatuses, + collectOpenDeviceIdsForTab, + setBadgeRefresh, + closeForCleanup, + closeFrameSessions } = webhid.import('bgStateOps') const { urlOrigin, frameKey, documentFrameKey } = webhid.import('bgCsp') const NativeMessaging = webhid.import('NativeMessaging') @@ -51,7 +56,293 @@ /** @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 + /** + * 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 && endpointDocumentIsLive(endpoint)) + 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 = 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) + } + } + /** + * 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) { + 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) + return 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 + * @returns {string|null} + */ + function persistenceOriginForRequest(request) { + return Object.prototype.hasOwnProperty.call(request, 'persistentOrigin') + ? 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 + * @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 = 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, + tabId, + frameId, + documentId, + origin, + url, + persistentOrigin: undefined, + frameKey: 'endpoint-' + nextEndpointId + } + frameEndpoints.set(port, endpoint) + if (!registerFrameLifetime(tabId, endpoint.frameKey)) { + frameEndpoints.delete(port) + return null + } + refreshEndpointPersistence(tabId) + 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, + childOrigin: endpoint.origin, + parentOrigin: parent.origin + }) + }) + } + /** + * Cancels delegation queries involving a retired endpoint. + * @param {object} endpoint + * @returns {void} + */ + function cancelEndpointDelegations(endpoint) { + for (const [requestId, pending] of delegationPending) { + if (pending.endpoint !== endpoint && pending.parent !== endpoint) continue + delegationPending.delete(requestId) + pending.resolve(false) + } + } + /** + * Sends a persistence-scope event only to endpoints owning that scope. + * @param {string|null} persistentOrigin + * @param {object} message + * @returns {number} + */ + function postToPersistentOriginEndpoints(persistentOrigin, message) { + if (!persistentOrigin) return 0 + let delivered = 0 + for (const endpoint of frameEndpoints.values()) { + if (endpoint.persistentOrigin !== persistentOrigin) continue + postToContentPort(endpoint.port, message) + delivered++ + } + return delivered + } /** * Replaces the in-memory device cache with `devices` (decoded), persisting * them afterwards. @@ -66,54 +357,68 @@ } /** - * @param {string} origin + * @param {string} authorityOrigin + * @param {string|null} persistentOrigin * @param {number[]} deviceIds * @returns {Promise} */ - async function notifyAllowedDevicesChanged(origin, deviceIds) { - await forTabsOfOrigin(null, (tab) => - browser.tabs - .sendMessage(tab.id, { action: 'allowedDevicesChanged', origin, deviceIds }) - .catch(() => {}) - ) + async function notifyAllowedDevicesChanged(authorityOrigin, persistentOrigin, deviceIds) { + postToPersistentOriginEndpoints(persistentOrigin, { + 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} + * @param {() => boolean} [isCurrent] + * @returns {Promise} */ - async function revokeDevices(origin, toRevoke, memberGroups) { + async function revokeDevices( + persistentOrigin, + authorityOrigin, + toRevoke, + memberGroups, + isCurrent = () => true + ) { for (const deviceId of toRevoke) { - await removeAllowedDevice(origin, deviceId) + if (!isCurrent()) return false + await removeAllowedDevice(persistentOrigin, deviceId) + if (!isCurrent()) return false 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) 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)) - 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(() => {}) - }) + if (!isCurrent()) return false + const deviceIds = await getAllowedDevices(persistentOrigin) + if (!isCurrent()) return false + for (const deviceId of toRevoke) { + postToPersistentOriginEndpoints(persistentOrigin, { + action: 'webhidDeviceEvent', + event: { + eventType: 'revoked', + deviceId, + origin: authorityOrigin, + persistentOrigin + } + }) + } + notifyAllowedDevicesChanged(authorityOrigin, persistentOrigin, deviceIds) + return true } /** @@ -145,14 +450,28 @@ * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse + * @param {object} port * @returns {boolean} */ - function handleEnumeratePaired(request, sender, sendResponse) { - const origin = request.origin || '' + 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 }) @@ -210,16 +529,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 { - if (!request.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(request.origin, request.deviceIds) + 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 }) @@ -232,13 +558,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(request.origin) - 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: [] }) } @@ -284,21 +620,25 @@ * @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 authority = scopeAuthorityForRequest(request, sender, port) + const endpoint = authority?.endpoint + const persistentOrigin = authority?.persistentOrigin + if (!authority || !endpoint || !persistentOrigin) { sendResponse({ s: 403 }) return true } - if (!registerFrameLifetime(tabId, ownerFrameKey)) { - sendResponse({ s: 503 }) - return true - } - getAllowedDevices(request.origin) + const { tabId, frameKey } = endpoint + const authorityOrigin = endpoint.origin + getAllowedDevices(persistentOrigin) .then((deviceIds) => { + if (!scopeAuthorityIsCurrent(authority)) { + sendResponse({ s: 503 }) + return + } if (!deviceIds.includes(request.deviceId)) { sendResponse({ s: 403 }) return @@ -307,40 +647,36 @@ .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( + const stillAllowed = (await getAllowedDevices(persistentOrigin)).includes( request.deviceId ) - const ownerStillAlive = isFrameLifetimeActive(tabId, ownerFrameKey) - if (!stillAllowed || !ownerStillAlive) { - logger.warn( - 'open for device', - request.deviceId, - !stillAllowed ? 'revoked while in flight' : 'owner died while in flight' - ) - if (response.t) { + 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 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: authorityOrigin, + persistentOrigin, + 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 +704,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 +719,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 +742,19 @@ } /** - * 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) { + const cleanup = retireEndpoint(endpoint) + refreshEndpointPersistence(endpoint.tabId) + if (cleanup) await cleanup } sendResponse({ s: 204 }) return true @@ -450,13 +778,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 origin = request.origin - if (!origin) { + 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 } @@ -464,15 +795,29 @@ 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) + 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(origin, 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 }) } @@ -484,29 +829,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, @@ -572,13 +917,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(request.origin) - 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: [] }) } @@ -590,15 +945,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 { - await addAllowedDevice(request.origin, request.device.deviceId) - const deviceIds = await getAllowedDevices(request.origin) - await notifyAllowedDevicesChanged(request.origin, deviceIds) - sendResponse({ success: true, hashes: deviceIds }) + 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( + scopeAuthorityIsCurrent(authority) + ? { success: true, hashes: deviceIds } + : { success: false, hashes: [] } + ) } catch (e) { sendResponse({ success: false, error: e.message, hashes: [] }) } @@ -610,20 +984,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 authority = scopeAuthorityForRequest(request, sender, port) + const origin = authority?.persistentOrigin + if (!authority || !origin) { + sendResponse({ success: false, hashes: [] }) + return + } if (request.deviceId) { - await removeAllowedDevice(request.origin, request.deviceId) + await removeAllowedDevice(origin, request.deviceId) + if (!scopeAuthorityIsCurrent(authority)) { + sendResponse({ success: false, hashes: [] }) + return + } removeDeviceInfo(request.deviceId) } - const deviceIds = await getAllowedDevices(request.origin) - if (request.deviceId) { - await notifyAllowedDevicesChanged(request.origin, deviceIds) + const deviceIds = await getAllowedDevices(origin) + if (!scopeAuthorityIsCurrent(authority)) { + sendResponse({ success: false, hashes: [] }) + return } - sendResponse({ success: true, hashes: deviceIds }) + if (request.deviceId) await notifyAllowedDevicesChanged(request.origin, origin, deviceIds) + sendResponse( + scopeAuthorityIsCurrent(authority) + ? { success: true, hashes: deviceIds } + : { success: false, hashes: [] } + ) } catch (e) { sendResponse({ success: false, error: e.message }) } @@ -635,13 +1026,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(request.origin) - 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: [] }) } @@ -650,19 +1047,113 @@ } /** + * 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 + * @param {object} [port] + * @returns {boolean} + */ + function handleGetDataPlaneStatus(request, sender, sendResponse, port) { + const tabId = Number.isInteger(request.tabId) ? request.tabId : sender.tab?.id + 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, + mode, + generation, + ready: ready === true + })), + defaultPlane: webhid.import('GLOBAL_DEFAULTS').dataPlane + }) + loadEffectiveSettings(origin || '') + .then((settings) => sendResponse({ ...response(), defaultPlane: settings.dataPlane })) + .catch(() => sendResponse(response())) + return true + } + + /** + * Updates one exact session's data-plane status. * @param {object} request * @param {object} sender + * @param {function(*): void} sendResponse + * @param {object} port * @returns {boolean} */ - function handleDeviceCountChanged(request, sender) { - if (actionApi) { - const tabId = sender.tab != null ? sender.tab.id : undefined - if (tabId != null) - actionApi.setBadgeText({ - text: request.count > 0 ? String(request.count) : '', - tabId - }) + 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} + */ + function handleDeviceCountChanged(request, sender) { + refreshTabDeviceBadge(sender.tab?.id) return false } @@ -761,8 +1252,13 @@ sendResponse(null) return false } - const origin = urlOrigin(request.origin || (sender.tab && sender.tab.url) || '') - const key = `csp:${frameKey(tabId, sender.frameId ?? 0, 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, documentUrlOrigin)}` browser.storage.session .get(key) .then((r) => sendResponse(r[key] ?? null)) @@ -781,14 +1277,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 } - browser.tabs - .sendMessage(tabId, { action: 'getFrameOrigins' }) - .then((r) => sendResponse({ origins: (r && r.origins) || [] })) - .catch(() => sendResponse({ origins: [] })) - return true + 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) { + 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', + origin: endpoint.origin, + persistentOrigin: endpoint.persistentOrigin + }) + } + } + sendResponse({ origins, targets }) + return false } /** @@ -911,32 +1431,77 @@ * @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 + } + /** * @param {object} request * @param {object} sender @@ -971,59 +1536,94 @@ 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}}} */ 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 = typeof sender.origin === 'string' ? sender.origin : '' 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 * @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 || + !(await ensureFrameDelegations(endpoint)) || + !endpointDocumentIsLive(endpoint) + ) { + sendResponse({ policy: { hid: 'none' } }) + return false + } sendResponse(policyForRequest(request, sender)) return false } /** - * Records exact iframe delegation observed by the top isolated bridge. * @param {object} request * @param {object} sender * @param {function(*): void} sendResponse @@ -1031,26 +1631,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 = typeof sender.origin === 'string' ? sender.origin : '' + if (tabId == null || frameId == null || !documentId || !origin) { sendResponse({ ok: false }) return false } @@ -1064,7 +1648,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 +1706,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 } @@ -1158,6 +1740,10 @@ pairDevice: handlePairDevice, unpairDevice: handleUnpairDevice, getAllowedDevices: handleGetAllowedDevices, + getOpenDeviceIds: handleGetOpenDeviceIds, + getDataPlaneStatus: handleGetDataPlaneStatus, + getDataPlaneStatusForOrigin: handleGetDataPlaneStatus, + setDataPlaneStatus: handleSetDataPlaneStatus, deviceCountChanged: handleDeviceCountChanged, showPageAction: handleShowPageAction, getDeviceCache: handleGetDeviceCache, @@ -1173,7 +1759,8 @@ getPolicy: handleGetPolicy, armShadowSpawn: handleArmShadowSpawn, unarmShadowSpawn: handleUnarmShadowSpawn, - pickerResult: handlePickerResult + pickerResult: handlePickerResult, + inlinePickerResult: handleInlinePickerResult } /** @@ -1183,6 +1770,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 @@ -1190,26 +1778,42 @@ }) browser.runtime.onConnect.addListener((port) => { registerContentPort(port) - let bridgeInstanceId = null + const endpoint = port.name === 'webhid-control' ? registerFrameEndpoint(port) : null port.onMessage.addListener((request) => { - const handler = HANDLERS[request.action] - if ( - port.name === 'webhid-control' && - bridgeInstanceId === null && - typeof request.bridgeInstanceId === 'string' - ) - bridgeInstanceId = request.bridgeInstanceId + 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 effectiveRequest = endpoint + ? { + ...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 let responded = false const sendPortResponse = (response) => { if (responded) return responded = true const responseMessage = { ...(response || {}) } - if (request.reqId != null) responseMessage.reqId = request.reqId - port.postMessage(responseMessage) + if (effectiveRequest.reqId != null) responseMessage.reqId = effectiveRequest.reqId + try { + port.postMessage(responseMessage) + } catch { + void 0 + } } try { - const result = handler(request, port.sender, sendPortResponse) + const result = handler(effectiveRequest, port.sender, sendPortResponse, port) if (result && typeof result.then === 'function') { result.catch(() => sendPortResponse({ s: 500 })) } else if (result !== true && !responded) { @@ -1219,17 +1823,16 @@ 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) => - NativeMessaging.closeDevice(deviceId, token) - ).catch((e) => logger.debug('bridge session cleanup failed', e)) + const cleanup = retireEndpoint(endpoint) + refreshEndpointPersistence(endpoint.tabId) + if (cleanup) void cleanup }) } }) } + webhid.export('backgroundEventFanout', { postToPersistentOriginEndpoints }) webhid.export('registerMessageHandlers', registerMessageHandlers) })() diff --git a/addon/js/background/nm.js b/addon/js/background/nm.js index ba3c30f6..77948187 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, @@ -33,6 +45,8 @@ reconnectDelay: 1000, nmHostName: NM_HOST_FORWARDER, lastError: null, + handshakePromise: null, + handshakePort: null, /** Per-request deadline for NM requests (see sendFrame). */ REQUEST_TIMEOUT_MS: 30000, @@ -147,17 +161,18 @@ }, /** - * Retires one exact Native Messaging port and its authority lifetime. * @param {object} port * @returns {boolean} */ retirePort(port) { if (this.port !== port) return false this.port = null + this.handshakePromise = null + this.handshakePort = null for (const [, p] of this.pending) p.resolve({ s: 503 }) this.pending.clear() clearAuthorityOwnership() - broadcastGlobalReset() + broadcastGlobalReset(broadcastExactGlobalReset) return true }, @@ -263,8 +278,20 @@ 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.handshakePromise) { + return this.handshakePromise + } + 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 }, async sendReport(deviceId, reportId, data) { return await this.sendPacked((reqId) => @@ -297,8 +324,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 +345,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 +377,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 +415,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 3894285c..c7a1ebe9 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 5871ae46..6b601245 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. @@ -131,19 +148,20 @@ } /** - * 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, persistentOrigin?: string|null, 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) if (!byToken) { byToken = new Map() @@ -151,11 +169,15 @@ } byToken.set(token, { tabId: owner.tabId, + frameId: owner.frameId, + documentId: owner.documentId || null, origin: owner.origin, + persistentOrigin: owner.persistentOrigin || null, frameKey, - bridgeInstanceId: owner.bridgeInstanceId || '', - clientKey: owner.clientKey || '' + clientKey: owner.clientKey || '', + port: owner.port || null }) + refreshBadge(owner.tabId) logger.debug('register session device ' + deviceId + ' tab ' + owner.tabId) return true } @@ -170,10 +192,22 @@ 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) } + /** + * 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 @@ -185,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 } @@ -215,6 +249,62 @@ 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.persistentOrigin || 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.persistentOrigin || owner.origin) === origin) + ) { + ids.add(String(deviceId)) + break + } + } + } + return [...ids] + } /** * Collects session tokens for one trusted frame generation. @@ -252,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 @@ -327,20 +420,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 +440,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 } @@ -376,31 +468,21 @@ await Promise.all(pending) } /** - * Retires all frame lifetimes and sessions owned by one bridge instance. + * Closes sessions owned by one live frame when its persistence scope changes. * @param {number} tabId - * @param {string} bridgeInstanceId + * @param {string} frameKey * @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) - } - } + 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 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 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) @@ -487,24 +569,36 @@ } /** - * 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)) } /** - * 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() { + 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) } /** @@ -513,22 +607,32 @@ * @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, unregisterDeviceSession, collectDeviceSessions, + collectDeviceSessionOwners, collectDeviceSessionsForOrigin, collectDeviceSessionsForTab, collectDeviceSessionsForFrame, getDeviceSessionOwner, + setDeviceSessionPlane, + collectDevicePlaneStatuses, + collectOpenDeviceIdsForTab, clearDeviceSessions, clearDeviceSessionsForOrigin, clearDeviceSessionsForTab, @@ -542,8 +646,8 @@ isFrameLifetimeActive, retireFrameLifetime, purgeFrame, - purgeBridge, purgeTab, + closeFrameSessions, broadcastGlobalReset, clearAuthorityOwnership, clearDeviceOwnership, diff --git a/addon/js/background/storage.js b/addon/js/background/storage.js index 790b8ac8..1be9d3cd 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/bootstrap-lifetime.js b/addon/js/content/isolated/bootstrap-lifetime.js deleted file mode 100644 index e4108bec..00000000 --- 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 d44d3c3f..492da97b 100644 --- a/addon/js/content/isolated/bridge.js +++ b/addon/js/content/isolated/bridge.js @@ -7,27 +7,43 @@ const isChromium = webhid.import('isChromium') 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') 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() + let authorityOrigin = '' + let persistentOrigin = null + let scopeLoadGeneration = 0 + let authorityFailed = false + let resolveAuthorityReady = null + const authorityReady = new Promise((resolve) => { + resolveAuthorityReady = resolve + }) /** @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 +70,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,13 +78,50 @@ }) } 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) + 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) => + sendBackgroundRequest({ + 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 } - if (message && message.action === 'allowedDevicesChanged') { - const origin = message.origin || window.location.origin - 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 @@ -94,6 +147,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) { @@ -104,8 +159,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', @@ -138,7 +193,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(() => { @@ -147,44 +202,33 @@ } /** - * 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 {string|null} persistentOrigin * @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 +238,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 +262,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,39 +272,42 @@ } 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, origin, frameId: identity.frameId, documentId: identity.documentId, + persistentOrigin: null, 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, + authorityOrigin || '', + browserFrameIdentity(window) + ) /** * @param {MessagePort} port @@ -325,7 +343,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 } /** @@ -351,20 +370,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}>} @@ -427,50 +432,40 @@ } 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) + const isStatusRequest = + request.action === 'getDataPlaneStatus' || request.action === 'getDataPlaneStatusForOrigin' + if ( + request.action !== 'getOpenDeviceIds' && + !isStatusRequest && + request.action !== 'getFrameOrigins' + ) + return false + 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 }) }) - 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 - } + .catch(() => sendResponse({ ids: [], planes: [], origins: [] })) + return true }) /** * @param {string} deviceId @@ -626,49 +621,97 @@ /** @type {import("./types.js").SettingsStore} */ const settings = createSettingsStore(webhid.import('GLOBAL_DEFAULTS')) /** @type {Map} */ - const settingsByOrigin = new Map([[window.location.origin, settings]]) - /** @type {Map>} */ - const settingsLoads = new Map() + const settingsByOrigin = 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 } + 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 existing = settingsLoads.get(origin) - if (existing) return existing - const load = loadEffectiveSettings(origin) - .then((values) => { - const store = settingsForOrigin(origin) - store.set(values) - return store - }) - .catch((error) => { - logger.warn('load settings failed for', origin, ':', error.message) - return settingsForOrigin(origin) + return settingsLoader.load(origin) + } + /** @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 (!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 + } + if (firstInitialization || scopeChanged) { + settingsByOrigin.clear() + settingsLoader.clear() + settingsByOrigin.set(persistentOrigin || '', settings) + installSettingsListeners(authorityOrigin, settings) + if (scopeChanged) { + allowedByOrigin.delete(previousPersistentOrigin || '') + loadedOrigins.delete(previousPersistentOrigin || '') + loadAllowedDeviceIds(persistentOrigin || '') + } + } + 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() + }) }) - settingsLoads.set(origin, load) - 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() + } + settleAuthorityReady() + } /** @type {Map} */ const spawnGen = new Map() /** @@ -753,6 +796,7 @@ if (!context) return const client = clientForKey(context, clientKeyForPlaneKey(key)) if (!client) return + notifyBackgroundPlaneStatus(key, generation, true) try { client.port.postMessage({ type: 'dataPlaneReady', @@ -763,6 +807,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 @@ -776,6 +853,7 @@ if (!context) return const client = clientForKey(context, clientKeyForPlaneKey(key)) if (!client) return + notifyBackgroundPlaneStatus(key, generation, false, true) try { client.port.postMessage({ type: 'dataPlaneUnavailable', @@ -794,6 +872,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`. @@ -810,7 +896,6 @@ } } } - /** * Checks whether a device is in the allowed set for `origin`, loading that * origin lazily when necessary. @@ -820,6 +905,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)) } @@ -839,6 +925,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', @@ -978,8 +1070,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') { @@ -1262,7 +1355,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 +1379,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 +1459,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 }) @@ -1421,28 +1514,32 @@ } ;(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(persistentOrigin || '') + loadAllowedDeviceIds(persistentOrigin || '') })() - /** * @param {object} msg * @param {ArrayBuffer[]} [transfer] @@ -1458,7 +1555,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 +1647,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 +1724,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 +1731,7 @@ */ function getRequestOrigin(data) { const port = requestPortMap.get(data.id) - return port ? portOrigin.get(port) : 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 {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 + return frameContextForPort(port)?.persistentOrigin || persistentOrigin || '' } /** @@ -1709,7 +1768,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({ @@ -1745,7 +1803,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 { @@ -1854,21 +1912,106 @@ } } /** - * @param {FrameContext} context + * @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 hasHidDelegation(context) { - if (!context.source || context.source === window) return true + 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 frames = document.querySelectorAll('iframe,frame') - for (const frame of frames) { - if (frame.contentWindow !== context.source) continue - const allow = frame.getAttribute('allow') || '' - return allow.split(';').some((directive) => /^\s*hid(?:\s|$)/i.test(directive)) + const getFrameId = browser.runtime.getFrameId + const getDocumentId = browser.runtime.getDocumentId + 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 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 {} + } 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 +2025,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, @@ -1936,66 +2073,54 @@ const filters = payload.filters || [] const exclusionFilters = payload.exclusionFilters || [] const context = frameContextForPort(requestPort) - const origin = context ? context.origin : window.location.origin + const origin = context ? context.persistentOrigin || '' : persistentOrigin || '' const originSettings = await loadSettingsForOrigin(origin) const pickerMode = isChromium && originSettings.devicePickerMode === 'pageAction' ? '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 +2136,7 @@ if ( !context || context.destroyed || - !frameContexts.has(context.key) || + frameContext !== context || !client || client.sessions !== sessions ) @@ -2027,10 +2152,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 @@ -2061,6 +2185,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 } } @@ -2078,10 +2203,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) + ) } /** * @@ -2105,7 +2229,7 @@ deviceIds: devices.map((device) => device.deviceId) }).catch((e) => logger.debug('recordGrantGroup failed', e)) } - await loadAllowedDeviceIds(origin) + await loadAllowedDeviceIds(persistentOrigin || '') } /** @@ -2119,7 +2243,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 @@ -2147,7 +2271,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 +2348,6 @@ } catch { if (action === 'open' && nmOpenAttempt) { releaseNmOpenAttempt(key) - nmOpenAttempt = false } if (action === 'open') { if (sessions) sessions.delete(deviceId) @@ -2281,7 +2404,6 @@ clientSessions.delete(workerPort) clientKeysByPort.delete(workerPort) frameContextByPort.delete(workerPort) - portOrigin.delete(workerPort) try { workerPort.onmessage = null workerPort.close() @@ -2315,11 +2437,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] @@ -2336,7 +2463,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 +2503,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 +2510,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 +2559,7 @@ } catch (e) { logger.debug('frame page port cleanup failed', e) } + if (frameContext === context) frameContext = null } /** @@ -2446,7 +2567,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() @@ -2480,11 +2601,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) ) - }) + ) } /** @@ -2513,7 +2634,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 +2666,18 @@ 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 = + 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) @@ -2672,7 +2795,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 +2823,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) @@ -2766,6 +2889,7 @@ logger.info('data plane changed:', dp, 'open devices:', active.length) } + const settingsListenerSet = createSettingsListenerSet() /** * @param {string} origin * @param {import("./types.js").SettingsStore} store @@ -2773,28 +2897,39 @@ */ function installSettingsListeners(origin, store) { 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 }) + settingsListenerSet.install(store, [ + [ + 'hidePageAction', + (hidden) => { + if (!hidden) pageActionMarked = false } - } - }) + ], + ['dataPlane', (dp) => applyDataPlane(dp, origin)], + [ + 'workerSpawnMode', + () => { + cachedSpawnModes.delete(origin) + applyDataPlane(store.dataPlane, origin) + } + ], + ['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) => { @@ -2804,15 +2939,19 @@ 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 (persistentOrigin && parsed.origin === persistentOrigin) { + 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 + 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/addon/js/content/main/index.js b/addon/js/content/main/index.js index 14d89e1a..b5776864 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, @@ -841,6 +846,11 @@ settings: (data) => { settings.set(data.settings || {}) }, + persistentScopeChanged: (data) => { + settings.set(data.settings || {}) + pairedDevices = null + deviceInfoCache = null + }, event: (data) => { dispatchDeviceEvent(data.event) } @@ -929,17 +939,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 {} @@ -1450,7 +1481,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 +1716,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} */ @@ -1973,6 +2009,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/addon/js/internal/pages/popup/index.js b/addon/js/internal/pages/popup/index.js index cab6fa7d..20975e5e 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,67 @@ 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) + } + /** + * 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 || target.origin + const parts = target.persistentOrigin.split('|') + return parts.length === 3 && parts[0] === 'opaque' + ? `${parts[2]} (Opaque iframe)` + : target.label || target.origin + } /** - * 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 = labelForTarget(selectedTarget()) + siteButton.classList.toggle('has-list', frameTargets.length > 1) siteButton.setAttribute('aria-expanded', 'false') originList.hidden = true } @@ -98,16 +132,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 +150,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 +166,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 = labelForTarget(target) + li.addEventListener('click', () => selectTarget(target)) originList.appendChild(li) } renderSiteLabel() @@ -170,7 +203,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 +211,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 +240,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 +257,7 @@ * @returns {Promise} */ async function loadSettings() { - return loadEffectiveSettings(origin) + return loadEffectiveSettings(persistentOrigin || origin) } /** @@ -228,8 +267,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,11 +386,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.tabs.sendMessage(tab.id, { + const r = await browser.runtime.sendMessage({ action: 'getDataPlaneStatus', - origin + tabId: tab.id, + origin: persistentOrigin }) planes = (r && r.planes) || [] } catch (e) { @@ -385,11 +425,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 { @@ -402,12 +442,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) @@ -548,9 +589,10 @@ /** @type {Set} */ let openIds = new Set() try { - const r = await browser.tabs.sendMessage(tab.id, { + const r = await browser.runtime.sendMessage({ action: 'getOpenDeviceIds', - origin + tabId: tab.id, + origin: persistentOrigin }) const rIds = r != null ? r.ids : undefined if (rIds) openIds = new Set(rIds.map((id) => Number(id))) diff --git a/addon/js/utils/settings.js b/addon/js/utils/settings.js index 11447177..1defcb43 100644 --- a/addon/js/utils/settings.js +++ b/addon/js/utils/settings.js @@ -196,9 +196,70 @@ } }) } + /** + * 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 + } + } + /** + * 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) @@ -240,6 +301,33 @@ 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|${topAuthorityOrigin}|${sourceOrigin}` + } /** * Loads all global settings from storage, applying defaults for missing keys. @@ -265,6 +353,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 +375,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 +405,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/addon/manifest.chromium.json b/addon/manifest.chromium.json index 0c5fea6d..e7c9ce4f 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 6f84ef6d..0fa5332e 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 d15b280e..671d9983 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/crates/Cargo.lock b/crates/Cargo.lock index 41e79907..699f67e5 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 5fdc7373..a2b5bf4f 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 41803bdf..0d547549 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 ead7a53e..f8d53b9b 100644 --- a/crates/webhid-daemon/src/hid.rs +++ b/crates/webhid-daemon/src/hid.rs @@ -9,29 +9,87 @@ 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/")) +} + +/// Identities on other platforms never depend on the descriptor. +#[cfg(not(target_os = "linux"))] +fn identity_needs_descriptor(_info: &HidDeviceInfo) -> bool { + false +} + #[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 +119,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 +167,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 +186,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 +217,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 +225,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 +292,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 +411,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 fd28191e..7e046fca 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 00000000..720e9670 --- /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" + ); +} diff --git a/crates/webhid-mock/src/lib.rs b/crates/webhid-mock/src/lib.rs new file mode 100644 index 00000000..f18cdcc4 --- /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 f9aa9284..44936ea7 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(); -} diff --git a/tests/browser/page-action.spec.ts b/tests/browser/page-action.spec.ts index 4bdb8078..4d1205c4 100644 --- a/tests/browser/page-action.spec.ts +++ b/tests/browser/page-action.spec.ts @@ -163,57 +163,130 @@ test.describe('extension action surfaces', () => { pageUrl }) => { const activeOrigin = new URL(pageUrl('/')).origin - const selectedOrigin = `${activeOrigin}-selected` + const selectedPersistent = 'opaque|https://host.example|https://widget.example' 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( + (target) => { + 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 }) + const storageSet = browser.storage.local.set.bind(browser.storage.local) + browser.storage.local.set = async (value) => { + saved.push(value) + return storageSet(value) } - if (action === 'getOpenDeviceIds') - return request.origin === origin.selected ? { ids: ['1'] } : { ids: [] } - return tabsSendMessage(tabId, message) - } - }, { active: activeOrigin, selected: selectedOrigin }) + 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 { + 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 === target.persistent + ? { 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: [] } + } + return runtimeSendMessage(message) + } + }, + { active: activeOrigin, persistent: selectedPersistent } + ) const popupUrl = await backgroundPage.evaluate(() => browser.runtime.getURL('js/internal/pages/popup/index.html') ) 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() await page.locator('#origin-list li').nth(1).click() - await expect(page.locator('#site-name-text')).toHaveText(selectedOrigin) - await expect(page.locator('#status')).toHaveClass(/state-warn/) + 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"]') + .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 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 ( @@ -227,22 +300,47 @@ test.describe('extension action surfaces', () => { }) ) }, - { start: before, origin: selectedOrigin }, + { start: before, origin: selectedPersistent }, { timeout: 15000 } ) 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 }>) - : [] + 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) expect(afterSelection).toEqual( expect.arrayContaining([ - { action: 'getDataPlaneStatus', origin: selectedOrigin }, - { action: 'getOpenDeviceIds', origin: selectedOrigin } + { action: 'getDataPlaneStatus', origin: selectedPersistent }, + { 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, diff --git a/tests/browser/permissions-policy.spec.ts b/tests/browser/permissions-policy.spec.ts index 0de95fe0..9388d04f 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 @@ -213,6 +261,147 @@ 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('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 + '/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 + 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') + 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] + 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) + 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') + 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('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, @@ -238,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/browser/worker-spawn.spec.ts b/tests/browser/worker-spawn.spec.ts index d41e0ec2..76249953 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) }) diff --git a/tests/e2e/e2e.spec.ts b/tests/e2e/e2e.spec.ts index 39d97b85..1375a2cd 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) => { @@ -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/e2e/input-report-fanout.spec.ts b/tests/e2e/input-report-fanout.spec.ts index 49bf0470..58ded7ad 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/e2e/nm-runtime-port.spec.ts b/tests/e2e/nm-runtime-port.spec.ts index 67dbeb81..cd825d04 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()) { @@ -105,4 +110,119 @@ test.describe.serial('NM runtime port topology', () => { 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/e2e/picker-bypass.spec.ts b/tests/e2e/picker-bypass.spec.ts index 37a28dd1..914a8fac 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() diff --git a/tests/pages/input-report-fanout-frame.html b/tests/pages/input-report-fanout-frame.html index 17bcb029..2502d0b9 100644 --- a/tests/pages/input-report-fanout-frame.html +++ b/tests/pages/input-report-fanout-frame.html @@ -7,6 +7,11 @@