Skip to content

Commit 5b97f5c

Browse files
authored
Merge pull request #210 from linux-credentials/webext-updates
Web extension updates
2 parents 747c1fc + 9da531e commit 5b97f5c

7 files changed

Lines changed: 146 additions & 85 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ run xdg-desktop-portal while we work on upstreaming the changes.
3939
- ui: Reorganize credential selection screen to promote hybrid QR code.
4040
- ui: Convert UI templates to Blueprint.
4141
- webext: Ignore conditional mediation requests.
42+
- webext: Fix request routing issues when multiple tabs are active.
43+
- webext: Only start extension during WebAuthn calls for performance.
44+
- webext: Load Firefox extension on all sites
4245

4346
# [0.2.0] - 2025-02-18
4447

‎webext/add-on/background.js‎

Lines changed: 16 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -9,53 +9,27 @@
99

1010
const browserAPI = globalThis.browser || globalThis.chrome;
1111

12-
let contentPort;
13-
let nativePort;
14-
1512
function connected(port) {
16-
console.log('[credentialsd] received connection from content script');
17-
contentPort = port;
18-
19-
// Connect to native messaging host
20-
nativePort = browserAPI.runtime.connectNative('xyz.iinuwa.credentialsd_helper');
21-
22-
// Check for connection errors (browser-specific patterns)
23-
const connectError = nativePort.error || browserAPI.runtime.lastError;
24-
if (connectError) {
25-
console.error('[credentialsd] native connect error:', connectError.message || connectError);
26-
return;
27-
}
28-
29-
console.log('[credentialsd] connected to native app');
30-
31-
contentPort.onMessage.addListener(rcvFromContent);
32-
nativePort.onMessage.addListener(rcvFromNative);
33-
34-
nativePort.onDisconnect.addListener(() => {
35-
const error = browserAPI.runtime.lastError;
36-
if (error) {
37-
console.error('[credentialsd] native port disconnected:', error.message);
38-
}
39-
});
13+
const portId = port.sender.tab.id;
14+
console.log('[credentialsd] received connection from content script', portId);
15+
port.onMessage.addListener((msg) => rcvFromContent(msg, port));
4016
}
4117

42-
function rcvFromContent(msg) {
43-
const { requestId, cmd, options } = msg;
44-
const origin = contentPort.sender.origin;
45-
const topOrigin = new URL(contentPort.sender.tab.url).origin;
18+
async function rcvFromContent(msg, port) {
19+
const { requestId, cmd, options = null } = msg;
20+
console.debug('[credentialsd] forwarding', cmd, 'to native app');
4621

47-
if (options) {
48-
console.debug('[credentialsd] forwarding', cmd, 'to native app');
49-
nativePort.postMessage({ requestId, cmd, options, origin, topOrigin });
50-
} else {
51-
console.debug('[credentialsd] forwarding', cmd, '(no options) to native app');
52-
nativePort.postMessage({ requestId, cmd, origin, topOrigin });
53-
}
54-
}
22+
const origin = port.sender.origin;
23+
const topOrigin = new URL(port.sender.tab.url).origin;
24+
const request = { requestId, cmd, options, origin, topOrigin };
5525

56-
function rcvFromNative(msg) {
57-
console.log('[credentialsd] received from native, forwarding to content');
58-
contentPort.postMessage(msg);
26+
try {
27+
const response = await browserAPI.runtime.sendNativeMessage('xyz.iinuwa.credentialsd_helper', request);
28+
console.log('[credentialsd] received from native, forwarding to content');
29+
port.postMessage(response);
30+
} catch (error) {
31+
console.error('[credentialsd] Error sending message to native app', error.message);
32+
}
5933
}
6034

6135
// Listen for connections from content script

‎webext/add-on/content-bridge.js‎

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,28 +7,35 @@
77
*/
88

99
const browserAPI = globalThis.browser || globalThis.chrome;
10-
const port = browserAPI.runtime.connect({ name: 'credentialsd-helper' });
10+
let mainPort = null;
1111

12-
// Forward responses from background back to page context
13-
port.onMessage.addListener((msg) => {
14-
const { requestId, data, error } = msg;
15-
window.postMessage({
16-
type: 'credentialsd-response',
17-
requestId,
18-
data,
19-
error,
20-
}, '*');
21-
});
12+
function connectToBackground() {
13+
mainPort = browserAPI.runtime.connect({ name: 'credentialsd-helper' });
14+
// Forward responses from background back to page context
15+
mainPort.onMessage.addListener((msg) => {
16+
const { requestId, data = undefined, error = undefined } = msg;
17+
window.postMessage({
18+
type: 'credentialsd-response',
19+
requestId,
20+
data,
21+
error,
22+
}, '*');
23+
});
2224

23-
port.onDisconnect.addListener(() => {
24-
console.warn('[credentialsd] background port disconnected');
25-
});
2625

26+
mainPort.onDisconnect.addListener(() => {
27+
console.warn('[credentialsd] background port disconnected');
28+
mainPort = null;
29+
setTimeout(connectToBackground, 1000);
30+
});
31+
return mainPort;
32+
}
2733
// Listen for requests from the MAIN world content script
2834
window.addEventListener('message', (event) => {
2935
if (event.source !== window) return;
3036
if (event.data?.type !== 'credentialsd-request') return;
3137

38+
const port = mainPort || connectToBackground();
3239
const { requestId, cmd, options } = event.data;
3340
port.postMessage({ requestId, cmd, options });
3441
});

‎webext/add-on/content-main.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ window.addEventListener('message', (event) => {
1717
if (event.source !== window) return;
1818
if (event.data?.type !== 'credentialsd-response') return;
1919

20-
const { requestId, data, error } = event.data;
20+
const { requestId, data = undefined, error = undefined } = event.data;
2121
const request = pendingRequests[requestId];
2222
if (!request) return;
2323
delete pendingRequests[requestId];

‎webext/add-on/manifest.chromium.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"description": "Helper to integrate credentialsd with the browser",
33
"manifest_version": 3,
44
"name": "credentialsd-helper",
5-
"version": "0.1.0",
5+
"version": "0.2.0",
66
"icons": {
77
"48": "icons/logo.svg"
88
},

‎webext/add-on/manifest.firefox.json‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"description": "Helper to integrate credentialsd with the browser",
33
"manifest_version": 3,
44
"name": "credentialsd-helper",
5-
"version": "0.1.0",
5+
"version": "0.2.0",
66
"icons": {
77
"48": "icons/logo.svg"
88
},
@@ -21,8 +21,7 @@
2121
"content_scripts": [
2222
{
2323
"matches": [
24-
"https://webauthn.io/*",
25-
"https://demo.yubico.com/*"
24+
"<all_urls>"
2625
],
2726
"js": [
2827
"content-bridge.js"
@@ -32,8 +31,7 @@
3231
},
3332
{
3433
"matches": [
35-
"https://webauthn.io/*",
36-
"https://demo.yubico.com/*"
34+
"<all_urls>"
3735
],
3836
"js": [
3937
"content-main.js"
@@ -48,4 +46,4 @@
4846
"permissions": [
4947
"nativeMessaging"
5048
]
51-
}
49+
}

‎webext/app/credential_manager_shim.py‎

Lines changed: 100 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from enum import Enum
99
import json
1010
import logging
11+
import re
1112
import secrets
1213
import signal
1314
import struct
@@ -52,6 +53,58 @@ def getMessage():
5253
raise e
5354

5455

56+
class PortalError(Exception):
57+
def from_string(s: str):
58+
m = re.match(r"xyz.iinuwa.credentialsd.(\w+): (?:no description|(.*))", s)
59+
if m:
60+
(name, message) = m.groups()
61+
match name:
62+
case "AbortError":
63+
return AbortError
64+
case "ConstraintError":
65+
return ConstraintError
66+
case "InvalidStateError":
67+
return InvalidStateError
68+
case "NotSupportedError":
69+
return NotSupportedError
70+
case "SecurityError":
71+
return SecurityError
72+
case "NotAllowedError":
73+
return NotAllowedError
74+
case "TypeError":
75+
return TypeError
76+
case _:
77+
return PortalError()
78+
79+
80+
class AbortError(PortalError):
81+
pass
82+
83+
84+
class ConstraintError(PortalError):
85+
pass
86+
87+
88+
class InvalidStateError(PortalError):
89+
pass
90+
91+
92+
class NotSupportedError(PortalError):
93+
pass
94+
95+
96+
class SecurityError(PortalError):
97+
pass
98+
99+
100+
class NotAllowedError(PortalError):
101+
pass
102+
103+
104+
class TypeError(PortalError):
105+
pass
106+
107+
55108
# Encode a message for transmission,
56109
# given its content.
57110
def encodeMessage(messageContent):
@@ -113,14 +166,15 @@ def message_handler(msg: Message):
113166
if code == 0:
114167
future.set_result(value)
115168
elif code == 1:
116-
future.set_exception(Exception("Portal request cancelled"))
169+
logging.error("Request cancelled")
170+
future.set_exception(AbortError())
117171
raise
118172
elif code == 2 and "error" in value:
119-
future.set_exception(
120-
Exception(f"Portal returned an error: {value['error'].value}")
121-
)
173+
logging.error(value["error"].value)
174+
future.set_exception(PortalError.from_string(value["error"].value))
122175
else:
123-
future.set_exception(Exception("Portal returned an unknown error"))
176+
logging.error("Portal returned an unknown error")
177+
future.set_exception(PortalError())
124178
return True
125179

126180
def when_done(_fut):
@@ -459,9 +513,8 @@ async def get_interface():
459513
return INTERFACE
460514

461515

462-
async def run(cmd, options, origin, top_origin):
516+
async def run(interface, cmd, options, origin, top_origin):
463517
logging.debug("Executing command")
464-
interface = await get_interface()
465518

466519
if cmd == "create":
467520
if "publicKey" in options:
@@ -519,22 +572,48 @@ async def run(cmd, options, origin, top_origin):
519572

520573
async def main():
521574
logging.info("starting credential_manager_shim")
575+
cancel_task = asyncio.create_task(quit.wait())
522576

523-
while not quit.is_set():
524-
logging.debug("starting event loop message")
525-
receivedMessage = getMessage()
526-
request_id = receivedMessage["requestId"]
527-
try:
528-
cmd = receivedMessage["cmd"]
529-
options = receivedMessage.get("options", None)
530-
origin = receivedMessage["origin"]
531-
top_origin = receivedMessage["topOrigin"]
532-
auth_data = await run(cmd, options, origin, top_origin)
577+
receivedMessage = getMessage()
578+
request_id = receivedMessage["requestId"]
579+
try:
580+
interface = await get_interface()
581+
cmd = receivedMessage["cmd"]
582+
options = receivedMessage.get("options", None)
583+
origin = receivedMessage["origin"]
584+
top_origin = receivedMessage["topOrigin"]
585+
credentialsd_task = asyncio.create_task(
586+
run(interface, cmd, options, origin, top_origin)
587+
)
588+
timeout = options.get("timeout", 5 * 60 * 1000) // 1000
589+
done, pending = await asyncio.wait(
590+
{credentialsd_task, cancel_task},
591+
timeout=timeout,
592+
return_when=asyncio.FIRST_COMPLETED,
593+
)
594+
if credentialsd_task in done:
595+
logging.info("got a response from credentialsd")
596+
auth_data = credentialsd_task.result()
533597
sendMessage(encodeMessage({"requestId": request_id, "data": auth_data}))
534-
except Exception as e:
535-
logging.error("Failed to send message", exc_info=e)
536-
sendMessage(encodeMessage({"requestId": request_id, "error": str(e)}))
537-
logging.debug("Sent error message")
598+
elif cancel_task in done:
599+
logging.info("cancelled")
600+
raise asyncio.CancelledError("Cancelled")
601+
else:
602+
logging.info("timed out")
603+
raise TimeoutError("Timed out")
604+
interface.bus.disconnect()
605+
606+
except Exception as e:
607+
logging.error("Failed to send message", exc_info=e)
608+
sendMessage(
609+
encodeMessage(
610+
{
611+
"requestId": request_id,
612+
"error": {"name": type(e).__name__, "message": str(e)},
613+
}
614+
)
615+
)
616+
logging.debug("Sent error message")
538617
logging.info("quitting credential_manager_shim")
539618

540619

0 commit comments

Comments
 (0)