A full-featured download manager.
feat(bridge): support remote extensions over MBP1 (#2033)
Dr_rOot1b51c8fc1d24
diff --git a/.claude/rules/bridge.md b/.claude/rules/bridge.mdindex 4e467da2..83b6d3eb 100644--- a/.claude/rules/bridge.md+++ b/.claude/rules/bridge.md@@ -17,7 +17,8 @@ Import `ErrorCodes` and `makeMdxpError` from the package.- Extension WebSockets speak MBP1 (`docs/bridge-pairing-protocol.md`), whichauthenticates *below* MDXP. `/pair?nonce=...` runs the §6 first-pairhandshake and `/v1` the §8 challenge–response; `/v1` carries **no**- credential in its URL and a `?token=` query is ignored. Only once a route+ credential in its URL and every query, including `?token=`, is rejected by+ the raw-route gate. Only once a routeauthenticates does MDXP start, inside the §10 AEAD envelope, and`motrix/initialize` is the client's first request there.- `WebSocketBridgeServer` always owns and registers `motrix/initialize`.diff --git a/README.md b/README.mdindex 5192a73f..eb828343 100644--- a/README.md+++ b/README.md@@ -187,9 +187,13 @@ docker compose exec server motrix-admin pairing approve ABCD-EFGH```Remote CLI and agent clients pair through the device-code flow. Browser-extensions pair with the desktop app through native messaging; first-time-extension pairing is not provided by the headless server. Direct HTTP is-appropriate only on a trusted LAN. Internet or untrusted-LAN access requires a+extensions can pair with the headless Server when+`MOTRIX_REMOTE_EXTENSION_ENABLED=true` and+`MOTRIX_REMOTE_EXTENSION_PUBLIC_URL` is the WS/WSS address entered in the+Extension. HTTPS remains the default operator requirement. A direct trusted-LAN+HTTP operator additionally requires+`MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP=true` and produces a startup warning;+never enable it on the Internet or an untrusted LAN. Internet access requires aTLS reverse proxy and firewall rules around the origin ports. See the[Docker Server deployment guide](./docs/docker-server.md) for ownership setup,Docker Hub/GHCR image and tag selection, DSM 7 and fnOS installation, ports,diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 77d032b1..c7d5445c 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -176,10 +176,13 @@ docker compose exec server motrix-admin pairing pendingdocker compose exec server motrix-admin pairing approve ABCD-EFGH```-远程 CLI 和 agent 客户端通过 device-code flow 配对。浏览器扩展通过 native messaging-与桌面应用配对;headless server 不提供浏览器扩展的首次配对。只应在可信 LAN 上-直接使用 HTTP;通过公网或不可信 LAN 访问时,必须配置 TLS 反向代理,并用防火墙保护-源端口。Docker Hub/GHCR 镜像与 tag 选择、群晖+远程 CLI 和 agent 客户端通过 device-code flow 配对。设置+`MOTRIX_REMOTE_EXTENSION_ENABLED=true`,并把扩展中要填写的 WS/WSS 地址设为+`MOTRIX_REMOTE_EXTENSION_PUBLIC_URL` 后,浏览器扩展也可以与 headless Server 配对。+operator 默认仍要求 HTTPS;可信局域网若要直接使用 HTTP,还必须显式设置+`MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP=true`,启动日志会持续提示风险。公网或不可信+LAN 绝不能开启该选项,必须配置 TLS 反向代理,并用防火墙保护源端口。+Docker Hub/GHCR 镜像与 tag 选择、群晖DSM 7 和飞牛 fnOS 安装、目录所有权、端口、诊断与备份/升级说明见[Docker Server 部署指南](./docs/docker-server.zh-CN.md)。diff --git a/compose.named-volumes.yaml b/compose.named-volumes.yamlindex 3dc8ec25..420e50c1 100644--- a/compose.named-volumes.yaml+++ b/compose.named-volumes.yaml@@ -22,6 +22,9 @@ services:MOTRIX_MDXP_HOST: 0.0.0.0MOTRIX_MDXP_PORT: 16801MOTRIX_PUBLIC_URL: "${MOTRIX_PUBLIC_URL:-}"+ MOTRIX_REMOTE_EXTENSION_ENABLED: "${MOTRIX_REMOTE_EXTENSION_ENABLED:-false}"+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: "${MOTRIX_REMOTE_EXTENSION_PUBLIC_URL:-}"+ MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP: "${MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP:-false}"ports:- "${MOTRIX_WEB_BIND_IP:-${MOTRIX_BIND_IP:-0.0.0.0}}:${MOTRIX_HTTP_PORT:-8080}:8080"- "${MOTRIX_MDXP_BIND_IP:-${MOTRIX_BIND_IP:-0.0.0.0}}:${MOTRIX_MDXP_PUBLIC_PORT:-16801}:16801"diff --git a/compose.yaml b/compose.yamlindex 966eff49..9d58329f 100644--- a/compose.yaml+++ b/compose.yaml@@ -22,6 +22,9 @@ services:MOTRIX_MDXP_HOST: 0.0.0.0MOTRIX_MDXP_PORT: 16801MOTRIX_PUBLIC_URL: "${MOTRIX_PUBLIC_URL:-}"+ MOTRIX_REMOTE_EXTENSION_ENABLED: "${MOTRIX_REMOTE_EXTENSION_ENABLED:-false}"+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: "${MOTRIX_REMOTE_EXTENSION_PUBLIC_URL:-}"+ MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP: "${MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP:-false}"ports:- "${MOTRIX_WEB_BIND_IP:-${MOTRIX_BIND_IP:-0.0.0.0}}:${MOTRIX_HTTP_PORT:-8080}:8080"- "${MOTRIX_MDXP_BIND_IP:-${MOTRIX_BIND_IP:-0.0.0.0}}:${MOTRIX_MDXP_PUBLIC_PORT:-16801}:16801"diff --git a/docs/bridge-pairing-protocol.md b/docs/bridge-pairing-protocol.mdindex 5bc6250c..b49f5cbd 100644--- a/docs/bridge-pairing-protocol.md+++ b/docs/bridge-pairing-protocol.md@@ -13,6 +13,13 @@ tracked to implementation — see the Appendix C review log). Phase-Aimplementation may begin; the remaining Phase-A prerequisites in[§14](#14-review-and-implementation-gates) still apply.+Release context: MBP1 is merged but not yet released. The browser Extension is+also unpublished, and only a small number of historical Server beta builds+exist. The supported profile therefore converges directly on MBP1; there is no+legacy Extension bearer migration or downgrade window. The remote Server+transport requirements in §4.4 are normative additions to the same MBP1 v1+wire protocol, not a second ciphersuite or remote-only frame fork.+Related documents: [RFC 9382] (SPAKE2), [RFC 5869] (HKDF), [RFC 8032](edwards25519 encoding), [RFC 7914] (scrypt), [RFC 4648] (base32 background;MBP1 uses the Crockford alphabet defined in §7). The MDXP application protocol@@ -44,6 +51,12 @@ candidate ports (16802–16806) remove that proof. MBP1 replaces it with:`official / attested-non-official / unverified` identity tri-state shown inthe approval dialog.+Remote Motrix Server uses the same SPAKE2, reconnect, credential commit, AEAD,+and MDXP-inside-MBP1 ordering over WS or WSS. It deliberately omits NM tickets: a+Chromium Origin remains verifiable at the WebSocket boundary, while remote+Firefox is displayed as `unverified`. The pairing code is displayed only by an+authenticated Server operator UI and typed by the user into the Extension.+Roles: the **extension is party A** (initiator, uses point *M*), the **Motrixbridge server is party B** (responder, uses point *N*), exactly as prescribedby [RFC 9382] §3.1.@@ -65,6 +78,16 @@ presence in the path, traffic sizes and timing, and being the port theextension pins — is an intrinsic residual of loopback port squatting and isdocumented, not claimed closed.+For the remote Server profile, the network attacker additionally controls DNS,+routes, redirects, reverse-proxy inputs, and unauthenticated discovery. Public+PKI/WSS, when configured, authenticates the network authority and protects+connection metadata; MBP1 authenticates continuity of the paired Server+instance on both WS and WSS. Discovery remains an untrusted hint.+Operator-session compromise, a compromised browser, Server host compromise,+and a byte-identical clone of the complete Server data directory remain outside+the cryptographic guarantee. The first supported deployment is one logical+Server instance (or a sticky single backend), not active-active replication.+---## 2. Notation and canonical encoding@@ -131,8 +154,10 @@ constant-time with respect to the scalar (noble-curves satisfies this).## 4. Transport surfaces and ingress demultiplexing-The bridge server listens on loopback, on the first free port of the candidate-range **16802–16806** (falling back to an ephemeral port). Four surfaces are+The Desktop bridge listens on loopback, on the first free port of the candidate+range **16802–16806** (falling back to an ephemeral port). The remote Server+profile exposes the same four logical surfaces behind an explicit disabled-by-+default feature bundle and a public WS/WSS authority (§4.4). Four surfaces arerelevant to MBP1:| Surface | Method | Auth | Purpose |@@ -167,12 +192,15 @@ Unauthenticated, replayable, **a hint and never a trust decision**. Response```json{ "app": "motrix-bridge", "apiVersion": 1,"instanceId": "<persisted per-install UUID>", "appVersion": "2.0.0-beta.20",- "runtime": "electron",+ "runtime": "electron" | "server","extensionPairing": { "protocol": "mbp1", "versions": [1] },"applicationProtocols": { "mdxp": ["1.0"] } }```-`instanceId` is a routing hint used to pick which candidate port to try first.+For Desktop, `instanceId` is a routing hint used to pick which candidate port+to try first. For remote Server, it is a compatibility/identity hint only; the+configured authority already fixes the route. In both profiles the value is+unauthenticated until pair/reconnect proves it through the MBP1 transcript/MAC.The compatibility fields let an extension stop before pairing and explain anupgrade requirement, but remain unauthenticated hints: they MUST NOT select alegacy downgrade, grant trust, or replace post-authentication capability@@ -187,9 +215,15 @@ header makes the request non-simple, cross-origin web pages are blocked by thebrowser preflight (the server grants no CORS). Response:```json-{ "nonce": "<one-shot opaque ASCII string>", "ttlSeconds": 60 }+{ "nonce": "<22-char unpadded base64url>", "ttlSeconds": 60 }```+This exact two-key DTO is shared by local and remote MBP1 v1 clients; the+remote profile MUST NOT remove `ttlSeconds`, add identity fields, or otherwise+fork the response shape. `nonce` is the canonical unpadded base64url encoding+of exactly 16 random bytes (22 characters; unused tail bits are zero). Both+fields are unauthenticated short-lived hints.+Nonces are one-shot, expire after 60 seconds, are consumed only by `/pair`,and MUST NOT be persisted by any party. The server MUST cap outstanding nonces(default 32), apply a global issuance rate limit, and apply per-verified-origin@@ -200,8 +234,149 @@ quotas where an origin exists.While bound to loopback, every HTTP route and WebSocket upgrade MUST reject(403) any request whose `Host` is not exactly `127.0.0.1[:port]`,`localhost[:port]`, or `[::1][:port]`. This closes DNS rebinding. (The server-shell binding non-loopback keeps its existing token + reverse-proxy model and-is out of MBP1 scope.)+shell's CLI/agent bearer routes remain a separate audience and never authorize+Extension `/pair` or `/v1`. The remote Extension Host rules are §4.4.)++### 4.4 Remote Motrix Server profile++Remote Extension support MUST be opt-in and fail closed. The canonical+configuration inputs are:++```text+MOTRIX_REMOTE_EXTENSION_ENABLED=false+MOTRIX_REMOTE_EXTENSION_PUBLIC_URL=ws(s)://host[:port][/base-path]+MOTRIX_PUBLIC_URL=http(s)://operator-host[:port][/base-path]+MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP=false+```++When enabled, both public URLs are required. The WebSocket URL accepts only WS+or WSS. The operator URL accepts HTTPS by default. An HTTP operator URL is+accepted only when `MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP=true` supplies a second,+explicit opt-in; startup then warns that the operator token, pairing codes,+session cookies, and administrator traffic lack TLS protection. This exception+is for a trusted LAN only and is forbidden for Internet-facing or untrusted-LAN+deployments. Neither operator scheme is rewritten or selected as a fallback.+The parser MUST reject all other schemes, userinfo, query, fragment, raw Unicode+whitespace, ASCII controls, backslashes, percent-encoded path separators+(including layered encoding), unstable canonicalization, and overlong values.+Invalid input closes only the remote Extension surface; CLI/agent and Desktop+behavior remain independent. Diagnostics contain fixed codes and variable+names, never full URLs, paths, codes, credentials, or tokens.++The WS/WSS public URL's canonical pathname is the only route prefix. The Server+accepts exactly `${prefix}/discovery`, `${prefix}/nonce`, `${prefix}/pair`, and+`${prefix}/v1`, with no unprefixed alias. Discovery, nonce, and v1 accept no+query; pair accepts exactly one canonical `nonce=<base64url>` query. An old+`token` query therefore selects no remote route and is rejected before a+pre-authentication socket or credential lookup exists. The Server compares a+strictly parsed request Host's canonical hostname plus effective port to the+configured public authority, rejects duplicate/malformed Host, and ignores+arbitrary `X-Forwarded-Host`. Host validation is defense in depth, not an ACL:+the origin listener MUST remain on loopback/private bind or behind a firewall,+and only an explicitly configured trusted proxy may supply a source address.+Arbitrary `X-Forwarded-For` is ignored.++For WSS, TLS MAY terminate at a trusted reverse proxy and the browser-visible+certificate MUST be trusted and hostname-valid. The proxy preserves Host,+Origin, Upgrade, `Sec-WebSocket-Protocol`, and the exact base path. Explicit WS+is also a production configuration: MBP1 still encrypts application payloads,+but TLS does not protect server network identity or connection metadata. Clients+warn without blocking. Neither side automatically upgrades, downgrades, or+falls back between schemes.++Remote first pair is ticketless: `pairHello` omits `nmTicket` and+`ticketBindingKey`; there is no Native Messaging, candidate-port sweep, App+launch, or local degraded-state warning. Pairing/reconnect use unchanged MBP1+v1 frames. `/v1` has no credential query, old `?token=` is rejected by the+public raw-route gate, raw MDXP is rejected, and CLI/operator bearers cannot+enter either Extension route.++The pairing code is released only through an authenticated operator snapshot or+event channel. HTTP snapshot/mutation responses use `Cache-Control: no-store`;+cookie-authenticated operator WebSockets require an Origin exactly matching the+canonical `MOTRIX_PUBLIC_URL`, and mutation CSRF remains enforced. Codes do not+enter URL, log, persistent browser storage, clipboard, CLI output, or+notification text. The user reads the code and types it into the Extension.+Origin/CSRF, HttpOnly, SameSite, no-store, and login-rate controls remain active+in explicitly authorized HTTP mode, but they do not provide confidentiality or+prevent an on-path attacker from reading or altering operator traffic.++Nonce issuance, `/pair` pre-auth sockets, `/v1` pre-auth sockets, pending+prompts, and discovery/nonce request rates each have independent global hard+caps. Prompt dedup uses verified Origin but rotating forged Origins cannot evade+global caps. `settings.bridge.instanceId` is stable across restart;+`serverGeneration` rotates per process start and CLI `localToken` remains a+separate credential/audience.++All four routes are one atomic feature bundle. Until configuration, credential+store, prompt controller/operator delivery, handlers/capability producer,+bookkeeping, rate limits, and durable revoke are all present before listener+start, every route—including `/nonce`—MUST stay 404. Feature-off, historical+Server, wrong URL, and a proxy-generated 404 are intentionally indistinguishable+to an unauthenticated client; only a valid discovery document can prove a+version incompatibility.++### 4.5 Remote Server deployment profile (beta)++The first beta supports exactly one logical Motrix Server identity. Run one+Server process for one data directory and route every Extension request for an+authority to that same process. A reverse proxy may provide TLS termination,+but round-robin/active-active backends, cloned data directories, and automatic+failover to a different bridge identity are unsupported. The bridge data-dir+lock and Server-process ownership record intentionally make accidental second+writers fail closed; they are not a distributed lock.++A minimal origin configuration is:++```text+MOTRIX_MDXP_HOST=127.0.0.1+MOTRIX_MDXP_PORT=16801+MOTRIX_REMOTE_EXTENSION_ENABLED=true+MOTRIX_REMOTE_EXTENSION_PUBLIC_URL=wss://motrix.example/bridge+MOTRIX_PUBLIC_URL=https://motrix.example+```++After the MBP1 listener and all four remote routes are ready, the Server logs+the canonical `MOTRIX_REMOTE_EXTENSION_PUBLIC_URL` as+`extensionServerAddress`. This is the exact address the user pastes into the+Extension. The ordinary Server HTTP port (`PORT`, default 8080) is not the+Extension address unless a reverse proxy on that port forwards all four routes+to the bridge. The origin bridge port is `MOTRIX_MDXP_PORT` (default 16801), but+users should normally copy the logged public address rather than reconstructing+one from either listener port. Disabled or invalid remote configuration prints+no pairing-ready address.++The public reverse proxy maps `/bridge/discovery`, `/bridge/nonce`,+`/bridge/pair`, and `/bridge/v1` to `http://127.0.0.1:16801` without stripping+or rewriting `/bridge`. It MUST forward the original `Host`, `Origin`,+`Upgrade`, `Connection`, and `Sec-WebSocket-Protocol` values. Do not expose+port 16801 outside the host, do not set `MOTRIX_MDXP_HOST` to a public address,+and do not use `X-Forwarded-Host` or `X-Forwarded-For` as an authentication+signal. The proxy/firewall permits only the four exact paths and SHOULD add+edge request/connection limits in addition to Motrix's conservative global+limits. Because Motrix deliberately does not trust forwarded client addresses,+origin-side per-client limits collapse to the proxy peer; edge per-IP limits+are therefore required for an Internet-facing beta.++When WSS is configured, the TLS certificate MUST chain to a trust anchor accepted+by the target browser and cover the exact configured hostname. Self-signed+certificates, hostname mismatch, and expired certificates are unsupported;+explicit WS is supported but never selected as a fallback. Before+enabling the feature, verify that the operator UI is reachable over its+canonical HTTPS origin, that its authenticated event channel can display a+pairing request/code, and that the proxy preserves the WebSocket subprotocol.+If any required value is absent or invalid, keep+`MOTRIX_REMOTE_EXTENSION_ENABLED=false`; the four public routes remain closed.++Back up the bridge data directory only as part of a single-instance Server+backup. Restoring it to a replacement host preserves the Server identity and+existing Extension credentials, so the replacement MUST take over the same+DNS name and trusted TLS identity and the old process MUST be offline. Cloning+the backup into two live Servers is forbidden. To intentionally create a new+Server identity, start from a fresh bridge data directory and pair every+Extension again. Rollback to a historical token-era Server does not migrate+credentials: disable the remote feature, forget the pairing in the Extension,+upgrade Motrix, and perform a fresh MBP1 pair.---@@ -212,9 +387,9 @@ extension called is not the same as proving it is *official*:| State | Condition | UI ||---|---|---|-| `official` | The proven caller identity — the Chromium verified `Origin` host, or the `callerId` inside a valid NM attestation ticket (§9) — appears on the immutable allowlist `src/shared/config/native-messaging-extensions.json` | May show Motrix branding |-| `attested-non-official` | A valid ticket proves the exact caller ID, but that ID is not on the allowlist | Raw proven ID, no branding |-| `unverified` | No attestation: any Firefox `/pair` without a ticket (a `moz-extension://<UUID>` origin cannot be mapped to a Gecko ID), and candidate-sweep peers | Warning styling, raw claimed ID |+| `official` | The Chromium verified `Origin` host, or the `callerId` inside a valid NM attestation ticket (§9), appears on the immutable allowlist `src/shared/config/native-messaging-extensions.json` | May show Motrix branding |+| `attested-non-official` | A valid ticket proves a non-allowlisted caller, or a ticketless Chromium WebSocket Origin proves a non-allowlisted extension ID | Raw proven ID, no branding |+| `unverified` | Any Firefox `/pair` without a ticket (a `moz-extension://<UUID>` origin cannot be mapped to a Gecko ID), and local candidate-sweep peers without attestation | Warning styling, raw claimed ID |Rules:@@ -226,6 +401,9 @@ Rules:server MUST reject the pairing. On Firefox, the `moz-extension://` origincannot be checked against the claimed Gecko ID; without a ticket the stateis `unverified`.+- Ticketless Chromium is permitted in the remote profile, but Origin proof does+ not promote a user-added registry entry to `official`; only the immutable+ allowlist can do that. Ticketless remote Firefox always remains `unverified`.- The verified origin is bound to the session, the credential principal, therate-limit keys, and the PAKE transcript (§6.4). Native local processes canforge any `Origin` header; origin binding raises the bar only inside@@ -282,7 +460,7 @@ extension (A) Motrix (B)On receipt the server MUST, in order: validate the `?nonce=` (one-shot,unexpired) — an invalid nonce closes the socket before any further work;-validate the Host header and `Origin`; enforce the pending-pair dedup (keyed+validate the profile-specific Host rule (§4.3 or §4.4) and `Origin`; enforce the pending-pair dedup (keyedby verified origin) and the global pending cap and backoff (§7.3) **beforecreating any session state or dialog**; validate `nmTicket` if present (§9),requiring `nmTicket`'s `bindingPub` to equal `ticketBindingKey` and@@ -295,8 +473,8 @@ queue exactly one approval dialog.{ "type": "pairAccept", "protocolVersion": 1, "instanceId": "<UUID>" }```-Sent when the dialog is queued. The extension popup then prompts for the-code. `pairAccept` carries no approval semantics — the extension MUST NOT+Sent when the Desktop dialog or authenticated Server operator prompt is queued.+The Extension popup then prompts for the code. `pairAccept` carries no approval semantics — the extension MUST NOTtreat any server message as "the user approved"; only successful keyconfirmation proves that.@@ -573,7 +751,14 @@ Atomicity rules:credential after the delete. It then sends the authenticated revocationnotification where possible and closes the live WebSocket; the shortnotification-drain window admits no control-plane requests, and a previously- issued key cannot reconnect.+ issued key cannot reconnect. Before the durable credential deletion, Server+ deployments MUST persist a pending-revoke marker keyed by verified identity.+ Startup restores that identity's deny gate and retries deletion before any+ remote Extension listener opens. If deletion fails, no authenticated revoke+ notification is sent, live/pre-auth sessions remain closed, bookkeeping stays+ visible as “revocation incomplete,” and the gate remains closed across+ restart. If the marker itself cannot be persisted, all four remote Extension+ routes enter degraded/closed state rather than risk reviving the old key.- Credential principal: `{browser, verifiedOrigin, clientInstallationId}`. Asecond browser profile is a **new principal** and pairs as a newcredential; issuing or rotating one credential MUST NOT affect another.@@ -678,7 +863,8 @@ fields, a 16 KiB pre-authentication frame cap, and abort with`protocolViolation` on unknown types, out-of-order or duplicate messages,oversized frames, or schema-invalid JSON. The whole challenge–response MUSTcomplete within **10 s** of the upgrade or the server closes the socket.-After upgrade (Host and Origin checks as in §4.3/§5), the server speaks+After upgrade (profile-specific Host checks as in §4.3/§4.4 and Origin checks+as in §5), the server speaksfirst:```json@@ -958,7 +1144,8 @@ cookies, headers, or commands.| `rateLimited` | global backoff or attempt exhaustion | §7.3 || `codeMismatch` | key confirmation failed | carries `attemptsRemaining` || `expired` | nonce or code lifetime exceeded | |-| `aborted` | user dismissed the dialog | |+| `denied` | authenticated operator explicitly denied the prompt | terminal until an explicit retry |+| `aborted` | PairSession/controller shut down without an operator decision | retryable; never infer denial || `authFailed` | `/v1` challenge–response failed | uniform for unknown-ID and bad-MAC || `protocolViolation` | malformed/out-of-order frame, bad point encoding, oversize | immediate close || `pairingFailed` | internal failure (e.g. `w = 0`) | generic |@@ -1001,12 +1188,22 @@ different meaning to `4001`.## 12. Credential and pin lifecycle (extension side)-- `PinStore` is a versioned store keyed by `credentialId` holding+- Client credentials are scoped outside the MBP1 wire principal by a+ `BackendAuthority`: `local`, or `{endpointId, canonicalWsBase}`. That+ authority is a storage/lifecycle namespace only and MUST NOT be inserted into+ `A_id`, `B_id`, `TT`, or reconnect MAC input. A URL change creates a new+ authority scope; a display-name change does not.+- `PinStore` is local-only and keyed by `credentialId`, holding`{port, instanceId}`. A pin is committed **only after** amutually-authenticated session on that port — never from `/discovery`.- Pinned-port mismatch → full candidate sweep for the matching `instanceId`→ re-commit only post-auth; otherwise clear the pin and fall back to freshcode-entry pairing.+- Remote authorities perform no port sweep and store no pin. Their committed+ credential durably includes the `authenticatedInstanceId`; reconnect uses+ that retained identity rather than the discovery hint. If the same authority+ retains a different authenticated instance, first pair/rotation MUST fail+ with an explicit identity-change state until the user forgets the old scope.- `storage.local` credential entries carry `state: "provisional" |"committed"` and, for provisionals, the `unacked` / `commit-uncertain`sub-state (§6.7), plus an `activeCredentialId` pointer written **atomically@@ -1092,9 +1289,10 @@ inputs.## Appendix A — Security properties and acceptance criteria-A malicious loopback listener replaying a real `instanceId` must not obtain:-the pairing code, any credential, a completed MDXP initialize, or any-download submission. Specifically:+A malicious loopback listener, or a remote network endpoint serving forged+discovery and replaying a real `instanceId`, must not obtain: the pairing code,+any credential, a completed MDXP initialize, or any download submission.+Specifically:- **Terminating MITM** (own PAKE with each side) cannot produce two confirmedkeys without the code; a grinder test with adversarial key generation MUST@@ -1119,6 +1317,15 @@ download submission. Specifically:or server generation; small-order `bindingPub` forgeries MUST be rejected.- **AEAD usage bounds** — sessions close before 2^24 frames or 2^30 encryptedblocks per direction (§10).+- **Remote authority and transport** — production accepts canonical WS/WSS and+ preserves the configured scheme. Redirects cannot change authority, discovery+ cannot replace authenticated identity, and old query tokens/raw MDXP never+ enter a session (§4.4). WSS adds PKI network identity and metadata protection;+ MBP1 protects application payloads on both transports.+- **Atomic exposure and revoke** — dependency omission keeps all four remote+ routes at 404; revoke cuts authorization first, persists a restart-safe deny+ marker, deletes credentials durably before notifying, and never reopens on a+ failed delete (§4.4/§6.7).## Appendix B — Externally-verified browser facts@@ -1132,10 +1339,12 @@ build matrix per §14.3.| MV3 service-worker keepalive | From Chrome 116, WebSocket activity resets the 30 s service-worker idle timer; keepalive requires exchanging a message within each 30 s window | [Chrome developers: WebSockets in service workers](https://developer.chrome.com/docs/extensions/how-to/web-platform/websockets) || Extension minimums | `minimum_chrome_version: "120"`, Gecko `strict_min_version: "121.0"` | `motrix-extension/packages/ext/manifest.config.ts` |-Consequence of the Firefox rows: before probing loopback the extension MUST-check `permissions.contains({origins:["http://127.0.0.1/*"]})`, request within-a user gesture when missing, and show an explicit degraded state on refusal.-The acceptance matrix covers Firefox 121–126, 127+, and manual revocation.+The current Extension manifest uses required host access, so there is no+actionable optional-host-permission reauthorization flow and UI MUST NOT offer+one. If a future release narrows this to optional origins, it must check and+request the exact local/remote authority only inside a user gesture, preserve+credentials on refusal/revocation, and add Firefox 121–126, 127+, and manual+revocation coverage before making that profile supported.## Appendix C — Review logdiff --git a/docs/docker-server.md b/docs/docker-server.mdindex 7c69e236..bd922683 100644--- a/docs/docker-server.md+++ b/docs/docker-server.md@@ -369,17 +369,30 @@ The command intentionally has no approve-latest, approve-all, remote endpoint,or token argument. Web approval remains available and is the normal path; thisis an optional local operator path for headless or recovery deployments.-Plain HTTP can be appropriate for a trusted LAN; Motrix does not force HTTPS.-For Internet or untrusted-LAN access, TLS termination at a trusted reverse-proxy **and** firewall protection for the origin ports are required. Proxy port+Plain HTTP can be appropriate for the ordinary Web UI on a trusted LAN. Remote+browser-Extension pairing is stricter because the operator UI carries a+long-lived operator token and pairing codes. To enable it with direct LAN HTTP,+set all four values explicitly:++```bash+export MOTRIX_REMOTE_EXTENSION_ENABLED=true+export MOTRIX_REMOTE_EXTENSION_PUBLIC_URL='ws://nas.example.lan:16801'+export MOTRIX_PUBLIC_URL='http://nas.example.lan:8080'+export MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP=true+```++Motrix then keeps Origin/CSRF and cookie protections active, emits a startup+warning, and prints the exact Extension Server address. Do not enable this HTTP+exception on the Internet or an untrusted LAN: the operator token, pairing+codes, session cookies, and administrator traffic remain visible to an on-path+attacker. For those networks, TLS termination at a trusted reverse proxy+**and** firewall protection for the origin ports are required. Proxy port8080 as the Web origin and preserve cookies, authorization headers, andstreaming responses. MDXP is a separate HTTP/SSE service: remote clients need aTLS-enabled proxy/upstream to port 16801 as well. Forwarding only port 8080 doesnot publish MDXP, and forwarding only 16801 does not serve the approval UI.These protections must not be implemented by disabling pairing; remote-CLI/agent pairing remains an operator-approved workflow. First-time browser-extension pairing is a desktop/native-messaging flow and is not offered by the-headless server.+CLI/agent and browser-Extension pairing remain operator-approved workflows.## Download paths and plugins@@ -522,6 +535,9 @@ detection.| `MOTRIX_MDXP_HOST` | runtime: `127.0.0.1`; Compose: `0.0.0.0` | MDXP listener inside the container, not the host publish address || `MOTRIX_MDXP_PORT` | `16801` | MDXP listen port; `0` disables a stable published port || `MOTRIX_PUBLIC_URL` | unset | Explicit externally reachable Web approval URL, not the MDXP URL; never defaults to localhost |+| `MOTRIX_REMOTE_EXTENSION_ENABLED` | `false` | Opt in to the four remote browser-Extension MBP1 routes |+| `MOTRIX_REMOTE_EXTENSION_PUBLIC_URL` | unset | Exact WS/WSS Server address entered in Motrix Extension |+| `MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP` | `false` | Explicitly accept exposed operator credentials and traffic on a trusted-LAN HTTP deployment; never use on an untrusted network || `MOTRIX_FFMPEG_PATH` | auto-detect | Optional absolute FFmpeg path || `MOTRIX_HOST_LANGUAGE` | system setting | Server/plugin locale override || `LOG_LEVEL` | `info` | Pino log level written to container stdout |diff --git a/docs/docker-server.zh-CN.md b/docs/docker-server.zh-CN.mdindex 542f7fd9..3c45cd6e 100644--- a/docs/docker-server.zh-CN.md+++ b/docs/docker-server.zh-CN.md@@ -328,13 +328,25 @@ docker compose exec server motrix-admin pairing deny ABCD-EFGHapprove-latest、approve-all、远程 endpoint 或 token 参数。Web 审批仍是正常路径;这个入口只用于 headless 或恢复场景下的本机 operator 操作。-在可信 LAN 中可以使用明文 HTTP,Motrix 不会强制 HTTPS。通过公网或不可信 LAN 访问时,-必须同时使用可信反向代理终止 TLS,并用防火墙保护 origin 端口。把 8080 作为 Web+普通 Web 界面在可信 LAN 中可以使用明文 HTTP。远程浏览器扩展配对要求更严格,因为+operator 页面会传输长期 operator token 和配对码。可信局域网若要直接使用 HTTP,必须+同时显式设置:++```bash+export MOTRIX_REMOTE_EXTENSION_ENABLED=true+export MOTRIX_REMOTE_EXTENSION_PUBLIC_URL='ws://nas.example.lan:16801'+export MOTRIX_PUBLIC_URL='http://nas.example.lan:8080'+export MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP=true+```++Motrix 会继续启用 Origin/CSRF 和 Cookie 防护,打印高风险警告,并输出扩展应填写的准确+Server 地址。公网或不可信 LAN 绝不能开启这个 HTTP 例外:路径上的攻击者仍可能读取+operator token、配对码、session Cookie 和管理操作。此类网络必须同时使用可信反向代理+终止 TLS,并用防火墙保护 origin 端口。把 8080 作为 Weborigin,并保留 cookie、Authorization header 和流式响应。MDXP 是独立的 HTTP/SSE 服务:远程客户端还需要一个启用 TLS、指向 16801 的代理/upstream。只转发 8080 不会发布MDXP,只转发 16801 也不会提供审批界面。不应通过禁用配对来实现这些保护;远程-CLI/agent 配对仍然是一项需要 operator 审批的正常流程。浏览器扩展的首次配对是桌面应用/-native messaging flow,headless server 不提供该流程。+CLI/agent 与浏览器扩展配对都仍然需要 operator 审批。## 下载路径与插件@@ -467,6 +479,9 @@ secret-store 状态和 FFmpeg 探测结果。| `MOTRIX_MDXP_HOST` | runtime:`127.0.0.1`;Compose:`0.0.0.0` | 容器内 MDXP listener,不是宿主发布地址 || `MOTRIX_MDXP_PORT` | `16801` | MDXP 监听端口;`0` 表示不使用固定发布端口 || `MOTRIX_PUBLIC_URL` | 未设置 | 显式设置的外部可访问 Web 审批 URL,不是 MDXP URL;不会默认为 localhost |+| `MOTRIX_REMOTE_EXTENSION_ENABLED` | `false` | 显式开启浏览器扩展使用的四条远程 MBP1 路由 |+| `MOTRIX_REMOTE_EXTENSION_PUBLIC_URL` | 未设置 | Motrix Extension 中应填写的准确 WS/WSS Server 地址 |+| `MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP` | `false` | 在可信局域网显式接受 operator 凭据和管理流量暴露风险;不可信网络绝不能开启 || `MOTRIX_FFMPEG_PATH` | 自动探测 | 可选的 FFmpeg 绝对路径 || `MOTRIX_HOST_LANGUAGE` | 系统设置 | Server/插件语言覆盖值 || `LOG_LEVEL` | `info` | 输出到容器 stdout 的 Pino 日志级别 |diff --git a/e2e/bridge/README.md b/e2e/bridge/README.mdindex 734f1eb7..305a54cf 100644--- a/e2e/bridge/README.md+++ b/e2e/bridge/README.md@@ -94,6 +94,120 @@ node e2e/bridge/server-leg.mjsExit `0` = all checks passed, `1` = a check failed, `2` = the server build ismissing (rebuild the worktree).+---++## Remote browser Extension leg (Chromium + Firefox)++This gate starts the real Server MBP1 runtime behind a local HTTPS/WSS reverse+proxy and drives the production Extension builds in both browsers. It covers+fresh pair, authority-scoped consent, sensitive header/Cookie stripping,+browser restart reconnect, Server restart reconnect, durable revoke, and+re-pair through both a `/bridge` reverse-proxy prefix and the proxy root. A+separate Chromium case keeps two independent Servers paired in one persistent+profile, proves consent does not leak between them, and verifies submissions+follow the selected authority. The Firefox assertion also requires the+ticketless remote identity to remain `unverified`.++Build both Extension variants in the Extension checkout, then run from Motrix:++```bash+pnpm --filter @motrix/extension build:chromium+pnpm --filter @motrix/extension build:firefox++MOTRIX_EXTENSION_BUILD=/absolute/path/to/motrix-extension/packages/ext/dist/chromium \+MOTRIX_FIREFOX_EXTENSION_BUILD=/absolute/path/to/motrix-extension/packages/ext/dist/firefox \+pnpm test:e2e:remote-extension+```++Before Playwright starts, the command verifies+`remote-extension-threat-evidence.json`: every T01–T29 threat must retain at+least one mapped test file and title across the two repositories. The Extension+checkout is inferred from `MOTRIX_EXTENSION_BUILD`; set+`MOTRIX_EXTENSION_REPO` explicitly only when the build lives outside its+checkout. A removed/renamed test, missing threat, unsafe path, or symlinked+evidence file fails the gate.++Optional executable overrides are `MOTRIX_CHROMIUM_EXECUTABLE` and+`MOTRIX_FIREFOX_EXECUTABLE`. The Firefox runner uses WebDriver BiDi's standard+temporary-extension install command. Browser certificate bypasses are confined+to this local test profile; the separate WSS integration suite proves trusted+CA success and unknown-CA, expired, and wrong-host rejection without bypasses.+Use Playwright's matching Chrome-for-Testing/Chromium build for Chromium. Some+stable Google Chrome releases ignore automated unpacked-extension flags and+will time out waiting for the Extension service worker; an explicit executable+override must still point to a build that supports that test mode.++### Pinning the compatible repository revisions++The browser harness is a cross-repository contract. Do not record the current+working-tree `HEAD` values before the implementation changes are committed.+Create one implementation commit in each repository first, then copy+`remote-extension-compatibility.example.json` to+`remote-extension-compatibility.json` and replace both placeholders with those+full 40-character lowercase commit SHAs. Verify the resulting pin from Motrix:++```bash+pnpm check:remote-extension-compatibility \+ --manifest e2e/bridge/remote-extension-compatibility.json \+ --motrix-repo . \+ --extension-repo /absolute/path/to/motrix-extension+```++The verifier rejects placeholders, short or uppercase SHAs, protocol drift,+fewer than five browser cases, a commit from the wrong repository, and any pin+that is not an ancestor of the corresponding checkout's `HEAD`. Commit the+verified manifest in a later Motrix commit; this avoids a self-referential+Motrix SHA and makes the exact implementation pair reviewable.++### Beta soak++The soak runner repeats the same threat-gated five-case suite; one failing+repetition fails the command. Its default is 20 repetitions / 100 browser+cases, bounded to 100 repetitions so a bad environment cannot accidentally+create an unbounded job:++```bash+MOTRIX_CHROMIUM_EXECUTABLE=/path/to/chrome-for-testing \+MOTRIX_EXTENSION_BUILD=/absolute/path/to/motrix-extension/packages/ext/dist/chromium \+MOTRIX_FIREFOX_EXTENSION_BUILD=/absolute/path/to/motrix-extension/packages/ext/dist/firefox \+MOTRIX_REMOTE_EXTENSION_SOAK_REPEATS=20 \+pnpm test:e2e:remote-extension:soak+```++Archive the full output together with OS, browser versions, both implementation+SHAs, repeat count, start/end time, and any proxy/network fault injection. A+single ordinary E2E pass is regression evidence, not completion of the beta+soak gate.++For the release gate, use the evidence-producing wrapper after the compatible+SHA manifest has been committed:++```bash+MOTRIX_CHROMIUM_EXECUTABLE=/path/to/chrome-for-testing \+MOTRIX_FIREFOX_EXECUTABLE=/path/to/firefox \+MOTRIX_EXTENSION_REPO=/absolute/path/to/motrix-extension \+MOTRIX_EXTENSION_BUILD=/absolute/path/to/motrix-extension/packages/ext/dist/chromium \+MOTRIX_FIREFOX_EXTENSION_BUILD=/absolute/path/to/motrix-extension/packages/ext/dist/firefox \+MOTRIX_REMOTE_EXTENSION_SOAK_EVIDENCE_DIR=/absolute/archive/remote-extension-soak \+MOTRIX_REMOTE_EXTENSION_SOAK_FAULTS=none \+pnpm test:e2e:remote-extension:release-soak+```++Release mode requires exactly 20 repetitions, clean repositories, Extension+`HEAD` equal to its pin, and no Motrix changes after its implementation pin+except the compatibility-manifest commit. After that source preflight it+rebuilds both Extension variants from the pinned checkout, rejects build paths+outside their expected repository directories or symbolic links, and hashes+the fresh output. It records explicit browser versions and OS details, and+writes `evidence.json` plus the full Playwright `playwright-report.json`. The+report must parse to exactly 100 passed browser cases with no top-level or case+errors. A failed browser run is archived as failed; a zero exit with a missing+or invalid JSON report is archived as incomplete and still fails the gate. The+evidence directory must not already exist, so a later run cannot overwrite an+earlier record.++## Server leg maintenance+### Env overrides (all optional)| Var | Default | Meaning |@@ -130,6 +244,7 @@ git worktree remove --force ../motrix-turbo-srvThe tests drive the *real* approval surface: `bridge:resolvePair` IPC onElectron, and the operator-gated `POST /rpc/command/bridge:resolvePair` on theserver.-- The other specs here — `pair-and-submit`, `receiver-direct`, `revoke` — are- `test.skip` stubs for the **browser-extension WebSocket** pairing path- (deferred), which is distinct from this CLI **HTTP** path.+- `remote-extension-wss.spec.ts` and+ `remote-extension-firefox-wss.spec.ts` are the active browser-extension WSS+ lifecycle gates. The older `pair-and-submit`, `receiver-direct`, and `revoke`+ files remain narrow placeholder scenarios and are not used as coverage proof.diff --git a/e2e/bridge/README.zh-CN.md b/e2e/bridge/README.zh-CN.mdindex 3a2f96af..a87bde97 100644--- a/e2e/bridge/README.zh-CN.md+++ b/e2e/bridge/README.zh-CN.md@@ -89,6 +89,101 @@ node e2e/bridge/server-leg.mjs退出码:`0` = 全部检查通过,`1` = 某项检查失败,`2` = server build 缺失(需要重新构建 worktree)。+---++## 远程浏览器 Extension 链路(Chromium + Firefox)++该门禁会把真实 Server MBP1 runtime 放在本地 HTTPS/WSS 反向代理之后,并在两个+浏览器中驱动生产 Extension 构建。测试分别经过 `/bridge` 代理前缀和代理根路径,+覆盖 fresh pair、按 authority 隔离的 consent、敏感 header/Cookie 剥离、浏览器重启+重连、Server 重启重连、durable revoke 和 re-pair。独立 Chromium 场景还会在同一+持久 profile 中保留两个 Server 的配对,证明 consent 不会跨 Server 泄漏,且提交始终+跟随当前选中的 authority。Firefox 还必须断言无 NM ticket 的远程身份保持为+`unverified`。++先在 Extension checkout 构建两个产物,再从 Motrix 运行:++```bash+pnpm --filter @motrix/extension build:chromium+pnpm --filter @motrix/extension build:firefox++MOTRIX_EXTENSION_BUILD=/absolute/path/to/motrix-extension/packages/ext/dist/chromium \+MOTRIX_FIREFOX_EXTENSION_BUILD=/absolute/path/to/motrix-extension/packages/ext/dist/firefox \+pnpm test:e2e:remote-extension+```++Playwright 启动前,该命令会先验证 `remote-extension-threat-evidence.json`:+T01–T29 每项威胁都必须继续绑定至少一个双仓测试文件和测试标题。Extension checkout+默认从 `MOTRIX_EXTENSION_BUILD` 推导;只有构建产物不在 checkout 内时才需要显式设置+`MOTRIX_EXTENSION_REPO`。删除或重命名测试、缺少威胁 ID、不安全路径或符号链接证据都会+使门禁失败。++可用 `MOTRIX_CHROMIUM_EXECUTABLE` 与 `MOTRIX_FIREFOX_EXECUTABLE` 覆盖浏览器路径。+Firefox runner 使用 WebDriver BiDi 标准临时扩展安装命令。证书绕过仅存在于本地+测试 profile;独立 WSS integration suite 会在不绕过验证的情况下证明受信 CA+成功,以及 unknown CA、过期证书和 hostname mismatch 必须失败。+Chromium 应使用与 Playwright 匹配的 Chrome-for-Testing/Chromium 构建。部分正式版+Google Chrome 会忽略自动加载 unpacked Extension 的参数,最终超时等待 service worker;+即便显式设置可执行文件,也必须指向支持该测试模式的浏览器构建。++### 固定双仓兼容版本++浏览器 harness 是跨仓协议契约。两端实现改动提交之前,不得把当前 working tree 的+旧 `HEAD` 写成兼容证据。先分别创建 Extension 与 Motrix 实现提交,再把+`remote-extension-compatibility.example.json` 复制为+`remote-extension-compatibility.json`,并将两个占位符替换为对应实现提交的完整+40 位小写 SHA。然后在 Motrix 仓库执行:++```bash+pnpm check:remote-extension-compatibility \+ --manifest e2e/bridge/remote-extension-compatibility.json \+ --motrix-repo . \+ --extension-repo /absolute/path/to/motrix-extension+```++验证器会拒绝占位符、短 SHA、大写 SHA、协议漂移、少于五个浏览器场景、来自错误仓库+的提交,以及不是对应 checkout 当前 `HEAD` 祖先的提交。验证通过后,用一个更晚的+Motrix 提交记录该清单;这样既避免 Motrix SHA 自引用,也能让审阅者精确复现兼容组合。++### Beta soak++Soak runner 会重复执行同一套带威胁前置门禁的五场景测试;任意一次失败都会令命令失败。+默认执行 20 轮、共 100 个浏览器场景,并限制最多 100 轮,避免环境配置错误产生无界任务:++```bash+MOTRIX_CHROMIUM_EXECUTABLE=/path/to/chrome-for-testing \+MOTRIX_EXTENSION_BUILD=/absolute/path/to/motrix-extension/packages/ext/dist/chromium \+MOTRIX_FIREFOX_EXTENSION_BUILD=/absolute/path/to/motrix-extension/packages/ext/dist/firefox \+MOTRIX_REMOTE_EXTENSION_SOAK_REPEATS=20 \+pnpm test:e2e:remote-extension:soak+```++必须归档完整输出,以及 OS、浏览器版本、两端实现 SHA、轮数、起止时间和所有代理/网络+故障注入记录。一次普通 E2E 全绿只是回归证据,不能代替 beta soak 门禁。++固定兼容 SHA 清单提交后,发布门禁必须改用自动生成证据的包装命令:++```bash+MOTRIX_CHROMIUM_EXECUTABLE=/path/to/chrome-for-testing \+MOTRIX_FIREFOX_EXECUTABLE=/path/to/firefox \+MOTRIX_EXTENSION_REPO=/absolute/path/to/motrix-extension \+MOTRIX_EXTENSION_BUILD=/absolute/path/to/motrix-extension/packages/ext/dist/chromium \+MOTRIX_FIREFOX_EXTENSION_BUILD=/absolute/path/to/motrix-extension/packages/ext/dist/firefox \+MOTRIX_REMOTE_EXTENSION_SOAK_EVIDENCE_DIR=/absolute/archive/remote-extension-soak \+MOTRIX_REMOTE_EXTENSION_SOAK_FAULTS=none \+pnpm test:e2e:remote-extension:release-soak+```++发布模式强制恰好 20 轮、两个仓库均干净、Extension `HEAD` 与固定 SHA 完全一致,且+Motrix 实现 SHA 之后只能新增兼容清单。源码预检通过后,它会从固定 Extension checkout+重新构建两个浏览器版本,拒绝仓库外或符号链接构建目录,并计算新产物哈希。它会记录显式+浏览器版本与 OS 信息,生成 `evidence.json` 和完整的 Playwright+`playwright-report.json`;报告必须能解析出恰好 100 个通过场景,且不得包含顶层或场景+错误。浏览器失败会归档为 failed;即使进程返回 0,只要 JSON 报告缺失或无效也会归档为+incomplete 并使门禁失败。证据目录必须是新目录,后续运行不能覆盖先前记录。++## Server 链路维护+### 环境变量覆盖(全部可选)| 变量 | 默认值 | 含义 |@@ -124,6 +219,7 @@ git worktree remove --force ../motrix-turbo-srv- **Pairing approval 是刻意保留的人工步骤**(没有 headless auto-approve)。测试驱动的是*真实* approval surface:Electron 上的 `bridge:resolvePair` IPC,以及 Server 上由 operator gate 保护的 `POST /rpc/command/bridge:resolvePair`。-- 这里的其他 specs,包括 `pair-and-submit`、`receiver-direct`、`revoke`,都是- **browser-extension WebSocket** pairing path 的 `test.skip` stub(暂缓实现),- 与当前 CLI **HTTP** path 是两条不同路径。+- `remote-extension-wss.spec.ts` 与+ `remote-extension-firefox-wss.spec.ts` 是当前启用的 browser-extension WSS+ 生命周期门禁。旧的 `pair-and-submit`、`receiver-direct`、`revoke` 仍是窄范围+ placeholder,不能作为覆盖证据。diff --git a/e2e/bridge/remote-extension-compatibility.example.json b/e2e/bridge/remote-extension-compatibility.example.jsonnew file mode 100644index 00000000..8d003859--- /dev/null+++ b/e2e/bridge/remote-extension-compatibility.example.json@@ -0,0 +1,16 @@+{+ "schemaVersion": 1,+ "protocol": "MDXP-over-MBP1",+ "extension": {+ "repository": "motrix-extension",+ "commit": "REPLACE_WITH_EXTENSION_IMPLEMENTATION_COMMIT"+ },+ "motrix": {+ "repository": "motrix-app",+ "commit": "REPLACE_WITH_MOTRIX_IMPLEMENTATION_COMMIT"+ },+ "e2e": {+ "browserCases": 5,+ "command": "pnpm test:e2e:remote-extension"+ }+}diff --git a/e2e/bridge/remote-extension-compatibility.json b/e2e/bridge/remote-extension-compatibility.jsonnew file mode 100644index 00000000..6a447fdd--- /dev/null+++ b/e2e/bridge/remote-extension-compatibility.json@@ -0,0 +1,16 @@+{+ "schemaVersion": 1,+ "protocol": "MDXP-over-MBP1",+ "extension": {+ "repository": "motrix-extension",+ "commit": "9247116ef3a8cf53b819fe6a10041fb287a75bd3"+ },+ "motrix": {+ "repository": "motrix-app",+ "commit": "45fd67e35c27396ae1fb091970852880d8cc9102"+ },+ "e2e": {+ "browserCases": 5,+ "command": "pnpm test:e2e:remote-extension"+ }+}diff --git a/e2e/bridge/remote-extension-firefox-wss.spec.ts b/e2e/bridge/remote-extension-firefox-wss.spec.tsnew file mode 100644index 00000000..2cd894e6--- /dev/null+++ b/e2e/bridge/remote-extension-firefox-wss.spec.ts@@ -0,0 +1,475 @@+import { type ChildProcess, spawn } from 'node:child_process'+import { existsSync } from 'node:fs'+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import type { DownloadSubmitParams } from '@motrix/mdxp'+import { expect, test } from '@playwright/test'+import WebSocket from 'ws'+import type { ServerBridgeRuntime } from '../../src/server/bridge/bootstrap'+import { getFreePort } from '../helpers/free-port'+import {+ PUBLIC_HOST,+ pendingPairingCode,+ ROUTE_PREFIX,+ startRuntime,+ startTlsProxy,+} from './remote-extension-harness'++const FIREFOX_UUID = '4d239095-47b4-4e18-a828-03c827da0a62'++interface BidiResponse {+ type: 'success' | 'error'+ id: number+ result?: unknown+ error?: string+ message?: string+}++class BidiClient {+ private nextId = 1+ private readonly pending = new Map<+ number,+ { resolve: (value: unknown) => void; reject: (cause: Error) => void }+ >()++ private constructor(private readonly socket: WebSocket) {+ socket.on('message', (data) => this.receive(JSON.parse(String(data))))+ }++ static async connect(url: string): Promise<BidiClient> {+ const socket = new WebSocket(url)+ await new Promise<void>((resolve, reject) => {+ socket.once('open', resolve)+ socket.once('error', reject)+ })+ return new BidiClient(socket)+ }++ command(method: string, params: unknown): Promise<unknown> {+ const id = this.nextId+++ return new Promise((resolve, reject) => {+ this.pending.set(id, { resolve, reject })+ this.socket.send(JSON.stringify({ id, method, params }))+ })+ }++ async close(): Promise<void> {+ if (this.socket.readyState === WebSocket.CLOSED) return+ await new Promise<void>((resolve) => {+ this.socket.once('close', () => resolve())+ this.socket.close()+ })+ }++ private receive(message: BidiResponse): void {+ const waiter = this.pending.get(message.id)+ if (!waiter) return+ this.pending.delete(message.id)+ if (message.type === 'error') {+ waiter.reject(+ new Error(`${message.error ?? 'BiDi error'}: ${message.message ?? ''}`)+ )+ } else {+ waiter.resolve(message.result)+ }+ }+}++interface FirefoxSession {+ client: BidiClient+ context: string+ process: ChildProcess+}++async function connectBidi(url: string): Promise<BidiClient> {+ const deadline = Date.now() + 20_000+ let lastError: unknown = null+ while (Date.now() < deadline) {+ try {+ return await BidiClient.connect(url)+ } catch (cause) {+ lastError = cause+ await new Promise((resolve) => setTimeout(resolve, 100))+ }+ }+ throw new Error('Firefox BiDi did not start', { cause: lastError })+}++function remoteValue(value: unknown): unknown {+ if (!value || typeof value !== 'object') return value+ const remote = value as { type?: string; value?: unknown }+ if (remote.type === 'undefined' || remote.type === 'null') return null+ if (remote.type === 'object' && Array.isArray(remote.value)) {+ return Object.fromEntries(+ remote.value.map(([key, item]) => [key, remoteValue(item)])+ )+ }+ if (remote.type === 'array' && Array.isArray(remote.value)) {+ return remote.value.map(remoteValue)+ }+ return remote.value+}++async function launchFirefox(input: {+ executable: string+ extensionBuild: string+ profileDir: string+}): Promise<FirefoxSession> {+ const port = await getFreePort()+ await writeFile(+ join(input.profileDir, 'user.js'),+ [+ `user_pref("extensions.webextensions.uuids", "{\\"[email protected]\\":\\"${FIREFOX_UUID}\\"}");`,+ `user_pref("network.dns.localDomains", "${PUBLIC_HOST}");`,+ 'user_pref("network.dns.forceResolve", "127.0.0.1");',+ 'user_pref("intl.locale.requested", "en-US");',+ ].join('\n')+ )+ const firefox = spawn(+ input.executable,+ [+ '--headless',+ '--no-remote',+ '--profile',+ input.profileDir,+ '--remote-debugging-port',+ String(port),+ '--remote-allow-system-access',+ ],+ { stdio: ['ignore', 'pipe', 'pipe'] }+ )+ const client = await connectBidi(`ws://127.0.0.1:${port}/session`)+ await client.command('session.new', {+ capabilities: {+ alwaysMatch: { browserName: 'firefox', acceptInsecureCerts: true },+ },+ })+ await client.command('webExtension.install', {+ extensionData: { type: 'path', path: input.extensionBuild },+ })+ const tree = (await client.command('browsingContext.getTree', {})) as {+ contexts: Array<{ context: string }>+ }+ const context = tree.contexts[0]?.context+ if (!context) throw new Error('Firefox did not expose a browsing context')+ await client.command('browsingContext.navigate', {+ context,+ url: `moz-extension://${FIREFOX_UUID}/options.html`,+ wait: 'complete',+ })+ return { client, context, process: firefox }+}++async function stopFirefox(session: FirefoxSession): Promise<void> {+ await session.client.command('session.end', {}).catch(() => {})+ await session.client.close()+ if (session.process.exitCode === null) session.process.kill('SIGTERM')+ await new Promise<void>((resolve) => {+ if (session.process.exitCode !== null) return resolve()+ session.process.once('exit', () => resolve())+ })+}++async function evaluate(+ session: FirefoxSession,+ expression: string+): Promise<unknown> {+ const response = (await session.client.command('script.evaluate', {+ expression,+ target: { context: session.context },+ awaitPromise: true,+ resultOwnership: 'none',+ })) as { type: string; result?: unknown; exceptionDetails?: unknown }+ if (response.type !== 'success') {+ throw new Error(`Firefox script failed: ${JSON.stringify(response)}`)+ }+ return remoteValue(response.result)+}++async function clickText(+ session: FirefoxSession,+ text: string,+ selector = 'button'+): Promise<void> {+ await expect+ .poll(() =>+ evaluate(+ session,+ `(() => { const el = [...document.querySelectorAll(${JSON.stringify(+ selector+ )})].find((node) => node.getAttribute('aria-label') === ${JSON.stringify(+ text+ )} || node.textContent?.trim() === ${JSON.stringify(+ text+ )}); if (!(el instanceof HTMLElement)) return false; if (('disabled' in el && Boolean(el.disabled)) || el.getAttribute('aria-disabled') === 'true') return false; el.click(); return true })()`+ )+ )+ .toBe(true)+}++async function fillLabel(+ session: FirefoxSession,+ labelText: string,+ value: string+): Promise<void> {+ await expect+ .poll(() =>+ evaluate(+ session,+ `(() => { const label = [...document.querySelectorAll('label')].find((node) => node.textContent?.trim() === ${JSON.stringify(+ labelText+ )}); const input = label?.control ?? document.getElementById(label?.htmlFor ?? ''); if (!(input instanceof HTMLInputElement)) return false; const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set; setter?.call(input, ${JSON.stringify(+ value+ )}); input.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText', data: ${JSON.stringify(+ value+ )} })); input.dispatchEvent(new Event('change', { bubbles: true })); return true })()`+ )+ )+ .toBe(true)+}++async function bodyIncludes(+ session: FirefoxSession,+ text: string+): Promise<boolean> {+ return Boolean(+ await evaluate(+ session,+ `document.body.innerText.includes(${JSON.stringify(text)})`+ )+ )+}++async function openIntegration(session: FirefoxSession): Promise<void> {+ await expect.poll(() => bodyIncludes(session, 'Integration')).toBe(true)+ await clickText(session, 'Integration', '[role="tab"]')+ await expect+ .poll(() =>+ evaluate(+ session,+ `document.querySelector('[aria-label="Available Motrix backends"]') !== null`+ )+ )+ .toBe(true)+}++async function pair(+ session: FirefoxSession,+ runtime: ServerBridgeRuntime+): Promise<void> {+ // A previous prompt projection must have reached its terminal transition+ // before a new click. Otherwise observing "some pending code" can mistake+ // stale Server state for this attempt and race the same-Origin busy gate.+ await expect+ .poll(() => pendingPairingCode(runtime), { timeout: 10_000 })+ .toBeNull()+ await clickText(session, 'Pair')+ let ready:+ | {+ code: string+ state: unknown+ hasInput: boolean+ body: unknown+ }+ | undefined+ try {+ await expect+ .poll(+ async () => {+ const code = await pendingPairingCode(runtime)+ const ui = (await evaluate(+ session,+ `(async () => { const state = await browser.runtime.sendMessage({kind:'bg.getState'}); const label = [...document.querySelectorAll('label')].find((node) => node.textContent?.trim() === 'Pairing code'); const input = label?.control ?? document.getElementById(label?.htmlFor ?? ''); return {state,hasInput:input instanceof HTMLInputElement,body:document.body.innerText} })()`+ )) as { state: unknown; hasInput: boolean; body: unknown }+ ready = code === null ? undefined : { code, ...ui }+ return {+ hasCode: code !== null,+ state: (ui.state as { state?: unknown } | null)?.state,+ hasInput: ui.hasInput,+ }+ },+ { timeout: 15_000 }+ )+ .toEqual({+ hasCode: true,+ state: 'awaiting-code',+ hasInput: true,+ })+ } catch {+ throw new Error(+ `Firefox pairing did not synchronize Server/background/UI: ${JSON.stringify(ready)}`+ )+ }+ if (ready === undefined) throw new Error('Firefox pairing state missing')+ await fillLabel(session, 'Pairing code', ready.code.replace('-', ''))+ await clickText(session, 'Pair', '[role="dialog"] button')+ await expect.poll(() => bodyIncludes(session, 'Pairing ready')).toBe(true)+ await expect.poll(() => bodyIncludes(session, 'Connected')).toBe(true)+}++async function submit(session: FirefoxSession): Promise<unknown> {+ return evaluate(+ session,+ `(async () => browser.runtime.sendMessage({kind:'bg.submitDownload',payload:{source:{pageUrl:'https://example.com/watch',pageTitle:'Remote Firefox E2E',detectedAt:Date.now()},selection:{kind:'direct',primary:{url:'https://cdn.example.com/video.mp4',headers:{Authorization:'Bearer must-not-cross',Referer:'https://example.com/watch'},cookies:[{name:'session',value:'must-not-cross',domain:'example.com'}],refererPolicy:'strict-origin-when-cross-origin'}},meta:{suggestedFilename:'video.mp4',qualityLabel:'source'}}}))()`+ )+}++for (const routePrefix of [ROUTE_PREFIX, ''])+ test(`real Firefox: unverified pair, consent, reconnect, revoke, and re-pair over WSS (${routePrefix || 'root path'})`, async () => {+ const extensionBuild = process.env.MOTRIX_FIREFOX_EXTENSION_BUILD+ const firefoxExecutable =+ process.env.MOTRIX_FIREFOX_EXECUTABLE ??+ '/Applications/Firefox.app/Contents/MacOS/firefox'+ if (!extensionBuild || !existsSync(join(extensionBuild, 'manifest.json'))) {+ throw new Error(+ 'MOTRIX_FIREFOX_EXTENSION_BUILD must point to the Firefox build'+ )+ }+ if (!existsSync(firefoxExecutable))+ throw new Error('Firefox executable missing')++ const fixtureRoot = join(process.cwd(), 'src/server/bridge/__fixtures__')+ const [cert, key] = await Promise.all([+ readFile(join(fixtureRoot, 'motrix.test-cert.pem'), 'utf8'),+ readFile(join(fixtureRoot, 'motrix.test-key.pem'), 'utf8'),+ ])+ const root = await mkdtemp(join(tmpdir(), 'motrix-firefox-remote-e2e-'))+ const serverDataDir = join(root, 'server')+ const profileDir = join(root, 'firefox-profile')+ await mkdir(profileDir, { recursive: true })+ const [bridgePort, proxyPort] = await Promise.all([+ getFreePort(),+ getFreePort(),+ ])+ const submissions: DownloadSubmitParams[] = []+ let runtime: ServerBridgeRuntime | null = null+ let browser: FirefoxSession | null = null+ let closeProxy: (() => Promise<void>) | null = null++ try {+ runtime = await startRuntime({+ dataDir: serverDataDir,+ bridgePort,+ proxyPort,+ submissions,+ publicHost: '127.0.0.1',+ routePrefix,+ })+ closeProxy = await startTlsProxy({+ listenPort: proxyPort,+ upstreamPort: bridgePort,+ key,+ cert,+ })+ browser = await launchFirefox({+ executable: firefoxExecutable,+ extensionBuild,+ profileDir,+ })+ await openIntegration(browser)+ await clickText(browser, 'Add server')+ await fillLabel(browser, 'Server name', 'Remote E2E')+ await fillLabel(+ browser,+ 'WebSocket URL',+ `wss://127.0.0.1:${proxyPort}${routePrefix}`+ )+ await clickText(browser, 'Save server')+ await clickText(browser, 'Use Remote E2E')+ const discovery = await evaluate(+ browser,+ `(async () => { try { const response = await fetch('https://127.0.0.1:${proxyPort}${routePrefix}/discovery', {cache:'no-store',credentials:'omit',redirect:'error'}); return {status:response.status,body:await response.json()} } catch (cause) { return {error:String(cause)} } })()`+ )+ expect(discovery).toMatchObject({ status: 200 })+ await pair(browser, runtime)++ expect(await submit(browser)).toMatchObject({+ error: expect.stringMatching(/data boundary consent is required/i),+ })+ await clickText(browser, 'Allow remote downloads')+ // A programmatic click only proves event dispatch. Wait for the UI to+ // render the policy returned by the background; that response now also+ // acknowledges completion of the required capability renegotiation.+ // Reloading before this point would test cancellation of an in-flight+ // click handler rather than MV3 persistence/recovery.+ await expect+ .poll(() =>+ evaluate(+ browser as FirefoxSession,+ `document.querySelector('[role="switch"][aria-label="Send request headers"]') !== null`+ )+ )+ .toBe(true)+ await browser.client.command('browsingContext.reload', {+ context: browser.context,+ wait: 'complete',+ })+ await openIntegration(browser)+ await expect+ .poll(() => bodyIncludes(browser as FirefoxSession, 'Connected'))+ .toBe(true)+ await expect+ .poll(() => submit(browser as FirefoxSession))+ .toEqual({ taskId: 'browser-task-1' })+ expect(submissions[0]?.selection.kind).toBe('direct')+ if (submissions[0]?.selection.kind !== 'direct')+ throw new Error('direct expected')+ expect(submissions[0].selection.primary.headers).toEqual({})+ expect(submissions[0].selection.primary.cookies).toEqual([])++ const paired = (await runtime.bridgeQueryHandlers[+ 'bridge:listPaired'+ ]()) as Array<{+ kind: string+ id: string+ browser?: 'chromium' | 'firefox'+ identityTrust?: string+ }>+ const firefoxPair = paired.find((item) => item.kind === 'extension')+ expect(firefoxPair).toMatchObject({+ browser: 'firefox',+ id: FIREFOX_UUID,+ identityTrust: 'unverified',+ })++ await stopFirefox(browser)+ browser = await launchFirefox({+ executable: firefoxExecutable,+ extensionBuild,+ profileDir,+ })+ await openIntegration(browser)+ await expect+ .poll(() => bodyIncludes(browser as FirefoxSession, 'Connected'))+ .toBe(true)+ await expect+ .poll(() => submit(browser as FirefoxSession))+ .toEqual({+ taskId: 'browser-task-2',+ })++ if (!firefoxPair?.browser) throw new Error('Firefox projection missing')+ await runtime.bridgeCommandHandlers['bridge:revokePair']({+ identity: {+ kind: 'extension',+ browser: firefoxPair.browser,+ extensionId: firefoxPair.id,+ },+ })+ await browser.client.command('browsingContext.reload', {+ context: browser.context,+ wait: 'complete',+ })+ await openIntegration(browser)+ await expect+ .poll(() => bodyIncludes(browser as FirefoxSession, 'Not paired'))+ .toBe(true)+ await pair(browser, runtime)+ } finally {+ if (browser) await stopFirefox(browser).catch(() => {})+ if (closeProxy) await closeProxy()+ if (runtime) await runtime.shutdown()+ await rm(root, { recursive: true, force: true })+ }+ })diff --git a/e2e/bridge/remote-extension-harness.ts b/e2e/bridge/remote-extension-harness.tsnew file mode 100644index 00000000..4ee3db33--- /dev/null+++ b/e2e/bridge/remote-extension-harness.ts@@ -0,0 +1,188 @@+import { request as httpRequest } from 'node:http'+import { createServer as createHttpsServer } from 'node:https'+import { connect as connectTcp } from 'node:net'+import type { BridgeEventBus } from '@core/bridge/bridge-event-bus'+import type { ReadHandlerDeps } from '@core/bridge/handlers/read-handlers'+import type { WriteHandlerDeps } from '@core/bridge/handlers/write-handlers'+import type { DownloadSubmitParams } from '@motrix/mdxp'+import { makeSessionKey } from '@shared/protocol/bridge'+import { EngineState } from '@shared/types/engine'+import {+ bootstrapBridgeForServer,+ type ServerBridgeRuntime,+ type ServerExtensionReceiver,+} from '../../src/server/bridge/bootstrap'+import { parseRemoteExtensionConfig } from '../../src/server/bridge/remote-extension-config'++export const PUBLIC_HOST = 'motrix.test'+export const ROUTE_PREFIX = '/bridge'++function readDeps(): ReadHandlerDeps {+ return {+ taskManager: { getAll: () => [], getById: () => undefined },+ statsAggregator: {+ getStats: () => ({+ totalDownloadSpeed: 0,+ totalUploadSpeed: 0,+ activeTasks: 0,+ waitingTasks: 0,+ stoppedTasks: 0,+ }),+ },+ supervisor: {+ getState: () => EngineState.Ready,+ getFeatureReport: () => null,+ },+ }+}++function writeDeps(): WriteHandlerDeps {+ return {+ taskManager: { getById: () => undefined },+ pauseTask: async () => {},+ resumeTask: async () => {},+ removeTask: async () => {},+ createTask: async () => ({ taskId: 'unused' }),+ parseTorrentFileCount: async () => 0,+ }+}++function createReceiver(+ submissions: DownloadSubmitParams[],+ bridgeBus: BridgeEventBus+): ServerExtensionReceiver {+ const progressTimers = new Set<ReturnType<typeof setTimeout>>()+ let stopped = false+ return {+ handle: async (params, context) => {+ submissions.push(structuredClone(params))+ const taskId = `browser-task-${submissions.length}`+ const identity = context.identity+ if (identity.kind !== 'extension') {+ throw new Error('remote Extension receiver got a non-Extension session')+ }+ const progressTimer = setTimeout(() => {+ progressTimers.delete(progressTimer)+ if (stopped) return+ bridgeBus.emitTaskProgress({+ sessionKey: makeSessionKey(identity.browser, identity.extensionId),+ params: {+ taskId,+ bytesDone: 512,+ bytesTotal: 1_024,+ speedBps: 256,+ etaSec: 2,+ phase: 'downloading',+ },+ })+ }, 25)+ progressTimers.add(progressTimer)+ progressTimer.unref()+ return { taskId }+ },+ cancel: async () => {},+ restoreInflight: async () => {},+ start: () => {+ stopped = false+ },+ stopAndDrain: async () => {+ stopped = true+ for (const timer of progressTimers) clearTimeout(timer)+ progressTimers.clear()+ },+ }+}++export async function startRuntime(input: {+ dataDir: string+ bridgePort: number+ proxyPort: number+ submissions: DownloadSubmitParams[]+ publicHost?: string+ routePrefix?: string+}): Promise<ServerBridgeRuntime> {+ const publicHost = input.publicHost ?? PUBLIC_HOST+ const routePrefix = input.routePrefix ?? ROUTE_PREFIX+ return bootstrapBridgeForServer({+ userDataDir: input.dataDir,+ host: '127.0.0.1',+ port: input.bridgePort,+ motrixVersion: '2.0.0-beta.remote-e2e',+ eventBus: { on: () => {}, off: () => {}, emit: () => {} },+ readHandlerDeps: readDeps(),+ writeHandlerDeps: writeDeps(),+ remoteExtensionConfig: parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: `wss://${publicHost}:${input.proxyPort}${routePrefix}`,+ MOTRIX_PUBLIC_URL: `https://${publicHost}:${input.proxyPort}`,+ }),+ createExtensionReceiver: ({ bridgeBus }) =>+ createReceiver(input.submissions, bridgeBus),+ })+}++export async function startTlsProxy(input: {+ listenPort: number+ upstreamPort: number+ key: string+ cert: string+}): Promise<() => Promise<void>> {+ const proxy = createHttpsServer({ key: input.key, cert: input.cert })+ proxy.on('request', (request, response) => {+ const upstream = httpRequest(+ {+ host: '127.0.0.1',+ port: input.upstreamPort,+ method: request.method,+ path: request.url,+ headers: request.headers,+ },+ (upstreamResponse) => {+ response.writeHead(+ upstreamResponse.statusCode ?? 502,+ upstreamResponse.headers+ )+ upstreamResponse.pipe(response)+ }+ )+ upstream.once('error', () => {+ if (!response.headersSent) response.writeHead(502)+ response.end()+ })+ request.pipe(upstream)+ })+ proxy.on('upgrade', (request, downstream, head) => {+ const upstream = connectTcp(input.upstreamPort, '127.0.0.1')+ upstream.once('connect', () => {+ upstream.write(+ `${request.method ?? 'GET'} ${request.url ?? '/'} HTTP/${request.httpVersion}\r\n`+ )+ for (let index = 0; index < request.rawHeaders.length; index += 2) {+ upstream.write(+ `${request.rawHeaders[index]}: ${request.rawHeaders[index + 1]}\r\n`+ )+ }+ upstream.write('\r\n')+ if (head.length > 0) upstream.write(head)+ downstream.pipe(upstream).pipe(downstream)+ })+ upstream.once('error', () => downstream.destroy())+ })+ await new Promise<void>((resolve, reject) => {+ proxy.once('error', reject)+ proxy.listen(input.listenPort, '127.0.0.1', () => resolve())+ })+ return () =>+ new Promise<void>((resolve, reject) => {+ proxy.close((error) => (error ? reject(error) : resolve()))+ })+}++export async function pendingPairingCode(+ runtime: ServerBridgeRuntime+): Promise<string | null> {+ const pending = (await runtime.bridgeQueryHandlers[+ 'bridge:listPendingPairRequests'+ ]()) as Array<{ kind: string; code?: string }>+ return pending.find((request) => request.kind === 'extension')?.code ?? null+}diff --git a/e2e/bridge/remote-extension-threat-evidence.json b/e2e/bridge/remote-extension-threat-evidence.jsonnew file mode 100644index 00000000..1f4f9a5a--- /dev/null+++ b/e2e/bridge/remote-extension-threat-evidence.json@@ -0,0 +1,355 @@+{+ "schemaVersion": 1,+ "threats": [+ {+ "id": "T01",+ "evidence": [+ {+ "repository": "extension",+ "path": "packages/ext/src/background/mbp1/__tests__/bridge-route.test.ts",+ "testName": "never emits a legacy token query parameter"+ }+ ]+ },+ {+ "id": "T02",+ "evidence": [+ {+ "repository": "extension",+ "path": "packages/ext/src/background/mbp1/__tests__/bridge-route.test.ts",+ "testName": "rejects a structurally manufactured authority"+ },+ {+ "repository": "motrix",+ "path": "src/server/bridge/remote-extension-wss.integration.test.ts",+ "testName": "rejects an expired certificate even when that certificate is explicitly trusted"+ }+ ]+ },+ {+ "id": "T03",+ "evidence": [+ {+ "repository": "extension",+ "path": "packages/ext/src/background/__tests__/ConnectionManager.mbp1.test.ts",+ "testName": "reconnects remote credentials with the authenticated instance id, not discovery hint"+ }+ ]+ },+ {+ "id": "T04",+ "evidence": [+ {+ "repository": "motrix",+ "path": "src/server/bridge/remote-extension-wss.integration.test.ts",+ "testName": "validates TLS hostname/CA, preserves Host/base path, pairs, and submits over WSS"+ }+ ]+ },+ {+ "id": "T05",+ "evidence": [+ {+ "repository": "motrix",+ "path": "src/core/bridge/mbp1/pair-session.test.ts",+ "testName": "rate-limits, closes, and invalidates the code on the third failure"+ }+ ]+ },+ {+ "id": "T06",+ "evidence": [+ {+ "repository": "extension",+ "path": "packages/ext/src/background/mbp1/__tests__/pairing-flow.test.ts",+ "testName": "refuses to open /pair at all while the lockout is active"+ }+ ]+ },+ {+ "id": "T07",+ "evidence": [+ {+ "repository": "motrix",+ "path": "src/server/http/operator-auth.test.ts",+ "testName": "keeps an Extension pairing code behind operator auth and same-origin CSRF checks"+ }+ ]+ },+ {+ "id": "T08",+ "evidence": [+ {+ "repository": "motrix",+ "path": "src/core/bridge/mbp1/pair-session.test.ts",+ "testName": "rejects a chromium hello whose claimed id does not match the origin"+ },+ {+ "repository": "motrix",+ "path": "src/core/bridge/mbp1/pair-session.test.ts",+ "testName": "resolves a ticketless firefox caller as unverified"+ }+ ]+ },+ {+ "id": "T09",+ "evidence": [+ {+ "repository": "extension",+ "path": "packages/ext/src/background/mbp1/__tests__/credential-store.test.ts",+ "testName": "isolates local, Server A, and Server B even when all reuse one credential id"+ }+ ]+ },+ {+ "id": "T10",+ "evidence": [+ {+ "repository": "extension",+ "path": "packages/ext/src/background/mbp1/__tests__/credential-store.test.ts",+ "testName": "detects same-authority id collisions without leaking values"+ }+ ]+ },+ {+ "id": "T11",+ "evidence": [+ {+ "repository": "extension",+ "path": "packages/ext/src/background/mbp1/__tests__/credential-store.test.ts",+ "testName": "survives repeated MV3 root reconstruction through commit-uncertain recovery, rotation, and revoke"+ }+ ]+ },+ {+ "id": "T12",+ "evidence": [+ {+ "repository": "extension",+ "path": "packages/ext/src/background/mbp1/__tests__/reconnect-flow.test.ts",+ "testName": "reports authFailed (not protocolViolation) when it arrives as the very first frame"+ }+ ]+ },+ {+ "id": "T13",+ "evidence": [+ {+ "repository": "motrix",+ "path": "src/core/bridge/__tests__/mbp1-transport.test.ts",+ "testName": "cannot resurrect a credential whose durable offer returns after revoke completes"+ }+ ]+ },+ {+ "id": "T14",+ "evidence": [+ {+ "repository": "motrix",+ "path": "src/main/bridge/bootstrap-lifecycle.test.ts",+ "testName": "retains a durable pending marker and deny gate when credential revocation fails"+ },+ {+ "repository": "motrix",+ "path": "src/main/bridge/bootstrap-lifecycle.test.ts",+ "testName": "keeps the listener closed when startup cannot finish a durable pending revoke"+ }+ ]+ },+ {+ "id": "T15",+ "evidence": [+ {+ "repository": "motrix",+ "path": "src/core/bridge/web-socket-bridge-server.authz.test.ts",+ "testName": "gives an unauthenticated peer no MDXP surface to drive at all"+ }+ ]+ },+ {+ "id": "T16",+ "evidence": [+ {+ "repository": "extension",+ "path": "packages/ext/src/background/__tests__/remote-submit-policy.test.ts",+ "testName": "strips cookies and every custom header by default without mutating the caller"+ }+ ]+ },+ {+ "id": "T17",+ "evidence": [+ {+ "repository": "motrix",+ "path": "src/core/bridge/__tests__/initialize-handler.test.ts",+ "testName": "derives taskReveal from the currently registered shell capability"+ },+ {+ "repository": "motrix",+ "path": "src/server/bridge/bootstrap.test.ts",+ "testName": "fails closed before listening when remote Extension has no download receiver"+ }+ ]+ },+ {+ "id": "T18",+ "evidence": [+ {+ "repository": "motrix",+ "path": "src/server/bridge/remote-extension-wss.integration.test.ts",+ "testName": "validates TLS hostname/CA, preserves Host/base path, pairs, and submits over WSS"+ }+ ]+ },+ {+ "id": "T19",+ "evidence": [+ {+ "repository": "extension",+ "path": "packages/ext/src/background/mbp1/__tests__/remote-discovery-service.test.ts",+ "testName": "maps the browser redirect:error rejection to generic unavailable"+ },+ {+ "repository": "extension",+ "path": "packages/ext/src/background/mbp1/__tests__/remote-nonce-service.test.ts",+ "testName": "rejects a nonconforming fetch that returns a redirect"+ }+ ]+ },+ {+ "id": "T20",+ "evidence": [+ {+ "repository": "motrix",+ "path": "src/core/bridge/__tests__/mbp1-transport.test.ts",+ "testName": "closes on a replayed sealed frame after activation"+ }+ ]+ },+ {+ "id": "T21",+ "evidence": [+ {+ "repository": "motrix",+ "path": "src/core/bridge/bridge-identity.test.ts",+ "testName": "preserves identity on offline backup restore, resets on a fresh directory, and cannot distinguish a byte-identical clone"+ },+ {+ "repository": "motrix",+ "path": "src/core/bridge/bridge-data-dir-lock.test.ts",+ "testName": "fails with one redacted error while another process owns the lock"+ }+ ]+ },+ {+ "id": "T22",+ "evidence": [+ {+ "repository": "motrix",+ "path": "e2e/bridge/remote-extension-wss.spec.ts",+ "testName": "pair, consent, submit, restart, revoke, and re-pair over WSS"+ },+ {+ "repository": "motrix",+ "path": "src/core/bridge/__tests__/bridge-connection.test.ts",+ "testName": "contains a notification write race after the socket has closed"+ }+ ]+ },+ {+ "id": "T23",+ "evidence": [+ {+ "repository": "extension",+ "path": "packages/ext/src/background/__tests__/EndpointCatalogService.test.ts",+ "testName": "retires only the old authority when an active Server URL changes"+ },+ {+ "repository": "motrix",+ "path": "e2e/bridge/remote-extension-wss.spec.ts",+ "testName": "An authority-changing URL edit is a fresh trust boundary"+ }+ ]+ },+ {+ "id": "T24",+ "evidence": [+ {+ "repository": "extension",+ "path": "packages/ext/src/background/__tests__/ConnectionManager.mbp1.test.ts",+ "testName": "maps a remote pairing WebSocket open failure to one non-specific transport reason"+ },+ {+ "repository": "extension",+ "path": "packages/ext/src/shared/__tests__/errorCopy.test.ts",+ "testName": "describes a remote transport failure without inventing a certificate diagnosis"+ }+ ]+ },+ {+ "id": "T25",+ "evidence": [+ {+ "repository": "motrix",+ "path": "src/core/bridge/__tests__/mbp1-transport.test.ts",+ "testName": "refuses all four Extension routes when MBP1 is not wired"+ }+ ]+ },+ {+ "id": "T26",+ "evidence": [+ {+ "repository": "extension",+ "path": "packages/ext/src/background/mbp1/__tests__/pairing-flow.test.ts",+ "testName": "rejects a pairAccept whose protocolVersion is not 1, as unsupportedVersion"+ },+ {+ "repository": "extension",+ "path": "packages/ext/src/background/mbp1/__tests__/remote-discovery-service.test.ts",+ "testName": "treats a valid Desktop discovery document as the wrong target, not an upgrade verdict"+ }+ ]+ },+ {+ "id": "T27",+ "evidence": [+ {+ "repository": "extension",+ "path": "packages/ext/src/background/mbp1/__tests__/credential-store.test.ts",+ "testName": "survives repeated MV3 root reconstruction through commit-uncertain recovery, rotation, and revoke"+ },+ {+ "repository": "motrix",+ "path": "e2e/bridge/remote-extension-wss.spec.ts",+ "testName": "pair, consent, submit, restart, revoke, and re-pair over WSS"+ }+ ]+ },+ {+ "id": "T28",+ "evidence": [+ {+ "repository": "motrix",+ "path": "e2e/bridge/remote-extension-firefox-wss.spec.ts",+ "testName": "real Firefox: unverified pair, consent, reconnect, revoke, and re-pair over WSS"+ }+ ]+ },+ {+ "id": "T29",+ "evidence": [+ {+ "repository": "motrix",+ "path": "src/server/bridge/remote-extension-admission-policy.test.ts",+ "testName": "bounds rotating source maps by the independent global window cap"+ },+ {+ "repository": "motrix",+ "path": "src/main/bridge/pairing-dialog-controller.test.ts",+ "testName": "enforces the core global capacity without publishing a fourth code"+ }+ ]+ }+ ]+}diff --git a/e2e/bridge/remote-extension-wss.spec.ts b/e2e/bridge/remote-extension-wss.spec.tsnew file mode 100644index 00000000..6c9037fe--- /dev/null+++ b/e2e/bridge/remote-extension-wss.spec.ts@@ -0,0 +1,507 @@+import { createHash, X509Certificate } from 'node:crypto'+import { existsSync } from 'node:fs'+import { mkdtemp, readFile, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import type { DownloadSubmitParams } from '@motrix/mdxp'+import type { BrowserContext, Page } from '@playwright/test'+import { chromium, expect, test } from '@playwright/test'+import type { ServerBridgeRuntime } from '../../src/server/bridge/bootstrap'+import { getFreePort } from '../helpers/free-port'+import {+ PUBLIC_HOST,+ pendingPairingCode,+ ROUTE_PREFIX,+ startRuntime,+ startTlsProxy,+} from './remote-extension-harness'++function certificateSpkiPin(certificatePem: string): string {+ const certificate = new X509Certificate(certificatePem)+ const spki = certificate.publicKey.export({ type: 'spki', format: 'der' })+ return createHash('sha256').update(spki).digest('base64')+}++async function launchExtension(input: {+ extensionBuild: string+ profileDir: string+ spkiPin: string+}): Promise<{ context: BrowserContext; extensionId: string }> {+ const context = await chromium.launchPersistentContext(input.profileDir, {+ ...(process.env.MOTRIX_CHROMIUM_EXECUTABLE+ ? { executablePath: process.env.MOTRIX_CHROMIUM_EXECUTABLE }+ : {}),+ headless: false,+ locale: 'en-US',+ args: [+ `--disable-extensions-except=${input.extensionBuild}`,+ `--load-extension=${input.extensionBuild}`,+ `--host-resolver-rules=MAP ${PUBLIC_HOST} 127.0.0.1`,+ `--ignore-certificate-errors-spki-list=${input.spkiPin}`,+ '--lang=en-US',+ '--no-proxy-server',+ ],+ })+ const serviceWorker =+ context.serviceWorkers()[0] ??+ (await context.waitForEvent('serviceworker', { timeout: 15_000 }))+ return {+ context,+ extensionId: new URL(serviceWorker.url()).hostname,+ }+}++async function openIntegration(+ context: BrowserContext,+ extensionId: string+): Promise<Page> {+ const page = await context.newPage()+ await page.goto(`chrome-extension://${extensionId}/options.html`)+ await page.getByRole('tab', { name: 'Integration' }).click()+ await expect(+ page.getByRole('list', { name: 'Available Motrix backends' })+ ).toBeVisible()+ return page+}++async function pairFromOptions(+ page: Page,+ runtime: ServerBridgeRuntime+): Promise<void> {+ const pairButton = page.getByRole('button', { name: 'Pair', exact: true })+ await expect(pairButton).toBeEnabled()+ await pairButton.click()+ const dialog = page.getByRole('dialog', { name: 'Pair with Motrix' })+ try {+ await expect(dialog).toBeVisible({ timeout: 5_000 })+ } catch {+ const state = await page.evaluate(async () => {+ const extensionGlobal = globalThis as typeof globalThis & {+ chrome: {+ runtime: {+ sendMessage(message: unknown): Promise<unknown>+ }+ }+ }+ return extensionGlobal.chrome.runtime.sendMessage({+ kind: 'bg.getState',+ })+ })+ throw new Error(+ `pairing did not reach code entry: ${JSON.stringify(state)}`+ )+ }+ await expect.poll(() => pendingPairingCode(runtime)).not.toBeNull()+ const code = await pendingPairingCode(runtime)+ if (code === null) throw new Error('remote pairing code was not queued')+ await dialog.getByLabel('Pairing code').fill(code.replace('-', ''))+ await dialog.getByRole('button', { name: 'Pair' }).click()+ await expect(page.getByText('Pairing ready')).toBeVisible()+ await expect(page.getByText('Connected')).toBeVisible()+}++async function addServerFromOptions(+ page: Page,+ name: string,+ url: string+): Promise<void> {+ await page.getByRole('button', { name: 'Add server' }).click()+ const editor = page.getByRole('dialog', { name: 'Add Motrix Server' })+ await editor.getByLabel('Server name').fill(name)+ await editor.getByLabel('WebSocket URL').fill(url)+ await editor.getByRole('button', { name: 'Save server' }).click()+}++async function submitFromExtension(page: Page): Promise<unknown> {+ return page.evaluate(async () => {+ const extensionGlobal = globalThis as typeof globalThis & {+ chrome: {+ runtime: {+ sendMessage(message: unknown): Promise<unknown>+ }+ }+ }+ const response = await extensionGlobal.chrome.runtime.sendMessage({+ kind: 'bg.submitDownload',+ payload: {+ source: {+ pageUrl: 'https://example.com/watch',+ pageTitle: 'Remote browser E2E',+ detectedAt: Date.now(),+ },+ selection: {+ kind: 'direct',+ primary: {+ url: 'https://cdn.example.com/video.mp4',+ headers: {+ Authorization: 'Bearer must-not-cross-without-consent',+ Referer: 'https://example.com/watch',+ },+ cookies: [+ {+ name: 'session',+ value: 'must-not-cross-without-consent',+ domain: 'example.com',+ },+ ],+ refererPolicy: 'strict-origin-when-cross-origin',+ },+ },+ meta: {+ suggestedFilename: 'video.mp4',+ qualityLabel: 'source',+ },+ },+ })+ return response+ })+}++async function actionBadgeText(page: Page): Promise<string> {+ return page.evaluate(async () => {+ const extensionGlobal = globalThis as typeof globalThis & {+ chrome: {+ action: {+ getBadgeText(details: Record<string, never>): Promise<string>+ }+ }+ }+ return extensionGlobal.chrome.action.getBadgeText({})+ })+}++for (const routePrefix of [ROUTE_PREFIX, ''])+ test(`real Chromium: pair, consent, submit, restart, revoke, and re-pair over WSS (${routePrefix || 'root path'})`, async () => {+ const extensionBuild = process.env.MOTRIX_EXTENSION_BUILD+ if (!extensionBuild || !existsSync(join(extensionBuild, 'manifest.json'))) {+ throw new Error(+ 'MOTRIX_EXTENSION_BUILD must point to a built Chromium Extension directory'+ )+ }++ const fixtureRoot = join(process.cwd(), 'src/server/bridge/__fixtures__')+ const [cert, key] = await Promise.all([+ readFile(join(fixtureRoot, 'motrix.test-cert.pem'), 'utf8'),+ readFile(join(fixtureRoot, 'motrix.test-key.pem'), 'utf8'),+ ])+ const root = await mkdtemp(join(tmpdir(), 'motrix-remote-browser-e2e-'))+ const serverDataDir = join(root, 'server')+ const profileDir = join(root, 'chromium-profile')+ const [bridgePort, proxyPort] = await Promise.all([+ getFreePort(),+ getFreePort(),+ ])+ const submissions: DownloadSubmitParams[] = []+ let runtime: ServerBridgeRuntime | null = null+ let context: BrowserContext | null = null+ let closeProxy: (() => Promise<void>) | null = null++ try {+ runtime = await startRuntime({+ dataDir: serverDataDir,+ bridgePort,+ proxyPort,+ submissions,+ routePrefix,+ })+ closeProxy = await startTlsProxy({+ listenPort: proxyPort,+ upstreamPort: bridgePort,+ key,+ cert,+ })+ const launch = await launchExtension({+ extensionBuild,+ profileDir,+ spkiPin: certificateSpkiPin(cert),+ })+ context = launch.context+ let extensionId = launch.extensionId+ let page = await openIntegration(context, extensionId)++ const discoveryProbe = await page.evaluate(async (url) => {+ try {+ const response = await fetch(url, {+ cache: 'no-store',+ credentials: 'omit',+ redirect: 'error',+ })+ return { status: response.status, body: await response.json() }+ } catch (cause) {+ return {+ error: cause instanceof Error ? cause.message : String(cause),+ }+ }+ }, `https://${PUBLIC_HOST}:${proxyPort}${routePrefix}/discovery`)+ expect(discoveryProbe).toMatchObject({+ status: 200,+ body: { runtime: 'server' },+ })++ await page.getByRole('button', { name: 'Add server' }).click()+ const editor = page.getByRole('dialog', { name: 'Add Motrix Server' })+ await editor.getByLabel('Server name').fill('Remote E2E')+ await editor+ .getByLabel('WebSocket URL')+ .fill(`wss://${PUBLIC_HOST}:${proxyPort}${routePrefix}`)+ await editor.getByRole('button', { name: 'Save server' }).click()+ await page.getByRole('button', { name: 'Use Remote E2E' }).click()+ await pairFromOptions(page, runtime)++ await expect(submitFromExtension(page)).resolves.toMatchObject({+ error: expect.stringMatching(+ /remote (?:download )?data boundary consent is required/i+ ),+ })+ await page.getByRole('button', { name: 'Allow remote downloads' }).click()+ await expect(+ page.getByRole('switch', { name: 'Send request headers' })+ ).toBeVisible()+ await page.reload()+ await page.getByRole('tab', { name: 'Integration' }).click()+ await expect(page.getByText('Connected')).toBeVisible()+ await expect(submitFromExtension(page)).resolves.toEqual({+ taskId: 'browser-task-1',+ })+ await expect.poll(() => actionBadgeText(page)).toBe('↓')+ expect(submissions).toHaveLength(1)+ expect(submissions[0]?.selection.kind).toBe('direct')+ if (submissions[0]?.selection.kind !== 'direct') {+ throw new Error('expected direct submission')+ }+ expect(submissions[0].selection.primary.headers).toEqual({})+ expect(submissions[0].selection.primary.cookies).toEqual([])++ await context.close()+ context = null+ const relaunched = await launchExtension({+ extensionBuild,+ profileDir,+ spkiPin: certificateSpkiPin(cert),+ })+ context = relaunched.context+ extensionId = relaunched.extensionId+ page = await openIntegration(context, extensionId)+ await expect(page.getByText('Pairing ready')).toBeVisible()+ await expect(page.getByText('Connected')).toBeVisible()+ await expect(submitFromExtension(page)).resolves.toEqual({+ taskId: 'browser-task-2',+ })++ await runtime.shutdown()+ runtime = await startRuntime({+ dataDir: serverDataDir,+ bridgePort,+ proxyPort,+ submissions,+ routePrefix,+ })+ await expect+ .poll(() => submitFromExtension(page), { timeout: 20_000 })+ .toEqual({+ taskId: 'browser-task-3',+ })++ const paired = (await runtime.bridgeQueryHandlers[+ 'bridge:listPaired'+ ]()) as Array<{+ kind: string+ id: string+ browser?: 'chromium' | 'firefox'+ }>+ const pairedExtension = paired.find(+ (client) => client.kind === 'extension' && client.id === extensionId+ )+ if (!pairedExtension?.browser) {+ throw new Error('paired Extension was not projected by Server')+ }+ await runtime.bridgeCommandHandlers['bridge:revokePair']({+ identity: {+ kind: 'extension',+ browser: pairedExtension.browser,+ extensionId: pairedExtension.id,+ },+ })+ await page.reload()+ await page.getByRole('tab', { name: 'Integration' }).click()+ await expect(page.getByText('Not paired')).toBeVisible()+ await pairFromOptions(page, runtime)+ await expect(page.getByText('Pairing ready')).toBeVisible()+ } finally {+ if (context !== null) await context.close()+ if (closeProxy !== null) await closeProxy()+ if (runtime !== null) await runtime.shutdown()+ await rm(root, { recursive: true, force: true })+ }+ })++test('real Chromium: local profile keeps two remote Servers paired and policy-isolated', async () => {+ const extensionBuild = process.env.MOTRIX_EXTENSION_BUILD+ if (!extensionBuild || !existsSync(join(extensionBuild, 'manifest.json'))) {+ throw new Error(+ 'MOTRIX_EXTENSION_BUILD must point to a built Chromium Extension directory'+ )+ }++ const fixtureRoot = join(process.cwd(), 'src/server/bridge/__fixtures__')+ const [cert, key] = await Promise.all([+ readFile(join(fixtureRoot, 'motrix.test-cert.pem'), 'utf8'),+ readFile(join(fixtureRoot, 'motrix.test-key.pem'), 'utf8'),+ ])+ const root = await mkdtemp(join(tmpdir(), 'motrix-two-server-e2e-'))+ const profileDir = join(root, 'chromium-profile')+ const serverDataDirA = join(root, 'server-a')+ const serverDataDirB = join(root, 'server-b')+ const [bridgePortA, proxyPortA, bridgePortB, proxyPortB] = await Promise.all([+ getFreePort(),+ getFreePort(),+ getFreePort(),+ getFreePort(),+ ])+ const submissionsA: DownloadSubmitParams[] = []+ const submissionsB: DownloadSubmitParams[] = []+ let runtimeA: ServerBridgeRuntime | null = null+ let runtimeB: ServerBridgeRuntime | null = null+ let context: BrowserContext | null = null+ let closeProxyA: (() => Promise<void>) | null = null+ let closeProxyB: (() => Promise<void>) | null = null++ try {+ runtimeA = await startRuntime({+ dataDir: serverDataDirA,+ bridgePort: bridgePortA,+ proxyPort: proxyPortA,+ submissions: submissionsA,+ routePrefix: ROUTE_PREFIX,+ })+ runtimeB = await startRuntime({+ dataDir: serverDataDirB,+ bridgePort: bridgePortB,+ proxyPort: proxyPortB,+ submissions: submissionsB,+ routePrefix: ROUTE_PREFIX,+ })+ closeProxyA = await startTlsProxy({+ listenPort: proxyPortA,+ upstreamPort: bridgePortA,+ key,+ cert,+ })+ closeProxyB = await startTlsProxy({+ listenPort: proxyPortB,+ upstreamPort: bridgePortB,+ key,+ cert,+ })+ const launched = await launchExtension({+ extensionBuild,+ profileDir,+ spkiPin: certificateSpkiPin(cert),+ })+ context = launched.context+ const page = await openIntegration(context, launched.extensionId)++ await addServerFromOptions(+ page,+ 'Server A',+ `wss://${PUBLIC_HOST}:${proxyPortA}${ROUTE_PREFIX}`+ )+ await page.getByRole('button', { name: 'Use Server A' }).click()+ await pairFromOptions(page, runtimeA)+ await page.getByRole('button', { name: 'Allow remote downloads' }).click()+ await page.reload()+ await page.getByRole('tab', { name: 'Integration' }).click()+ await expect(page.getByText('Connected')).toBeVisible()+ await expect(submitFromExtension(page)).resolves.toEqual({+ taskId: 'browser-task-1',+ })++ await addServerFromOptions(+ page,+ 'Server B',+ `wss://${PUBLIC_HOST}:${proxyPortB}${ROUTE_PREFIX}`+ )+ await page.getByRole('button', { name: 'Use Server B' }).click()+ await pairFromOptions(page, runtimeB)+ await expect(submitFromExtension(page)).resolves.toMatchObject({+ error: expect.stringMatching(/remote (?:download )?data boundary/i),+ })+ expect(submissionsA).toHaveLength(1)+ expect(submissionsB).toHaveLength(0)++ await page.getByRole('button', { name: 'Allow remote downloads' }).click()+ await page.reload()+ await page.getByRole('tab', { name: 'Integration' }).click()+ await expect(page.getByText('Connected')).toBeVisible()+ await expect(submitFromExtension(page)).resolves.toEqual({+ taskId: 'browser-task-1',+ })+ expect(submissionsB).toHaveLength(1)++ await page.getByRole('button', { name: 'Use Server A' }).click()+ await expect(page.getByText('Pairing ready')).toBeVisible()+ await expect+ .poll(() => submitFromExtension(page), { timeout: 20_000 })+ .toEqual({ taskId: 'browser-task-2' })+ expect(submissionsA).toHaveLength(2)+ expect(submissionsB).toHaveLength(1)++ for (const runtime of [runtimeA, runtimeB]) {+ const paired = (await runtime.bridgeQueryHandlers[+ 'bridge:listPaired'+ ]()) as Array<{ kind: string; id: string }>+ expect(paired).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ kind: 'extension',+ id: launched.extensionId,+ browser: 'chromium',+ identityTrust: 'attested-non-official',+ status: 'ready',+ pairedAt: expect.any(Number),+ }),+ ])+ )+ }++ // An authority-changing URL edit is a fresh trust boundary even when the+ // proxy reaches the same durable Server identity. Retire A's old+ // credential/policy, re-pair on the root route, and prove B remains+ // untouched.+ await runtimeA.shutdown()+ runtimeA = await startRuntime({+ dataDir: serverDataDirA,+ bridgePort: bridgePortA,+ proxyPort: proxyPortA,+ submissions: submissionsA,+ routePrefix: '',+ })+ await page.getByRole('button', { name: 'Edit Server A' }).click()+ const editor = page.getByRole('dialog', { name: 'Edit Motrix Server' })+ const urlInput = editor.getByLabel('WebSocket URL')+ await urlInput.fill(`wss://${PUBLIC_HOST}:${proxyPortA}`)+ await editor.getByRole('button', { name: 'Save server' }).click()+ await expect(page.getByText('Not paired')).toBeVisible()++ await pairFromOptions(page, runtimeA)+ await expect(submitFromExtension(page)).resolves.toMatchObject({+ error: expect.stringMatching(/remote (?:download )?data boundary/i),+ })+ await page.getByRole('button', { name: 'Allow remote downloads' }).click()+ await page.reload()+ await page.getByRole('tab', { name: 'Integration' }).click()+ await expect(page.getByText('Connected')).toBeVisible()+ await expect(submitFromExtension(page)).resolves.toEqual({+ taskId: 'browser-task-3',+ })+ expect(submissionsA).toHaveLength(3)+ expect(submissionsB).toHaveLength(1)+ } finally {+ if (context !== null) await context.close()+ if (closeProxyB !== null) await closeProxyB()+ if (closeProxyA !== null) await closeProxyA()+ if (runtimeB !== null) await runtimeB.shutdown()+ if (runtimeA !== null) await runtimeA.shutdown()+ await rm(root, { recursive: true, force: true })+ }+})diff --git a/e2e/bridge/remote-extension.playwright.config.ts b/e2e/bridge/remote-extension.playwright.config.tsnew file mode 100644index 00000000..b324d5e9--- /dev/null+++ b/e2e/bridge/remote-extension.playwright.config.ts@@ -0,0 +1,25 @@+import { join } from 'node:path'+import { defineConfig } from '@playwright/test'++const evidenceDirectory = process.env.MOTRIX_REMOTE_EXTENSION_EVIDENCE_DIR++export default defineConfig({+ testDir: '.',+ testMatch: /remote-extension(?:-firefox)?-wss\.spec\.ts$/,+ workers: 1,+ fullyParallel: false,+ retries: 0,+ reporter:+ evidenceDirectory === undefined+ ? [['list']]+ : [+ ['list'],+ [+ 'json',+ { outputFile: join(evidenceDirectory, 'playwright-report.json') },+ ],+ ],+ timeout: 120_000,+ expect: { timeout: 15_000 },+ outputDir: '../test-results/remote-extension',+})diff --git a/package.json b/package.jsonindex 06869e3a..d7bb92cb 100644--- a/package.json+++ b/package.json@@ -43,6 +43,8 @@"check:flatpak": "node scripts/verify-flatpak-packaging.mjs","check:i18n": "node --import tsx scripts/check-i18n.mjs","check:registry-runtime": "pnpm run ensure:electron-runtime && node scripts/check-registry-electron-runtime.mjs",+ "check:remote-extension-compatibility": "node scripts/verify-remote-extension-compatibility.mjs",+ "check:remote-extension-threats": "node scripts/verify-remote-extension-threat-evidence.mjs","check:schema-parity": "node scripts/check-schema-parity.mjs","check:third-party-notices": "pnpm run ensure:electron-runtime && node scripts/generate-third-party-notices.mjs --check && vitest run tests/check-third-party-notices.test.ts tests/generate-third-party-notices.test.ts","check:update-artifacts": "node scripts/verify-update-artifacts.mjs",@@ -67,6 +69,9 @@"test:watch": "vitest","pretest:e2e": "pnpm run ensure:electron-runtime && node scripts/ensure-native-abi.mjs electron","test:e2e": "playwright test",+ "test:e2e:remote-extension": "pnpm check:remote-extension-threats && playwright test --config e2e/bridge/remote-extension.playwright.config.ts",+ "test:e2e:remote-extension:soak": "node scripts/run-remote-extension-soak.mjs",+ "test:e2e:remote-extension:release-soak": "node scripts/run-remote-extension-release-soak.mjs","pretest:e2e:ui": "pnpm run ensure:electron-runtime && node scripts/ensure-native-abi.mjs electron","test:e2e:ui": "playwright test --ui","pretest:e2e:debug": "pnpm run ensure:electron-runtime && node scripts/ensure-native-abi.mjs electron",diff --git a/scripts/run-remote-extension-release-soak.mjs b/scripts/run-remote-extension-release-soak.mjsnew file mode 100644index 00000000..c3e68085--- /dev/null+++ b/scripts/run-remote-extension-release-soak.mjs@@ -0,0 +1,487 @@+import { spawnSync } from 'node:child_process'+import { createHash } from 'node:crypto'+import {+ existsSync,+ lstatSync,+ mkdirSync,+ readdirSync,+ readFileSync,+ realpathSync,+ statSync,+ writeFileSync,+} from 'node:fs'+import { arch, platform, release } from 'node:os'+import { basename, dirname, join, relative, resolve, sep } from 'node:path'+import process from 'node:process'+import { fileURLToPath } from 'node:url'+import { parseRemoteExtensionSoakRepeats } from './run-remote-extension-soak.mjs'+import { verifyRemoteExtensionCompatibility } from './verify-remote-extension-compatibility.mjs'++const RELEASE_REPEATS = 20+const DEFAULT_MANIFEST = 'e2e/bridge/remote-extension-compatibility.json'++function run(command, args, options = {}) {+ const result = spawnSync(command, args, {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'pipe'],+ ...options,+ })+ if (result.error) throw result.error+ if (result.status !== 0) {+ const detail = `${result.stderr ?? ''}${result.stdout ?? ''}`.trim()+ throw new Error(+ `${basename(command)} ${args.join(' ')} failed${detail ? `: ${detail}` : ''}`+ )+ }+ return String(result.stdout ?? '').trim()+}++function git(repository, args) {+ return run('git', ['-C', repository, ...args])+}++function normalizeRepoPath(value) {+ return value.split(sep).join('/')+}++function listFiles(root, current = root) {+ const files = []+ for (const entry of readdirSync(current, { withFileTypes: true })) {+ const path = join(current, entry.name)+ if (entry.isDirectory()) files.push(...listFiles(root, path))+ else if (entry.isFile()) files.push(path)+ else throw new Error(`release build contains unsupported entry: ${path}`)+ }+ return files.sort((a, b) => a.localeCompare(b))+}++export function digestDirectory(directory) {+ const root = resolve(directory)+ if (lstatSync(root).isSymbolicLink()) {+ throw new Error(`release build must not be a symbolic link: ${root}`)+ }+ if (!statSync(root).isDirectory()) {+ throw new Error(`release build is not a directory: ${root}`)+ }+ const hash = createHash('sha256')+ for (const path of listFiles(root)) {+ hash.update(normalizeRepoPath(relative(root, path)))+ hash.update('\0')+ hash.update(readFileSync(path))+ hash.update('\0')+ }+ return hash.digest('hex')+}++export function validateReleaseSoakState(input) {+ if (input.repeats !== RELEASE_REPEATS) {+ throw new Error(+ `release soak requires exactly ${RELEASE_REPEATS} repetitions`+ )+ }+ if (input.extensionDirty || input.motrixDirty) {+ throw new Error(+ 'release soak requires clean Extension and Motrix worktrees'+ )+ }+ if (input.extensionHead !== input.extensionPin) {+ throw new Error('Extension HEAD must exactly match the compatibility pin')+ }+ if (input.manifestRelativePath !== DEFAULT_MANIFEST) {+ throw new Error(`release manifest must be ${DEFAULT_MANIFEST}`)+ }+ if (+ input.motrixChangedFiles.length !== 1 ||+ input.motrixChangedFiles[0] !== input.manifestRelativePath+ ) {+ throw new Error(+ 'Motrix changes after its compatibility pin must contain only the pinned manifest'+ )+ }+ return input+}++function inferExtensionRepository(env) {+ if (env.MOTRIX_EXTENSION_REPO)+ return realpathSync(resolve(env.MOTRIX_EXTENSION_REPO))+ if (env.MOTRIX_EXTENSION_BUILD) {+ return realpathSync(resolve(env.MOTRIX_EXTENSION_BUILD, '../../../..'))+ }+ throw new Error('MOTRIX_EXTENSION_REPO or MOTRIX_EXTENSION_BUILD is required')+}++export function validateReleaseManifestLocation(input) {+ if (input.relativePath !== DEFAULT_MANIFEST) {+ throw new Error(`release manifest must be ${DEFAULT_MANIFEST}`)+ }+ if (!input.isFile || input.isSymbolicLink) {+ throw new Error('release manifest must be a regular non-symlink file')+ }+ return input.relativePath+}++export function validateReleaseBuildLocation(input) {+ if (input.isSymbolicLink || input.actualPath !== input.expectedPath) {+ throw new Error(+ `${input.kind} build must be inside the pinned Extension checkout and must not be a symbolic link`+ )+ }+ return input.actualPath+}++function expectedBuildDirectory(extensionRepository, kind, configured) {+ if (!configured) {+ throw new Error(+ `MOTRIX_${kind === 'chromium' ? '' : 'FIREFOX_'}EXTENSION_BUILD is required in release mode`+ )+ }+ const expected = join(extensionRepository, 'packages/ext/dist', kind)+ const actual = resolve(configured)+ const isSymbolicLink = lstatSync(actual).isSymbolicLink()+ validateReleaseBuildLocation({+ kind,+ actualPath: isSymbolicLink ? actual : realpathSync(actual),+ expectedPath: realpathSync(expected),+ isSymbolicLink,+ })+ return actual+}++export function buildReleaseExtensions(env = process.env, spawn = spawnSync) {+ const extensionRepository = inferExtensionRepository(env)+ const executable = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm'+ for (const target of ['build:chromium', 'build:firefox']) {+ const result = spawn(+ executable,+ ['--dir', extensionRepository, '--filter', '@motrix/extension', target],+ { stdio: 'inherit', env }+ )+ if (result.error) throw result.error+ if (result.status !== 0) {+ throw new Error(+ `release Extension ${target} failed with exit code ${String(result.status)}`+ )+ }+ }+}++function executableVersion(path, label) {+ if (!path)+ throw new Error(`${label} executable must be explicit in release mode`)+ if (!existsSync(path))+ throw new Error(`${label} executable does not exist: ${path}`)+ return run(path, ['--version'])+}++export function collectReleaseSoakContext(+ env = process.env,+ { includeBuilds = true } = {}+) {+ const motrixRepository = resolve(process.cwd())+ const extensionRepository = inferExtensionRepository(env)+ const manifestPath = resolve(+ motrixRepository,+ env.MOTRIX_REMOTE_EXTENSION_COMPATIBILITY_MANIFEST ?? DEFAULT_MANIFEST+ )+ const manifestRelativePath = normalizeRepoPath(+ relative(motrixRepository, manifestPath)+ )+ const manifestStat = lstatSync(manifestPath)+ validateReleaseManifestLocation({+ relativePath: manifestRelativePath,+ isFile: manifestStat.isFile(),+ isSymbolicLink: manifestStat.isSymbolicLink(),+ })+ const manifest = verifyRemoteExtensionCompatibility({+ manifestPath,+ motrixRepository,+ extensionRepository,+ })+ const extensionHead = git(extensionRepository, ['rev-parse', 'HEAD'])+ const motrixHead = git(motrixRepository, ['rev-parse', 'HEAD'])+ const extensionDirty =+ git(extensionRepository, [+ 'status',+ '--porcelain',+ '--untracked-files=normal',+ ]).length > 0+ const motrixDirty =+ git(motrixRepository, ['status', '--porcelain', '--untracked-files=normal'])+ .length > 0+ const changed = git(motrixRepository, [+ 'diff',+ '--name-only',+ `${manifest.motrix.commit}..HEAD`,+ ])+ const motrixChangedFiles = changed === '' ? [] : changed.split('\n').sort()+ validateReleaseSoakState({+ repeats: RELEASE_REPEATS,+ extensionDirty,+ motrixDirty,+ extensionHead,+ extensionPin: manifest.extension.commit,+ motrixChangedFiles,+ manifestRelativePath,+ })++ const builds = includeBuilds+ ? (() => {+ const chromiumBuild = expectedBuildDirectory(+ extensionRepository,+ 'chromium',+ env.MOTRIX_EXTENSION_BUILD+ )+ const firefoxBuild = expectedBuildDirectory(+ extensionRepository,+ 'firefox',+ env.MOTRIX_FIREFOX_EXTENSION_BUILD+ )+ return {+ chromium: {+ path: chromiumBuild,+ sha256: digestDirectory(chromiumBuild),+ },+ firefox: {+ path: firefoxBuild,+ sha256: digestDirectory(firefoxBuild),+ },+ }+ })()+ : null+ return {+ protocol: manifest.protocol,+ compatibilityManifest: manifestRelativePath,+ pins: {+ extension: manifest.extension.commit,+ motrix: manifest.motrix.commit,+ },+ heads: { extension: extensionHead, motrix: motrixHead },+ repositories: { extension: extensionRepository, motrix: motrixRepository },+ builds,+ browsers: {+ chromium: executableVersion(env.MOTRIX_CHROMIUM_EXECUTABLE, 'Chromium'),+ firefox: executableVersion(env.MOTRIX_FIREFOX_EXECUTABLE, 'Firefox'),+ },+ operatingSystem: { platform: platform(), release: release(), arch: arch() },+ faultInjection: env.MOTRIX_REMOTE_EXTENSION_SOAK_FAULTS ?? 'none',+ }+}++function defaultWriteEvidence(directory, evidence) {+ mkdirSync(directory, { recursive: true })+ const path = join(directory, 'evidence.json')+ writeFileSync(path, `${JSON.stringify(evidence, null, 2)}\n`, {+ encoding: 'utf8',+ flag: 'wx',+ })+ return path+}++function defaultPrepareEvidenceDirectory(directory) {+ mkdirSync(dirname(directory), { recursive: true })+ // Deliberately omit `recursive`: an existing run directory must fail rather+ // than allowing Playwright's JSON reporter to overwrite prior evidence.+ mkdirSync(directory)+}++function assertObject(value, label) {+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {+ throw new Error(`${label} must be an object`)+ }+ return value+}++export function validateReleasePlaywrightReport(+ input,+ expectedBrowserCases = RELEASE_REPEATS * 5+) {+ const report = assertObject(input, 'Playwright report')+ if (!Array.isArray(report.errors) || report.errors.length !== 0) {+ throw new Error('Playwright report contains top-level errors')+ }+ if (!Array.isArray(report.suites)) {+ throw new Error('Playwright report suites must be an array')+ }+ const summary = {+ testEntries: 0,+ browserCases: 0,+ passed: 0,+ failed: 0,+ }+ const visitSuite = (value) => {+ const suite = assertObject(value, 'Playwright suite')+ if (suite.specs !== undefined) {+ if (!Array.isArray(suite.specs)) {+ throw new Error('Playwright suite specs must be an array')+ }+ for (const specValue of suite.specs) {+ const spec = assertObject(specValue, 'Playwright spec')+ if (!Array.isArray(spec.tests)) {+ throw new Error('Playwright spec tests must be an array')+ }+ for (const testValue of spec.tests) {+ const test = assertObject(testValue, 'Playwright test')+ summary.testEntries += 1+ if (+ test.expectedStatus !== 'passed' ||+ test.status !== 'expected' ||+ !Array.isArray(test.results) ||+ test.results.length === 0+ ) {+ summary.failed += 1+ continue+ }+ for (const resultValue of test.results) {+ const result = assertObject(resultValue, 'Playwright result')+ summary.browserCases += 1+ if (+ result.status === 'passed' &&+ Array.isArray(result.errors) &&+ result.errors.length === 0+ ) {+ summary.passed += 1+ } else {+ summary.failed += 1+ }+ }+ }+ }+ }+ if (suite.suites !== undefined) {+ if (!Array.isArray(suite.suites)) {+ throw new Error('Playwright nested suites must be an array')+ }+ for (const nested of suite.suites) visitSuite(nested)+ }+ }+ for (const suite of report.suites) visitSuite(suite)+ if (+ summary.browserCases !== expectedBrowserCases ||+ summary.passed !== expectedBrowserCases ||+ summary.failed !== 0+ ) {+ throw new Error(+ `Playwright report must contain exactly ${expectedBrowserCases} passed browser cases; got ${JSON.stringify(summary)}`+ )+ }+ return summary+}++function defaultValidateReport(path) {+ return validateReleasePlaywrightReport(JSON.parse(readFileSync(path, 'utf8')))+}++export function runRemoteExtensionReleaseSoak({+ env = process.env,+ spawn = spawnSync,+ context,+ prepareBuild = buildReleaseExtensions,+ collectContext = collectReleaseSoakContext,+ now = () => new Date(),+ writeEvidence = defaultWriteEvidence,+ reportExists = existsSync,+ validateReport = defaultValidateReport,+ prepareEvidenceDirectory = defaultPrepareEvidenceDirectory,+} = {}) {+ let releaseContext = context+ if (releaseContext === undefined) {+ // First collection is a clean/pinned source preflight. Build both browser+ // artifacts from that exact checkout, then collect again so recorded+ // digests describe the newly produced output and any tracked build side+ // effect fails the second clean-worktree check.+ collectContext(env, { includeBuilds: false })+ prepareBuild(env)+ releaseContext = collectContext(env, { includeBuilds: true })+ }+ const repeats = parseRemoteExtensionSoakRepeats(+ env.MOTRIX_REMOTE_EXTENSION_SOAK_REPEATS+ )+ validateReleaseSoakState({+ repeats,+ extensionDirty: false,+ motrixDirty: false,+ extensionHead: releaseContext.heads.extension,+ extensionPin: releaseContext.pins.extension,+ motrixChangedFiles: [releaseContext.compatibilityManifest],+ manifestRelativePath: releaseContext.compatibilityManifest,+ })+ const started = now()+ const runId = started.toISOString().replaceAll(':', '-').replaceAll('.', '-')+ const evidenceDirectory = resolve(+ env.MOTRIX_REMOTE_EXTENSION_SOAK_EVIDENCE_DIR ??+ join('e2e/test-results/remote-extension-soak', runId)+ )+ prepareEvidenceDirectory(evidenceDirectory)+ const reportPath = join(evidenceDirectory, 'playwright-report.json')+ const executable = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm'+ const result = spawn(executable, ['test:e2e:remote-extension:soak'], {+ stdio: 'inherit',+ env: {+ ...env,+ MOTRIX_REMOTE_EXTENSION_SOAK_REPEATS: String(RELEASE_REPEATS),+ MOTRIX_REMOTE_EXTENSION_EVIDENCE_DIR: evidenceDirectory,+ },+ })+ const ended = now()+ const reportPresent = reportExists(reportPath)+ let reportSummary = null+ let reportValidationError = null+ if (result.status === 0 && reportPresent) {+ try {+ reportSummary = validateReport(reportPath)+ } catch (error) {+ reportValidationError =+ error instanceof Error ? error.message : String(error)+ }+ }+ const status = result.error+ ? 'spawn-error'+ : result.status !== 0+ ? 'failed'+ : reportPresent && reportValidationError === null+ ? 'passed'+ : 'incomplete'+ const evidence = {+ schemaVersion: 1,+ protocol: 'MDXP-over-MBP1',+ status,+ repeats: RELEASE_REPEATS,+ browserCases: RELEASE_REPEATS * 5,+ startedAt: started.toISOString(),+ endedAt: ended.toISOString(),+ durationMs: ended.getTime() - started.getTime(),+ context: releaseContext,+ artifacts: {+ playwrightReport: reportPath,+ reportPresent,+ reportSummary,+ reportValidationError,+ },+ }+ const evidencePath = writeEvidence(evidenceDirectory, evidence)+ if (result.error) throw result.error+ if (result.status !== 0) {+ throw new Error(+ `remote Extension release soak failed with exit code ${String(result.status)}; evidence: ${evidencePath}`+ )+ }+ if (!reportPresent) {+ throw new Error(`Playwright JSON report missing: ${reportPath}`)+ }+ if (reportValidationError !== null) {+ throw new Error(`Playwright JSON report invalid: ${reportValidationError}`)+ }+ return { evidencePath, reportPath, evidence }+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ try {+ const result = runRemoteExtensionReleaseSoak()+ console.log(+ `Remote Extension release soak evidence: ${result.evidencePath}`+ )+ } catch (error) {+ console.error(error instanceof Error ? error.message : String(error))+ process.exitCode = 1+ }+}diff --git a/scripts/run-remote-extension-soak.mjs b/scripts/run-remote-extension-soak.mjsnew file mode 100644index 00000000..8f4f29f4--- /dev/null+++ b/scripts/run-remote-extension-soak.mjs@@ -0,0 +1,55 @@+import { spawnSync } from 'node:child_process'+import process from 'node:process'+import { fileURLToPath } from 'node:url'++const DEFAULT_REPEATS = 20+const MAX_REPEATS = 100++export function parseRemoteExtensionSoakRepeats(value) {+ if (value === undefined || value === '') return DEFAULT_REPEATS+ if (!/^[1-9][0-9]*$/u.test(value)) {+ throw new TypeError(+ 'MOTRIX_REMOTE_EXTENSION_SOAK_REPEATS must be a positive integer'+ )+ }+ const repeats = Number(value)+ if (!Number.isSafeInteger(repeats) || repeats > MAX_REPEATS) {+ throw new TypeError(+ `MOTRIX_REMOTE_EXTENSION_SOAK_REPEATS must be <= ${MAX_REPEATS}`+ )+ }+ return repeats+}++export function runRemoteExtensionSoak({+ repeats = parseRemoteExtensionSoakRepeats(+ process.env.MOTRIX_REMOTE_EXTENSION_SOAK_REPEATS+ ),+ spawn = spawnSync,+} = {}) {+ const executable = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm'+ const result = spawn(+ executable,+ ['test:e2e:remote-extension', `--repeat-each=${repeats}`],+ { stdio: 'inherit', env: process.env }+ )+ if (result.error) throw result.error+ if (result.status !== 0) {+ throw new Error(+ `remote Extension soak failed with exit code ${String(result.status)}`+ )+ }+ return { repeats, browserCases: repeats * 5 }+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ try {+ const result = runRemoteExtensionSoak()+ console.log(+ `Remote Extension soak passed ${result.repeats} repetitions / ${result.browserCases} browser cases`+ )+ } catch (error) {+ console.error(error instanceof Error ? error.message : String(error))+ process.exitCode = 1+ }+}diff --git a/scripts/verify-remote-extension-compatibility.mjs b/scripts/verify-remote-extension-compatibility.mjsnew file mode 100644index 00000000..b5dd67c4--- /dev/null+++ b/scripts/verify-remote-extension-compatibility.mjs@@ -0,0 +1,169 @@+import { spawnSync } from 'node:child_process'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import process from 'node:process'+import { pathToFileURL } from 'node:url'++const FULL_SHA_PATTERN = /^[0-9a-f]{40}$/u+const PLACEHOLDER_SHA_PATTERN = /^(?:0{40}|f{40})$/u+const EXPECTED_PROTOCOL = 'MDXP-over-MBP1'++function assertRecord(value, label) {+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {+ throw new TypeError(`${label} must be an object`)+ }+ return value+}++function assertExactKeys(value, expected, label) {+ const actual = Object.keys(value).sort()+ const wanted = [...expected].sort()+ if (JSON.stringify(actual) !== JSON.stringify(wanted)) {+ throw new TypeError(+ `${label} must contain exactly: ${wanted.join(', ')}; got: ${actual.join(', ')}`+ )+ }+}++function assertFullCommit(value, label) {+ if (+ typeof value !== 'string' ||+ !FULL_SHA_PATTERN.test(value) ||+ PLACEHOLDER_SHA_PATTERN.test(value)+ ) {+ throw new TypeError(`${label} must be a non-placeholder full lowercase SHA`)+ }+}++export function validateRemoteExtensionCompatibilityManifest(input) {+ const manifest = assertRecord(input, 'manifest')+ assertExactKeys(+ manifest,+ ['schemaVersion', 'protocol', 'extension', 'motrix', 'e2e'],+ 'manifest'+ )+ if (manifest.schemaVersion !== 1) {+ throw new TypeError('manifest.schemaVersion must be 1')+ }+ if (manifest.protocol !== EXPECTED_PROTOCOL) {+ throw new TypeError(`manifest.protocol must be ${EXPECTED_PROTOCOL}`)+ }++ const extension = assertRecord(manifest.extension, 'manifest.extension')+ const motrix = assertRecord(manifest.motrix, 'manifest.motrix')+ const e2e = assertRecord(manifest.e2e, 'manifest.e2e')+ assertExactKeys(extension, ['repository', 'commit'], 'manifest.extension')+ assertExactKeys(motrix, ['repository', 'commit'], 'manifest.motrix')+ assertExactKeys(e2e, ['browserCases', 'command'], 'manifest.e2e')++ if (extension.repository !== 'motrix-extension') {+ throw new TypeError(+ 'manifest.extension.repository must be motrix-extension'+ )+ }+ if (motrix.repository !== 'motrix-app') {+ throw new TypeError('manifest.motrix.repository must be motrix-app')+ }+ assertFullCommit(extension.commit, 'manifest.extension.commit')+ assertFullCommit(motrix.commit, 'manifest.motrix.commit')+ if (!Number.isInteger(e2e.browserCases) || e2e.browserCases < 5) {+ throw new TypeError('manifest.e2e.browserCases must be an integer >= 5')+ }+ if (e2e.command !== 'pnpm test:e2e:remote-extension') {+ throw new TypeError(+ 'manifest.e2e.command must be pnpm test:e2e:remote-extension'+ )+ }++ return manifest+}++function runGit(repository, args) {+ return spawnSync('git', ['-C', repository, ...args], {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'pipe'],+ })+}++export function verifyPinnedCommit(repository, commit, label) {+ const resolvedRepository = resolve(repository)+ const object = runGit(resolvedRepository, [+ 'cat-file',+ '-e',+ `${commit}^{commit}`,+ ])+ if (object.status !== 0) {+ throw new Error(+ `${label} commit ${commit} does not resolve in ${resolvedRepository}`+ )+ }+ const ancestor = runGit(resolvedRepository, [+ 'merge-base',+ '--is-ancestor',+ commit,+ 'HEAD',+ ])+ if (ancestor.status !== 0) {+ throw new Error(+ `${label} commit ${commit} is not an ancestor of HEAD in ${resolvedRepository}`+ )+ }+}++export function verifyRemoteExtensionCompatibility({+ manifestPath,+ motrixRepository,+ extensionRepository,+}) {+ const parsed = JSON.parse(readFileSync(resolve(manifestPath), 'utf8'))+ const manifest = validateRemoteExtensionCompatibilityManifest(parsed)+ verifyPinnedCommit(+ extensionRepository,+ manifest.extension.commit,+ 'Extension'+ )+ verifyPinnedCommit(motrixRepository, manifest.motrix.commit, 'Motrix')+ return manifest+}++function parseArguments(argv) {+ const values = new Map()+ for (let index = 0; index < argv.length; index += 2) {+ const key = argv[index]+ const value = argv[index + 1]+ if (!key?.startsWith('--') || value === undefined) {+ throw new TypeError(+ 'usage: node scripts/verify-remote-extension-compatibility.mjs --manifest <path> --motrix-repo <path> --extension-repo <path>'+ )+ }+ values.set(key, value)+ }+ for (const required of ['--manifest', '--motrix-repo', '--extension-repo']) {+ if (!values.has(required)) {+ throw new TypeError(`missing required argument: ${required}`)+ }+ }+ return {+ manifestPath: values.get('--manifest'),+ motrixRepository: values.get('--motrix-repo'),+ extensionRepository: values.get('--extension-repo'),+ }+}++const isMain =+ process.argv[1] !== undefined &&+ import.meta.url === pathToFileURL(resolve(process.argv[1])).href++if (isMain) {+ try {+ const manifest = verifyRemoteExtensionCompatibility(+ parseArguments(process.argv.slice(2))+ )+ console.log(+ `Verified ${manifest.protocol}: Extension ${manifest.extension.commit}, Motrix ${manifest.motrix.commit}, ${manifest.e2e.browserCases} browser cases`+ )+ } catch (error) {+ console.error(error instanceof Error ? error.message : String(error))+ process.exitCode = 1+ }+}diff --git a/scripts/verify-remote-extension-threat-evidence.mjs b/scripts/verify-remote-extension-threat-evidence.mjsnew file mode 100644index 00000000..980d19ba--- /dev/null+++ b/scripts/verify-remote-extension-threat-evidence.mjs@@ -0,0 +1,197 @@+import {+ existsSync,+ lstatSync,+ readFileSync,+ realpathSync,+ statSync,+} from 'node:fs'+import { dirname, resolve, sep } from 'node:path'+import process from 'node:process'+import { fileURLToPath } from 'node:url'++const scriptRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')+const expectedThreatIds = Array.from(+ { length: 29 },+ (_, index) => `T${String(index + 1).padStart(2, '0')}`+)+const testFilePattern = /\.(?:test|spec)\.[cm]?[jt]sx?$/u++function assertRecord(value, label) {+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {+ throw new TypeError(`${label} must be an object`)+ }+ return value+}++function assertExactKeys(value, expected, label) {+ const actual = Object.keys(value).sort()+ const wanted = [...expected].sort()+ if (JSON.stringify(actual) !== JSON.stringify(wanted)) {+ throw new TypeError(`${label} must contain exactly: ${wanted.join(', ')}`)+ }+}++export function validateThreatEvidenceManifest(input) {+ const manifest = assertRecord(input, 'manifest')+ assertExactKeys(manifest, ['schemaVersion', 'threats'], 'manifest')+ if (manifest.schemaVersion !== 1) {+ throw new TypeError('manifest.schemaVersion must be 1')+ }+ if (!Array.isArray(manifest.threats)) {+ throw new TypeError('manifest.threats must be an array')+ }++ const seen = new Set()+ for (const [threatIndex, rawThreat] of manifest.threats.entries()) {+ const label = `manifest.threats[${threatIndex}]`+ const threat = assertRecord(rawThreat, label)+ assertExactKeys(threat, ['id', 'evidence'], label)+ if (!expectedThreatIds.includes(threat.id) || seen.has(threat.id)) {+ throw new TypeError(`${label}.id must be one unique T01-T29 id`)+ }+ seen.add(threat.id)+ if (!Array.isArray(threat.evidence) || threat.evidence.length === 0) {+ throw new TypeError(`${label}.evidence must be a non-empty array`)+ }+ for (const [evidenceIndex, rawEvidence] of threat.evidence.entries()) {+ const evidenceLabel = `${label}.evidence[${evidenceIndex}]`+ const evidence = assertRecord(rawEvidence, evidenceLabel)+ assertExactKeys(+ evidence,+ ['repository', 'path', 'testName'],+ evidenceLabel+ )+ if (+ evidence.repository !== 'extension' &&+ evidence.repository !== 'motrix'+ ) {+ throw new TypeError(+ `${evidenceLabel}.repository must be extension or motrix`+ )+ }+ if (+ typeof evidence.path !== 'string' ||+ evidence.path.startsWith('/') ||+ evidence.path.includes('\\') ||+ evidence.path.split('/').includes('..') ||+ !testFilePattern.test(evidence.path)+ ) {+ throw new TypeError(+ `${evidenceLabel}.path must be a relative test file`+ )+ }+ if (+ typeof evidence.testName !== 'string' ||+ evidence.testName.length === 0 ||+ evidence.testName.length > 240 ||+ /[\r\n\0]/u.test(evidence.testName)+ ) {+ throw new TypeError(+ `${evidenceLabel}.testName must be one bounded single-line title`+ )+ }+ }+ }++ const actualIds = [...seen].sort()+ if (JSON.stringify(actualIds) !== JSON.stringify(expectedThreatIds)) {+ const missing = expectedThreatIds.filter((id) => !seen.has(id))+ throw new TypeError(+ `manifest must map every T01-T29 id; missing: ${missing.join(', ')}`+ )+ }+ return manifest+}++function assertInsideRepository(repository, relativePath) {+ const root = realpathSync(resolve(repository))+ const absolutePath = resolve(root, relativePath)+ if (!absolutePath.startsWith(`${root}${sep}`)) {+ throw new Error(`evidence path escapes repository: ${relativePath}`)+ }+ if (existsSync(absolutePath) && lstatSync(absolutePath).isSymbolicLink()) {+ throw new Error(+ `evidence file must not be a symbolic link: ${relativePath}`+ )+ }+ if (+ existsSync(absolutePath) &&+ !realpathSync(absolutePath).startsWith(`${root}${sep}`)+ ) {+ throw new Error(+ `evidence file resolves outside repository: ${relativePath}`+ )+ }+ return absolutePath+}++export function verifyThreatEvidence({+ manifestPath = resolve(+ scriptRoot,+ 'e2e/bridge/remote-extension-threat-evidence.json'+ ),+ motrixRepository = scriptRoot,+ extensionRepository,+}) {+ const parsed = JSON.parse(readFileSync(resolve(manifestPath), 'utf8'))+ const manifest = validateThreatEvidenceManifest(parsed)+ const roots = {+ motrix: resolve(motrixRepository),+ extension: resolve(extensionRepository),+ }++ let evidenceCount = 0+ for (const threat of manifest.threats) {+ for (const evidence of threat.evidence) {+ const absolutePath = assertInsideRepository(+ roots[evidence.repository],+ evidence.path+ )+ if (!existsSync(absolutePath) || !statSync(absolutePath).isFile()) {+ throw new Error(+ `${threat.id} evidence file is missing: ${evidence.path}`+ )+ }+ const source = readFileSync(absolutePath, 'utf8')+ if (!source.includes(evidence.testName)) {+ throw new Error(+ `${threat.id} evidence title is missing from ${evidence.path}: ${evidence.testName}`+ )+ }+ evidenceCount += 1+ }+ }+ return { threatCount: manifest.threats.length, evidenceCount }+}++function inferExtensionRepository() {+ if (process.env.MOTRIX_EXTENSION_REPO) {+ return resolve(process.env.MOTRIX_EXTENSION_REPO)+ }+ if (process.env.MOTRIX_EXTENSION_BUILD) {+ const build = resolve(process.env.MOTRIX_EXTENSION_BUILD)+ const candidate = resolve(build, '../../../..')+ const packagePath = resolve(candidate, 'package.json')+ if (existsSync(packagePath)) {+ const packageJson = JSON.parse(readFileSync(packagePath, 'utf8'))+ if (packageJson.name === 'motrix-extension') return candidate+ }+ }+ throw new Error(+ 'set MOTRIX_EXTENSION_REPO or MOTRIX_EXTENSION_BUILD to the compatible Extension checkout/build'+ )+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ try {+ const result = verifyThreatEvidence({+ extensionRepository: inferExtensionRepository(),+ })+ console.log(+ `Verified ${result.threatCount} remote Extension threats with ${result.evidenceCount} stable test references`+ )+ } catch (error) {+ console.error(error instanceof Error ? error.message : String(error))+ process.exitCode = 1+ }+}diff --git a/src/core/bridge/__tests__/bridge-connection.test.ts b/src/core/bridge/__tests__/bridge-connection.test.tsindex 83963328..703860f3 100644--- a/src/core/bridge/__tests__/bridge-connection.test.ts+++ b/src/core/bridge/__tests__/bridge-connection.test.ts@@ -86,6 +86,31 @@ describe('BridgeConnection', () => {expect(parsed.id).toBeUndefined()})+ it('contains a notification write race after the socket has closed', async () => {+ const ws = new FakeWebSocket()+ const conn = new BridgeConnection(ws as never, {+ sessionKey: 'chromium:abc',+ extensionId: 'abc',+ browser: 'chromium',+ startedAt: 1000,+ })+ conn.listen()+ ws.close()++ expect(() =>+ conn.sendNotification('$/task/progress', {+ taskId: 't1',+ bytesDone: 100,+ bytesTotal: 1000,+ speedBps: 50,+ etaSec: 18,+ phase: 'downloading',+ })+ ).not.toThrow()+ await new Promise((resolve) => setTimeout(resolve, 0))+ expect(ws.sent).toHaveLength(0)+ })+it('motrix/initialized notification flips isReady to true', async () => {const ws = new FakeWebSocket()const conn = new BridgeConnection(ws as never, {diff --git a/src/core/bridge/__tests__/fakes.ts b/src/core/bridge/__tests__/fakes.tsindex 26d9c421..de2a6130 100644--- a/src/core/bridge/__tests__/fakes.ts+++ b/src/core/bridge/__tests__/fakes.ts@@ -7,7 +7,13 @@ import {MBP1_CREDENTIALS_FILENAME,Mbp1CredentialStore,} from '../credential-store'-import type { PairDialogHandle, PairDialogRequest } from '../mbp1/pair-session'+import type { PairDialogRequest } from '../mbp1/pair-session'+import type {+ PairingPromptEnqueueResult,+ PairingPromptSessionOutcome,+ PairingPromptSettleResult,+ PairingPromptTerminalOutcome,+} from '../pairing-prompt-controller'import { type PairedClient, PairingService } from '../pairing-service'import type { TrustedExtensionRegistry } from '../trusted-extension-registry'@@ -120,17 +126,36 @@ export interface FakeDialogs {latest(): PairDialogRequest/** The display code of the most recent request. */latestCode(): string- /** How many dialogs were closed by the server. */+ /** How many prompts reached one explicit terminal outcome. */closed: number- /** Resolve the newest dialog's `dismissed`, as the user dismissing it. */+ /** Settle the newest prompt as an operator denial. */dismissLatest(): void- queue(args: PairDialogRequest): PairDialogHandle+ queue(args: PairDialogRequest): PairingPromptEnqueueResult}export function makeFakeDialogs(): FakeDialogs {const requests: PairDialogRequest[] = []- const dismissals: Array<() => void> = []+ const prompts: Array<{+ live: boolean+ resolve: (outcome: PairingPromptTerminalOutcome) => void+ terminal: Promise<PairingPromptTerminalOutcome>+ }> = []const state = { closed: 0 }++ const settle = (+ index: number,+ outcome: PairingPromptTerminalOutcome+ ): PairingPromptSettleResult => {+ const prompt = prompts[index]+ if (prompt === undefined || !prompt.live) {+ return { ok: false, reason: 'unavailable' }+ }+ prompt.live = false+ state.closed += 1+ prompt.resolve(outcome)+ return { ok: true, outcome }+ }+return {requests,get closed() {@@ -147,23 +172,29 @@ export function makeFakeDialogs(): FakeDialogs {return this.latest().code},dismissLatest() {- const dismiss = dismissals.at(-1)- if (!dismiss) {+ const index = prompts.length - 1+ if (index < 0) {throw new Error('no pairing dialog was queued')}- dismiss()+ settle(index, 'denied')},queue(args) {requests.push(args)- let resolve!: () => void- const dismissed = new Promise<void>((done) => {+ let resolve!: (outcome: PairingPromptTerminalOutcome) => void+ const terminal = new Promise<PairingPromptTerminalOutcome>((done) => {resolve = done})- dismissals.push(resolve)+ const index = prompts.length+ prompts.push({ live: true, resolve, terminal })return {- dismissed,- close: () => {- state.closed += 1+ ok: true,+ handle: {+ promptId: `fake-prompt-${index + 1}`,+ published: Promise.resolve('delivered'),+ terminal,+ settle: (outcome: PairingPromptSessionOutcome) => {+ return settle(index, outcome)+ },},}},@@ -192,7 +223,7 @@ export interface Mbp1TestWiring {appVersion: stringcredentials: Mbp1CredentialStoreisOfficialId: (browser: Browser, id: string) => boolean- queueMbp1Dialog: (args: PairDialogRequest) => PairDialogHandle+ queueMbp1Dialog: (args: PairDialogRequest) => PairingPromptEnqueueResult}}diff --git a/src/core/bridge/__tests__/mbp1-client.ts b/src/core/bridge/__tests__/mbp1-client.tsindex 5edd40fd..ae43a280 100644--- a/src/core/bridge/__tests__/mbp1-client.ts+++ b/src/core/bridge/__tests__/mbp1-client.ts@@ -12,6 +12,8 @@import { Buffer } from 'node:buffer'import { randomBytes } from 'node:crypto'+import { request as httpRequest } from 'node:http'+import { request as httpsRequest } from 'node:https'import { createMdxpConnection, type MdxpConnection } from '@motrix/mdxp'import { utf8ToBytes } from '@noble/hashes/utils.js'import type { Browser } from '@shared/protocol/bridge'@@ -116,10 +118,14 @@ export class WireClient {static async open(url: string,origin: string,- subprotocol: string | null = 'motrix-bridge.v1'+ subprotocol: string | null = 'motrix-bridge.v1',+ hostHeader?: string,+ secureTransport?: { ca: string; servername: string }): Promise<WireClient> {const ws = new WebSocket(url, subprotocol === null ? [] : subprotocol, {origin,+ ...(hostHeader === undefined ? {} : { headers: { host: hostHeader } }),+ ...secureTransport,})const client = new WireClient(ws)await new Promise<void>((resolve, reject) => {@@ -191,6 +197,12 @@ export interface PairAttemptOptions {claimedExtensionId: stringclientInstallationId?: stringticket?: ClientTicket+ /** Test-only public surface prefix, such as `/bridge`. */+ routePrefix?: string+ /** Test-only reverse-proxy Host preserved at the raw boundary. */+ hostHeader?: string+ /** Test-only trusted-CA WSS/HTTPS transport through a TLS proxy. */+ secureTransport?: { ca: string; servername: string }/*** The `verifiedOrigin` this client binds into `A_id`, when it must differ* from the origin it actually connects with. Only a misbinding test wants@@ -215,8 +227,65 @@ export interface PairHandshake {}/** Fetch a nonce the way the native-messaging host does (§4.2). */-export async function fetchNonce(port: number): Promise<string> {- const res = await fetch(`http://127.0.0.1:${port}/nonce`, {+export async function fetchNonce(+ port: number,+ options: {+ routePrefix?: string+ hostHeader?: string+ secureTransport?: { ca: string; servername: string }+ } = {}+): Promise<string> {+ const prefix = options.routePrefix ?? ''+ if (+ options.hostHeader !== undefined ||+ options.secureTransport !== undefined+ ) {+ return new Promise((resolve, reject) => {+ const requestFn =+ 'secureTransport' in options && options.secureTransport !== undefined+ ? httpsRequest+ : httpRequest+ const request = requestFn(+ {+ host: '127.0.0.1',+ port,+ path: `${prefix}/nonce`,+ method: 'POST',+ headers: {+ 'x-motrix-bridge': '1',+ 'content-length': '0',+ ...(options.hostHeader === undefined+ ? {}+ : { host: options.hostHeader }),+ },+ ...('secureTransport' in options ? options.secureTransport : {}),+ },+ (response) => {+ let body = ''+ response.setEncoding('utf8')+ response.on('data', (chunk) => {+ body += chunk+ })+ response.once('end', () => {+ if (response.statusCode !== 200) {+ reject(+ new Error(`POST /nonce failed with ${response.statusCode}`)+ )+ return+ }+ try {+ resolve((JSON.parse(body) as { nonce: string }).nonce)+ } catch (error) {+ reject(error)+ }+ })+ }+ )+ request.once('error', reject)+ request.end()+ })+ }+ const res = await fetch(`http://127.0.0.1:${port}${prefix}/nonce`, {method: 'POST',headers: { 'x-motrix-bridge': '1' },})@@ -235,10 +304,15 @@ export async function fetchNonce(port: number): Promise<string> {export async function startPair(opts: PairAttemptOptions): Promise<PairHandshake> {- const pairNonce = await fetchNonce(opts.port)+ const pairNonce = await fetchNonce(opts.port, opts)+ const prefix = opts.routePrefix ?? ''+ const protocol = opts.secureTransport === undefined ? 'ws' : 'wss'const wire = await WireClient.open(- `ws://127.0.0.1:${opts.port}/pair?nonce=${pairNonce}`,- opts.origin+ `${protocol}://127.0.0.1:${opts.port}${prefix}/pair?nonce=${pairNonce}`,+ opts.origin,+ 'motrix-bridge.v1',+ opts.hostHeader,+ opts.secureTransport)const clientInstallationId = opts.clientInstallationId ?? 'install-1'@@ -464,10 +538,18 @@ export async function reconnect(opts: {/** Corrupts the MAC, for the bad-MAC case. */corruptMac?: booleanquery?: string+ routePrefix?: string+ hostHeader?: string+ secureTransport?: { ca: string; servername: string }}): Promise<{ wire: WireClient; channel: EnvelopeChannel }> {+ const prefix = opts.routePrefix ?? ''+ const protocol = opts.secureTransport === undefined ? 'ws' : 'wss'const wire = await WireClient.open(- `ws://127.0.0.1:${opts.port}/v1${opts.query ?? ''}`,- opts.origin+ `${protocol}://127.0.0.1:${opts.port}${prefix}/v1${opts.query ?? ''}`,+ opts.origin,+ 'motrix-bridge.v1',+ opts.hostHeader,+ opts.secureTransport)const challenge = await wire.takeJson<{ type: string; S: string }>()if (challenge.type !== 'reconnectChallenge') {diff --git a/src/core/bridge/__tests__/mbp1-transport.test.ts b/src/core/bridge/__tests__/mbp1-transport.test.tsindex 7d49c552..0eb21697 100644--- a/src/core/bridge/__tests__/mbp1-transport.test.ts+++ b/src/core/bridge/__tests__/mbp1-transport.test.ts@@ -2,6 +2,8 @@ import { createServer as createHttpServer } from 'node:http'import { connect as netConnect } from 'node:net'import { MAX_ENVELOPE_PLAINTEXT_BYTES } from '@core/bridge/mbp1/envelope'import type { EnvelopeChannel } from '@core/bridge/mbp1/envelope-message-stream'+import type { PairDialogRequest } from '@core/bridge/mbp1/pair-session'+import type { PairingPromptEnqueueResult } from '@core/bridge/pairing-prompt-controller'import {BRIDGE_CANDIDATE_PORTS,MAX_WEBSOCKET_PAYLOAD_BYTES,@@ -52,17 +54,25 @@ interface Harness {port: numberdialogs: FakeDialogscredentials: Awaited<ReturnType<typeof makeTempCredentialStore>>- authenticated: Array<ClientIdentity & { kind: 'extension' }>+ authenticated: Array<{+ identity: ClientIdentity & { kind: 'extension' }+ credentialId: string+ }>}async function makeHarness(overrides: {allowlist?: ReadonlyArray<[Browser, string]>host?: string+ queueMbp1Dialog?: (+ args: PairDialogRequest,+ dialogs: FakeDialogs+ ) => PairingPromptEnqueueResult+ extensionMbp1RoutesEnabled?: boolean} = {}): Promise<Harness> {const dialogs = makeFakeDialogs()- const authenticated: Array<ClientIdentity & { kind: 'extension' }> = []+ const authenticated: Harness['authenticated'] = []const credentials = await makeTempCredentialStore()const server = new WebSocketBridgeServer({pairing: makeStatefulFakePairing(),@@ -78,8 +88,11 @@ async function makeHarness(isOfficialId: makeAllowlist(overrides.allowlist ?? [['chromium', OFFICIAL_ID]]),- queueMbp1Dialog: (args) => dialogs.queue(args),- onExtensionAuthenticated: (identity) => authenticated.push(identity),+ queueMbp1Dialog: (args) =>+ overrides.queueMbp1Dialog?.(args, dialogs) ?? dialogs.queue(args),+ extensionMbp1RoutesEnabled: overrides.extensionMbp1RoutesEnabled,+ onExtensionAuthenticated: (identity, credentialId) =>+ authenticated.push({ identity, credentialId }),})server.registerReadMethods({taskManager: { getAll: () => [], getById: () => undefined },@@ -455,7 +468,7 @@ describe('§4 ingress demux', () => {await expect(wire.closed).resolves.toMatchObject({ code: 1009 })})- it('refuses both routes when MBP1 is not wired', async () => {+ it('refuses all four Extension routes when MBP1 is not wired', async () => {const bare = new WebSocketBridgeServer({pairing: makeStatefulFakePairing(),registry: makeFakeRegistry(),@@ -479,10 +492,47 @@ describe('§4 ingress demux', () => {expect((await fetch(`http://127.0.0.1:${port}/discovery`)).status).toBe(404)+ expect(+ (+ await fetch(`http://127.0.0.1:${port}/nonce`, {+ method: 'POST',+ headers: { 'X-Motrix-Bridge': '1' },+ })+ ).status+ ).toBe(404)} finally {await bare.stop()}})++ it('keeps all four routes closed behind the composition-root kill switch', async () => {+ const closed = await makeHarness({ extensionMbp1RoutesEnabled: false })+ try {+ const nonce = closed.server.issuePairNonce()+ await expect(+ WireClient.open(+ `ws://127.0.0.1:${closed.port}/pair?nonce=${nonce}`,+ OFFICIAL_ORIGIN+ )+ ).rejects.toThrow()+ await expect(+ WireClient.open(`ws://127.0.0.1:${closed.port}/v1`, OFFICIAL_ORIGIN)+ ).rejects.toThrow()+ expect(+ (await fetch(`http://127.0.0.1:${closed.port}/discovery`)).status+ ).toBe(404)+ expect(+ (+ await fetch(`http://127.0.0.1:${closed.port}/nonce`, {+ method: 'POST',+ headers: { 'X-Motrix-Bridge': '1' },+ })+ ).status+ ).toBe(404)+ } finally {+ await closed.server.stop()+ }+ })})// ---------------------------------------------------------------------------@@ -792,7 +842,14 @@ describe('§6 first pair over the wire', () => {expect(session).toBeDefined()expect(Array.from(h.server.iterSessions())).toHaveLength(1)expect(h.authenticated).toEqual([- { kind: 'extension', browser: 'chromium', extensionId: OFFICIAL_ID },+ {+ identity: {+ kind: 'extension',+ browser: 'chromium',+ extensionId: OFFICIAL_ID,+ },+ credentialId: credential.credentialId,+ },])conn.dispose()@@ -1059,7 +1116,7 @@ describe('§6 first pair over the wire', () => {await hs.wire.closed})- it('aborts when the user dismisses the dialog', async () => {+ it('reports an authenticated operator denial distinctly from shutdown', async () => {const hs = await startPair({port: h.port,origin: OFFICIAL_ORIGIN,@@ -1070,7 +1127,7 @@ describe('§6 first pair over the wire', () => {h.dialogs.dismissLatest()const frame = await hs.wire.takeJson<{ type: string; code: string }>()- expect(frame).toMatchObject({ type: 'pairError', code: 'aborted' })+ expect(frame).toMatchObject({ type: 'pairError', code: 'denied' })await hs.wire.closed})@@ -1176,6 +1233,14 @@ describe('R3 adoption boundary', () => {const second = await pairFully(h)const secondSession = h.server.getSession(`chromium:${OFFICIAL_ID}`)+ expect(second.credential.credentialId).not.toBe(+ first.credential.credentialId+ )+ expect(h.authenticated.map(({ credentialId }) => credentialId)).toEqual([+ first.credential.credentialId,+ second.credential.credentialId,+ ])+// The key never went empty, and it now holds the newcomer.expect(secondSession).toBeDefined()expect(secondSession).not.toBe(firstSession)@@ -1276,6 +1341,91 @@ describe('R4 §7.3 flood control', () => {expect(h.dialogs.requests).toHaveLength(1)})+ it('does not count a typed prompt refusal that published no code', async () => {+ await h.server.stop()+ let refuseNext = true+ h = await makeHarness({+ queueMbp1Dialog: (args, dialogs) => {+ if (refuseNext) {+ refuseNext = false+ return { ok: false, reason: 'capacity' }+ }+ return dialogs.queue(args)+ },+ })++ await expect(+ startPair({+ port: h.port,+ origin: OFFICIAL_ORIGIN,+ browser: 'chromium',+ claimedExtensionId: OFFICIAL_ID,+ })+ ).rejects.toMatchObject({+ frame: { type: 'pairError', code: 'pairingFailed' },+ })++ const peer = peerFor(11)+ const next = await startPair({+ port: h.port,+ origin: peer.origin,+ browser: 'chromium',+ claimedExtensionId: peer.id,+ })+ expect(h.dialogs.requests).toHaveLength(1)+ next.wire.ws.close()+ })++ it.each([+ ['failed', () => Promise.resolve<'failed'>('failed')],+ [+ 'rejected',+ () =>+ Promise.reject<'failed'>(new Error('secret publisher failure detail')),+ ],+ ] as const)(+ 'does not count a %s prompt publisher or leak an unhandled rejection',+ async (_label, publication) => {+ await h.server.stop()+ let replaceNextPublication = true+ h = await makeHarness({+ queueMbp1Dialog: (args, dialogs) => {+ const result = dialogs.queue(args)+ if (!result.ok || !replaceNextPublication) return result+ replaceNextPublication = false+ return {+ ok: true,+ handle: {+ ...result.handle,+ published: publication(),+ },+ }+ },+ })++ await expect(+ startPair({+ port: h.port,+ origin: OFFICIAL_ORIGIN,+ browser: 'chromium',+ claimedExtensionId: OFFICIAL_ID,+ })+ ).rejects.toMatchObject({+ frame: { type: 'pairError', code: 'pairingFailed' },+ })++ const peer = peerFor(12)+ const next = await startPair({+ port: h.port,+ origin: peer.origin,+ browser: 'chromium',+ claimedExtensionId: peer.id,+ })+ expect(h.dialogs.requests).toHaveLength(2)+ next.wire.ws.close()+ }+ )+it('answers busy — not rateLimited — for a same-origin duplicate with no failures', async () => {// The two codes are distinct §11 rows and mean different things to the// client; conflating them would tell a caller to back off for 30 s when it@@ -1454,7 +1604,10 @@ describe('§8 reconnect over the wire', () => {expect(result.server.name).toBe('motrix')expect(h.server.getSession(`chromium:${OFFICIAL_ID}`)).toBeDefined()- expect(h.authenticated).toHaveLength(2)+ expect(h.authenticated.map(({ credentialId }) => credentialId)).toEqual([+ paired.credential.credentialId,+ paired.credential.credentialId,+ ])conn.dispose()back.wire.ws.close()@@ -1505,6 +1658,65 @@ describe('§8 reconnect over the wire', () => {conn.dispose()})+ it('cuts authorization synchronously and retains the identity gate when durable deletion fails', async () => {+ const paired = await pairFully(h)+ const conn = mdxpOverChannel(paired.wire, paired.channel)+ await conn.sendRequest('motrix/initialize', initializeParams(OFFICIAL_ID))+ const revokedNotice = vi.fn()+ conn.onNotification(Notifications.PairRevoked, revokedNotice)++ const identity = {+ kind: 'extension' as const,+ browser: 'chromium' as const,+ extensionId: OFFICIAL_ID,+ }+ const durableFailure = new Error('secret durable path')+ vi.spyOn(h.credentials, 'revokeExtensionIdentity').mockRejectedValueOnce(+ durableFailure+ )++ const lease = h.server.beginExtensionRevocation(identity)++ // No await exists between the operator action and this cutoff. The live+ // transport is already unauthorized while durable storage is untouched.+ await expect(conn.sendRequest('task/list', {})).rejects.toMatchObject({+ code: ErrorCodes.PermissionDenied,+ })+ await expect(+ h.server.deleteExtensionAuthorization(lease, 'user-revoked')+ ).rejects.toBe(durableFailure)+ expect(revokedNotice).not.toHaveBeenCalled()+ expect(+ h.credentials.findForAuth(paired.credential.credentialId)+ ).not.toBeNull()+ await expect(paired.wire.closed).resolves.toMatchObject({+ code: expect.any(Number),+ })++ // Failure keeps the same verified identity closed. The retry reuses the+ // nominal lease and only the successful durable delete permits completion.+ await expect(+ WireClient.open(`ws://127.0.0.1:${h.port}/v1`, OFFICIAL_ORIGIN)+ ).rejects.toThrow('unexpected-response 401')+ await expect(+ h.server.deleteExtensionAuthorization(lease, 'user-revoked')+ ).resolves.toBe(1)+ h.server.completeExtensionRevocation(lease)++ await expect(+ reconnect({+ port: h.port,+ origin: OFFICIAL_ORIGIN,+ instanceId: INSTANCE_ID,+ credential: paired.credential,+ })+ ).rejects.toMatchObject({+ frame: { type: 'pairError', code: 'authFailed' },+ })++ conn.dispose()+ })+it('cancels same-origin pre-auth sessions and refuses replacement handshakes throughout revoke', async () => {// Both sockets are admitted before revoke but deliberately remain// pre-authenticated: `/pair` is silent, while `/v1` has only received thediff --git a/src/core/bridge/__tests__/web-socket-bridge-server.test.ts b/src/core/bridge/__tests__/web-socket-bridge-server.test.tsindex 6b5161ef..220603f5 100644--- a/src/core/bridge/__tests__/web-socket-bridge-server.test.ts+++ b/src/core/bridge/__tests__/web-socket-bridge-server.test.ts@@ -19,6 +19,7 @@ import {WS_CLOSE_PROTOCOL_ERROR,} from '@core/bridge/web-socket-bridge-server'import type { WebSocketLike } from '@core/bridge/web-socket-message-stream'+import type { ClientIdentity } from '@shared/protocol/bridge'import { EngineState } from '@shared/types/engine'import { TaskStatus } from '@shared/types/task'import { makeDownloadTask } from '@test-utils/task'@@ -81,6 +82,28 @@ describe('WebSocketBridgeServer upgrade gates', () => {let server: WebSocketBridgeServerlet port: number+ async function restartWithIdentityGate(+ canAdmitExtensionIdentity: NonNullable<+ ConstructorParameters<+ typeof WebSocketBridgeServer+ >[0]['canAdmitExtensionIdentity']+ >+ ): Promise<void> {+ await server.stop()+ const mbp1 = await makeMbp1TestWiring([['chromium', EXTENSION_ID]])+ server = new WebSocketBridgeServer({+ pairing: makeStatefulFakePairing(),+ registry: makeFakeRegistry(),+ motrixVersion: '2.0',+ runtime: 'electron',+ ffmpegAvailable: true,+ localToken: 'test-token',+ ...mbp1.options,+ canAdmitExtensionIdentity,+ })+ port = await server.start()+ }+beforeEach(async () => {// Deliberately WITHOUT the six MBP1 options: this is a shell that has not// wired MBP1, and both extension routes must fail closed rather than fall@@ -140,6 +163,71 @@ describe('WebSocketBridgeServer upgrade gates', () => {})).resolves.toBe(false)})++ it('gates /pair before consuming its one-shot nonce', async () => {+ let admissible = false+ const gate = vi.fn(() => admissible)+ await restartWithIdentityGate(gate)+ const nonce = server.issuePairNonce()+ const path = `/pair?nonce=${nonce}`++ await expect(+ tryUpgrade(port, path, {+ origin: ORIGIN,+ subprotocol: 'motrix-bridge.v1',+ })+ ).resolves.toBe(false)+ expect(gate).toHaveBeenLastCalledWith({+ kind: 'extension',+ browser: 'chromium',+ extensionId: EXTENSION_ID,+ })++ admissible = true+ await expect(+ tryUpgrade(port, path, {+ origin: ORIGIN,+ subprotocol: 'motrix-bridge.v1',+ })+ ).resolves.toBe(true)+ })++ it('gates /v1 before spending reconnect admission allowance', async () => {+ let admissible = false+ await restartWithIdentityGate(() => admissible)++ // Ten rejected attempts would exhaust the normal per-Origin allowance if+ // the shell gate ran after reconnect admission.+ for (let attempt = 0; attempt < 10; attempt += 1) {+ await expect(+ tryUpgrade(port, '/v1', {+ origin: ORIGIN,+ subprotocol: 'motrix-bridge.v1',+ })+ ).resolves.toBe(false)+ }++ admissible = true+ await expect(+ tryUpgrade(port, '/v1', {+ origin: ORIGIN,+ subprotocol: 'motrix-bridge.v1',+ })+ ).resolves.toBe(true)+ })++ it('fails closed when the shell admission gate throws', async () => {+ await restartWithIdentityGate(() => {+ throw new Error('projection unavailable')+ })++ await expect(+ tryUpgrade(port, `/pair?nonce=${server.issuePairNonce()}`, {+ origin: ORIGIN,+ subprotocol: 'motrix-bridge.v1',+ })+ ).resolves.toBe(false)+ })})describe('WebSocketBridgeServer.start() bind guard', () => {@@ -359,13 +447,19 @@ class FakeExtensionSocket extends EventEmitter {describe('WebSocketBridgeServer.adoptAuthenticatedSession — envelope fault close codes', () => {let server: WebSocketBridgeServerconst KEY = new Uint8Array(32).fill(3)+ const CREDENTIAL_ID = 'credential-used-by-this-transport'const IDENTITY = {kind: 'extension' as const,browser: 'chromium' as const,extensionId: EXTENSION_ID,}+ let authenticated: Array<{+ identity: ClientIdentity & { kind: 'extension' }+ credentialId: string+ }>beforeEach(async () => {+ authenticated = []server = new WebSocketBridgeServer({pairing: makeStatefulFakePairing(),registry: makeFakeRegistry(),@@ -373,6 +467,9 @@ describe('WebSocketBridgeServer.adoptAuthenticatedSession — envelope fault cloruntime: 'electron',ffmpegAvailable: true,localToken: 'test-token',+ onExtensionAuthenticated: (identity, credentialId) => {+ authenticated.push({ identity, credentialId })+ },})await server.start()})@@ -383,12 +480,17 @@ describe('WebSocketBridgeServer.adoptAuthenticatedSession — envelope fault cloit('closes with the usage-limit code — not protocol-error or internal-error — when an inbound §10 bound is reached', () => {const ws = new FakeExtensionSocket()- server.adoptAuthenticatedSession(ws.asLike(), IDENTITY, {- sealer: new EnvelopeSealer(KEY, DIR_S2C),- // Already AT the frame-count bound: the very next open() throws- // EnvelopeLimitError before it even looks at the frame's contents.- opener: new EnvelopeOpener(KEY, DIR_C2S, MAX_ENVELOPE_FRAMES),- })+ server.adoptAuthenticatedSession(+ ws.asLike(),+ IDENTITY,+ {+ sealer: new EnvelopeSealer(KEY, DIR_S2C),+ // Already AT the frame-count bound: the very next open() throws+ // EnvelopeLimitError before it even looks at the frame's contents.+ opener: new EnvelopeOpener(KEY, DIR_C2S, MAX_ENVELOPE_FRAMES),+ },+ CREDENTIAL_ID+ )ws.emit('message', Buffer.alloc(8 + 16), true)@@ -397,10 +499,15 @@ describe('WebSocketBridgeServer.adoptAuthenticatedSession — envelope fault cloit('still closes with the protocol-error code for an ordinary peer violation', () => {const ws = new FakeExtensionSocket()- server.adoptAuthenticatedSession(ws.asLike(), IDENTITY, {- sealer: new EnvelopeSealer(KEY, DIR_S2C),- opener: new EnvelopeOpener(KEY, DIR_C2S),- })+ server.adoptAuthenticatedSession(+ ws.asLike(),+ IDENTITY,+ {+ sealer: new EnvelopeSealer(KEY, DIR_S2C),+ opener: new EnvelopeOpener(KEY, DIR_C2S),+ },+ CREDENTIAL_ID+ )// §10: a text frame after channel activation is a protocol violation.ws.emit('message', Buffer.from('not an envelope'), false)@@ -410,14 +517,19 @@ describe('WebSocketBridgeServer.adoptAuthenticatedSession — envelope fault cloit('closes with the usage-limit code when an OUTBOUND §10 bound is reached', () => {const ws = new FakeExtensionSocket()- server.adoptAuthenticatedSession(ws.asLike(), IDENTITY, {- // Already AT the frame-count bound: the very next seal() throws, and no- // later one can ever succeed, so the connection must be re-established- // with fresh keys (§8) — the one seal failure that is a connection-level- // event rather than a single failed write.- sealer: new EnvelopeSealer(KEY, DIR_S2C, MAX_ENVELOPE_FRAMES),- opener: new EnvelopeOpener(KEY, DIR_C2S),- })+ server.adoptAuthenticatedSession(+ ws.asLike(),+ IDENTITY,+ {+ // Already AT the frame-count bound: the very next seal() throws, and no+ // later one can ever succeed, so the connection must be re-established+ // with fresh keys (§8) — the one seal failure that is a connection-level+ // event rather than a single failed write.+ sealer: new EnvelopeSealer(KEY, DIR_S2C, MAX_ENVELOPE_FRAMES),+ opener: new EnvelopeOpener(KEY, DIR_C2S),+ },+ CREDENTIAL_ID+ )const session = server.getSession(`chromium:${EXTENSION_ID}`)if (!session) throw new Error('session was not registered')@@ -433,10 +545,15 @@ describe('WebSocketBridgeServer.adoptAuthenticatedSession — envelope fault clo// it. The refused application frame can desynchronize request state, so// the session fails closed with 1011 rather than staying half-usable.const ws = new FakeExtensionSocket()- server.adoptAuthenticatedSession(ws.asLike(), IDENTITY, {- sealer: new EnvelopeSealer(KEY, DIR_S2C),- opener: new EnvelopeOpener(KEY, DIR_C2S),- })+ server.adoptAuthenticatedSession(+ ws.asLike(),+ IDENTITY,+ {+ sealer: new EnvelopeSealer(KEY, DIR_S2C),+ opener: new EnvelopeOpener(KEY, DIR_C2S),+ },+ CREDENTIAL_ID+ )const session = server.getSession(`chromium:${EXTENSION_ID}`)if (!session) throw new Error('session was not registered')@@ -448,4 +565,22 @@ describe('WebSocketBridgeServer.adoptAuthenticatedSession — envelope fault cloexpect(ws.readyState).toBe(3)expect(ws.sent).toHaveLength(0)})++ it('publishes the exact authenticating credential in the adoption tick', () => {+ const ws = new FakeExtensionSocket()++ server.adoptAuthenticatedSession(+ ws.asLike(),+ IDENTITY,+ {+ sealer: new EnvelopeSealer(KEY, DIR_S2C),+ opener: new EnvelopeOpener(KEY, DIR_C2S),+ },+ CREDENTIAL_ID+ )++ expect(authenticated).toEqual([+ { identity: IDENTITY, credentialId: CREDENTIAL_ID },+ ])+ })})diff --git a/src/core/bridge/bridge-connection.ts b/src/core/bridge/bridge-connection.tsindex 196d90bf..f94f382c 100644--- a/src/core/bridge/bridge-connection.ts+++ b/src/core/bridge/bridge-connection.ts@@ -116,7 +116,21 @@ export class BridgeConnection {/** Send a typed notification to the peer. */sendNotification: MdxpConnection['sendNotification'] = (name, params) => {- this.mdxp.sendNotification(name, params)+ // Notifications are best-effort by JSON-RPC definition. The typed MDXP+ // wrapper intentionally exposes a void return, while vscode-jsonrpc's raw+ // writer returns a Promise that rejects if the socket closes between+ // session lookup and write. Always observe that Promise here so a routine+ // disconnect/revoke cannot become an unhandled process rejection.+ try {+ const pending =+ params === undefined+ ? this.mdxp.raw.sendNotification(name as string)+ : this.mdxp.raw.sendNotification(name as string, params)+ void pending.catch(() => {})+ } catch {+ // The connection may already be disposed. There is no request id to+ // retry or report, and a later session must never receive this event.+ }}dispose(): void {diff --git a/src/core/bridge/bridge-data-dir-lock.test.ts b/src/core/bridge/bridge-data-dir-lock.test.tsnew file mode 100644index 00000000..81fbc05c--- /dev/null+++ b/src/core/bridge/bridge-data-dir-lock.test.ts@@ -0,0 +1,647 @@+import { type ChildProcessWithoutNullStreams, spawn } from 'node:child_process'+import fs from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { pathToFileURL } from 'node:url'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import {+ acquireBridgeDataDirLock,+ BRIDGE_DATA_DIR_LOCK_FILE_NAME,+ BRIDGE_DATA_DIR_LOCK_RECOVERY_MODE,+ BRIDGE_DATA_DIR_LOCK_UNAVAILABLE,+ type BridgeDataDirLockAcquireOptions,+} from './bridge-data-dir-lock'++interface LockWorker {+ readonly child: ChildProcessWithoutNullStreams+ readonly nextLine: () => Promise<string>+ readonly send: (command: string) => void+}++const workers = new Set<ChildProcessWithoutNullStreams>()+const closedWorkers = new WeakSet<ChildProcessWithoutNullStreams>()+const TEST_OWNERSHIP_EPOCH = 'E'.repeat(43)++describe('bridge data-directory lock', () => {+ let directory: string+ let lockPath: string++ beforeEach(async () => {+ directory = await fs.mkdtemp(path.join(os.tmpdir(), 'motrix-bridge-lock-'))+ lockPath = path.join(directory, BRIDGE_DATA_DIR_LOCK_FILE_NAME)+ })++ afterEach(async () => {+ const activeWorkers = [...workers]+ for (const child of activeWorkers) {+ if (child.exitCode === null && child.signalCode === null) {+ child.kill('SIGKILL')+ }+ }+ await Promise.all(activeWorkers.map((child) => waitForExit(child)))+ workers.clear()+ await fs.rm(directory, { recursive: true, force: true })+ })++ it('creates one bounded 0600 lock and returns an idempotent nominal handle', async () => {+ const handle = await acquireBridgeDataDirLock(directory)+ const raw = await fs.readFile(lockPath)+ const document = JSON.parse(raw.toString('utf-8')) as Record<+ string,+ unknown+ >++ expect(raw.byteLength).toBeGreaterThan(0)+ expect(raw.byteLength).toBeLessThanOrEqual(256)+ expect(Object.keys(document).sort()).toEqual([+ 'ownerNonce',+ 'ownershipEpoch',+ 'version',+ ])+ expect(document.version).toBe(1)+ expect(document.ownerNonce).toMatch(/^[A-Za-z0-9_-]{43}$/u)+ expect(document.ownershipEpoch).toBeNull()+ if (process.platform !== 'win32') {+ expect((await fs.stat(lockPath)).mode & 0o777).toBe(0o600)+ }++ await expectFixedFailure(acquireBridgeDataDirLock(directory), directory)+ await Promise.all([handle.release(), handle.release(), handle.release()])+ await handle.release()+ await expect(fs.lstat(lockPath)).rejects.toMatchObject({ code: 'ENOENT' })++ const replacement = await acquireBridgeDataDirLock(directory)+ await replacement.release()+ })++ it('does not let authorized recovery steal a live in-process claim', async () => {+ const handle = await acquireBridgeDataDirLock(directory)+ const assertExclusiveProcessOwnership = vi.fn(() => true)++ await expectFixedFailure(+ acquireBridgeDataDirLock(directory, {+ recoverExisting: {+ ownershipEpoch: TEST_OWNERSHIP_EPOCH,+ assertExclusiveProcessOwnership,+ },+ }),+ directory+ )+ expect(assertExclusiveProcessOwnership).not.toHaveBeenCalled()+ await handle.release()+ })++ it.runIf(process.platform !== 'win32')(+ 'commits release once unlink succeeds even if the directory sync fails',+ async () => {+ const handle = await acquireBridgeDataDirLock(directory)+ const probe = await fs.open(directory, 'r')+ const fileHandlePrototype = Object.getPrototypeOf(probe) as {+ sync(): Promise<void>+ }+ await probe.close()+ const syncSpy = vi+ .spyOn(fileHandlePrototype, 'sync')+ .mockRejectedValue(new Error('synthetic directory sync failure'))++ try {+ await handle.release()+ } finally {+ syncSpy.mockRestore()+ }+ await expect(fs.lstat(lockPath)).rejects.toMatchObject({ code: 'ENOENT' })+ const next = await acquireBridgeDataDirLock(directory)+ await next.release()+ }+ )++ it('shares the live claim across duplicate ESM module instances', async () => {+ const worker = spawnLockWorker(directory, 'duplicate-module')+ await expect(worker.nextLine()).resolves.toBe('ready')+ worker.send('go')+ await expect(worker.nextLine()).resolves.toBe(+ `duplicate-protected:0:${BRIDGE_DATA_DIR_LOCK_UNAVAILABLE}`+ )+ await waitForExit(worker.child)+ })++ it.runIf(process.platform !== 'win32')(+ 'canonicalizes directory aliases before applying the module claim',+ async () => {+ const alias = path.join(directory, 'same-directory-alias')+ await fs.symlink(directory, alias, 'dir')+ const handle = await acquireBridgeDataDirLock(directory)++ await expectFixedFailure(acquireBridgeDataDirLock(alias), directory)+ await handle.release()+ }+ )++ it('does not let an old released handle remove its successor', async () => {+ const old = await acquireBridgeDataDirLock(directory)+ await old.release()+ const current = await acquireBridgeDataDirLock(directory)++ await old.release()+ await expectFixedFailure(acquireBridgeDataDirLock(directory), directory)+ await current.release()+ })++ it.runIf(process.platform !== 'win32')(+ 'refuses to release a replaced path even when its content looks valid',+ async () => {+ const handle = await acquireBridgeDataDirLock(directory)+ const displacedPath = `${lockPath}.displaced`+ await fs.rename(lockPath, displacedPath)+ const forged = JSON.stringify({+ version: 1,+ ownerNonce: 'A'.repeat(43),+ ownershipEpoch: null,+ })+ await fs.writeFile(lockPath, forged, { mode: 0o600 })++ await expectFixedFailure(handle.release(), directory)+ await expect(fs.readFile(lockPath, 'utf-8')).resolves.toBe(forged)+ expect((await fs.lstat(displacedPath)).isFile()).toBe(true)++ await fs.unlink(lockPath)+ await fs.rename(displacedPath, lockPath)+ await handle.release()+ }+ )++ it('fails with one redacted error while another process owns the lock', async () => {+ const worker = spawnLockWorker(directory, 'hold')+ await expect(worker.nextLine()).resolves.toBe('ready')+ worker.send('go')+ await expect(worker.nextLine()).resolves.toBe('acquired')++ await expectFixedFailure(acquireBridgeDataDirLock(directory), directory)+ worker.send('release')+ await expect(worker.nextLine()).resolves.toBe('released')+ await waitForExit(worker.child)+ })++ it('keeps crash residue fail-closed by default and recovers only with external authority', async () => {+ const worker = spawnLockWorker(directory, 'crash')+ await expect(worker.nextLine()).resolves.toBe('ready')+ worker.send('go')+ await expect(worker.nextLine()).resolves.toBe('acquired')+ await waitForExit(worker.child)+ const residue = await fs.readFile(lockPath)++ await expectFixedFailure(acquireBridgeDataDirLock(directory), directory)+ await expectFixedFailure(+ acquireBridgeDataDirLock(directory, {+ recoverExisting: {+ ownershipEpoch: TEST_OWNERSHIP_EPOCH,+ assertExclusiveProcessOwnership: () => false,+ },+ }),+ directory+ )+ await expectFixedFailure(+ acquireBridgeDataDirLock(directory, {+ recoverExisting: {+ ownershipEpoch: TEST_OWNERSHIP_EPOCH,+ assertExclusiveProcessOwnership: () => {+ throw new Error('private-process-detail')+ },+ },+ }),+ directory+ )+ expect(await fs.readFile(lockPath)).toEqual(residue)+ const assertExclusiveProcessOwnership = vi.fn(() => true)+ const recovery = acquireBridgeDataDirLock(directory, {+ recoverExisting: {+ ownershipEpoch: TEST_OWNERSHIP_EPOCH,+ assertExclusiveProcessOwnership,+ },+ })++ if (+ BRIDGE_DATA_DIR_LOCK_RECOVERY_MODE ===+ 'external-single-instance-authority'+ ) {+ const recovered = await recovery+ expect(assertExclusiveProcessOwnership).toHaveBeenCalledTimes(1)+ expect(await fs.readFile(lockPath)).not.toEqual(residue)+ expect(await fs.readdir(directory)).toEqual([+ BRIDGE_DATA_DIR_LOCK_FILE_NAME,+ ])+ await recovered.release()+ } else {+ await expectFixedFailure(recovery, directory)+ expect(assertExclusiveProcessOwnership).not.toHaveBeenCalled()+ expect(await fs.readFile(lockPath)).toEqual(residue)+ }+ })++ it.runIf(+ BRIDGE_DATA_DIR_LOCK_RECOVERY_MODE === 'external-single-instance-authority'+ )('allows only one authorized recovery contender to acquire', async () => {+ const crashed = spawnLockWorker(directory, 'crash')+ await expect(crashed.nextLine()).resolves.toBe('ready')+ crashed.send('go')+ await expect(crashed.nextLine()).resolves.toBe('acquired')+ await waitForExit(crashed.child)++ const first = spawnLockWorker(directory, 'recover')+ const second = spawnLockWorker(directory, 'recover')+ await Promise.all([+ expect(first.nextLine()).resolves.toBe('ready'),+ expect(second.nextLine()).resolves.toBe('ready'),+ ])+ first.send('go')+ second.send('go')+ const outcomes = await Promise.all([first.nextLine(), second.nextLine()])++ expect([...outcomes].sort()).toEqual([+ 'acquired',+ `failed:${BRIDGE_DATA_DIR_LOCK_UNAVAILABLE}`,+ ])+ const winner = outcomes[0] === 'acquired' ? first : second+ const loser = winner === first ? second : first++ const delayed = spawnLockWorker(directory, 'recover')+ await expect(delayed.nextLine()).resolves.toBe('ready')+ delayed.send('go')+ await expect(delayed.nextLine()).resolves.toBe(+ `failed:${BRIDGE_DATA_DIR_LOCK_UNAVAILABLE}`+ )+ winner.send('release')+ await expect(winner.nextLine()).resolves.toBe('released')+ await Promise.all([+ waitForExit(winner.child),+ waitForExit(loser.child),+ waitForExit(delayed.child),+ ])+ })++ it.runIf(+ BRIDGE_DATA_DIR_LOCK_RECOVERY_MODE === 'external-single-instance-authority'+ )(+ 'resumes every durable interrupted-recovery shape in a new ownership epoch',+ async () => {+ const guardPath = path.join(directory, '.motrix-bridge.lock.recovery')+ const recoveryNonce = 'Q'.repeat(43)+ const quarantinePath = `${lockPath}.stale-${recoveryNonce}`+ const oldLock = {+ version: 1,+ ownerNonce: 'L'.repeat(43),+ ownershipEpoch: null,+ }+ const replacementLock = {+ version: 1,+ ownerNonce: 'N'.repeat(43),+ ownershipEpoch: 'O'.repeat(43),+ }+ const guard = {+ version: 1,+ recoveryNonce,+ ownershipEpoch: 'O'.repeat(43),+ }+ const stages: Array<() => Promise<void>> = [+ async () => {+ await writePrivateJson(lockPath, oldLock)+ },+ async () => {+ await writePrivateJson(lockPath, oldLock)+ await fs.link(lockPath, quarantinePath)+ },+ async () => {+ await writePrivateJson(lockPath, oldLock)+ await fs.link(lockPath, quarantinePath)+ await fs.unlink(lockPath)+ },+ async () => {+ await writePrivateJson(quarantinePath, oldLock)+ await writePrivateJson(lockPath, replacementLock)+ },+ async () => {+ await writePrivateJson(lockPath, replacementLock)+ },+ async () => undefined,+ ]++ for (const createStage of stages) {+ await writePrivateJson(guardPath, guard)+ await createStage()++ const recovered = await acquireBridgeDataDirLock(+ directory,+ authorizedRecovery(TEST_OWNERSHIP_EPOCH)+ )+ expect(await fs.readdir(directory)).toEqual([+ BRIDGE_DATA_DIR_LOCK_FILE_NAME,+ ])+ await recovered.release()+ expect(await fs.readdir(directory)).toEqual([])+ }+ }+ )++ it.runIf(+ BRIDGE_DATA_DIR_LOCK_RECOVERY_MODE === 'external-single-instance-authority'+ )(+ 'does not resume a recovery guard from the current ownership epoch',+ async () => {+ const guardPath = path.join(directory, '.motrix-bridge.lock.recovery')+ await writePrivateJson(guardPath, {+ version: 1,+ recoveryNonce: 'Q'.repeat(43),+ ownershipEpoch: TEST_OWNERSHIP_EPOCH,+ })+ await writePrivateJson(lockPath, {+ version: 1,+ ownerNonce: 'L'.repeat(43),+ ownershipEpoch: null,+ })++ await expectFixedFailure(+ acquireBridgeDataDirLock(+ directory,+ authorizedRecovery(TEST_OWNERSHIP_EPOCH)+ ),+ directory+ )+ expect(await fs.readdir(directory)).toEqual([+ BRIDGE_DATA_DIR_LOCK_FILE_NAME,+ '.motrix-bridge.lock.recovery',+ ])+ }+ )++ it.runIf(process.platform !== 'win32')(+ 'never follows a forged final symlink during default or authorized acquire',+ async () => {+ const target = path.join(directory, 'sensitive.txt')+ await fs.writeFile(target, 'preserve-me', { mode: 0o600 })+ await fs.symlink(target, lockPath)++ await expectFixedFailure(acquireBridgeDataDirLock(directory), directory)+ await expectFixedFailure(+ acquireBridgeDataDirLock(directory, authorizedRecovery()),+ directory+ )+ await expect(fs.readFile(target, 'utf-8')).resolves.toBe('preserve-me')+ expect((await fs.lstat(lockPath)).isSymbolicLink()).toBe(true)+ }+ )++ it('rejects non-regular, oversized, and malformed recovery candidates', async () => {+ const cases: Array<() => Promise<void>> = [+ async () => fs.mkdir(lockPath),+ async () =>+ fs.writeFile(lockPath, Buffer.alloc(257, 0x61), { mode: 0o600 }),+ async () => fs.writeFile(lockPath, '{"version":1}', { mode: 0o600 }),+ ]+ if (process.platform !== 'win32') {+ cases.push(async () => {+ await fs.writeFile(+ lockPath,+ JSON.stringify({+ version: 1,+ ownerNonce: 'A'.repeat(43),+ ownershipEpoch: null,+ }),+ { mode: 0o600 }+ )+ await fs.chmod(lockPath, 0o644)+ })+ }++ for (const createCandidate of cases) {+ await createCandidate()+ await expectFixedFailure(+ acquireBridgeDataDirLock(directory, authorizedRecovery()),+ directory+ )+ await fs.rm(lockPath, { recursive: true, force: true })+ }+ })++ it('publishes an explicit fail-closed recovery downgrade', () => {+ expect([+ 'external-single-instance-authority',+ 'unavailable-fail-closed',+ ]).toContain(BRIDGE_DATA_DIR_LOCK_RECOVERY_MODE)+ if (process.platform === 'win32') {+ expect(BRIDGE_DATA_DIR_LOCK_RECOVERY_MODE).toBe('unavailable-fail-closed')+ }+ })+})++function authorizedRecovery(+ ownershipEpoch = TEST_OWNERSHIP_EPOCH+): BridgeDataDirLockAcquireOptions {+ return {+ recoverExisting: {+ ownershipEpoch,+ assertExclusiveProcessOwnership: () => true,+ },+ }+}++async function writePrivateJson(+ filePath: string,+ value: Record<string, unknown>+): Promise<void> {+ await fs.writeFile(filePath, JSON.stringify(value), { mode: 0o600 })+ if (process.platform !== 'win32') await fs.chmod(filePath, 0o600)+}++async function expectFixedFailure(+ promise: Promise<unknown>,+ sensitivePath: string+): Promise<void> {+ let error: unknown+ try {+ await promise+ } catch (caught) {+ error = caught+ }+ expect(error).toBeInstanceOf(Error)+ const message = (error as Error).message+ expect(message).toBe(BRIDGE_DATA_DIR_LOCK_UNAVAILABLE)+ expect(message).not.toContain(sensitivePath)+ expect(message).not.toContain(process.pid.toString())+}++function spawnLockWorker(+ directory: string,+ mode: 'hold' | 'crash' | 'recover' | 'duplicate-module'+): LockWorker {+ const moduleUrl = pathToFileURL(+ path.resolve(process.cwd(), 'src/core/bridge/bridge-data-dir-lock.ts')+ ).href+ const script = `+ import readline from 'node:readline'+ import {+ acquireBridgeDataDirLock,+ BRIDGE_DATA_DIR_LOCK_UNAVAILABLE,+ } from ${JSON.stringify(moduleUrl)}++ const moduleUrl = ${JSON.stringify(moduleUrl)}+ const directory = process.argv[1]+ const mode = process.argv[2]+ const lines = readline.createInterface({ input: process.stdin })+ let handle = null++ process.stdout.write('ready\\n')+ lines.on('line', async (line) => {+ if (line === 'go') {+ if (mode === 'duplicate-module') {+ const first = await import(moduleUrl + '?instance=first')+ const second = await import(moduleUrl + '?instance=second')+ const firstHandle = await first.acquireBridgeDataDirLock(directory)+ let authorityCalls = 0+ try {+ await second.acquireBridgeDataDirLock(directory, {+ recoverExisting: {+ ownershipEpoch: 'R'.repeat(43),+ assertExclusiveProcessOwnership: () => {+ authorityCalls += 1+ return true+ },+ },+ })+ await firstHandle.release()+ process.stdout.write(+ 'duplicate-bypassed:' + String(authorityCalls) + '\\n',+ () => process.exit(0)+ )+ } catch (error) {+ const message =+ error instanceof Error+ ? error.message+ : BRIDGE_DATA_DIR_LOCK_UNAVAILABLE+ await firstHandle.release()+ process.stdout.write(+ 'duplicate-protected:' ++ String(authorityCalls) ++ ':' ++ message ++ '\\n',+ () => process.exit(0)+ )+ }+ return+ }+ try {+ handle = await acquireBridgeDataDirLock(+ directory,+ mode === 'recover'+ ? {+ recoverExisting: {+ ownershipEpoch: 'R'.repeat(43),+ assertExclusiveProcessOwnership: () => true,+ },+ }+ : undefined+ )+ process.stdout.write('acquired\\n', () => {+ if (mode === 'crash') process.exit(0)+ })+ } catch (error) {+ const message =+ error instanceof Error ? error.message : BRIDGE_DATA_DIR_LOCK_UNAVAILABLE+ process.stdout.write('failed:' + message + '\\n', () => process.exit(0))+ }+ }+ if (line === 'release' && handle !== null) {+ try {+ await handle.release()+ process.stdout.write('released\\n', () => process.exit(0))+ } catch {+ process.stdout.write(+ 'failed:' + BRIDGE_DATA_DIR_LOCK_UNAVAILABLE + '\\n',+ () => process.exit(0)+ )+ }+ }+ })+ `+ const child = spawn(+ process.execPath,+ [+ '--import',+ 'tsx',+ '--input-type=module',+ '--eval',+ script,+ directory,+ mode,+ ],+ { stdio: ['pipe', 'pipe', 'pipe'] }+ )+ workers.add(child)++ let buffer = ''+ let stderr = ''+ const queued: string[] = []+ const waiters: Array<{+ readonly resolve: (line: string) => void+ readonly reject: (error: Error) => void+ }> = []+ child.stdout.setEncoding('utf-8')+ child.stderr.setEncoding('utf-8')+ child.stderr.on('data', (chunk: string) => {+ stderr += chunk+ })+ child.stdout.on('data', (chunk: string) => {+ buffer += chunk+ let newline = buffer.indexOf('\n')+ while (newline >= 0) {+ const line = buffer.slice(0, newline)+ buffer = buffer.slice(newline + 1)+ const waiter = waiters.shift()+ if (waiter === undefined) queued.push(line)+ else waiter.resolve(line)+ newline = buffer.indexOf('\n')+ }+ })+ child.once('close', (code, signal) => {+ closedWorkers.add(child)+ workers.delete(child)+ for (const waiter of waiters.splice(0)) {+ waiter.reject(+ new Error(+ `lock worker exited before output (${String(code)}, ${String(signal)}): ${stderr}`+ )+ )+ }+ })++ return {+ child,+ nextLine: async () => {+ const next = queued.shift()+ if (next !== undefined) return next+ return new Promise<string>((resolve, reject) => {+ const timeout = setTimeout(() => {+ reject(new Error(`lock worker output timed out: ${stderr}`))+ }, 10_000)+ waiters.push({+ resolve: (line) => {+ clearTimeout(timeout)+ resolve(line)+ },+ reject: (error) => {+ clearTimeout(timeout)+ reject(error)+ },+ })+ })+ },+ send: (command) => child.stdin.write(`${command}\n`),+ }+}++async function waitForExit(+ child: ChildProcessWithoutNullStreams+): Promise<void> {+ if (closedWorkers.has(child)) return+ await new Promise<void>((resolve) => child.once('close', () => resolve()))+}diff --git a/src/core/bridge/bridge-data-dir-lock.ts b/src/core/bridge/bridge-data-dir-lock.tsnew file mode 100644index 00000000..be8667fc--- /dev/null+++ b/src/core/bridge/bridge-data-dir-lock.ts@@ -0,0 +1,963 @@+import { randomBytes } from 'node:crypto'+import { type BigIntStats, constants } from 'node:fs'+import fs, { type FileHandle } from 'node:fs/promises'+import path from 'node:path'++const LOCK_DOCUMENT_VERSION = 1+const OWNER_NONCE_BYTES = 32+const OWNER_NONCE_PATTERN = /^[A-Za-z0-9_-]{43}$/u+const MAX_LOCK_DOCUMENT_BYTES = 256+const NO_FOLLOW = constants.O_NOFOLLOW ?? 0+const LOCK_MODE = 0o600++export const BRIDGE_DATA_DIR_LOCK_FILE_NAME = '.motrix-bridge.lock'+const RECOVERY_GUARD_FILE_NAME = '.motrix-bridge.lock.recovery'++export const BRIDGE_DATA_DIR_LOCK_UNAVAILABLE =+ 'bridge data directory lock unavailable'++/**+ * Node has no portable advisory file-lock primitive. Fresh create-exclusive+ * locking works on every supported platform, while automatic stale recovery+ * is intentionally unavailable where final-component no-follow semantics+ * cannot be established. In particular, Windows fails closed on a residue;+ * it requests 0600 at creation but relies on the data directory's Windows ACL+ * because POSIX permission bits have no equivalent enforcement there.+ */+export const BRIDGE_DATA_DIR_LOCK_RECOVERY_MODE =+ process.platform !== 'win32' && NO_FOLLOW !== 0+ ? 'external-single-instance-authority'+ : 'unavailable-fail-closed'++const lockHandleBrand: unique symbol = Symbol('BridgeDataDirLockHandle')++export interface BridgeDataDirLockHandle {+ readonly [lockHandleBrand]: true+ /** Idempotent across repeated and concurrent shutdown paths. */+ release(): Promise<void>+}++/**+ * Trusted composition-root authority for stale recovery.+ *+ * This assertion MUST return true only while Motrix Main already owns+ * Electron's `requestSingleInstanceLock()` result, acquired before bridge+ * startup. PID checks, file age, mtime, and heartbeat expiry are not adequate+ * substitutes. Core deliberately cannot manufacture this OS-level proof.+ */+export interface BridgeDataDirLockRecoveryAuthority {+ /**+ * A fresh random value created once for this successful OS single-instance+ * ownership session. All callers in that Main session must share it; a new+ * process ownership session must use a new value.+ */+ readonly ownershipEpoch: string+ assertExclusiveProcessOwnership(): boolean | Promise<boolean>+}++export interface BridgeDataDirLockAcquireOptions {+ readonly recoverExisting?: BridgeDataDirLockRecoveryAuthority+}++interface LockDocument {+ readonly version: typeof LOCK_DOCUMENT_VERSION+ readonly ownerNonce: string+ readonly ownershipEpoch: string | null+}++interface RecoveryGuardDocument {+ readonly version: typeof LOCK_DOCUMENT_VERSION+ readonly recoveryNonce: string+ readonly ownershipEpoch: string+}++interface FileIdentity {+ readonly device: bigint+ readonly inode: bigint+}++interface OwnedFile {+ readonly path: string+ readonly identity: FileIdentity+ readonly expected: Buffer+ handle: FileHandle | null+}++interface ObservedLock {+ readonly identity: FileIdentity+ readonly document: LockDocument+}++interface ObservedRecoveryGuard {+ readonly identity: FileIdentity+ readonly document: RecoveryGuardDocument+}++interface ObservedLockWithLinks extends ObservedLock {+ readonly links: bigint+}++class ExistingLockError extends Error {}+class InternalLockError extends Error {}+class RetainModuleClaimError extends Error {}++interface ProcessClaimRegistry {+ readonly version: 1+ readonly claims: Map<string, symbol>+}++const PROCESS_CLAIM_REGISTRY_KEY = Symbol.for(+ 'motrix.bridge.data-dir-lock.process-claims.v1'+)++/**+ * `Symbol.for` + a non-replaceable global slot makes duplicate ESM URLs and+ * duplicate bundles in the same JavaScript realm share the live-path guard.+ * The file's O_EXCL remains the cross-process arbiter.+ */+function processClaimRegistry(): Map<string, symbol> | null {+ try {+ const root = globalThis as typeof globalThis & {+ [PROCESS_CLAIM_REGISTRY_KEY]?: unknown+ }+ const existing = root[PROCESS_CLAIM_REGISTRY_KEY]+ if (existing !== undefined) {+ if (+ typeof existing !== 'object' ||+ existing === null ||+ (existing as Partial<ProcessClaimRegistry>).version !== 1 ||+ !((existing as Partial<ProcessClaimRegistry>).claims instanceof Map)+ ) {+ return null+ }+ return (existing as ProcessClaimRegistry).claims+ }++ const created: ProcessClaimRegistry = Object.freeze({+ version: 1,+ claims: new Map<string, symbol>(),+ })+ Object.defineProperty(root, PROCESS_CLAIM_REGISTRY_KEY, {+ configurable: false,+ enumerable: false,+ value: created,+ writable: false,+ })+ return created.claims+ } catch {+ return null+ }+}++const moduleClaims = processClaimRegistry()+const activeLockHandles = new WeakMap<+ object,+ {+ readonly owned: OwnedFile+ readonly claim: symbol+ readonly claims: Map<string, symbol>+ }+>()++class FileBridgeDataDirLockHandle implements BridgeDataDirLockHandle {+ readonly [lockHandleBrand] = true as const+ private releasePromise: Promise<void> | null = null+ private released = false++ constructor(+ private readonly owned: OwnedFile,+ private readonly claim: symbol,+ private readonly claims: Map<string, symbol>+ ) {+ activeLockHandles.set(this, { owned, claim, claims })+ }++ release(): Promise<void> {+ if (this.released) return Promise.resolve()+ if (this.releasePromise !== null) return this.releasePromise++ this.releasePromise = this.releaseOnce()+ .then(() => {+ this.released = true+ activeLockHandles.delete(this)+ })+ .catch(() => {+ throw publicFailure()+ })+ .finally(() => {+ this.releasePromise = null+ })+ return this.releasePromise+ }++ private async releaseOnce(): Promise<void> {+ if (this.claims.get(this.owned.path) !== this.claim) {+ throw new InternalLockError()+ }+ await removeOwnedFile(this.owned)+ if (this.claims.get(this.owned.path) !== this.claim) {+ throw new InternalLockError()+ }+ this.claims.delete(this.owned.path)+ }+}++/**+ * Execute one trusted startup repair only while `handle` still owns the exact+ * data-directory lock file. The WeakMap claim makes copied or structurally+ * forged handles unusable; the on-disk identity/bytes check catches path+ * replacement before the repair begins.+ */+export async function withBridgeDataDirLock<T>(+ handle: BridgeDataDirLockHandle,+ dataDirectory: string,+ operation: () => Promise<T>+): Promise<T> {+ const active = activeLockHandles.get(handle)+ try {+ if (active === undefined) throw new InternalLockError()+ const canonicalDirectory = await canonicalDataDirectory(dataDirectory)+ if (+ path.dirname(active.owned.path) !== canonicalDirectory ||+ active.claims.get(active.owned.path) !== active.claim+ ) {+ throw new InternalLockError()+ }+ const raw = await readOwnedFile(active.owned, 1n)+ if (!raw.equals(active.owned.expected)) throw new InternalLockError()+ } catch {+ throw publicFailure()+ }+ return operation()+}++/**+ * Acquires the bridge data-directory lock before any bridge store or listener+ * is opened. An existing entry is unavailable by default, including a crash+ * residue. Recovery is a separate, explicit operation authorized only by the+ * process-wide OS ownership assertion documented above.+ */+export async function acquireBridgeDataDirLock(+ dataDirectory: string,+ options: BridgeDataDirLockAcquireOptions = {}+): Promise<BridgeDataDirLockHandle> {+ let lockPath: string | null = null+ let claim: symbol | null = null+ const claims = moduleClaims+ try {+ if (claims === null) throw new InternalLockError()+ const canonicalDirectory = await canonicalDataDirectory(dataDirectory)+ lockPath = path.join(canonicalDirectory, BRIDGE_DATA_DIR_LOCK_FILE_NAME)+ const recoveryGuardPath = path.join(+ canonicalDirectory,+ RECOVERY_GUARD_FILE_NAME+ )++ if (claims.has(lockPath)) throw new ExistingLockError()+ claim = Symbol('bridge-data-dir-lock-claim')+ claims.set(lockPath, claim)++ let owned: OwnedFile+ if (await pathExists(recoveryGuardPath)) {+ owned = await resumeInterruptedRecovery(+ lockPath,+ recoveryGuardPath,+ options.recoverExisting+ )+ } else {+ try {+ owned = await createLockFile(+ lockPath,+ declaredOwnershipEpoch(options.recoverExisting)+ )+ try {+ await assertMissing(recoveryGuardPath)+ } catch (error) {+ try {+ await removeOwnedFile(owned)+ } catch {+ throw new RetainModuleClaimError()+ }+ throw error+ }+ } catch (error) {+ if (!(error instanceof ExistingLockError)) throw error+ owned = await recoverExistingLock(+ lockPath,+ recoveryGuardPath,+ options.recoverExisting+ )+ }+ }++ return new FileBridgeDataDirLockHandle(owned, claim, claims)+ } catch (error) {+ if (+ lockPath !== null &&+ claim !== null &&+ claims?.get(lockPath) === claim &&+ !(error instanceof RetainModuleClaimError)+ ) {+ claims.delete(lockPath)+ }+ throw publicFailure()+ }+}++async function recoverExistingLock(+ lockPath: string,+ recoveryGuardPath: string,+ authority: BridgeDataDirLockRecoveryAuthority | undefined+): Promise<OwnedFile> {+ const ownershipEpoch = await validateRecoveryAuthority(authority)++ const observed = await readExistingLock(lockPath, 1n)+ if (observed.document.ownershipEpoch === ownershipEpoch) {+ throw new ExistingLockError()+ }+ const recoveryNonce = ownerNonce()+ const guard = await createOwnedFile(+ recoveryGuardPath,+ serializeRecoveryGuard({+ version: LOCK_DOCUMENT_VERSION,+ recoveryNonce,+ ownershipEpoch,+ })+ )+ const quarantinePath = `${lockPath}.stale-${recoveryNonce}`+ let quarantineCreated = false+ let originalUnlinked = false+ let replacement: OwnedFile | null = null+ try {+ const current = await readExistingLock(lockPath, 1n)+ if (!sameObservedLock(observed, current)) throw new InternalLockError()++ await fs.link(lockPath, quarantinePath)+ quarantineCreated = true+ const quarantined = await readExistingLock(quarantinePath, 2n)+ if (!sameObservedLock(observed, quarantined)) throw new InternalLockError()+ const stillCurrent = await readExistingLock(lockPath, 2n)+ if (!sameObservedLock(observed, stillCurrent)) throw new InternalLockError()++ await fs.unlink(lockPath)+ originalUnlinked = true+ await syncDirectory(path.dirname(lockPath))+ replacement = await createLockFile(lockPath, ownershipEpoch)++ await removeObservedPath(quarantinePath, observed.identity, 1n)+ quarantineCreated = false+ await removeOwnedFile(guard)+ await syncDirectory(path.dirname(lockPath))+ return replacement+ } catch (error) {+ let cleanupFailed = false+ if (replacement !== null) {+ try {+ await removeOwnedFile(replacement)+ } catch {+ cleanupFailed = true+ }+ }+ if (quarantineCreated) {+ try {+ await removeObservedPath(+ quarantinePath,+ observed.identity,+ originalUnlinked ? 1n : 2n+ )+ } catch {+ cleanupFailed = true+ }+ }+ try {+ await removeOwnedFile(guard)+ } catch {+ cleanupFailed = true+ }+ if (cleanupFailed) throw new RetainModuleClaimError()+ throw error+ }+}++async function resumeInterruptedRecovery(+ lockPath: string,+ recoveryGuardPath: string,+ authority: BridgeDataDirLockRecoveryAuthority | undefined+): Promise<OwnedFile> {+ const ownershipEpoch = await validateRecoveryAuthority(authority)+ const guard = await readRecoveryGuard(recoveryGuardPath)+ if (guard.document.ownershipEpoch === ownershipEpoch) {+ throw new ExistingLockError()+ }++ const quarantinePath = `${lockPath}.stale-${guard.document.recoveryNonce}`+ const [current, quarantined] = await Promise.all([+ readOptionalLock(lockPath),+ readOptionalLock(quarantinePath),+ ])++ if (+ current !== null &&+ quarantined !== null &&+ sameIdentity(current.identity, quarantined.identity)+ ) {+ if (current.links !== 2n || quarantined.links !== 2n) {+ throw new InternalLockError()+ }+ await removeObservedPath(lockPath, current.identity, 2n)+ await removeObservedPath(quarantinePath, quarantined.identity, 1n)+ } else {+ if (current !== null) {+ if (current.links !== 1n) throw new InternalLockError()+ await removeObservedPath(lockPath, current.identity, 1n)+ }+ if (quarantined !== null) {+ if (quarantined.links !== 1n) throw new InternalLockError()+ await removeObservedPath(quarantinePath, quarantined.identity, 1n)+ }+ }++ const stillGuard = await readRecoveryGuard(recoveryGuardPath)+ if (!sameRecoveryGuard(guard, stillGuard)) throw new InternalLockError()+ await removeObservedPath(recoveryGuardPath, guard.identity, 1n)+ await syncDirectoryBestEffort(path.dirname(lockPath))+ return createFreshDuringRecovery(lockPath, recoveryGuardPath, ownershipEpoch)+}++async function createFreshDuringRecovery(+ lockPath: string,+ recoveryGuardPath: string,+ ownershipEpoch: string+): Promise<OwnedFile> {+ const guard = await createOwnedFile(+ recoveryGuardPath,+ serializeRecoveryGuard({+ version: LOCK_DOCUMENT_VERSION,+ recoveryNonce: ownerNonce(),+ ownershipEpoch,+ })+ )+ let replacement: OwnedFile | null = null+ try {+ await assertMissing(lockPath)+ replacement = await createLockFile(lockPath, ownershipEpoch)+ await removeOwnedFile(guard)+ return replacement+ } catch (error) {+ let cleanupFailed = false+ if (replacement !== null) {+ try {+ await removeOwnedFile(replacement)+ } catch {+ cleanupFailed = true+ }+ }+ try {+ await removeOwnedFile(guard)+ } catch {+ cleanupFailed = true+ }+ if (cleanupFailed) throw new RetainModuleClaimError()+ throw error+ }+}++async function validateRecoveryAuthority(+ authority: BridgeDataDirLockRecoveryAuthority | undefined+): Promise<string> {+ if (+ BRIDGE_DATA_DIR_LOCK_RECOVERY_MODE !==+ 'external-single-instance-authority' ||+ authority === undefined+ ) {+ throw new ExistingLockError()+ }+ const ownershipEpoch = declaredOwnershipEpoch(authority)+ if (ownershipEpoch === null) throw new ExistingLockError()++ let authorized = false+ try {+ authorized = (await authority.assertExclusiveProcessOwnership()) === true+ } catch {+ throw new InternalLockError()+ }+ if (!authorized) throw new ExistingLockError()+ return ownershipEpoch+}++function declaredOwnershipEpoch(+ authority: BridgeDataDirLockRecoveryAuthority | undefined+): string | null {+ if (authority === undefined) return null+ if (!OWNER_NONCE_PATTERN.test(authority.ownershipEpoch)) {+ throw new InternalLockError()+ }+ return authority.ownershipEpoch+}++async function canonicalDataDirectory(dataDirectory: string): Promise<string> {+ if (+ typeof dataDirectory !== 'string' ||+ dataDirectory.length === 0 ||+ dataDirectory.includes('\0')+ ) {+ throw new InternalLockError()+ }+ const canonical = await fs.realpath(dataDirectory)+ const metadata = await fs.stat(canonical)+ if (!metadata.isDirectory()) throw new InternalLockError()+ return canonical+}++async function createLockFile(+ lockPath: string,+ ownershipEpoch: string | null+): Promise<OwnedFile> {+ const document: LockDocument = {+ version: LOCK_DOCUMENT_VERSION,+ ownerNonce: ownerNonce(),+ ownershipEpoch,+ }+ return createOwnedFile(lockPath, serializeDocument(document))+}++async function createOwnedFile(+ filePath: string,+ content: Buffer+): Promise<OwnedFile> {+ if (+ content.byteLength === 0 ||+ content.byteLength > MAX_LOCK_DOCUMENT_BYTES+ ) {+ throw new InternalLockError()+ }++ let handle: FileHandle+ try {+ handle = await fs.open(+ filePath,+ constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | NO_FOLLOW,+ LOCK_MODE+ )+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') {+ throw new ExistingLockError()+ }+ throw error+ }++ let owned: OwnedFile | null = null+ let createdIdentity: FileIdentity | undefined+ try {+ if (process.platform !== 'win32') await handle.chmod(LOCK_MODE)+ const metadata = await handle.stat({ bigint: true })+ if (metadata.isFile() && metadata.ino !== 0n) {+ createdIdentity = identityOf(metadata)+ }+ validateLockMetadata(metadata, 1n, false)+ owned = {+ path: filePath,+ identity: identityOf(metadata),+ expected: content,+ handle,+ }+ await handle.writeFile(content)+ await handle.sync()+ const written = await readOwnedFile(owned, 1n)+ if (!written.equals(content)) throw new InternalLockError()+ await syncDirectory(path.dirname(filePath))+ return owned+ } catch (error) {+ if (createdIdentity === undefined) {+ try {+ const metadata = await handle.stat({ bigint: true })+ if (metadata.isFile() && metadata.ino !== 0n) {+ createdIdentity = identityOf(metadata)+ }+ } catch {+ // An unidentifiable create result is retained fail-closed below.+ }+ }+ let closeFailed = false+ try {+ await handle.close()+ } catch {+ closeFailed = true+ }+ if (owned !== null) owned.handle = null+ let removeFailed = false+ try {+ await removePathIfIdentityMatches(filePath, createdIdentity)+ } catch {+ removeFailed = true+ }+ if (closeFailed || createdIdentity === undefined || removeFailed) {+ throw new RetainModuleClaimError()+ }+ throw error+ }+}++async function readExistingLock(+ filePath: string,+ expectedLinks: bigint+): Promise<ObservedLock> {+ if (+ BRIDGE_DATA_DIR_LOCK_RECOVERY_MODE !== 'external-single-instance-authority'+ ) {+ throw new InternalLockError()+ }+ const before = await fs.lstat(filePath, { bigint: true })+ validateLockMetadata(before, expectedLinks, true)++ const handle = await fs.open(filePath, constants.O_RDONLY | NO_FOLLOW)+ try {+ const opened = await handle.stat({ bigint: true })+ validateLockMetadata(opened, expectedLinks, true)+ if (!sameIdentity(identityOf(before), identityOf(opened))) {+ throw new InternalLockError()+ }+ const raw = await readBounded(handle, opened)+ return {+ identity: identityOf(opened),+ document: parseLockDocument(raw),+ }+ } finally {+ await handle.close()+ }+}++async function readRecoveryGuard(+ filePath: string+): Promise<ObservedRecoveryGuard> {+ if (+ BRIDGE_DATA_DIR_LOCK_RECOVERY_MODE !== 'external-single-instance-authority'+ ) {+ throw new InternalLockError()+ }+ const before = await fs.lstat(filePath, { bigint: true })+ validateLockMetadata(before, 1n, true)++ const handle = await fs.open(filePath, constants.O_RDONLY | NO_FOLLOW)+ try {+ const opened = await handle.stat({ bigint: true })+ validateLockMetadata(opened, 1n, true)+ if (!sameIdentity(identityOf(before), identityOf(opened))) {+ throw new InternalLockError()+ }+ return {+ identity: identityOf(opened),+ document: parseRecoveryGuard(await readBounded(handle, opened)),+ }+ } finally {+ await handle.close()+ }+}++async function readOptionalLock(+ filePath: string+): Promise<ObservedLockWithLinks | null> {+ let metadata: BigIntStats+ try {+ metadata = await fs.lstat(filePath, { bigint: true })+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null+ throw error+ }+ if (metadata.nlink !== 1n && metadata.nlink !== 2n) {+ throw new InternalLockError()+ }+ const observed = await readExistingLock(filePath, metadata.nlink)+ return { ...observed, links: metadata.nlink }+}++async function readOwnedFile(+ owned: OwnedFile,+ expectedLinks: bigint+): Promise<Buffer> {+ const handle = owned.handle+ if (handle === null) throw new InternalLockError()+ const metadata = await handle.stat({ bigint: true })+ validateLockMetadata(metadata, expectedLinks, false)+ if (!sameIdentity(owned.identity, identityOf(metadata))) {+ throw new InternalLockError()+ }+ return readBounded(handle, metadata)+}++async function readBounded(+ handle: FileHandle,+ metadata: BigIntStats+): Promise<Buffer> {+ const size = Number(metadata.size)+ if (+ !Number.isSafeInteger(size) ||+ size <= 0 ||+ size > MAX_LOCK_DOCUMENT_BYTES+ ) {+ throw new InternalLockError()+ }+ const result = Buffer.allocUnsafe(size)+ let offset = 0+ while (offset < result.byteLength) {+ const { bytesRead } = await handle.read(+ result,+ offset,+ result.byteLength - offset,+ offset+ )+ if (bytesRead === 0) throw new InternalLockError()+ offset += bytesRead+ }+ const after = await handle.stat({ bigint: true })+ if (after.size !== metadata.size) throw new InternalLockError()+ return result+}++async function removeOwnedFile(owned: OwnedFile): Promise<void> {+ if (owned.handle !== null) {+ const raw = await readOwnedFile(owned, 1n)+ if (!raw.equals(owned.expected)) throw new InternalLockError()+ const atPath = await fs.lstat(owned.path, { bigint: true })+ validateLockMetadata(atPath, 1n, false)+ if (!sameIdentity(owned.identity, identityOf(atPath))) {+ throw new InternalLockError()+ }+ await owned.handle.close()+ owned.handle = null+ }++ const current = await fs.lstat(owned.path, { bigint: true })+ validateLockMetadata(current, 1n, false)+ if (!sameIdentity(owned.identity, identityOf(current))) {+ throw new InternalLockError()+ }+ await fs.unlink(owned.path)+ await syncDirectoryBestEffort(path.dirname(owned.path))+}++async function removeObservedPath(+ filePath: string,+ identity: FileIdentity,+ expectedLinks: bigint+): Promise<void> {+ const metadata = await fs.lstat(filePath, { bigint: true })+ validateLockMetadata(metadata, expectedLinks, false)+ if (!sameIdentity(identity, identityOf(metadata))) {+ throw new InternalLockError()+ }+ await fs.unlink(filePath)+}++async function removePathIfIdentityMatches(+ filePath: string,+ identity: FileIdentity | undefined+): Promise<void> {+ if (identity === undefined) return+ const metadata = await fs.lstat(filePath, { bigint: true })+ if (sameIdentity(identity, identityOf(metadata))) await fs.unlink(filePath)+}++function validateLockMetadata(+ metadata: BigIntStats,+ expectedLinks: bigint,+ requireSecureExistingOpen: boolean+): void {+ if (+ !metadata.isFile() ||+ metadata.isSymbolicLink() ||+ metadata.ino === 0n ||+ metadata.nlink !== expectedLinks ||+ metadata.size < 0n ||+ metadata.size > BigInt(MAX_LOCK_DOCUMENT_BYTES) ||+ (process.platform !== 'win32' &&+ (metadata.mode & 0o777n) !== BigInt(LOCK_MODE)) ||+ (requireSecureExistingOpen && NO_FOLLOW === 0)+ ) {+ throw new InternalLockError()+ }+}++function identityOf(metadata: BigIntStats): FileIdentity {+ return { device: metadata.dev, inode: metadata.ino }+}++function sameIdentity(left: FileIdentity, right: FileIdentity): boolean {+ return left.device === right.device && left.inode === right.inode+}++function sameObservedLock(left: ObservedLock, right: ObservedLock): boolean {+ return (+ sameIdentity(left.identity, right.identity) &&+ left.document.version === right.document.version &&+ left.document.ownerNonce === right.document.ownerNonce &&+ left.document.ownershipEpoch === right.document.ownershipEpoch+ )+}++function sameRecoveryGuard(+ left: ObservedRecoveryGuard,+ right: ObservedRecoveryGuard+): boolean {+ return (+ sameIdentity(left.identity, right.identity) &&+ left.document.version === right.document.version &&+ left.document.recoveryNonce === right.document.recoveryNonce &&+ left.document.ownershipEpoch === right.document.ownershipEpoch+ )+}++function parseLockDocument(raw: Buffer): LockDocument {+ let value: unknown+ try {+ value = JSON.parse(raw.toString('utf-8'))+ } catch {+ throw new InternalLockError()+ }+ if (+ typeof value !== 'object' ||+ value === null ||+ Object.getPrototypeOf(value) !== Object.prototype ||+ !hasExactKeys(value as Record<string, unknown>, [+ 'ownerNonce',+ 'ownershipEpoch',+ 'version',+ ])+ ) {+ throw new InternalLockError()+ }+ const candidate = value as Record<string, unknown>+ if (+ candidate.version !== LOCK_DOCUMENT_VERSION ||+ typeof candidate.ownerNonce !== 'string' ||+ !OWNER_NONCE_PATTERN.test(candidate.ownerNonce) ||+ (candidate.ownershipEpoch !== null &&+ (typeof candidate.ownershipEpoch !== 'string' ||+ !OWNER_NONCE_PATTERN.test(candidate.ownershipEpoch)))+ ) {+ throw new InternalLockError()+ }+ return {+ version: LOCK_DOCUMENT_VERSION,+ ownerNonce: candidate.ownerNonce,+ ownershipEpoch: candidate.ownershipEpoch as string | null,+ }+}++function parseRecoveryGuard(raw: Buffer): RecoveryGuardDocument {+ let value: unknown+ try {+ value = JSON.parse(raw.toString('utf-8'))+ } catch {+ throw new InternalLockError()+ }+ if (+ typeof value !== 'object' ||+ value === null ||+ Object.getPrototypeOf(value) !== Object.prototype ||+ !hasExactKeys(value as Record<string, unknown>, [+ 'ownershipEpoch',+ 'recoveryNonce',+ 'version',+ ])+ ) {+ throw new InternalLockError()+ }+ const candidate = value as Record<string, unknown>+ if (+ candidate.version !== LOCK_DOCUMENT_VERSION ||+ typeof candidate.recoveryNonce !== 'string' ||+ !OWNER_NONCE_PATTERN.test(candidate.recoveryNonce) ||+ typeof candidate.ownershipEpoch !== 'string' ||+ !OWNER_NONCE_PATTERN.test(candidate.ownershipEpoch)+ ) {+ throw new InternalLockError()+ }+ return {+ version: LOCK_DOCUMENT_VERSION,+ recoveryNonce: candidate.recoveryNonce,+ ownershipEpoch: candidate.ownershipEpoch,+ }+}++function serializeDocument(document: LockDocument): Buffer {+ const serialized = Buffer.from(JSON.stringify(document), 'utf-8')+ if (+ serialized.byteLength === 0 ||+ serialized.byteLength > MAX_LOCK_DOCUMENT_BYTES+ ) {+ throw new InternalLockError()+ }+ return serialized+}++function serializeRecoveryGuard(document: RecoveryGuardDocument): Buffer {+ const serialized = Buffer.from(JSON.stringify(document), 'utf-8')+ if (+ serialized.byteLength === 0 ||+ serialized.byteLength > MAX_LOCK_DOCUMENT_BYTES+ ) {+ throw new InternalLockError()+ }+ return serialized+}++function ownerNonce(): string {+ return randomBytes(OWNER_NONCE_BYTES).toString('base64url')+}++function hasExactKeys(+ value: Record<string, unknown>,+ expected: readonly string[]+): boolean {+ const keys = Object.keys(value).sort()+ const wanted = [...expected].sort()+ return (+ keys.length === wanted.length &&+ keys.every((key, index) => key === wanted[index])+ )+}++async function assertMissing(filePath: string): Promise<void> {+ try {+ await fs.lstat(filePath)+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return+ throw error+ }+ throw new ExistingLockError()+}++async function pathExists(filePath: string): Promise<boolean> {+ try {+ await fs.lstat(filePath)+ return true+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false+ throw error+ }+}++async function syncDirectory(directory: string): Promise<void> {+ if (process.platform === 'win32') return+ const handle = await fs.open(directory, 'r')+ try {+ await handle.sync()+ } finally {+ await handle.close()+ }+}++async function syncDirectoryBestEffort(directory: string): Promise<void> {+ try {+ await syncDirectory(directory)+ } catch {+ // Unlink is the ownership commit point. A failed directory fsync may leave+ // a crash residue after power loss, but must not report the live handle as+ // retained after the path is already available to another process.+ }+}++function publicFailure(): Error {+ return new Error(BRIDGE_DATA_DIR_LOCK_UNAVAILABLE)+}diff --git a/src/core/bridge/bridge-event-bus.test.ts b/src/core/bridge/bridge-event-bus.test.tsindex ed973845..097e00da 100644--- a/src/core/bridge/bridge-event-bus.test.ts+++ b/src/core/bridge/bridge-event-bus.test.ts@@ -31,18 +31,19 @@ describe('BridgeEventBus', () => {expect(r).toHaveLength(2)})- it('emits PairRequestSettled with key + outcome', () => {- const bus = new BridgeEventBus()- const received: unknown[] = []- bus.on('PairRequestSettled', (p) => received.push(p))- bus.emitPairRequestSettled({- key: 'chromium:ext-1:nonce-1',- outcome: 'allowed',- })- expect(received).toEqual([- { key: 'chromium:ext-1:nonce-1', outcome: 'allowed' },- ])- })+ it.each(['allowed', 'denied', 'aborted'] as const)(+ 'emits PairRequestSettled with the %s outcome',+ (outcome) => {+ const bus = new BridgeEventBus()+ const received: unknown[] = []+ bus.on('PairRequestSettled', (p) => received.push(p))+ bus.emitPairRequestSettled({+ key: 'chromium:ext-1:nonce-1',+ outcome,+ })+ expect(received).toEqual([{ key: 'chromium:ext-1:nonce-1', outcome }])+ }+ )it('emits PairRequestExpired with key', () => {const bus = new BridgeEventBus()diff --git a/src/core/bridge/bridge-identity.test.ts b/src/core/bridge/bridge-identity.test.tsindex c7f44221..7a93513d 100644--- a/src/core/bridge/bridge-identity.test.ts+++ b/src/core/bridge/bridge-identity.test.ts@@ -2,7 +2,10 @@ import fs from 'node:fs/promises'import os from 'node:os'import path from 'node:path'import { afterEach, beforeEach, describe, expect, it } from 'vitest'-import { loadOrCreateBridgeIdentity } from './bridge-identity'+import {+ loadOrCreateBridgeIdentity,+ loadOrCreateBridgeInstanceId,+} from './bridge-identity'const UUID_PATTERN =/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i@@ -87,3 +90,81 @@ describe('loadOrCreateBridgeIdentity', () => {expect(st.mode & 0o777).toBe(0o600)})})++describe('loadOrCreateBridgeInstanceId', () => {+ let tmpDir: string+ let instanceIdFilePath: string++ beforeEach(async () => {+ tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'bridge-instance-id-'))+ instanceIdFilePath = path.join(tmpDir, 'server-instance-id')+ })++ afterEach(async () => {+ await fs.rm(tmpDir, { recursive: true, force: true })+ })++ it('creates one stable owner-only UUID identity', async () => {+ const first = await loadOrCreateBridgeInstanceId(instanceIdFilePath)+ const second = await loadOrCreateBridgeInstanceId(instanceIdFilePath)++ expect(first).toMatch(UUID_PATTERN)+ expect(second).toBe(first)+ if (process.platform !== 'win32') {+ expect((await fs.stat(instanceIdFilePath)).mode & 0o777).toBe(0o600)+ }+ })++ it('preserves identity on offline backup restore, resets on a fresh directory, and cannot distinguish a byte-identical clone', async () => {+ const sourceDir = path.join(tmpDir, 'source-data')+ const backupDir = path.join(tmpDir, 'offline-backup')+ const cloneDir = path.join(tmpDir, 'unsupported-live-clone')+ const freshDir = path.join(tmpDir, 'fresh-data')+ const identityPath = (directory: string) =>+ path.join(directory, 'bridge', 'server-instance-id')++ const original = await loadOrCreateBridgeInstanceId(identityPath(sourceDir))+ await fs.cp(sourceDir, backupDir, { recursive: true })+ await fs.rm(sourceDir, { recursive: true, force: true })+ await fs.cp(backupDir, sourceDir, { recursive: true })++ await expect(+ loadOrCreateBridgeInstanceId(identityPath(sourceDir))+ ).resolves.toBe(original)+ await expect(+ loadOrCreateBridgeInstanceId(identityPath(freshDir))+ ).resolves.not.toBe(original)++ // A complete byte-identical clone necessarily carries the same transcript+ // identity. This is why active-active clones are documented as forbidden,+ // not advertised as automatically client-detectable.+ await fs.cp(backupDir, cloneDir, { recursive: true })+ await expect(+ loadOrCreateBridgeInstanceId(identityPath(cloneDir))+ ).resolves.toBe(original)+ })++ it('fails closed rather than silently replacing malformed identity state', async () => {+ await fs.writeFile(instanceIdFilePath, 'not-an-instance-id', {+ mode: 0o600,+ })++ await expect(+ loadOrCreateBridgeInstanceId(instanceIdFilePath)+ ).rejects.toThrow('bridge instance identity unavailable')+ await expect(fs.readFile(instanceIdFilePath, 'utf8')).resolves.toBe(+ 'not-an-instance-id'+ )+ })++ it('rejects a symbolic link instead of following it', async () => {+ if (process.platform === 'win32') return+ const target = path.join(tmpDir, 'target')+ await fs.writeFile(target, '00000000-0000-4000-8000-000000000000')+ await fs.symlink(target, instanceIdFilePath)++ await expect(+ loadOrCreateBridgeInstanceId(instanceIdFilePath)+ ).rejects.toThrow('bridge instance identity unavailable')+ })+})diff --git a/src/core/bridge/bridge-identity.ts b/src/core/bridge/bridge-identity.tsindex 87155786..4d303c4d 100644--- a/src/core/bridge/bridge-identity.ts+++ b/src/core/bridge/bridge-identity.ts@@ -1,9 +1,12 @@import { randomBytes, randomUUID } from 'node:crypto'-import { chmod, mkdir, readFile } from 'node:fs/promises'+import { constants } from 'node:fs'+import { chmod, lstat, mkdir, open, readFile } from 'node:fs/promises'import { dirname } from 'node:path'import writeFileAtomic from 'write-file-atomic'const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43,128}$/+const INSTANCE_ID_PATTERN =+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/uexport interface BridgeIdentity {localToken: string@@ -38,6 +41,55 @@ export async function loadOrCreateBridgeIdentity(return { localToken, serverGeneration: randomUUID() }}+/**+ * Load the stable MBP1 transcript identity for a shell which has no settings+ * store of its own (currently Motrix Server). Missing is the only create case:+ * malformed, symbolic-link, non-regular, or multiply-linked state fails+ * closed so a storage problem cannot silently present a new Server identity.+ * The caller must already own the bridge data-directory lock.+ */+export async function loadOrCreateBridgeInstanceId(+ instanceIdFilePath: string+): Promise<string> {+ await mkdir(dirname(instanceIdFilePath), { recursive: true })+ try {+ const before = await lstat(instanceIdFilePath, { bigint: true })+ if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1n) {+ throw new Error('bridge instance identity unavailable')+ }+ const handle = await open(+ instanceIdFilePath,+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)+ )+ let value: string+ try {+ const during = await handle.stat({ bigint: true })+ if (during.dev !== before.dev || during.ino !== before.ino) {+ throw new Error('bridge instance identity unavailable')+ }+ value = await handle.readFile('utf8')+ const after = await lstat(instanceIdFilePath, { bigint: true })+ if (after.dev !== during.dev || after.ino !== during.ino) {+ throw new Error('bridge instance identity unavailable')+ }+ } finally {+ await handle.close()+ }+ if (!INSTANCE_ID_PATTERN.test(value)) {+ throw new Error('bridge instance identity unavailable')+ }+ await chmod(instanceIdFilePath, 0o600)+ return value+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error+ }++ const value = randomUUID()+ await writeFileAtomic(instanceIdFilePath, value, { mode: 0o600 })+ await chmod(instanceIdFilePath, 0o600)+ return value+}+async function readExistingToken(tokenFilePath: string): Promise<string | undefined> {diff --git a/src/core/bridge/credential-store.test.ts b/src/core/bridge/credential-store.test.tsindex 5c7a8b84..2e3d5631 100644--- a/src/core/bridge/credential-store.test.ts+++ b/src/core/bridge/credential-store.test.ts@@ -2,11 +2,18 @@ import fs from 'node:fs/promises'import os from 'node:os'import path from 'node:path'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { CredentialPrincipal, StoredCredential } from './credential-store'+import type {+ CredentialPrincipal,+ ExtensionIdentityAbsenceWitness,+ StoredCredential,+} from './credential-store'import {+ CommittedExtensionCredentialError,Mbp1CredentialStore,PROVISIONAL_TTL_MS,principalKey,+ withLiveCommittedExtensionWitness,+ withLiveExtensionIdentityAbsenceWitness,} from './credential-store'/**@@ -106,7 +113,7 @@ describe('Mbp1CredentialStore', () => {// Read the FILE, not the instance: the provisional must already be durable// by the time the caller is free to send `credentialOffer` (§6.7 step 1).const doc = await readDoc()- expect(doc.version).toBe(1)+ expect(doc.version).toBe(2)expect(doc.pendingPromote).toBeNull()expect(doc.credentials).toHaveLength(1)expect(doc.credentials[0]).toMatchObject({@@ -572,7 +579,321 @@ describe('Mbp1CredentialStore', () => {expect(doc.credentials[0]?.credentialId).toBe(second.credentialId)})- it('ignores malformed on-disk records', async () => {+ it('issues nominal witnesses only for durably committed exact credentials', async () => {+ const store = await open()+ const offer = await store.offerProvisional(PRINCIPAL_A, 'official')+ await expect(+ store.issueCommittedExtensionWitness(offer.credentialId)+ ).rejects.toThrow(CommittedExtensionCredentialError.NotCommitted)++ now = START + 100+ await store.commitFromPair(offer.credentialId)+ const witness = await store.issueCommittedExtensionWitness(+ offer.credentialId+ )+ expect(witness).toMatchObject({+ identity: {+ kind: 'extension',+ browser: 'chromium',+ extensionId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ },+ identityTrust: 'official',+ committedAt: START + 100,+ })+ expect(Object.isFrozen(witness)).toBe(true)+ expect(Object.isFrozen(witness.identity)).toBe(true)+ await expect(+ withLiveCommittedExtensionWitness(witness, async () => 'live')+ ).resolves.toBe('live')+ await expect(+ withLiveCommittedExtensionWitness({ ...witness }, async () => 'forged')+ ).rejects.toThrow(CommittedExtensionCredentialError.InvalidWitness)++ await store.revoke(offer.credentialId)+ await expect(+ withLiveCommittedExtensionWitness(witness, async () => 'replayed')+ ).rejects.toThrow(CommittedExtensionCredentialError.NotCommitted)+ })++ it('keeps one authorization epoch across installations and rotation but invalidates the rotated witness', async () => {+ const store = await open()+ const first = await store.offerProvisional(PRINCIPAL_A, 'official')+ await store.commitFromPair(first.credentialId)+ const firstWitness = await store.issueCommittedExtensionWitness(+ first.credentialId+ )++ const secondInstallPrincipal = {+ ...PRINCIPAL_A,+ clientInstallationId: 'install-a-2',+ }+ const secondInstall = await store.offerProvisional(+ secondInstallPrincipal,+ 'unverified'+ )+ await store.commitFromPair(secondInstall.credentialId)+ const secondWitness = await store.issueCommittedExtensionWitness(+ secondInstall.credentialId+ )++ const rotated = await store.offerProvisional(PRINCIPAL_A, 'official')+ await store.commitFromPair(rotated.credentialId)+ const rotatedWitness = await store.issueCommittedExtensionWitness(+ rotated.credentialId+ )++ expect(secondWitness.authorizationEpoch).toBe(+ firstWitness.authorizationEpoch+ )+ expect(rotatedWitness.authorizationEpoch).toBe(+ firstWitness.authorizationEpoch+ )+ expect(secondWitness.identityTrust).toBe('unverified')+ await expect(+ withLiveCommittedExtensionWitness(firstWitness, async () => undefined)+ ).rejects.toThrow(CommittedExtensionCredentialError.NotCommitted)+ await expect(+ withLiveCommittedExtensionWitness(rotatedWitness, async () => undefined)+ ).resolves.toBeUndefined()+ })++ it('issues only nominal, live absence witnesses after every identity credential is gone', async () => {+ const store = await open()+ const offer = await store.offerProvisional(PRINCIPAL_A, 'official')+ const identity = {+ browser: 'chromium' as const,+ extensionId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ }++ await expect(+ store.issueExtensionIdentityAbsenceWitness(+ identity.browser,+ identity.extensionId+ )+ ).rejects.toThrow(CommittedExtensionCredentialError.NotAbsent)++ await store.revokeExtensionIdentity(identity.browser, identity.extensionId)+ expect(store.findForAuth(offer.credentialId)).toBeNull()+ const witness = await store.issueExtensionIdentityAbsenceWitness(+ identity.browser,+ identity.extensionId+ )+ await expect(+ withLiveExtensionIdentityAbsenceWitness(witness, identity, async () =>+ Promise.resolve('absent')+ )+ ).resolves.toBe('absent')+ await expect(+ withLiveExtensionIdentityAbsenceWitness(+ { ...witness } as ExtensionIdentityAbsenceWitness,+ identity,+ async () => Promise.resolve('forged')+ )+ ).rejects.toThrow(CommittedExtensionCredentialError.InvalidWitness)++ await store.offerProvisional(PRINCIPAL_A, 'official')+ await expect(+ withLiveExtensionIdentityAbsenceWitness(witness, identity, async () =>+ Promise.resolve('stale')+ )+ ).rejects.toThrow(CommittedExtensionCredentialError.NotAbsent)+ })++ it('holds the credential queue while an absence-guarded cleanup runs', async () => {+ const store = await open()+ const identity = {+ browser: 'chromium' as const,+ extensionId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ }+ const witness = await store.issueExtensionIdentityAbsenceWitness(+ identity.browser,+ identity.extensionId+ )+ let release!: () => void+ let entered!: () => void+ const blocked = new Promise<void>((resolve) => {+ release = resolve+ })+ const started = new Promise<void>((resolve) => {+ entered = resolve+ })+ const cleanup = withLiveExtensionIdentityAbsenceWitness(+ witness,+ identity,+ async () => {+ entered()+ await blocked+ }+ )+ await started++ let offerSettled = false+ const offer = store.offerProvisional(PRINCIPAL_A, 'official').then(() => {+ offerSettled = true+ })+ await Promise.resolve()+ expect(offerSettled).toBe(false)++ release()+ await cleanup+ await offer+ expect(offerSettled).toBe(true)+ })++ it('assigns a new authorization epoch after full identity revoke and re-pair', async () => {+ const store = await open()+ const first = await store.offerProvisional(PRINCIPAL_A, 'official')+ await store.commitFromPair(first.credentialId)+ const firstWitness = await store.issueCommittedExtensionWitness(+ first.credentialId+ )++ await store.revokeExtensionIdentity(+ firstWitness.identity.browser,+ firstWitness.identity.extensionId+ )+ now = START + 1_000+ const repaired = await store.offerProvisional(PRINCIPAL_A, 'official')+ await store.commitFromPair(repaired.credentialId)+ const repairedWitness = await store.issueCommittedExtensionWitness(+ repaired.credentialId+ )++ expect(repairedWitness.authorizationEpoch).not.toBe(+ firstWitness.authorizationEpoch+ )+ })++ it('migrates v1 credentials for one verified identity to one durable epoch', async () => {+ await fs.mkdir(path.dirname(filePath), { recursive: true })+ await writeDoc({+ version: 1,+ credentials: [+ credential({ credentialId: 'legacy-a' }),+ credential({+ credentialId: 'legacy-a-2',+ principal: {+ ...PRINCIPAL_A,+ clientInstallationId: 'install-a-2',+ },+ identity: 'unverified',+ }),+ ],+ pendingPromote: null,+ })++ const store = await open()+ const migrated = await readDoc()+ expect(migrated.version).toBe(2)+ const epochs = migrated.credentials.map((entry) => entry.authorizationEpoch)+ expect(new Set(epochs).size).toBe(1)+ expect(epochs[0]).toMatch(+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u+ )+ expect(+ (await store.issueCommittedExtensionSnapshot()).witnesses+ ).toHaveLength(2)++ const durableMigration = await fs.readFile(filePath, 'utf-8')+ await open()+ await expect(fs.readFile(filePath, 'utf-8')).resolves.toBe(durableMigration)+ })++ it('safely migrates early v1 absence of predecessor and pending journal fields', async () => {+ await fs.mkdir(path.dirname(filePath), { recursive: true })+ const earlyCredential = credential({ credentialId: 'early-beta' })+ Reflect.deleteProperty(earlyCredential, 'predecessorId')+ await fs.writeFile(+ filePath,+ JSON.stringify({ version: 1, credentials: [earlyCredential] }),+ 'utf-8'+ )++ const store = await open()+ expect(store.findForAuth('early-beta')).toMatchObject({+ predecessorId: null,+ state: 'committed',+ })+ expect(await readDoc()).toMatchObject({+ version: 2,+ pendingPromote: null,+ })+ })++ it('preserves and rejects a v2 document with conflicting epochs for one identity', async () => {+ await fs.mkdir(path.dirname(filePath), { recursive: true })+ await writeDoc({+ version: 2,+ credentials: [+ credential({+ credentialId: 'conflict-a',+ authorizationEpoch: '11111111-1111-4111-8111-111111111111',+ }),+ credential({+ credentialId: 'conflict-a-2',+ principal: {+ ...PRINCIPAL_A,+ clientInstallationId: 'install-a-2',+ },+ authorizationEpoch: '22222222-2222-4222-8222-222222222222',+ }),+ ],+ pendingPromote: null,+ })+ const before = await fs.readFile(filePath, 'utf-8')++ await expect(open()).rejects.toThrow(+ CommittedExtensionCredentialError.EpochConflict+ )+ await expect(fs.readFile(filePath, 'utf-8')).resolves.toBe(before)+ })++ it('returns frozen credential copies that cannot mutate store liveness', async () => {+ const store = await open()+ const offer = await store.offerProvisional(PRINCIPAL_A, 'official')+ await store.commitFromPair(offer.credentialId)+ const listed = store.listCommitted()++ expect(Object.isFrozen(listed[0])).toBe(true)+ expect(Object.isFrozen(listed[0]?.principal)).toBe(true)+ expect(() => {+ ;(listed[0] as StoredCredential).state = 'provisional'+ }).toThrow()+ expect(store.findForAuth(offer.credentialId)?.state).toBe('committed')+ })++ it('bounds credential counts and rejects non-canonical revoke identities', async () => {+ await fs.mkdir(path.dirname(filePath), { recursive: true })+ await fs.writeFile(+ filePath,+ JSON.stringify({+ version: 1,+ credentials: Array.from({ length: 16_385 }, () => null),+ pendingPromote: null,+ }),+ 'utf-8'+ )+ await expect(open()).rejects.toThrow('mbp1 credential storage rejected')++ await fs.unlink(filePath)+ const store = await open()+ const offer = await store.offerProvisional(PRINCIPAL_A, 'official')+ await expect(+ store.revokeExtensionIdentity('chromium', 'A'.repeat(32))+ ).rejects.toThrow(CommittedExtensionCredentialError.InvalidInput)+ await expect(+ store.offerProvisional(+ {+ ...PRINCIPAL_A,+ verifiedOrigin: `chrome-extension://${'A'.repeat(32)}`,+ },+ 'official'+ )+ ).rejects.toThrow(CommittedExtensionCredentialError.InvalidInput)+ expect(store.findForAuth(offer.credentialId)).not.toBeNull()+ })++ it('preserves and rejects a document containing any malformed record', async () => {await fs.mkdir(path.dirname(filePath), { recursive: true })await fs.writeFile(filePath,@@ -588,19 +909,19 @@ describe('Mbp1CredentialStore', () => {'utf-8')- const store = await open()-- expect(store.listCommitted().map((c) => c.credentialId)).toEqual(['c1'])+ const before = await fs.readFile(filePath, 'utf-8')+ await expect(open()).rejects.toThrow('mbp1 credential storage rejected')+ await expect(fs.readFile(filePath, 'utf-8')).resolves.toBe(before)})- it('starts empty when the file is missing or unparsable', async () => {+ it('starts empty only when missing and preserves unparsable state', async () => {const missing = await open()expect(missing.listCommitted()).toEqual([])await fs.mkdir(path.dirname(filePath), { recursive: true })await fs.writeFile(filePath, 'not json', 'utf-8')- const corrupt = await open()- expect(corrupt.listCommitted()).toEqual([])+ await expect(open()).rejects.toThrow('mbp1 credential storage rejected')+ await expect(fs.readFile(filePath, 'utf-8')).resolves.toBe('not json')})})diff --git a/src/core/bridge/credential-store.ts b/src/core/bridge/credential-store.tsindex 6a55faaf..1c1ea369 100644--- a/src/core/bridge/credential-store.ts+++ b/src/core/bridge/credential-store.ts@@ -4,6 +4,7 @@ import { dirname } from 'node:path'import type { Browser } from '@shared/protocol/bridge'import writeFileAtomic from 'write-file-atomic'import { z } from 'zod'+import { normalizeExtensionIdentity } from './extension-identity-resolver'/** Default lifetime of a provisional credential that is never acked or used* (spec §6.7). */@@ -12,15 +13,26 @@ export const PROVISIONAL_TTL_MS = 10 * 60 * 1000/** Sibling of `pairing.json` / `endpoint.json` in the bridge data directory. */export const MBP1_CREDENTIALS_FILENAME = 'mbp1-credentials.json'-const DOCUMENT_VERSION = 1+const DOCUMENT_VERSION = 2+const LEGACY_DOCUMENT_VERSION = 1+const MAX_STORED_CREDENTIALS = 16_384+const MAX_CREDENTIAL_ID_LENGTH = 128+const MAX_MUTUAL_KEY_LENGTH = 256+const MAX_VERIFIED_ORIGIN_LENGTH = 512+const MAX_INSTALLATION_ID_LENGTH = 256+const MAX_EXTENSION_ID_LENGTH = 256+const UUID_V4_PATTERN =+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/uconst BrowserSchema: z.ZodType<Browser> = z.enum(['chromium', 'firefox'])-const CredentialPrincipalSchema = z.object({- browser: BrowserSchema,- verifiedOrigin: z.string().min(1),- clientInstallationId: z.string().min(1),-})+const CredentialPrincipalSchema = z+ .object({+ browser: BrowserSchema,+ verifiedOrigin: z.string().min(1).max(MAX_VERIFIED_ORIGIN_LENGTH),+ clientInstallationId: z.string().min(1).max(MAX_INSTALLATION_ID_LENGTH),+ })+ .strict()/** Spec §6.7: a second browser profile is a new principal, so issuing or* rotating one credential never affects another. */@@ -36,28 +48,76 @@ const IdentityTriStateSchema = z.enum([* time so a later reconnect renders the same trust level. */export type IdentityTriState = z.infer<typeof IdentityTriStateSchema>-const StoredCredentialSchema = z.object({- credentialId: z.string().min(1),- mutualKeyB64: z.string().min(1),- principal: CredentialPrincipalSchema,- /** The principal's committed `credentialId` this successor was offered- * against — `null` for a first pair. It is both half of the single-slot key- * and the compare-and-swap witness for the rotation (§6.7). Cleared once the- * credential itself becomes the committed one. */- predecessorId: z.string().min(1).nullable().catch(null),- state: z.enum(['provisional', 'committed']),- identity: IdentityTriStateSchema,- createdAt: z.number().int(),- committedAt: z.number().int().nullable(),-})+const StoredCredentialBaseSchema = z+ .object({+ credentialId: z.string().min(1).max(MAX_CREDENTIAL_ID_LENGTH),+ mutualKeyB64: z.string().min(1).max(MAX_MUTUAL_KEY_LENGTH),+ principal: CredentialPrincipalSchema,+ /** The principal's committed `credentialId` this successor was offered+ * against — `null` for a first pair. It is both half of the single-slot key+ * and the compare-and-swap witness for the rotation (§6.7). Cleared once the+ * credential itself becomes the committed one. */+ predecessorId: z.string().min(1).max(MAX_CREDENTIAL_ID_LENGTH).nullable(),+ state: z.enum(['provisional', 'committed']),+ identity: IdentityTriStateSchema,+ createdAt: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),+ committedAt: z+ .number()+ .int()+ .min(0)+ .max(Number.MAX_SAFE_INTEGER)+ .nullable(),+ })+ .strict()-export type StoredCredential = z.infer<typeof StoredCredentialSchema>+const StoredCredentialSchema = StoredCredentialBaseSchema.extend({+ authorizationEpoch: z.string().regex(UUID_V4_PATTERN),+})-const CredentialDocumentSchema = z.object({- version: z.literal(DOCUMENT_VERSION),- credentials: z.array(z.unknown()).catch([]),- pendingPromote: z.string().min(1).nullable().catch(null),+const LegacyStoredCredentialSchema = StoredCredentialBaseSchema.omit({+ predecessorId: true,})+ .extend({+ // Early beta documents could omit this field. Mapping only absence to+ // null is safe: a rotation then fails its predecessor CAS rather than+ // authenticating against an inferred predecessor.+ predecessorId: z+ .string()+ .min(1)+ .max(MAX_CREDENTIAL_ID_LENGTH)+ .nullable()+ .optional(),+ })+ .transform((credential) => ({+ ...credential,+ predecessorId: credential.predecessorId ?? null,+ }))++/**+ * `authorizationEpoch` is optional in the exported structural type solely so+ * existing MBP1 state-machine doubles remain source-compatible. Every real+ * credential loaded or written by {@link Mbp1CredentialStore} has it; witness+ * issuance rejects a record without it.+ */+export type StoredCredential = z.infer<typeof StoredCredentialBaseSchema> & {+ authorizationEpoch?: string+}++const CredentialDocumentSchema = z+ .object({+ version: z.literal(DOCUMENT_VERSION),+ credentials: z.array(z.unknown()).max(MAX_STORED_CREDENTIALS),+ pendingPromote: z.string().min(1).nullable(),+ })+ .strict()++const LegacyCredentialDocumentSchema = z+ .object({+ version: z.literal(LEGACY_DOCUMENT_VERSION),+ credentials: z.array(z.unknown()).max(MAX_STORED_CREDENTIALS),+ pendingPromote: z.string().min(1).nullable().optional(),+ })+ .strict()interface CredentialDocument {version: typeof DOCUMENT_VERSION@@ -65,6 +125,76 @@ interface CredentialDocument {pendingPromote: string | null}+const COMMITTED_EXTENSION_WITNESS_BRAND: unique symbol = Symbol(+ 'motrix.mbp1.committed-extension-witness'+)+const COMMITTED_EXTENSION_SNAPSHOT_BRAND: unique symbol = Symbol(+ 'motrix.mbp1.committed-extension-snapshot'+)+const EXTENSION_IDENTITY_ABSENCE_WITNESS_BRAND: unique symbol = Symbol(+ 'motrix.mbp1.extension-identity-absence-witness'+)++export interface CommittedExtensionCredentialWitness {+ readonly [COMMITTED_EXTENSION_WITNESS_BRAND]: true+ readonly identity: {+ readonly kind: 'extension'+ readonly browser: Browser+ readonly extensionId: string+ }+ readonly verifiedOrigin: string+ readonly identityTrust: IdentityTriState+ readonly authorizationEpoch: string+ readonly createdAt: number+ readonly committedAt: number+}++export interface CommittedExtensionCredentialSnapshot {+ readonly [COMMITTED_EXTENSION_SNAPSHOT_BRAND]: true+ readonly witnesses: readonly CommittedExtensionCredentialWitness[]+}++/**+ * Nominal proof that one transport identity currently has no committed or+ * provisional MBP1 credential in the issuing store. The proof is useful only+ * through {@link withLiveExtensionIdentityAbsenceWitness}; copying its public+ * fields does not copy the issuing store's queue-bound claim.+ */+export interface ExtensionIdentityAbsenceWitness {+ readonly [EXTENSION_IDENTITY_ABSENCE_WITNESS_BRAND]: true+ readonly identity: {+ readonly kind: 'extension'+ readonly browser: Browser+ readonly extensionId: string+ }+}++export const CommittedExtensionCredentialError = Object.freeze({+ InvalidWitness: 'mbp1 committed extension witness rejected',+ NotCommitted: 'mbp1 committed extension credential unavailable',+ NotAbsent: 'mbp1 extension credential identity still authorized',+ EpochConflict: 'mbp1 extension authorization epoch conflict',+ InvalidInput: 'mbp1 credential input rejected',+ CapacityExceeded: 'mbp1 credential capacity exceeded',+} as const)++interface WitnessClaim {+ run<T>(operation: () => Promise<T>): Promise<T>+}++interface SnapshotClaim {+ run<T>(operation: () => Promise<T>): Promise<T>+}++interface AbsenceWitnessClaim {+ readonly key: string+ run<T>(operation: () => Promise<T>): Promise<T>+}++const witnessClaims = new WeakMap<object, WitnessClaim>()+const snapshotClaims = new WeakMap<object, SnapshotClaim>()+const absenceWitnessClaims = new WeakMap<object, AbsenceWitnessClaim>()+/*** Injective principal key: a delimiter-free concatenation of three* attacker-influenced strings is not (`{browser:'a', origin:'bc'}` would@@ -74,6 +204,67 @@ export function principalKey(p: CredentialPrincipal): string {return JSON.stringify([p.browser, p.verifiedOrigin, p.clientInstallationId])}+/**+ * Run a projection mutation while the issuing credential store's queue proves+ * the exact credential is still committed. Holding that queue until+ * `operation` settles prevents an in-process revoke or rotation from racing+ * between the liveness check and the projection write.+ */+export function withLiveCommittedExtensionWitness<T>(+ witness: CommittedExtensionCredentialWitness,+ operation: () => Promise<T>+): Promise<T> {+ const claim = witnessClaims.get(witness)+ if (!claim) {+ return Promise.reject(+ new Error(CommittedExtensionCredentialError.InvalidWitness)+ )+ }+ return claim.run(operation)+}++/** The snapshot counterpart of {@link withLiveCommittedExtensionWitness}.+ * Its fingerprint proves the caller supplied the complete committed set,+ * including an authentically empty set after a full revoke. */+export function withLiveCommittedExtensionSnapshot<T>(+ snapshot: CommittedExtensionCredentialSnapshot,+ operation: (+ witnesses: readonly CommittedExtensionCredentialWitness[]+ ) => Promise<T>+): Promise<T> {+ const claim = snapshotClaims.get(snapshot)+ if (!claim) {+ return Promise.reject(+ new Error(CommittedExtensionCredentialError.InvalidWitness)+ )+ }+ return claim.run(() => operation(snapshot.witnesses))+}++/**+ * Run a cleanup mutation while the issuing credential store's serialization+ * queue proves the named identity is still fully absent. This makes+ * projection deletion depend on credential deletion at the API boundary and+ * prevents a new provisional credential from appearing during that deletion.+ */+export function withLiveExtensionIdentityAbsenceWitness<T>(+ witness: ExtensionIdentityAbsenceWitness,+ expectedIdentity: { readonly browser: Browser; readonly extensionId: string },+ operation: () => Promise<T>+): Promise<T> {+ const normalized = normalizeTransportIdentity(+ expectedIdentity.browser,+ expectedIdentity.extensionId+ )+ const claim = absenceWitnessClaims.get(witness)+ if (normalized === null || claim?.key !== transportIdentityKey(normalized)) {+ return Promise.reject(+ new Error(CommittedExtensionCredentialError.InvalidWitness)+ )+ }+ return claim.run(operation)+}+/*** Durable MBP1 credential storage — the server half of the §6.7 two-phase* commit.@@ -115,10 +306,13 @@ export class Mbp1CredentialStore {): Promise<Mbp1CredentialStore> {const now = opts?.now ?? Date.nowconst parsed = await readDocument(filePath)- const { credentials, changed } = reconcile(parsed, now())+ const { credentials, changed } = reconcile(parsed, readClock(now))// The replay is durable before any caller holds the store, which is what// makes "replay completes before /v1 accepts authentication" true.- if (changed) await writeDocument(filePath, credentials)+ if (changed) {+ await writeDocument(filePath, credentials)+ await syncParentDirectory(filePath)+ }return new Mbp1CredentialStore(filePath, credentials, now)}@@ -136,14 +330,19 @@ export class Mbp1CredentialStore {identity: IdentityTriState): Promise<{ credentialId: string; mutualKeyB64: string }> {return this.enqueue(async () => {- const key = principalKey(principal)+ const parsedPrincipal = parseCredentialPrincipal(principal)+ if (!IdentityTriStateSchema.safeParse(identity).success) {+ throw new Error(CommittedExtensionCredentialError.InvalidInput)+ }+ const operationNow = this.readNow()+ const key = principalKey(parsedPrincipal)const predecessorId = this.committedForKey(key)?.credentialId ?? nullconst slot = this.credentials.find((c) =>c.state === 'provisional' &&principalKey(c.principal) === key &&c.predecessorId === predecessorId &&- !isExpiredAt(c, this.now())+ !isExpiredAt(c, operationNow))if (slot) {return {@@ -151,24 +350,29 @@ export class Mbp1CredentialStore {mutualKeyB64: slot.mutualKeyB64,}}+ const retained = this.credentials.filter(+ (credential) =>+ credential.state !== 'provisional' ||+ principalKey(credential.principal) !== key+ )+ if (retained.length >= MAX_STORED_CREDENTIALS) {+ throw new Error(CommittedExtensionCredentialError.CapacityExceeded)+ }const fresh: StoredCredential = {credentialId: randomUUID(),mutualKeyB64: randomBytes(32).toString('base64url'),- principal: { ...principal },+ principal: { ...parsedPrincipal },predecessorId,state: 'provisional',identity,- createdAt: this.now(),+ authorizationEpoch:+ this.authorizationEpochForPrincipal(parsedPrincipal) ?? randomUUID(),+ createdAt: operationNow,committedAt: null,}// Replacing the slot (its occupant expired, or the committed credential// moved) drops the previous provisional instead of accumulating P₁…Pₙ.- const next = [- ...this.credentials.filter(- (c) => c.state !== 'provisional' || principalKey(c.principal) !== key- ),- fresh,- ]+ const next = [...retained, fresh]await this.persist(next)return {credentialId: fresh.credentialId,@@ -184,6 +388,7 @@ export class Mbp1CredentialStore {* as {@link promoteOnReconnect}.*/async commitFromPair(credentialId: string): Promise<void> {+ assertCredentialId(credentialId)return this.enqueue(() => this.promoteDurably(credentialId))}@@ -198,36 +403,100 @@ export class Mbp1CredentialStore {* whose state is `provisional`.*/async promoteOnReconnect(credentialId: string): Promise<void> {+ assertCredentialId(credentialId)return this.enqueue(() => this.promoteDurably(credentialId))}/** The credential a reconnect may authenticate against: committed, or a* provisional that is still live and still the current successor. */findForAuth(credentialId: string): StoredCredential | null {+ if (!validCredentialId(credentialId)) return nullconst found = this.credentials.find((c) => c.credentialId === credentialId)if (!found) return null- if (found.state === 'committed') return found- if (isExpiredAt(found, this.now())) return null+ if (found.state === 'committed') return freezeCredential(found)+ if (isExpiredAt(found, this.readNow())) return null// A successor whose predecessor is no longer the committed credential can// never be promoted, so it must not authenticate either — otherwise the// §6.7 ordering would owe an accept the promote cannot back.const key = principalKey(found.principal)const committedId = this.committedForKey(key)?.credentialId ?? null- return committedId === found.predecessorId ? found : null+ return committedId === found.predecessorId ? freezeCredential(found) : null}committedFor(principal: CredentialPrincipal): StoredCredential | null {- return this.committedForKey(principalKey(principal))+ const parsed = CredentialPrincipalSchema.safeParse(principal)+ if (!parsed.success) return null+ const credential = this.committedForKey(principalKey(parsed.data))+ return credential ? freezeCredential(credential) : null}listCommitted(): StoredCredential[] {- return this.credentials.filter((c) => c.state === 'committed')+ return this.credentials+ .filter((credential) => credential.state === 'committed')+ .map(freezeCredential)+ }++ /** Issue one nominal projection witness for an exact committed credential.+ * Callers must retain the credential id from the MBP1 commit/reconnect path;+ * there is intentionally no identity-only or "first matching" fallback. */+ async issueCommittedExtensionWitness(+ credentialId: string+ ): Promise<CommittedExtensionCredentialWitness> {+ assertCredentialId(credentialId)+ return this.enqueue(async () => {+ const credential = this.credentials.find(+ (candidate) =>+ candidate.credentialId === credentialId &&+ candidate.state === 'committed'+ )+ if (!credential) {+ throw new Error(CommittedExtensionCredentialError.NotCommitted)+ }+ return this.issueWitness(credential)+ })+ }++ /** Issue a complete, nominal snapshot for startup/cleanup reconciliation. */+ async issueCommittedExtensionSnapshot(): Promise<CommittedExtensionCredentialSnapshot> {+ return this.enqueue(async () => {+ this.assertOneEpochPerTransportIdentity()+ const committed = this.credentials.filter(+ (credential) => credential.state === 'committed'+ )+ const witnesses = Object.freeze(+ committed.map((credential) => this.issueWitness(credential))+ )+ const snapshot = { witnesses } as CommittedExtensionCredentialSnapshot+ Object.defineProperty(snapshot, COMMITTED_EXTENSION_SNAPSHOT_BRAND, {+ configurable: false,+ enumerable: false,+ value: true,+ writable: false,+ })+ Object.freeze(snapshot)+ const fingerprint = committedFingerprint(committed)+ snapshotClaims.set(snapshot, {+ run: <T>(operation: () => Promise<T>): Promise<T> =>+ this.enqueue(async () => {+ const liveCommitted = this.credentials.filter(+ (credential) => credential.state === 'committed'+ )+ if (committedFingerprint(liveCommitted) !== fingerprint) {+ throw new Error(CommittedExtensionCredentialError.NotCommitted)+ }+ this.assertOneEpochPerTransportIdentity()+ return operation()+ }),+ })+ return snapshot+ })}/** Revoke a credential and, in the same write, the provisional successor it* was to be rotated into — that successor's trust derives entirely from the* revoked credential, and §6.7 allows no silent re-trust. */async revoke(credentialId: string): Promise<void> {+ assertCredentialId(credentialId)return this.enqueue(async () => {const next = this.credentials.filter((c) =>@@ -254,13 +523,17 @@ export class Mbp1CredentialStore {browser: Browser,extensionId: string): Promise<number> {+ const identity = normalizeTransportIdentity(browser, extensionId)+ if (identity === null) {+ throw new Error(CommittedExtensionCredentialError.InvalidInput)+ }return this.enqueue(async () => {const next = this.credentials.filter((credential) =>!principalMatchesExtensionIdentity(credential.principal,- browser,- extensionId+ identity.browser,+ identity.extensionId))const revoked = this.credentials.length - next.length@@ -270,23 +543,181 @@ export class Mbp1CredentialStore {})}+ /**+ * Issue a nominal, queue-bound proof that an extension transport identity+ * has no committed or provisional credential. A surviving rotation slot or+ * a newly offered first-pair credential makes issuance fail closed.+ */+ async issueExtensionIdentityAbsenceWitness(+ browser: Browser,+ extensionId: string+ ): Promise<ExtensionIdentityAbsenceWitness> {+ const identity = normalizeTransportIdentity(browser, extensionId)+ if (identity === null) {+ throw new Error(CommittedExtensionCredentialError.InvalidInput)+ }+ return this.enqueue(async () => {+ this.assertExtensionIdentityAbsent(identity)+ return this.issueAbsenceWitness(identity)+ })+ }+/** Drop provisionals that were never acked or used within the TTL (§6.7).* Committed credentials are never swept — only explicit revocation or a* rotation removes one. */async sweepExpiredProvisionals(): Promise<void> {return this.enqueue(async () => {- const now = this.now()+ const now = this.readNow()const next = this.credentials.filter((c) => !isExpiredAt(c, now))if (next.length === this.credentials.length) returnawait this.persist(next)})}+ private issueWitness(+ credential: StoredCredential+ ): CommittedExtensionCredentialWitness {+ if (+ credential.state !== 'committed' ||+ credential.committedAt === null ||+ credential.authorizationEpoch === undefined+ ) {+ throw new Error(CommittedExtensionCredentialError.NotCommitted)+ }+ const transport = transportIdentityForPrincipal(credential.principal)+ if (!transport) {+ throw new Error(CommittedExtensionCredentialError.NotCommitted)+ }+ const witness = {+ identity: Object.freeze({+ kind: 'extension' as const,+ browser: transport.browser,+ extensionId: transport.extensionId,+ }),+ verifiedOrigin: credential.principal.verifiedOrigin,+ identityTrust: credential.identity,+ authorizationEpoch: credential.authorizationEpoch,+ createdAt: credential.createdAt,+ committedAt: credential.committedAt,+ } as CommittedExtensionCredentialWitness+ Object.defineProperty(witness, COMMITTED_EXTENSION_WITNESS_BRAND, {+ configurable: false,+ enumerable: false,+ value: true,+ writable: false,+ })+ Object.freeze(witness)+ const credentialId = credential.credentialId+ const authorizationEpoch = credential.authorizationEpoch+ witnessClaims.set(witness, {+ run: <T>(operation: () => Promise<T>): Promise<T> =>+ this.enqueue(async () => {+ const live = this.credentials.find(+ (candidate) =>+ candidate.credentialId === credentialId &&+ candidate.state === 'committed' &&+ candidate.authorizationEpoch === authorizationEpoch+ )+ if (!live) {+ throw new Error(CommittedExtensionCredentialError.NotCommitted)+ }+ return operation()+ }),+ })+ return witness+ }++ private issueAbsenceWitness(identity: {+ browser: Browser+ extensionId: string+ }): ExtensionIdentityAbsenceWitness {+ const key = transportIdentityKey(identity)+ const witness = {+ identity: Object.freeze({ kind: 'extension' as const, ...identity }),+ } as ExtensionIdentityAbsenceWitness+ Object.defineProperty(witness, EXTENSION_IDENTITY_ABSENCE_WITNESS_BRAND, {+ configurable: false,+ enumerable: false,+ value: true,+ writable: false,+ })+ Object.freeze(witness)+ absenceWitnessClaims.set(witness, {+ key,+ run: <T>(operation: () => Promise<T>): Promise<T> =>+ this.enqueue(async () => {+ this.assertExtensionIdentityAbsent(identity)+ return operation()+ }),+ })+ return witness+ }++ private assertExtensionIdentityAbsent(identity: {+ browser: Browser+ extensionId: string+ }): void {+ if (+ this.credentials.some((credential) =>+ principalMatchesExtensionIdentity(+ credential.principal,+ identity.browser,+ identity.extensionId+ )+ )+ ) {+ throw new Error(CommittedExtensionCredentialError.NotAbsent)+ }+ }++ private authorizationEpochForPrincipal(+ principal: CredentialPrincipal+ ): string | null {+ const key = transportKeyForPrincipal(principal)+ if (key === null) {+ throw new Error(CommittedExtensionCredentialError.NotCommitted)+ }+ const epochs = new Set(+ this.credentials+ .filter(+ (credential) => transportKeyForPrincipal(credential.principal) === key+ )+ .map((credential) => credential.authorizationEpoch)+ .filter((epoch): epoch is string => epoch !== undefined)+ )+ if (epochs.size > 1) {+ throw new Error(CommittedExtensionCredentialError.EpochConflict)+ }+ return epochs.values().next().value ?? null+ }++ private assertOneEpochPerTransportIdentity(): void {+ const byIdentity = new Map<string, string>()+ for (const credential of this.credentials) {+ if (credential.state !== 'committed') continue+ const key = transportKeyForPrincipal(credential.principal)+ const epoch = credential.authorizationEpoch+ if (key === null || epoch === undefined) {+ throw new Error(CommittedExtensionCredentialError.EpochConflict)+ }+ const seen = byIdentity.get(key)+ if (seen !== undefined && seen !== epoch) {+ throw new Error(CommittedExtensionCredentialError.EpochConflict)+ }+ byIdentity.set(key, epoch)+ }+ }+/** Commit-new and revoke-old as one document write: a crash can leave both* credentials valid or neither only if these are two writes. */private async promoteDurably(credentialId: string): Promise<void> {const target = this.credentials.find((c) => c.credentialId === credentialId)- if (target?.state !== 'provisional' || isExpiredAt(target, this.now())) {+ const now = this.readNow()+ if (+ target?.state !== 'provisional' ||+ isExpiredAt(target, now) ||+ now < target.createdAt+ ) {throw new Error('mbp1 credential promote rejected: no live provisional')}// Compare-and-swap on the principal's current committed credentialId.@@ -298,7 +729,7 @@ export class Mbp1CredentialStore {if (committedId !== target.predecessorId) {throw new Error('mbp1 credential promote rejected: stale rotation')}- await this.persist(applyPromote(this.credentials, target, this.now()))+ await this.persist(applyPromote(this.credentials, target, now))}private committedForKey(key: string): StoredCredential | null {@@ -309,6 +740,10 @@ export class Mbp1CredentialStore {)}+ private readNow(): number {+ return readClock(this.now)+ }+/*** `rename` → memory → parent-directory sync, in that order, and the order is* the whole design.@@ -346,6 +781,139 @@ export class Mbp1CredentialStore {}}+function parseCredentialPrincipal(+ principal: CredentialPrincipal+): CredentialPrincipal {+ const parsed = CredentialPrincipalSchema.safeParse(principal)+ if (!parsed.success || transportIdentityForPrincipal(parsed.data) === null) {+ throw new Error(CommittedExtensionCredentialError.InvalidInput)+ }+ return parsed.data+}++function normalizeTransportIdentity(+ browser: Browser,+ extensionId: string+): { browser: Browser; extensionId: string } | null {+ if (+ (browser !== 'chromium' && browser !== 'firefox') ||+ typeof extensionId !== 'string' ||+ extensionId.length === 0 ||+ extensionId.length > MAX_EXTENSION_ID_LENGTH ||+ extensionId !== extensionId.toLowerCase()+ ) {+ return null+ }+ const scheme = browser === 'chromium' ? 'chrome-extension' : 'moz-extension'+ const normalized = normalizeExtensionIdentity({+ browser,+ verifiedOrigin: `${scheme}://${extensionId}`,+ claimedExtensionId: extensionId,+ })+ if (!normalized.ok || normalized.identity.originHost !== extensionId) {+ return null+ }+ return { browser, extensionId }+}++function validCredentialId(value: unknown): value is string {+ return (+ typeof value === 'string' &&+ value.length > 0 &&+ value.length <= MAX_CREDENTIAL_ID_LENGTH+ )+}++function assertCredentialId(value: unknown): asserts value is string {+ if (!validCredentialId(value)) {+ throw new Error(CommittedExtensionCredentialError.InvalidInput)+ }+}++function readClock(clock: () => number): number {+ let value: number+ try {+ value = clock()+ } catch {+ throw new Error(CommittedExtensionCredentialError.InvalidInput)+ }+ if (!Number.isSafeInteger(value) || value < 0) {+ throw new Error(CommittedExtensionCredentialError.InvalidInput)+ }+ return value+}++function freezeCredential(credential: StoredCredential): StoredCredential {+ return Object.freeze({+ ...credential,+ principal: Object.freeze({ ...credential.principal }),+ })+}++function transportIdentityForPrincipal(principal: CredentialPrincipal): {+ browser: Browser+ extensionId: string+} | null {+ let parsed: URL+ try {+ parsed = new URL(principal.verifiedOrigin)+ } catch {+ return null+ }+ const normalized = normalizeExtensionIdentity({+ browser: principal.browser,+ verifiedOrigin: principal.verifiedOrigin,+ claimedExtensionId: parsed.hostname,+ })+ if (+ !normalized.ok ||+ normalized.identity.originHost.length > MAX_EXTENSION_ID_LENGTH ||+ normalized.identity.originHost !==+ normalized.identity.originHost.toLowerCase()+ ) {+ return null+ }+ return {+ browser: normalized.identity.browser,+ extensionId: normalized.identity.originHost,+ }+}++function transportKeyForPrincipal(+ principal: CredentialPrincipal+): string | null {+ const identity = transportIdentityForPrincipal(principal)+ return identity+ ? JSON.stringify([identity.browser, identity.extensionId])+ : null+}++function transportIdentityKey(identity: {+ browser: Browser+ extensionId: string+}): string {+ return JSON.stringify([identity.browser, identity.extensionId])+}++function committedFingerprint(+ credentials: readonly StoredCredential[]+): string {+ return JSON.stringify(+ credentials+ .map((credential) => [+ credential.credentialId,+ credential.authorizationEpoch ?? null,+ principalKey(credential.principal),+ credential.identity,+ credential.createdAt,+ credential.committedAt,+ ])+ .sort((left, right) =>+ JSON.stringify(left).localeCompare(JSON.stringify(right))+ )+ )+}+function principalMatchesExtensionIdentity(principal: CredentialPrincipal,browser: Browser,@@ -393,34 +961,62 @@ function isExpiredAt(credential: StoredCredential, now: number): boolean {interface ParsedDocument {credentials: StoredCredential[]pendingPromote: string | null+ legacy: boolean}-/** Read the document defensively: a missing, unparsable, or wrong-version file- * yields an empty store, and individual malformed records are dropped rather- * than failing the whole load. */+const CREDENTIAL_STORAGE_REJECTED = 'mbp1 credential storage rejected'++/** Missing is a clean first run. Corrupt, future, or partially malformed+ * state is preserved and rejected wholesale; silently dropping credentials+ * would turn storage damage into a fresh authorization boundary. */async function readDocument(filePath: string): Promise<ParsedDocument> {- const empty: ParsedDocument = { credentials: [], pendingPromote: null }+ const empty: ParsedDocument = {+ credentials: [],+ pendingPromote: null,+ legacy: false,+ }let raw: stringtry {raw = await readFile(filePath, 'utf-8')- } catch {- return empty+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return empty+ throw new Error(CREDENTIAL_STORAGE_REJECTED)}let json: unknowntry {json = JSON.parse(raw)} catch {- return empty+ throw new Error(CREDENTIAL_STORAGE_REJECTED)}- const envelope = CredentialDocumentSchema.safeParse(json)- if (!envelope.success) return empty+ const currentEnvelope = CredentialDocumentSchema.safeParse(json)+ const legacyEnvelope = LegacyCredentialDocumentSchema.safeParse(json)+ if (!currentEnvelope.success && !legacyEnvelope.success) {+ throw new Error(CREDENTIAL_STORAGE_REJECTED)+ }+ const legacy = !currentEnvelope.success+ const envelope = currentEnvelope.success+ ? currentEnvelope.data+ : legacyEnvelope.success+ ? legacyEnvelope.data+ : null+ if (envelope === null) throw new Error(CREDENTIAL_STORAGE_REJECTED)+ const recordSchema = legacy+ ? LegacyStoredCredentialSchema+ : StoredCredentialSchemaconst credentials: StoredCredential[] = []- for (const record of envelope.data.credentials) {- const parsed = StoredCredentialSchema.safeParse(record)- if (parsed.success) credentials.push(parsed.data)+ for (const record of envelope.credentials) {+ const parsed = recordSchema.safeParse(record)+ if (!parsed.success || !validCredentialState(parsed.data)) {+ throw new Error(CREDENTIAL_STORAGE_REJECTED)+ }+ credentials.push(parsed.data)+ }+ return {+ credentials,+ pendingPromote: envelope.pendingPromote ?? null,+ legacy,}- return { credentials, pendingPromote: envelope.data.pendingPromote }}/** Journal replay plus convergence to one committed credential per principal@@ -428,11 +1024,12 @@ async function readDocument(filePath: string): Promise<ParsedDocument> {* handed out. */function reconcile(doc: ParsedDocument,- now: number+ now: number,+ makeEpoch: () => string = randomUUID): { credentials: StoredCredential[]; changed: boolean } {let credentials = doc.credentials// A journal entry always forces the write-back, if only to clear it.- let changed = doc.pendingPromote !== null+ let changed = doc.pendingPromote !== null || doc.legacyif (doc.pendingPromote !== null) {const target = credentials.find(@@ -459,7 +1056,32 @@ function reconcile(: !isExpiredAt(c, now))if (converged.length !== credentials.length) changed = true- return { credentials: converged, changed }++ const groups = new Map<string, StoredCredential[]>()+ for (const credential of converged) {+ const key = transportKeyForPrincipal(credential.principal)+ if (key === null) throw new Error(CREDENTIAL_STORAGE_REJECTED)+ const group = groups.get(key) ?? []+ group.push(credential)+ groups.set(key, group)+ }+ const migrated: StoredCredential[] = []+ for (const group of groups.values()) {+ const epochs = new Set(+ group+ .map((credential) => credential.authorizationEpoch)+ .filter((epoch): epoch is string => epoch !== undefined)+ )+ if (epochs.size > 1) {+ throw new Error(CommittedExtensionCredentialError.EpochConflict)+ }+ const epoch = epochs.values().next().value ?? makeEpoch()+ for (const credential of group) {+ if (credential.authorizationEpoch !== epoch) changed = true+ migrated.push({ ...credential, authorizationEpoch: epoch })+ }+ }+ return { credentials: migrated, changed }}function committedOrder(credential: StoredCredential): number {@@ -501,6 +1123,15 @@ async function writeDocument(filePath: string,credentials: StoredCredential[]): Promise<void> {+ if (+ credentials.some(+ (credential) =>+ credential.authorizationEpoch === undefined ||+ !validCredentialState(credential)+ )+ ) {+ throw new Error(CREDENTIAL_STORAGE_REJECTED)+ }await mkdir(dirname(filePath), { recursive: true })const document: CredentialDocument = {version: DOCUMENT_VERSION,@@ -532,3 +1163,10 @@ async function writeDocument(mode: 0o600,})}++function validCredentialState(credential: StoredCredential): boolean {+ return credential.state === 'committed'+ ? credential.committedAt !== null &&+ credential.committedAt >= credential.createdAt+ : credential.committedAt === null+}diff --git a/src/core/bridge/extension-identity-resolver.test.ts b/src/core/bridge/extension-identity-resolver.test.tsnew file mode 100644index 00000000..88e4593d--- /dev/null+++ b/src/core/bridge/extension-identity-resolver.test.ts@@ -0,0 +1,349 @@+import { describe, expect, it } from 'vitest'+import {+ BUILTIN_OFFICIAL_EXTENSION_ENTRIES,+ createExtensionIdentityResolver,+ ExtensionIdentityResolutionError,+ type NormalizedExtensionIdentity,+ normalizeExtensionIdentity,+ parseDevTrustedExtensions,+} from './extension-identity-resolver'+import { TrustedExtensionRegistry } from './trusted-extension-registry'++const BUILTIN_CHROMIUM_ID = 'ibpkjhgpbidfmbmomagmldcdlpbmchgi'+const BUILTIN_FIREFOX_ID = '[email protected]'+const OTHER_CHROMIUM_ID = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'+const DEV_CHROMIUM_ID = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'+const FIREFOX_ORIGIN = 'moz-extension://8c1a0d6e-1f2b-4c3d-9e0a-5b6c7d8e9f01'++function normalizedChromium(+ id = BUILTIN_CHROMIUM_ID+): NormalizedExtensionIdentity {+ const result = normalizeExtensionIdentity({+ browser: 'chromium',+ verifiedOrigin: `chrome-extension://${id}`,+ claimedExtensionId: id,+ })+ if (!result.ok) throw new Error('test identity did not normalize')+ return result.identity+}++function normalizedFirefox(): NormalizedExtensionIdentity {+ const result = normalizeExtensionIdentity({+ browser: 'firefox',+ verifiedOrigin: FIREFOX_ORIGIN,+ claimedExtensionId: BUILTIN_FIREFOX_ID,+ })+ if (!result.ok) throw new Error('test identity did not normalize')+ return result.identity+}++describe('extension identity allowlist', () => {+ it('owns a frozen built-in allowlist independent from callers', () => {+ expect(BUILTIN_OFFICIAL_EXTENSION_ENTRIES).toContainEqual({+ browser: 'chromium',+ id: BUILTIN_CHROMIUM_ID,+ })+ expect(BUILTIN_OFFICIAL_EXTENSION_ENTRIES).toContainEqual({+ browser: 'firefox',+ id: BUILTIN_FIREFOX_ID,+ })+ expect(Object.isFrozen(BUILTIN_OFFICIAL_EXTENSION_ENTRIES)).toBe(true)+ for (const entry of BUILTIN_OFFICIAL_EXTENSION_ENTRIES) {+ expect(Object.isFrozen(entry)).toBe(true)+ }+ })++ it('enables explicit development entries only in non-production', () => {+ const entries = [{ browser: 'chromium' as const, id: DEV_CHROMIUM_ID }]+ const development = createExtensionIdentityResolver({+ environment: 'non-production',+ developmentEntries: entries,+ })+ const production = createExtensionIdentityResolver({+ environment: 'production',+ developmentEntries: entries,+ })++ expect(development.isOfficialId('chromium', DEV_CHROMIUM_ID)).toBe(true)+ expect(production.isOfficialId('chromium', DEV_CHROMIUM_ID)).toBe(false)+ expect(production.developmentEntries).toEqual([])+ expect(production.officialEntries).not.toContainEqual(entries[0])+ })++ it('copies and freezes development inputs before they become official', () => {+ const entries = [{ browser: 'chromium' as const, id: DEV_CHROMIUM_ID }]+ const resolver = createExtensionIdentityResolver({+ environment: 'non-production',+ developmentEntries: entries,+ })++ entries[0].id = OTHER_CHROMIUM_ID+ entries.push({ browser: 'chromium', id: OTHER_CHROMIUM_ID })++ expect(resolver.isOfficialId('chromium', DEV_CHROMIUM_ID)).toBe(true)+ expect(resolver.isOfficialId('chromium', OTHER_CHROMIUM_ID)).toBe(false)+ expect(Object.isFrozen(resolver.developmentEntries)).toBe(true)+ expect(Object.isFrozen(resolver.officialEntries)).toBe(true)+ expect(Object.isFrozen(resolver.developmentEntries[0])).toBe(true)+ })++ it('never crosses browser namespaces', () => {+ const resolver = createExtensionIdentityResolver({+ environment: 'production',+ developmentEntries: [],+ })++ expect(resolver.isOfficialId('chromium', BUILTIN_CHROMIUM_ID)).toBe(true)+ expect(resolver.isOfficialId('firefox', BUILTIN_CHROMIUM_ID)).toBe(false)+ })++ it('cannot be elevated by user-added or imported registry entries', async () => {+ const resolver = createExtensionIdentityResolver({+ environment: 'production',+ developmentEntries: [],+ })+ const store = {+ read: async () =>+ JSON.stringify([+ {+ id: OTHER_CHROMIUM_ID,+ browser: 'chromium',+ source: 'user-added',+ addedAt: 1,+ },+ {+ id: '[email protected]',+ browser: 'firefox',+ source: 'imported',+ addedAt: 2,+ },+ ]),+ write: async () => {},+ }+ const registry = new TrustedExtensionRegistry(store, [+ ...resolver.officialEntries,+ ])+ await registry.load()++ expect(registry.has(OTHER_CHROMIUM_ID, 'chromium')).toBe(true)+ expect(registry.has('[email protected]', 'firefox')).toBe(true)+ expect(resolver.isOfficialId('chromium', OTHER_CHROMIUM_ID)).toBe(false)+ expect(resolver.isOfficialId('firefox', '[email protected]')).toBe(false)+ })++ it('parses development entries without reading process state', () => {+ expect(+ parseDevTrustedExtensions(+ ' chromium:aaa, bad,firefox:[email protected],unknown:nope '+ )+ ).toEqual([+ { browser: 'chromium', id: 'aaa' },+ { browser: 'firefox', id: '[email protected]' },+ ])+ expect(parseDevTrustedExtensions(undefined)).toEqual([])+ })+})++describe('normalizeExtensionIdentity', () => {+ it('derives Chromium identity only when the verified Origin host strictly matches the claim', () => {+ const result = normalizeExtensionIdentity({+ browser: 'chromium',+ verifiedOrigin: `chrome-extension://${BUILTIN_CHROMIUM_ID}`,+ claimedExtensionId: BUILTIN_CHROMIUM_ID,+ })++ expect(result).toEqual({+ ok: true,+ identity: {+ browser: 'chromium',+ originHost: BUILTIN_CHROMIUM_ID,+ verifiedExtensionId: BUILTIN_CHROMIUM_ID,+ },+ })+ expect(Object.isFrozen(result)).toBe(true)+ expect(result.ok && Object.isFrozen(result.identity)).toBe(true)+ expect(result).not.toHaveProperty('claimedExtensionId')+ })++ it('returns one fixed, attacker-free error for a Chromium claim mismatch', () => {+ const attackerClaim = 'attacker-controlled-claim'+ const result = normalizeExtensionIdentity({+ browser: 'chromium',+ verifiedOrigin: `chrome-extension://${BUILTIN_CHROMIUM_ID}`,+ claimedExtensionId: attackerClaim,+ })++ expect(result).toEqual({+ ok: false,+ error: ExtensionIdentityResolutionError,+ })+ expect(JSON.stringify(result)).not.toContain(attackerClaim)+ expect(JSON.stringify(result)).not.toContain(BUILTIN_CHROMIUM_ID)+ })++ it.each([+ ['wrong scheme', `https://${BUILTIN_CHROMIUM_ID}`],+ ['empty host', 'chrome-extension:///'],+ ['userinfo', `chrome-extension://user@${BUILTIN_CHROMIUM_ID}`],+ ['port', `chrome-extension://${BUILTIN_CHROMIUM_ID}:1234`],+ ['path', `chrome-extension://${BUILTIN_CHROMIUM_ID}/path`],+ ['query', `chrome-extension://${BUILTIN_CHROMIUM_ID}?x=1`],+ ['empty query', `chrome-extension://${BUILTIN_CHROMIUM_ID}?`],+ ['fragment', `chrome-extension://${BUILTIN_CHROMIUM_ID}#x`],+ ['empty fragment', `chrome-extension://${BUILTIN_CHROMIUM_ID}#`],+ ['empty port delimiter', `chrome-extension://${BUILTIN_CHROMIUM_ID}:`],+ ['backslash', `chrome-extension://${BUILTIN_CHROMIUM_ID}\\alias`],+ ['percent alias', `chrome-extension://${BUILTIN_CHROMIUM_ID}%2ealias`],+ ['unicode alias', 'chrome-extension://ídentity'],+ ])(+ 'fails closed with the same error for a malformed Origin (%s)',+ (_label, verifiedOrigin) => {+ expect(+ normalizeExtensionIdentity({+ browser: 'chromium',+ verifiedOrigin,+ claimedExtensionId: BUILTIN_CHROMIUM_ID,+ })+ ).toEqual({+ ok: false,+ error: ExtensionIdentityResolutionError,+ })+ }+ )++ it.each([+ ['chrome-extension://ídentity', '%C3%ADdentity'],+ ['chrome-extension://foo%2ebar', 'foo%2ebar'],+ ])(+ 'rejects a normalized host alias even when the claim copies it (%s)',+ (verifiedOrigin, claimedExtensionId) => {+ const result = normalizeExtensionIdentity({+ browser: 'chromium',+ verifiedOrigin,+ claimedExtensionId,+ })++ expect(result).toEqual({+ ok: false,+ error: ExtensionIdentityResolutionError,+ })+ expect(JSON.stringify(result)).not.toContain(claimedExtensionId)+ }+ )++ it('does not promote a Firefox claim into verified output', () => {+ const claimedExtensionId = '[email protected]'+ const result = normalizeExtensionIdentity({+ browser: 'firefox',+ verifiedOrigin: FIREFOX_ORIGIN,+ claimedExtensionId,+ })++ expect(result).toEqual({+ ok: true,+ identity: {+ browser: 'firefox',+ originHost: '8c1a0d6e-1f2b-4c3d-9e0a-5b6c7d8e9f01',+ verifiedExtensionId: null,+ },+ })+ expect(JSON.stringify(result)).not.toContain(claimedExtensionId)+ })+})++describe('ExtensionIdentityResolver.resolve', () => {+ const resolver = createExtensionIdentityResolver({+ environment: 'production',+ developmentEntries: [],+ })++ it('classifies an allowlisted ticketless Chromium Origin as official', () => {+ expect(resolver.resolve(normalizedChromium(), { kind: 'none' })).toEqual({+ ok: true,+ identity: 'official',+ evidence: 'verified-origin',+ provenExtensionId: BUILTIN_CHROMIUM_ID,+ })+ })++ it('classifies another ticketless Chromium Origin as attested-non-official', () => {+ expect(+ resolver.resolve(normalizedChromium(OTHER_CHROMIUM_ID), { kind: 'none' })+ ).toEqual({+ ok: true,+ identity: 'attested-non-official',+ evidence: 'verified-origin',+ provenExtensionId: OTHER_CHROMIUM_ID,+ })+ })++ it('keeps ticketless remote Firefox unverified and excludes its claim', () => {+ const result = resolver.resolve(normalizedFirefox(), { kind: 'none' })++ expect(result).toEqual({+ ok: true,+ identity: 'unverified',+ evidence: 'none',+ provenExtensionId: null,+ })+ expect(JSON.stringify(result)).not.toContain(BUILTIN_FIREFOX_ID)+ })++ it.each([+ [BUILTIN_FIREFOX_ID, 'official'],+ ['[email protected]', 'attested-non-official'],+ ] as const)(+ 'preserves valid NM ticket classification for caller %s',+ (callerId, expectedIdentity) => {+ expect(+ resolver.resolve(normalizedFirefox(), {+ kind: 'verified-nm-ticket',+ callerId,+ })+ ).toEqual({+ ok: true,+ identity: expectedIdentity,+ evidence: 'verified-nm-ticket',+ provenExtensionId: callerId,+ })+ }+ )++ it('preserves a valid Chromium NM ticket only when it agrees with the Origin', () => {+ expect(+ resolver.resolve(normalizedChromium(), {+ kind: 'verified-nm-ticket',+ callerId: BUILTIN_CHROMIUM_ID,+ })+ ).toEqual({+ ok: true,+ identity: 'official',+ evidence: 'verified-nm-ticket',+ provenExtensionId: BUILTIN_CHROMIUM_ID,+ })++ const mismatch = resolver.resolve(normalizedChromium(), {+ kind: 'verified-nm-ticket',+ callerId: OTHER_CHROMIUM_ID,+ })+ expect(mismatch).toEqual({+ ok: false,+ error: ExtensionIdentityResolutionError,+ })+ expect(JSON.stringify(mismatch)).not.toContain(OTHER_CHROMIUM_ID)+ })++ it('returns the fixed error without echoing malformed ticket evidence', () => {+ const attackerData = 'attacker\u0000ticket'+ const result = resolver.resolve(normalizedFirefox(), {+ kind: 'verified-nm-ticket',+ callerId: attackerData,+ })++ expect(result).toEqual({+ ok: false,+ error: ExtensionIdentityResolutionError,+ })+ expect(JSON.stringify(result)).not.toContain('attacker')+ })+})diff --git a/src/core/bridge/extension-identity-resolver.ts b/src/core/bridge/extension-identity-resolver.tsnew file mode 100644index 00000000..d0ba7c19--- /dev/null+++ b/src/core/bridge/extension-identity-resolver.ts@@ -0,0 +1,351 @@+import nativeMessagingExtensions from '@shared/config/native-messaging-extensions.json' with {+ type: 'json',+}+import type { Browser } from '@shared/protocol/bridge'+import type { IdentityTriState } from './credential-store'++export interface OfficialExtensionEntry {+ readonly browser: Browser+ readonly id: string+}++function freezeEntries(+ entries: ReadonlyArray<OfficialExtensionEntry>+): readonly OfficialExtensionEntry[] {+ return Object.freeze(+ entries.map((entry) =>+ Object.freeze({ browser: entry.browser, id: entry.id })+ )+ )+}++/**+ * Store-signed identities compiled into Motrix. This is the only production+ * source of the `official` tier; persisted registry entries never enter it.+ */+export const BUILTIN_OFFICIAL_EXTENSION_ENTRIES = freezeEntries([+ ...nativeMessagingExtensions.chromium.map((id) => ({+ browser: 'chromium' as const,+ id,+ })),+ ...nativeMessagingExtensions.firefox.map((id) => ({+ browser: 'firefox' as const,+ id,+ })),+])++export type ExtensionIdentityEnvironment = 'production' | 'non-production'++export interface ExtensionIdentityResolverOptions {+ /** Must be chosen explicitly by the shell; core never reads process state. */+ readonly environment: ExtensionIdentityEnvironment+ /** Parsed shell configuration. Ignored completely in production. */+ readonly developmentEntries: ReadonlyArray<OfficialExtensionEntry>+}++export interface ExtensionIdentityInput {+ readonly browser: Browser+ /** Origin header accepted and browser-derived by the transport boundary. */+ readonly verifiedOrigin: string+ /** Untrusted pairHello field. Never copied into normalized output. */+ readonly claimedExtensionId: string+}++export type NormalizedExtensionIdentity =+ | {+ readonly browser: 'chromium'+ readonly originHost: string+ readonly verifiedExtensionId: string+ }+ | {+ readonly browser: 'firefox'+ readonly originHost: string+ readonly verifiedExtensionId: null+ }++export const ExtensionIdentityResolutionError =+ 'invalid-extension-identity' as const++export interface ExtensionIdentityFailure {+ readonly ok: false+ readonly error: typeof ExtensionIdentityResolutionError+}++export type ExtensionIdentityNormalizationResult =+ | {+ readonly ok: true+ readonly identity: NormalizedExtensionIdentity+ }+ | ExtensionIdentityFailure++export type ExtensionIdentityAttestation =+ | { readonly kind: 'none' }+ | {+ readonly kind: 'verified-nm-ticket'+ /** The callerId returned by successful NM ticket verification. */+ readonly callerId: string+ }++export type ExtensionIdentityEvidence =+ | 'verified-origin'+ | 'verified-nm-ticket'+ | 'none'++export type ExtensionIdentityResolution =+ | {+ readonly ok: true+ readonly identity: IdentityTriState+ readonly evidence: ExtensionIdentityEvidence+ /** A proven store/Gecko id, never the unverified pairHello claim. */+ readonly provenExtensionId: string | null+ }+ | ExtensionIdentityFailure++export interface ExtensionIdentityResolver {+ readonly builtInEntries: readonly OfficialExtensionEntry[]+ /** Empty in production, even if the shell supplied development entries. */+ readonly developmentEntries: readonly OfficialExtensionEntry[]+ /** Frozen effective input for Native Messaging manifest/registry setup. */+ readonly officialEntries: readonly OfficialExtensionEntry[]+ isOfficialId(browser: Browser, id: string): boolean+ resolve(+ identity: NormalizedExtensionIdentity,+ attestation: ExtensionIdentityAttestation+ ): ExtensionIdentityResolution+}++export type IsOfficialExtensionId = (browser: Browser, id: string) => boolean++const INVALID_IDENTITY_RESULT: ExtensionIdentityFailure = Object.freeze({+ ok: false,+ error: ExtensionIdentityResolutionError,+})++function invalidResolution(): ExtensionIdentityResolution {+ return INVALID_IDENTITY_RESULT+}++function keyOf(entry: OfficialExtensionEntry): string {+ return JSON.stringify([entry.browser, entry.id])+}++function deduplicateEntries(+ entries: ReadonlyArray<OfficialExtensionEntry>+): readonly OfficialExtensionEntry[] {+ const unique = new Map<string, OfficialExtensionEntry>()+ for (const entry of entries) {+ if (+ (entry.browser !== 'chromium' && entry.browser !== 'firefox') ||+ entry.id.length === 0+ ) {+ continue+ }+ const frozen = Object.freeze({ browser: entry.browser, id: entry.id })+ unique.set(keyOf(frozen), frozen)+ }+ return Object.freeze([...unique.values()])+}++function containsUnsafeOriginSyntax(value: string): boolean {+ if (value.includes('\\') || value.includes('%') || /\s/u.test(value)) {+ return true+ }+ for (let index = 0; index < value.length; index += 1) {+ const code = value.charCodeAt(index)+ if (code <= 0x1f || code >= 0x7f) return true+ }+ return false+}++/**+ * Normalize only transport-derived evidence. The claimed id is used once for+ * Chromium equality and is then discarded; Firefox claims prove nothing.+ */+export function normalizeExtensionIdentity(+ input: ExtensionIdentityInput+): ExtensionIdentityNormalizationResult {+ const scheme =+ input.browser === 'chromium' ? 'chrome-extension:' : 'moz-extension:'+ const prefix = `${scheme}//`+ if (+ input.verifiedOrigin.length === 0 ||+ !input.verifiedOrigin.startsWith(prefix) ||+ containsUnsafeOriginSyntax(input.verifiedOrigin)+ ) {+ return INVALID_IDENTITY_RESULT+ }++ let parsed: URL+ try {+ parsed = new URL(input.verifiedOrigin)+ } catch {+ return INVALID_IDENTITY_RESULT+ }++ if (+ parsed.protocol !== scheme ||+ parsed.hostname.length === 0 ||+ parsed.port !== '' ||+ parsed.username !== '' ||+ parsed.password !== '' ||+ parsed.pathname !== '' ||+ parsed.search !== '' ||+ parsed.hash !== ''+ ) {+ return INVALID_IDENTITY_RESULT+ }++ // WHATWG parsing normalizes aliases such as a trailing bare `:`, `?`, or+ // `#`. Identity evidence must be the exact canonical Origin bytes, not+ // merely something whose parsed host happens to match an official id.+ if (input.verifiedOrigin !== `${prefix}${parsed.hostname}`) {+ return INVALID_IDENTITY_RESULT+ }++ if (+ input.browser === 'chromium' &&+ parsed.hostname !== input.claimedExtensionId+ ) {+ return INVALID_IDENTITY_RESULT+ }++ const identity: NormalizedExtensionIdentity =+ input.browser === 'chromium'+ ? Object.freeze({+ browser: 'chromium',+ originHost: parsed.hostname,+ verifiedExtensionId: parsed.hostname,+ })+ : Object.freeze({+ browser: 'firefox',+ originHost: parsed.hostname,+ verifiedExtensionId: null,+ })+ return Object.freeze({ ok: true, identity })+}++function validProvenId(value: string): boolean {+ if (value.length === 0) return false+ for (let index = 0; index < value.length; index += 1) {+ const code = value.charCodeAt(index)+ if (code < 0x21 || code > 0x7e) return false+ }+ return true+}++/**+ * Build one immutable resolver. User/imported registry entries are+ * intentionally not an input, so mutating that registry cannot raise trust.+ */+export function createExtensionIdentityResolver(+ options: ExtensionIdentityResolverOptions+): ExtensionIdentityResolver {+ const builtInEntries = BUILTIN_OFFICIAL_EXTENSION_ENTRIES+ const developmentEntries =+ options.environment === 'non-production'+ ? deduplicateEntries(options.developmentEntries)+ : Object.freeze([])+ const officialEntries = deduplicateEntries([+ ...builtInEntries,+ ...developmentEntries,+ ])+ const officialIds = new Set(officialEntries.map(keyOf))++ const isOfficialId = (browser: Browser, id: string): boolean =>+ officialIds.has(JSON.stringify([browser, id]))++ const resolve = (+ identity: NormalizedExtensionIdentity,+ attestation: ExtensionIdentityAttestation+ ): ExtensionIdentityResolution =>+ resolveNormalizedExtensionIdentity(identity, attestation, isOfficialId)++ return Object.freeze({+ builtInEntries,+ developmentEntries,+ officialEntries,+ isOfficialId,+ resolve,+ })+}++/**+ * Resolve already-normalized transport evidence. PairSession uses this form+ * with its injected immutable-allowlist predicate, keeping wire options and+ * test doubles stable while sharing the classification rules with shells.+ */+export function resolveNormalizedExtensionIdentity(+ identity: NormalizedExtensionIdentity,+ attestation: ExtensionIdentityAttestation,+ isOfficialId: IsOfficialExtensionId+): ExtensionIdentityResolution {+ if (+ identity.originHost.length === 0 ||+ (identity.browser === 'chromium' &&+ (identity.verifiedExtensionId.length === 0 ||+ identity.verifiedExtensionId !== identity.originHost)) ||+ (identity.browser === 'firefox' && identity.verifiedExtensionId !== null)+ ) {+ return invalidResolution()+ }++ if (attestation.kind === 'verified-nm-ticket') {+ if (+ !validProvenId(attestation.callerId) ||+ (identity.browser === 'chromium' &&+ attestation.callerId !== identity.verifiedExtensionId)+ ) {+ return invalidResolution()+ }+ return Object.freeze({+ ok: true,+ identity: isOfficialId(identity.browser, attestation.callerId)+ ? 'official'+ : 'attested-non-official',+ evidence: 'verified-nm-ticket',+ provenExtensionId: attestation.callerId,+ })+ }++ if (identity.browser === 'firefox') {+ return Object.freeze({+ ok: true,+ identity: 'unverified',+ evidence: 'none',+ provenExtensionId: null,+ })+ }++ return Object.freeze({+ ok: true,+ identity: isOfficialId('chromium', identity.verifiedExtensionId)+ ? 'official'+ : 'attested-non-official',+ evidence: 'verified-origin',+ provenExtensionId: identity.verifiedExtensionId,+ })+}++/**+ * Parse a shell-provided comma-separated `<browser>:<id>` list. This helper+ * reads no environment variable; the shell must supply the string and choose+ * the resolver environment explicitly.+ */+export function parseDevTrustedExtensions(+ raw: string | undefined+): readonly OfficialExtensionEntry[] {+ if (!raw) return Object.freeze([])+ const entries: OfficialExtensionEntry[] = []+ for (const part of raw.split(',')) {+ const trimmed = part.trim()+ if (!trimmed) continue+ const colon = trimmed.indexOf(':')+ if (colon <= 0) continue+ const browser = trimmed.slice(0, colon).trim()+ const id = trimmed.slice(colon + 1).trim()+ if (!id) continue+ if (browser !== 'chromium' && browser !== 'firefox') continue+ entries.push({ browser, id })+ }+ return freezeEntries(entries)+}diff --git a/src/core/bridge/extension-pairing-projection.test.ts b/src/core/bridge/extension-pairing-projection.test.tsnew file mode 100644index 00000000..6de0f1a8--- /dev/null+++ b/src/core/bridge/extension-pairing-projection.test.ts@@ -0,0 +1,641 @@+import fs from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import {+ CommittedExtensionCredentialError,+ type CommittedExtensionCredentialSnapshot,+ type CommittedExtensionCredentialWitness,+ type CredentialPrincipal,+ type ExtensionIdentityAbsenceWitness,+ type IdentityTriState,+ Mbp1CredentialStore,+} from './credential-store'+import {+ type ExtensionPairingCleanupLease,+ type ExtensionPairingProjection,+ ExtensionPairingProjectionError,+ ExtensionPairingProjectionService,+ type ExtensionPairingProjectionStore,+ type ExtensionPairingProjectionStoreSnapshot,+} from './extension-pairing-projection'++const START = 1_700_000_000_000++const PRINCIPAL_A: CredentialPrincipal = {+ browser: 'chromium',+ verifiedOrigin: 'chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ clientInstallationId: 'install-a',+}++const PRINCIPAL_A_SECOND_INSTALL: CredentialPrincipal = {+ ...PRINCIPAL_A,+ clientInstallationId: 'install-a-2',+}++const PRINCIPAL_B: CredentialPrincipal = {+ browser: 'firefox',+ verifiedOrigin: 'moz-extension://bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',+ clientInstallationId: 'install-b',+}++function clone<T>(value: T): T {+ return structuredClone(value)+}++class MemoryProjectionStore implements ExtensionPairingProjectionStore {+ revision = 0+ records: unknown = []+ saveCalls = 0+ failNextSave = false+ failLoad = false+ lastSaveWasDeepFrozen = false+ private blockedSave:+ | {+ readonly entered: () => void+ readonly wait: Promise<void>+ }+ | undefined++ async load(): Promise<ExtensionPairingProjectionStoreSnapshot> {+ if (this.failLoad) throw new Error('untrusted load detail')+ return { revision: this.revision, records: clone(this.records) }+ }++ async save(+ next: readonly ExtensionPairingProjection[],+ expectedRevision: number+ ): Promise<number> {+ this.saveCalls += 1+ this.lastSaveWasDeepFrozen =+ Object.isFrozen(next) &&+ next.every(+ (record) => Object.isFrozen(record) && Object.isFrozen(record.identity)+ )+ const blocked = this.blockedSave+ this.blockedSave = undefined+ if (blocked) {+ blocked.entered()+ await blocked.wait+ }+ if (this.failNextSave) {+ this.failNextSave = false+ throw new Error('untrusted persistence detail')+ }+ if (expectedRevision !== this.revision) throw new Error('stale revision')+ this.records = clone(next)+ this.revision += 1+ return this.revision+ }++ blockNextSave(): { entered: Promise<void>; release: () => void } {+ let announce!: () => void+ let release!: () => void+ const entered = new Promise<void>((resolve) => {+ announce = resolve+ })+ const wait = new Promise<void>((resolve) => {+ release = resolve+ })+ this.blockedSave = { entered: announce, wait }+ return { entered, release }+ }+}++interface PairResult {+ readonly credentialId: string+ readonly witness: CommittedExtensionCredentialWitness+}++describe('ExtensionPairingProjectionService', () => {+ let directory: string+ let credentialPath: string+ let credentialStore: Mbp1CredentialStore+ let projectionStore: MemoryProjectionStore+ let service: ExtensionPairingProjectionService+ let now: number++ const pair = async (+ principal: CredentialPrincipal,+ identityTrust: IdentityTriState,+ committedAt: number+ ): Promise<PairResult> => {+ now = committedAt - 1+ const offer = await credentialStore.offerProvisional(+ principal,+ identityTrust+ )+ now = committedAt+ await credentialStore.commitFromPair(offer.credentialId)+ return {+ credentialId: offer.credentialId,+ witness: await credentialStore.issueCommittedExtensionWitness(+ offer.credentialId+ ),+ }+ }++ const absenceFor = (+ identity: CommittedExtensionCredentialWitness['identity']+ ): Promise<ExtensionIdentityAbsenceWitness> =>+ credentialStore.issueExtensionIdentityAbsenceWitness(+ identity.browser,+ identity.extensionId+ )++ beforeEach(async () => {+ directory = await fs.mkdtemp(+ path.join(os.tmpdir(), 'extension-pairing-projection-service-')+ )+ credentialPath = path.join(directory, 'mbp1-credentials.json')+ now = START+ credentialStore = await Mbp1CredentialStore.load(credentialPath, {+ now: () => now,+ })+ projectionStore = new MemoryProjectionStore()+ service = new ExtensionPairingProjectionService(projectionStore, {+ now: () => now,+ })+ await service.load()+ })++ afterEach(async () => {+ await fs.rm(directory, { recursive: true, force: true })+ })++ it('rejects copied, forged, and self-reported witnesses without writing', async () => {+ const { witness } = await pair(PRINCIPAL_A, 'official', START + 100)+ const copies = [+ { ...witness },+ {+ ...witness,+ state: 'committed',+ credentialId: 'self-reported',+ },+ {+ identity: witness.identity,+ identityTrust: 'official',+ authorizationEpoch: witness.authorizationEpoch,+ createdAt: witness.createdAt,+ committedAt: witness.committedAt,+ verifiedOrigin: witness.verifiedOrigin,+ },+ ]++ for (const copy of copies) {+ await expect(+ service.recordCommitted(+ copy as unknown as CommittedExtensionCredentialWitness+ )+ ).rejects.toThrow(CommittedExtensionCredentialError.InvalidWitness)+ }+ expect(projectionStore.saveCalls).toBe(0)+ expect(service.list()).toEqual([])+ })++ it('creates a tokenless record only after durable credential commit', async () => {+ now = START + 50+ const provisional = await credentialStore.offerProvisional(+ PRINCIPAL_A,+ 'official'+ )+ await expect(+ credentialStore.issueCommittedExtensionWitness(provisional.credentialId)+ ).rejects.toThrow(CommittedExtensionCredentialError.NotCommitted)++ now = START + 100+ await credentialStore.commitFromPair(provisional.credentialId)+ const witness = await credentialStore.issueCommittedExtensionWitness(+ provisional.credentialId+ )+ const record = await service.recordCommitted(witness)++ expect(record).toEqual({+ identity: witness.identity,+ identityTrust: 'official',+ authorizationEpoch: witness.authorizationEpoch,+ status: 'ready',+ pairedAt: START + 100,+ lastActiveAt: null,+ })+ const serialized = JSON.stringify(service.list())+ expect(serialized).not.toMatch(/token|bearer|credentialId|mutualKey/iu)+ expect(Object.keys(record).sort()).toEqual([+ 'authorizationEpoch',+ 'identity',+ 'identityTrust',+ 'lastActiveAt',+ 'pairedAt',+ 'status',+ ])+ })++ it('preserves pairedAt across reconnects and avoids redundant writes', async () => {+ const { witness } = await pair(PRINCIPAL_A, 'official', START + 100)+ await service.recordCommitted(witness)+ await service.recordCommitted(witness)+ expect(projectionStore.saveCalls).toBe(1)++ await service.recordAuthenticated(witness, START + 300)+ await service.recordAuthenticated(witness, START + 200)++ expect(service.list()[0]).toMatchObject({+ pairedAt: START + 100,+ lastActiveAt: START + 300,+ })+ expect(projectionStore.saveCalls).toBe(2)+ })++ it('requires authenticatedAt to be at or after committedAt', async () => {+ const { witness } = await pair(PRINCIPAL_A, 'official', START + 100)++ await expect(+ service.recordAuthenticated(witness, START + 99)+ ).rejects.toThrow(ExtensionPairingProjectionError.InvalidTime)+ expect(projectionStore.saveCalls).toBe(0)+ })++ it('invalidates an old witness after revoke', async () => {+ const paired = await pair(PRINCIPAL_A, 'official', START + 100)+ await service.recordCommitted(paired.witness)+ await credentialStore.revoke(paired.credentialId)++ await expect(+ service.recordAuthenticated(paired.witness, START + 200)+ ).rejects.toThrow(CommittedExtensionCredentialError.NotCommitted)+ expect(service.list()[0]?.lastActiveAt).toBeNull()+ })++ it('holds credential liveness until the projection mutation is durable', async () => {+ const paired = await pair(PRINCIPAL_A, 'official', START + 100)+ const gate = projectionStore.blockNextSave()+ const recording = service.recordCommitted(paired.witness)+ await gate.entered++ let revokeFinished = false+ const revoking = credentialStore.revoke(paired.credentialId).then(() => {+ revokeFinished = true+ })+ await Promise.resolve()+ await Promise.resolve()+ expect(revokeFinished).toBe(false)++ gate.release()+ await recording+ await revoking+ await expect(+ service.recordAuthenticated(paired.witness, START + 200)+ ).rejects.toThrow(CommittedExtensionCredentialError.NotCommitted)+ })++ it('keeps the authorization epoch and pairedAt through credential rotation', async () => {+ const first = await pair(PRINCIPAL_A, 'official', START + 100)+ await service.recordCommitted(first.witness)+ const rotated = await pair(PRINCIPAL_A, 'official', START + 500)++ expect(rotated.witness.authorizationEpoch).toBe(+ first.witness.authorizationEpoch+ )+ await expect(service.recordCommitted(first.witness)).rejects.toThrow(+ CommittedExtensionCredentialError.NotCommitted+ )+ await service.recordCommitted(rotated.witness)+ expect(service.list()[0]?.pairedAt).toBe(START + 100)+ })++ it('folds multiple installations by verified transport identity and keeps the most conservative trust', async () => {+ const first = await pair(PRINCIPAL_A, 'official', START + 100)+ const second = await pair(+ PRINCIPAL_A_SECOND_INSTALL,+ 'unverified',+ START + 200+ )+ expect(second.witness.authorizationEpoch).toBe(+ first.witness.authorizationEpoch+ )++ await service.reconcileCommitted(+ await credentialStore.issueCommittedExtensionSnapshot()+ )++ expect(service.list()).toEqual([+ {+ identity: first.witness.identity,+ identityTrust: 'unverified',+ authorizationEpoch: first.witness.authorizationEpoch,+ status: 'ready',+ pairedAt: START + 100,+ lastActiveAt: null,+ },+ ])+ })++ it('derives the Firefox management key only from verified Origin', async () => {+ const { witness } = await pair(PRINCIPAL_B, 'official', START + 100)++ expect(witness.identity).toEqual({+ kind: 'extension',+ browser: 'firefox',+ extensionId: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',+ })+ expect(witness).not.toHaveProperty('claimedExtensionId')+ })++ it('reconciles additions and stale deletions while isolating identities', async () => {+ const a = await pair(PRINCIPAL_A, 'official', START + 100)+ const b = await pair(PRINCIPAL_B, 'unverified', START + 200)+ const oldSnapshot = await credentialStore.issueCommittedExtensionSnapshot()+ await service.reconcileCommitted(oldSnapshot)+ expect(service.list()).toHaveLength(2)++ await credentialStore.revokeExtensionIdentity(+ 'chromium',+ a.witness.identity.extensionId+ )+ await expect(service.reconcileCommitted(oldSnapshot)).rejects.toThrow(+ CommittedExtensionCredentialError.NotCommitted+ )+ await service.reconcileCommitted(+ await credentialStore.issueCommittedExtensionSnapshot()+ )++ expect(service.list()).toHaveLength(1)+ expect(service.list()[0]?.identity).toEqual(b.witness.identity)+ })++ it('persists cleanup-pending before revoke and gives a full re-pair a new epoch and pairedAt', async () => {+ const first = await pair(PRINCIPAL_A, 'official', START + 100)+ await service.recordCommitted(first.witness)++ const lease = await service.prepareCleanup(first.witness)+ expect(service.list()[0]?.status).toBe('cleanup-pending')+ expect(service.listReady()).toEqual([])+ expect(service.canAdmitIdentity(first.witness.identity)).toBe(false)++ await credentialStore.revokeExtensionIdentity(+ first.witness.identity.browser,+ first.witness.identity.extensionId+ )+ await service.completeCleanup(+ lease,+ await absenceFor(first.witness.identity)+ )+ expect(service.list()).toEqual([])++ const repaired = await pair(PRINCIPAL_A, 'official', START + 900)+ expect(repaired.witness.authorizationEpoch).not.toBe(+ first.witness.authorizationEpoch+ )+ await service.recordCommitted(repaired.witness)+ expect(service.list()[0]?.pairedAt).toBe(START + 900)+ })++ it('keeps a durable pending revoke closed across restart until an explicit retry completes', async () => {+ const paired = await pair(PRINCIPAL_A, 'official', START + 100)+ await service.recordCommitted(paired.witness)+ await service.prepareCleanup(paired.witness)++ const restarted = new ExtensionPairingProjectionService(projectionStore)+ await restarted.load()+ expect(restarted.canAdmitIdentity(paired.witness.identity)).toBe(false)+ await restarted.reconcileCommitted(+ await credentialStore.issueCommittedExtensionSnapshot()+ )++ expect(restarted.list()[0]).toMatchObject({+ status: 'cleanup-pending',+ pairedAt: START + 100,+ })+ expect(restarted.canAdmitIdentity(paired.witness.identity)).toBe(false)++ const recoveredLease = await restarted.prepareIdentityCleanup(+ paired.witness.identity+ )+ await credentialStore.revokeExtensionIdentity(+ paired.witness.identity.browser,+ paired.witness.identity.extensionId+ )+ await restarted.completeCleanup(+ recoveredLease,+ await absenceFor(paired.witness.identity)+ )+ expect(restarted.list()).toEqual([])+ })++ it('does not let generic reconcile override pending cleanup and requires nominal explicit cancellation', async () => {+ const paired = await pair(PRINCIPAL_A, 'official', START + 100)+ await service.recordCommitted(paired.witness)+ const lease = await service.prepareCleanup(paired.witness)++ await service.reconcileCommitted(+ await credentialStore.issueCommittedExtensionSnapshot()+ )+ expect(service.list()[0]?.status).toBe('cleanup-pending')+ expect(service.canAdmitIdentity(paired.witness.identity)).toBe(false)++ await service.cancelCleanup(lease, paired.witness)+ expect(service.list()[0]).toMatchObject({+ status: 'ready',+ pairedAt: START + 100,+ })+ expect(service.canAdmitIdentity(paired.witness.identity)).toBe(true)+ })++ it('finishes a durable pending cleanup after restart without its old lease', async () => {+ const paired = await pair(PRINCIPAL_A, 'official', START + 100)+ await service.recordCommitted(paired.witness)+ await service.prepareCleanup(paired.witness)+ await credentialStore.revokeExtensionIdentity(+ paired.witness.identity.browser,+ paired.witness.identity.extensionId+ )++ const restarted = new ExtensionPairingProjectionService(projectionStore)+ await restarted.load()+ expect(restarted.list()[0]?.status).toBe('cleanup-pending')+ await restarted.reconcileCommitted(+ await credentialStore.issueCommittedExtensionSnapshot()+ )+ expect(restarted.list()[0]?.status).toBe('cleanup-pending')++ const recoveredLease = await restarted.prepareIdentityCleanup(+ paired.witness.identity+ )+ await restarted.completeCleanup(+ recoveredLease,+ await absenceFor(paired.witness.identity)+ )+ expect(restarted.list()).toEqual([])+ })++ it('degrades and keeps the durable previous row when cleanup persistence fails', async () => {+ const paired = await pair(PRINCIPAL_A, 'official', START + 100)+ await service.recordCommitted(paired.witness)+ const durableBefore = clone(projectionStore.records)+ projectionStore.failNextSave = true++ await expect(service.prepareCleanup(paired.witness)).rejects.toThrow(+ ExtensionPairingProjectionError.PersistenceFailed+ )++ expect(service.getHealth()).toBe('degraded')+ expect(service.list()).toEqual([])+ expect(projectionStore.records).toEqual(durableBefore)+ expect(service.canAdmitIdentity(paired.witness.identity)).toBe(false)+ })++ it('degrades instead of reusing a stale row when a new epoch appears without cleanup', async () => {+ const first = await pair(PRINCIPAL_A, 'official', START + 100)+ await service.recordCommitted(first.witness)+ await credentialStore.revokeExtensionIdentity(+ first.witness.identity.browser,+ first.witness.identity.extensionId+ )+ const repaired = await pair(PRINCIPAL_A, 'official', START + 800)++ await expect(service.recordCommitted(repaired.witness)).rejects.toThrow(+ ExtensionPairingProjectionError.CleanupRequired+ )+ expect(service.getHealth()).toBe('degraded')+ expect(service.list()).toEqual([])+ })++ it('serializes concurrent updates without losing either identity', async () => {+ const a = await pair(PRINCIPAL_A, 'official', START + 100)+ const b = await pair(PRINCIPAL_B, 'unverified', START + 200)++ await Promise.all([+ service.recordCommitted(a.witness),+ service.recordCommitted(b.witness),+ ])++ expect(service.list().map((record) => record.identity)).toEqual([+ a.witness.identity,+ b.witness.identity,+ ])+ expect(projectionStore.saveCalls).toBe(2)+ })++ it('deletes only the identity named by a nominal cleanup lease', async () => {+ const a = await pair(PRINCIPAL_A, 'official', START + 100)+ const b = await pair(PRINCIPAL_B, 'official', START + 200)+ await service.reconcileCommitted(+ await credentialStore.issueCommittedExtensionSnapshot()+ )++ const lease = await service.prepareCleanup(a.witness)+ await credentialStore.revokeExtensionIdentity(+ a.witness.identity.browser,+ a.witness.identity.extensionId+ )+ await service.completeCleanup(lease, await absenceFor(a.witness.identity))+ expect(service.list()[0]?.identity).toEqual(b.witness.identity)++ await expect(+ service.completeCleanup(+ {+ identity: b.witness.identity,+ authorizationEpoch: b.witness.authorizationEpoch,+ } as ExtensionPairingCleanupLease,+ {} as ExtensionIdentityAbsenceWitness+ )+ ).rejects.toThrow(ExtensionPairingProjectionError.InvalidCleanupLease)+ })++ it('preserves an existing pairedAt forever during same-epoch reconcile', async () => {+ const paired = await pair(PRINCIPAL_A, 'official', START + 100)+ projectionStore.records = [+ {+ identity: paired.witness.identity,+ identityTrust: 'official',+ authorizationEpoch: paired.witness.authorizationEpoch,+ status: 'ready',+ pairedAt: START + 500,+ lastActiveAt: null,+ },+ ] satisfies ExtensionPairingProjection[]+ service = new ExtensionPairingProjectionService(projectionStore)+ await service.load()++ await service.reconcileCommitted(+ await credentialStore.issueCommittedExtensionSnapshot()+ )+ expect(service.list()[0]?.pairedAt).toBe(START + 500)+ })++ it.each([+ ['future fields', [{ unexpected: true }]],+ ['too many rows', Array.from({ length: 4_097 }, () => null)],+ ])('fails closed on %s in storage', async (_name, records) => {+ projectionStore.records = records+ const candidate = new ExtensionPairingProjectionService(projectionStore)++ await expect(candidate.load()).rejects.toThrow(+ ExtensionPairingProjectionError.StorageRejected+ )+ expect(candidate.getHealth()).toBe('degraded')+ expect(candidate.list()).toEqual([])+ })++ it('redacts load failures and enters degraded state', async () => {+ projectionStore.failLoad = true+ const candidate = new ExtensionPairingProjectionService(projectionStore)++ await expect(candidate.load()).rejects.toThrow(+ ExtensionPairingProjectionError.PersistenceFailed+ )+ expect(candidate.getHealth()).toBe('degraded')+ })++ it('returns frozen copies and gives the store a deeply frozen snapshot', async () => {+ const paired = await pair(PRINCIPAL_A, 'official', START + 100)+ const created = await service.recordCommitted(paired.witness)+ const listed = service.list()++ expect(Object.isFrozen(created)).toBe(true)+ expect(Object.isFrozen(created.identity)).toBe(true)+ expect(Object.isFrozen(listed)).toBe(true)+ expect(Object.isFrozen(listed[0]?.identity)).toBe(true)+ expect(projectionStore.lastSaveWasDeepFrozen).toBe(true)+ expect(() => {+ ;(listed[0] as { pairedAt: number }).pairedAt = 0+ }).toThrow()+ expect(service.list()[0]?.pairedAt).toBe(START + 100)+ })++ it('drains admitted work while rejecting new work after stop is requested', async () => {+ const paired = await pair(PRINCIPAL_A, 'official', START + 100)+ const gate = projectionStore.blockNextSave()+ const pending = service.recordCommitted(paired.witness)+ await gate.entered++ const drained = service.stopAndDrain()+ await expect(service.load()).rejects.toThrow(+ ExtensionPairingProjectionError.Stopped+ )+ gate.release()+ await expect(pending).resolves.toMatchObject({ pairedAt: START + 100 })+ await drained++ expect(service.getHealth()).toBe('stopped')+ await expect(service.recordCommitted(paired.witness)).rejects.toThrow(+ ExtensionPairingProjectionError.Stopped+ )+ })++ it('rejects a copied complete snapshot and a snapshot made stale by mutation', async () => {+ const paired = await pair(PRINCIPAL_A, 'official', START + 100)+ const snapshot = await credentialStore.issueCommittedExtensionSnapshot()++ await expect(+ service.reconcileCommitted({+ witnesses: snapshot.witnesses,+ } as unknown as CommittedExtensionCredentialSnapshot)+ ).rejects.toThrow(CommittedExtensionCredentialError.InvalidWitness)++ await credentialStore.revoke(paired.credentialId)+ await expect(service.reconcileCommitted(snapshot)).rejects.toThrow(+ CommittedExtensionCredentialError.NotCommitted+ )+ })+})diff --git a/src/core/bridge/extension-pairing-projection.ts b/src/core/bridge/extension-pairing-projection.tsnew file mode 100644index 00000000..9666b3a9--- /dev/null+++ b/src/core/bridge/extension-pairing-projection.ts@@ -0,0 +1,882 @@+import type { Browser } from '@shared/protocol/bridge'+import {+ type CommittedExtensionCredentialSnapshot,+ type CommittedExtensionCredentialWitness,+ type ExtensionIdentityAbsenceWitness,+ type IdentityTriState,+ withLiveCommittedExtensionSnapshot,+ withLiveCommittedExtensionWitness,+ withLiveExtensionIdentityAbsenceWitness,+} from './credential-store'+import { normalizeExtensionIdentity } from './extension-identity-resolver'++const MAX_EXTENSION_ID_LENGTH = 256+const MAX_PROJECTION_RECORDS = 4_096+const CLEANUP_LEASE_BRAND: unique symbol = Symbol(+ 'motrix.extension-pairing-projection.cleanup-lease'+)++type ProjectionStatus = 'ready' | 'cleanup-pending'+export type ExtensionPairingProjectionHealth =+ | 'uninitialized'+ | 'ready'+ | 'degraded'+ | 'stopped'++export interface ExtensionTransportIdentity {+ readonly kind: 'extension'+ readonly browser: Browser+ readonly extensionId: string+}++export interface ExtensionPairingProjection {+ readonly identity: ExtensionTransportIdentity+ readonly identityTrust: IdentityTriState+ readonly authorizationEpoch: string+ readonly status: ProjectionStatus+ readonly pairedAt: number+ readonly lastActiveAt: number | null+}++export interface ExtensionPairingProjectionStoreSnapshot {+ readonly revision: number+ readonly records: unknown+}++export interface ExtensionPairingProjectionStore {+ load(): Promise<ExtensionPairingProjectionStoreSnapshot>+ /** Compare-and-swap `expectedRevision`; resolve with exactly the next+ * revision only after the replacement is durable. */+ save(+ next: readonly ExtensionPairingProjection[],+ expectedRevision: number+ ): Promise<number>+}++export interface ExtensionPairingCleanupLease {+ readonly [CLEANUP_LEASE_BRAND]: true+ readonly identity: ExtensionTransportIdentity+ readonly authorizationEpoch: string+}++export interface ExtensionPairingProjectionServiceOptions {+ readonly now?: () => number+}++export const ExtensionPairingProjectionError = Object.freeze({+ InvalidWitness: 'extension-pairing-projection invalid witness',+ InvalidIdentity: 'extension-pairing-projection invalid identity',+ InvalidTime: 'extension-pairing-projection invalid time',+ StorageRejected: 'extension-pairing-projection storage rejected',+ PersistenceFailed: 'extension-pairing-projection persistence failed',+ CapacityExceeded: 'extension-pairing-projection capacity exceeded',+ NotLoaded: 'extension-pairing-projection not loaded',+ Degraded: 'extension-pairing-projection degraded',+ CleanupPending: 'extension-pairing-projection cleanup pending',+ CleanupRequired: 'extension-pairing-projection cleanup required',+ InvalidCleanupLease: 'extension-pairing-projection cleanup lease rejected',+ EpochConflict: 'extension-pairing-projection epoch conflict',+ Stopped: 'extension-pairing-projection stopped',+} as const)++interface CleanupLeaseClaim {+ readonly service: ExtensionPairingProjectionService+ readonly key: string+ readonly authorizationEpoch: string+}++const cleanupLeaseClaims = new WeakMap<object, CleanupLeaseClaim>()++export class ExtensionPairingProjectionService {+ private records: ExtensionPairingProjection[] = []+ private revision = 0+ private persistenceTail: Promise<void> = Promise.resolve()+ private health: ExtensionPairingProjectionHealth = 'uninitialized'+ private drainPromise: Promise<void> | null = null+ private stopRequested = false+ private readonly activeCleanup = new Map<+ string,+ ExtensionPairingCleanupLease+ >()+ private readonly now: () => number++ constructor(+ private readonly store: ExtensionPairingProjectionStore,+ options: ExtensionPairingProjectionServiceOptions = {}+ ) {+ this.now = options.now ?? Date.now+ }++ async load(): Promise<void> {+ return this.enqueue(async () => {+ this.health = 'uninitialized'+ this.records = []+ let snapshot: ExtensionPairingProjectionStoreSnapshot+ try {+ snapshot = await this.store.load()+ } catch {+ return this.failDegraded(+ ExtensionPairingProjectionError.PersistenceFailed+ )+ }+ let parsed: ReturnType<typeof parseStoreSnapshot>+ try {+ parsed = parseStoreSnapshot(snapshot)+ } catch {+ return this.failDegraded(+ ExtensionPairingProjectionError.StorageRejected+ )+ }+ this.records = parsed.records+ this.revision = parsed.revision+ this.pruneResolvedCleanupLeases()+ this.health = 'ready'+ }, false)+ }++ getHealth(): ExtensionPairingProjectionHealth {+ return this.health+ }++ list(): readonly ExtensionPairingProjection[] {+ return freezeSnapshot(this.records)+ }++ listReady(): readonly ExtensionPairingProjection[] {+ return freezeSnapshot(+ this.records.filter((record) => record.status === 'ready')+ )+ }++ canAdmitIdentity(identity: ExtensionTransportIdentity): boolean {+ const normalized = normalizeTransportIdentity(identity)+ if (normalized === null || this.health !== 'ready') return false+ const key = identityKey(normalized)+ return (+ !this.activeCleanup.has(key) &&+ !this.records.some(+ (record) =>+ identityKey(record.identity) === key &&+ record.status === 'cleanup-pending'+ )+ )+ }++ async recordCommitted(+ witness: CommittedExtensionCredentialWitness+ ): Promise<ExtensionPairingProjection> {+ return withLiveCommittedExtensionWitness(witness, () =>+ this.enqueue(async () => this.upsertLiveWitness(witness, null))+ )+ }++ async recordAuthenticated(+ witness: CommittedExtensionCredentialWitness,+ authenticatedAt?: number+ ): Promise<ExtensionPairingProjection> {+ return withLiveCommittedExtensionWitness(witness, () =>+ this.enqueue(async () => {+ const observedAt = authenticatedAt ?? this.readNow()+ if (!validTimestamp(observedAt) || observedAt < witness.committedAt) {+ throw new Error(ExtensionPairingProjectionError.InvalidTime)+ }+ return this.upsertLiveWitness(witness, observedAt)+ })+ )+ }++ /**+ * Persist the admission tombstone before the authoritative credential+ * revoke starts. The caller must not revoke first. After this resolves it+ * may revoke every credential for the identity, then call+ * {@link completeCleanup} with a queue-bound credential-absence witness.+ * Generic reconciliation never overrides a durable pending cleanup.+ */+ async prepareCleanup(+ witness: CommittedExtensionCredentialWitness+ ): Promise<ExtensionPairingCleanupLease> {+ return withLiveCommittedExtensionWitness(witness, () =>+ this.enqueue(async () => {+ const key = identityKey(witness.identity)+ const current = this.records.find(+ (record) => identityKey(record.identity) === key+ )+ if (+ current &&+ current.authorizationEpoch !== witness.authorizationEpoch+ ) {+ return this.failDegraded(+ ExtensionPairingProjectionError.CleanupRequired+ )+ }+ const pending: ExtensionPairingProjection = {+ identity: witness.identity,+ identityTrust: current+ ? conservativeTrust(current.identityTrust, witness.identityTrust)+ : witness.identityTrust,+ authorizationEpoch: witness.authorizationEpoch,+ status: 'cleanup-pending',+ pairedAt: current?.pairedAt ?? witness.committedAt,+ lastActiveAt: current?.lastActiveAt ?? null,+ }+ if (current?.status !== 'cleanup-pending') {+ const next = this.records.filter(+ (record) => identityKey(record.identity) !== key+ )+ next.push(pending)+ await this.persist(sortRecords(next))+ }+ return this.issueCleanupLease(pending)+ })+ )+ }++ /**+ * Prepare or resume a security-reducing cleanup from the durable management+ * row itself. This is the operator-revoke/startup-recovery seam: unlike an+ * authorization grant, marking an already-recorded identity pending cannot+ * create trust. It is required when a crash happened after credential+ * deletion, so no live credential witness remains with which to recover the+ * pending marker.+ */+ async prepareIdentityCleanup(+ identity: ExtensionTransportIdentity+ ): Promise<ExtensionPairingCleanupLease> {+ return this.enqueue(async () => {+ const normalized = normalizeTransportIdentity(identity)+ if (normalized === null) {+ throw new Error(ExtensionPairingProjectionError.InvalidIdentity)+ }+ const key = identityKey(normalized)+ const current = this.records.find(+ (record) => identityKey(record.identity) === key+ )+ if (current === undefined) {+ throw new Error(ExtensionPairingProjectionError.CleanupRequired)+ }+ if (current.status === 'ready') {+ await this.persist(+ sortRecords(+ this.records.map((record) =>+ identityKey(record.identity) === key+ ? { ...record, status: 'cleanup-pending' as const }+ : record+ )+ )+ )+ }+ const pending = this.records.find(+ (record) => identityKey(record.identity) === key+ )+ if (pending?.status !== 'cleanup-pending') {+ throw new Error(ExtensionPairingProjectionError.CleanupRequired)+ }+ return this.issueCleanupLease(pending)+ })+ }++ async completeCleanup(+ lease: ExtensionPairingCleanupLease,+ absenceWitness: ExtensionIdentityAbsenceWitness+ ): Promise<void> {+ const claim = cleanupLeaseClaims.get(lease)+ if (+ !claim ||+ claim.service !== this ||+ this.activeCleanup.get(claim.key) !== lease+ ) {+ throw new Error(ExtensionPairingProjectionError.InvalidCleanupLease)+ }+ return withLiveExtensionIdentityAbsenceWitness(+ absenceWitness,+ lease.identity,+ () =>+ this.enqueue(async () => {+ const current = this.records.find(+ (record) => identityKey(record.identity) === claim.key+ )+ if (+ current?.status !== 'cleanup-pending' ||+ current.authorizationEpoch !== claim.authorizationEpoch+ ) {+ throw new Error(ExtensionPairingProjectionError.InvalidCleanupLease)+ }+ await this.persist(+ this.records.filter(+ (record) => identityKey(record.identity) !== claim.key+ )+ )+ cleanupLeaseClaims.delete(lease)+ this.activeCleanup.delete(claim.key)+ })+ )+ }++ /** Roll back a prepared cleanup only while the same authorization epoch is+ * still authoritatively committed. This is the explicit credential-revoke+ * failure path; it cannot be invoked with a copied lease or stale witness. */+ async cancelCleanup(+ lease: ExtensionPairingCleanupLease,+ witness: CommittedExtensionCredentialWitness+ ): Promise<ExtensionPairingProjection> {+ const claim = cleanupLeaseClaims.get(lease)+ if (+ !claim ||+ claim.service !== this ||+ this.activeCleanup.get(claim.key) !== lease+ ) {+ throw new Error(ExtensionPairingProjectionError.InvalidCleanupLease)+ }+ return withLiveCommittedExtensionWitness(witness, () =>+ this.enqueue(async () => {+ if (+ identityKey(witness.identity) !== claim.key ||+ witness.authorizationEpoch !== claim.authorizationEpoch+ ) {+ throw new Error(ExtensionPairingProjectionError.InvalidCleanupLease)+ }+ const current = this.records.find(+ (record) => identityKey(record.identity) === claim.key+ )+ if (+ current?.status !== 'cleanup-pending' ||+ current.authorizationEpoch !== claim.authorizationEpoch+ ) {+ throw new Error(ExtensionPairingProjectionError.InvalidCleanupLease)+ }+ const restored: ExtensionPairingProjection = {+ ...current,+ identityTrust: conservativeTrust(+ current.identityTrust,+ witness.identityTrust+ ),+ status: 'ready',+ }+ const next = this.records.filter(+ (record) => identityKey(record.identity) !== claim.key+ )+ next.push(restored)+ await this.persist(sortRecords(next))+ cleanupLeaseClaims.delete(lease)+ this.activeCleanup.delete(claim.key)+ return freezeRecord(restored)+ })+ )+ }++ /** Reconcile from one store-issued complete snapshot. This is the only API+ * allowed to remove stale rows without a prepared cleanup lease. */+ async reconcileCommitted(+ snapshot: CommittedExtensionCredentialSnapshot+ ): Promise<readonly ExtensionPairingProjection[]> {+ return withLiveCommittedExtensionSnapshot(snapshot, (witnesses) =>+ this.enqueue(async () => {+ let aggregates: WitnessAggregate[]+ try {+ aggregates = aggregateWitnesses(witnesses)+ } catch (error) {+ return this.failDegraded(+ error instanceof Error &&+ error.message === ExtensionPairingProjectionError.CapacityExceeded+ ? ExtensionPairingProjectionError.CapacityExceeded+ : ExtensionPairingProjectionError.EpochConflict+ )+ }+ const existing = new Map(+ this.records.map((record) => [identityKey(record.identity), record])+ )+ const authoritativeKeys = new Set<string>()+ const next: ExtensionPairingProjection[] = []+ for (const aggregate of aggregates) {+ const key = identityKey(aggregate.identity)+ authoritativeKeys.add(key)+ const current = existing.get(key)+ const sameEpoch =+ current?.authorizationEpoch === aggregate.authorizationEpoch+ if (current?.status === 'cleanup-pending') {+ if (!sameEpoch) {+ return this.failDegraded(+ ExtensionPairingProjectionError.CleanupRequired+ )+ }+ next.push({+ ...current,+ identityTrust: conservativeTrust(+ current.identityTrust,+ aggregate.identityTrust+ ),+ })+ continue+ }+ next.push({+ identity: aggregate.identity,+ identityTrust: aggregate.identityTrust,+ authorizationEpoch: aggregate.authorizationEpoch,+ status: 'ready',+ pairedAt: sameEpoch+ ? current.pairedAt+ : aggregate.earliestCommittedAt,+ lastActiveAt: sameEpoch ? current.lastActiveAt : null,+ })+ }+ for (const current of this.records) {+ const key = identityKey(current.identity)+ if (+ current.status === 'cleanup-pending' &&+ !authoritativeKeys.has(key)+ ) {+ next.push(current)+ }+ }+ const sorted = sortRecords(next)+ if (!recordsEqual(this.records, sorted)) await this.persist(sorted)+ return freezeSnapshot(sorted)+ })+ )+ }++ stopAndDrain(): Promise<void> {+ if (this.drainPromise) return this.drainPromise+ this.stopRequested = true+ this.drainPromise = this.persistenceTail.then(() => {+ this.health = 'stopped'+ })+ return this.drainPromise+ }++ private async upsertLiveWitness(+ witness: CommittedExtensionCredentialWitness,+ authenticatedAt: number | null+ ): Promise<ExtensionPairingProjection> {+ const key = identityKey(witness.identity)+ const current = this.records.find(+ (record) => identityKey(record.identity) === key+ )+ if (current?.status === 'cleanup-pending') {+ throw new Error(ExtensionPairingProjectionError.CleanupPending)+ }+ if (current && current.authorizationEpoch !== witness.authorizationEpoch) {+ return this.failDegraded(ExtensionPairingProjectionError.CleanupRequired)+ }+ if (!current && this.records.length >= MAX_PROJECTION_RECORDS) {+ throw new Error(ExtensionPairingProjectionError.CapacityExceeded)+ }+ if (+ current &&+ authenticatedAt !== null &&+ authenticatedAt < current.pairedAt+ ) {+ throw new Error(ExtensionPairingProjectionError.InvalidTime)+ }+ const updated: ExtensionPairingProjection = {+ identity: witness.identity,+ identityTrust: current+ ? conservativeTrust(current.identityTrust, witness.identityTrust)+ : witness.identityTrust,+ authorizationEpoch: witness.authorizationEpoch,+ status: 'ready',+ pairedAt: current?.pairedAt ?? witness.committedAt,+ lastActiveAt:+ authenticatedAt === null+ ? (current?.lastActiveAt ?? null)+ : Math.max(current?.lastActiveAt ?? 0, authenticatedAt),+ }+ if (current && recordEqual(current, updated)) return freezeRecord(current)+ const next = this.records.filter(+ (record) => identityKey(record.identity) !== key+ )+ next.push(updated)+ await this.persist(sortRecords(next))+ return freezeRecord(updated)+ }++ private issueCleanupLease(+ record: ExtensionPairingProjection+ ): ExtensionPairingCleanupLease {+ const key = identityKey(record.identity)+ const existing = this.activeCleanup.get(key)+ if (existing) return existing+ const lease = {+ identity: freezeIdentity(record.identity),+ authorizationEpoch: record.authorizationEpoch,+ } as ExtensionPairingCleanupLease+ Object.defineProperty(lease, CLEANUP_LEASE_BRAND, {+ configurable: false,+ enumerable: false,+ value: true,+ writable: false,+ })+ Object.freeze(lease)+ cleanupLeaseClaims.set(lease, {+ service: this,+ key,+ authorizationEpoch: record.authorizationEpoch,+ })+ this.activeCleanup.set(key, lease)+ return lease+ }++ private pruneResolvedCleanupLeases(): void {+ for (const [key, lease] of this.activeCleanup) {+ const claim = cleanupLeaseClaims.get(lease)+ const pending = this.records.find(+ (record) =>+ identityKey(record.identity) === key &&+ record.status === 'cleanup-pending'+ )+ if (+ !claim ||+ !pending ||+ pending.authorizationEpoch !== claim.authorizationEpoch+ ) {+ cleanupLeaseClaims.delete(lease)+ this.activeCleanup.delete(key)+ }+ }+ }++ private async persist(next: ExtensionPairingProjection[]): Promise<void> {+ const snapshot = freezeSnapshot(next)+ let nextRevision: number+ try {+ nextRevision = await this.store.save(snapshot, this.revision)+ } catch {+ return this.failDegraded(+ ExtensionPairingProjectionError.PersistenceFailed+ )+ }+ if (nextRevision !== this.revision + 1 || !validRevision(nextRevision)) {+ return this.failDegraded(+ ExtensionPairingProjectionError.PersistenceFailed+ )+ }+ this.records = snapshot.map(cloneRecord)+ this.revision = nextRevision+ }++ private readNow(): number {+ const now = this.now()+ if (!validTimestamp(now)) {+ throw new Error(ExtensionPairingProjectionError.InvalidTime)+ }+ return now+ }++ private failDegraded(message: string): never {+ this.health = 'degraded'+ this.records = []+ throw new Error(message)+ }++ private enqueue<T>(+ operation: () => Promise<T>,+ requiresReady = true+ ): Promise<T> {+ if (this.stopRequested || this.health === 'stopped') {+ return Promise.reject(new Error(ExtensionPairingProjectionError.Stopped))+ }+ const result = this.persistenceTail.then(async () => {+ if (requiresReady && this.health !== 'ready') {+ throw new Error(+ this.health === 'degraded'+ ? ExtensionPairingProjectionError.Degraded+ : ExtensionPairingProjectionError.NotLoaded+ )+ }+ return operation()+ })+ this.persistenceTail = result.then(+ () => undefined,+ () => undefined+ )+ return result+ }+}++function parseStoreSnapshot(snapshot: unknown): {+ revision: number+ records: ExtensionPairingProjection[]+} {+ if (+ typeof snapshot !== 'object' ||+ snapshot === null ||+ !hasOnlyKeys(snapshot as Record<string, unknown>, ['records', 'revision'])+ ) {+ throw new Error(ExtensionPairingProjectionError.StorageRejected)+ }+ const candidate = snapshot as { revision?: unknown; records?: unknown }+ if (!validRevision(candidate.revision) || !Array.isArray(candidate.records)) {+ throw new Error(ExtensionPairingProjectionError.StorageRejected)+ }+ if (candidate.records.length > MAX_PROJECTION_RECORDS) {+ throw new Error(ExtensionPairingProjectionError.StorageRejected)+ }+ const records = candidate.records.map(parseRecord)+ const sorted = sortRecords(records)+ for (let index = 1; index < sorted.length; index += 1) {+ if (+ identityKey(sorted[index - 1].identity) ===+ identityKey(sorted[index].identity)+ ) {+ throw new Error(ExtensionPairingProjectionError.StorageRejected)+ }+ }+ return { revision: candidate.revision, records: sorted }+}++function parseRecord(value: unknown): ExtensionPairingProjection {+ if (+ typeof value !== 'object' ||+ value === null ||+ !hasOnlyKeys(value as Record<string, unknown>, [+ 'authorizationEpoch',+ 'identity',+ 'identityTrust',+ 'lastActiveAt',+ 'pairedAt',+ 'status',+ ])+ ) {+ throw new Error(ExtensionPairingProjectionError.StorageRejected)+ }+ const candidate = value as Record<string, unknown>+ const identity = normalizeTransportIdentity(candidate.identity)+ if (+ identity === null ||+ !validTrust(candidate.identityTrust) ||+ !validEpoch(candidate.authorizationEpoch) ||+ (candidate.status !== 'ready' && candidate.status !== 'cleanup-pending') ||+ !validTimestamp(candidate.pairedAt) ||+ !(+ candidate.lastActiveAt === null ||+ (validTimestamp(candidate.lastActiveAt) &&+ candidate.lastActiveAt >= candidate.pairedAt)+ )+ ) {+ throw new Error(ExtensionPairingProjectionError.StorageRejected)+ }+ return {+ identity,+ identityTrust: candidate.identityTrust,+ authorizationEpoch: candidate.authorizationEpoch,+ status: candidate.status,+ pairedAt: candidate.pairedAt,+ lastActiveAt: candidate.lastActiveAt,+ }+}++interface WitnessAggregate {+ readonly identity: ExtensionTransportIdentity+ readonly identityTrust: IdentityTriState+ readonly authorizationEpoch: string+ readonly earliestCommittedAt: number+}++function aggregateWitnesses(+ witnesses: readonly CommittedExtensionCredentialWitness[]+): WitnessAggregate[] {+ if (witnesses.length > MAX_PROJECTION_RECORDS * 4) {+ throw new Error(ExtensionPairingProjectionError.CapacityExceeded)+ }+ const byIdentity = new Map<string, WitnessAggregate>()+ for (const witness of witnesses) {+ const key = identityKey(witness.identity)+ const current = byIdentity.get(key)+ if (current && current.authorizationEpoch !== witness.authorizationEpoch) {+ throw new Error(ExtensionPairingProjectionError.EpochConflict)+ }+ byIdentity.set(key, {+ identity: witness.identity,+ identityTrust: current+ ? conservativeTrust(current.identityTrust, witness.identityTrust)+ : witness.identityTrust,+ authorizationEpoch: witness.authorizationEpoch,+ earliestCommittedAt: Math.min(+ current?.earliestCommittedAt ?? witness.committedAt,+ witness.committedAt+ ),+ })+ if (byIdentity.size > MAX_PROJECTION_RECORDS) {+ throw new Error(ExtensionPairingProjectionError.CapacityExceeded)+ }+ }+ return [...byIdentity.values()].sort((left, right) =>+ compareIdentity(left.identity, right.identity)+ )+}++function conservativeTrust(+ left: IdentityTriState,+ right: IdentityTriState+): IdentityTriState {+ const order: readonly IdentityTriState[] = [+ 'unverified',+ 'attested-non-official',+ 'official',+ ]+ return order[Math.min(order.indexOf(left), order.indexOf(right))]+}++function normalizeTransportIdentity(+ value: unknown+): ExtensionTransportIdentity | null {+ if (+ typeof value !== 'object' ||+ value === null ||+ !hasOnlyKeys(value as Record<string, unknown>, [+ 'browser',+ 'extensionId',+ 'kind',+ ])+ ) {+ return null+ }+ const candidate = value as Record<string, unknown>+ if (+ candidate.kind !== 'extension' ||+ (candidate.browser !== 'chromium' && candidate.browser !== 'firefox') ||+ typeof candidate.extensionId !== 'string' ||+ candidate.extensionId.length === 0 ||+ candidate.extensionId.length > MAX_EXTENSION_ID_LENGTH ||+ candidate.extensionId !== candidate.extensionId.toLowerCase()+ ) {+ return null+ }+ const scheme =+ candidate.browser === 'chromium' ? 'chrome-extension' : 'moz-extension'+ const normalized = normalizeExtensionIdentity({+ browser: candidate.browser,+ verifiedOrigin: `${scheme}://${candidate.extensionId}`,+ claimedExtensionId: candidate.extensionId,+ })+ if (+ !normalized.ok ||+ normalized.identity.originHost !== candidate.extensionId+ ) {+ return null+ }+ return {+ kind: 'extension',+ browser: candidate.browser,+ extensionId: candidate.extensionId,+ }+}++function validTrust(value: unknown): value is IdentityTriState {+ return (+ value === 'official' ||+ value === 'attested-non-official' ||+ value === 'unverified'+ )+}++function validEpoch(value: unknown): value is string {+ return (+ typeof value === 'string' &&+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u.test(+ value+ )+ )+}++function validTimestamp(value: unknown): value is number {+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0+}++function validRevision(value: unknown): value is number {+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0+}++function identityKey(identity: ExtensionTransportIdentity): string {+ return JSON.stringify([identity.browser, identity.extensionId])+}++function compareIdentity(+ left: ExtensionTransportIdentity,+ right: ExtensionTransportIdentity+): number {+ return (+ left.browser.localeCompare(right.browser) ||+ left.extensionId.localeCompare(right.extensionId)+ )+}++function sortRecords(+ records: readonly ExtensionPairingProjection[]+): ExtensionPairingProjection[] {+ return [...records]+ .map(cloneRecord)+ .sort((left, right) => compareIdentity(left.identity, right.identity))+}++function recordEqual(+ left: ExtensionPairingProjection,+ right: ExtensionPairingProjection+): boolean {+ return (+ identityKey(left.identity) === identityKey(right.identity) &&+ left.identityTrust === right.identityTrust &&+ left.authorizationEpoch === right.authorizationEpoch &&+ left.status === right.status &&+ left.pairedAt === right.pairedAt &&+ left.lastActiveAt === right.lastActiveAt+ )+}++function recordsEqual(+ left: readonly ExtensionPairingProjection[],+ right: readonly ExtensionPairingProjection[]+): boolean {+ return (+ left.length === right.length &&+ left.every((record, index) =>+ right[index] ? recordEqual(record, right[index]) : false+ )+ )+}++function freezeIdentity(+ identity: ExtensionTransportIdentity+): ExtensionTransportIdentity {+ return Object.freeze({ ...identity })+}++function cloneRecord(+ record: ExtensionPairingProjection+): ExtensionPairingProjection {+ return {+ identity: { ...record.identity },+ identityTrust: record.identityTrust,+ authorizationEpoch: record.authorizationEpoch,+ status: record.status,+ pairedAt: record.pairedAt,+ lastActiveAt: record.lastActiveAt,+ }+}++function freezeRecord(+ record: ExtensionPairingProjection+): ExtensionPairingProjection {+ return Object.freeze({+ ...cloneRecord(record),+ identity: freezeIdentity(record.identity),+ })+}++function freezeSnapshot(+ records: readonly ExtensionPairingProjection[]+): readonly ExtensionPairingProjection[] {+ return Object.freeze(records.map(freezeRecord))+}++function hasOnlyKeys(+ value: Record<string, unknown>,+ expected: readonly string[]+): boolean {+ const keys = Object.keys(value).sort()+ const wanted = [...expected].sort()+ return (+ keys.length === wanted.length &&+ keys.every((key, index) => key === wanted[index])+ )+}diff --git a/src/core/bridge/file-extension-pairing-projection-store.test.ts b/src/core/bridge/file-extension-pairing-projection-store.test.tsnew file mode 100644index 00000000..1ff9d7c8--- /dev/null+++ b/src/core/bridge/file-extension-pairing-projection-store.test.ts@@ -0,0 +1,274 @@+import fs from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { acquireBridgeDataDirLock } from './bridge-data-dir-lock'+import type { ExtensionPairingProjection } from './extension-pairing-projection'+import {+ FileExtensionPairingProjectionStore,+ FileExtensionPairingProjectionStoreError,+ recoverExtensionPairingProjectionWriterLock,+} from './file-extension-pairing-projection-store'++const RECORD_A: ExtensionPairingProjection = {+ identity: {+ kind: 'extension',+ browser: 'chromium',+ extensionId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ },+ identityTrust: 'official',+ authorizationEpoch: '11111111-1111-4111-8111-111111111111',+ status: 'ready',+ pairedAt: 1_700_000_000_000,+ lastActiveAt: null,+}++const RECORD_B: ExtensionPairingProjection = {+ identity: {+ kind: 'extension',+ browser: 'firefox',+ extensionId: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',+ },+ identityTrust: 'unverified',+ authorizationEpoch: '22222222-2222-4222-8222-222222222222',+ status: 'ready',+ pairedAt: 1_700_000_001_000,+ lastActiveAt: 1_700_000_002_000,+}++describe('FileExtensionPairingProjectionStore', () => {+ let directory: string+ let filePath: string++ beforeEach(async () => {+ directory = await fs.mkdtemp(+ path.join(os.tmpdir(), 'extension-pairing-projection-')+ )+ filePath = path.join(directory, 'nested', 'extension-pairings.json')+ })++ afterEach(async () => {+ await fs.rm(directory, { recursive: true, force: true })+ })++ it('loads a missing document as revision zero and requires that load before save', async () => {+ const unloaded = new FileExtensionPairingProjectionStore(filePath)+ await expect(unloaded.save([RECORD_A], 0)).rejects.toThrow(+ FileExtensionPairingProjectionStoreError.Conflict+ )++ const store = new FileExtensionPairingProjectionStore(filePath)+ await expect(store.load()).resolves.toEqual({ revision: 0, records: [] })+ await expect(store.save([RECORD_A], 0)).resolves.toBe(1)+ })++ it('publishes a versioned document at 0600 and advances its durable revision', async () => {+ const store = new FileExtensionPairingProjectionStore(filePath)+ await store.load()++ await expect(store.save([RECORD_A], 0)).resolves.toBe(1)+ await expect(store.save([RECORD_A, RECORD_B], 1)).resolves.toBe(2)++ expect(JSON.parse(await fs.readFile(filePath, 'utf-8'))).toEqual({+ version: 1,+ revision: 2,+ records: [RECORD_A, RECORD_B],+ })+ if (process.platform !== 'win32') {+ expect((await fs.stat(filePath)).mode & 0o777).toBe(0o600)+ }+ expect(await fs.readdir(path.dirname(filePath))).toEqual([+ 'extension-pairings.json',+ ])+ })++ it.each([+ ['malformed', '{not-json'],+ [+ 'future',+ JSON.stringify({ version: 2, revision: 7, records: [RECORD_A] }),+ ],+ [+ 'unknown-field',+ JSON.stringify({+ version: 1,+ revision: 7,+ records: [RECORD_A],+ ignored: true,+ }),+ ],+ ])('preserves and fails closed on %s content', async (_name, content) => {+ await fs.mkdir(path.dirname(filePath), { recursive: true })+ await fs.writeFile(filePath, content, 'utf-8')+ const store = new FileExtensionPairingProjectionStore(filePath)++ await expect(store.load()).resolves.toEqual({+ revision: -1,+ records: null,+ })+ await expect(store.save([], 0)).rejects.toThrow(+ FileExtensionPairingProjectionStoreError.Conflict+ )+ await expect(fs.readFile(filePath, 'utf-8')).resolves.toBe(content)+ })++ it('rejects an oversized input before an unbounded read and preserves it', async () => {+ await fs.mkdir(path.dirname(filePath), { recursive: true })+ const content = Buffer.alloc(2 * 1024 * 1024 + 1, 0x61)+ await fs.writeFile(filePath, content)+ const store = new FileExtensionPairingProjectionStore(filePath)++ await expect(store.load()).rejects.toThrow(+ FileExtensionPairingProjectionStoreError.Rejected+ )+ expect((await fs.stat(filePath)).size).toBe(content.byteLength)+ })++ it('caps serialized output before creating the target', async () => {+ const store = new FileExtensionPairingProjectionStore(filePath)+ await store.load()+ const oversized = {+ ...RECORD_A,+ identity: {+ ...RECORD_A.identity,+ extensionId: 'a'.repeat(2 * 1024 * 1024),+ },+ }++ await expect(+ store.save([oversized as ExtensionPairingProjection], 0)+ ).rejects.toThrow(FileExtensionPairingProjectionStoreError.Rejected)+ await expect(fs.stat(filePath)).rejects.toMatchObject({ code: 'ENOENT' })+ })++ it('rejects a same-revision external rewrite using the loaded byte fingerprint', async () => {+ const store = new FileExtensionPairingProjectionStore(filePath)+ await store.load()+ await store.save([RECORD_A], 0)++ const external = JSON.stringify({+ version: 1,+ revision: 1,+ records: [RECORD_B],+ })+ await fs.writeFile(filePath, external, 'utf-8')++ await expect(store.save([], 1)).rejects.toThrow(+ FileExtensionPairingProjectionStoreError.Conflict+ )+ await expect(fs.readFile(filePath, 'utf-8')).resolves.toBe(external)+ })++ it('makes the second stale writer fail CAS without losing the first write', async () => {+ const first = new FileExtensionPairingProjectionStore(filePath)+ const second = new FileExtensionPairingProjectionStore(filePath)+ await Promise.all([first.load(), second.load()])++ await expect(first.save([RECORD_A], 0)).resolves.toBe(1)+ await expect(second.save([RECORD_B], 0)).rejects.toThrow(+ FileExtensionPairingProjectionStoreError.Conflict+ )++ const observer = new FileExtensionPairingProjectionStore(filePath)+ await expect(observer.load()).resolves.toEqual({+ revision: 1,+ records: [RECORD_A],+ })+ })++ it('fails closed while a writer lock already exists', async () => {+ const store = new FileExtensionPairingProjectionStore(filePath)+ await store.load()+ await fs.mkdir(path.dirname(filePath), { recursive: true })+ await fs.writeFile(`${filePath}.lock`, 'unknown owner', { mode: 0o600 })++ await expect(store.save([RECORD_A], 0)).rejects.toThrow(+ FileExtensionPairingProjectionStoreError.Conflict+ )+ await expect(fs.stat(filePath)).rejects.toMatchObject({ code: 'ENOENT' })+ })++ it('rejects a residual writer lock on startup without consuming the target', async () => {+ await fs.mkdir(path.dirname(filePath), { recursive: true })+ const content = JSON.stringify({+ version: 1,+ revision: 4,+ records: [RECORD_A],+ })+ await fs.writeFile(filePath, content, { mode: 0o600 })+ await fs.writeFile(`${filePath}.lock`, 'unknown owner', { mode: 0o600 })+ const store = new FileExtensionPairingProjectionStore(filePath)++ await expect(store.load()).rejects.toThrow(+ FileExtensionPairingProjectionStoreError.Conflict+ )+ await expect(fs.readFile(filePath, 'utf-8')).resolves.toBe(content)+ await expect(fs.readFile(`${filePath}.lock`, 'utf-8')).resolves.toBe(+ 'unknown owner'+ )+ })++ it.runIf(process.platform !== 'win32')(+ 'removes a regular crash-residual writer lock only under the data-root lock',+ async () => {+ const dataDirectory = path.dirname(filePath)+ await fs.mkdir(dataDirectory, { recursive: true })+ const dataDirLock = await acquireBridgeDataDirLock(dataDirectory)+ await fs.writeFile(`${filePath}.lock`, 'crashed writer', { mode: 0o600 })++ await recoverExtensionPairingProjectionWriterLock(filePath, dataDirLock)+ await expect(fs.lstat(`${filePath}.lock`)).rejects.toMatchObject({+ code: 'ENOENT',+ })+ await expect(+ new FileExtensionPairingProjectionStore(filePath).load()+ ).resolves.toEqual({ revision: 0, records: [] })++ await dataDirLock.release()+ }+ )++ it.runIf(process.platform !== 'win32')(+ 'preserves and rejects a symlinked residual writer lock',+ async () => {+ const dataDirectory = path.dirname(filePath)+ await fs.mkdir(dataDirectory, { recursive: true })+ const target = path.join(directory, 'unrelated-lock-target')+ await fs.writeFile(target, 'keep me', { mode: 0o600 })+ await fs.symlink(target, `${filePath}.lock`)+ const dataDirLock = await acquireBridgeDataDirLock(dataDirectory)++ await expect(+ recoverExtensionPairingProjectionWriterLock(filePath, dataDirLock)+ ).rejects.toThrow(FileExtensionPairingProjectionStoreError.Rejected)+ await expect(fs.readFile(target, 'utf-8')).resolves.toBe('keep me')+ expect((await fs.lstat(`${filePath}.lock`)).isSymbolicLink()).toBe(true)++ await dataDirLock.release()+ }+ )++ it.runIf(process.platform !== 'win32')(+ 'never follows a final symlink on load or save',+ async () => {+ await fs.mkdir(path.dirname(filePath), { recursive: true })+ const target = path.join(directory, 'sensitive.json')+ const original = 'do not replace'+ await fs.writeFile(target, original, 'utf-8')+ await fs.symlink(target, filePath)+ const store = new FileExtensionPairingProjectionStore(filePath)++ await expect(store.load()).rejects.toThrow(+ FileExtensionPairingProjectionStoreError.Rejected+ )+ await expect(fs.readFile(target, 'utf-8')).resolves.toBe(original)++ await fs.unlink(filePath)+ const writer = new FileExtensionPairingProjectionStore(filePath)+ await writer.load()+ await fs.symlink(target, filePath)+ await expect(writer.save([RECORD_A], 0)).rejects.toThrow()+ await expect(fs.readFile(target, 'utf-8')).resolves.toBe(original)+ }+ )+})diff --git a/src/core/bridge/file-extension-pairing-projection-store.ts b/src/core/bridge/file-extension-pairing-projection-store.tsnew file mode 100644index 00000000..59953707--- /dev/null+++ b/src/core/bridge/file-extension-pairing-projection-store.ts@@ -0,0 +1,439 @@+import { createHash, randomUUID } from 'node:crypto'+import { constants, type Stats } from 'node:fs'+import fs from 'node:fs/promises'+import path from 'node:path'+import {+ type BridgeDataDirLockHandle,+ withBridgeDataDirLock,+} from './bridge-data-dir-lock'+import type {+ ExtensionPairingProjection,+ ExtensionPairingProjectionStore,+ ExtensionPairingProjectionStoreSnapshot,+} from './extension-pairing-projection'++const PROJECTION_DOCUMENT_VERSION = 1+const MAX_PROJECTION_DOCUMENT_BYTES = 2 * 1024 * 1024+const MISSING_FINGERPRINT = 'missing'++export const FileExtensionPairingProjectionStoreError = Object.freeze({+ Rejected: 'extension-pairing-projection file rejected',+ Conflict: 'extension-pairing-projection file conflict',+} as const)++type StoreFailureKind = 'rejected' | 'conflict'++class StoreFailure extends Error {+ constructor(readonly kind: StoreFailureKind) {+ super(+ kind === 'conflict'+ ? FileExtensionPairingProjectionStoreError.Conflict+ : FileExtensionPairingProjectionStoreError.Rejected+ )+ }+}++interface ProjectionDocument {+ readonly version: typeof PROJECTION_DOCUMENT_VERSION+ readonly revision: number+ readonly records: unknown[]+}++interface ReadResult {+ readonly fingerprint: string+ readonly document: ProjectionDocument | null+}++interface LoadedClaim {+ readonly fingerprint: string+ readonly revision: number+ readonly valid: boolean+}++/**+ * Remove a crash-residual projection writer lock while the caller owns the+ * entire bridge data root. Unknown file types, links, permissions, or path+ * replacement are preserved and rejected; no age/PID heuristic is used.+ */+export async function recoverExtensionPairingProjectionWriterLock(+ filePath: string,+ dataDirLock: BridgeDataDirLockHandle+): Promise<void> {+ const directory = path.dirname(filePath)+ return withBridgeDataDirLock(dataDirLock, directory, async () => {+ const lockPath = `${filePath}.lock`+ let before: Awaited<ReturnType<typeof fs.lstat>>+ try {+ before = await fs.lstat(lockPath)+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return+ throw new Error(FileExtensionPairingProjectionStoreError.Rejected)+ }+ if (+ process.platform === 'win32' ||+ constants.O_NOFOLLOW === undefined ||+ before.isSymbolicLink() ||+ !before.isFile() ||+ before.nlink !== 1 ||+ (before.mode & 0o777) !== 0o600+ ) {+ throw new Error(FileExtensionPairingProjectionStoreError.Rejected)+ }++ let handle: fs.FileHandle | null = null+ try {+ handle = await fs.open(+ lockPath,+ constants.O_RDONLY | constants.O_NOFOLLOW+ )+ const opened = await handle.stat()+ if (+ !opened.isFile() ||+ opened.dev !== before.dev ||+ opened.ino !== before.ino ||+ opened.nlink !== 1+ ) {+ throw new Error(FileExtensionPairingProjectionStoreError.Rejected)+ }+ await handle.close()+ handle = null++ const current = await fs.lstat(lockPath)+ if (current.dev !== before.dev || current.ino !== before.ino) {+ throw new Error(FileExtensionPairingProjectionStoreError.Rejected)+ }+ await fs.unlink(lockPath)+ await syncParentDirectory(directory)+ } catch {+ throw new Error(FileExtensionPairingProjectionStoreError.Rejected)+ } finally {+ await handle?.close().catch(() => undefined)+ }+ })+}++/**+ * A bounded, fail-closed projection store.+ *+ * Every save holds a sibling exclusive lock, re-reads the target without+ * following a final symlink, and compares both the durable revision and the+ * exact bytes seen by this instance's last successful load/save. The content+ * fingerprint prevents a same-revision external edit from being overwritten.+ * A crash may leave the lock file behind; that intentionally blocks future+ * writers until the bridge data directory is recovered rather than guessing+ * whether an unknown writer is still active.+ */+export class FileExtensionPairingProjectionStore+ implements ExtensionPairingProjectionStore+{+ private loadedClaim: LoadedClaim | null = null++ constructor(private readonly filePath: string) {}++ async load(): Promise<ExtensionPairingProjectionStoreSnapshot> {+ try {+ // A crashed writer may have published the target and died before+ // releasing its sibling lock. Treat that state as unavailable even for+ // reads: consuming the target would let startup present a projection+ // whose transaction outcome is unknown.+ await assertWriterLockMissing(this.filePath)+ const result = await readBoundedDocument(this.filePath)+ if (result.document === null) {+ this.loadedClaim = {+ fingerprint: result.fingerprint,+ revision: -1,+ valid: false,+ }+ return { revision: -1, records: null }+ }+ this.loadedClaim = {+ fingerprint: result.fingerprint,+ revision: result.document.revision,+ valid: true,+ }+ return {+ revision: result.document.revision,+ records: result.document.records,+ }+ } catch (error) {+ this.loadedClaim = {+ fingerprint: 'rejected',+ revision: -1,+ valid: false,+ }+ throw publicFailure(error)+ }+ }++ async save(+ next: readonly ExtensionPairingProjection[],+ expectedRevision: number+ ): Promise<number> {+ try {+ return await this.saveChecked(next, expectedRevision)+ } catch (error) {+ throw publicFailure(error)+ }+ }++ private async saveChecked(+ next: readonly ExtensionPairingProjection[],+ expectedRevision: number+ ): Promise<number> {+ if (+ !validRevision(expectedRevision) ||+ expectedRevision >= Number.MAX_SAFE_INTEGER+ ) {+ throw new StoreFailure('rejected')+ }+ const claim = this.loadedClaim+ if (claim === null || !claim.valid || claim.revision !== expectedRevision) {+ throw new StoreFailure('conflict')+ }++ const nextRevision = expectedRevision + 1+ const document: ProjectionDocument = {+ version: PROJECTION_DOCUMENT_VERSION,+ revision: nextRevision,+ records: [...next],+ }+ let serialized: Buffer+ try {+ serialized = Buffer.from(JSON.stringify(document, null, 2), 'utf-8')+ } catch {+ throw new StoreFailure('rejected')+ }+ if (serialized.byteLength > MAX_PROJECTION_DOCUMENT_BYTES) {+ throw new StoreFailure('rejected')+ }++ await fs.mkdir(path.dirname(this.filePath), { recursive: true })+ const lockPath = `${this.filePath}.lock`+ let lock: fs.FileHandle+ try {+ lock = await fs.open(+ lockPath,+ constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL,+ 0o600+ )+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') {+ throw new StoreFailure('conflict')+ }+ throw error+ }++ let result: number | undefined+ let primaryError: unknown+ try {+ const current = await readBoundedDocument(this.filePath)+ if (+ current.document === null ||+ current.document.revision !== expectedRevision ||+ current.fingerprint !== claim.fingerprint+ ) {+ throw new StoreFailure('conflict')+ }++ await replaceDurably(this.filePath, serialized)+ this.loadedClaim = {+ fingerprint: fingerprint(serialized),+ revision: nextRevision,+ valid: true,+ }+ result = nextRevision+ } catch (error) {+ primaryError = error+ }+ try {+ await lock.close()+ await fs.unlink(lockPath)+ } catch (cleanupError) {+ primaryError ??= cleanupError+ }+ if (primaryError !== undefined) throw primaryError+ if (result === undefined) throw new StoreFailure('rejected')+ return result+ }+}++async function assertWriterLockMissing(filePath: string): Promise<void> {+ try {+ await fs.lstat(`${filePath}.lock`)+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return+ throw error+ }+ throw new StoreFailure('conflict')+}++async function readBoundedDocument(filePath: string): Promise<ReadResult> {+ let metadata: Stats+ try {+ metadata = await fs.lstat(filePath)+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {+ return {+ fingerprint: MISSING_FINGERPRINT,+ document: {+ version: PROJECTION_DOCUMENT_VERSION,+ revision: 0,+ records: [],+ },+ }+ }+ throw error+ }+ if (metadata.isSymbolicLink() || !metadata.isFile()) {+ throw new StoreFailure('rejected')+ }+ if (metadata.size > MAX_PROJECTION_DOCUMENT_BYTES) {+ throw new StoreFailure('rejected')+ }++ const noFollow = constants.O_NOFOLLOW ?? 0+ const handle = await fs.open(filePath, constants.O_RDONLY | noFollow)+ try {+ const openedMetadata = await handle.stat()+ if (+ !openedMetadata.isFile() ||+ openedMetadata.size > MAX_PROJECTION_DOCUMENT_BYTES+ ) {+ throw new StoreFailure('rejected')+ }+ const buffer = Buffer.allocUnsafe(MAX_PROJECTION_DOCUMENT_BYTES + 1)+ let offset = 0+ while (offset < buffer.byteLength) {+ const { bytesRead } = await handle.read(+ buffer,+ offset,+ buffer.byteLength - offset,+ offset+ )+ if (bytesRead === 0) break+ offset += bytesRead+ }+ if (offset > MAX_PROJECTION_DOCUMENT_BYTES) {+ throw new StoreFailure('rejected')+ }+ const raw = buffer.subarray(0, offset)+ return {+ fingerprint: fingerprint(raw),+ document: parseDocument(raw),+ }+ } finally {+ await handle.close()+ }+}++function parseDocument(raw: Buffer): ProjectionDocument | null {+ let value: unknown+ try {+ value = JSON.parse(raw.toString('utf-8'))+ } catch {+ return null+ }+ if (+ typeof value !== 'object' ||+ value === null ||+ !hasOnlyKeys(value as Record<string, unknown>, [+ 'records',+ 'revision',+ 'version',+ ])+ ) {+ return null+ }+ const candidate = value as Record<string, unknown>+ if (+ candidate.version !== PROJECTION_DOCUMENT_VERSION ||+ !validRevision(candidate.revision) ||+ !Array.isArray(candidate.records)+ ) {+ return null+ }+ return {+ version: PROJECTION_DOCUMENT_VERSION,+ revision: candidate.revision,+ records: candidate.records,+ }+}++async function replaceDurably(+ filePath: string,+ content: Buffer+): Promise<void> {+ await rejectFinalSymlink(filePath)+ const directory = path.dirname(filePath)+ const temporaryPath = path.join(+ directory,+ `.${path.basename(filePath)}.${process.pid}.${randomUUID()}.tmp`+ )+ const noFollow = constants.O_NOFOLLOW ?? 0+ let temporary: fs.FileHandle | null = null+ let renamed = false+ try {+ temporary = await fs.open(+ temporaryPath,+ constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollow,+ 0o600+ )+ await temporary.writeFile(content)+ await temporary.sync()+ await temporary.close()+ temporary = null+ await rejectFinalSymlink(filePath)+ await fs.rename(temporaryPath, filePath)+ renamed = true+ await syncParentDirectory(directory)+ } finally {+ if (temporary !== null) await temporary.close().catch(() => undefined)+ if (!renamed) await fs.unlink(temporaryPath).catch(() => undefined)+ }+}++async function rejectFinalSymlink(filePath: string): Promise<void> {+ try {+ const metadata = await fs.lstat(filePath)+ if (metadata.isSymbolicLink() || !metadata.isFile()) {+ throw new StoreFailure('rejected')+ }+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error+ }+}++async function syncParentDirectory(directory: string): Promise<void> {+ if (process.platform === 'win32') return+ const handle = await fs.open(directory, 'r')+ try {+ await handle.sync()+ } finally {+ await handle.close()+ }+}++function fingerprint(raw: Buffer): string {+ return createHash('sha256').update(raw).digest('base64url')+}++function validRevision(value: unknown): value is number {+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0+}++function hasOnlyKeys(+ value: Record<string, unknown>,+ expected: readonly string[]+): boolean {+ const keys = Object.keys(value).sort()+ const wanted = [...expected].sort()+ return (+ keys.length === wanted.length &&+ keys.every((key, index) => key === wanted[index])+ )+}++function publicFailure(error: unknown): Error {+ if (error instanceof StoreFailure) return new Error(error.message)+ return new Error(FileExtensionPairingProjectionStoreError.Rejected)+}diff --git a/src/core/bridge/mbp1/frames.ts b/src/core/bridge/mbp1/frames.tsindex 8d7b597a..0b6befdd 100644--- a/src/core/bridge/mbp1/frames.ts+++ b/src/core/bridge/mbp1/frames.ts@@ -297,6 +297,7 @@ export const PAIR_ERROR_CODES = ['rateLimited','codeMismatch','expired',+ 'denied','aborted','authFailed','protocolViolation',diff --git a/src/core/bridge/mbp1/nonce-service.ts b/src/core/bridge/mbp1/nonce-service.tsindex 6c2859e4..ffe37d62 100644--- a/src/core/bridge/mbp1/nonce-service.ts+++ b/src/core/bridge/mbp1/nonce-service.ts@@ -18,6 +18,13 @@ const DEFAULT_MAX_OUTSTANDING = 32const DEFAULT_RATE_PER_MINUTE = 60const DEFAULT_PER_ORIGIN_PER_MINUTE = 10const RATE_WINDOW_MS = 60_000+export const MBP1_PAIR_NONCE_BYTES = 16+const CANONICAL_MBP1_PAIR_NONCE = /^[A-Za-z0-9_-]{21}[AQgw]$/u++/** Canonical unpadded base64url encoding of the 16-byte §4.2 nonce. */+export function isCanonicalMbp1PairNonce(value: unknown): value is string {+ return typeof value === 'string' && CANONICAL_MBP1_PAIR_NONCE.test(value)+}export interface NonceServiceOptions {/** Nonce lifetime. Default 60s (§4.2). */@@ -101,7 +108,10 @@ export class NonceService {this.originIssueTimes.set(verifiedOrigin, recentOrigin)}- const nonce = toBase64Url(randomBytes(16))+ const nonce = toBase64Url(randomBytes(MBP1_PAIR_NONCE_BYTES))+ if (!isCanonicalMbp1PairNonce(nonce)) {+ throw new Error('mbp1 nonce generation failed')+ }this.nonces.set(nonce, t + this.ttlMs)return { nonce, ttlSeconds: Math.floor(this.ttlMs / 1000) }}diff --git a/src/core/bridge/mbp1/pair-session.test.ts b/src/core/bridge/mbp1/pair-session.test.tsindex 78855a8d..e3705d90 100644--- a/src/core/bridge/mbp1/pair-session.test.ts+++ b/src/core/bridge/mbp1/pair-session.test.ts@@ -5,6 +5,13 @@ import { utf8ToBytes } from '@noble/hashes/utils.js'import type { Browser } from '@shared/protocol/bridge'import { beforeEach, describe, expect, it, vi } from 'vitest'import type { CredentialPrincipal, IdentityTriState } from '../credential-store'+import type {+ PairingPromptCallbackStatus,+ PairingPromptEnqueueResult,+ PairingPromptSessionOutcome,+ PairingPromptSettleResult,+ PairingPromptTerminalOutcome,+} from '../pairing-prompt-controller'import { hexToBytes, loadMbp1Vectors } from './__tests__/vectors'import {concatBytes,@@ -59,6 +66,7 @@ interface DialogArgs {identity: IdentityTriStatecode: stringpairingNonce: string+ verifiedOrigin: string}interface Deferred<T> {@@ -90,6 +98,8 @@ interface HarnessOptions {credentialId: stringmutualKeyB64: string}>+ enqueueFailure?: Extract<PairingPromptEnqueueResult, { ok: false }>['reason']+ published?: Promise<PairingPromptCallbackStatus>}function makeHarness(opts: HarnessOptions = {}) {@@ -98,11 +108,16 @@ function makeHarness(opts: HarnessOptions = {}) {const closed: string[] = []const dialogs: DialogArgs[] = []const order: string[] = []- const dismissals: Deferred<void>[] = []- const dialogClosed: number[] = []+ const promptSettlements: PairingPromptTerminalOutcome[] = []+ const prompts: Array<{+ live: boolean+ terminal: Deferred<PairingPromptTerminalOutcome>+ }> = []const released: string[] = []- let authenticated: { sealer: EnvelopeSealer; opener: EnvelopeOpener } | null =- null+ let authenticated: {+ channel: { sealer: EnvelopeSealer; opener: EnvelopeOpener }+ credentialId: string+ } | null = nullconst replay = new TicketReplayCache()const replayAdd = vi.spyOn(replay, 'add').mockImplementation(function (@@ -165,16 +180,24 @@ function makeHarness(opts: HarnessOptions = {}) {order.push('release')released.push(origin)}),- queueDialog: vi.fn((args: DialogArgs) => {+ queueDialog: vi.fn((args: DialogArgs): PairingPromptEnqueueResult => {order.push('queueDialog')dialogs.push(args)- const d = deferred<void>()- dismissals.push(d)- const index = dismissals.length - 1+ if (opts.enqueueFailure !== undefined) {+ return { ok: false, reason: opts.enqueueFailure }+ }+ const terminal = deferred<PairingPromptTerminalOutcome>()+ const record = { live: true, terminal }+ prompts.push(record)+ const index = prompts.length - 1return {- dismissed: d.promise,- close: () => {- dialogClosed.push(index)+ ok: true,+ handle: {+ promptId: `prompt-${index + 1}`,+ published: opts.published ?? Promise.resolve('delivered'),+ terminal: terminal.promise,+ settle: (outcome: PairingPromptSessionOutcome) =>+ settlePrompt(index, outcome),},}}),@@ -189,9 +212,9 @@ function makeHarness(opts: HarnessOptions = {}) {close: (reason: string) => {closed.push(reason)},- onAuthenticated: (channel) => {+ onAuthenticated: (channel, credentialId) => {order.push('onAuthenticated')- authenticated = channel+ authenticated = { channel, credentialId }},now: opts.now ?? (() => T0),random: opts.random ?? ((n: number) => new Uint8Array(randomBytes(n))),@@ -207,12 +230,12 @@ function makeHarness(opts: HarnessOptions = {}) {closed,dialogs,order,- dismissals,- dialogClosed,+ promptSettlements,released,replayAdd,offerProvisional,commitFromPair,+ settlePrompt,get authenticated() {return authenticated},@@ -232,6 +255,20 @@ function makeHarness(opts: HarnessOptions = {}) {return this.lastSent() as unknown as PairErrorFrame},}++ function settlePrompt(+ index: number,+ outcome: PairingPromptTerminalOutcome+ ): PairingPromptSettleResult {+ const prompt = prompts[index]+ if (prompt === undefined || !prompt.live) {+ return { ok: false, reason: 'unavailable' }+ }+ prompt.live = false+ promptSettlements.push(outcome)+ prompt.terminal.resolve(outcome)+ return { ok: true, outcome }+ }}type Harness = ReturnType<typeof makeHarness>@@ -508,6 +545,7 @@ describe('PairSession', () => {)expect(h.authenticated).not.toBeNull()+ expect(h.authenticated?.credentialId).toBe('cred-1111-2222-3333')expect(h.order.indexOf('onAuthenticated')).toBeGreaterThan(h.order.lastIndexOf('sendBinary'))@@ -823,7 +861,7 @@ describe('PairSession', () => {expect(h.error()).toEqual({ type: 'pairError', code: 'rateLimited' })expect(h.closed).toHaveLength(1)expect(h.session.attemptCount).toBe(3)- expect(h.dialogClosed).toEqual([0])+ expect(h.promptSettlements).toEqual(['aborted'])// The code is dead: even the right one cannot start another run.const right = new ClientDouble({ code })@@ -974,7 +1012,7 @@ describe('PairSession', () => {h.session.dispose('socket-closed')expect(h.session.attemptCount).toBe(1)- expect(h.dialogClosed).toEqual([0])+ expect(h.promptSettlements).toEqual(['aborted'])})it('does not consume an attempt for a session that never reached pakeA', async () => {@@ -993,13 +1031,100 @@ describe('PairSession', () => {expect(h.sent).toEqual([{ type: 'pairAccept', protocolVersion: 1, instanceId: INSTANCE_ID },])- expect(h.dialogClosed).toEqual([])+ expect(h.promptSettlements).toEqual([])expect(h.order.indexOf('queueDialog')).toBeLessThan(h.order.indexOf('sendText'))})})+ describe('prompt adapter fail-closed boundary', () => {+ it('sends pairAccept only after the shell confirms prompt publication', async () => {+ const publication = deferred<PairingPromptCallbackStatus>()+ const h = makeHarness({ published: publication.promise })+ const handling = h.text(helloFrame())+ await Promise.resolve()+ await Promise.resolve()++ expect(h.sent).toEqual([])+ publication.resolve('delivered')+ await handling++ expect(h.sent).toEqual([+ { type: 'pairAccept', protocolVersion: 1, instanceId: INSTANCE_ID },+ ])+ })++ it.each([+ 'duplicate',+ 'capacity',+ 'disposed',+ 'invalid-origin',+ 'scheduling-failed',+ ] as const)(+ 'collapses an enqueue %s refusal to pairingFailed',+ async (enqueueFailure) => {+ const h = makeHarness({ enqueueFailure })++ await h.text(helloFrame())++ expect(h.error()).toEqual({+ type: 'pairError',+ code: 'pairingFailed',+ })+ expect(h.closed).toHaveLength(1)+ expect(h.promptSettlements).toEqual([])+ expect(h.released).toEqual([ORIGIN])+ }+ )++ it.each(['failed', 'not-configured'] as const)(+ 'closes generically when prompt publication is %s',+ async (status) => {+ const h = makeHarness({ published: Promise.resolve(status) })++ await h.text(helloFrame())++ expect(h.sent).toEqual([{ type: 'pairError', code: 'pairingFailed' }])+ expect(h.promptSettlements).toEqual(['aborted'])+ expect(h.closed).toHaveLength(1)+ }+ )++ it('contains a rejected publisher without leaking its error or hanging', async () => {+ const h = makeHarness({+ published: Promise.reject(+ new Error(`publisher-secret:${PAIR_NONCE}:1234-5678`)+ ),+ })++ await h.text(helloFrame())++ expect(h.sent).toEqual([{ type: 'pairError', code: 'pairingFailed' }])+ expect(JSON.stringify(h.sent)).not.toContain('publisher-secret')+ expect(JSON.stringify(h.sent)).not.toContain(PAIR_NONCE)+ expect(h.promptSettlements).toEqual(['aborted'])+ })++ it('does not emit pairAccept after teardown wins a pending publication', async () => {+ const publication = deferred<PairingPromptCallbackStatus>()+ const h = makeHarness({ published: publication.promise })+ const handling = h.text(helloFrame())+ await Promise.resolve()+ await Promise.resolve()++ expect(h.dialogs).toHaveLength(1)+ expect(h.sent).toEqual([])+ h.session.dispose('socket-closed')+ publication.resolve('delivered')+ await handling++ expect(h.sent).toEqual([])+ expect(h.promptSettlements).toEqual(['aborted'])+ expect(h.released).toEqual([ORIGIN])+ })+ })+describe('scenario 7: 120 s code lifetime (§7.2)', () => {it('expires the code 120 s after the dialog was queued', async () => {let now = T0@@ -1013,7 +1138,7 @@ describe('PairSession', () => {expect(h.error()).toEqual({ type: 'pairError', code: 'expired' })expect(h.closed).toHaveLength(1)- expect(h.dialogClosed).toEqual([0])+ expect(h.promptSettlements).toEqual(['aborted'])})it('still accepts a run that starts inside the window', async () => {@@ -1041,18 +1166,29 @@ describe('PairSession', () => {})})- describe('scenario 8: dialog dismissal', () => {- it('aborts and closes when the user dismisses the dialog', async () => {- const h = makeHarness()- await openSession(h)+ describe('scenario 8: prompt terminal outcome mapping', () => {+ it.each([+ ['denied', 'denied'],+ ['expired', 'expired'],+ ['aborted', 'aborted'],+ ] as const)(+ 'maps controller %s to wire %s before confirmation',+ async (terminal, wire) => {+ const h = makeHarness()+ await openSession(h)- h.dismissals[0].resolve()- await Promise.resolve()- await Promise.resolve()+ expect(h.settlePrompt(0, terminal)).toEqual({+ ok: true,+ outcome: terminal,+ })+ await Promise.resolve()+ await Promise.resolve()- expect(h.error()).toEqual({ type: 'pairError', code: 'aborted' })- expect(h.closed).toHaveLength(1)- })+ expect(h.error()).toEqual({ type: 'pairError', code: wire })+ expect(h.closed).toHaveLength(1)+ expect(h.promptSettlements).toEqual([terminal])+ }+ )it('ignores a dismissal that arrives after the pairing already succeeded', async () => {const h = makeHarness()@@ -1061,13 +1197,34 @@ describe('PairSession', () => {await runHandshake(h, client)const before = h.sent.length- h.dismissals[0].resolve()+ expect(h.settlePrompt(0, 'denied')).toEqual({+ ok: false,+ reason: 'unavailable',+ })await Promise.resolve()await Promise.resolve()expect(h.sent).toHaveLength(before)expect(h.closed).toEqual([])})++ it('lets denial win a same-turn confirm race without sending confirmB', async () => {+ const h = makeHarness()+ const code = await openSession(h)+ const client = new ClientDouble({ code })+ await h.text(client.pakeA())+ const confirmA = client.confirmA(h.lastSent())++ expect(h.settlePrompt(0, 'denied')).toEqual({+ ok: true,+ outcome: 'denied',+ })+ await h.text(confirmA)++ expect(h.sent.some((frame) => frame.type === 'confirmB')).toBe(false)+ expect(h.error()).toEqual({ type: 'pairError', code: 'denied' })+ expect(h.closed).toHaveLength(1)+ })})describe('§7.3 admission ordering', () => {@@ -1100,19 +1257,19 @@ describe('PairSession', () => {// Released at confirmation, not at socket close: a paired connection// lives for hours, and three of them would otherwise block every dialog.expect(h.released).toEqual([ORIGIN])- expect(h.dialogClosed).toEqual([0])+ expect(h.promptSettlements).toEqual(['paired'])h.session.dispose('socket-closed')expect(h.released).toEqual([ORIGIN])- // The dialog is closed exactly once too: `PairDialogHandle.close` is not- // required to be idempotent, and confirmation + dispose both reach it.- expect(h.dialogClosed).toEqual([0])+ // The explicit terminal handle is settled exactly once: confirmation+ // wins with `paired`, so later socket disposal cannot relabel it.+ expect(h.promptSettlements).toEqual(['paired'])})it('frees the pending slot when the session ends without pairing', async () => {for (const end of [async (h: Harness) => {- h.dismissals[0].resolve()+ h.settlePrompt(0, 'denied')await Promise.resolve()await Promise.resolve()},@@ -1277,21 +1434,18 @@ describe('PairSession', () => {expect(h.closed).toHaveLength(1)})- it('reports a non-ASCII verified origin as pairingFailed', async () => {- // `enc()` refuses a non-ASCII string (§2), which would otherwise throw- // out of the frame handler while building A_id.- //- // Uses a Firefox origin throughout rather than declaring `firefox` over a- // `chrome-extension://` one. The old version did the latter to skip the- // Chromium origin/claimedId check and reach `enc()` — which is exactly- // the bypass that check now refuses, so the test was quietly relying on- // the defect it sat next to.+ it('rejects a non-ASCII verified origin at the identity boundary', async () => {+ // Raw Origin bytes must exactly match canonical `scheme//host`; allowing+ // WHATWG's Unicode/percent normalization would create identity aliases.const h = makeHarness({browser: 'firefox',verifiedOrigin: 'moz-extension://ídentity',})await h.text(helloFrame({ browser: 'firefox' }))- expect(h.error()).toEqual({ type: 'pairError', code: 'pairingFailed' })+ expect(h.error()).toEqual({+ type: 'pairError',+ code: 'protocolViolation',+ })expect(h.dialogs).toHaveLength(0)})diff --git a/src/core/bridge/mbp1/pair-session.ts b/src/core/bridge/mbp1/pair-session.tsindex dacadbea..6ccc863d 100644--- a/src/core/bridge/mbp1/pair-session.ts+++ b/src/core/bridge/mbp1/pair-session.ts@@ -47,6 +47,18 @@ import { timingSafeEqual } from 'node:crypto'import { utf8ToBytes } from '@noble/hashes/utils.js'import type { Browser } from '@shared/protocol/bridge'import type { CredentialPrincipal, IdentityTriState } from '../credential-store'+import {+ type NormalizedExtensionIdentity,+ normalizeExtensionIdentity,+ resolveNormalizedExtensionIdentity,+} from '../extension-identity-resolver'+import type {+ PairingPromptEnqueueResult,+ PairingPromptHandle,+ PairingPromptSessionOutcome,+ PairingPromptSettleResult,+ PairingPromptTerminalOutcome,+} from '../pairing-prompt-controller'import { fromBase64Url, toBase64Url } from './canonical'import { DIR_C2S, DIR_S2C, EnvelopeOpener, EnvelopeSealer } from './envelope'import {@@ -90,11 +102,9 @@ import { buildAad, buildAId, buildBId, ticketDigest } from './transcript'/** Attempts a single pairing code allows before it dies (§7.2). */const MAX_ATTEMPTS = 3-/** Pairing-code lifetime from the moment the dialog is queued (§7.2). */+/** Pairing-code lifetime from the moment the prompt is queued (§7.2). */const CODE_LIFETIME_MS = 120_000-const CHROMIUM_ORIGIN_SCHEME = 'chrome-extension://'-/*** The §7.3 admission verdict. Structurally identical to* `PairFloodControl.admit`, which is what the wiring passes through.@@ -113,8 +123,8 @@ export interface PairDialogRequest {pairingNonce: string/*** The verified `Origin` this `/pair` connection presented (§5) — never a- * self-reported field. The shell's dialog controller keys its per-key- * prompt dedup on this, never on `claimedExtensionId`: on Firefox the+ * self-reported field. The prompt controller keys its dedup on this, never+ * on `claimedExtensionId`: on Firefox the* claimed id is self-reported, so keying on it would let one extension* suppress another's prompt by claiming its id. Internal bookkeeping only —* never surfaced to the renderer.@@ -122,12 +132,6 @@ export interface PairDialogRequest {verifiedOrigin: string}-/** A queued approval dialog. `dismissed` resolves when the user dismisses it. */-export interface PairDialogHandle {- dismissed: Promise<void>- close(): void-}-/*** The two `Mbp1CredentialStore` operations §6.7's first-pair flow needs.* Narrowed to what this module calls so the session can be driven by a double@@ -190,7 +194,7 @@ export interface PairSessionDeps {* from `attemptCount` and whether `onAuthenticated` fired.*/release(verifiedOrigin: string): void- queueDialog(args: PairDialogRequest): PairDialogHandle+ queueDialog(args: PairDialogRequest): PairingPromptEnqueueResultsendText(json: object): voidsendBinary(frame: Uint8Array): voidclose(reason: string): void@@ -199,10 +203,14 @@ export interface PairSessionDeps {* envelope endpoints — their sequence counters continue from the credential* exchange, so MDXP must reuse these instances rather than derive new ones.*/- onAuthenticated(channel: {- sealer: EnvelopeSealer- opener: EnvelopeOpener- }): void+ onAuthenticated(+ channel: {+ sealer: EnvelopeSealer+ opener: EnvelopeOpener+ },+ /** The exact durable credential committed by this session. */+ credentialId: string+ ): voidnow(): numberrandom(n: number): Uint8Array}@@ -241,7 +249,7 @@ export class PairSession {private readonly deps: PairSessionDepsprivate state: PairState = 'awaiting-hello'private hello: HelloContext | null = null- private dialog: PairDialogHandle | null = null+ private prompt: PairingPromptHandle | null = nullprivate codeNormalized: string | null = nullprivate codeExpiresAt = 0private w: bigint | null = null@@ -304,7 +312,7 @@ export class PairSession {switch (envelope.data.type) {case 'pairHello':- this.onPairHello(body)+ await this.onPairHello(body)returncase 'pakeA':this.onPakeA(body)@@ -349,10 +357,11 @@ export class PairSession {return}+ const credentialId = ack.data.credentialIdthis.state = 'acked'try {// §6.7 step 3: durable first, then the message that announces it.- await this.deps.credentials.commitFromPair(ack.data.credentialId)+ await this.deps.credentials.commitFromPair(credentialId)} catch {this.terminate('credentialCommitFailed')return@@ -377,7 +386,7 @@ export class PairSession {return}this.state = 'committed'- this.deps.onAuthenticated(channel)+ this.deps.onAuthenticated(channel, credentialId)}/**@@ -388,13 +397,13 @@ export class PairSession {* deliberately preserved (§7.2).*/dispose(_reason: 'socket-closed' | 'timeout' | 'access-revoked'): void {- if (this.state === 'closed') {+ if (this.isClosed()) {return}this.state = 'closed'this.discardRunState()try {- this.closeDialog()+ this.settlePrompt('aborted')} finally {// A renderer/dialog teardown fault must not leak §7.3's pending slot.this.releasePendingSlot()@@ -403,7 +412,7 @@ export class PairSession {// -- §6.1 pairHello ------------------------------------------------------- private onPairHello(body: unknown): void {+ private async onPairHello(body: unknown): Promise<void> {if (this.state !== 'awaiting-hello') {this.violation()return@@ -432,30 +441,21 @@ export class PairSession {return}- // §5: on Chromium the verified `Origin` host proves the extension id, so a- // `claimedExtensionId` that disagrees with it is a rejected pairing. On- // Firefox a `moz-extension://<UUID>` origin cannot be mapped to a Gecko- // id, so there is nothing to compare. Host-header validation is the- // wiring's, since the header never reaches this module.- //- // Branches on the **derived** browser, not the frame's. The check above- // makes them equal, so this is belt and braces — but this is the check- // §5's whole identity proof rests on, and while it keyed off the client's- // own field a Chromium caller could declare `firefox` to skip it entirely- // and then claim any `claimedExtensionId` it liked. Identity resolved to- // `unverified`, which renders the *claimed* id in the dialog, so the- // payoff was showing the user a recognizable id from an extension that- // was not it. Never let this predicate depend on a frame field again.- if (- this.deps.browser === 'chromium' &&- this.deps.verifiedOrigin !==- `${CHROMIUM_ORIGIN_SCHEME}${frame.claimedExtensionId}`- ) {+ // Normalize only the transport-derived browser/Origin. The helper uses+ // the pairHello claim once for Chromium host equality, then discards it;+ // Firefox's claimed Gecko id never enters normalized evidence. This runs+ // before admission so a contradictory identity cannot occupy a §7.3 slot.+ const normalizedIdentity = normalizeExtensionIdentity({+ browser: this.deps.browser,+ verifiedOrigin: this.deps.verifiedOrigin,+ claimedExtensionId: frame.claimedExtensionId,+ })+ if (!normalizedIdentity.ok) {this.violation()return}- // §7.3, before any session state, ticket work, or dialog.+ // §7.3, before any session state, ticket work, or prompt.const admission = this.deps.admit(this.deps.verifiedOrigin)if (!admission.ok) {// No slot was taken, so `releasePendingSlot` must stay a no-op — the@@ -465,7 +465,7 @@ export class PairSession {}this.admitted = true- const resolved = this.resolveIdentity(frame)+ const resolved = this.resolveIdentity(frame, normalizedIdentity.identity)if (resolved === null) {return}@@ -511,20 +511,7 @@ export class PairSession {this.codeNormalized = codethis.codeExpiresAt = this.deps.now() + CODE_LIFETIME_MS- this.dialog = this.deps.queueDialog({- browser: frame.browser,- claimedExtensionId: frame.claimedExtensionId,- identity: resolved.identity,- code: formatPairingCode(code),- pairingNonce: this.deps.pairNonce,- verifiedOrigin: this.deps.verifiedOrigin,- })- this.dialog.dismissed.then(- () => this.onDismissed(),- () => this.onDismissed()- )-- // §6.1: sent when the dialog is queued, and carrying no approval+ // §6.1: sent when the prompt is queued, and carrying no approval// semantics — only key confirmation proves the user approved.const acceptFrame = {type: 'pairAccept',@@ -535,6 +522,58 @@ export class PairSession {this.terminate('pairAcceptInvalid')return}++ let enqueued: PairingPromptEnqueueResult+ try {+ enqueued = this.deps.queueDialog({+ browser: frame.browser,+ claimedExtensionId: frame.claimedExtensionId,+ identity: resolved.identity,+ code: formatPairingCode(code),+ pairingNonce: this.deps.pairNonce,+ verifiedOrigin: this.deps.verifiedOrigin,+ })+ } catch {+ this.fail('pairingFailed')+ return+ }+ if (!enqueued.ok) {+ // The refusal reason belongs to the local prompt adapter. Collapsing all+ // of them avoids turning duplicate/capacity/scheduler state into a wire+ // oracle and, critically, leaves no session waiting for a handle that+ // does not exist.+ this.fail('pairingFailed')+ return+ }++ const prompt = enqueued.handle+ this.prompt = prompt+ prompt.terminal.then(+ (outcome) => this.onPromptTerminal(outcome),+ () => this.onPromptContractFailure()+ )++ let published: Awaited<PairingPromptHandle['published']>+ try {+ published = await prompt.published+ } catch {+ published = 'failed'+ }+ if (this.isClosed()) {+ return+ }+ if (published !== 'delivered') {+ // A code that never reached the authenticated shell UI cannot authorize+ // anything. Fail generically, then settle the prompt as session-aborted+ // during terminate(); callback errors and their details stay local.+ this.fail('pairingFailed')+ return+ }+ if (this.codeExpired()) {+ this.expire()+ return+ }+this.state = 'awaiting-pakeA'this.deps.sendText(acceptFrame)}@@ -543,12 +582,15 @@ export class PairSession {* Applies §9.2's outcome table and §5's tri-state. Returns `null` once the* session has already been ended by an abort.*/- private resolveIdentity(frame: {- browser: Browser- claimedExtensionId: string- nmTicket?: unknown- ticketBindingKey?: string- }): {+ private resolveIdentity(+ frame: {+ browser: Browser+ claimedExtensionId: string+ nmTicket?: unknown+ ticketBindingKey?: string+ },+ normalizedIdentity: NormalizedExtensionIdentity+ ): {identity: IdentityTriStatebindingPub: Uint8Array | nulldigest: Uint8Array | null@@ -583,8 +625,17 @@ export class PairSession {// not change this: it applies equally to the `official` row and the spec// accepts it there. The user-facing boundary is the pairing code, the// approval dialog, and the global prompt caps (§7.3) — never the Origin.+ const resolution = resolveNormalizedExtensionIdentity(+ normalizedIdentity,+ { kind: 'none' },+ this.deps.isOfficialId+ )+ if (!resolution.ok) {+ this.violation()+ return null+ }return {- identity: this.originIdentity(frame),+ identity: resolution.identity,bindingPub: null,digest: null,}@@ -623,33 +674,23 @@ export class PairSession {// downgrade contributes nothing, so identity falls back to what the// verified origin alone establishes — the exact ticketless outcome, so a// stale ticket is never worse for a caller than presenting none.- const identity: IdentityTriState =+ const resolution = resolveNormalizedExtensionIdentity(+ normalizedIdentity,verdict.kind === 'attested'- ? this.deps.isOfficialId(frame.browser, verdict.callerId)- ? 'official'- : 'attested-non-official'- : this.originIdentity(frame)-- return { identity, bindingPub: verdict.deferredProof.bindingPub, digest }- }+ ? { kind: 'verified-nm-ticket', callerId: verdict.callerId }+ : { kind: 'none' },+ this.deps.isOfficialId+ )+ if (!resolution.ok) {+ this.violation()+ return null+ }- /**- * §5's origin-only identity: what the connection proves with no ticket- * contribution. A surviving Chromium session's origin host already agrees- * with `claimedExtensionId` (checked before `resolveIdentity`), so the id- * is proven and the allowlist alone splits `official` from- * `attested-non-official`; a Firefox `moz-extension://<UUID>` origin maps- * to no Gecko id, so it stays `unverified`.- */- private originIdentity(frame: {- browser: Browser- claimedExtensionId: string- }): IdentityTriState {- return frame.browser === 'firefox'- ? 'unverified'- : this.deps.isOfficialId(frame.browser, frame.claimedExtensionId)- ? 'official'- : 'attested-non-official'+ return {+ identity: resolution.identity,+ bindingPub: verdict.deferredProof.bindingPub,+ digest,+ }}private helloBindingKey(frame: {@@ -820,6 +861,19 @@ export class PairSession {this.terminate('confirmBInvalid')return}+ let promptSettlement: PairingPromptSettleResult+ try {+ promptSettlement = this.settlePrompt('paired')+ } catch {+ this.fail('pairingFailed')+ return+ }+ if (!promptSettlement.ok) {+ // Denial, expiry, adapter disposal, or session teardown already won.+ // Its terminal callback owns the corresponding wire outcome.+ return+ }+this.confirmed = truethis.deps.sendText(confirmBFrame)@@ -833,11 +887,10 @@ export class PairSession {this.run = nullthis.w = nullthis.codeNormalized = null- this.closeDialog()- // The dialog is gone, so the §7.3 pending slot is free — and it must be+ // The prompt is terminal, so the §7.3 pending slot is free — and it must be// freed here rather than at `dispose`, or a long-lived paired connection// would hold a slot for its whole lifetime and three of them would block- // every new dialog.+ // every new prompt.this.releasePendingSlot()await this.issueCredential()@@ -924,6 +977,10 @@ export class PairSession {return this.deps.now() >= this.codeExpiresAt}+ private isClosed(): boolean {+ return this.state === 'closed'+ }+/** A run that reached `pakeA` and ended without mutual confirmation (§7.2). */private failRun(): void {this.run = null@@ -943,11 +1000,39 @@ export class PairSession {this.state = 'awaiting-pakeA'}- private onDismissed(): void {- if (this.confirmed || this.state === 'closed') {+ private onPromptTerminal(outcome: PairingPromptTerminalOutcome): void {+ if (+ this.confirmed ||+ this.state === 'closed' ||+ this.state === 'committed'+ ) {+ return+ }++ if (outcome === 'paired') {+ // Only this PairSession owns `paired`; observing it before the session+ // marked mutual confirmation is a broken adapter contract, not approval.+ this.fail('pairingFailed')return}- this.fail('aborted')+ this.fail(+ outcome === 'expired'+ ? 'expired'+ : outcome === 'denied'+ ? 'denied'+ : 'aborted'+ )+ }++ private onPromptContractFailure(): void {+ if (+ this.confirmed ||+ this.state === 'closed' ||+ this.state === 'committed'+ ) {+ return+ }+ this.fail('pairingFailed')}private expire(): void {@@ -990,24 +1075,29 @@ export class PairSession {}this.state = 'closed'this.discardRunState()- this.closeDialog()- this.releasePendingSlot()- this.deps.close(reason)+ try {+ this.settlePrompt('aborted')+ } catch {+ // The socket still closes and the admission slot is still released. A+ // broken shell adapter cannot keep protocol state alive.+ } finally {+ this.releasePendingSlot()+ this.deps.close(reason)+ }}- /**- * Closes the approval dialog at most once. `PairDialogHandle.close` is not- * required to be idempotent, and the close sites overlap: key confirmation- * closes the dialog, and the later `dispose` on socket close would close it- * a second time.- */- private closeDialog(): void {- const dialog = this.dialog- if (dialog === null) {- return+ private settlePrompt(+ outcome: PairingPromptSessionOutcome+ ): PairingPromptSettleResult {+ const prompt = this.prompt+ if (prompt === null) {+ return { ok: false, reason: 'unavailable' }+ }+ const result = prompt.settle(outcome)+ if (result.ok) {+ this.prompt = null}- this.dialog = null- dialog.close()+ return result}/** See `PairSessionDeps.release`: at most once, and only for a slot we took. */diff --git a/src/core/bridge/mbp1/reconnect-session.test.ts b/src/core/bridge/mbp1/reconnect-session.test.tsindex 02651418..29b4d4e1 100644--- a/src/core/bridge/mbp1/reconnect-session.test.ts+++ b/src/core/bridge/mbp1/reconnect-session.test.ts@@ -316,6 +316,7 @@ describe('ReconnectSession (§8)', () => {)expect(h.authenticated).not.toBeNull()expect(h.authenticated?.credential).toBe(promoted)+ expect(h.authenticated?.credential.credentialId).toBe(CREDENTIAL_ID)expect(h.authenticated?.credential.state).toBe('committed')// Traffic keys derived per §8, proven by round-tripping through a@@ -477,6 +478,7 @@ describe('ReconnectSession (§8)', () => {expect(h.promoteOnReconnect).not.toHaveBeenCalled()expect(h.lastSent().type).toBe('reconnectAccept')expect(h.authenticated?.credential).toBe(committed)+ expect(h.authenticated?.credential.credentialId).toBe(CREDENTIAL_ID)})})diff --git a/src/core/bridge/pairing-prompt-controller.test.ts b/src/core/bridge/pairing-prompt-controller.test.tsnew file mode 100644index 00000000..226718ed--- /dev/null+++ b/src/core/bridge/pairing-prompt-controller.test.ts@@ -0,0 +1,713 @@+import { describe, expect, expectTypeOf, it, vi } from 'vitest'+import type { PairDialogRequest } from './mbp1/pair-session'+import {+ PairingPromptController,+ type PairingPromptControllerOptions,+ type PairingPromptEnqueueResult,+ type PairingPromptSnapshot,+ type PairingPromptTerminalEvent,+ PairingPromptTerminalOutcomes,+ type PairingPromptTimeSource,+} from './pairing-prompt-controller'++const REQUEST: PairDialogRequest = {+ browser: 'chromium',+ claimedExtensionId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ identity: 'official',+ code: '1234-5678',+ pairingNonce: 'nonce-1',+ verifiedOrigin: 'chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+}+const DELIVERED = 'delivered' as const++class FakeTimeSource implements PairingPromptTimeSource {+ private current = 1_000+ private nextId = 1+ private readonly timers = new Map<+ number,+ { readonly at: number; readonly callback: () => void }+ >()++ now = (): number => this.current++ schedule = (callback: () => void, delayMs: number): (() => void) => {+ const id = this.nextId+ this.nextId += 1+ this.timers.set(id, { at: this.current + delayMs, callback })+ let cancelled = false+ return () => {+ if (cancelled) return+ cancelled = true+ this.timers.delete(id)+ }+ }++ advance(ms: number): void {+ this.current += ms+ while (true) {+ const due = [...this.timers.entries()]+ .filter(([, timer]) => timer.at <= this.current)+ .sort((left, right) => left[1].at - right[1].at)[0]+ if (due === undefined) return+ this.timers.delete(due[0])+ due[1].callback()+ }+ }++ pendingTimers(): number {+ return this.timers.size+ }+}++function accepted(result: PairingPromptEnqueueResult) {+ if (!result.ok)+ throw new Error(`expected accepted prompt, got ${result.reason}`)+ return result.handle+}++function request(+ overrides: Partial<PairDialogRequest> = {}+): PairDialogRequest {+ return { ...REQUEST, ...overrides }+}++function makeController(overrides: PairingPromptControllerOptions = {}): {+ controller: PairingPromptController+ time: FakeTimeSource+} {+ const time = new FakeTimeSource()+ return {+ controller: new PairingPromptController({+ timeSource: time,+ ...overrides,+ }),+ time,+ }+}++describe('PairingPromptController contract', () => {+ it('freezes the complete typed terminal vocabulary', () => {+ expect(PairingPromptTerminalOutcomes).toEqual({+ Paired: 'paired',+ Denied: 'denied',+ Expired: 'expired',+ Aborted: 'aborted',+ })+ expect(Object.isFrozen(PairingPromptTerminalOutcomes)).toBe(true)+ })++ it('restricts a PairSession handle to paired or aborted outcomes', () => {+ const { controller } = makeController()+ const handle = accepted(controller.enqueue(REQUEST))++ expectTypeOf(handle.settle)+ .parameter(0)+ .toEqualTypeOf<'paired' | 'aborted'>()+ expectTypeOf(controller.deny).parameter(0).toEqualTypeOf<string>()+ expectTypeOf<+ ReturnType<NonNullable<PairingPromptControllerOptions['onEnqueued']>>+ >().toEqualTypeOf<'delivered' | 'failed'>()+ expectTypeOf<+ ReturnType<NonNullable<PairingPromptControllerOptions['onTerminal']>>+ >().toEqualTypeOf<'delivered' | 'failed'>()+ })++ it.each([+ [{ ttlMs: 0 }, 'ttl'],+ [{ ttlMs: 1.5 }, 'ttl'],+ [{ ttlMs: Number.POSITIVE_INFINITY }, 'ttl'],+ [{ maxPending: 0 }, 'cap'],+ [{ maxPending: 1.5 }, 'cap'],+ ] as const)('rejects invalid programmer option %s', (options, _label) => {+ expect(() => new PairingPromptController(options)).toThrow()+ })+})++describe('PairingPromptController.enqueue and snapshot', () => {+ it('publishes one frozen in-memory snapshot with verified identity', async () => {+ const published = vi.fn((_prompt: PairingPromptSnapshot) => DELIVERED)+ const { controller } = makeController({ onEnqueued: published })+ const handle = accepted(+ controller.enqueue(+ request({ verifiedOrigin: `${REQUEST.verifiedOrigin}/` })+ )+ )++ expect(await handle.published).toBe('delivered')+ expect(published).toHaveBeenCalledTimes(1)+ const prompt = published.mock.calls[0]?.[0]+ expect(prompt).toEqual({+ promptId: handle.promptId,+ verifiedIdentity: {+ browser: 'chromium',+ verifiedOrigin: REQUEST.verifiedOrigin,+ originHost: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ },+ claimedExtensionId: REQUEST.claimedExtensionId,+ identity: 'official',+ pairingNonce: 'nonce-1',+ code: '1234-5678',+ createdAt: 1_000,+ expiresAt: 121_000,+ })+ expect(Object.isFrozen(prompt)).toBe(true)+ expect(Object.isFrozen(prompt?.verifiedIdentity)).toBe(true)+ })++ it('returns an immutable snapshot that tracks live prompts only', async () => {+ const { controller } = makeController()+ const first = accepted(controller.enqueue(REQUEST))+ const second = accepted(+ controller.enqueue(+ request({+ pairingNonce: 'nonce-2',+ claimedExtensionId: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',+ verifiedOrigin: 'chrome-extension://bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',+ })+ )+ )++ const snapshot = controller.snapshot()+ expect(Object.isFrozen(snapshot)).toBe(true)+ expect(snapshot.map((item) => item.promptId)).toEqual([+ first.promptId,+ second.promptId,+ ])++ controller.deny(first.promptId)+ expect(controller.snapshot().map((item) => item.promptId)).toEqual([+ second.promptId,+ ])+ })++ it.each([+ ['empty', ''],+ ['wrong scheme', 'https://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'],+ ['missing host', 'chrome-extension:///'],+ ['userinfo', 'chrome-extension://user@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'],+ ['path', 'chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/path'],+ ['query', 'chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa?x=1'],+ ['fragment', 'chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa#x'],+ ['whitespace', ` ${REQUEST.verifiedOrigin}`],+ ['port', `${REQUEST.verifiedOrigin}:1234`],+ ['backslash', `${REQUEST.verifiedOrigin}\\alias`],+ ['percent alias', `${REQUEST.verifiedOrigin}%2falias`],+ ['non-ASCII host', 'chrome-extension://\u00eddentity'],+ ])('rejects an invalid verified Origin (%s)', (_label, verifiedOrigin) => {+ const { controller } = makeController()++ expect(controller.enqueue(request({ verifiedOrigin }))).toEqual({+ ok: false,+ reason: 'invalid-origin',+ })+ expect(controller.snapshot()).toEqual([])+ })++ it('deduplicates by verified browser+Origin, never claimed id', async () => {+ const published = vi.fn(() => DELIVERED)+ const { controller } = makeController({ onEnqueued: published })+ const first = accepted(controller.enqueue(REQUEST))+ await first.published++ const duplicate = controller.enqueue(+ request({+ pairingNonce: 'nonce-attacker',+ claimedExtensionId: 'attacker-self-report',+ })+ )++ expect(duplicate).toEqual({ ok: false, reason: 'duplicate' })+ expect(controller.snapshot()).toHaveLength(1)+ expect(published).toHaveBeenCalledTimes(1)+ })++ it('does not let the same claimed id suppress a different verified Origin', () => {+ const { controller } = makeController()+ accepted(+ controller.enqueue(+ request({+ browser: 'firefox',+ verifiedOrigin:+ 'moz-extension://11111111-1111-1111-1111-111111111111',+ })+ )+ )++ const other = controller.enqueue(+ request({+ browser: 'firefox',+ pairingNonce: 'nonce-2',+ verifiedOrigin: 'moz-extension://22222222-2222-2222-2222-222222222222',+ })+ )++ expect(other.ok).toBe(true)+ expect(controller.snapshot()).toHaveLength(2)+ })++ it('enforces a global cap and frees the slot synchronously on settle', async () => {+ const { controller } = makeController({ maxPending: 1 })+ const first = accepted(controller.enqueue(REQUEST))+ const otherRequest = request({+ pairingNonce: 'nonce-2',+ claimedExtensionId: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',+ verifiedOrigin: 'chrome-extension://bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',+ })++ expect(controller.enqueue(otherRequest)).toEqual({+ ok: false,+ reason: 'capacity',+ })+ const settling = first.settle('paired')+ expect(controller.enqueue(otherRequest).ok).toBe(true)+ expect(settling).toEqual({ ok: true, outcome: 'paired' })+ })++ it.each([+ [+ 'throw',+ {+ now: (): number => 0,+ schedule: () => {+ throw new Error('timer unavailable')+ },+ },+ ],+ [+ 'fire synchronously',+ {+ now: (): number => 0,+ schedule: (callback: () => void) => {+ callback()+ return () => {}+ },+ },+ ],+ ] as const)(+ 'fails closed when the timer scheduler would %s',+ (_label, timeSource) => {+ const controller = new PairingPromptController({ timeSource })++ expect(controller.enqueue(REQUEST)).toEqual({+ ok: false,+ reason: 'scheduling-failed',+ })+ expect(controller.snapshot()).toEqual([])+ }+ )++ it('keeps the PAKE code out of ids, handles, and non-snapshot JSON', async () => {+ const terminalEvents: unknown[] = []+ const { controller } = makeController({+ onTerminal: (event) => {+ terminalEvents.push(event)+ return DELIVERED+ },+ })+ const handle = accepted(controller.enqueue(REQUEST))++ expect(handle.promptId).not.toContain(REQUEST.code)+ expect(handle.promptId).not.toContain(REQUEST.pairingNonce)+ expect(handle.promptId).not.toContain(REQUEST.verifiedOrigin)+ expect(JSON.stringify(handle)).not.toContain(REQUEST.code)+ controller.deny(handle.promptId)+ expect(JSON.stringify(terminalEvents)).not.toContain(REQUEST.code)+ expect(JSON.stringify(controller.callbackFailureSnapshot())).not.toContain(+ REQUEST.code+ )+ })+})++describe('PairingPromptController TTL', () => {+ it('expires exactly at the injected deadline and emits once', async () => {+ const terminal = vi.fn((_event: PairingPromptTerminalEvent) => DELIVERED)+ const { controller, time } = makeController({+ ttlMs: 10_000,+ onTerminal: terminal,+ })+ const handle = accepted(controller.enqueue(REQUEST))+ let outcome: string | undefined+ void handle.terminal.then((value) => {+ outcome = value+ })++ time.advance(9_999)+ await Promise.resolve()+ expect(outcome).toBeUndefined()+ expect(controller.snapshot()).toHaveLength(1)++ time.advance(1)+ expect(await handle.terminal).toBe('expired')+ await Promise.resolve()+ expect(controller.snapshot()).toEqual([])+ expect(terminal).toHaveBeenCalledTimes(1)+ expect(terminal).toHaveBeenCalledWith(+ expect.objectContaining({ outcome: 'expired' })+ )+ })++ it('lazily expires a prompt when the injected scheduler is delayed', async () => {+ let now = 50+ const delayedTime: PairingPromptTimeSource = {+ now: () => now,+ schedule: () => () => {},+ }+ const controller = new PairingPromptController({+ ttlMs: 100,+ timeSource: delayedTime,+ })+ const handle = accepted(controller.enqueue(REQUEST))++ now = 150+ expect(controller.snapshot()).toEqual([])+ expect(await handle.terminal).toBe('expired')+ })++ it('lets expiry win over an explicit decision at the deadline', async () => {+ let now = 0+ const delayedTime: PairingPromptTimeSource = {+ now: () => now,+ schedule: () => () => {},+ }+ const controller = new PairingPromptController({+ ttlMs: 100,+ timeSource: delayedTime,+ })+ const handle = accepted(controller.enqueue(REQUEST))++ now = 100+ expect(controller.deny(handle.promptId)).toEqual({+ ok: false,+ reason: 'unavailable',+ })+ await expect(handle.terminal).resolves.toBe('expired')+ })++ it('cancels the TTL after explicit settle so it cannot emit twice', async () => {+ const terminal = vi.fn(() => DELIVERED)+ const { controller, time } = makeController({+ ttlMs: 100,+ onTerminal: terminal,+ })+ const handle = accepted(controller.enqueue(REQUEST))++ expect(handle.settle('paired')).toEqual({+ ok: true,+ outcome: 'paired',+ })+ expect(time.pendingTimers()).toBe(0)+ time.advance(1_000)+ await Promise.resolve()++ expect(terminal).toHaveBeenCalledTimes(1)+ await expect(handle.terminal).resolves.toBe('paired')+ })+})++describe('PairingPromptController settle', () => {+ it.each(['paired', 'aborted'] as const)(+ 'lets the PairSession handle settle %s exactly once',+ async (outcome) => {+ const { controller } = makeController()+ const handle = accepted(controller.enqueue(REQUEST))++ expect(handle.settle(outcome)).toEqual({ ok: true, outcome })+ await expect(handle.terminal).resolves.toBe(outcome)+ expect(controller.snapshot()).toEqual([])+ }+ )++ it('gives the operator a deny-only terminal transition', async () => {+ const { controller } = makeController()+ const handle = accepted(controller.enqueue(REQUEST))++ expect(controller.deny(handle.promptId)).toEqual({+ ok: true,+ outcome: 'denied',+ })+ await expect(handle.terminal).resolves.toBe('denied')+ })++ it('returns unavailable and invokes no callback on duplicate settle', async () => {+ const terminal = vi.fn(() => DELIVERED)+ const { controller } = makeController({ onTerminal: terminal })+ const handle = accepted(controller.enqueue(REQUEST))++ expect(controller.deny(handle.promptId)).toEqual({+ ok: true,+ outcome: 'denied',+ })+ expect(handle.settle('paired')).toEqual({+ ok: false,+ reason: 'unavailable',+ })++ await Promise.resolve()+ expect(terminal).toHaveBeenCalledTimes(1)+ await expect(handle.terminal).resolves.toBe('denied')+ })++ it('re-admits the verified identity after any terminal outcome', async () => {+ const { controller } = makeController()+ const first = accepted(controller.enqueue(REQUEST))++ controller.deny(first.promptId)+ expect(controller.enqueue(request({ pairingNonce: 'nonce-2' })).ok).toBe(+ true+ )+ })++ it('publishes a frozen code-free terminal event', async () => {+ const terminal = vi.fn((_event: PairingPromptTerminalEvent) => DELIVERED)+ const { controller } = makeController({ onTerminal: terminal })+ const handle = accepted(controller.enqueue(REQUEST))++ controller.deny(handle.promptId)+ await Promise.resolve()+ const event = terminal.mock.calls[0]?.[0]+ expect(event).toEqual({+ promptId: handle.promptId,+ verifiedIdentity: {+ browser: 'chromium',+ verifiedOrigin: REQUEST.verifiedOrigin,+ originHost: REQUEST.claimedExtensionId,+ },+ outcome: 'denied',+ })+ expect(Object.isFrozen(event)).toBe(true)+ expect(event).not.toHaveProperty('code')+ expect(event).not.toHaveProperty('pairingNonce')+ })++ it('removes state before synchronously publishing the terminal callback', async () => {+ let duplicate: ReturnType<PairingPromptController['deny']> | undefined+ let controller!: PairingPromptController+ const terminal = vi.fn((event: { promptId: string }) => {+ duplicate = controller.deny(event.promptId)+ return DELIVERED+ })+ controller = makeController({ onTerminal: terminal }).controller+ const handle = accepted(controller.enqueue(REQUEST))++ const first = handle.settle('paired')+ expect(duplicate).toEqual({+ ok: false,+ reason: 'unavailable',+ })+ await expect(handle.terminal).resolves.toBe('paired')+ expect(terminal).toHaveBeenCalledTimes(1)+ expect(first).toEqual({ ok: true, outcome: 'paired' })+ })+})++describe('PairingPromptController callback failures', () => {+ it.each([+ [+ 'throw',+ () => {+ throw new Error('secret callback detail')+ },+ ],+ ['reject', () => Promise.reject(new Error('secret callback detail'))],+ ] as const)(+ 'observes an enqueue callback %s without dropping the prompt',+ async (_label, onEnqueued) => {+ const observed = vi.fn()+ const { controller } = makeController({+ onEnqueued: onEnqueued as unknown as NonNullable<+ PairingPromptControllerOptions['onEnqueued']+ >,+ onCallbackFailure: observed,+ })+ const handle = accepted(controller.enqueue(REQUEST))++ await expect(handle.published).resolves.toBe('failed')+ expect(controller.snapshot()).toHaveLength(1)+ expect(controller.callbackFailureSnapshot()).toEqual([+ { phase: 'enqueue' },+ ])+ expect(observed).toHaveBeenCalledExactlyOnceWith({ phase: 'enqueue' })+ expect(+ JSON.stringify(controller.callbackFailureSnapshot())+ ).not.toContain('secret callback detail')+ }+ )++ it('fails an invalid never-settling enqueue callback without hanging PairSession', async () => {+ const never = new Promise<void>(() => {})+ const { controller } = makeController({+ onEnqueued: (() => never) as unknown as NonNullable<+ PairingPromptControllerOptions['onEnqueued']+ >,+ })+ const handle = accepted(controller.enqueue(REQUEST))++ await expect(handle.published).resolves.toBe('failed')+ expect(handle.settle('aborted')).toEqual({+ ok: true,+ outcome: 'aborted',+ })+ await expect(controller.dispose()).resolves.toBeUndefined()+ expect(controller.callbackFailureSnapshot()).toEqual([{ phase: 'enqueue' }])+ })++ it.each(['resolve', 'reject'] as const)(+ 'does not revise terminal lifecycle when an invalid thenable %ss late',+ async (completion) => {+ let resolve!: () => void+ let reject!: (reason: Error) => void+ const returned = new Promise<void>((done, fail) => {+ resolve = done+ reject = fail+ })+ const { controller } = makeController({+ onEnqueued: (() => returned) as unknown as NonNullable<+ PairingPromptControllerOptions['onEnqueued']+ >,+ })+ const handle = accepted(controller.enqueue(REQUEST))++ await expect(handle.published).resolves.toBe('failed')+ expect(handle.settle('aborted')).toEqual({+ ok: true,+ outcome: 'aborted',+ })+ if (completion === 'resolve') {+ resolve()+ } else {+ reject(new Error('late adapter contract violation'))+ }+ await Promise.resolve()++ await expect(handle.terminal).resolves.toBe('aborted')+ expect(handle.settle('paired')).toEqual({+ ok: false,+ reason: 'unavailable',+ })+ expect(controller.callbackFailureSnapshot()).toEqual([+ { phase: 'enqueue' },+ ])+ }+ )++ it.each([+ [+ 'throw',+ () => {+ throw new Error('secret callback detail')+ },+ ],+ ['reject', () => Promise.reject(new Error('secret callback detail'))],+ ] as const)(+ 'observes a terminal callback %s and never settles twice',+ async (_label, onTerminal) => {+ const observed = vi.fn()+ const { controller } = makeController({+ onTerminal: onTerminal as unknown as NonNullable<+ PairingPromptControllerOptions['onTerminal']+ >,+ onCallbackFailure: observed,+ })+ const handle = accepted(controller.enqueue(REQUEST))++ expect(controller.deny(handle.promptId)).toEqual({+ ok: true,+ outcome: 'denied',+ })+ expect(handle.settle('paired')).toEqual({+ ok: false,+ reason: 'unavailable',+ })+ await expect(handle.terminal).resolves.toBe('denied')+ await controller.dispose()+ expect(controller.callbackFailureSnapshot()).toEqual([+ { phase: 'terminal', outcome: 'denied' },+ ])+ expect(observed).toHaveBeenCalledTimes(1)+ }+ )++ it('retains failure observability when the failure observer also breaks', async () => {+ const { controller } = makeController({+ onTerminal: () => {+ throw new Error('terminal failure')+ },+ onCallbackFailure: () => {+ throw new Error('observer failure')+ },+ })+ const handle = accepted(controller.enqueue(REQUEST))++ handle.settle('aborted')+ await controller.dispose()+ expect(controller.callbackFailureSnapshot()).toEqual([+ { phase: 'terminal', outcome: 'aborted' },+ ])+ })+})++describe('PairingPromptController.dispose', () => {+ it('commits code publication synchronously before enqueue returns', async () => {+ const published = vi.fn(() => DELIVERED)+ const { controller } = makeController({ onEnqueued: published })+ const handle = accepted(controller.enqueue(REQUEST))++ expect(published).toHaveBeenCalledTimes(1)+ await controller.dispose()++ await expect(handle.published).resolves.toBe('delivered')+ await expect(handle.terminal).resolves.toBe('aborted')+ expect(published).toHaveBeenCalledTimes(1)+ expect(controller.callbackFailureSnapshot()).toEqual([])+ })++ it('aborts every pending prompt, cancels timers, and is idempotent', async () => {+ const terminal = vi.fn(() => DELIVERED)+ const { controller, time } = makeController({ onTerminal: terminal })+ const first = accepted(controller.enqueue(REQUEST))+ const second = accepted(+ controller.enqueue(+ request({+ pairingNonce: 'nonce-2',+ claimedExtensionId: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',+ verifiedOrigin: 'chrome-extension://bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',+ })+ )+ )++ const disposing = controller.dispose()+ expect(controller.dispose()).toBe(disposing)+ expect(controller.snapshot()).toEqual([])+ expect(time.pendingTimers()).toBe(0)+ await disposing++ await expect(first.terminal).resolves.toBe('aborted')+ await expect(second.terminal).resolves.toBe('aborted')+ expect(terminal).toHaveBeenCalledTimes(2)+ })++ it('rejects future enqueue after disposal', async () => {+ const { controller } = makeController()+ await controller.dispose()++ expect(controller.enqueue(REQUEST)).toEqual({+ ok: false,+ reason: 'disposed',+ })+ })++ it('fails an invalid never-settling terminal callback without blocking disposal', async () => {+ const never = new Promise<void>(() => {})+ const { controller } = makeController({+ onTerminal: (() => never) as unknown as NonNullable<+ PairingPromptControllerOptions['onTerminal']+ >,+ })+ accepted(controller.enqueue(REQUEST))++ await expect(controller.dispose()).resolves.toBeUndefined()+ expect(controller.callbackFailureSnapshot()).toEqual([+ { phase: 'terminal', outcome: 'aborted' },+ ])+ })+})diff --git a/src/core/bridge/pairing-prompt-controller.ts b/src/core/bridge/pairing-prompt-controller.tsnew file mode 100644index 00000000..af811dc2--- /dev/null+++ b/src/core/bridge/pairing-prompt-controller.ts@@ -0,0 +1,507 @@+import { randomUUID } from 'node:crypto'+import type { PairDialogRequest } from './mbp1/pair-session'++export const PairingPromptTerminalOutcomes = Object.freeze({+ Paired: 'paired',+ Denied: 'denied',+ Expired: 'expired',+ Aborted: 'aborted',+} as const)++export type PairingPromptTerminalOutcome =+ (typeof PairingPromptTerminalOutcomes)[keyof typeof PairingPromptTerminalOutcomes]++export type PairingPromptSessionOutcome = Extract<+ PairingPromptTerminalOutcome,+ 'paired' | 'aborted'+>++export type PairingPromptCallbackStatus =+ | 'delivered'+ | 'failed'+ | 'not-configured'++/**+ * Synchronous receipt returned only after a trusted in-repo shell adapter has+ * committed an event to its authenticated operator channel. Promise/thenable+ * publishers are outside this contract and are classified as `failed`+ * immediately; the controller never awaits them. Once arbitrary JavaScript+ * has received the snapshot, its own out-of-contract side effects cannot be+ * revoked by the controller.+ */+export type PairingPromptCallbackReceipt = Exclude<+ PairingPromptCallbackStatus,+ 'not-configured'+>++export interface VerifiedPairingPromptIdentity {+ readonly browser: PairDialogRequest['browser']+ readonly verifiedOrigin: string+ readonly originHost: string+}++/**+ * In-memory operator projection for one pending prompt.+ *+ * `code` is the MBP1 PAKE password. It may be delivered only through an+ * authenticated shell adapter and must never be logged, persisted, placed in+ * a URL, or copied into a terminal event.+ */+export interface PairingPromptSnapshot {+ readonly promptId: string+ readonly verifiedIdentity: VerifiedPairingPromptIdentity+ readonly claimedExtensionId: string+ readonly identity: PairDialogRequest['identity']+ readonly pairingNonce: string+ readonly code: string+ readonly createdAt: number+ readonly expiresAt: number+}++/** Tokenless terminal event. Deliberately excludes the pairing code. */+export interface PairingPromptTerminalEvent {+ readonly promptId: string+ readonly verifiedIdentity: VerifiedPairingPromptIdentity+ readonly outcome: PairingPromptTerminalOutcome+}++export type PairingPromptCallbackFailure =+ | { readonly phase: 'enqueue' }+ | {+ readonly phase: 'terminal'+ readonly outcome: PairingPromptTerminalOutcome+ }++export interface PairingPromptTimeSource {+ now(): number+ /** Schedule once and return an idempotent cancellation callback. */+ schedule(callback: () => void, delayMs: number): () => void+}++export interface PairingPromptControllerOptions {+ /** Pairing-code/prompt lifetime. Default 120 seconds. */+ ttlMs?: number+ /** Global in-memory pending cap. Default 3. */+ maxPending?: number+ timeSource?: PairingPromptTimeSource+ /**+ * Code-bearing callback for an authenticated shell adapter only. It must+ * synchronously commit delivery and return its receipt; Promise returns are+ * a contract failure and are never awaited.+ */+ onEnqueued?: (prompt: PairingPromptSnapshot) => PairingPromptCallbackReceipt+ /**+ * Code-free callback for operator/UI lifecycle bookkeeping. It follows the+ * same synchronous receipt contract so controller disposal is bounded.+ */+ onTerminal?: (+ event: PairingPromptTerminalEvent+ ) => PairingPromptCallbackReceipt+ /** Receives a fixed, secret-free failure marker. */+ onCallbackFailure?: (+ failure: PairingPromptCallbackFailure+ ) => void | Promise<void>+}++export interface PairingPromptHandle {+ readonly promptId: string+ /** Whether the shell adapter accepted the code-bearing enqueue callback. */+ readonly published: Promise<PairingPromptCallbackStatus>+ /** Resolves exactly once and never rejects. */+ readonly terminal: Promise<PairingPromptTerminalOutcome>+ /** PairSession-owned outcomes only; operator denial uses controller.deny. */+ settle(outcome: PairingPromptSessionOutcome): PairingPromptSettleResult+}++export type PairingPromptEnqueueResult =+ | { readonly ok: true; readonly handle: PairingPromptHandle }+ | {+ readonly ok: false+ readonly reason:+ | 'duplicate'+ | 'capacity'+ | 'disposed'+ | 'invalid-origin'+ | 'scheduling-failed'+ }++export type PairingPromptSettleResult =+ | {+ readonly ok: true+ readonly outcome: PairingPromptTerminalOutcome+ }+ | { readonly ok: false; readonly reason: 'unavailable' }++interface PendingPrompt {+ readonly snapshot: PairingPromptSnapshot+ readonly identityKey: string+ readonly terminal: Promise<PairingPromptTerminalOutcome>+ readonly resolveTerminal: (outcome: PairingPromptTerminalOutcome) => void+ cancelTimer: () => void+ published: Promise<PairingPromptCallbackStatus>+}++const DEFAULT_TTL_MS = 120_000+const DEFAULT_MAX_PENDING = 3+const MAX_RETAINED_CALLBACK_FAILURES = 100++const DEFAULT_TIME_SOURCE: PairingPromptTimeSource = Object.freeze({+ now: () => Date.now(),+ schedule: (callback: () => void, delayMs: number) => {+ const timer = setTimeout(callback, delayMs)+ timer.unref?.()+ let cancelled = false+ return () => {+ if (cancelled) return+ cancelled = true+ clearTimeout(timer)+ }+ },+})++function frozenUnavailable(): PairingPromptSettleResult {+ return Object.freeze({ ok: false, reason: 'unavailable' })+}++function frozenEnqueueFailure(+ reason: Extract<PairingPromptEnqueueResult, { ok: false }>['reason']+): PairingPromptEnqueueResult {+ return Object.freeze({ ok: false, reason })+}++function hasUnsafeOriginCharacter(value: string): boolean {+ if (/\s/u.test(value)) return true+ for (let index = 0; index < value.length; index += 1) {+ const code = value.charCodeAt(index)+ if (code <= 0x1f || code >= 0x7f) return true+ }+ return false+}++function parseVerifiedIdentity(+ request: PairDialogRequest+): VerifiedPairingPromptIdentity | null {+ if (+ request.verifiedOrigin.length === 0 ||+ hasUnsafeOriginCharacter(request.verifiedOrigin) ||+ request.verifiedOrigin.includes('\\') ||+ request.verifiedOrigin.includes('%')+ ) {+ return null+ }++ let parsed: URL+ try {+ parsed = new URL(request.verifiedOrigin)+ } catch {+ return null+ }++ const expectedProtocol =+ request.browser === 'chromium' ? 'chrome-extension:' : 'moz-extension:'+ if (+ parsed.protocol !== expectedProtocol ||+ parsed.host === '' ||+ parsed.port !== '' ||+ parsed.username !== '' ||+ parsed.password !== '' ||+ parsed.search !== '' ||+ parsed.hash !== '' ||+ (parsed.pathname !== '' && parsed.pathname !== '/')+ ) {+ return null+ }++ return Object.freeze({+ browser: request.browser,+ verifiedOrigin: `${parsed.protocol}//${parsed.host}`,+ originHost: parsed.host,+ })+}++function identityKey(identity: VerifiedPairingPromptIdentity): string {+ return JSON.stringify([identity.browser, identity.verifiedOrigin])+}++export class PairingPromptController {+ private readonly ttlMs: number+ private readonly maxPending: number+ private readonly timeSource: PairingPromptTimeSource+ private readonly onEnqueued: PairingPromptControllerOptions['onEnqueued']+ private readonly onTerminal: PairingPromptControllerOptions['onTerminal']+ private readonly onCallbackFailure: PairingPromptControllerOptions['onCallbackFailure']+ private readonly pending = new Map<string, PendingPrompt>()+ private readonly openIdentities = new Set<string>()+ private readonly callbackFailures: PairingPromptCallbackFailure[] = []+ private readonly promptNamespace = randomUUID()+ private nextPromptSequence = 0+ private disposed = false+ private disposePromise: Promise<void> | null = null++ constructor(options: PairingPromptControllerOptions = {}) {+ this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS+ this.maxPending = options.maxPending ?? DEFAULT_MAX_PENDING+ this.timeSource = options.timeSource ?? DEFAULT_TIME_SOURCE+ this.onEnqueued = options.onEnqueued+ this.onTerminal = options.onTerminal+ this.onCallbackFailure = options.onCallbackFailure++ if (!Number.isSafeInteger(this.ttlMs) || this.ttlMs <= 0) {+ throw new Error('pairing prompt ttlMs must be a positive safe integer')+ }+ if (!Number.isSafeInteger(this.maxPending) || this.maxPending <= 0) {+ throw new Error(+ 'pairing prompt maxPending must be a positive safe integer'+ )+ }+ }++ enqueue(request: PairDialogRequest): PairingPromptEnqueueResult {+ if (this.disposed) return frozenEnqueueFailure('disposed')++ const now = this.readNow()+ this.expireDueEntries(now)++ const verifiedIdentity = parseVerifiedIdentity(request)+ if (verifiedIdentity === null) {+ return frozenEnqueueFailure('invalid-origin')+ }++ const verifiedIdentityKey = identityKey(verifiedIdentity)+ if (this.openIdentities.has(verifiedIdentityKey)) {+ return frozenEnqueueFailure('duplicate')+ }+ if (this.pending.size >= this.maxPending) {+ return frozenEnqueueFailure('capacity')+ }++ const promptId = `${this.promptNamespace}:${this.nextPromptSequence + 1}`+ this.nextPromptSequence += 1+ const snapshot: PairingPromptSnapshot = Object.freeze({+ promptId,+ verifiedIdentity,+ claimedExtensionId: request.claimedExtensionId,+ identity: request.identity,+ pairingNonce: request.pairingNonce,+ code: request.code,+ createdAt: now,+ expiresAt: now + this.ttlMs,+ })++ let resolveTerminal!: (outcome: PairingPromptTerminalOutcome) => void+ const terminal = new Promise<PairingPromptTerminalOutcome>((resolve) => {+ resolveTerminal = resolve+ })+ const entry: PendingPrompt = {+ snapshot,+ identityKey: verifiedIdentityKey,+ terminal,+ resolveTerminal,+ cancelTimer: () => {},+ published: Promise.resolve('not-configured'),+ }+ this.pending.set(promptId, entry)+ this.openIdentities.add(verifiedIdentityKey)++ let armed = false+ let firedSynchronously = false+ try {+ const cancelTimer = this.timeSource.schedule(() => {+ if (!armed) {+ firedSynchronously = true+ return+ }+ void this.settleInternal(+ promptId,+ PairingPromptTerminalOutcomes.Expired+ )+ }, this.ttlMs)+ if (typeof cancelTimer !== 'function' || firedSynchronously) {+ if (typeof cancelTimer === 'function') cancelTimer()+ this.pending.delete(promptId)+ this.openIdentities.delete(verifiedIdentityKey)+ entry.resolveTerminal(PairingPromptTerminalOutcomes.Aborted)+ return frozenEnqueueFailure('scheduling-failed')+ }+ entry.cancelTimer = cancelTimer+ armed = true+ } catch {+ this.pending.delete(promptId)+ this.openIdentities.delete(verifiedIdentityKey)+ entry.resolveTerminal(PairingPromptTerminalOutcomes.Aborted)+ return frozenEnqueueFailure('scheduling-failed')+ }++ // Publication is a synchronous trusted-adapter commit. The Promise-shaped+ // handle wraps the already-computed receipt, keeping PairSession's+ // contract uniform without ever waiting on an adapter-returned thenable.+ entry.published = Promise.resolve(this.publishIfPending(promptId, entry))+ const handle: PairingPromptHandle = Object.freeze({+ promptId,+ published: entry.published,+ terminal,+ settle: (outcome: PairingPromptSessionOutcome) =>+ this.settleFromSession(promptId, outcome),+ })+ return Object.freeze({ ok: true, handle })+ }++ /**+ * Deny one live prompt from the operator surface. A prompt that is missing,+ * already terminal, or due for expiry returns `unavailable`: an operator+ * action must never report success unless it actually won the terminal+ * transition.+ */+ deny(promptId: string): PairingPromptSettleResult {+ const entry = this.pending.get(promptId)+ if (entry === undefined) return frozenUnavailable()++ if (this.readNow() >= entry.snapshot.expiresAt) {+ this.settleInternal(promptId, PairingPromptTerminalOutcomes.Expired)+ return frozenUnavailable()+ }+ return this.settleInternal(promptId, PairingPromptTerminalOutcomes.Denied)+ }++ snapshot(): readonly PairingPromptSnapshot[] {+ if (!this.disposed) this.expireDueEntries(this.readNow())+ return Object.freeze(+ [...this.pending.values()].map((entry) => entry.snapshot)+ )+ }++ callbackFailureSnapshot(): readonly PairingPromptCallbackFailure[] {+ return Object.freeze([...this.callbackFailures])+ }++ /**+ * Abort every live prompt and prevent future enqueue. State transitions and+ * terminal publication are synchronous, so the returned promise is bounded+ * and exists only to keep shell shutdown composition uniform.+ */+ dispose(): Promise<void> {+ if (this.disposePromise !== null) return this.disposePromise+ this.disposed = true+ for (const promptId of [...this.pending.keys()]) {+ this.settleInternal(promptId, PairingPromptTerminalOutcomes.Aborted)+ }+ this.openIdentities.clear()+ this.disposePromise = Promise.resolve()+ return this.disposePromise+ }++ private readNow(): number {+ const now = this.timeSource.now()+ if (!Number.isSafeInteger(now)) {+ throw new Error(+ 'pairing prompt time source returned a non-safe-integer value'+ )+ }+ return now+ }++ private expireDueEntries(now: number): void {+ for (const [promptId, entry] of [...this.pending]) {+ if (now < entry.snapshot.expiresAt) continue+ this.settleInternal(promptId, PairingPromptTerminalOutcomes.Expired)+ }+ }++ private settleFromSession(+ promptId: string,+ outcome: PairingPromptSessionOutcome+ ): PairingPromptSettleResult {+ const entry = this.pending.get(promptId)+ if (entry === undefined) return frozenUnavailable()+ if (this.readNow() >= entry.snapshot.expiresAt) {+ this.settleInternal(promptId, PairingPromptTerminalOutcomes.Expired)+ return frozenUnavailable()+ }+ return this.settleInternal(promptId, outcome)+ }++ /** Removes state before invoking callbacks, making concurrent settle safe. */+ private settleInternal(+ promptId: string,+ outcome: PairingPromptTerminalOutcome+ ): PairingPromptSettleResult {+ const entry = this.pending.get(promptId)+ if (entry === undefined) return frozenUnavailable()++ this.pending.delete(promptId)+ this.openIdentities.delete(entry.identityKey)+ try {+ entry.cancelTimer()+ } catch {+ // State is already removed. A broken injected cancellation callback+ // cannot be allowed to strand the terminal promise or duplicate settle.+ }+ entry.resolveTerminal(outcome)++ const event: PairingPromptTerminalEvent = Object.freeze({+ promptId,+ verifiedIdentity: entry.snapshot.verifiedIdentity,+ outcome,+ })+ const onTerminal = this.onTerminal+ this.invokeCallback(+ { phase: 'terminal', outcome },+ onTerminal === undefined ? undefined : () => onTerminal(event)+ )+ return Object.freeze({ ok: true, outcome })+ }++ private publishIfPending(+ promptId: string,+ entry: PendingPrompt+ ): PairingPromptCallbackStatus {+ const onEnqueued = this.onEnqueued+ if (onEnqueued === undefined) return 'not-configured'++ if (this.pending.get(promptId) !== entry) return 'failed'+ return this.invokeCallback({ phase: 'enqueue' }, () =>+ onEnqueued(entry.snapshot)+ )+ }++ private invokeCallback(+ failure: PairingPromptCallbackFailure,+ invoke: (() => PairingPromptCallbackReceipt) | undefined+ ): PairingPromptCallbackStatus {+ if (invoke === undefined) return 'not-configured'++ try {+ const receipt: unknown = invoke()+ if (receipt === 'delivered') return receipt++ // Includes an explicit `failed`, an accidental `undefined`, and a+ // Promise returned through an untyped JavaScript boundary. Never await+ // an invalid thenable; merely suppress a later rejection so it cannot+ // become a process-level unhandled rejection.+ if (receipt !== 'failed') {+ void Promise.resolve(receipt).catch(() => {})+ }+ this.recordCallbackFailure(failure)+ return 'failed'+ } catch {+ this.recordCallbackFailure(failure)+ return 'failed'+ }+ }++ private recordCallbackFailure(failure: PairingPromptCallbackFailure): void {+ const frozenFailure = Object.freeze({ ...failure })+ this.callbackFailures.push(frozenFailure)+ if (this.callbackFailures.length > MAX_RETAINED_CALLBACK_FAILURES) {+ this.callbackFailures.shift()+ }++ try {+ const observed = this.onCallbackFailure?.(frozenFailure)+ void Promise.resolve(observed).catch(() => {})+ } catch {+ // The durable in-memory marker above remains observable even if the+ // optional observer is itself broken. Never recurse or expose secrets.+ }+ }+}diff --git a/src/core/bridge/to-paired-client-info.test.ts b/src/core/bridge/to-paired-client-info.test.tsindex 538924c8..1ddf1140 100644--- a/src/core/bridge/to-paired-client-info.test.ts+++ b/src/core/bridge/to-paired-client-info.test.ts@@ -1,4 +1,5 @@import { describe, expect, it } from 'vitest'+import type { ExtensionPairingProjection } from './extension-pairing-projection'import type { PairedClient } from './pairing-service'import { toPairedClientInfo } from './to-paired-client-info'@@ -23,14 +24,29 @@ describe('toPairedClientInfo', () => {lastActiveAt: null,}+ const projectedExt: ExtensionPairingProjection = {+ identity: {+ kind: 'extension',+ browser: 'firefox',+ extensionId: 'moz-extension-uuid',+ },+ identityTrust: 'unverified',+ authorizationEpoch: '11111111-1111-4111-8111-111111111111',+ status: 'ready',+ pairedAt: 3000,+ lastActiveAt: 4000,+ }+it('maps an extension identity to id + browser and keeps display fields', () => {- expect(toPairedClientInfo(pairedExt)).toEqual({+ expect(toPairedClientInfo(projectedExt)).toEqual({kind: 'extension',- id: 'ext-abc',- browser: 'chromium',- name: 'Motrix Bridge',- pairedAt: 1000,- lastActiveAt: 2000,+ id: 'moz-extension-uuid',+ browser: 'firefox',+ identityTrust: 'unverified',+ status: 'ready',+ name: '',+ pairedAt: 3000,+ lastActiveAt: 4000,})})@@ -44,11 +60,31 @@ describe('toPairedClientInfo', () => {})})+ it('maps an extension projection without inventing a token or display name', () => {+ expect(toPairedClientInfo(projectedExt)).toEqual({+ kind: 'extension',+ id: 'moz-extension-uuid',+ browser: 'firefox',+ identityTrust: 'unverified',+ status: 'ready',+ name: '',+ pairedAt: 3000,+ lastActiveAt: 4000,+ })+ })+it('never includes the token', () => {- const info = toPairedClientInfo(pairedExt) as unknown as Record<+ const info = toPairedClientInfo(projectedExt) as unknown as Record<string,unknown>expect(info.token).toBeUndefined()+ expect(info.authorizationEpoch).toBeUndefined()+ })++ it('rejects a token-backed extension instead of projecting it as MBP1 state', () => {+ expect(() => toPairedClientInfo(pairedExt)).toThrow(+ 'token-backed extension projection rejected'+ )})})diff --git a/src/core/bridge/to-paired-client-info.ts b/src/core/bridge/to-paired-client-info.tsindex a2ae903d..05b8c6eb 100644--- a/src/core/bridge/to-paired-client-info.ts+++ b/src/core/bridge/to-paired-client-info.ts@@ -1,4 +1,5 @@import type { PairedClientInfo } from '@shared/protocol/bridge'+import type { ExtensionPairingProjection } from './extension-pairing-projection'import type { PairedClient } from './pairing-service'/**@@ -7,17 +8,24 @@ import type { PairedClient } from './pairing-service'* identity `kind` + its id (extension id or cli id) and, for an extension, the* `browser`.*/-export function toPairedClientInfo(p: PairedClient): PairedClientInfo {+export function toPairedClientInfo(+ p: PairedClient | ExtensionPairingProjection+): PairedClientInfo {const base = {- name: p.name,+ name: 'name' in p ? p.name : '',pairedAt: p.pairedAt,lastActiveAt: p.lastActiveAt,}if (p.identity.kind === 'extension') {+ if (!('identityTrust' in p) || !('status' in p)) {+ throw new Error('token-backed extension projection rejected')+ }return {kind: 'extension',id: p.identity.extensionId,browser: p.identity.browser,+ identityTrust: p.identityTrust,+ status: p.status,...base,}}diff --git a/src/core/bridge/web-socket-bridge-server.ts b/src/core/bridge/web-socket-bridge-server.tsindex 4603dca3..f263acab 100644--- a/src/core/bridge/web-socket-bridge-server.ts+++ b/src/core/bridge/web-socket-bridge-server.ts@@ -46,11 +46,7 @@ import {} from './mbp1/envelope-message-stream'import { PairFloodControl } from './mbp1/flood-control'import { NonceService } from './mbp1/nonce-service'-import {- type PairDialogHandle,- type PairDialogRequest,- PairSession,-} from './mbp1/pair-session'+import { type PairDialogRequest, PairSession } from './mbp1/pair-session'import { PreAuthTable } from './mbp1/pre-auth-table'import { ReconnectRateLimit } from './mbp1/reconnect-rate-limit'import { ReconnectSession } from './mbp1/reconnect-session'@@ -60,6 +56,7 @@ import {contextFromConnection,type MdxpSessionContext,} from './mdxp-session-context'+import type { PairingPromptEnqueueResult } from './pairing-prompt-controller'import type { PairingService } from './pairing-service'import type { TrustedExtensionRegistry } from './trusted-extension-registry'import type { WebSocketLike } from './web-socket-message-stream'@@ -134,12 +131,33 @@ export interface BridgeServerOptions {*/isOfficialId?: (browser: Browser, id: string) => boolean/**- * Shows the §7.1 approval dialog. Error-free by construction: §7.3 admission- * (dedup, the global pending cap, and the failure lockout) is core's, runs- * *before* ticket validation, and is applied by this server through- * `PairFloodControl` — the shell only renders.+ * Queues the §7.1 approval prompt. The prompt controller reports a typed+ * refusal instead of manufacturing a handle when its own lifecycle cannot+ * safely publish one.+ */+ queueMbp1Dialog?: (args: PairDialogRequest) => PairingPromptEnqueueResult+ /**+ * Composition-root kill switch for the four Extension MBP1 routes. The+ * credential/projection management runtime may be prepared while this is+ * false, but `/discovery`, `/nonce`, `/pair`, and `/v1` remain indistinguishable+ * from unknown routes. Omission preserves the Desktop/test default.*/- queueMbp1Dialog?: (args: PairDialogRequest) => PairDialogHandle+ extensionMbp1RoutesEnabled?: boolean+ /** Optional shell-owned raw request boundary for a prefixed/public MBP1+ * surface. It must make Host, path, method, query, proxy and admission+ * decisions without trusting framework-normalized URL fields. */+ extensionMbp1RoutePolicy?: (+ request: ExtensionMbp1RouteRequest+ ) => ExtensionMbp1RouteDecision+ /**+ * Synchronous shell-owned admission gate for an Origin-derived extension+ * identity. A `false` verdict (or a thrown error) refuses both MBP1 upgrade+ * routes before a nonce, rate-limit allowance, pre-authentication slot, or+ * session is consumed. Omission preserves the existing desktop behavior.+ */+ canAdmitExtensionIdentity?: (+ identity: ClientIdentity & { kind: 'extension' }+ ) => boolean/*** Fired once an extension session authenticates over MBP1 — first pair or* reconnect alike. It is the only remaining signal that an extension became@@ -147,10 +165,33 @@ export interface BridgeServerOptions {* paired-client list, revoke command, and revoke-kick all hang off it.*/onExtensionAuthenticated?: (- identity: ClientIdentity & { kind: 'extension' }+ identity: ClientIdentity & { kind: 'extension' },+ /** The exact credential that authenticated this transport. */+ credentialId: string) => void}+export interface ExtensionMbp1RouteRequest {+ readonly rawTarget: string+ readonly method: string+ readonly transport: 'http' | 'websocket'+ readonly rawHeaders: readonly string[]+ readonly directPeerAddress: string | undefined+}++export type ExtensionMbp1RouteName = 'discovery' | 'nonce' | 'pair' | 'v1'++export type ExtensionMbp1RouteDecision =+ | { readonly kind: 'not-extension' }+ | { readonly kind: 'reject'; readonly status: 403 | 404 | 405 | 429 }+ | {+ readonly kind: 'route'+ readonly route: ExtensionMbp1RouteName+ readonly pairNonce?: string+ /** Idempotent capacity lease release, owned by the handshake lifetime. */+ readonly releaseAdmission?: () => void+ }+/*** The MBP1 options resolved as a unit. They arrive together or not at all: a* `/pair` session needs every one of them, so admitting a connection against a@@ -163,7 +204,7 @@ interface Mbp1Wiring {appVersion: stringcredentials: Mbp1CredentialStoreisOfficialId: (browser: Browser, id: string) => boolean- queueMbp1Dialog: (args: PairDialogRequest) => PairDialogHandle+ queueMbp1Dialog: (args: PairDialogRequest) => PairingPromptEnqueueResult}function resolveMbp1Wiring(opts: BridgeServerOptions): Mbp1Wiring | null {@@ -209,6 +250,34 @@ export interface BridgeSession {envelope: EnvelopeStream}+const EXTENSION_REVOCATION_LEASE_BRAND: unique symbol = Symbol(+ 'motrix.bridge.extension-revocation-lease'+)++/**+ * Process-local proof that this server has already entered the synchronous+ * revoke critical section for one verified Extension identity. The WeakMap+ * claim, not the structural fields, is authoritative at runtime.+ */+export interface ExtensionRevocationLease {+ readonly [EXTENSION_REVOCATION_LEASE_BRAND]: true+ readonly identity: ClientIdentity & { kind: 'extension' }+}++interface ExtensionRevocationClaim {+ readonly server: WebSocketBridgeServer+ readonly sessionKey: string+ readonly identity: ClientIdentity & { kind: 'extension' }+ phase: 'gated' | 'credentials-deleted' | 'completed'+ deletePromise: Promise<number> | null+ revokedCount: number | null+}++const extensionRevocationClaims = new WeakMap<+ object,+ ExtensionRevocationClaim+>()+/*** Optional per-method handlers registered via `setHandlers()`. `motrix/initialize`* and `system/ping` are wired by the server itself; these are the shell-supplied@@ -395,6 +464,35 @@ function parseExtensionOrigin(origin: string): ExtensionPeer | null {return { browser, extensionId: host, origin }}+function normalizeRevocationIdentity(+ identity: ClientIdentity & { kind: 'extension' }+): ClientIdentity & { kind: 'extension' } {+ if (+ identity?.kind !== 'extension' ||+ (identity.browser !== 'chromium' && identity.browser !== 'firefox') ||+ typeof identity.extensionId !== 'string' ||+ identity.extensionId.length === 0 ||+ identity.extensionId.length > 256+ ) {+ throw new Error('extension revocation identity rejected')+ }+ const scheme =+ identity.browser === 'chromium' ? 'chrome-extension' : 'moz-extension'+ const parsed = parseExtensionOrigin(`${scheme}://${identity.extensionId}`)+ if (+ parsed === null ||+ parsed.browser !== identity.browser ||+ parsed.extensionId !== identity.extensionId+ ) {+ throw new Error('extension revocation identity rejected')+ }+ return Object.freeze({+ kind: 'extension' as const,+ browser: identity.browser,+ extensionId: identity.extensionId,+ })+}+/** A `/pair` connection held in the pre-authentication table (§4, §7.3). */interface PairPreAuthEntry {readonly ws: WebSocket@@ -409,6 +507,7 @@ interface PairPreAuthEntry {/** §7.3's counter must move exactly once per session, whichever terminal* path (success, deadline, close) gets there first. */outcomeRecorded: boolean+ readonly releaseAdmission: () => void}/** A `/v1` connection held in the pre-authentication table (§4, §8). */@@ -417,6 +516,7 @@ interface ReconnectPreAuthEntry {/** Verified Origin-derived identity used for revoke-critical cancellation. */readonly sessionKey: stringsession: ReconnectSession | null+ readonly releaseAdmission: () => void}export class WebSocketBridgeServer {@@ -445,7 +545,10 @@ export class WebSocketBridgeServer {/** Session keys in the durable-revocation critical section. Matching* pre-auth sessions are cancelled, new upgrades are refused, and any MBP1* flow that still finishes concurrently is refused again at adoption. */- private readonly revokingExtensionKeys = new Map<string, number>()+ private readonly revokingExtensionKeys = new Map<+ string,+ ExtensionRevocationLease+ >()// Open SSE connections (GET /mdxp/events) → their heartbeat timer + the// authenticated caller identity. The CLI `watch` firehose; a global// (non-session) push of $/task/* + $/stats. The identity is retained so a@@ -477,6 +580,7 @@ export class WebSocketBridgeServer {try {entry.session?.dispose('timeout')} finally {+ entry.releaseAdmission()// `dispose` deliberately does NOT close the socket — both session// modules read it as "the peer is already gone, or the wiring is// closing it" — so the wiring must close, or a peer that upgrades and@@ -518,15 +622,22 @@ export class WebSocketBridgeServer {})this.http.on('upgrade', (req, socket, head) => {- // The base is a placeholder for relative-URL parsing only. The Host- // header is validated separately below and is never derived from here.- const url = new URL(req.url ?? '/', 'http://localhost')+ const route = this.resolveExtensionMbp1Route(req, 'websocket')+ if (route.kind === 'not-extension') return this.reject(socket, 404)+ if (route.kind === 'reject') {+ return this.reject(socket, route.status === 405 ? 404 : route.status)+ }+ if (route.route !== 'pair' && route.route !== 'v1') {+ route.releaseAdmission?.()+ return this.reject(socket, 404)+ }const protoHeader = req.headers['sec-websocket-protocol'] ?? ''// §5: the verified origin, and every identity fact taken from it, comes// from this header alone.const peer = parseExtensionOrigin(req.headers.origin ?? '')if (peer === null) {+ route.releaseAdmission?.()return this.reject(socket, 401)}if (@@ -535,48 +646,76 @@ export class WebSocketBridgeServer {.map((s) => s.trim()).includes('motrix-bridge.v1')) {+ route.releaseAdmission?.()return this.reject(socket, 401)}- // §4.3/§6.1: before the route decides anything, before a nonce is- // consumed, and before any session object exists.- if (!this.hostHeaderAllowed(req)) {- return this.reject(socket, 403)- }const mbp1 = this.mbp1- if (mbp1 === null) {+ if (mbp1 === null || this.opts.extensionMbp1RoutesEnabled === false) {+ route.releaseAdmission?.()// Both routes speak MBP1 and nothing else (§4). A shell that has not// wired it has no extension WebSocket surface at all — the same 404 an// unknown path gets, so the response says nothing about which it was.return this.reject(socket, 404)}- if (url.pathname === '/pair') {- return this.handleMbp1PairUpgrade(req, socket, head, url, peer, mbp1)+ const identity: ClientIdentity & { kind: 'extension' } = {+ kind: 'extension',+ browser: peer.browser,+ extensionId: peer.extensionId,}- if (url.pathname === '/v1') {- return this.handleMbp1ReconnectUpgrade(req, socket, head, peer, mbp1)++ if (route.route === 'pair') {+ if (!this.canAdmitExtensionIdentity(identity)) {+ route.releaseAdmission?.()+ return this.reject(socket, 401)+ }+ return this.handleMbp1PairUpgrade(+ req,+ socket,+ head,+ route.pairNonce ?? '',+ peer,+ identity,+ mbp1,+ route.releaseAdmission ?? (() => undefined)+ )}+ if (route.route === 'v1') {+ if (!this.canAdmitExtensionIdentity(identity)) {+ route.releaseAdmission?.()+ return this.reject(socket, 401)+ }+ return this.handleMbp1ReconnectUpgrade(+ req,+ socket,+ head,+ peer,+ identity,+ mbp1,+ route.releaseAdmission ?? (() => undefined)+ )+ }+ route.releaseAdmission?.()this.reject(socket, 404)})this.http.on('request', (req, res) => {- const pathname = new URL(req.url ?? '/', 'http://localhost').pathname- // §4.3 DNS-rebinding guard, ahead of every route including the CLI's.- // The body names no condition, so it is not an oracle for which check- // rejected the request (§11).- if (!this.hostHeaderAllowed(req)) {- writeJson(res, 403, {- error: { code: ErrorCodes.PermissionDenied, message: 'forbidden' },- })+ const extensionRoute = this.resolveExtensionMbp1Route(req, 'http')+ if (extensionRoute.kind === 'reject') {+ res.writeHead(extensionRoute.status)+ res.end()return}// GET /discovery — §4.1. Unauthenticated, replayable, and explicitly a// routing hint rather than a trust signal: an extension may pin a port// only after a mutually-authenticated MBP1 session on it. `instanceId`// is emitted verbatim, whatever the shell configured.- if (req.method === 'GET' && pathname === '/discovery') {+ if (+ extensionRoute.kind === 'route' &&+ extensionRoute.route === 'discovery'+ ) {const mbp1 = this.mbp1- if (mbp1 === null) {+ if (mbp1 === null || this.opts.extensionMbp1RoutesEnabled === false) {res.writeHead(404)res.end()return@@ -590,12 +729,49 @@ export class WebSocketBridgeServer {extensionPairing: { protocol: 'mbp1', versions: [1] },applicationProtocols: { mdxp: ['1.0'] },})+ extensionRoute.releaseAdmission?.()return}// POST /nonce — §4.2. The former GET route is gone and now falls through// to the bare 404 below, which is what the spec requires.- if (req.method === 'POST' && pathname === '/nonce') {+ if (extensionRoute.kind === 'route' && extensionRoute.route === 'nonce') {+ // `/nonce` is part of the same Extension-only MBP1 surface as+ // `/discovery`, `/pair`, and `/v1`. A shell which did not provide the+ // complete MBP1 wiring must expose none of the four routes; issuing a+ // nonce here would otherwise create a misleading partial surface and+ // violate the dependency-omission gate.+ if (+ this.mbp1 === null ||+ this.opts.extensionMbp1RoutesEnabled === false+ ) {+ res.writeHead(404)+ res.end()+ extensionRoute.releaseAdmission?.()+ return+ }this.handleNonceIssue(req, res)+ extensionRoute.releaseAdmission?.()+ return+ }+ if (extensionRoute.kind === 'route') {+ extensionRoute.releaseAdmission?.()+ res.writeHead(404)+ res.end()+ return+ }+ // §4.3 DNS-rebinding guard for every non-Extension route.+ if (!this.hostHeaderAllowed(req)) {+ writeJson(res, 403, {+ error: { code: ErrorCodes.PermissionDenied, message: 'forbidden' },+ })+ return+ }+ let pathname: string+ try {+ pathname = new URL(req.url ?? '/', 'http://localhost').pathname+ } catch {+ res.writeHead(404)+ res.end()return}// GET /mdxp/events — Server-Sent Events firehose for CLI/agents (watch).@@ -752,6 +928,56 @@ export class WebSocketBridgeServer {this.boundPort = port}+ private resolveExtensionMbp1Route(+ req: IncomingMessage,+ transport: 'http' | 'websocket'+ ): ExtensionMbp1RouteDecision {+ const policy = this.opts.extensionMbp1RoutePolicy+ if (policy !== undefined) {+ try {+ return policy({+ rawTarget: req.url ?? '/',+ method: req.method ?? '',+ transport,+ rawHeaders: req.rawHeaders,+ directPeerAddress: req.socket.remoteAddress,+ })+ } catch {+ return { kind: 'reject', status: 404 }+ }+ }++ let url: URL+ try {+ url = new URL(req.url ?? '/', 'http://localhost')+ } catch {+ return { kind: 'reject', status: 404 }+ }+ const route =+ url.pathname === '/discovery'+ ? 'discovery'+ : url.pathname === '/nonce'+ ? 'nonce'+ : url.pathname === '/pair'+ ? 'pair'+ : url.pathname === '/v1'+ ? 'v1'+ : null+ if (route === null) return { kind: 'not-extension' }+ if (!this.hostHeaderAllowed(req)) return { kind: 'reject', status: 403 }+ if (+ (transport === 'http' && route !== 'discovery' && route !== 'nonce') ||+ (transport === 'websocket' && route !== 'pair' && route !== 'v1')+ ) {+ return { kind: 'reject', status: 404 }+ }+ const expectedMethod = route === 'nonce' ? 'POST' : 'GET'+ if (req.method !== expectedMethod) return { kind: 'reject', status: 404 }+ return route === 'pair'+ ? { kind: 'route', route, pairNonce: url.searchParams.get('nonce') ?? '' }+ : { kind: 'route', route }+ }+/*** §4.3, scoped to a loopback bind. The non-loopback server shell keeps its* existing token + reverse-proxy model and is explicitly out of MBP1 scope;@@ -784,8 +1010,12 @@ export class WebSocketBridgeServer {// they fire `onDeadline` into a stopped server — `unref()` keeps them from// holding the process open but does not stop them running while it lives.// Their sockets die with the `wss.clients` terminate loop further down.- this.preAuthPair.clear()- this.preAuthReconnect.clear()+ for (const entry of this.preAuthPair.takeWhere(() => true)) {+ entry.releaseAdmission()+ }+ for (const entry of this.preAuthReconnect.takeWhere(() => true)) {+ entry.releaseAdmission()+ }for (const session of this.sessions.values()) {session.conn.dispose()}@@ -989,49 +1219,163 @@ export class WebSocketBridgeServer {}/**- * Cancel an extension's pending handshakes, durably revoke its MBP1- * authorization, and disconnect its live session. Credential removal happens- * before UI bookkeeping: a UI/pairing-store failure may leave stale display- * state, but it can never leave the secret usable.+ * Enter the verified-identity revoke gate synchronously. This method performs+ * every in-memory authorization cutoff before returning: live MDXP is marked+ * unauthorized, admitted pair/reconnect handshakes are cancelled, and later+ * upgrades/adoption observe the gate. It performs no I/O and is therefore the+ * first operation a shell must call for an operator revoke.+ *+ * Re-entry for the same identity returns the existing nominal lease so an+ * operator retry can resume a durable deletion that previously failed. The+ * gate is released only by {@link completeExtensionRevocation}.+ */+ beginExtensionRevocation(+ identity: ClientIdentity & { kind: 'extension' }+ ): ExtensionRevocationLease {+ const normalized = normalizeRevocationIdentity(identity)+ const sessionKey = makeSessionKey(+ normalized.browser,+ normalized.extensionId+ )+ const existing = this.revokingExtensionKeys.get(sessionKey)++ // Repeat the cutoff even for a resumed attempt: a test double or future+ // transport must not be able to attach work between retry calls.+ this.sessions.get(sessionKey)?.conn.revokeAuthorization()+ this.cancelPreAuthForSessionKey(sessionKey)+ if (existing !== undefined) return existing++ const lease = { identity: normalized } as ExtensionRevocationLease+ Object.defineProperty(lease, EXTENSION_REVOCATION_LEASE_BRAND, {+ configurable: false,+ enumerable: false,+ value: true,+ writable: false,+ })+ Object.freeze(lease)+ extensionRevocationClaims.set(lease, {+ server: this,+ sessionKey,+ identity: normalized,+ phase: 'gated',+ deletePromise: null,+ revokedCount: null,+ })+ this.revokingExtensionKeys.set(sessionKey, lease)+ return lease+ }++ /**+ * Durably remove every credential for a gated identity, then notify and+ * close its live session. A failed write closes the transport without a+ * trusted revoke notification and deliberately retains the deny gate.+ * Concurrent/repeated calls share one deletion attempt; a failed attempt may+ * be retried with the same lease.+ */+ deleteExtensionAuthorization(+ lease: ExtensionRevocationLease,+ reason: string+ ): Promise<number> {+ const claim = this.requireExtensionRevocationClaim(lease)+ if (claim.phase === 'completed') {+ return Promise.reject(new Error('extension revocation lease rejected'))+ }+ if (claim.phase === 'credentials-deleted') {+ return Promise.resolve(claim.revokedCount ?? 0)+ }+ if (claim.deletePromise !== null) return claim.deletePromise++ const operation = this.deleteExtensionAuthorizationOnce(claim, reason)+ claim.deletePromise = operation+ void operation.catch(() => {+ if (claim.phase === 'gated' && claim.deletePromise === operation) {+ claim.deletePromise = null+ }+ })+ return operation+ }++ /** Release a revoke gate only after credential deletion and every durable+ * shell projection/marker cleanup have succeeded. */+ completeExtensionRevocation(lease: ExtensionRevocationLease): void {+ const claim = this.requireExtensionRevocationClaim(lease)+ if (claim.phase !== 'credentials-deleted') {+ throw new Error('extension revocation is incomplete')+ }+ if (this.revokingExtensionKeys.get(claim.sessionKey) !== lease) {+ throw new Error('extension revocation lease rejected')+ }+ claim.phase = 'completed'+ claim.deletePromise = null+ this.revokingExtensionKeys.delete(claim.sessionKey)+ extensionRevocationClaims.delete(lease)+ }++ /** Close any still-live transport while deliberately retaining the deny+ * gate. Used when the shell cannot persist its pending-revoke marker. */+ retainFailedExtensionRevocation(lease: ExtensionRevocationLease): void {+ const claim = this.requireExtensionRevocationClaim(lease)+ this.closeExtensionSessionNow(claim.sessionKey)+ }++ /**+ * Backward-compatible all-in-one façade for callers that have no separate+ * durable projection. New shell code must use begin → durable marker →+ * delete → projection cleanup → complete so no pre-marker await window+ * exists.*/async revokeExtensionAccess(identity: ClientIdentity & { kind: 'extension' },reason: string+ ): Promise<number> {+ const lease = this.beginExtensionRevocation(identity)+ const revoked = await this.deleteExtensionAuthorization(lease, reason)+ this.completeExtensionRevocation(lease)+ return revoked+ }++ private async deleteExtensionAuthorizationOnce(+ claim: ExtensionRevocationClaim,+ reason: string): Promise<number> {const mbp1 = this.mbp1- if (mbp1 === null) return 0- const sessionKey = makeSessionKey(identity.browser, identity.extensionId)- this.revokingExtensionKeys.set(- sessionKey,- (this.revokingExtensionKeys.get(sessionKey) ?? 0) + 1- )- // Authorization stops synchronously, before either durable IO or the- // notification grace window can yield back to an inbound request.- this.sessions.get(sessionKey)?.conn.revokeAuthorization()- this.cancelPreAuthForSessionKey(sessionKey)+ if (mbp1 === null) {+ claim.revokedCount = 0+ claim.phase = 'credentials-deleted'+ return 0+ }try {const revoked = await mbp1.credentials.revokeExtensionIdentity(- identity.browser,- identity.extensionId+ claim.identity.browser,+ claim.identity.extensionId)- await this.disconnectExtensionSession(identity, reason)+ claim.revokedCount = revoked+ claim.phase = 'credentials-deleted'+ await this.disconnectExtensionSession(claim.identity, reason)return revoked} catch (error) {- // Do not send an authenticated PairRevoked notice when persistence did- // not land (the peer would delete its only key while the server kept it),- // but keep this live transport fail-closed.- this.closeExtensionSessionNow(sessionKey)+ // The old key may still be durable. Close without a trusted revoke+ // notice, keep the identity gated, and allow an explicit retry to reuse+ // this same lease.+ this.closeExtensionSessionNow(claim.sessionKey)throw error- } finally {- const remaining = (this.revokingExtensionKeys.get(sessionKey) ?? 1) - 1- if (remaining === 0) {- this.revokingExtensionKeys.delete(sessionKey)- } else {- this.revokingExtensionKeys.set(sessionKey, remaining)- }}}+ private requireExtensionRevocationClaim(+ lease: ExtensionRevocationLease+ ): ExtensionRevocationClaim {+ const claim = extensionRevocationClaims.get(lease)+ if (+ claim === undefined ||+ claim.server !== this ||+ this.revokingExtensionKeys.get(claim.sessionKey) !== lease+ ) {+ throw new Error('extension revocation lease rejected')+ }+ return claim+ }+/*** End every handshake for this verified Origin before durable revocation* yields. Otherwise a `/pair` admitted immediately before revoke could@@ -1041,6 +1385,7 @@ export class WebSocketBridgeServer {for (const entry of this.preAuthPair.takeWhere((candidate) => candidate.sessionKey === sessionKey)) {+ entry.releaseAdmission()try {entry.session?.dispose('access-revoked')} catch {@@ -1061,6 +1406,7 @@ export class WebSocketBridgeServer {for (const entry of this.preAuthReconnect.takeWhere((candidate) => candidate.sessionKey === sessionKey)) {+ entry.releaseAdmission()try {entry.session?.dispose('access-revoked')} catch {@@ -1435,9 +1781,11 @@ export class WebSocketBridgeServer {req: IncomingMessage,socket: Duplex,head: Buffer,- url: URL,+ pairNonce: string,peer: ExtensionPeer,- mbp1: Mbp1Wiring+ identity: ClientIdentity & { kind: 'extension' },+ mbp1: Mbp1Wiring,+ releaseAdmission: () => void): void {const sessionKey = makeSessionKey(peer.browser, peer.extensionId)// A revoke owns this verified Origin until durable removal and transport@@ -1445,6 +1793,7 @@ export class WebSocketBridgeServer {// can retry after the critical section rather than being forced to mint a// new nonce for a request the server intentionally did not admit.if (this.revokingExtensionKeys.has(sessionKey)) {+ releaseAdmission()this.reject(socket, 401)return}@@ -1460,8 +1809,8 @@ export class WebSocketBridgeServer {// stays silent could fill all 32 slots for the whole deadline at no cost.// `PairSessionDeps.nonceValid` therefore stays `true` for every session// this demux builds, and remains as the session's own defence in depth.- const pairNonce = url.searchParams.get('nonce') ?? ''if (!this.nonces.consume(pairNonce)) {+ releaseAdmission()this.reject(socket, 401)return}@@ -1473,6 +1822,7 @@ export class WebSocketBridgeServer {// Defence in depth for a future asynchronous upgrade implementation:// never admit a socket if revoke began after the pre-upgrade check.if (this.revokingExtensionKeys.has(sessionKey)) {+ releaseAdmission()ws.close()return}@@ -1483,10 +1833,12 @@ export class WebSocketBridgeServer {queuedDialog: false,confirmed: false,outcomeRecorded: false,+ releaseAdmission,}if (!this.preAuthPair.admit(entry)) {// §4: the table is full. Nothing is constructed, so this attempt// cannot touch flood control or any live session.+ entry.releaseAdmission()ws.close()return}@@ -1514,32 +1866,35 @@ export class WebSocketBridgeServer {admit: (origin) => this.floodControl.admit(origin),release: (origin) => this.floodControl.release(origin),queueDialog: (args) => {- // The one §7.3 outcome flag the session does not expose.- entry.queuedDialog = true- return mbp1.queueMbp1Dialog(args)+ const result = mbp1.queueMbp1Dialog(args)+ // §7.3 counts a failed attempt only after the code-bearing prompt+ // actually reached the shell. A typed enqueue refusal or failed+ // publisher showed no code and must not penalize the peer.+ if (result.ok) {+ void result.handle.published.then(+ (status) => {+ if (status === 'delivered') entry.queuedDialog = true+ },+ () => {}+ )+ }+ return result},sendText: (json) => sendText(ws, json),sendBinary: (frame) => sendBinary(ws, frame),// The reason names an internal step, so it stays off the wire and out// of every log (§11).close: () => ws.close(),- onAuthenticated: (channel) => {+ onAuthenticated: (channel, credentialId) => {// Synchronous, in the same tick: no `await` may separate the// session's `committed` state from this handover, or the post-commit// drop guards swallow the client's first real frames.detachPreAuth()this.preAuthPair.settle(entry)+ entry.releaseAdmission()entry.confirmed = truethis.recordPairOutcome(entry)- this.adoptAuthenticatedSession(- ws,- {- kind: 'extension',- browser: peer.browser,- extensionId: peer.extensionId,- },- channel- )+ this.adoptAuthenticatedSession(ws, identity, channel, credentialId)},now: () => Date.now(),random: (n) => new Uint8Array(randomBytes(n)),@@ -1565,6 +1920,7 @@ export class WebSocketBridgeServer {ws.on('close', () => {detachPreAuth()this.preAuthPair.settle(entry)+ entry.releaseAdmission()session.dispose('socket-closed')// §7.3 names the early disconnect explicitly: a guesser must not be// able to dodge the failure counter by closing the socket.@@ -1575,20 +1931,24 @@ export class WebSocketBridgeServer {/*** `/v1` — the §8 challenge–response. The upgrade carries no credentials in- * the URL; a `?token=` query is simply ignored, because there is no token- * path left for it to reach.+ * the URL. The public raw-route policy rejects every query (including a+ * historical `?token=`) before this handler can run, and no token auth path+ * exists behind it.*/private handleMbp1ReconnectUpgrade(req: IncomingMessage,socket: Duplex,head: Buffer,peer: ExtensionPeer,- mbp1: Mbp1Wiring+ identity: ClientIdentity & { kind: 'extension' },+ mbp1: Mbp1Wiring,+ releaseAdmission: () => void): void {const sessionKey = makeSessionKey(peer.browser, peer.extensionId)// Keep a revoke critical section closed to both credential reuse and new// first-pair credential creation for the same verified Origin.if (this.revokingExtensionKeys.has(sessionKey)) {+ releaseAdmission()this.reject(socket, 401)return}@@ -1603,17 +1963,25 @@ export class WebSocketBridgeServer {// requirement that an unknown `credentialId` and a bad MAC be// indistinguishable concerns what happens *after* admission.if (!this.reconnectRate.admit(peer.origin)) {+ releaseAdmission()this.reject(socket, 429)return}this.wss.handleUpgrade(req, socket, head, (ws) => {if (this.revokingExtensionKeys.has(sessionKey)) {+ releaseAdmission()ws.close()return}- const entry: ReconnectPreAuthEntry = { ws, sessionKey, session: null }+ const entry: ReconnectPreAuthEntry = {+ ws,+ sessionKey,+ session: null,+ releaseAdmission,+ }if (!this.preAuthReconnect.admit(entry)) {+ entry.releaseAdmission()ws.close()return}@@ -1628,17 +1996,15 @@ export class WebSocketBridgeServer {credentials: mbp1.credentials,sendText: (json) => sendText(ws, json),close: () => ws.close(),- onAuthenticated: (channel) => {+ onAuthenticated: (channel, credential) => {detachPreAuth()this.preAuthReconnect.settle(entry)+ entry.releaseAdmission()this.adoptAuthenticatedSession(ws,- {- kind: 'extension',- browser: peer.browser,- extensionId: peer.extensionId,- },- channel+ identity,+ channel,+ credential.credentialId)},now: () => Date.now(),@@ -1665,6 +2031,7 @@ export class WebSocketBridgeServer {ws.on('close', () => {detachPreAuth()this.preAuthReconnect.settle(entry)+ entry.releaseAdmission()session.dispose('socket-closed')})@@ -1686,7 +2053,8 @@ export class WebSocketBridgeServer {adoptAuthenticatedSession(ws: WebSocketLike,identity: ClientIdentity & { kind: 'extension' },- channel: EnvelopeChannel+ channel: EnvelopeChannel,+ credentialId: string): void {// Byte-identical to `clientKey(identity)`, which the SSE revoke matcher// and `getSession` both rely on.@@ -1751,7 +2119,22 @@ export class WebSocketBridgeServer {})conn.listen()- this.opts.onExtensionAuthenticated?.(identity)+ // Deliberately synchronous and un-awaited: the session handover and the+ // exact credential evidence are published in this adoption tick. The+ // shell may schedule follow-up work, but cannot block the live transport.+ this.opts.onExtensionAuthenticated?.(identity, credentialId)+ }++ private canAdmitExtensionIdentity(+ identity: ClientIdentity & { kind: 'extension' }+ ): boolean {+ try {+ return this.opts.canAdmitExtensionIdentity?.(identity) ?? true+ } catch {+ // Projection/recovery state is an authorization input. A broken gate+ // must close the surface, not turn an upgrade into an uncaught error.+ return false+ }}/** §7.3's counter moves exactly once per `/pair` session, on whichever@@ -1775,6 +2158,7 @@ export class WebSocketBridgeServer {entry.session?.dispose('timeout')this.recordPairOutcome(entry)} finally {+ entry.releaseAdmission()// `dispose` deliberately does NOT close the socket — both session modules// read it as "the peer is already gone, or the wiring is closing it" — so// the wiring must, and must do so even if the bookkeeping above throws.diff --git a/src/main/bridge/bootstrap-lifecycle.test.ts b/src/main/bridge/bootstrap-lifecycle.test.tsindex 09f81fff..36278f24 100644--- a/src/main/bridge/bootstrap-lifecycle.test.ts+++ b/src/main/bridge/bootstrap-lifecycle.test.ts@@ -1,8 +1,19 @@-import { mkdtemp, rm } from 'node:fs/promises'+import {+ lstat,+ mkdir,+ mkdtemp,+ readFile,+ rm,+ symlink,+ writeFile,+} from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'-import type { Mbp1CredentialStore } from '@core/bridge/credential-store'+import { BRIDGE_DATA_DIR_LOCK_FILE_NAME } from '@core/bridge/bridge-data-dir-lock'+import { Mbp1CredentialStore } from '@core/bridge/credential-store'import { EndpointFileWriter } from '@core/bridge/endpoint-file-writer'+import type { PairDialogRequest } from '@core/bridge/mbp1/pair-session'+import type { PairingPromptEnqueueResult } from '@core/bridge/pairing-prompt-controller'import { PairingService } from '@core/bridge/pairing-service'import { WebSocketBridgeServer } from '@core/bridge/web-socket-bridge-server'import { BridgeReceiver } from '@core/bridge-receiver/bridge-receiver'@@ -69,6 +80,10 @@ function args(): Parameters<typeof bootstrapBridge>[0] {ffmpegAvailable: false,enabled: true,bridgeSettings: { fixedPort: 'auto', instanceId: 'test-instance-id' },+ bridgeDataDirLockRecoveryAuthority: {+ ownershipEpoch: 'T'.repeat(43),+ assertExclusiveProcessOwnership: () => true,+ },eventBus: { on: vi.fn(), off: vi.fn() },createTaskDeps: {} as never,activityRecorder: {} as never,@@ -171,6 +186,96 @@ describe('desktop bridge bootstrap ownership', () => {await rm(userDataDir, { recursive: true, force: true })})+ it('acquires the data-root lock before the first bridge store load', async () => {+ const lockPath = join(userDataDir, 'bridge', BRIDGE_DATA_DIR_LOCK_FILE_NAME)+ const load = vi.spyOn(PairingService.prototype, 'load')+ load.mockImplementationOnce(async () => {+ const document = JSON.parse(await readFile(lockPath, 'utf-8')) as {+ ownershipEpoch?: unknown+ }+ expect(document.ownershipEpoch).toBe('T'.repeat(43))+ })++ const runtime = await bootstrapBridge(args())+ expect(runtime).not.toBeNull()+ await runtime?.shutdown()+ })++ it('holds the data-root lock through listener and store drain, then releases it', async () => {+ const lockPath = join(userDataDir, 'bridge', BRIDGE_DATA_DIR_LOCK_FILE_NAME)+ vi.mocked(WebSocketBridgeServer.prototype.stop).mockImplementation(+ async () => {+ expect((await lstat(lockPath)).isFile()).toBe(true)+ }+ )+ vi.mocked(PairingService.prototype.stopAndDrain).mockImplementation(+ async () => {+ expect((await lstat(lockPath)).isFile()).toBe(true)+ }+ )++ const runtime = await bootstrapBridge(args())+ await runtime?.shutdown()++ await expect(lstat(lockPath)).rejects.toMatchObject({ code: 'ENOENT' })+ })++ it('releases the data-root lock when the first store load fails', async () => {+ const failure = new Error('pairing store unavailable')+ vi.spyOn(PairingService.prototype, 'load').mockRejectedValueOnce(failure)+ const lockPath = join(userDataDir, 'bridge', BRIDGE_DATA_DIR_LOCK_FILE_NAME)++ await expect(bootstrapBridge(args())).rejects.toBe(failure)+ await expect(lstat(lockPath)).rejects.toMatchObject({ code: 'ENOENT' })+ expect(+ WebSocketBridgeServer.prototype.startOnFirstFree+ ).not.toHaveBeenCalled()+ })++ it.runIf(process.platform !== 'win32')(+ 'repairs a projection writer residue before loading any bridge store',+ async () => {+ const bridgeDirectory = join(userDataDir, 'bridge')+ await mkdir(bridgeDirectory, { recursive: true })+ const projectionLock = join(+ bridgeDirectory,+ 'extension-pairings.json.lock'+ )+ await writeFile(projectionLock, 'crashed writer', { mode: 0o600 })++ const runtime = await bootstrapBridge(args())+ expect(runtime).not.toBeNull()+ await expect(lstat(projectionLock)).rejects.toMatchObject({+ code: 'ENOENT',+ })+ await runtime?.shutdown()+ }+ )++ it.runIf(process.platform !== 'win32')(+ 'keeps listeners closed when a projection residue is not a regular owned file',+ async () => {+ const bridgeDirectory = join(userDataDir, 'bridge')+ await mkdir(bridgeDirectory, { recursive: true })+ const target = join(userDataDir, 'do-not-remove')+ const projectionLock = join(+ bridgeDirectory,+ 'extension-pairings.json.lock'+ )+ await writeFile(target, 'preserved', { mode: 0o600 })+ await symlink(target, projectionLock)++ await expect(bootstrapBridge(args())).rejects.toThrow(+ 'extension-pairing-projection file rejected'+ )+ expect(+ WebSocketBridgeServer.prototype.startOnFirstFree+ ).not.toHaveBeenCalled()+ await expect(readFile(target, 'utf-8')).resolves.toBe('preserved')+ expect((await lstat(projectionLock)).isSymbolicLink()).toBe(true)+ }+ )+it('drains receiver work published before restore rejects', async () => {const failure = new Error('receiver restore failed after resume')let receiverLive = false@@ -254,6 +359,55 @@ describe('desktop bridge bootstrap ownership', () => {expect(activeChannels.size).toBe(0)})+ it.each([+ [false, 'test', true],+ [true, 'test', false],+ [false, 'production', false],+ ] as const)(+ 'gates an env development id for isPackaged=%s NODE_ENV=%s',+ async (isPackaged, nodeEnv, expectedOfficial) => {+ const devId = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'+ const previous = process.env.MOTRIX_DEV_TRUSTED_EXTENSIONS+ const previousNodeEnv = process.env.NODE_ENV+ process.env.MOTRIX_DEV_TRUSTED_EXTENSIONS = `chromium:${devId}`+ process.env.NODE_ENV = nodeEnv+ electron.isPackaged = isPackaged+ snapRuntime.enabled = isPackaged+ let runtime: Awaited<ReturnType<typeof bootstrapBridge>> = null++ try {+ runtime = await bootstrapBridge(args())+ expect(runtime).not.toBeNull()+ if (runtime === null) throw new Error('bridge did not start')+ const manifests = vi+ .mocked(NativeMessagingInstaller.prototype.syncManifests)+ .mock.calls.at(-1)?.[0]+ expect(manifests?.chromium.includes(devId)).toBe(expectedOfficial)++ const mbp1 = (+ runtime.server as unknown as {+ mbp1: {+ isOfficialId(browser: 'chromium', id: string): boolean+ } | null+ }+ ).mbp1+ expect(mbp1?.isOfficialId('chromium', devId)).toBe(expectedOfficial)+ } finally {+ await runtime?.shutdown()+ if (previous === undefined) {+ delete process.env.MOTRIX_DEV_TRUSTED_EXTENSIONS+ } else {+ process.env.MOTRIX_DEV_TRUSTED_EXTENSIONS = previous+ }+ if (previousNodeEnv === undefined) {+ delete process.env.NODE_ENV+ } else {+ process.env.NODE_ENV = previousNodeEnv+ }+ }+ }+ )+it.each(['EACCES', 'EPERM'] as const)('keeps the bridge live when Snap manifest sync fails with %s',async (code) => {@@ -388,7 +542,105 @@ describe('desktop bridge bootstrap ownership', () => {expect(shutdownOrder).toEqual(['server', 'pairing'])})+ it('aborts and drains a pending MBP1 prompt during bridge shutdown', async () => {+ const runtime = await bootstrapBridge(args())+ expect(runtime).not.toBeNull()+ if (!runtime) return++ const request: PairDialogRequest = {+ browser: 'chromium',+ claimedExtensionId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ identity: 'official',+ code: '1234-5678',+ pairingNonce: 'nonce-shutdown',+ verifiedOrigin: 'chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ }+ const queuePrompt = (+ runtime.server as unknown as {+ opts: {+ queueMbp1Dialog?: (+ value: PairDialogRequest+ ) => PairingPromptEnqueueResult+ }+ }+ ).opts.queueMbp1Dialog+ expect(queuePrompt).toBeTypeOf('function')+ if (!queuePrompt) return++ const result = queuePrompt(request)+ expect(result.ok).toBe(true)+ if (!result.ok) return+ await expect(result.handle.published).resolves.toBe('delivered')+ const settled = vi.fn()+ runtime.bus.on('PairRequestSettled', settled)++ await runtime.shutdown()++ await expect(result.handle.terminal).resolves.toBe('aborted')+ expect(settled).toHaveBeenCalledExactlyOnceWith({+ key: 'chromium:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:nonce-shutdown',+ outcome: 'aborted',+ })+ expect(queuePrompt(request)).toEqual({ ok: false, reason: 'disposed' })+ })+describe('MBP1 identity persistence (§9.2) and the Paired seam', () => {+ const extensionIdentity = {+ kind: 'extension' as const,+ browser: 'chromium' as const,+ extensionId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ }++ type LiveBridgeRuntime = NonNullable<+ Awaited<ReturnType<typeof bootstrapBridge>>+ >++ function extensionServerOptions(runtime: LiveBridgeRuntime) {+ return (+ runtime.server as unknown as {+ opts: {+ onExtensionAuthenticated?: (+ identity: typeof extensionIdentity,+ credentialId: string+ ) => void+ credentials: Mbp1CredentialStore+ }+ }+ ).opts+ }++ function revokeExtensionHandler() {+ return electron.handle.mock.calls.find(+ ([channel]) => channel === 'bridge:revokePair'+ )?.[1] as+ | ((+ event: unknown,+ params: { identity: typeof extensionIdentity }+ ) => Promise<unknown>)+ | undefined+ }++ async function commitAndProjectExtension(runtime: LiveBridgeRuntime) {+ const opts = extensionServerOptions(runtime)+ const credential = await opts.credentials.offerProvisional(+ {+ browser: extensionIdentity.browser,+ verifiedOrigin: `chrome-extension://${extensionIdentity.extensionId}`,+ clientInstallationId: 'install-a',+ },+ 'official'+ )+ await opts.credentials.commitFromPair(credential.credentialId)+ opts.onExtensionAuthenticated?.(+ extensionIdentity,+ credential.credentialId+ )+ await vi.waitFor(() =>+ expect(runtime.extensionPairings.list()).toHaveLength(1)+ )+ return { opts, credential }+ }+it('persists localToken across a restart while rotating serverGeneration', async () => {const writeCalls: Array<{port: number@@ -416,35 +668,22 @@ describe('desktop bridge bootstrap ownership', () => {expect(writeCalls[0]?.generation).not.toBe(writeCalls[1]?.generation)})- it('durably revokes MBP1 credentials before removing PairingService state and closing the live socket', async () => {+ it('records the exact committed credential and durably revokes the whole extension identity', async () => {const runtime = await bootstrapBridge(args())expect(runtime).not.toBeNull()if (!runtime) return- const identity = {- kind: 'extension' as const,- browser: 'chromium' as const,- extensionId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',- }-// Reach the real callback WebSocketBridgeServer's constructor was// given — the exact seam `adoptAuthenticatedSession` invokes on// every successful MBP1 authentication (Task 18's own tests prove// THAT call fires; this proves the desktop shell's closure).- const opts = (- runtime.server as unknown as {- opts: {- onExtensionAuthenticated?: (id: typeof identity) => void- credentials: Mbp1CredentialStore- }- }- ).opts+ const opts = extensionServerOptions(runtime)expect(opts.onExtensionAuthenticated).toBeTypeOf('function')const credential = await opts.credentials.offerProvisional({- browser: identity.browser,- verifiedOrigin: `chrome-extension://${identity.extensionId}`,+ browser: extensionIdentity.browser,+ verifiedOrigin: `chrome-extension://${extensionIdentity.extensionId}`,clientInstallationId: 'install-a',},'official'@@ -452,8 +691,8 @@ describe('desktop bridge bootstrap ownership', () => {await opts.credentials.commitFromPair(credential.credentialId)const successor = await opts.credentials.offerProvisional({- browser: identity.browser,- verifiedOrigin: `chrome-extension://${identity.extensionId}`,+ browser: extensionIdentity.browser,+ verifiedOrigin: `chrome-extension://${extensionIdentity.extensionId}`,clientInstallationId: 'install-a',},'official'@@ -472,29 +711,35 @@ describe('desktop bridge bootstrap ownership', () => {).sessions.set('chromium:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', {conn,envelope,- extensionId: identity.extensionId,- browser: identity.browser,+ extensionId: extensionIdentity.extensionId,+ browser: extensionIdentity.browser,startedAt: Date.now(),})- opts.onExtensionAuthenticated?.(identity)+ opts.onExtensionAuthenticated?.(+ extensionIdentity,+ credential.credentialId+ )await vi.waitFor(() =>- expect(runtime.pairing.listPaired()).toHaveLength(1)+ expect(runtime.extensionPairings.list()).toHaveLength(1))- expect(runtime.pairing.listPaired()[0]?.identity).toEqual(identity)+ expect(runtime.extensionPairings.list()[0]?.identity).toEqual(+ extensionIdentity+ )+ expect(runtime.extensionPairings.list()[0]).toMatchObject({+ identityTrust: 'official',+ status: 'ready',+ pairedAt: expect.any(Number),+ })- const revokeHandler = electron.handle.mock.calls.find(- ([channel]) => channel === 'bridge:revokePair'- )?.[1] as- | ((event: unknown, params: { identity: typeof identity }) => unknown)- | undefined+ const revokeHandler = revokeExtensionHandler()expect(revokeHandler).toBeTypeOf('function')- await revokeHandler?.(undefined, { identity })+ await revokeHandler?.(undefined, { identity: extensionIdentity })expect(opts.credentials.findForAuth(credential.credentialId)).toBeNull()expect(opts.credentials.findForAuth(successor.credentialId)).toBeNull()- expect(runtime.pairing.listPaired()).toHaveLength(0)+ expect(runtime.extensionPairings.list()).toHaveLength(0)expect(conn.sendNotification).toHaveBeenCalledWith(expect.anything(),expect.objectContaining({ reason: 'user-revoked' })@@ -508,6 +753,314 @@ describe('desktop bridge bootstrap ownership', () => {await runtime.shutdown()})++ it('keeps the credential durable but immediately quarantines an unprojectable authenticated session', async () => {+ const runtime = await bootstrapBridge(args())+ expect(runtime).not.toBeNull()+ if (!runtime) return++ const opts = extensionServerOptions(runtime)+ const credential = await opts.credentials.offerProvisional(+ {+ browser: extensionIdentity.browser,+ verifiedOrigin: `chrome-extension://${extensionIdentity.extensionId}`,+ clientInstallationId: 'install-a',+ },+ 'official'+ )+ await opts.credentials.commitFromPair(credential.credentialId)++ const paired = vi.fn()+ const errors = vi.fn()+ runtime.bus.on('Paired', paired)+ runtime.bus.on('Error', errors)+ const conn = {+ revokeAuthorization: vi.fn(),+ dispose: vi.fn(),+ }+ const envelope = { close: vi.fn() }+ ;(+ runtime.server as unknown as { sessions: Map<string, unknown> }+ ).sessions.set('chromium:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', {+ conn,+ envelope,+ extensionId: extensionIdentity.extensionId,+ browser: extensionIdentity.browser,+ startedAt: Date.now(),+ })+ vi.spyOn(+ runtime.extensionPairings,+ 'recordAuthenticated'+ ).mockRejectedValueOnce(new Error('secret projection path'))++ opts.onExtensionAuthenticated?.(+ extensionIdentity,+ credential.credentialId+ )++ await vi.waitFor(() =>+ expect(errors).toHaveBeenCalledExactlyOnceWith({+ code: 'extensionProjectionDegraded',+ message:+ 'Extension pairing state could not be updated; access is closed until startup repair.',+ })+ )+ expect(paired).not.toHaveBeenCalled()+ expect(+ opts.credentials.findForAuth(credential.credentialId)+ ).not.toBeNull()+ expect(conn.revokeAuthorization).toHaveBeenCalled()+ expect(envelope.close).toHaveBeenCalledWith(1000)+ expect(conn.dispose).toHaveBeenCalledOnce()+ expect(+ runtime.server.getSession('chromium:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')+ ).toBeUndefined()++ await runtime.shutdown()+ })++ it('retains a durable pending marker and deny gate when credential revocation fails', async () => {+ const runtime = await bootstrapBridge(args())+ expect(runtime).not.toBeNull()+ if (!runtime) return++ const { opts, credential } = await commitAndProjectExtension(runtime)+ const errors = vi.fn()+ const revoked = vi.fn()+ runtime.bus.on('Error', errors)+ runtime.bus.on('Revoked', revoked)+ vi.spyOn(+ runtime.server,+ 'deleteExtensionAuthorization'+ ).mockRejectedValueOnce(+ new Error('secret credential persistence failure')+ )++ await expect(+ revokeExtensionHandler()?.(undefined, {+ identity: extensionIdentity,+ })+ ).rejects.toThrow('extension revocation incomplete')++ expect(runtime.extensionPairings.list()).toMatchObject([+ { identity: extensionIdentity, status: 'cleanup-pending' },+ ])+ expect(+ opts.credentials.findForAuth(credential.credentialId)+ ).not.toBeNull()+ expect(+ runtime.extensionPairings.canAdmitIdentity(extensionIdentity)+ ).toBe(false)+ expect(revoked).not.toHaveBeenCalled()+ expect(errors).toHaveBeenCalledExactlyOnceWith({+ code: 'extensionRevocationIncomplete',+ message:+ 'Extension revocation is incomplete; access remains closed and startup will retry it.',+ })++ await runtime.shutdown()+ })++ it('cuts live authorization before a blocked pending-revoke marker write', async () => {+ const runtime = await bootstrapBridge(args())+ expect(runtime).not.toBeNull()+ if (!runtime) return++ await commitAndProjectExtension(runtime)+ const conn = {+ revokeAuthorization: vi.fn(),+ dispose: vi.fn(),+ }+ const envelope = { close: vi.fn() }+ ;(+ runtime.server as unknown as { sessions: Map<string, unknown> }+ ).sessions.set('chromium:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', {+ conn,+ envelope,+ extensionId: extensionIdentity.extensionId,+ browser: extensionIdentity.browser,+ startedAt: Date.now(),+ })++ let announceMarkerWrite!: () => void+ const markerWriteEntered = new Promise<void>((resolve) => {+ announceMarkerWrite = resolve+ })+ let releaseMarkerWrite!: () => void+ const markerWriteReleased = new Promise<void>((resolve) => {+ releaseMarkerWrite = resolve+ })+ const prepare = runtime.extensionPairings.prepareIdentityCleanup.bind(+ runtime.extensionPairings+ )+ vi.spyOn(+ runtime.extensionPairings,+ 'prepareIdentityCleanup'+ ).mockImplementationOnce(async (identity) => {+ announceMarkerWrite()+ await markerWriteReleased+ return prepare(identity)+ })++ const revoke = revokeExtensionHandler()?.(undefined, {+ identity: extensionIdentity,+ })+ await markerWriteEntered++ expect(conn.revokeAuthorization).toHaveBeenCalledOnce()+ expect(+ (+ runtime.server as unknown as {+ revokingExtensionKeys: Map<string, unknown>+ }+ ).revokingExtensionKeys.has('chromium:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')+ ).toBe(true)++ releaseMarkerWrite()+ await expect(revoke).resolves.toBeUndefined()+ expect(runtime.extensionPairings.list()).toEqual([])+ expect(+ (+ runtime.server as unknown as {+ revokingExtensionKeys: Map<string, unknown>+ }+ ).revokingExtensionKeys.has('chromium:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')+ ).toBe(false)++ await runtime.shutdown()+ })++ it('keeps admission closed and reports a fixed repair signal when projection cleanup fails after revocation', async () => {+ const runtime = await bootstrapBridge(args())+ expect(runtime).not.toBeNull()+ if (!runtime) return++ const { opts, credential } = await commitAndProjectExtension(runtime)+ const revoked = vi.fn()+ const errors = vi.fn()+ runtime.bus.on('Revoked', revoked)+ runtime.bus.on('Error', errors)+ vi.spyOn(+ runtime.extensionPairings,+ 'completeCleanup'+ ).mockRejectedValueOnce(new Error('secret projection path'))++ await expect(+ revokeExtensionHandler()?.(undefined, {+ identity: extensionIdentity,+ })+ ).rejects.toThrow('extension revocation incomplete')++ expect(opts.credentials.findForAuth(credential.credentialId)).toBeNull()+ expect(runtime.extensionPairings.list()).toMatchObject([+ { identity: extensionIdentity, status: 'cleanup-pending' },+ ])+ expect(+ runtime.extensionPairings.canAdmitIdentity(extensionIdentity)+ ).toBe(false)+ expect(revoked).not.toHaveBeenCalled()+ expect(errors).toHaveBeenCalledExactlyOnceWith({+ code: 'extensionRevocationIncomplete',+ message:+ 'Extension revocation is incomplete; access remains closed and startup will retry it.',+ })++ await runtime.shutdown()+ })++ it('does not delete credentials when the pending-revoke marker cannot be persisted', async () => {+ const runtime = await bootstrapBridge(args())+ expect(runtime).not.toBeNull()+ if (!runtime) return++ const { opts, credential } = await commitAndProjectExtension(runtime)+ const revoked = vi.fn()+ const errors = vi.fn()+ runtime.bus.on('Revoked', revoked)+ runtime.bus.on('Error', errors)+ vi.spyOn(+ runtime.extensionPairings,+ 'prepareIdentityCleanup'+ ).mockRejectedValueOnce(new Error('secret projection failure'))++ await expect(+ revokeExtensionHandler()?.(undefined, {+ identity: extensionIdentity,+ })+ ).rejects.toThrow('extension revocation incomplete')++ expect(+ opts.credentials.findForAuth(credential.credentialId)+ ).not.toBeNull()+ expect(revoked).not.toHaveBeenCalled()+ expect(errors).toHaveBeenCalledExactlyOnceWith({+ code: 'extensionRevocationMarkerFailed',+ message:+ 'Extension revocation could not be recorded; access is closed for this run, but restart may restore the old credential.',+ })++ await runtime.shutdown()+ })++ it('restores a durable pending revoke and finishes it before the next listener starts', async () => {+ const first = await bootstrapBridge(args())+ expect(first).not.toBeNull()+ if (!first) return++ const { credential } = await commitAndProjectExtension(first)+ await first.extensionPairings.prepareIdentityCleanup(extensionIdentity)+ await first.shutdown()+ vi.mocked(WebSocketBridgeServer.prototype.startOnFirstFree).mockClear()++ const second = await bootstrapBridge(args())+ expect(second).not.toBeNull()+ if (!second) return+ const secondOptions = extensionServerOptions(second)++ expect(+ secondOptions.credentials.findForAuth(credential.credentialId)+ ).toBeNull()+ expect(second.extensionPairings.list()).toEqual([])+ expect(+ WebSocketBridgeServer.prototype.startOnFirstFree+ ).toHaveBeenCalledOnce()++ await second.shutdown()+ })++ it('keeps the listener closed when startup cannot finish a durable pending revoke', async () => {+ const first = await bootstrapBridge(args())+ expect(first).not.toBeNull()+ if (!first) return++ const { credential } = await commitAndProjectExtension(first)+ await first.extensionPairings.prepareIdentityCleanup(extensionIdentity)+ await first.shutdown()+ vi.mocked(WebSocketBridgeServer.prototype.startOnFirstFree).mockClear()++ const deleteFailure = vi+ .spyOn(Mbp1CredentialStore.prototype, 'revokeExtensionIdentity')+ .mockRejectedValueOnce(new Error('secret durable path'))+ await expect(bootstrapBridge(args())).rejects.toThrow(+ 'extension revocation recovery failed'+ )+ expect(+ WebSocketBridgeServer.prototype.startOnFirstFree+ ).not.toHaveBeenCalled()+ deleteFailure.mockRestore()++ const recovered = await bootstrapBridge(args())+ expect(recovered).not.toBeNull()+ if (!recovered) return+ expect(+ extensionServerOptions(recovered).credentials.findForAuth(+ credential.credentialId+ )+ ).toBeNull()+ expect(recovered.extensionPairings.list()).toEqual([])++ await recovered.shutdown()+ })})describe('bridge:getStatus (Task 21)', () => {@@ -527,6 +1080,7 @@ describe('desktop bridge bootstrap ownership', () => {await expect(handler?.()).resolves.toEqual({port: 19002,degraded: false,+ extensionPairingHealth: 'ready',fixedPort: 'auto',instanceId: 'test-instance-id',})@@ -546,6 +1100,7 @@ describe('desktop bridge bootstrap ownership', () => {await expect(getStatusHandler()?.()).resolves.toEqual({port: 54321,degraded: true,+ extensionPairingHealth: 'ready',fixedPort: 'auto',instanceId: 'test-instance-id',})diff --git a/src/main/bridge/bridge-manager.test.ts b/src/main/bridge/bridge-manager.test.tsindex 443aae52..f1d47237 100644--- a/src/main/bridge/bridge-manager.test.ts+++ b/src/main/bridge/bridge-manager.test.ts@@ -6,6 +6,7 @@ function makeRuntime(): BridgeRuntime {return {server: {} as unknown as BridgeRuntime['server'],pairing: {} as unknown as BridgeRuntime['pairing'],+ extensionPairings: {} as unknown as BridgeRuntime['extensionPairings'],registry: {} as unknown as BridgeRuntime['registry'],bus: {} as unknown as BridgeRuntime['bus'],installer: {diff --git a/src/main/bridge/index.ts b/src/main/bridge/index.tsindex ec90df13..8d80ccee 100644--- a/src/main/bridge/index.ts+++ b/src/main/bridge/index.ts@@ -1,11 +1,28 @@+import { mkdir } from 'node:fs/promises'import { homedir, platform as osPlatform } from 'node:os'import { join } from 'node:path'+import {+ acquireBridgeDataDirLock,+ type BridgeDataDirLockRecoveryAuthority,+} from '@core/bridge/bridge-data-dir-lock'import { BridgeEventBus } from '@core/bridge/bridge-event-bus'import { loadOrCreateBridgeIdentity } from '@core/bridge/bridge-identity'import { BridgeOwnership } from '@core/bridge/bridge-ownership'-import { Mbp1CredentialStore } from '@core/bridge/credential-store'+import {+ type CommittedExtensionCredentialWitness,+ Mbp1CredentialStore,+} from '@core/bridge/credential-store'import { DeviceCodeService } from '@core/bridge/device-code-service'import { EndpointFileWriter } from '@core/bridge/endpoint-file-writer'+import {+ createExtensionIdentityResolver,+ parseDevTrustedExtensions,+} from '@core/bridge/extension-identity-resolver'+import { ExtensionPairingProjectionService } from '@core/bridge/extension-pairing-projection'+import {+ FileExtensionPairingProjectionStore,+ recoverExtensionPairingProjectionWriterLock,+} from '@core/bridge/file-extension-pairing-projection-store'import { FilePairingStore } from '@core/bridge/file-pairing-store'import type { ReadHandlerDeps } from '@core/bridge/handlers/read-handlers'import type { WriteHandlerDeps } from '@core/bridge/handlers/write-handlers'@@ -30,13 +47,11 @@ import type { PluginHost } from '@core/plugin/host/plugin-host'import type { PluginRegistry } from '@core/plugin/plugin-registry'import { handleCreateTask } from '@core/task/create-task-handler'import { Notifications } from '@motrix/mdxp'-import nativeMessagingExtensions from '@shared/config/native-messaging-extensions.json'import {BridgeCommands,BridgeEvents,BridgeQueries,type BridgeStatusInfo,- type Browser,type ClientIdentity,type PairRequestPayload,pairRequestKey,@@ -174,65 +189,6 @@ function camelize(code: string): string {return code.replace(/-(\w)/g, (_, c: string) => c.toUpperCase())}-// This file is also embedded into the Rust Flatpak companion. Keep one source-// of truth for the manifest allowlist and Motrix's in-app trust registry.-const BUILTIN_TRUSTED: Array<{- id: string- browser: 'chromium' | 'firefox'-}> = [- ...nativeMessagingExtensions.chromium.map((id) => ({- id,- browser: 'chromium' as const,- })),- ...nativeMessagingExtensions.firefox.map((id) => ({- id,- browser: 'firefox' as const,- })),-]--/**- * Parse `MOTRIX_DEV_TRUSTED_EXTENSIONS` — comma-separated- * `<browser>:<id>` pairs (e.g.- * `chromium:abcdefghijklmnopabcdefghijklmnop,firefox:moo@bar`).- *- * Used during development to allow an unpacked extension whose ID is- * not yet in BUILTIN_TRUSTED to clear the NM `allowed_origins` gate.- * Silently skips malformed entries so a typo cannot break startup.- */-export function parseDevTrustedExtensions(- raw: string | undefined-): Array<{ id: string; browser: 'chromium' | 'firefox' }> {- if (!raw) return []- const out: Array<{ id: string; browser: 'chromium' | 'firefox' }> = []- for (const part of raw.split(',')) {- const trimmed = part.trim()- if (!trimmed) continue- const colon = trimmed.indexOf(':')- if (colon <= 0) continue- const browser = trimmed.slice(0, colon).trim()- const id = trimmed.slice(colon + 1).trim()- if (!id) continue- if (browser !== 'chromium' && browser !== 'firefox') continue- out.push({ id, browser })- }- return out-}--/**- * §5's `isOfficialId`, backed by the immutable allowlist only. Deliberately- * never derived from `TrustedExtensionRegistry.has()`, which also admits- * `user-added` and `imported` entries — a source §5 forbids for the- * `official` tier (spec-coverage audit W1). Extracted so the two arrays that- * feed the registry (`BUILTIN_TRUSTED` + `parseDevTrustedExtensions`) can be- * unit-tested against this resolver without standing up a registry at all.- */-export function resolveOfficialIds(- entries: ReadonlyArray<{ id: string; browser: 'chromium' | 'firefox' }>-): (browser: Browser, id: string) => boolean {- const allowed = new Set(entries.map((e) => `${e.browser}:${e.id}`))- return (browser, id) => allowed.has(`${browser}:${id}`)-}-/** §4: `fixedPort` resolves to the candidate range, or pins a single port. */function resolveBridgePorts(fixedPort: BridgeSettings['fixedPort']@@ -240,6 +196,16 @@ function resolveBridgePorts(return fixedPort === 'auto' ? BRIDGE_CANDIDATE_PORTS : [fixedPort]}+function extensionIdentityMatchesWitness(+ identity: ClientIdentity & { kind: 'extension' },+ witness: CommittedExtensionCredentialWitness+): boolean {+ return (+ witness.identity.browser === identity.browser &&+ witness.identity.extensionId === identity.extensionId+ )+}+/*** How often `sweepExpiredProvisionals()` runs. §6.7 bounds a first-pair* provisional's TTL to 10 minutes; sweeping on the same cadence keeps@@ -253,6 +219,7 @@ const CREDENTIAL_SWEEP_INTERVAL_MS = 10 * 60 * 1000export interface BridgeRuntime {server: WebSocketBridgeServerpairing: PairingService+ extensionPairings: ExtensionPairingProjectionServiceregistry: TrustedExtensionRegistrybus: BridgeEventBusinstaller: NativeMessagingInstaller@@ -444,6 +411,8 @@ export async function bootstrapBridge(args: {/** `bridge.fixedPort` (port policy, §4) + `bridge.instanceId` (the §4.1* discovery routing hint) from persisted settings. */bridgeSettings: BridgeSettings+ /** Electron single-instance ownership, acquired before bridge bootstrap. */+ bridgeDataDirLockRecoveryAuthority: BridgeDataDirLockRecoveryAuthority/** Test-only override for `sweepExpiredProvisionals()`'s cadence —* production always relies on {@link CREDENTIAL_SWEEP_INTERVAL_MS}. */credentialSweepIntervalMs?: number@@ -455,95 +424,118 @@ export async function bootstrapBridge(args: {app.getPath('userData'),process.env.MOTRIX_BRIDGE_DATA_DIR)- // pairing.json lives under bridge/ alongside its siblings (registry.json,- // endpoint.json, receiver/) rather than at the userData root, so the whole- // bridge subsystem state is grouped in one place.- const pairingStore = new FilePairingStore(join(dataDir, 'pairing.json'))- const registryStore = new FileRegistryStoreAdapter(- join(dataDir, 'registry.json')- )+ await mkdir(dataDir, { recursive: true })+ const ownership = new BridgeOwnership()+ try {+ // This is the first bridge-state acquisition. No store is loaded and no+ // listener is constructed until the process owns the entire data root.+ const dataDirLock = await acquireBridgeDataDirLock(dataDir, {+ recoverExisting: args.bridgeDataDirLockRecoveryAuthority,+ })+ // BridgeOwnership disposes in reverse order, so registering the lock first+ // keeps it held until every listener, callback and persistence queue drains.+ ownership.own('bridge-data-dir-lock', () => dataDirLock.release())+ await recoverExtensionPairingProjectionWriterLock(+ join(dataDir, 'extension-pairings.json'),+ dataDirLock+ )+ // pairing.json lives under bridge/ alongside its siblings (registry.json,+ // endpoint.json, receiver/) rather than at the userData root, so the whole+ // bridge subsystem state is grouped in one place.+ const pairingStore = new FilePairingStore(join(dataDir, 'pairing.json'))+ const registryStore = new FileRegistryStoreAdapter(+ join(dataDir, 'registry.json')+ )- const pairing = new PairingService(pairingStore)- await pairing.load()+ const pairing = new PairingService(pairingStore)+ await pairing.load()- const devTrusted = parseDevTrustedExtensions(- process.env.MOTRIX_DEV_TRUSTED_EXTENSIONS- )- // Computed from the immutable arrays BEFORE they enter the registry:- // `isOfficialId` must never read `TrustedExtensionRegistry`, which also- // admits `user-added`/`imported` entries (§5, spec-coverage audit W1).- const officialEntries = [...BUILTIN_TRUSTED, ...devTrusted]- const isOfficialId = resolveOfficialIds(officialEntries)- const registry = new TrustedExtensionRegistry(registryStore, officialEntries)- await registry.load()-- const bus = new BridgeEventBus()- const dialog = new PairingDialogController(bus, args.getMainWindow)- // Device-code pairing for cli/agent clients (Spec 7b): the HTTP routes call- // request()/poll(); the renderer ResolvePair handler calls approve()/deny().- // onLifecycle re-emits the SAME settled/expired events the extension's- // PairingDialogController emits directly, so the renderer's approval inbox- // sees one lifecycle shape regardless of which pairing kind moved.- const deviceCode = new DeviceCodeService(pairing, {- onLifecycle: {- settled: (requestId, outcome) =>- bus.emitPairRequestSettled({- key: pairRequestKey({ kind: 'cli', requestId }),- outcome,- }),- expired: (requestId) =>- bus.emitPairRequestExpired({- key: pairRequestKey({ kind: 'cli', requestId }),- }),- },- })+ const devTrusted = parseDevTrustedExtensions(+ process.env.MOTRIX_DEV_TRUSTED_EXTENSIONS+ )+ const identityResolver = createExtensionIdentityResolver({+ // `app.isPackaged` is authoritative for shipped builds. The NODE_ENV+ // check also closes an unpackaged production build: an env-provided dev+ // id never reaches the official tier in either production shape.+ environment:+ app.isPackaged || process.env.NODE_ENV === 'production'+ ? 'production'+ : 'non-production',+ developmentEntries: devTrusted,+ })+ // The resolver owns immutable official inputs and never reads the registry,+ // whose persisted user-added/imported entries therefore cannot raise trust.+ const registry = new TrustedExtensionRegistry(registryStore, [+ ...identityResolver.officialEntries,+ ])+ await registry.load()++ const bus = new BridgeEventBus()+ const dialog = new PairingDialogController(bus, args.getMainWindow)+ // Device-code pairing for cli/agent clients (Spec 7b): the HTTP routes call+ // request()/poll(); the renderer ResolvePair handler calls approve()/deny().+ // onLifecycle re-emits the same renderer lifecycle DTOs as the extension+ // prompt adapter, so the approval inbox sees one shape across pairing kinds.+ const deviceCode = new DeviceCodeService(pairing, {+ onLifecycle: {+ settled: (requestId, outcome) =>+ bus.emitPairRequestSettled({+ key: pairRequestKey({ kind: 'cli', requestId }),+ outcome,+ }),+ expired: (requestId) =>+ bus.emitPairRequestExpired({+ key: pairRequestKey({ kind: 'cli', requestId }),+ }),+ },+ })- // Forward bus events to the renderer. The webContents lookup is deferred- // (called per-event) so that window-recreation paths see the current window.- const forwardToRenderer = (channel: string, payload: unknown) => {- const win = args.getMainWindow()- win?.webContents.send(channel, payload)- }- bus.on('PairRequested', (p) => {- forwardToRenderer(BridgeEvents.PairRequested, p)- // #1: a device-code (cli) prompt has no PairingDialogController, so surface- // the window here — the same restore()/focus() the extension flow does.- if ((p as PairRequestPayload).kind === 'cli') {+ // Forward bus events to the renderer. The webContents lookup is deferred+ // (called per-event) so that window-recreation paths see the current window.+ const forwardToRenderer = (channel: string, payload: unknown) => {const win = args.getMainWindow()- if (win) {- if (win.isMinimized()) win.restore()- win.focus()- }+ win?.webContents.send(channel, payload)}- })- bus.on('Paired', (p) => forwardToRenderer(BridgeEvents.Paired, p))- bus.on('Revoked', (p) => forwardToRenderer(BridgeEvents.Revoked, p))- bus.on('Error', (p) => forwardToRenderer(BridgeEvents.Error, p))- // Pending pair request lifecycle (pending -> settled | expired) — drives the- // approval inbox's live countdown/removal on the renderer side.- bus.on('PairRequestSettled', (p) =>- forwardToRenderer(BridgeEvents.PairRequestSettled, p)- )- bus.on('PairRequestExpired', (p) =>- forwardToRenderer(BridgeEvents.PairRequestExpired, p)- )-- // ─── bridge receiver (subsystem ③) ───────────────────- // Constructed BEFORE WebSocketBridgeServer so that setHandlers() can- // reference receiver before server.start() is called — eliminating the- // race window where the server is listening but handlers aren't registered.- const receiverDataDir = join(dataDir, 'receiver')- const t = i18n.t.bind(i18n)- const localize = (code: string) =>- t(`bridge.receiver.error.${camelize(code)}`)-- // Build the resolver once — shared between BridgeReceiver (extension submit-- // path) and the BridgeRuntime surface (desktop Add-Task path). A single- // instance ensures both paths see the same plugin registry state.- const resolveToMuxFn = makeResolveToMux(args.pluginRegistry, args.pluginHost)- const ownership = new BridgeOwnership()+ bus.on('PairRequested', (p) => {+ forwardToRenderer(BridgeEvents.PairRequested, p)+ // #1: a device-code (cli) prompt has no PairingDialogController, so surface+ // the window here — the same restore()/focus() the extension flow does.+ if ((p as PairRequestPayload).kind === 'cli') {+ const win = args.getMainWindow()+ if (win) {+ if (win.isMinimized()) win.restore()+ win.focus()+ }+ }+ })+ bus.on('Paired', (p) => forwardToRenderer(BridgeEvents.Paired, p))+ bus.on('Revoked', (p) => forwardToRenderer(BridgeEvents.Revoked, p))+ bus.on('Error', (p) => forwardToRenderer(BridgeEvents.Error, p))+ // Pending pair request lifecycle (pending -> settled | expired) — drives the+ // approval inbox's live countdown/removal on the renderer side.+ bus.on('PairRequestSettled', (p) =>+ forwardToRenderer(BridgeEvents.PairRequestSettled, p)+ )+ bus.on('PairRequestExpired', (p) =>+ forwardToRenderer(BridgeEvents.PairRequestExpired, p)+ )- try {+ // ─── bridge receiver (subsystem ③) ───────────────────+ // Constructed BEFORE WebSocketBridgeServer so that setHandlers() can+ // reference receiver before server.start() is called — eliminating the+ // race window where the server is listening but handlers aren't registered.+ const receiverDataDir = join(dataDir, 'receiver')+ const t = i18n.t.bind(i18n)+ const localize = (code: string) =>+ t(`bridge.receiver.error.${camelize(code)}`)++ // Build the resolver once — shared between BridgeReceiver (extension submit-+ // path) and the BridgeRuntime surface (desktop Add-Task path). A single+ // instance ensures both paths see the same plugin registry state.+ const resolveToMuxFn = makeResolveToMux(+ args.pluginRegistry,+ args.pluginHost+ )const receiver = new BridgeReceiver({dataDir: receiverDataDir,defaultSaveDir: args.defaultSaveDir,@@ -597,6 +589,12 @@ export async function bootstrapBridge(args: {const credentials = await Mbp1CredentialStore.load(join(dataDir, 'mbp1-credentials.json'))+ const extensionPairings = new ExtensionPairingProjectionService(+ new FileExtensionPairingProjectionStore(+ join(dataDir, 'extension-pairings.json')+ )+ )+ await extensionPairings.load()// Storage hygiene only (findForAuth already rejects an expired// provisional on its own) — periodic so an unbounded number of crashed// first-pair attempts cannot accumulate for the life of a long-running@@ -609,8 +607,28 @@ export async function bootstrapBridge(args: {ownership.own('credential-sweep', () => {clearInterval(sweepTimer)})+ ownership.own('extension-pairings', () => extensionPairings.stopAndDrain())- const server: WebSocketBridgeServer = new WebSocketBridgeServer({+ let server: WebSocketBridgeServer+ const quarantineProjectionFailure = (+ identity: ClientIdentity & { kind: 'extension' }+ ): void => {+ try {+ const revokeLease = server.beginExtensionRevocation(identity)+ server.retainFailedExtensionRevocation(revokeLease)+ } catch {+ // The fixed operator signal below remains the observable failure. A+ // malformed callback identity must not leak its value or resurrect a+ // session by escaping this quarantine path.+ }+ bus.emitError({+ code: 'extensionProjectionDegraded',+ message:+ 'Extension pairing state could not be updated; access is closed until startup repair.',+ })+ }++ server = new WebSocketBridgeServer({pairing,registry,motrixVersion: args.motrixVersion,@@ -625,24 +643,66 @@ export async function bootstrapBridge(args: {serverGeneration: bridgeIdentity.serverGeneration,appVersion: args.motrixVersion,credentials,- isOfficialId,+ isOfficialId: (browser, id) => identityResolver.isOfficialId(browser, id),queueMbp1Dialog: (req) => dialog.queueMbp1Prompt(req),+ canAdmitExtensionIdentity: (identity) =>+ extensionPairings.canAdmitIdentity(identity),// The only remaining signal that an extension became usable now that- // `motrix/initialize` mints nothing (R18-10): restores the paired-client- // list, RevokePair, and the revoke-kick by feeding the SAME- // `PairingService` bookkeeping the pre-MBP1 extension flow used. The- // token this mints is otherwise inert for an extension identity —- // `resolveBearer` only ever accepts a `cli` token — so its only job is- // list/revoke/kick, exactly as before. Best-effort: a persistence- // failure must not tear down the just-authenticated session.- onExtensionAuthenticated: (identity) => {- void pairing- .issueToken(identity, '')- .then(() => bus.emitPaired({ identity }))- .catch(() => {})+ // `motrix/initialize` mints nothing (R18-10): refresh the extension+ // management projection from the authoritative MBP1 credential set, then+ // emit the paired event. Best-effort: display persistence must not tear+ // down the durable credential, but an unlisted session is not safe to+ // keep usable in this process. Projection failure therefore gates and+ // closes this identity until startup reconciliation can make it visible.+ onExtensionAuthenticated: (identity, credentialId) => {+ try {+ void args+ .trackAsyncWork(async () => {+ const witness =+ await credentials.issueCommittedExtensionWitness(credentialId)+ if (!extensionIdentityMatchesWitness(identity, witness)) {+ throw new Error('authenticated extension identity mismatch')+ }+ await extensionPairings.recordAuthenticated(witness, Date.now())+ bus.emitPaired({ identity })+ })+ .catch(() => quarantineProjectionFailure(identity))+ } catch {+ quarantineProjectionFailure(identity)+ }},})+ // A crash may leave a durable pending-revoke marker after either side of+ // credential deletion. Restore its verified-identity gate and finish the+ // delete before any listener exists. Generic snapshot reconciliation must+ // never infer that a surviving old credential cancels the operator's+ // revoke intent.+ for (const pending of extensionPairings+ .list()+ .filter((record) => record.status === 'cleanup-pending')) {+ const serverLease = server.beginExtensionRevocation(pending.identity)+ const projectionLease = await extensionPairings.prepareIdentityCleanup(+ pending.identity+ )+ try {+ await server.deleteExtensionAuthorization(serverLease, 'user-revoked')+ const absenceWitness =+ await credentials.issueExtensionIdentityAbsenceWitness(+ pending.identity.browser,+ pending.identity.extensionId+ )+ await extensionPairings.completeCleanup(projectionLease, absenceWitness)+ server.completeExtensionRevocation(serverLease)+ } catch {+ server.retainFailedExtensionRevocation(serverLease)+ throw new Error('extension revocation recovery failed')+ }+ }+ await extensionPairings.reconcileCommitted(+ await credentials.issueCommittedExtensionSnapshot()+ )+// Register the shell's domain handlers BEFORE start() — no race window where// the server is listening but handlers aren't yet registered. motrix/initialize// and system/ping are wired by the server itself; the dispatcher validates@@ -701,8 +761,8 @@ export async function bootstrapBridge(args: {ownership.own('stream-source', () => streamSource.detach(args.eventBus))streamSource.attach(args.eventBus)- // An initialize request may be blocked on the renderer's pairing prompt.- // Settle it before server.stop() drains accepted dispatcher work.+ // Abort every code prompt before server.stop() tears down its PairSession,+ // and await code-free terminal event publication during the drain.ownership.own('pairing-dialog', () => dialog.dispose())// Clear every device-code TTL timer so none fires — into a torn-down bus —// after this bridge instance is gone.@@ -754,9 +814,13 @@ export async function bootstrapBridge(args: {installedIpcChannels.push(channel)}- installIpcHandler(BridgeQueries.ListPaired, () =>- pairing.listPaired().map(toPairedClientInfo)- )+ installIpcHandler(BridgeQueries.ListPaired, () => [+ ...extensionPairings.list().map(toPairedClientInfo),+ ...pairing+ .listPaired()+ .filter((entry) => entry.identity.kind === 'cli')+ .map(toPairedClientInfo),+ ])// Merged snapshot: a cli device-code request and an extension /pair// prompt are both "pending pair requests" for the approval inbox — union// them so the renderer sees one list regardless of kind.@@ -770,6 +834,8 @@ export async function bootstrapBridge(args: {(): BridgeStatusInfo => ({port,degraded,+ extensionPairingHealth:+ extensionPairings.getHealth() === 'ready' ? 'ready' : 'degraded',fixedPort: args.bridgeSettings.fixedPort,instanceId: args.bridgeSettings.instanceId,})@@ -779,12 +845,48 @@ export async function bootstrapBridge(args: {async (_e, params: { identity: ClientIdentity }) => {const reason = 'user-revoked'if (params.identity.kind === 'extension') {- // Credential removal is the authorization boundary; it MUST land- // before display bookkeeping is updated or the old mutual key can- // reconnect immediately after the user clicks Revoke.- await server.revokeExtensionAccess(params.identity, reason)+ const extensionIdentity = params.identity+ // This synchronous call MUST precede every snapshot or durable+ // projection await. It immediately de-authorizes live MDXP, cancels+ // pre-auth sessions, and rejects new pair/reconnect attempts.+ const serverLease = server.beginExtensionRevocation(extensionIdentity)+ let markerPersisted = false++ try {+ const cleanupLease =+ await extensionPairings.prepareIdentityCleanup(extensionIdentity)+ markerPersisted = true+ await server.deleteExtensionAuthorization(serverLease, reason)+ const absenceWitness =+ await credentials.issueExtensionIdentityAbsenceWitness(+ extensionIdentity.browser,+ extensionIdentity.extensionId+ )+ await extensionPairings.completeCleanup(+ cleanupLease,+ absenceWitness+ )+ server.completeExtensionRevocation(serverLease)+ } catch {+ // Never infer that persistence failure cancels a user revoke. The+ // identity remains gated and its transport is closed. A durable+ // marker is retried before the next listener; if the marker itself+ // could not be written, the warning explicitly names the restart+ // limitation instead of falsely reporting success.+ server.retainFailedExtensionRevocation(serverLease)+ bus.emitError({+ code: markerPersisted+ ? 'extensionRevocationIncomplete'+ : 'extensionRevocationMarkerFailed',+ message: markerPersisted+ ? 'Extension revocation is incomplete; access remains closed and startup will retry it.'+ : 'Extension revocation could not be recorded; access is closed for this run, but restart may restore the old credential.',+ })+ throw new Error('extension revocation incomplete')+ }+ } else {+ await pairing.revoke(params.identity, reason)}- await pairing.revoke(params.identity, reason)bus.emitRevoked({ identity: params.identity })})@@ -829,9 +931,9 @@ export async function bootstrapBridge(args: {})- // Renderer-side pair-decision command (sent back when user clicks Allow/Deny).- // Discriminated on kind: an extension settles the blocked /pair WebSocket; a- // cli approves/denies a device-code request by its requestId.+ // Renderer-side pair command. A cli explicitly allows/denies a device-code+ // request; an extension action is deny-only because approval is the PAKE+ // code entered in the extension, never a Motrix button.installIpcHandler(BridgeCommands.ResolvePair,async (_e, params: ResolvePairParams): Promise<ResolvePairResult> => {@@ -886,6 +988,7 @@ export async function bootstrapBridge(args: {return {server,pairing,+ extensionPairings,registry,bus,installer,diff --git a/src/main/bridge/pairing-dialog-controller.test.ts b/src/main/bridge/pairing-dialog-controller.test.tsindex 893de476..3437f31d 100644--- a/src/main/bridge/pairing-dialog-controller.test.ts+++ b/src/main/bridge/pairing-dialog-controller.test.ts@@ -1,7 +1,12 @@import { BridgeEventBus } from '@core/bridge/bridge-event-bus'import type { PairDialogRequest } from '@core/bridge/mbp1/pair-session'+import type {+ PairingPromptEnqueueResult,+ PairingPromptHandle,+} from '@core/bridge/pairing-prompt-controller'import { pairRequestKey } from '@shared/protocol/bridge'-import { describe, expect, it, vi } from 'vitest'+import type { BrowserWindow } from 'electron'+import { afterEach, describe, expect, it, vi } from 'vitest'import { PairingDialogController } from './pairing-dialog-controller'const REQ: PairDialogRequest = {@@ -13,23 +18,65 @@ const REQ: PairDialogRequest = {verifiedOrigin: 'chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',}-function makeController() {+function accepted(result: PairingPromptEnqueueResult): PairingPromptHandle {+ if (!result.ok) {+ throw new Error(`expected prompt, got ${result.reason}`)+ }+ return result.handle+}++function request(+ overrides: Partial<PairDialogRequest> = {}+): PairDialogRequest {+ return { ...REQ, ...overrides }+}++function extensionKey(req: PairDialogRequest = REQ): string {+ return pairRequestKey({+ kind: 'extension',+ pairingNonce: req.pairingNonce,+ extensionId: req.claimedExtensionId,+ browser: req.browser,+ })+}++function makeController(+ getMainWindow: () => BrowserWindow | null = () => null+) {const bus = new BridgeEventBus()const requested: unknown[] = []const settled: unknown[] = []const expired: unknown[] = []- bus.on('PairRequested', (p) => requested.push(p))- bus.on('PairRequestSettled', (p) => settled.push(p))- bus.on('PairRequestExpired', (p) => expired.push(p))- const ctrl = new PairingDialogController(bus, () => null)- return { ctrl, bus, requested, settled, expired }+ bus.on('PairRequested', (payload) => requested.push(payload))+ bus.on('PairRequestSettled', (payload) => settled.push(payload))+ bus.on('PairRequestExpired', (payload) => expired.push(payload))+ const controller = new PairingDialogController(bus, getMainWindow)+ return { controller, bus, requested, settled, expired }}-describe('PairingDialogController.queueMbp1Prompt', () => {- it('emits PairRequested with the code+identity payload and no self-reported name', () => {- const { ctrl, requested } = makeController()+async function queue(+ controller: PairingDialogController,+ req: PairDialogRequest = REQ+): Promise<PairingPromptHandle> {+ const handle = accepted(controller.queueMbp1Prompt(req))+ await expect(handle.published).resolves.toBe('delivered')+ return handle+}++afterEach(() => {+ vi.useRealTimers()+})- ctrl.queueMbp1Prompt(REQ)+describe('PairingDialogController shell projection', () => {+ it('publishes the existing renderer payload and focuses a restored window', async () => {+ const window = {+ isMinimized: vi.fn(() => true),+ restore: vi.fn(),+ focus: vi.fn(),+ } as unknown as BrowserWindow+ const { controller, requested } = makeController(() => window)++ await queue(controller)expect(requested).toEqual([{@@ -41,239 +88,251 @@ describe('PairingDialogController.queueMbp1Prompt', () => {code: REQ.code,},])+ expect(window.isMinimized()).toBe(true)+ expect(window.restore).toHaveBeenCalledOnce()+ expect(window.focus).toHaveBeenCalledOnce()})- it('returns a handle whose dismissed resolves when the session confirms and closes it', async () => {- const { ctrl } = makeController()- const handle = ctrl.queueMbp1Prompt(REQ)- let resolved = false- void handle.dismissed.then(() => {- resolved = true- })-- expect(resolved).toBe(false)- handle.close()- await handle.dismissed-- expect(resolved).toBe(true)+ it('keeps an emitted code delivered when Electron focus operations fail', async () => {+ const window = {+ isMinimized: vi.fn(() => true),+ restore: vi.fn(() => {+ throw new Error('window restore unavailable')+ }),+ focus: vi.fn(() => {+ throw new Error('window focus unavailable')+ }),+ } as unknown as BrowserWindow+ const { controller, requested } = makeController(() => window)++ const handle = accepted(controller.queueMbp1Prompt(REQ))++ await expect(handle.published).resolves.toBe('delivered')+ expect(requested).toHaveLength(1)+ expect(window.restore).toHaveBeenCalledOnce()+ expect(window.focus).toHaveBeenCalledOnce()})- it('close() is idempotent — a second call is a no-op', async () => {- const { ctrl, expired } = makeController()- const handle = ctrl.queueMbp1Prompt(REQ)+ it('projects only the code-bearing prompt and snapshot channels', async () => {+ const { controller, settled, expired } = makeController()+ const handle = await queue(controller)++ expect(controller.listPending()).toEqual([+ expect.objectContaining({+ kind: 'extension',+ pairingNonce: REQ.pairingNonce,+ extensionId: REQ.claimedExtensionId,+ browser: REQ.browser,+ identity: REQ.identity,+ code: REQ.code,+ }),+ ])- handle.close()- handle.close()- await handle.dismissed+ handle.settle('aborted')+ await handle.terminal+ await Promise.resolve()- expect(expired).toHaveLength(1)+ expect(controller.listPending()).toEqual([])+ expect(JSON.stringify([...settled, ...expired])).not.toContain(REQ.code)})+})- it('close() emits PairRequestExpired, never PairRequestSettled — a machine-side teardown is not a user denial', async () => {- const { ctrl, settled, expired } = makeController()- const handle = ctrl.queueMbp1Prompt(REQ)- const key = pairRequestKey({- kind: 'extension',+describe('PairingDialogController terminal mapping', () => {+ it('maps a real operator dismiss to denied exactly once', async () => {+ const { controller, settled, expired } = makeController()+ const handle = await queue(controller)+ const params = {+ kind: 'extension' as const,pairingNonce: REQ.pairingNonce,extensionId: REQ.claimedExtensionId,browser: REQ.browser,- })+ }- handle.close()- await handle.dismissed+ expect(controller.settle(params)).toEqual({ ok: true })+ expect(controller.settle(params)).toEqual({+ ok: false,+ reason: 'unavailable',+ })+ await expect(handle.terminal).resolves.toBe('denied')+ await Promise.resolve()- expect(expired).toEqual([{ key }])- expect(settled).toHaveLength(0)+ expect(settled).toEqual([{ key: extensionKey(), outcome: 'denied' }])+ expect(expired).toEqual([])})- it('auto-closes after the 120s code lifetime and emits PairRequestExpired', async () => {+ it.each([+ ['paired', 'allowed'],+ ['aborted', 'aborted'],+ ] as const)(+ 'maps a session-owned %s outcome to renderer %s',+ async (outcome, rendererOutcome) => {+ const { controller, settled, expired } = makeController()+ const handle = await queue(controller)++ expect(handle.settle(outcome)).toEqual({ ok: true, outcome })+ await expect(handle.terminal).resolves.toBe(outcome)+ await Promise.resolve()++ expect(settled).toEqual([+ { key: extensionKey(), outcome: rendererOutcome },+ ])+ expect(expired).toEqual([])+ }+ )++ it('maps the core TTL to expiry and makes a late operator action unavailable', async () => {vi.useFakeTimers()- const { ctrl, expired } = makeController()- const handle = ctrl.queueMbp1Prompt(REQ)- let resolved = false- void handle.dismissed.then(() => {- resolved = true- })+ const { controller, settled, expired } = makeController()+ const handle = await queue(controller)- vi.advanceTimersByTime(119_999)- expect(resolved).toBe(false)- vi.advanceTimersByTime(2)- await Promise.resolve()+ await vi.advanceTimersByTimeAsync(120_000)++ await expect(handle.terminal).resolves.toBe('expired')+ expect(+ controller.settle({+ kind: 'extension',+ pairingNonce: REQ.pairingNonce,+ extensionId: REQ.claimedExtensionId,+ browser: REQ.browser,+ })+ ).toEqual({ ok: false, reason: 'unavailable' })+ expect(settled).toEqual([])+ expect(expired).toEqual([{ key: extensionKey() }])+ })++ it('maps adapter disposal to aborted and drains terminal publication', async () => {+ const { controller, settled, expired } = makeController()+ const handle = await queue(controller)- expect(resolved).toBe(true)- expect(expired).toHaveLength(1)- vi.useRealTimers()+ await controller.dispose()++ await expect(handle.terminal).resolves.toBe('aborted')+ expect(settled).toEqual([{ key: extensionKey(), outcome: 'aborted' }])+ expect(expired).toEqual([])+ expect(controller.listPending()).toEqual([])})- it('dedups on the verified origin — a second attempt while one is live returns an already-dismissed handle and emits nothing new', () => {- const { ctrl, requested } = makeController()- ctrl.queueMbp1Prompt(REQ)+ it('returns unavailable for an unknown request without emitting', () => {+ const { controller, settled, expired } = makeController()- const second = ctrl.queueMbp1Prompt({ ...REQ, pairingNonce: 'nonce-2' })+ expect(+ controller.settle({+ kind: 'extension',+ pairingNonce: 'never-requested',+ extensionId: REQ.claimedExtensionId,+ browser: REQ.browser,+ })+ ).toEqual({ ok: false, reason: 'unavailable' })+ expect(settled).toEqual([])+ expect(expired).toEqual([])+ })+})+describe('PairingDialogController admission projection', () => {+ it('delegates verified-Origin dedup to core', async () => {+ const { controller, requested } = makeController()+ await queue(controller)++ expect(+ controller.queueMbp1Prompt(+ request({+ pairingNonce: 'nonce-2',+ claimedExtensionId: 'attacker-self-report',+ })+ )+ ).toEqual({ ok: false, reason: 'duplicate' })expect(requested).toHaveLength(1)- return expect(second.dismissed).resolves.toBeUndefined()})- it('never suppresses one extension by another claiming its id — dedup is NOT keyed on claimedExtensionId', () => {- // Regression: on Firefox the claimed id is self-reported, so keying dedup- // on it would let an attacker extension suppress a legitimate one simply- // by claiming the same id. Two different verified origins claiming the- // SAME id must both get a live prompt.- const { ctrl, requested } = makeController()- ctrl.queueMbp1Prompt({- ...REQ,+ it('does not dedup different verified Firefox origins with the same claim', async () => {+ const { controller, requested } = makeController()+ const first = request({browser: 'firefox',verifiedOrigin: 'moz-extension://11111111-1111-1111-1111-111111111111',})-- ctrl.queueMbp1Prompt({- ...REQ,+ const second = request({browser: 'firefox',pairingNonce: 'nonce-2',verifiedOrigin: 'moz-extension://22222222-2222-2222-2222-222222222222',})- expect(requested).toHaveLength(2)- })-- it('clears dedup once the live prompt settles by any outcome, admitting a fresh attempt from the same origin', async () => {- const { ctrl, requested } = makeController()- const first = ctrl.queueMbp1Prompt(REQ)-- first.close()- await first.dismissed-- const second = ctrl.queueMbp1Prompt({ ...REQ, pairingNonce: 'nonce-2' })+ await queue(controller, first)+ await queue(controller, second)expect(requested).toHaveLength(2)- expect(second.dismissed).not.toBe(first.dismissed)})-})-describe('PairingDialogController.settle', () => {- it('resolves the pending handle (dismiss), removes it from pending, and emits PairRequestExpired', async () => {- const { ctrl, expired } = makeController()- const handle = ctrl.queueMbp1Prompt(REQ)- let resolved = false- void handle.dismissed.then(() => {- resolved = true+ it('enforces the core global capacity without publishing a fourth code', async () => {+ const { controller, requested } = makeController()+ for (let index = 0; index < 3; index += 1) {+ const extensionId = `${index}`.repeat(32)+ await queue(+ controller,+ request({+ pairingNonce: `nonce-${index}`,+ claimedExtensionId: extensionId,+ verifiedOrigin: `chrome-extension://${extensionId}`,+ })+ )+ }+ const fourth = request({+ pairingNonce: 'nonce-4',+ claimedExtensionId: 'dddddddddddddddddddddddddddddddd',+ verifiedOrigin: 'chrome-extension://dddddddddddddddddddddddddddddddd',})- const result = ctrl.settle({- kind: 'extension',- pairingNonce: REQ.pairingNonce,- extensionId: REQ.claimedExtensionId,- browser: REQ.browser,+ expect(controller.queueMbp1Prompt(fourth)).toEqual({+ ok: false,+ reason: 'capacity',})-- expect(result).toEqual({ ok: true })- await handle.dismissed- expect(resolved).toBe(true)- expect(expired).toHaveLength(1)- expect(ctrl.listPending()).toEqual([])+ expect(requested).toHaveLength(3)})- it('returns unavailable for an unknown key and emits nothing', () => {- const { ctrl, expired } = makeController()-- const result = ctrl.settle({- kind: 'extension',- pairingNonce: 'never-requested',- extensionId: REQ.claimedExtensionId,- browser: REQ.browser,- })-- expect(result).toEqual({ ok: false, reason: 'unavailable' })- expect(expired).toHaveLength(0)- })-- it('duplicate settle is a no-op returning unavailable', () => {- const { ctrl } = makeController()- ctrl.queueMbp1Prompt(REQ)- const params = {- kind: 'extension' as const,- pairingNonce: REQ.pairingNonce,- extensionId: REQ.claimedExtensionId,- browser: REQ.browser,- }-- const first = ctrl.settle(params)- const second = ctrl.settle(params)-- expect(first).toEqual({ ok: true })- expect(second).toEqual({ ok: false, reason: 'unavailable' })- })-- it('re-admits the origin so a re-pair attempt after a user dismiss is not silently suppressed', () => {- const { ctrl, requested } = makeController()- ctrl.queueMbp1Prompt(REQ)- ctrl.settle({+ it('re-admits an Origin after the real denial terminal transition', async () => {+ const { controller, requested } = makeController()+ await queue(controller)+ controller.settle({kind: 'extension',pairingNonce: REQ.pairingNonce,extensionId: REQ.claimedExtensionId,browser: REQ.browser,})- ctrl.queueMbp1Prompt({ ...REQ, pairingNonce: 'nonce-2' })+ await queue(controller, request({ pairingNonce: 'nonce-2' }))expect(requested).toHaveLength(2)})})-describe('PairingDialogController.listPending', () => {- it('reflects add/settle, carrying the pairing code and identity', () => {- vi.useFakeTimers()- const { ctrl } = makeController()-- expect(ctrl.listPending()).toEqual([])-- ctrl.queueMbp1Prompt(REQ)- const list = ctrl.listPending()- expect(list).toHaveLength(1)- expect(list[0]).toMatchObject({- kind: 'extension',- pairingNonce: REQ.pairingNonce,- extensionId: REQ.claimedExtensionId,- browser: REQ.browser,- identity: REQ.identity,- code: REQ.code,+describe('PairingDialogController callback failure containment', () => {+ it('reports failed publication without throwing or stranding the handle', async () => {+ const bus = new BridgeEventBus()+ bus.on('PairRequested', () => {+ throw new Error(`must-not-escape:${REQ.code}`)})- expect(list[0]?.createdAt).toBeTypeOf('number')- expect(list[0]?.expiresAt).toBe((list[0]?.createdAt ?? 0) + 120_000)+ const controller = new PairingDialogController(bus, () => null)+ const handle = accepted(controller.queueMbp1Prompt(REQ))- ctrl.settle({- kind: 'extension',- pairingNonce: REQ.pairingNonce,- extensionId: REQ.claimedExtensionId,- browser: REQ.browser,+ await expect(handle.published).resolves.toBe('failed')+ expect(handle.settle('aborted')).toEqual({+ ok: true,+ outcome: 'aborted',})- expect(ctrl.listPending()).toEqual([])- vi.useRealTimers()+ await expect(handle.terminal).resolves.toBe('aborted')+ await expect(controller.dispose()).resolves.toBeUndefined()})-})-describe('PairingDialogController.dispose', () => {- it('settles every pending dismissed and emits PairRequestExpired per entry, so a blocked session cannot await forever across a restart', async () => {- const { ctrl, expired } = makeController()- const other: PairDialogRequest = {- ...REQ,- claimedExtensionId: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',- pairingNonce: 'nonce-2',- verifiedOrigin: 'chrome-extension://bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',- }- const h1 = ctrl.queueMbp1Prompt(REQ)- const h2 = ctrl.queueMbp1Prompt(other)-- ctrl.dispose()-- await Promise.all([h1.dismissed, h2.dismissed])- expect(expired).toHaveLength(2)- expect(ctrl.listPending()).toEqual([])- })+ it('drains disposal even when a terminal renderer callback throws', async () => {+ const bus = new BridgeEventBus()+ bus.on('PairRequestSettled', () => {+ throw new Error('renderer unavailable')+ })+ const controller = new PairingDialogController(bus, () => null)+ const handle = accepted(controller.queueMbp1Prompt(REQ))+ await handle.published- it('dispose() is safe with no pending prompts', () => {- const { ctrl } = makeController()- expect(() => ctrl.dispose()).not.toThrow()+ await expect(controller.dispose()).resolves.toBeUndefined()+ await expect(handle.terminal).resolves.toBe('aborted')+ expect(controller.listPending()).toEqual([])})})diff --git a/src/main/bridge/pairing-dialog-controller.ts b/src/main/bridge/pairing-dialog-controller.tsindex 62a5f5dd..2beacf88 100644--- a/src/main/bridge/pairing-dialog-controller.ts+++ b/src/main/bridge/pairing-dialog-controller.ts@@ -1,9 +1,13 @@import type { BridgeEventBus } from '@core/bridge/bridge-event-bus'import type { IdentityTriState as CoreIdentityTriState } from '@core/bridge/credential-store'-import type {- PairDialogHandle,- PairDialogRequest,-} from '@core/bridge/mbp1/pair-session'+import type { PairDialogRequest } from '@core/bridge/mbp1/pair-session'+import {+ type PairingPromptCallbackReceipt,+ PairingPromptController,+ type PairingPromptEnqueueResult,+ type PairingPromptSnapshot,+ type PairingPromptTerminalEvent,+} from '@core/bridge/pairing-prompt-controller'import {type PendingPairRequestInfo,pairRequestKey,@@ -13,14 +17,8 @@ import {} from '@shared/protocol/bridge'import type { BrowserWindow } from 'electron'-// Drift guard (progress.md:155): `SharedIdentityTriState` is a renderer-safe-// literal copy of core's `IdentityTriState` — duplicated because the-// renderer must not import `@core/`. This module is the one place that-// assigns a value of one into the other (below, building the renderer-// payload), so the bidirectional assignability check lives here. Never-// called — a real call would need a live `IdentityTriState` value this file-// has no reason to fabricate — so it costs nothing at runtime; its only job-// is that `tsc` rejects it if either union ever widens without the other.+// `SharedIdentityTriState` is a renderer-safe literal copy of core's union.+// This is the one layer that maps between them, so keep the drift guard here.function _assertIdentityTriStateParity(): void {const core: CoreIdentityTriState = null as neverconst shared: SharedIdentityTriState = core@@ -29,157 +27,148 @@ function _assertIdentityTriStateParity(): void {}void _assertIdentityTriStateParity-/** Renderer-safe request metadata for {@link PairingDialogController.listPending},- * minus the createdAt/expiresAt which the entry already tracks separately. */type ExtensionPairRequestPayload = Omit<Extract<PendingPairRequestInfo, { kind: 'extension' }>,'createdAt' | 'expiresAt'>-interface PendingRequest {- payload: ExtensionPairRequestPayload- /** Idempotent teardown: resolves `dismissed`, drops the origin's dedup- * entry, clears the timer, and emits `PairRequestExpired` — but only on- * its FIRST call. Shared by the timeout, an explicit `settle()`, and the- * `PairDialogHandle.close()` a `PairSession` calls on its own teardown, so- * whichever fires first is the one that actually tears down. */- close: () => void- createdAt: number- expiresAt: number-}-/**- * How long the desktop dialog stays open before auto-closing. Matches §7.2's- * pairing-code lifetime (`CODE_LIFETIME_MS` in `mbp1/pair-session.ts`, not- * exported — this is a deliberately independent constant, not a shared one):- * the code the dialog displays stops being usable at exactly this point, so- * there is nothing left to keep the prompt open for.+ * Electron-only projection of the host-neutral prompt controller.+ *+ * Core owns TTL, capacity, verified-Origin dedup, and the terminal state+ * machine. This adapter owns only renderer DTOs, window focus, and the stable+ * renderer key <-> opaque core prompt id mapping. The pairing code crosses+ * this layer only in PairRequested/listPending payloads; terminal events are+ * code-free.*/-const PROMPT_TIMEOUT_MS = 120_000-export class PairingDialogController {- private pending = new Map<string, PendingRequest>()- /**- * Dedup keyed on the verified origin (§5), never on `claimedExtensionId`:- * on Firefox the claimed id is self-reported, so keying on it would let one- * extension suppress another's prompt by claiming its id. Presence means- * "a prompt is currently open for this origin" — cleared the moment that- * prompt settles by ANY outcome (success, dismiss, or timeout), not after a- * cooldown window. There is deliberately no dedup timestamp: a window would- * either be shorter than §7.2's 120s code lifetime (letting a second- * legitimate attempt in) or longer (reintroducing the old "forget + re-pair- * is silently denied" regression, and worse — invisibly, since there is no- * deny event to explain it).- */- private openOrigins = new Set<string>()+ private readonly promptIdsByKey = new Map<string, string>()+ private readonly keysByPromptId = new Map<string, string>()+ private readonly prompts: PairingPromptControllerconstructor(- private bus: BridgeEventBus,- private getMainWindow: () => BrowserWindow | null- ) {}+ private readonly bus: BridgeEventBus,+ private readonly getMainWindow: () => BrowserWindow | null+ ) {+ this.prompts = new PairingPromptController({+ onEnqueued: (snapshot) => this.publish(snapshot),+ onTerminal: (event) => this.publishTerminal(event),+ })+ }++ queueMbp1Prompt(args: PairDialogRequest): PairingPromptEnqueueResult {+ return this.prompts.enqueue(args)+ }/**- * Show the §7.1 approval dialog for a `/pair` session that reached- * `pairHello`. Error-free by construction — §7.3 admission (core's- * `PairFloodControl`) already ran before this is called, so the only- * refusal this method can make is its own per-origin dedup, and it reports- * that as an immediate dismissal (an already-resolved `dismissed`) rather- * than hanging: `PairSession` treats a resolved `dismissed` as a clean user- * dismissal, whereas a handle that never resolves would hold a §7.3- * pending slot for the full 150s pre-auth deadline.+ * The extension operator action is denial only. Approval is still proven by+ * entering the PAKE code in the extension, never by clicking in Motrix.*/- queueMbp1Prompt(args: PairDialogRequest): PairDialogHandle {- if (this.openOrigins.has(args.verifiedOrigin)) {- return { dismissed: Promise.resolve(), close: () => {} }+ settle(+ params: Extract<ResolvePairParams, { kind: 'extension' }>+ ): ResolvePairResult {+ const promptId = this.promptIdsByKey.get(pairRequestKey(params))+ if (promptId === undefined) {+ return { ok: false, reason: 'unavailable' }}- this.openOrigins.add(args.verifiedOrigin)- const payload: ExtensionPairRequestPayload = {- kind: 'extension',- pairingNonce: args.pairingNonce,- extensionId: args.claimedExtensionId,- browser: args.browser,- identity: args.identity,- code: args.code,- }- const key = pairRequestKey(payload)- const createdAt = Date.now()- const expiresAt = createdAt + PROMPT_TIMEOUT_MS+ const result = this.prompts.deny(promptId)+ return result.ok && result.outcome === 'denied'+ ? { ok: true }+ : { ok: false, reason: 'unavailable' }+ }- let resolveDismissed!: () => void- const dismissed = new Promise<void>((resolve) => {- resolveDismissed = resolve- })+ listPending(): PendingPairRequestInfo[] {+ return this.prompts.snapshot().map((snapshot) => ({+ ...this.toPayload(snapshot),+ createdAt: snapshot.createdAt,+ expiresAt: snapshot.expiresAt,+ }))+ }++ /** Abort every live prompt and drain code-free terminal callbacks. */+ dispose(): Promise<void> {+ return this.prompts.dispose()+ }- let closed = false- const close = (): void => {- if (closed) return- closed = true- clearTimeout(timer)- this.pending.delete(key)- this.openOrigins.delete(args.verifiedOrigin)- resolveDismissed()- // A machine-side teardown (session confirmed, session aborted, or this- // prompt's own timeout) is never a user denial — `denied` must mean the- // user denied and nothing else, or the approval inbox would lie about- // why a prompt disappeared. The renderer already treats `expired` as- // "remove this entry", regardless of which of those three caused it.- this.bus.emitPairRequestExpired({ key })+ private publish(+ snapshot: PairingPromptSnapshot+ ): PairingPromptCallbackReceipt {+ const payload = this.toPayload(snapshot)+ const key = pairRequestKey(payload)+ if (+ this.promptIdsByKey.has(key) ||+ this.keysByPromptId.has(snapshot.promptId)+ ) {+ throw new Error('pairing prompt adapter key collision')}- const timer = setTimeout(close, PROMPT_TIMEOUT_MS)- this.pending.set(key, { payload, close, createdAt, expiresAt })+ this.promptIdsByKey.set(key, snapshot.promptId)+ this.keysByPromptId.set(snapshot.promptId, key)this.bus.emitPairRequested(payload)- const win = this.getMainWindow()- if (win) {++ // Delivery commits at the synchronous renderer event above. Window+ // ergonomics are best-effort and must never turn an already-visible code+ // into `failed` (which would abort PairSession and undercount flood+ // control). Each Electron call is isolated so one broken operation does+ // not suppress the others.+ let win: BrowserWindow | null+ try {+ win = this.getMainWindow()+ } catch {+ return 'delivered'+ }+ if (win === null) return 'delivered'+ try {if (win.isMinimized()) win.restore()+ } catch {+ // The renderer event is already committed; focus remains worth trying.+ }+ try {win.focus()+ } catch {+ // Best-effort window focus is outside the publication receipt boundary.}-- return { dismissed, close }+ return 'delivered'}- /**- * Explicit dismiss path for the renderer's ResolvePair command (the user- * closed the prompt). Under MBP1 there is no allow/deny decision to make- * here — approval is proven by typing the code into the extension, not by- * a click in this dialog — so this only resolves the pending `dismissed`- * promise, which `PairSession` observes as an abort. An unknown key —- * already settled, already expired, or never requested — returns- * `{ ok: false, reason: 'unavailable' }` and emits nothing: this method- * must NEVER report apparent success for a request that didn't actually- * land anywhere (a duplicate settle call is therefore a no-op on the- * second call).- */- settle(- params: Extract<ResolvePairParams, { kind: 'extension' }>- ): ResolvePairResult {- const key = pairRequestKey(params)- const p = this.pending.get(key)- if (!p) return { ok: false, reason: 'unavailable' }- p.close()- return { ok: true }- }+ private publishTerminal(+ event: PairingPromptTerminalEvent+ ): PairingPromptCallbackReceipt {+ const key = this.keysByPromptId.get(event.promptId)+ if (key === undefined) {+ return 'delivered'+ }+ this.keysByPromptId.delete(event.promptId)+ this.promptIdsByKey.delete(key)- /** Snapshot of every currently-pending extension `/pair` prompt, for the- * approval inbox. Renderer-safe: token-free by construction, and the- * pairing code is never logged (§7.1) — only ever sent to the renderer. */- listPending(): PendingPairRequestInfo[] {- return [...this.pending.values()].map((p) => ({- ...p.payload,- createdAt: p.createdAt,- expiresAt: p.expiresAt,- }))+ switch (event.outcome) {+ case 'paired':+ this.bus.emitPairRequestSettled({ key, outcome: 'allowed' })+ break+ case 'denied':+ this.bus.emitPairRequestSettled({ key, outcome: 'denied' })+ break+ case 'expired':+ this.bus.emitPairRequestExpired({ key })+ break+ case 'aborted':+ this.bus.emitPairRequestSettled({ key, outcome: 'aborted' })+ break+ }+ return 'delivered'}- /** Settle every pending prompt before the bridge request drain begins, so- * no `PairSession` awaits a `dismissed` that will never resolve across a- * bridge restart. */- dispose(): void {- for (const pending of [...this.pending.values()]) {- pending.close()+ private toPayload(+ snapshot: PairingPromptSnapshot+ ): ExtensionPairRequestPayload {+ return {+ kind: 'extension',+ pairingNonce: snapshot.pairingNonce,+ extensionId: snapshot.claimedExtensionId,+ browser: snapshot.verifiedIdentity.browser,+ identity: snapshot.identity,+ code: snapshot.code,}- this.pending.clear()- this.openOrigins.clear()}}diff --git a/src/main/bridge/parse-dev-trusted-extensions.test.ts b/src/main/bridge/parse-dev-trusted-extensions.test.tsindex 6e23273d..3f610800 100644--- a/src/main/bridge/parse-dev-trusted-extensions.test.ts+++ b/src/main/bridge/parse-dev-trusted-extensions.test.ts@@ -1,5 +1,5 @@+import { parseDevTrustedExtensions } from '@core/bridge/extension-identity-resolver'import { describe, expect, it } from 'vitest'-import { parseDevTrustedExtensions } from './index'describe('parseDevTrustedExtensions', () => {it('returns an empty list when env var is unset', () => {diff --git a/src/main/bridge/resolve-official-ids.test.ts b/src/main/bridge/resolve-official-ids.test.tsdeleted file mode 100644index db6f616f..00000000--- a/src/main/bridge/resolve-official-ids.test.ts+++ /dev/null@@ -1,30 +0,0 @@-import { describe, expect, it } from 'vitest'-import { resolveOfficialIds } from './index'--describe('resolveOfficialIds', () => {- it('returns true only for an id+browser pair in the allowlist', () => {- const isOfficialId = resolveOfficialIds([- { id: 'aaa', browser: 'chromium' },- { id: 'b@c', browser: 'firefox' },- ])-- expect(isOfficialId('chromium', 'aaa')).toBe(true)- expect(isOfficialId('firefox', 'b@c')).toBe(true)- expect(isOfficialId('chromium', 'unknown')).toBe(false)- })-- it('does not cross browsers — the same id under a different browser is not official', () => {- const isOfficialId = resolveOfficialIds([- { id: 'aaa', browser: 'chromium' },- ])-- expect(isOfficialId('firefox', 'aaa')).toBe(false)- })-- it('returns false for every id against an empty allowlist', () => {- const isOfficialId = resolveOfficialIds([])-- expect(isOfficialId('chromium', 'aaa')).toBe(false)- expect(isOfficialId('firefox', 'b@c')).toBe(false)- })-})diff --git a/src/main/index.ts b/src/main/index.tsindex db13863e..1d8f83df 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -2198,6 +2198,11 @@ async function initializeMainProcess(): Promise<void> {shell,getTask: (taskId) => taskManager.getById(taskId),})+ const bridgeDataDirLockRecoveryAuthority =+ launcher.bridgeDataDirLockRecoveryAuthority+ if (bridgeDataDirLockRecoveryAuthority === null) {+ throw new Error('bridge single-instance ownership unavailable')+ }// mediaTmpDir / mediaTmpRoot were computed once at bootstrap (above) so// SessionManager.restore() and the poll loop share the exact same root.return bootstrapBridge({@@ -2209,6 +2214,7 @@ async function initializeMainProcess(): Promise<void> {// BridgeManager.restart()), so a `bridge.fixedPort`/`instanceId` change// takes effect without a full app restart.bridgeSettings: settingsManager.get().bridge,+ bridgeDataDirLockRecoveryAuthority,eventBus,createTaskDeps,activityRecorder: activeTaskActivityService,diff --git a/src/main/launcher.test.ts b/src/main/launcher.test.tsindex 70edf0ea..d8bdea51 100644--- a/src/main/launcher.test.ts+++ b/src/main/launcher.test.ts@@ -51,14 +51,32 @@ describe('setupLauncher', () => {it('exits immediately if lock not acquired', () => {mockRequestLock.mockReturnValue(false)- setupLauncher(callbacks)+ const handle = setupLauncher(callbacks)expect(mockExit).toHaveBeenCalledWith(0)+ expect(handle.bridgeDataDirLockRecoveryAuthority).toBeNull()+ expect(mockOn).not.toHaveBeenCalled()})it('returns handle with wasOpenedAtLogin and flushDeferred', () => {const handle = setupLauncher(callbacks)expect(typeof handle.wasOpenedAtLogin).toBe('boolean')expect(typeof handle.flushDeferred).toBe('function')+ expect(handle.bridgeDataDirLockRecoveryAuthority).toEqual({+ ownershipEpoch: expect.stringMatching(/^[A-Za-z0-9_-]{43}$/u),+ assertExclusiveProcessOwnership: expect.any(Function),+ })+ expect(+ handle.bridgeDataDirLockRecoveryAuthority?.assertExclusiveProcessOwnership()+ ).toBe(true)+ })++ it('creates a fresh recovery epoch for each successful process ownership session', () => {+ const first = setupLauncher(callbacks)+ const second = setupLauncher(callbacks)++ expect(first.bridgeDataDirLockRecoveryAuthority?.ownershipEpoch).not.toBe(+ second.bridgeDataDirLockRecoveryAuthority?.ownershipEpoch+ )})it('detects wasOpenedAtLogin on macOS', () => {diff --git a/src/main/launcher.ts b/src/main/launcher.tsindex c7310706..05177a49 100644--- a/src/main/launcher.ts+++ b/src/main/launcher.ts@@ -1,3 +1,5 @@+import { randomBytes } from 'node:crypto'+import type { BridgeDataDirLockRecoveryAuthority } from '@core/bridge/bridge-data-dir-lock'import { getLogger } from '@core/logger'import { app } from 'electron'@@ -9,6 +11,8 @@ export interface LauncherCallbacks {export interface LauncherHandle {wasOpenedAtLogin: boolean+ /** OS-level process ownership proof used only for bridge crash recovery. */+ bridgeDataDirLockRecoveryAuthority: BridgeDataDirLockRecoveryAuthority | nullflushDeferred: () => void}@@ -47,8 +51,23 @@ export function setupLauncher(callbacks: LauncherCallbacks): LauncherHandle {if (!gotLock) {log.info('another instance is running, exiting')app.exit(0)+ return {+ wasOpenedAtLogin: false,+ bridgeDataDirLockRecoveryAuthority: null,+ flushDeferred: () => undefined,+ }}+ // One unpredictable epoch for this successful Electron single-instance+ // ownership session. A restarted process receives a different epoch, which+ // lets the bridge distinguish crash residue from its own still-live handle.+ const ownershipEpoch = randomBytes(32).toString('base64url')+ const bridgeDataDirLockRecoveryAuthority: BridgeDataDirLockRecoveryAuthority =+ Object.freeze({+ ownershipEpoch,+ assertExclusiveProcessOwnership: () => true,+ })+// Detect login launchlet wasOpenedAtLogin = falseif (process.platform === 'darwin') {@@ -121,6 +140,7 @@ export function setupLauncher(callbacks: LauncherCallbacks): LauncherHandle {return {wasOpenedAtLogin,+ bridgeDataDirLockRecoveryAuthority,flushDeferred() {flushed = truefor (const url of pendingUrls) {diff --git a/src/renderer/routes/settings/cards/integration/browser-extensions-section.tsx b/src/renderer/routes/settings/cards/integration/browser-extensions-section.tsxindex da8733b0..45882103 100644--- a/src/renderer/routes/settings/cards/integration/browser-extensions-section.tsx+++ b/src/renderer/routes/settings/cards/integration/browser-extensions-section.tsx@@ -22,6 +22,13 @@ import type { IntegrationFormValues } from './integration-dialog'import { TrustedExtensionsSection } from './trusted-extensions-section'import { useBridgeStatus, usePairedExtensions } from './use-bridge'+const IDENTITY_LABEL_KEYS = {+ official: 'settings.integration.browser.pairToast.identityLabel.official',+ 'attested-non-official':+ 'settings.integration.browser.pairToast.identityLabel.attested',+ unverified: 'settings.integration.browser.pairToast.identityLabel.unverified',+} as const+export function BrowserExtensionsSection() {const { t } = useTranslation()const form = useFormContext<IntegrationFormValues>()@@ -71,6 +78,18 @@ export function BrowserExtensionsSection() {</Alert>)}+ {status?.extensionPairingHealth === 'degraded' && (+ <Alert className="border-destructive/30 bg-destructive/10 px-3 py-2 text-[11px] leading-4 text-destructive">+ <TriangleAlertIcon />+ <AlertTitle>+ {t('settings.integration.browser.pairingStateDegraded.title')}+ </AlertTitle>+ <AlertDescription className="text-destructive/80">+ {t('settings.integration.browser.pairingStateDegraded.description')}+ </AlertDescription>+ </Alert>+ )}+<divclassName={cn('space-y-2',@@ -97,6 +116,7 @@ export function BrowserExtensionsSection() {<span className="font-mono">{it.name || it.id}</span><span className="text-muted-foreground">{browserDisplayName(it.browser)}+ {` · ${t(IDENTITY_LABEL_KEYS[it.identityTrust])}`}{it.lastActiveAt? ` · ${t('settings.integration.browser.lastActive')}: ${new Date(it.lastActiveAt).toLocaleString()}`: ''}@@ -113,8 +133,13 @@ export function BrowserExtensionsSection() {extensionId: it.id,})}+ disabled={it.status === 'cleanup-pending'}>- {t('settings.integration.browser.revoke')}+ {t(+ it.status === 'cleanup-pending'+ ? 'settings.integration.browser.disconnecting'+ : 'settings.integration.browser.revoke'+ )}</Button></div>))diff --git a/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsx b/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsxindex ddef927f..93c2a2e4 100644--- a/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsx+++ b/src/renderer/routes/settings/cards/integration/integration-dialog.test.tsx@@ -16,6 +16,7 @@ const bridgeStatus = vi.hoisted(() => ({current: {port: 16802,degraded: false,+ extensionPairingHealth: 'ready' as 'ready' | 'degraded',fixedPort: 'auto' as const,instanceId: 'test-instance',},@@ -102,6 +103,7 @@ describe('IntegrationDialog scaffold', () => {bridgeStatus.current = {port: 16802,degraded: false,+ extensionPairingHealth: 'ready',fixedPort: 'auto',instanceId: 'test-instance',}@@ -233,6 +235,7 @@ describe('IntegrationDialog scaffold', () => {bridgeStatus.current = {port: 54321,degraded: true,+ extensionPairingHealth: 'ready',fixedPort: 'auto',instanceId: 'test-instance',}@@ -267,4 +270,30 @@ describe('IntegrationDialog scaffold', () => {screen.queryByText('Bridge running on a fallback port')).not.toBeInTheDocument()})++ it('keeps a projection failure visible and warns that the paired list is incomplete', async () => {+ bridgeStatus.current = {+ port: 16802,+ degraded: false,+ extensionPairingHealth: 'degraded',+ fixedPort: 'auto',+ instanceId: 'test-instance',+ }++ render(+ <IntegrationDialog+ open={true}+ onClose={() => {}}+ labelKey="settings.cards.integration.title"+ descKey="settings.cards.integration.desc"+ />+ )++ expect(+ await screen.findByText('Extension access is temporarily closed')+ ).toBeInTheDocument()+ expect(+ screen.getByText(/do not rely on the list below/i)+ ).toBeInTheDocument()+ })})diff --git a/src/renderer/routes/settings/cards/integration/use-bridge.test.tsx b/src/renderer/routes/settings/cards/integration/use-bridge.test.tsxindex a04fdb02..86bed975 100644--- a/src/renderer/routes/settings/cards/integration/use-bridge.test.tsx+++ b/src/renderer/routes/settings/cards/integration/use-bridge.test.tsx@@ -19,6 +19,7 @@ describe('useBridgeStatus (Task 21)', () => {vi.mocked(transport.invoke).mockResolvedValue({port: 16802,degraded: false,+ extensionPairingHealth: 'ready',fixedPort: 'auto',instanceId: 'abc-instance',})@@ -30,6 +31,7 @@ describe('useBridgeStatus (Task 21)', () => {expect(result.current).toEqual({port: 16802,degraded: false,+ extensionPairingHealth: 'ready',fixedPort: 'auto',instanceId: 'abc-instance',})@@ -41,6 +43,7 @@ describe('useBridgeStatus (Task 21)', () => {vi.mocked(transport.invoke).mockResolvedValue({port: 54321,degraded: true,+ extensionPairingHealth: 'ready',fixedPort: 'auto',instanceId: 'abc-instance',})@@ -54,6 +57,7 @@ describe('useBridgeStatus (Task 21)', () => {vi.mocked(transport.invoke).mockResolvedValue({port: 18080,degraded: false,+ extensionPairingHealth: 'ready',fixedPort: 18080,instanceId: 'abc-instance',})diff --git a/src/renderer/routes/settings/cards/integration/use-bridge.ts b/src/renderer/routes/settings/cards/integration/use-bridge.tsindex 6e2492bc..a6eafb5b 100644--- a/src/renderer/routes/settings/cards/integration/use-bridge.ts+++ b/src/renderer/routes/settings/cards/integration/use-bridge.ts@@ -112,7 +112,11 @@ function isBridgeStatusInfo(value: unknown): value is BridgeStatusInfo {return (typeof value === 'object' &&value !== null &&- typeof (value as { degraded?: unknown }).degraded === 'boolean'+ typeof (value as { degraded?: unknown }).degraded === 'boolean' &&+ ((value as { extensionPairingHealth?: unknown }).extensionPairingHealth ===+ 'ready' ||+ (value as { extensionPairingHealth?: unknown }).extensionPairingHealth ===+ 'degraded'))}@@ -205,7 +209,7 @@ export function usePendingPairRequests() {)}, [])- // Settled (denied/approved elsewhere, e.g. the pairing toast) and expired+ // Settled (denied/approved elsewhere, or transport-aborted) and expired// (lapsed past TTL) both need to drop this row's Approve button promptly// rather than wait for focus/visibility or the 1s local prune — see// src/main/bridge/index.ts's PairRequestSettled / PairRequestExpireddiff --git a/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.test.tsx b/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.test.tsxindex 73dfb62b..568c0888 100644--- a/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.test.tsx+++ b/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.test.tsx@@ -194,6 +194,28 @@ describe('usePairRequestPrompts', () => {})})+ it('never copies an Extension pairing code to the clipboard while presenting it', () => {+ const writeText = vi.fn()+ const originalClipboard = navigator.clipboard+ Object.defineProperty(navigator, 'clipboard', {+ configurable: true,+ value: { writeText },+ })+ try {+ render(<Host />)+ findListener(BridgeEvents.PairRequested)(EXT_A)+ expect(+ findAddCall('chromium:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:n')+ ).toBeDefined()+ expect(writeText).not.toHaveBeenCalled()+ } finally {+ Object.defineProperty(navigator, 'clipboard', {+ configurable: true,+ value: originalClipboard,+ })+ }+ })+it('over-limit sanity: 4 pending requests synthesize 4 prompts', async () => {invokeMock.mockResolvedValueOnce([cliPending('REQ1'),@@ -336,17 +358,20 @@ describe('usePairRequestPrompts', () => {expect(invokeMock).not.toHaveBeenCalled()})- it('backend settle closes the prompt silently, without sending a deny', () => {- render(<Host />)- findListener(BridgeEvents.PairRequested)(CLI_A)- invokeMock.mockClear()- findListener(BridgeEvents.PairRequestSettled)({- key: 'cli:A',- outcome: 'allowed',- })- expect(toastCloseMock).toHaveBeenCalledWith('cli:A')- expect(invokeMock).not.toHaveBeenCalled()- })+ it.each(['allowed', 'denied', 'aborted'] as const)(+ 'backend %s settle closes the prompt silently, without sending a deny',+ (outcome) => {+ render(<Host />)+ findListener(BridgeEvents.PairRequested)(CLI_A)+ invokeMock.mockClear()+ findListener(BridgeEvents.PairRequestSettled)({+ key: 'cli:A',+ outcome,+ })+ expect(toastCloseMock).toHaveBeenCalledWith('cli:A')+ expect(invokeMock).not.toHaveBeenCalled()+ }+ )it('duplicate PairRequested events for one key produce exactly one add', () => {render(<Host />)@@ -500,7 +525,7 @@ describe('usePairRequestPrompts', () => {expect(toastAddMock).toHaveBeenCalledWith(expect.objectContaining({type: 'error',- title: "Couldn't submit your decision — try again.",+ title: 'Couldn’t submit your decision — try again.',})))diff --git a/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.tsx b/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.tsxindex fafa14a3..961b0136 100644--- a/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.tsx+++ b/src/renderer/routes/settings/cards/integration/use-pair-request-prompts.tsx@@ -180,11 +180,11 @@ export function usePairRequestPrompts(): void {})}- // Backend-driven lifecycle: the request reached a final decision- // (elsewhere — e.g. the Pending Approvals inbox, or another window)- // or lapsed past its TTL. Either way we close without ourselves- // sending a deny; the "no longer pending" feedback stays where it- // lives today — a late settle attempt via `resolvePairWithFeedback`.+ // Backend-driven lifecycle: the request reached a non-TTL terminal+ // outcome (approved, denied, or transport-aborted elsewhere) or lapsed+ // past its TTL. Either way we close without ourselves sending a deny; the+ // "no longer pending" feedback stays where it lives today — a late settle+ // attempt via `resolvePairWithFeedback`.const closeSilently = (key: string) => {const state = prompts.get(key)if (state) {diff --git a/src/server/bridge/__fixtures__/expired-motrix.test-cert.pem b/src/server/bridge/__fixtures__/expired-motrix.test-cert.pemnew file mode 100644index 00000000..d96c557e--- /dev/null+++ b/src/server/bridge/__fixtures__/expired-motrix.test-cert.pem@@ -0,0 +1,19 @@+-----BEGIN CERTIFICATE-----+MIIDJjCCAg6gAwIBAgIUOH7DJyv1Dj8EINcDYI/4aLF1yTMwDQYJKoZIhvcNAQEL+BQAwFjEUMBIGA1UEAwwLbW90cml4LnRlc3QwHhcNMjAwMTAxMDAwMDAwWhcNMjEw+MTAxMDAwMDAwWjAWMRQwEgYDVQQDDAttb3RyaXgudGVzdDCCASIwDQYJKoZIhvcN+AQEBBQADggEPADCCAQoCggEBALxsOBfNMtjv9QnIbmQQyqxUCrah4Q9Xh/R3kY4H+prdOzxxzrZ4GLdmNjSZiLgM2AznAvZntKmukpqJpRE9lKvYnnvRk4s12NyO5zpYO+ckYuCRcs0U9Gljx9ffPc70XWxvUBYeZm40uM79mc1UL9779FmD8Bn4jWWRk5zf4e+CZ2VnrOrTV22yUUR2cbJ28vQ9+kuIf3aX+tt2nDGN+EAbO/u/cJbgTI6xdeJHLjc+RvvqjOnS8HIOKpLZVuNAcqYuCPwDBI4zr+ATq5bqgUiZTGIxUxEtJcXCZDnq1uAN+qTHcUW93V+oLuwYkv1k6aE3K4Xye4y7pYdFxchJ12agJP2UCAwEAAaNsMGowFgYD+VR0RBA8wDYILbW90cml4LnRlc3QwDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMC+BaAwEwYDVR0lBAwwCgYIKwYBBQUHAwEwHQYDVR0OBBYEFIlo96o4iSpm5dWlrZ3p+/i0sORB7MA0GCSqGSIb3DQEBCwUAA4IBAQBlZN45vbDDKNHvpPGr4VDytQKb1uOh+cTO2MdADAen0huc1Jl+XDYuOsgPd/O3NpYAQouVa7lw1S4+9DuZwo/bfBSCZZ2sz+YYV3rEO97RT6YO/iPsuYyVx4fB9v7J+jSeIPvSWjPLRB/5TIuHR764VzmzuAyjuR+uO0lj8D5n6K38Pvx/Fv048jOSohDe9bnoMosTw3eNnit2Qjl9+6RgDnR2oeOEnOo+JaKFVjAoL2jDcHY3S3l/QatEaMCvI2RL5b5OZ/vE1lzRcjbwNuSBLp2VE68tFQzs+5WayIavn4JiaryGjgbFkfb4nmII7EnnRK7bVE0Qjemn5AIxBuXV/tcue+-----END CERTIFICATE-----diff --git a/src/server/bridge/__fixtures__/expired-motrix.test-key.pem b/src/server/bridge/__fixtures__/expired-motrix.test-key.pemnew file mode 100644index 00000000..2ea28d17--- /dev/null+++ b/src/server/bridge/__fixtures__/expired-motrix.test-key.pem@@ -0,0 +1,28 @@+-----BEGIN PRIVATE KEY-----+MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC8bDgXzTLY7/UJ+yG5kEMqsVAq2oeEPV4f0d5GOB6a3Ts8cc62eBi3ZjY0mYi4DNgM5wL2Z7SprpKai+aURPZSr2J570ZOLNdjcjuc6WDnJGLgkXLNFPRpY8fX3z3O9F1sb1AWHmZuNLjO/Z+nNVC/e+/RZg/AZ+I1lkZOc3+HgmdlZ6zq01dtslFEdnGydvL0PfpLiH92l/rbdpw+xjfhAGzv7v3CW4EyOsXXiRy43Eb76ozp0vByDiqS2VbjQHKmLgj8AwSOM6/gE6uW+6oFImUxiMVMRLSXFwmQ56tbgDakx3FFvd1fqC7sGJL9ZOmhNyuF8nuMu6WHRcXIS+ddmoCT9lAgMBAAECggEAUw4Ay70PpMBg6qcGweUE8WE6N7azVefnbcMmzcxhmHuM+n6X96aIfo73Zcgnk7lVoppRm/uqjwD8blIuCKN0XStm8H045CwgI1h6ZCVvk0zqH+l0eSG7epkZBfbJb+gXJi0KyDUuQXXL4LG4keGCGHBHDQ4zT79X1GWPA59MGYy3Te+MJUodL4/dIdZnGBgLB1SJxutQ+W4LCt7LGPNKBM+/RsP/fTifgTlQLXoBm45xxH9+se+QvLpiD9gOEnQBf2lXa5ZcPPtr/Sck2pojjwKzVUAy7APcNgHwje3I8FlQJmxk+2MPnR4vAjka/3jKYxEVuVE8vkkZpjad9kO3rsbhyIQKBgQDqUJgOtErtxiSm5m/Y+Yhsokg0EFFv3/zXeDL2fbBBPZg7UMGZd7DKQqXaOwQt2wotvZENiSLgQYnPK+tWX++8+lRjnp88/yDNDMEezIzz2AxCWB4iybqwbbnWeZ1vsZa6xmJhnYrR9b3ezUc1Gh+bfoZilKw3Wp/3uvoOSo5MiMJTwKBgQDN3FiSBFHNStRm82eVswmNOjlAy8M1W7QO+nJ3QkiSV6g+v+iEWoOyZzOtFwk5LdnL+k7FrUHFD/z9+oN3PXO1Aktqv8ronPYEZ+x3/B5JEEMQzO4KyrVl8HcVpFfQky+cITFWSWCRKVO0uSYL9iNtGt+9HMW+9btUJx+mWN6LkJXCwKBgQDBj1YtP25uQTJh1RYrj8+TkiLCbfcTRHXBOpEiMui+TjaNvnWx+vL6AlhzkDEBmGIuKty6a8CttDYdN9Cuh41hC1WJeCxSKhV+uVFhgAiJyTpYVVzs2+VO/TV5IPmXHQLAw8TdkoDstK3mcXkTOrwOfLVWK9zAqAGyyRpzdkDDC5LQKBgA8t+j9o0N1PLkJ2GlLyU1r9y64W7gEkO2de59GjMXaYv+7gd2RKyCr/MPAyIpv0pXpEm+ko43ACLjTusnMTN4xoVcToNqgg8imcIs016YW5jThP470n9PfvItiVpWPbdkcsq1+aRUm1hfqp0fDmljDcfJB/tXycVNxqdR2Wr9HadzBAoGBAJd6EOKUU+HjwtP87W+A+Fd5j/3ifeTm3IITHvIL6Gg8+PDonK0zJK6XdKKyyYOW3FEdd5tgsnNieCoR3fsVE+etpWSxi7AVgLgtbtJx1H4Ocwvmx+WsV43rjUqS4PTvEyUXuw19J8VChoEgGrEg2i+tMeCRH5tacVkDdgwdqWcj2aV+-----END PRIVATE KEY-----diff --git a/src/server/bridge/__fixtures__/motrix.test-cert.pem b/src/server/bridge/__fixtures__/motrix.test-cert.pemnew file mode 100644index 00000000..c98bc795--- /dev/null+++ b/src/server/bridge/__fixtures__/motrix.test-cert.pem@@ -0,0 +1,20 @@+-----BEGIN CERTIFICATE-----+MIIDOTCCAiGgAwIBAgIUM+7Z6+/IM8njwWnESG17dGoPERswDQYJKoZIhvcNAQEL+BQAwGTEXMBUGA1UEAwwOTW90cml4LVRlc3QtQ0EwHhcNMjYwODMwMTQxMDA1WhcN+MzYwODI3MTQxMDA1WjAWMRQwEgYDVQQDDAttb3RyaXgudGVzdDCCASIwDQYJKoZI+hvcNAQEBBQADggEPADCCAQoCggEBAMh38yF2P8QtZNPI7/8i9oye16PNFoAwliWr+LtOHb6BIiGubIKRChe9pKoniecnFYMn/bqJQeugco04VlLL4kc8+DP3WOiQ08ebb+VdN+Am6hk/rEZriCC5hD44aAnCiTVwiDH4ZIjYpOS+zoxbIBGK5vFeRSlB6d8IWG++G/DB6S61rI0KahpL+7wuU71aXK6/zzIGJ7aSgqiTrZyZXbIFPiVYukxJ7Vg9jxw+IaQ4FmrpJKM6Ii+imOGAARVXBuE/9hWO1I25VM2BeHaY8Qx2bAu1I5s9Nk45hFE1+XDcmlgW0S2gmk+6VwyU8J0oo/H7MEKxT+Qi/LuwyoK3sQKgWkn8CAwEAAaN8MHow+FgYDVR0RBA8wDYILbW90cml4LnRlc3QwEwYDVR0lBAwwCgYIKwYBBQUHAwEwCwYD+VR0PBAQDAgWgMB0GA1UdDgQWBBRDCOJm5Koj0nmtGfB27A/yZZYM1DAfBgNVHSME+GDAWgBQHxVDTEmTazXe71Q+chn9kfmqN8jANBgkqhkiG9w0BAQsFAAOCAQEAIp47+2U7ENjfyU/U2l+UN5Irazp4NRxxbgIqp/2uRF/AQDSkb4IpqKWZRUD+SokQ77dFT+abHjGJELdgpgUShQwRiDQ30322dUQUc3vuz0+1uXA6UKhhuEjJOfQ89VM1T7YX1r+u0zHrvokM2E046IJ9uVQBlcAgcpRMFrHblRGuw0Ur/0f8YA0XJ+2/8jbR3onvH9H+v8qkC67F3pC0hl3KLzsjgQmkBrCSf/OPbmFmIedsmpxtg8fnwMR2IAfhBbBmNKIx+loIcQ/kyCIRXJHI9lZf/d0PK1LMXiFGEjKQtP1U/2PrNfe3BYO5/m+wRYC3/kPeA+kjAwfIU1Ftl/mIIqkw==+-----END CERTIFICATE-----diff --git a/src/server/bridge/__fixtures__/motrix.test-key.pem b/src/server/bridge/__fixtures__/motrix.test-key.pemnew file mode 100644index 00000000..fbee7902--- /dev/null+++ b/src/server/bridge/__fixtures__/motrix.test-key.pem@@ -0,0 +1,28 @@+-----BEGIN PRIVATE KEY-----+MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDId/Mhdj/ELWTT+yO//IvaMntejzRaAMJYlqy7Th2+gSIhrmyCkQoXvaSqJ4nnJxWDJ/26iUHroHKNO+FZSy+JHPPgz91jokNPHm21XTfgJuoZP6xGa4gguYQ+OGgJwok1cIgx+GSI2KTkvs+6MWyARiubxXkUpQenfCFhvhvwwekutayNCmoaS/u8LlO9Wlyuv88yBie2koKok62+cmV2yBT4lWLpMSe1YPY8cCGkOBZq6SSjOiIvopjhgAEVVwbhP/YVjtSNuVTNgXh2+mPEMdmwLtSObPTZOOYRRNVw3JpYFtEtoJpPulcMlPCdKKPx+zBCsU/kIvy7sMqCt+7ECoFpJ/AgMBAAECggEAFjDE7orO4zHdK95dxqHBpe49U4nzuCvoqvHIhKzEy/rL+cxHgap5cghRjm5DAx3d8T8/hGMGM4V2uLAoShD8ksMqfGIgatoBP2Kyl0vvrXACx+xzvvXPQ0QV4edPiOkKVCqJQPLMeiN1GUcPyRSbN6XnC4fSYw9DSqd7VpkcGGepLr+22TWoYBPU0IHnhjQ/e79EUaB/HMYY/sq9mc30/+bY0BJ2sRFcDZkxybSRYtbf5Tx+NCjv15kv5/OIteCYVd6DS8aDAm7Im4o93AMTwYeXa6vIDNmW2shNqtcyEFaJHbXY+r/ify9H6kC44MaKDOpUu+ucT93DQlwIgrfksBVDqvQKBgQDqYlLDgKHyZhH1Rvq6+aBwXHm241i8bm2p/LyXcaJV6O12JcYbQmcaOo6R85jJ3opBVt2sDLS51pMhHpUZ9+ZIkEh0JUOIk6SXdSXvFiQUmz2FdfGoYZO850R7wTUeK/g+jWMMwyNrAEBOgHwMj/+mml35d8+gATVcLzqe3i32yXVqwKBgQDa9OZkOF2uXfbs0fR4SFvJvlkhPJIY0UzY+NPt4O52+gkxClvq83NS4Gxg0WnN4vmpRpMA2MV5dUStgY/evvbimNHGPzwdPB/0K+7dKDEvlyeqRNJxPltXsDyW4aCAVF6+0S36+BcdKSSWT10CyGRERVsFiApIr9yp8r+Q06I3x26fQKBgGnnO1YyzPnlvL+C7s9DM04O5azaujZTJu+IsibA6qlsIXt03GFs+2hahQjVdHfiIb4cLdULeK1vktMoKl6sYvgBZzVKYqQi5IT0KwS6QKWklm3TRWz4T+k9legFCKc1XtmEsPiXQ22Zk3TlASf79eWcFfEFwBJC383p9kYstQLew5AoGAc8fy+mGZR62VWsC3ppz0kBE86VF/yJVtv1hhWLWLg7B98ce3iUsI3Xc8+AlkeHGgcUmXb+Gg0LCC9mz4atL+oT3Rd4QYJJLBpeTUwq+BKtg0Kk5QNX+yz3Cq6WIP/CwhGagFN2+O+3TWnWjBHT7RliNBf7FHelkcgWWG0txGOFamAUCgYEAsRSmT/LTAbvPa1ADKBnz+6k4Ie1SToaoJaPn6coMBsOGJNiR11a//Nz0XxjjhR/MDsJ6ErHf8NVPjIuaTUvSm+Ec4D+gBefssHzVLkM9IsWgwHwhZsCr1AdzNUmkv3WpcgYFmRVcPbn1utbSINq7uU+wOOf/OLCjprD2o9NFkNHDHs=+-----END PRIVATE KEY-----diff --git a/src/server/bridge/__fixtures__/test-ca.pem b/src/server/bridge/__fixtures__/test-ca.pemnew file mode 100644index 00000000..08231948--- /dev/null+++ b/src/server/bridge/__fixtures__/test-ca.pem@@ -0,0 +1,19 @@+-----BEGIN CERTIFICATE-----+MIIDEzCCAfugAwIBAgIUbEF6j3ClHFSYh9zv0v68gzltVkYwDQYJKoZIhvcNAQEL+BQAwGTEXMBUGA1UEAwwOTW90cml4LVRlc3QtQ0EwHhcNMjYwODMwMTQwOTQ3WhcN+MzYwODI3MTQwOTQ3WjAZMRcwFQYDVQQDDA5Nb3RyaXgtVGVzdC1DQTCCASIwDQYJ+KoZIhvcNAQEBBQADggEPADCCAQoCggEBAK8xb/3xfbLbMB3ox5WyD8GWx2jclcIr+VUBKsmUpBN4V6nEALns8CuVtQy7SdYSbz1oFF0dZ63lSRCttPA5k89uGZ9ac4kGf+MkKN5zfX2iyvaPINxLyKexhpM8f/lm3RAdXwQ7kJEmyayke+uXgNbboCd3ttpcdq+D+kiKAC85OURYwVahRUwRhKgNTDa3NdP/rqOoHAohiLpYSSuws24NFSDEaLdBvwV+Y4q0EYDUjHC6rn2rAlCYjB0bOyWTO7Ixk50nqzeTREhgsqZn5Yu3nLJGmpwXwi1H+v4/9Nt1HvL3mRSp1M9z8zvAAlht/CVuIu/XdlQzABOGPFNTdkxlmw6kCAwEAAaNT+MFEwHQYDVR0OBBYEFAfFUNMSZNrNd7vVD5yGf2R+ao3yMB8GA1UdIwQYMBaAFAfF+UNMSZNrNd7vVD5yGf2R+ao3yMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL+BQADggEBADRhiyFJIiAPxhhymaS2gAACqf5osXOA/ZxZowqKjgYN17nNmyaTiL/t+D5cbQRhQWIqtk+LK9yUIPZ0WCvrWov4dmCqG7S/B40Soz6wUPYUtoM/xfDVvnOIe+0E/cVcFiYAxdk2T58TnNmNvPJaLalNrPwQvSzlxPO0QGkkM0jNC+Acb/3cXaHyCa+3ESBmZQT6IcvZhjnY6eXz31/Rh/Hda1KkOli9EuQL+Hqkc3SBScQAFhZa7jceDfa+C7D15ByPWSijRXkEunTRKIeLTkphu+WXsogR7LvIMe6vodtvhF48Y8sIGfRd6ywm+WBDT2zJE+NfP4lWC9Lry1I9iagCiThA=+-----END CERTIFICATE-----diff --git a/src/server/bridge/bootstrap.test.ts b/src/server/bridge/bootstrap.test.tsindex 4007fd75..f8c4761d 100644--- a/src/server/bridge/bootstrap.test.ts+++ b/src/server/bridge/bootstrap.test.ts@@ -1,7 +1,16 @@-import { mkdtemp, readFile, rm } from 'node:fs/promises'+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'import { request as httpRequest } from 'node:http'import { tmpdir } from 'node:os'import { join } from 'node:path'+import {+ exchangeCredential,+ initializeParams,+ mdxpOverChannel,+ runPake,+ startPair,+} from '@core/bridge/__tests__/mbp1-client'+import { BRIDGE_DATA_DIR_LOCK_FILE_NAME } from '@core/bridge/bridge-data-dir-lock'+import type { BridgeEventBus } from '@core/bridge/bridge-event-bus'import { EndpointFileWriter } from '@core/bridge/endpoint-file-writer'import type { ReadHandlerDeps } from '@core/bridge/handlers/read-handlers'import type { WriteHandlerDeps } from '@core/bridge/handlers/write-handlers'@@ -9,12 +18,18 @@ import { PairingService } from '@core/bridge/pairing-service'import { WebSocketBridgeServer } from '@core/bridge/web-socket-bridge-server'import { BridgeStreamSource } from '@core/bridge-receiver/bridge-stream-source'import { EventBus } from '@core/events/event-bus'+import { Notifications } from '@motrix/mdxp'+import { BridgeEvents } from '@shared/protocol/bridge'import { Events } from '@shared/protocol/events'import { EngineState } from '@shared/types/engine'import { TaskStatus } from '@shared/types/task'import { makeDownloadTask } from '@test-utils/task'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { bootstrapBridgeForServer } from './bootstrap'+import {+ bootstrapBridgeForServer,+ type ServerExtensionReceiver,+} from './bootstrap'+import { parseRemoteExtensionConfig } from './remote-extension-config'function readDeps(): ReadHandlerDeps {return {@@ -51,10 +66,53 @@ function writeDeps(): WriteHandlerDeps {}}+function extensionReceiver(): ServerExtensionReceiver {+ return {+ handle: vi.fn(async () => ({ taskId: 'submitted' })),+ cancel: vi.fn(async () => {}),+ restoreInflight: vi.fn(async () => {}),+ start: vi.fn(),+ stopAndDrain: vi.fn(async () => {}),+ }+}+interface Resp {status: numberbody: { result?: unknown; error?: { code: number } }}++function rawRequest(+ port: number,+ lines: readonly string[]+): Promise<{ status: number }> {+ const [requestLine, ...headerLines] = lines+ const [method, requestPath] = requestLine?.split(' ') ?? []+ const headers = Object.fromEntries(+ headerLines+ .filter((line) => line.includes(':'))+ .map((line) => {+ const offset = line.indexOf(':')+ return [line.slice(0, offset), line.slice(offset + 1).trim()]+ })+ )+ return new Promise((resolve, reject) => {+ const req = httpRequest(+ {+ host: '127.0.0.1',+ port,+ path: requestPath,+ method,+ headers,+ },+ (res) => {+ res.resume()+ res.once('end', () => resolve({ status: res.statusCode ?? 0 }))+ }+ )+ req.once('error', reject)+ req.end()+ })+}function post(port: number, payload: unknown, token?: string): Promise<Resp> {return new Promise((resolve, reject) => {const data = JSON.stringify(payload)@@ -202,6 +260,381 @@ describe('bootstrapBridgeForServer', () => {expect(res.status).toBe(401)})+ it('opens an explicit WS public route bundle with stable Server identity', async () => {+ const remoteExtensionConfig = parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'ws://motrix.example/bridge',+ MOTRIX_PUBLIC_URL: 'https://motrix.example',+ })+ const firstReceiver = extensionReceiver()+ runtime = await bootstrapBridgeForServer({+ userDataDir,+ host: '127.0.0.1',+ port: 0,+ motrixVersion: '2.0',+ eventBus: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+ readHandlerDeps: readDeps(),+ writeHandlerDeps: writeDeps(),+ remoteExtensionConfig,+ createExtensionReceiver: () => firstReceiver,+ })+ expect(firstReceiver.restoreInflight).toHaveBeenCalledOnce()+ expect(firstReceiver.start).toHaveBeenCalledOnce()+ const firstInstanceId = await readFile(+ join(userDataDir, 'bridge', 'server-instance-id'),+ 'utf8'+ )+ expect(firstInstanceId).toMatch(/^[0-9a-f-]{36}$/u)+ expect(+ (await fetch(`http://127.0.0.1:${runtime.port}/discovery`)).status+ ).toBe(404)+ expect(+ (+ await fetch(`http://127.0.0.1:${runtime.port}/nonce`, {+ method: 'POST',+ headers: { 'X-Motrix-Bridge': '1' },+ })+ ).status+ ).toBe(404)+ await expect(+ rawRequest(runtime.port, [+ 'GET /bridge/discovery HTTP/1.1',+ 'Host: motrix.example',+ 'Connection: close',+ ])+ ).resolves.toMatchObject({ status: 200 })+ await expect(+ rawRequest(runtime.port, [+ 'POST /bridge/nonce HTTP/1.1',+ 'Host: motrix.example',+ 'X-Motrix-Bridge: 1',+ 'Content-Length: 0',+ 'Connection: close',+ ])+ ).resolves.toMatchObject({ status: 200 })+ await expect(+ runtime.bridgeQueryHandlers['bridge:listPaired']()+ ).resolves.toEqual([])++ // The public bundle is not merely connectable: a real first-pair channel+ // reaches the shell receiver's validated download/submit handler.+ const extensionId = 'ibpkjhgpbidfmbmomagmldcdlpbmchgi'+ const handshake = await startPair({+ port: runtime.port,+ origin: `chrome-extension://${extensionId}`,+ browser: 'chromium',+ claimedExtensionId: extensionId,+ routePrefix: '/bridge',+ hostHeader: 'motrix.example',+ })+ const pending = (await runtime.bridgeQueryHandlers[+ 'bridge:listPendingPairRequests'+ ]()) as Array<{+ kind: string+ code?: string+ verifiedOrigin?: string+ originHost?: string+ claimedExtensionId?: string+ attestationClass?: string+ publicAuthority?: string+ }>+ expect(pending).toHaveLength(1)+ expect(pending[0]).toMatchObject({+ verifiedOrigin: `chrome-extension://${extensionId}`,+ originHost: extensionId,+ claimedExtensionId: extensionId,+ attestationClass: 'official',+ publicAuthority: 'motrix.example',+ })+ const code = pending[0]?.code+ if (code === undefined) throw new Error('extension pairing code missing')+ const { channel } = await runPake(handshake, code)+ await exchangeCredential(handshake, channel)+ const connection = mdxpOverChannel(handshake.wire, channel)+ await connection.sendRequest(+ 'motrix/initialize',+ initializeParams(extensionId)+ )+ await expect(+ connection.sendRequest('download/submit', {+ source: {+ pageUrl: 'https://example.com/watch',+ pageTitle: 'Remote submit',+ detectedAt: Date.now(),+ },+ selection: {+ kind: 'direct',+ primary: {+ url: 'https://cdn.example.com/video.mp4',+ headers: {},+ cookies: [],+ refererPolicy: 'strict-origin-when-cross-origin',+ },+ },+ meta: { suggestedFilename: 'video.mp4', qualityLabel: 'source' },+ })+ ).resolves.toEqual({ taskId: 'submitted' })+ expect(firstReceiver.handle).toHaveBeenCalledOnce()+ await vi.waitFor(async () =>+ expect(+ (await runtime?.bridgeQueryHandlers['bridge:listPaired']()) ?? []+ ).toHaveLength(1)+ )+ const durablePairingState = await Promise.all([+ readFile(join(userDataDir, 'bridge', 'mbp1-credentials.json'), 'utf8'),+ readFile(join(userDataDir, 'bridge', 'extension-pairings.json'), 'utf8'),+ readFile(join(userDataDir, 'bridge', 'endpoint.json'), 'utf8'),+ ])+ expect(durablePairingState.join('\n')).not.toContain(code)+ connection.dispose()++ await runtime.shutdown()+ expect(firstReceiver.stopAndDrain).toHaveBeenCalledOnce()+ const secondReceiver = extensionReceiver()+ runtime = await bootstrapBridgeForServer({+ userDataDir,+ host: '127.0.0.1',+ port: 0,+ motrixVersion: '2.0',+ eventBus: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+ readHandlerDeps: readDeps(),+ writeHandlerDeps: writeDeps(),+ remoteExtensionConfig,+ createExtensionReceiver: () => secondReceiver,+ })+ await expect(+ readFile(join(userDataDir, 'bridge', 'server-instance-id'), 'utf8')+ ).resolves.toBe(firstInstanceId)+ })++ it('quarantines a committed Extension when projection persistence fails and repairs it on restart', async () => {+ const remoteExtensionConfig = parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'wss://motrix.example/bridge',+ MOTRIX_PUBLIC_URL: 'https://motrix.example',+ })+ const emit = vi.fn()+ runtime = await bootstrapBridgeForServer({+ userDataDir,+ host: '127.0.0.1',+ port: 0,+ motrixVersion: '2.0',+ eventBus: { on: vi.fn(), off: vi.fn(), emit },+ readHandlerDeps: readDeps(),+ writeHandlerDeps: writeDeps(),+ remoteExtensionConfig,+ createExtensionReceiver: extensionReceiver,+ })++ // Establish an independent CLI bearer before faulting the Extension-only+ // management projection. The injected failure must not corrupt this plane.+ const base = `http://127.0.0.1:${runtime.port}`+ const cliRequest = await fetch(`${base}/mdxp/pair/request`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ clientName: 'Agent', clientVersion: '1' }),+ })+ const { requestId } = (await cliRequest.json()) as { requestId: string }+ await runtime.bridgeCommandHandlers['bridge:resolvePair']({+ kind: 'cli',+ requestId,+ decision: 'allow',+ })+ const cliPoll = await fetch(`${base}/mdxp/pair/poll`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ requestId }),+ })+ const { token: cliToken } = (await cliPoll.json()) as { token?: string }+ if (cliToken === undefined) throw new Error('CLI pairing token missing')+ emit.mockClear()++ const extensionId = 'ibpkjhgpbidfmbmomagmldcdlpbmchgi'+ const handshake = await startPair({+ port: runtime.port,+ origin: `chrome-extension://${extensionId}`,+ browser: 'chromium',+ claimedExtensionId: extensionId,+ routePrefix: '/bridge',+ hostHeader: 'motrix.example',+ })+ const pending = (await runtime.bridgeQueryHandlers[+ 'bridge:listPendingPairRequests'+ ]()) as Array<{ code?: string }>+ const code = pending[0]?.code+ if (code === undefined) throw new Error('extension pairing code missing')+ const { channel } = await runPake(handshake, code)++ const projectionLock = join(+ userDataDir,+ 'bridge',+ 'extension-pairings.json.lock'+ )+ await writeFile(projectionLock, 'fault injection', { mode: 0o600 })+ await exchangeCredential(handshake, channel)++ await vi.waitFor(() =>+ expect(emit).toHaveBeenCalledWith(BridgeEvents.Error, {+ code: 'extensionProjectionDegraded',+ message:+ 'Extension pairing state could not be updated; access is closed until startup repair.',+ })+ )+ expect(emit).not.toHaveBeenCalledWith(+ BridgeEvents.Paired,+ expect.anything()+ )+ await expect(+ runtime.bridgeQueryHandlers['bridge:listPaired']()+ ).resolves.toEqual([expect.objectContaining({ kind: 'cli' })])+ await expect(+ post(+ runtime.port,+ { jsonrpc: '2.0', id: 1, method: 'task/list', params: {} },+ cliToken+ )+ ).resolves.toMatchObject({ status: 200 })++ await runtime.shutdown()+ runtime = null+ await rm(projectionLock)++ const repairedEmit = vi.fn()+ runtime = await bootstrapBridgeForServer({+ userDataDir,+ host: '127.0.0.1',+ port: 0,+ motrixVersion: '2.0',+ eventBus: { on: vi.fn(), off: vi.fn(), emit: repairedEmit },+ readHandlerDeps: readDeps(),+ writeHandlerDeps: writeDeps(),+ remoteExtensionConfig,+ createExtensionReceiver: extensionReceiver,+ })+ const repairedPaired = (await runtime.bridgeQueryHandlers[+ 'bridge:listPaired'+ ]()) as Array<{ kind: string; browser?: string; id: string }>+ expect(repairedPaired).toHaveLength(2)+ expect(repairedPaired).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ kind: 'cli' }),+ expect.objectContaining({+ kind: 'extension',+ browser: 'chromium',+ id: extensionId,+ }),+ ])+ )+ await expect(+ post(+ runtime.port,+ { jsonrpc: '2.0', id: 2, method: 'task/list', params: {} },+ cliToken+ )+ ).resolves.toMatchObject({ status: 200 })+ expect(repairedEmit).not.toHaveBeenCalledWith(+ BridgeEvents.Paired,+ expect.anything()+ )+ })++ it('fails closed before listening when remote Extension has no download receiver', async () => {+ const remoteExtensionConfig = parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'wss://motrix.example/bridge',+ MOTRIX_PUBLIC_URL: 'https://motrix.example',+ })+ const start = vi.spyOn(WebSocketBridgeServer.prototype, 'start')++ await expect(+ bootstrapBridgeForServer({+ userDataDir,+ host: '127.0.0.1',+ port: 0,+ motrixVersion: '2.0',+ eventBus: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+ readHandlerDeps: readDeps(),+ writeHandlerDeps: writeDeps(),+ remoteExtensionConfig,+ })+ ).rejects.toThrow('remote Extension receiver is not configured')++ expect(start).not.toHaveBeenCalled()+ await expect(+ readFile(join(userDataDir, 'bridge', 'endpoint.json'), 'utf8')+ ).rejects.toMatchObject({ code: 'ENOENT' })+ })++ it('routes Extension task lifecycle events only to their authenticated session', async () => {+ const remoteExtensionConfig = parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'wss://motrix.example/bridge',+ MOTRIX_PUBLIC_URL: 'https://motrix.example',+ })+ const captured: { bridgeBus?: BridgeEventBus } = {}+ const sendNotification = vi.fn()+ vi.spyOn(WebSocketBridgeServer.prototype, 'getSession').mockImplementation(+ (sessionKey) =>+ sessionKey === 'chromium:target'+ ? ({ conn: { sendNotification } } as never)+ : undefined+ )++ runtime = await bootstrapBridgeForServer({+ userDataDir,+ host: '127.0.0.1',+ port: 0,+ motrixVersion: '2.0',+ eventBus: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+ readHandlerDeps: readDeps(),+ writeHandlerDeps: writeDeps(),+ remoteExtensionConfig,+ createExtensionReceiver: (context) => {+ captured.bridgeBus = context.bridgeBus+ return extensionReceiver()+ },+ })+ const bridgeBus = captured.bridgeBus+ if (bridgeBus === undefined) throw new Error('bridge event bus missing')++ const progress = {+ taskId: 'task-1',+ bytesDone: 1,+ bytesTotal: 2,+ speedBps: 3,+ etaSec: 4,+ phase: 'downloading' as const,+ }+ bridgeBus.emitTaskProgress({+ sessionKey: 'chromium:target',+ params: progress,+ })+ const completed = {+ taskId: 'task-1',+ filePath: '/downloads/file.bin',+ durationMs: 5,+ }+ bridgeBus.emitTaskCompleted({+ sessionKey: 'chromium:target',+ params: completed,+ })+ const failed = { taskId: 'task-2', code: 'disk-full', message: 'full' }+ bridgeBus.emitTaskError({+ sessionKey: 'chromium:target',+ params: failed,+ })+ bridgeBus.emitTaskProgress({+ sessionKey: 'chromium:other',+ params: progress,+ })++ expect(sendNotification.mock.calls).toEqual([+ [Notifications.TaskProgress, progress],+ [Notifications.TaskCompleted, completed],+ [Notifications.TaskError, failed],+ ])+ })+it('device-code: request emits a web prompt, approve issues a token, listPaired shows the cli', async () => {const emit = vi.fn()runtime = await bootstrapBridgeForServer({@@ -458,6 +891,85 @@ describe('bootstrapBridgeForServer', () => {expect(shutdownOrder).toEqual(['server', 'pairing'])})+ it('holds the data-directory lock before stores load and releases it last', async () => {+ const lockPath = join(userDataDir, 'bridge', BRIDGE_DATA_DIR_LOCK_FILE_NAME)+ vi.spyOn(PairingService.prototype, 'load').mockImplementation(async () => {+ await expect(readFile(lockPath, 'utf8')).resolves.toContain('ownerNonce')+ })++ runtime = await bootstrapBridgeForServer({+ userDataDir,+ host: '127.0.0.1',+ port: 0,+ motrixVersion: '2.0',+ eventBus: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+ readHandlerDeps: readDeps(),+ writeHandlerDeps: writeDeps(),+ })+ await expect(readFile(lockPath, 'utf8')).resolves.toContain('ownerNonce')++ await runtime.shutdown()+ runtime = null+ await expect(readFile(lockPath)).rejects.toMatchObject({ code: 'ENOENT' })+ })++ it('recovers a crash residue only with the supplied external authority', async () => {+ const bridgeDir = join(userDataDir, 'bridge')+ await mkdir(bridgeDir, { recursive: true })+ const lockPath = join(bridgeDir, BRIDGE_DATA_DIR_LOCK_FILE_NAME)+ await writeFile(+ lockPath,+ `${JSON.stringify({+ version: 1,+ ownerNonce: 'A'.repeat(43),+ ownershipEpoch: 'B'.repeat(43),+ })}\n`,+ { mode: 0o600 }+ )++ runtime = await bootstrapBridgeForServer({+ userDataDir,+ host: '127.0.0.1',+ port: 0,+ motrixVersion: '2.0',+ eventBus: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+ readHandlerDeps: readDeps(),+ writeHandlerDeps: writeDeps(),+ bridgeDataDirLockRecoveryAuthority: {+ ownershipEpoch: 'C'.repeat(43),+ assertExclusiveProcessOwnership: () => true,+ },+ })++ await expect(readFile(lockPath, 'utf8')).resolves.toContain(+ `"ownershipEpoch":"${'C'.repeat(43)}"`+ )+ })++ it('rejects a concurrent bridge using the same data directory', async () => {+ runtime = await bootstrapBridgeForServer({+ userDataDir,+ host: '127.0.0.1',+ port: 0,+ motrixVersion: '2.0',+ eventBus: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+ readHandlerDeps: readDeps(),+ writeHandlerDeps: writeDeps(),+ })++ await expect(+ bootstrapBridgeForServer({+ userDataDir,+ host: '127.0.0.1',+ port: 0,+ motrixVersion: '2.0',+ eventBus: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+ readHandlerDeps: readDeps(),+ writeHandlerDeps: writeDeps(),+ })+ ).rejects.toThrow('bridge data directory lock unavailable')+ })+it('rolls back a partially-created listener when bind rejects', async () => {const bindError = new Error('bind failed after allocation')vi.spyOn(WebSocketBridgeServer.prototype, 'start').mockRejectedValue(diff --git a/src/server/bridge/bootstrap.ts b/src/server/bridge/bootstrap.tsindex 479f01db..07cdd388 100644--- a/src/server/bridge/bootstrap.ts+++ b/src/server/bridge/bootstrap.ts@@ -1,9 +1,15 @@import { randomBytes, randomUUID } from 'node:crypto'+import { mkdir } from 'node:fs/promises'import { join } from 'node:path'+import {+ acquireBridgeDataDirLock,+ type BridgeDataDirLockRecoveryAuthority,+} from '@core/bridge/bridge-data-dir-lock'import { BridgeEventBus } from '@core/bridge/bridge-event-bus'import { BridgeOwnership } from '@core/bridge/bridge-ownership'import { DeviceCodeService } from '@core/bridge/device-code-service'import { EndpointFileWriter } from '@core/bridge/endpoint-file-writer'+import { recoverExtensionPairingProjectionWriterLock } from '@core/bridge/file-extension-pairing-projection-store'import { FilePairingStore } from '@core/bridge/file-pairing-store'import type { ReadHandlerDeps } from '@core/bridge/handlers/read-handlers'import type { WriteHandlerDeps } from '@core/bridge/handlers/write-handlers'@@ -12,19 +18,30 @@ import { FileRegistryStoreAdapter } from '@core/bridge/registry-store-adapter'import { resolveCliPair } from '@core/bridge/resolve-cli-pair'import { toPairedClientInfo } from '@core/bridge/to-paired-client-info'import { TrustedExtensionRegistry } from '@core/bridge/trusted-extension-registry'-import { WebSocketBridgeServer } from '@core/bridge/web-socket-bridge-server'+import {+ type MethodHandlers,+ WebSocketBridgeServer,+} from '@core/bridge/web-socket-bridge-server'import { BridgeStreamSource } from '@core/bridge-receiver/bridge-stream-source'import type { BridgeErrorCode } from '@core/bridge-receiver/errors'+import { Notifications } from '@motrix/mdxp'import {BridgeCommands,BridgeEvents,BridgeQueries,+ type BridgeStatusInfo,type ClientIdentity,pairRequestKey,type ResolvePairParams,type ResolvePairResult,} from '@shared/protocol/bridge'import type { Handler } from '@shared/protocol/handler-types'+import {+ isIssuedRemoteExtensionConfig,+ type RemoteExtensionConfig,+} from './remote-extension-config'+import { RemoteExtensionSurfacePolicy } from './remote-extension-surface-policy'+import { ServerExtensionMbp1Runtime } from './server-extension-mbp1-runtime'/** What `bootstrapBridgeForServer` returns; `localToken`/`port` are exposed for* the host + tests (the CLI discovers them via `endpoint.json`). The bridge:*@@ -39,6 +56,17 @@ export interface ServerBridgeRuntime {shutdown: () => Promise<void>}+/** Extension-only download application surface. The Server composition root+ * builds the existing BridgeReceiver against its live task/engine services;+ * bootstrap owns its recovery, admission and shutdown ordering. */+export interface ServerExtensionReceiver {+ handle: NonNullable<MethodHandlers['submitDownload']>+ cancel: (taskId: string) => Promise<void>+ restoreInflight: () => Promise<void>+ start: () => void+ stopAndDrain: () => Promise<void>+}+export interface ServerBridgeOptions {/** Server data dir (env MOTRIX_DATA_DIR / platform.userDataDir); the bridge* state lives under `<userDataDir>/bridge/`. */@@ -65,6 +93,17 @@ export interface ServerBridgeOptions {* a test observe the real TTL-timer expiry push over a real HTTP + real* clock round trip without waiting 5 minutes. */deviceCodeTtlMs?: number+ /** Production supplies an authority derived from the already-bound main+ * control-plane port. Omitted only by isolated tests with a fresh data dir. */+ bridgeDataDirLockRecoveryAuthority?: BridgeDataDirLockRecoveryAuthority+ /** Parser-issued all-or-nothing remote Extension configuration. */+ remoteExtensionConfig?: RemoteExtensionConfig+ /** Required when remote Extension support is enabled. Absence keeps the+ * public MBP1 surface from starting instead of exposing a connect-only shell. */+ createExtensionReceiver?: (context: {+ dataDir: string+ bridgeBus: BridgeEventBus+ }) => ServerExtensionReceiver | Promise<ServerExtensionReceiver>}/**@@ -75,131 +114,252 @@ export interface ServerBridgeOptions {* Mirrors the desktop bootstrap minus every Electron piece: NO* PairingDialogController (headless; web-UI approval is Spec 7),* NO NativeMessagingInstaller (no browser NM on a server),- * NO ipcMain. The extension `download/submit` WS path is intentionally NOT wired- * here — the server's value is the agent HTTP MDXP surface.+ * NO ipcMain. Remote Extension routes are atomic: MBP1 authorization, the raw+ * public-route policy, and the real download receiver must all be present+ * before any of the four routes becomes visible.*/export async function bootstrapBridgeForServer(opts: ServerBridgeOptions): Promise<ServerBridgeRuntime> {const dataDir = join(opts.userDataDir, 'bridge')- const pairing = new PairingService(- new FilePairingStore(join(dataDir, 'pairing.json'))- )- await pairing.load()- const registry = new TrustedExtensionRegistry(- new FileRegistryStoreAdapter(join(dataDir, 'registry.json')),- []- )- await registry.load()+ await mkdir(dataDir, { recursive: true })+ const ownership = new BridgeOwnership()+ const dataDirLock = await acquireBridgeDataDirLock(dataDir, {+ recoverExisting: opts.bridgeDataDirLockRecoveryAuthority,+ })+ ownership.own('bridge-data-dir-lock', () => dataDirLock.release())+ try {+ const pairing = new PairingService(+ new FilePairingStore(join(dataDir, 'pairing.json'))+ )+ await pairing.load()+ const bridgeBus = new BridgeEventBus()+ const remoteExtensionEnabled =+ opts.remoteExtensionConfig !== undefined &&+ isIssuedRemoteExtensionConfig(opts.remoteExtensionConfig) &&+ opts.remoteExtensionConfig.status === 'enabled'+ if (+ remoteExtensionEnabled &&+ opts.host !== '127.0.0.1' &&+ opts.host !== '::1' &&+ opts.host !== 'localhost'+ ) {+ throw new Error('remote Extension bridge must bind to loopback')+ }+ if (remoteExtensionEnabled) {+ await recoverExtensionPairingProjectionWriterLock(+ join(dataDir, 'extension-pairings.json'),+ dataDirLock+ )+ }+ const extensionMbp1 = remoteExtensionEnabled+ ? await ServerExtensionMbp1Runtime.load({+ dataDir,+ bus: bridgeBus,+ publicAuthority:+ opts.remoteExtensionConfig?.status === 'enabled'+ ? opts.remoteExtensionConfig.publicWebSocketAuthority+ : '',+ })+ : null+ const remoteExtensionSurface =+ remoteExtensionEnabled && opts.remoteExtensionConfig !== undefined+ ? new RemoteExtensionSurfacePolicy(opts.remoteExtensionConfig)+ : null+ if (remoteExtensionSurface !== null) {+ ownership.own('remote-extension-surface', () =>+ remoteExtensionSurface.dispose()+ )+ }+ if (extensionMbp1 !== null) {+ ownership.own('extension-mbp1', () => extensionMbp1.stopAndDrain())+ }+ if (remoteExtensionEnabled && opts.createExtensionReceiver === undefined) {+ throw new Error('remote Extension receiver is not configured')+ }+ const extensionReceiver = remoteExtensionEnabled+ ? await opts.createExtensionReceiver?.({+ dataDir: join(dataDir, 'receiver'),+ bridgeBus,+ })+ : null+ if (remoteExtensionEnabled && extensionReceiver == null) {+ throw new Error('remote Extension receiver is unavailable')+ }+ if (extensionReceiver != null) {+ ownership.own('extension-receiver', () =>+ extensionReceiver.stopAndDrain()+ )+ await extensionReceiver.restoreInflight()+ }+ let boundPort = opts.port+ const registry = new TrustedExtensionRegistry(+ new FileRegistryStoreAdapter(join(dataDir, 'registry.json')),+ extensionMbp1 === null+ ? []+ : [...extensionMbp1.identityResolver.officialEntries]+ )+ await registry.load()- // Machine-owner Bearer token for the unary/SSE transports (same model as the- // desktop). On a NAS it lives in endpoint.json (readable only on the host); a- // remote CLI obtains a token via Spec 7 device-code pairing.- // Agent /mdxp secret — self-minted, written to endpoint.json. Distinct from- // the operator control-plane token (Spec 9 / F1): the two planes no longer- // share a secret, so a leak/loss of one does not compromise the other.- // Per-start, deliberately NOT persisted like the desktop shell's- // `loadOrCreateBridgeIdentity`: extension pairing is headless-denied here- // (no NM tickets are ever minted against this token), so a restart- // invalidating every previously-issued Bearer token is a wanted property,- // not a gap.- const localToken = randomBytes(32).toString('base64url')- // One generation for the life of this process, named here (rather than- // inlined at the endpoint write below) so a future second write site can't- // accidentally mint a fresh one and make every NM ticket look stale.- const serverGeneration = randomUUID()+ // Machine-owner Bearer token for the unary/SSE transports (same model as the+ // desktop). On a NAS it lives in endpoint.json (readable only on the host); a+ // remote CLI obtains a token via Spec 7 device-code pairing.+ // Agent /mdxp secret — self-minted, written to endpoint.json. Distinct from+ // the operator control-plane token (Spec 9 / F1): the two planes no longer+ // share a secret, so a leak/loss of one does not compromise the other.+ // Per-start, deliberately NOT persisted like the desktop shell's+ // `loadOrCreateBridgeIdentity`: extension pairing is headless-denied here+ // (no NM tickets are ever minted against this token), so a restart+ // invalidating every previously-issued Bearer token is a wanted property,+ // not a gap.+ const localToken = randomBytes(32).toString('base64url')+ // One generation for the life of this process, named here (rather than+ // inlined at the endpoint write below) so a future second write site can't+ // accidentally mint a fresh one and make every NM ticket look stale.+ const serverGeneration = randomUUID()- // Device-code pairing for cli/agent clients. The approval prompt is surfaced- // in the WEB UI: bridge events are re-emitted onto the core EventBus, which- // the Fastify broadcaster forwards over /rpc/events. (The desktop uses- // Electron IPC for the same events; only the server shell takes this path.)- const bridgeBus = new BridgeEventBus()- // onLifecycle re-emits the cli device-code settle/expire push onto the SAME- // bridgeBus channel the desktop shell uses, so it flows through the- // identical re-emit-onto-eventBus wiring below (→ /rpc/events broadcaster).- const deviceCode = new DeviceCodeService(pairing, {- ttlMs: opts.deviceCodeTtlMs,- onLifecycle: {- settled: (requestId, outcome) =>- bridgeBus.emitPairRequestSettled({- key: pairRequestKey({ kind: 'cli', requestId }),- outcome,- }),- expired: (requestId) =>- bridgeBus.emitPairRequestExpired({- key: pairRequestKey({ kind: 'cli', requestId }),- }),- },- })- bridgeBus.on('PairRequested', (p) =>- opts.eventBus.emit(BridgeEvents.PairRequested, p)- )- bridgeBus.on('Paired', (p) => opts.eventBus.emit(BridgeEvents.Paired, p))- bridgeBus.on('Revoked', (p) => opts.eventBus.emit(BridgeEvents.Revoked, p))- bridgeBus.on('Error', (p) => opts.eventBus.emit(BridgeEvents.Error, p))- bridgeBus.on('PairRequestSettled', (p) =>- opts.eventBus.emit(BridgeEvents.PairRequestSettled, p)- )- bridgeBus.on('PairRequestExpired', (p) =>- opts.eventBus.emit(BridgeEvents.PairRequestExpired, p)- )+ // Device-code pairing for cli/agent clients. The approval prompt is surfaced+ // in the WEB UI: bridge events are re-emitted onto the core EventBus, which+ // the Fastify broadcaster forwards over /rpc/events. (The desktop uses+ // Electron IPC for the same events; only the server shell takes this path.)+ // onLifecycle re-emits the cli device-code settle/expire push onto the SAME+ // bridgeBus channel the desktop shell uses, so it flows through the+ // identical re-emit-onto-eventBus wiring below (→ /rpc/events broadcaster).+ const deviceCode = new DeviceCodeService(pairing, {+ ttlMs: opts.deviceCodeTtlMs,+ onLifecycle: {+ settled: (requestId, outcome) =>+ bridgeBus.emitPairRequestSettled({+ key: pairRequestKey({ kind: 'cli', requestId }),+ outcome,+ }),+ expired: (requestId) =>+ bridgeBus.emitPairRequestExpired({+ key: pairRequestKey({ kind: 'cli', requestId }),+ }),+ },+ })+ bridgeBus.on('PairRequested', (p) =>+ opts.eventBus.emit(BridgeEvents.PairRequested, p)+ )+ bridgeBus.on('Paired', (p) => opts.eventBus.emit(BridgeEvents.Paired, p))+ bridgeBus.on('Revoked', (p) => opts.eventBus.emit(BridgeEvents.Revoked, p))+ bridgeBus.on('Error', (p) => opts.eventBus.emit(BridgeEvents.Error, p))+ bridgeBus.on('PairRequestSettled', (p) =>+ opts.eventBus.emit(BridgeEvents.PairRequestSettled, p)+ )+ bridgeBus.on('PairRequestExpired', (p) =>+ opts.eventBus.emit(BridgeEvents.PairRequestExpired, p)+ )- const server = new WebSocketBridgeServer({- pairing,- registry,- // None of the six MBP1 options (instanceId, serverGeneration, appVersion,- // credentials, isOfficialId, queueMbp1Dialog) are wired for this runtime,- // so `/pair` and `/v1` both 404 (they resolve as a unit — see- // `resolveMbp1Wiring`): there is no extension WebSocket surface here at- // all, not even reconnect for a previously-paired extension. cli/agent- // clients pair through the device-code flow below instead, approved in- // the web UI.- motrixVersion: opts.motrixVersion,- runtime: 'server',- ffmpegAvailable: false,- localToken,- deviceCode,- onPairRequested: (payload) => bridgeBus.emitPairRequested(payload),- verificationUri: opts.verificationUri,- })+ const server = new WebSocketBridgeServer({+ pairing,+ registry,+ motrixVersion: opts.motrixVersion,+ runtime: 'server',+ ffmpegAvailable: false,+ localToken,+ deviceCode,+ onPairRequested: (payload) => bridgeBus.emitPairRequested(payload),+ verificationUri: opts.verificationUri,+ ...(extensionMbp1 === null+ ? {}+ : {+ instanceId: extensionMbp1.instanceId,+ serverGeneration,+ appVersion: opts.motrixVersion,+ credentials: extensionMbp1.credentials,+ isOfficialId: (browser, id) =>+ extensionMbp1.identityResolver.isOfficialId(browser, id),+ queueMbp1Dialog: (request) =>+ extensionMbp1.prompts.queueMbp1Prompt(request),+ canAdmitExtensionIdentity: (identity) =>+ extensionMbp1.extensionPairings.canAdmitIdentity(identity),+ onExtensionAuthenticated: (identity, credentialId) =>+ extensionMbp1.onAuthenticated(identity, credentialId),+ extensionMbp1RoutesEnabled:+ remoteExtensionSurface !== null && extensionReceiver != null,+ extensionMbp1RoutePolicy: (request) =>+ remoteExtensionSurface?.evaluate(request) ?? {+ kind: 'reject',+ status: 404,+ },+ }),+ })+ if (extensionMbp1 !== null) {+ extensionMbp1.attachServer(server)+ await extensionMbp1.recoverBeforeListen()+ }- // bridge:* RPC handlers the web renderer reaches via /rpc/{command,query}.- const bridgeCommandHandlers: Record<string, Handler> = {- [BridgeCommands.ResolvePair]: async (- params: ResolvePairParams- ): Promise<ResolvePairResult> => {- // Only cli (device-code) approval has a server-shell path; the extension- // /pair WS flow is not wired here (headless).- if (params.kind === 'cli') {- return resolveCliPair(deviceCode, params, (paired) =>- bridgeBus.emitPaired({ identity: paired.identity })+ // bridge:* RPC handlers the web renderer reaches via /rpc/{command,query}.+ const bridgeCommandHandlers: Record<string, Handler> = {+ [BridgeCommands.ResolvePair]: async (+ params: ResolvePairParams+ ): Promise<ResolvePairResult> => {+ if (params.kind === 'cli') {+ return resolveCliPair(deviceCode, params, (paired) =>+ bridgeBus.emitPaired({ identity: paired.identity })+ )+ }+ return (+ extensionMbp1?.settleExtensionPrompt(params) ?? {+ ok: false,+ reason: 'unavailable',+ })- }- return { ok: true }- },- [BridgeCommands.RevokePair]: async (params: {- identity: ClientIdentity- }) => {- await pairing.revoke(params.identity, 'user-revoked')- bridgeBus.emitRevoked({ identity: params.identity })- },- }- const bridgeQueryHandlers: Record<string, Handler> = {- [BridgeQueries.ListPaired]: async () =>- pairing.listPaired().map(toPairedClientInfo),- // cli-only — unlike the desktop shell, there is no PairingDialogController- // here to union in (extension pairing is headless-denied, above).- [BridgeQueries.ListPendingPairRequests]: async () =>- deviceCode.listPending(),- }+ },+ [BridgeCommands.RevokePair]: async (params: {+ identity: ClientIdentity+ }) => {+ if (params.identity.kind === 'extension') {+ if (extensionMbp1 === null) {+ throw new Error('extension pairing is unavailable')+ }+ await extensionMbp1.revoke(params.identity)+ return+ }+ await pairing.revoke(params.identity, 'user-revoked')+ bridgeBus.emitRevoked({ identity: params.identity })+ },+ }+ const bridgeQueryHandlers: Record<string, Handler> = {+ [BridgeQueries.ListPaired]: async () => [+ ...(extensionMbp1?.extensionPairings.list().map(toPairedClientInfo) ??+ []),+ ...pairing.listPaired().map(toPairedClientInfo),+ ],+ [BridgeQueries.ListPendingPairRequests]: async () => [+ ...deviceCode.listPending(),+ ...(extensionMbp1?.prompts.listPending() ?? []),+ ],+ [BridgeQueries.ListTrusted]: async () => registry.list(),+ [BridgeQueries.GetStatus]: async (): Promise<BridgeStatusInfo> => ({+ port: boundPort,+ degraded: false,+ extensionPairingHealth:+ extensionMbp1 === null ||+ extensionMbp1.extensionPairings.getHealth() === 'ready'+ ? 'ready'+ : 'degraded',+ fixedPort: opts.port,+ instanceId: extensionMbp1?.instanceId ?? 'extension-mbp1-disabled',+ }),+ }- // Register the agent-facing methods BEFORE start() (no listening-without-- // handlers race). Read/write/SSE only — no extension submit/cancel handlers.- server.registerReadMethods(opts.readHandlerDeps)- server.registerWriteMethods(opts.writeHandlerDeps)+ // Register every application method BEFORE start() (no+ // listening-without-handlers race). A remotely enabled Server cannot reach+ // this point without its real receiver, so discovery never advertises a+ // connect-only bridge.+ if (extensionReceiver != null) {+ server.setHandlers({+ submitDownload: (params, ctx) => extensionReceiver.handle(params, ctx),+ cancelDownload: ({ taskId }) => extensionReceiver.cancel(taskId),+ })+ extensionReceiver.start()+ }+ server.registerReadMethods(opts.readHandlerDeps)+ server.registerWriteMethods(opts.writeHandlerDeps)- const ownership = new BridgeOwnership()- try {// Acquire persistence ownership before the listener so reverse-order// shutdown first stops request admission, then drains every markActive// write accepted by that listener.@@ -207,6 +367,28 @@ export async function bootstrapBridgeForServer(// Own the server before bind so a partial listen failure is rolled back.ownership.own('server', () => server.stop())const port = await server.start(opts.host, opts.port)+ boundPort = port++ // Per-session Extension task lifecycle push. This mirrors the Desktop+ // shell: BridgeReceiver publishes against the authenticated session key;+ // the shell converts those events into encrypted MDXP notifications on+ // that session only. The global SSE stream below remains a separate agent+ // surface and must not substitute for this routing.+ bridgeBus.on('TaskProgress', ({ sessionKey, params }) => {+ server+ .getSession(sessionKey)+ ?.conn.sendNotification(Notifications.TaskProgress, params)+ })+ bridgeBus.on('TaskCompleted', ({ sessionKey, params }) => {+ server+ .getSession(sessionKey)+ ?.conn.sendNotification(Notifications.TaskCompleted, params)+ })+ bridgeBus.on('TaskError', ({ sessionKey, params }) => {+ server+ .getSession(sessionKey)+ ?.conn.sendNotification(Notifications.TaskError, params)+ })const streamSource = new BridgeStreamSource(server, opts.localize)ownership.own('stream-source', () => streamSource.detach(opts.eventBus))diff --git a/src/server/bridge/extension-pairing-prompt-adapter.test.ts b/src/server/bridge/extension-pairing-prompt-adapter.test.tsnew file mode 100644index 00000000..9f64768c--- /dev/null+++ b/src/server/bridge/extension-pairing-prompt-adapter.test.ts@@ -0,0 +1,153 @@+import type { PairDialogRequest } from '@core/bridge/mbp1/pair-session'+import type { PairingPromptTimeSource } from '@core/bridge/pairing-prompt-controller'+import { pairRequestKey } from '@shared/protocol/bridge'+import { describe, expect, it, vi } from 'vitest'+import { BridgeEventBus } from '../../core/bridge/bridge-event-bus'+import { ServerExtensionPairingPromptAdapter } from './extension-pairing-prompt-adapter'++const REQUEST: PairDialogRequest = {+ browser: 'chromium',+ verifiedOrigin: 'chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ claimedExtensionId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ identity: 'official',+ pairingNonce: 'nonce-a',+ code: 'ABCD-EFGH',+}++function fakeTime(start = 1_700_000_000_000): {+ source: PairingPromptTimeSource+ advance(ms: number): void+} {+ let now = start+ let scheduled: (() => void) | null = null+ return {+ source: {+ now: () => now,+ schedule: (callback) => {+ scheduled = callback+ return () => {+ scheduled = null+ }+ },+ },+ advance(ms) {+ now += ms+ const callback = scheduled+ scheduled = null+ callback?.()+ },+ }+}++describe('ServerExtensionPairingPromptAdapter', () => {+ it('publishes the code synchronously and exposes the same pending snapshot', async () => {+ const bus = new BridgeEventBus()+ const requested = vi.fn()+ bus.on('PairRequested', requested)+ const adapter = new ServerExtensionPairingPromptAdapter(bus, {+ publicAuthority: 'motrix.example',+ })++ const queued = adapter.queueMbp1Prompt(REQUEST)+ expect(queued.ok).toBe(true)+ if (!queued.ok) return+ await expect(queued.handle.published).resolves.toBe('delivered')+ expect(requested).toHaveBeenCalledExactlyOnceWith({+ kind: 'extension',+ pairingNonce: 'nonce-a',+ extensionId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ browser: 'chromium',+ identity: 'official',+ code: 'ABCD-EFGH',+ verifiedOrigin: 'chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ originHost: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ claimedExtensionId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ attestationClass: 'official',+ publicAuthority: 'motrix.example',+ })+ expect(adapter.listPending()).toEqual([+ expect.objectContaining({+ code: 'ABCD-EFGH',+ createdAt: expect.any(Number),+ expiresAt: expect.any(Number),+ }),+ ])++ await adapter.dispose()+ })++ it('maps an operator dismissal to one code-free denied terminal event', async () => {+ const bus = new BridgeEventBus()+ const settled = vi.fn()+ bus.on('PairRequestSettled', settled)+ const adapter = new ServerExtensionPairingPromptAdapter(bus)+ const queued = adapter.queueMbp1Prompt(REQUEST)+ expect(queued.ok).toBe(true)+ if (!queued.ok) return++ expect(+ adapter.settle({+ kind: 'extension',+ browser: REQUEST.browser,+ extensionId: REQUEST.claimedExtensionId,+ pairingNonce: REQUEST.pairingNonce,+ })+ ).toEqual({ ok: true })+ await expect(queued.handle.terminal).resolves.toBe('denied')+ expect(settled).toHaveBeenCalledExactlyOnceWith({+ key: pairRequestKey({+ kind: 'extension',+ browser: REQUEST.browser,+ extensionId: REQUEST.claimedExtensionId,+ pairingNonce: REQUEST.pairingNonce,+ }),+ outcome: 'denied',+ })+ expect(JSON.stringify(settled.mock.calls)).not.toContain(REQUEST.code)+ expect(adapter.listPending()).toEqual([])+ expect(+ adapter.settle({+ kind: 'extension',+ browser: REQUEST.browser,+ extensionId: REQUEST.claimedExtensionId,+ pairingNonce: REQUEST.pairingNonce,+ })+ ).toEqual({ ok: false, reason: 'unavailable' })+ })++ it('expires without placing the code in the terminal event', async () => {+ const clock = fakeTime()+ const bus = new BridgeEventBus()+ const expired = vi.fn()+ bus.on('PairRequestExpired', expired)+ const adapter = new ServerExtensionPairingPromptAdapter(bus, {+ ttlMs: 1_000,+ timeSource: clock.source,+ })+ const queued = adapter.queueMbp1Prompt(REQUEST)+ expect(queued.ok).toBe(true)+ if (!queued.ok) return++ clock.advance(1_000)+ await expect(queued.handle.terminal).resolves.toBe('expired')+ expect(expired).toHaveBeenCalledOnce()+ expect(JSON.stringify(expired.mock.calls)).not.toContain(REQUEST.code)+ expect(adapter.listPending()).toEqual([])+ })++ it('classifies a throwing operator publisher as failed', async () => {+ const bus = new BridgeEventBus()+ bus.on('PairRequested', () => {+ throw new Error('secret delivery path')+ })+ const adapter = new ServerExtensionPairingPromptAdapter(bus)+ const queued = adapter.queueMbp1Prompt(REQUEST)+ expect(queued.ok).toBe(true)+ if (!queued.ok) return++ await expect(queued.handle.published).resolves.toBe('failed')+ expect(adapter.listPending()).toHaveLength(1)+ await adapter.dispose()+ await expect(queued.handle.terminal).resolves.toBe('aborted')+ })+})diff --git a/src/server/bridge/extension-pairing-prompt-adapter.ts b/src/server/bridge/extension-pairing-prompt-adapter.tsnew file mode 100644index 00000000..e9864a50--- /dev/null+++ b/src/server/bridge/extension-pairing-prompt-adapter.ts@@ -0,0 +1,147 @@+import type { BridgeEventBus } from '@core/bridge/bridge-event-bus'+import type { PairDialogRequest } from '@core/bridge/mbp1/pair-session'+import {+ type PairingPromptCallbackReceipt,+ PairingPromptController,+ type PairingPromptControllerOptions,+ type PairingPromptEnqueueResult,+ type PairingPromptSnapshot,+ type PairingPromptTerminalEvent,+} from '@core/bridge/pairing-prompt-controller'+import {+ type PendingPairRequestInfo,+ pairRequestKey,+ type ResolvePairParams,+ type ResolvePairResult,+} from '@shared/protocol/bridge'++type ExtensionPairRequestPayload = Omit<+ Extract<PendingPairRequestInfo, { kind: 'extension' }>,+ 'createdAt' | 'expiresAt'+>++interface ServerExtensionPairingPromptAdapterOptions+ extends Pick<+ PairingPromptControllerOptions,+ 'maxPending' | 'timeSource' | 'ttlMs'+ > {+ /** Canonical public WS/WSS Host authority from the parser-issued config. */+ publicAuthority?: string+}++/**+ * Server-shell projection of the host-neutral MBP1 prompt controller.+ *+ * The caller must connect `bus` only to the authenticated operator control+ * plane. Enqueue publication is synchronous: returning `delivered` means the+ * code-bearing event has been committed to that in-process channel before the+ * PairSession is allowed to continue. Terminal events are always code-free.+ */+export class ServerExtensionPairingPromptAdapter {+ private readonly promptIdsByKey = new Map<string, string>()+ private readonly keysByPromptId = new Map<string, string>()+ private readonly prompts: PairingPromptController++ constructor(+ private readonly bus: BridgeEventBus,+ private readonly options: ServerExtensionPairingPromptAdapterOptions = {}+ ) {+ this.prompts = new PairingPromptController({+ ...options,+ onEnqueued: (snapshot) => this.publish(snapshot),+ onTerminal: (event) => this.publishTerminal(event),+ })+ }++ queueMbp1Prompt(request: PairDialogRequest): PairingPromptEnqueueResult {+ return this.prompts.enqueue(request)+ }++ /** Extension operator actions are deny-only; PAKE code entry is approval. */+ settle(+ params: Extract<ResolvePairParams, { kind: 'extension' }>+ ): ResolvePairResult {+ const promptId = this.promptIdsByKey.get(pairRequestKey(params))+ if (promptId === undefined) {+ return { ok: false, reason: 'unavailable' }+ }+ const result = this.prompts.deny(promptId)+ return result.ok && result.outcome === 'denied'+ ? { ok: true }+ : { ok: false, reason: 'unavailable' }+ }++ listPending(): PendingPairRequestInfo[] {+ return this.prompts.snapshot().map((snapshot) => ({+ ...this.toPayload(snapshot),+ createdAt: snapshot.createdAt,+ expiresAt: snapshot.expiresAt,+ }))+ }++ dispose(): Promise<void> {+ return this.prompts.dispose()+ }++ private publish(+ snapshot: PairingPromptSnapshot+ ): PairingPromptCallbackReceipt {+ const payload = this.toPayload(snapshot)+ const key = pairRequestKey(payload)+ if (+ this.promptIdsByKey.has(key) ||+ this.keysByPromptId.has(snapshot.promptId)+ ) {+ throw new Error('server pairing prompt adapter key collision')+ }+ this.promptIdsByKey.set(key, snapshot.promptId)+ this.keysByPromptId.set(snapshot.promptId, key)+ this.bus.emitPairRequested(payload)+ return 'delivered'+ }++ private publishTerminal(+ event: PairingPromptTerminalEvent+ ): PairingPromptCallbackReceipt {+ const key = this.keysByPromptId.get(event.promptId)+ if (key === undefined) return 'delivered'+ this.keysByPromptId.delete(event.promptId)+ this.promptIdsByKey.delete(key)++ switch (event.outcome) {+ case 'paired':+ this.bus.emitPairRequestSettled({ key, outcome: 'allowed' })+ break+ case 'denied':+ this.bus.emitPairRequestSettled({ key, outcome: 'denied' })+ break+ case 'expired':+ this.bus.emitPairRequestExpired({ key })+ break+ case 'aborted':+ this.bus.emitPairRequestSettled({ key, outcome: 'aborted' })+ break+ }+ return 'delivered'+ }++ private toPayload(+ snapshot: PairingPromptSnapshot+ ): ExtensionPairRequestPayload {+ return {+ kind: 'extension',+ pairingNonce: snapshot.pairingNonce,+ extensionId: snapshot.claimedExtensionId,+ browser: snapshot.verifiedIdentity.browser,+ identity: snapshot.identity,+ code: snapshot.code,+ verifiedOrigin: snapshot.verifiedIdentity.verifiedOrigin,+ originHost: snapshot.verifiedIdentity.originHost,+ claimedExtensionId: snapshot.claimedExtensionId,+ attestationClass: snapshot.identity,+ ...(this.options.publicAuthority === undefined+ ? {}+ : { publicAuthority: this.options.publicAuthority }),+ }+ }+}diff --git a/src/server/bridge/remote-extension-admission-policy.test.ts b/src/server/bridge/remote-extension-admission-policy.test.tsnew file mode 100644index 00000000..d0b675a9--- /dev/null+++ b/src/server/bridge/remote-extension-admission-policy.test.ts@@ -0,0 +1,933 @@+import { describe, expect, it } from 'vitest'+import {+ RemoteExtensionAdmissionPolicy,+ type RemoteExtensionAdmissionPolicyOptions,+ type RemoteExtensionClientSourceInput,+} from './remote-extension-admission-policy'+import {+ parseRemoteExtensionConfig,+ type RemoteExtensionConfig,+} from './remote-extension-config'++const ENABLED_CONFIG = parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'wss://motrix.example/bridge',+ MOTRIX_PUBLIC_URL: 'https://motrix.example/operator',+})++function options(+ overrides: Partial<RemoteExtensionAdmissionPolicyOptions> = {}+): RemoteExtensionAdmissionPolicyOptions {+ return {+ config: ENABLED_CONFIG,+ nonceIssuanceCap: 2,+ nonceIssuanceTtlMs: 60,+ pairPreAuthSocketCap: 2,+ pairPreAuthSocketTtlMs: 150,+ v1PreAuthSocketCap: 2,+ v1PreAuthSocketTtlMs: 15,+ pendingPromptCap: 2,+ pendingPromptTtlMs: 120,+ discoveryRate: {+ globalCap: 4,+ perSourceCap: 2,+ windowMs: 100,+ },+ nonceRate: {+ globalCap: 4,+ perSourceCap: 2,+ windowMs: 100,+ },+ ...overrides,+ }+}++function source(+ directPeerAddress: string,+ rawHeaders: readonly string[] = []+): RemoteExtensionClientSourceInput {+ return { directPeerAddress, rawHeaders }+}++function expectLease(+ result: ReturnType<RemoteExtensionAdmissionPolicy['acquirePairPreAuthSocket']>+) {+ expect(result.ok).toBe(true)+ if (!result.ok) throw new Error('test expected an admission lease')+ return result.lease+}++describe('RemoteExtensionAdmissionPolicy resource caps', () => {+ it('starts with independent empty counters', () => {+ const policy = new RemoteExtensionAdmissionPolicy(options())++ expect(policy.snapshot()).toEqual({+ nonceIssuances: 0,+ pairPreAuthSockets: 0,+ v1PreAuthSockets: 0,+ pendingPrompts: 0,+ discoveryRequestsInWindow: 0,+ nonceRequestsInWindow: 0,+ discoverySourcesInWindow: 0,+ nonceSourcesInWindow: 0,+ })+ })++ it('enforces nonce issuance capacity before mutating its request rate', () => {+ const policy = new RemoteExtensionAdmissionPolicy(+ options({+ nonceIssuanceCap: 1,+ nonceRate: { globalCap: 3, perSourceCap: 3, windowMs: 100 },+ })+ )+ const first = policy.admitNonceRequest(source('192.0.2.1'))+ const refused = policy.admitNonceRequest(source('192.0.2.2'))++ expect(first.ok).toBe(true)+ expect(refused).toEqual({ ok: false, reason: 'capacity' })+ expect(policy.snapshot()).toMatchObject({+ nonceIssuances: 1,+ nonceRequestsInWindow: 1,+ })+ })++ it('releases a nonce slot once and permits a replacement', () => {+ const policy = new RemoteExtensionAdmissionPolicy(+ options({ nonceIssuanceCap: 1 })+ )+ const first = policy.admitNonceRequest(source('192.0.2.1'))+ expect(first.ok).toBe(true)+ if (!first.ok) return++ first.lease.release()+ first.lease.release()++ expect(policy.snapshot().nonceIssuances).toBe(0)+ expect(policy.admitNonceRequest(source('192.0.2.1')).ok).toBe(true)+ expect(policy.snapshot().nonceIssuances).toBe(1)+ })++ it('expires abandoned nonce reservations exactly at their TTL boundary', () => {+ let now = 10+ const policy = new RemoteExtensionAdmissionPolicy(+ options({ nonceIssuanceCap: 1, nonceIssuanceTtlMs: 60, now: () => now })+ )+ const first = policy.admitNonceRequest(source('192.0.2.1'))+ expect(first.ok).toBe(true)++ now = 69+ expect(policy.snapshot().nonceIssuances).toBe(1)+ now = 70+ expect(policy.snapshot().nonceIssuances).toBe(0)+ expect(policy.admitNonceRequest(source('192.0.2.1')).ok).toBe(true)+ })++ it('expires pair and v1 socket reservations on their independent deadlines', () => {+ let now = 0+ const policy = new RemoteExtensionAdmissionPolicy(+ options({+ pairPreAuthSocketCap: 1,+ pairPreAuthSocketTtlMs: 20,+ v1PreAuthSocketCap: 1,+ v1PreAuthSocketTtlMs: 10,+ now: () => now,+ })+ )+ expect(policy.acquirePairPreAuthSocket().ok).toBe(true)+ expect(policy.acquireV1PreAuthSocket().ok).toBe(true)++ now = 10+ expect(policy.snapshot()).toMatchObject({+ pairPreAuthSockets: 1,+ v1PreAuthSockets: 0,+ })+ now = 20+ expect(policy.snapshot()).toMatchObject({+ pairPreAuthSockets: 0,+ v1PreAuthSockets: 0,+ })+ })++ it('keeps pair, v1, nonce, and prompt capacities independent', () => {+ const policy = new RemoteExtensionAdmissionPolicy(+ options({+ nonceIssuanceCap: 1,+ pairPreAuthSocketCap: 1,+ v1PreAuthSocketCap: 1,+ pendingPromptCap: 1,+ })+ )++ expect(policy.acquirePairPreAuthSocket().ok).toBe(true)+ expect(policy.acquirePairPreAuthSocket()).toEqual({+ ok: false,+ reason: 'capacity',+ })+ expect(policy.acquireV1PreAuthSocket().ok).toBe(true)+ expect(policy.acquireV1PreAuthSocket()).toEqual({+ ok: false,+ reason: 'capacity',+ })+ expect(policy.admitNonceRequest(source('192.0.2.1')).ok).toBe(true)+ expect(+ policy.acquirePendingPrompt('chrome-extension://forged-one').ok+ ).toBe(true)+ expect(policy.snapshot()).toMatchObject({+ nonceIssuances: 1,+ pairPreAuthSockets: 1,+ v1PreAuthSockets: 1,+ pendingPrompts: 1,+ })+ })++ it('deduplicates one verified Origin without weakening the global prompt cap', () => {+ const policy = new RemoteExtensionAdmissionPolicy(+ options({ pendingPromptCap: 2 })+ )+ const first = policy.acquirePendingPrompt('chrome-extension://forged-one/')+ const duplicate = policy.acquirePendingPrompt(+ 'chrome-extension://FORGED-ONE'+ )+ const rotated = policy.acquirePendingPrompt('chrome-extension://forged-two')+ const exhausted = policy.acquirePendingPrompt(+ 'chrome-extension://forged-three'+ )++ expect(first.ok && first.disposition).toBe('opened')+ expect(duplicate).toEqual({ ok: true, disposition: 'deduplicated' })+ expect(rotated.ok && rotated.disposition).toBe('opened')+ expect(exhausted).toEqual({ ok: false, reason: 'capacity' })+ expect(policy.snapshot().pendingPrompts).toBe(2)+ })++ it('rejects unsafe prompt origins without allocating a map entry', () => {+ const policy = new RemoteExtensionAdmissionPolicy(options())++ for (const verifiedOrigin of [+ '',+ 'https://example.test',+ 'chrome-extension://one/path',+ 'chrome-extension://one?query',+ 'chrome-extension://one%2falias',+ `chrome-extension://${'a'.repeat(1_025)}`,+ ]) {+ expect(policy.acquirePendingPrompt(verifiedOrigin)).toEqual({+ ok: false,+ reason: 'invalid-verified-origin',+ })+ }+ expect(policy.snapshot().pendingPrompts).toBe(0)+ })++ it('does not let an expired prompt lease release its replacement', () => {+ let now = 0+ const policy = new RemoteExtensionAdmissionPolicy(+ options({ pendingPromptCap: 1, pendingPromptTtlMs: 10, now: () => now })+ )+ const first = policy.acquirePendingPrompt('moz-extension://first-origin')+ expect(first.ok && first.disposition).toBe('opened')+ if (!first.ok || first.disposition !== 'opened') return++ now = 10+ const replacement = policy.acquirePendingPrompt(+ 'moz-extension://first-origin'+ )+ expect(replacement.ok && replacement.disposition).toBe('opened')+ first.lease.release()+ expect(policy.snapshot().pendingPrompts).toBe(1)+ })++ it('makes release and dispose safe across duplicate exceptional cleanup paths', () => {+ const policy = new RemoteExtensionAdmissionPolicy(options())+ const lease = expectLease(policy.acquirePairPreAuthSocket())++ try {+ throw new Error('synthetic handler failure')+ } catch {+ lease.release()+ } finally {+ lease.release()+ policy.dispose()+ policy.dispose()+ }++ expect(policy.snapshot()).toMatchObject({+ nonceIssuances: 0,+ pairPreAuthSockets: 0,+ v1PreAuthSockets: 0,+ pendingPrompts: 0,+ })+ expect(policy.acquirePairPreAuthSocket()).toEqual({+ ok: false,+ reason: 'disposed',+ })+ })++ it('admits concurrent callers only up to the synchronous global cap', async () => {+ const policy = new RemoteExtensionAdmissionPolicy(+ options({ pairPreAuthSocketCap: 3 })+ )+ const decisions = await Promise.all(+ Array.from({ length: 20 }, async () => policy.acquirePairPreAuthSocket())+ )++ expect(decisions.filter((decision) => decision.ok)).toHaveLength(3)+ expect(policy.snapshot().pairPreAuthSockets).toBe(3)+ for (const decision of decisions) {+ if (decision.ok) decision.lease.release()+ }+ expect(policy.snapshot().pairPreAuthSockets).toBe(0)+ })+})++describe('RemoteExtensionAdmissionPolicy request rates', () => {+ it('keeps discovery and nonce global windows independent', () => {+ const policy = new RemoteExtensionAdmissionPolicy(+ options({+ nonceIssuanceCap: 4,+ discoveryRate: { globalCap: 1, perSourceCap: 1, windowMs: 100 },+ nonceRate: { globalCap: 1, perSourceCap: 1, windowMs: 100 },+ })+ )+ const peer = source('192.0.2.1')++ expect(policy.admitDiscoveryRequest(peer)).toEqual({ ok: true })+ expect(policy.admitDiscoveryRequest(peer)).toEqual({+ ok: false,+ reason: 'rate-limited',+ })+ expect(policy.admitNonceRequest(peer).ok).toBe(true)+ expect(policy.admitNonceRequest(peer)).toEqual({+ ok: false,+ reason: 'rate-limited',+ })+ })++ it('expires rate entries at the exact injected-clock window boundary', () => {+ let now = 1_000+ const policy = new RemoteExtensionAdmissionPolicy(+ options({+ now: () => now,+ discoveryRate: { globalCap: 1, perSourceCap: 1, windowMs: 100 },+ })+ )+ const peer = source('192.0.2.1')++ expect(policy.admitDiscoveryRequest(peer).ok).toBe(true)+ now = 1_099+ expect(policy.admitDiscoveryRequest(peer).ok).toBe(false)+ now = 1_100+ expect(policy.admitDiscoveryRequest(peer).ok).toBe(true)+ })++ it('does not let a backwards clock jump reopen a rate window', () => {+ let now = 1_000+ const policy = new RemoteExtensionAdmissionPolicy(+ options({+ now: () => now,+ discoveryRate: { globalCap: 1, perSourceCap: 1, windowMs: 100 },+ })+ )+ const peer = source('192.0.2.1')++ expect(policy.admitDiscoveryRequest(peer).ok).toBe(true)+ now = 900+ expect(policy.admitDiscoveryRequest(peer)).toEqual({+ ok: false,+ reason: 'rate-limited',+ })+ })++ it('does not count a replayed source interval twice for a rate window', () => {+ let now = 1_000+ const policy = new RemoteExtensionAdmissionPolicy(+ options({+ now: () => now,+ discoveryRate: { globalCap: 1, perSourceCap: 1, windowMs: 100 },+ })+ )+ const peer = source('192.0.2.1')++ expect(policy.admitDiscoveryRequest(peer)).toEqual({ ok: true })+ now = 1_050+ expect(policy.admitDiscoveryRequest(peer)).toEqual({+ ok: false,+ reason: 'rate-limited',+ })+ now = 1_000+ expect(policy.admitDiscoveryRequest(peer)).toEqual({+ ok: false,+ reason: 'rate-limited',+ })+ now = 1_050+ expect(policy.admitDiscoveryRequest(peer)).toEqual({+ ok: false,+ reason: 'rate-limited',+ })+ now = 1_099+ expect(policy.admitDiscoveryRequest(peer)).toEqual({+ ok: false,+ reason: 'rate-limited',+ })+ now = 1_100+ expect(policy.admitDiscoveryRequest(peer)).toEqual({ ok: true })+ })++ it('does not count a replayed source interval twice for a capacity lease', () => {+ let now = 1_000+ const policy = new RemoteExtensionAdmissionPolicy(+ options({+ now: () => now,+ pairPreAuthSocketCap: 1,+ pairPreAuthSocketTtlMs: 100,+ })+ )++ expect(policy.acquirePairPreAuthSocket().ok).toBe(true)+ now = 1_050+ expect(policy.acquirePairPreAuthSocket()).toEqual({+ ok: false,+ reason: 'capacity',+ })+ now = 1_000+ expect(policy.acquirePairPreAuthSocket()).toEqual({+ ok: false,+ reason: 'capacity',+ })+ now = 1_050+ expect(policy.acquirePairPreAuthSocket()).toEqual({+ ok: false,+ reason: 'capacity',+ })+ now = 1_099+ expect(policy.acquirePairPreAuthSocket()).toEqual({+ ok: false,+ reason: 'capacity',+ })+ now = 1_100+ expect(policy.acquirePairPreAuthSocket().ok).toBe(true)+ })++ it('expires records that existed before an unreplayed forward jump', () => {+ let now = 1_000+ const policy = new RemoteExtensionAdmissionPolicy(+ options({+ now: () => now,+ pairPreAuthSocketCap: 1,+ pairPreAuthSocketTtlMs: 100,+ discoveryRate: { globalCap: 1, perSourceCap: 1, windowMs: 100 },+ })+ )+ const peer = source('192.0.2.1')++ expect(policy.acquirePairPreAuthSocket().ok).toBe(true)+ expect(policy.admitDiscoveryRequest(peer)).toEqual({ ok: true })+ now = 1_100+ expect(policy.acquirePairPreAuthSocket().ok).toBe(true)+ expect(policy.admitDiscoveryRequest(peer)).toEqual({ ok: true })+ })++ it('bounds rotating source maps by the independent global window cap', () => {+ let now = 0+ const policy = new RemoteExtensionAdmissionPolicy(+ options({+ now: () => now,+ trustedProxyAddresses: ['192.0.2.10'],+ discoveryRate: { globalCap: 3, perSourceCap: 2, windowMs: 100 },+ })+ )++ for (const forwarded of ['198.51.100.1', '198.51.100.2', '198.51.100.3']) {+ expect(+ policy.admitDiscoveryRequest(+ source('192.0.2.10', ['X-Forwarded-For', forwarded])+ ).ok+ ).toBe(true)+ }+ expect(+ policy.admitDiscoveryRequest(+ source('192.0.2.10', ['X-Forwarded-For', '198.51.100.4'])+ )+ ).toEqual({ ok: false, reason: 'rate-limited' })+ expect(policy.snapshot().discoverySourcesInWindow).toBe(3)++ now = 100+ expect(+ policy.admitDiscoveryRequest(+ source('192.0.2.10', ['X-Forwarded-For', '198.51.100.4'])+ ).ok+ ).toBe(true)+ expect(policy.snapshot().discoverySourcesInWindow).toBe(1)+ })++ it('does not allocate source buckets for refused rotating attempts', () => {+ const policy = new RemoteExtensionAdmissionPolicy(+ options({+ trustedProxyAddresses: ['192.0.2.10'],+ nonceIssuanceCap: 10,+ nonceRate: { globalCap: 2, perSourceCap: 1, windowMs: 100 },+ })+ )++ expect(+ policy.admitNonceRequest(+ source('192.0.2.10', ['Forwarded', 'for=198.51.100.1'])+ ).ok+ ).toBe(true)+ expect(+ policy.admitNonceRequest(+ source('192.0.2.10', ['Forwarded', 'for=198.51.100.1'])+ )+ ).toEqual({ ok: false, reason: 'rate-limited' })+ expect(policy.snapshot().nonceSourcesInWindow).toBe(1)+ })+})++describe('RemoteExtensionAdmissionPolicy source boundary', () => {+ it('ignores all forwarded fields from an arbitrary direct peer', () => {+ const policy = new RemoteExtensionAdmissionPolicy(options())+ const decision = policy.resolveClientSource(+ source('192.0.2.50', [+ 'Forwarded',+ 'for=198.51.100.1, for=198.51.100.2',+ 'X-Forwarded-For',+ 'not-an-ip',+ 'X-Forwarded-For',+ '203.0.113.2',+ ])+ )++ expect(decision).toEqual({+ ok: true,+ source: '192.0.2.50',+ provenance: 'direct-peer',+ })+ })++ it('fails closed when the socket has no direct peer address', () => {+ const policy = new RemoteExtensionAdmissionPolicy(options())++ expect(+ policy.resolveClientSource({+ directPeerAddress: undefined,+ rawHeaders: ['X-Forwarded-For', '198.51.100.1'],+ })+ ).toEqual({ ok: false, reason: 'invalid-direct-peer' })+ })++ it('prevents arbitrary XFF rotation from obtaining new rate buckets', () => {+ const policy = new RemoteExtensionAdmissionPolicy(+ options({+ discoveryRate: { globalCap: 10, perSourceCap: 1, windowMs: 100 },+ })+ )++ expect(+ policy.admitDiscoveryRequest(+ source('192.0.2.50', ['X-Forwarded-For', '198.51.100.1'])+ ).ok+ ).toBe(true)+ for (const forged of ['198.51.100.2', '198.51.100.3']) {+ expect(+ policy.admitDiscoveryRequest(+ source('192.0.2.50', ['X-Forwarded-For', forged])+ )+ ).toEqual({ ok: false, reason: 'rate-limited' })+ }+ expect(policy.snapshot().discoverySourcesInWindow).toBe(1)+ })++ it.each([+ ['dotted then mapped', '192.0.2.50', '::ffff:192.0.2.50'],+ ['mapped then dotted', '::ffff:c000:232', '192.0.2.50'],+ ])(+ 'does not give one IPv4 peer two source buckets via %s representation',+ (_label, firstPeer, secondPeer) => {+ const policy = new RemoteExtensionAdmissionPolicy(+ options({+ discoveryRate: { globalCap: 10, perSourceCap: 1, windowMs: 100 },+ })+ )++ expect(policy.admitDiscoveryRequest(source(firstPeer))).toEqual({+ ok: true,+ })+ expect(policy.admitDiscoveryRequest(source(secondPeer))).toEqual({+ ok: false,+ reason: 'rate-limited',+ })+ expect(policy.snapshot().discoverySourcesInWindow).toBe(1)+ }+ )++ it('shares a trusted-proxy forwarded-source bucket across dotted and mapped IPv4', () => {+ const policy = new RemoteExtensionAdmissionPolicy(+ options({+ trustedProxyAddresses: ['192.0.2.10'],+ discoveryRate: { globalCap: 10, perSourceCap: 1, windowMs: 100 },+ })+ )++ expect(+ policy.admitDiscoveryRequest(+ source('192.0.2.10', ['X-Forwarded-For', '198.51.100.7'])+ )+ ).toEqual({ ok: true })+ expect(+ policy.admitDiscoveryRequest(+ source('::ffff:192.0.2.10', ['X-Forwarded-For', '::ffff:198.51.100.7'])+ )+ ).toEqual({ ok: false, reason: 'rate-limited' })+ expect(policy.snapshot().discoverySourcesInWindow).toBe(1)+ })++ it.each([+ [+ 'X-Forwarded-For IPv4',+ ['X-Forwarded-For', '198.51.100.7'],+ '198.51.100.7',+ ],+ [+ 'X-Forwarded-For IPv6',+ ['X-Forwarded-For', '2001:0db8:0:0::7'],+ '2001:db8::7',+ ],+ ['Forwarded IPv4', ['Forwarded', 'for=198.51.100.8'], '198.51.100.8'],+ [+ 'Forwarded IPv4 with parameters',+ ['Forwarded', 'for=198.51.100.9;proto=https;host=motrix.example'],+ '198.51.100.9',+ ],+ [+ 'Forwarded quoted IPv6',+ ['Forwarded', 'for="[2001:0db8:0:0::9]";proto=https'],+ '2001:db8::9',+ ],+ [+ 'Forwarded quoted IPv4-mapped IPv6',+ ['Forwarded', 'for="[::ffff:198.51.100.9]";proto=https'],+ '198.51.100.9',+ ],+ ])(+ 'accepts one unambiguous %s from a trusted proxy',+ (_label, headers, ip) => {+ const policy = new RemoteExtensionAdmissionPolicy(+ options({ trustedProxyAddresses: ['192.0.2.10'] })+ )++ expect(policy.resolveClientSource(source('192.0.2.10', headers))).toEqual(+ {+ ok: true,+ source: ip,+ provenance: 'trusted-proxy',+ }+ )+ }+ )++ it('canonicalizes the direct peer before checking the proxy allowlist', () => {+ const policy = new RemoteExtensionAdmissionPolicy(+ options({ trustedProxyAddresses: ['2001:db8::1'] })+ )++ expect(+ policy.resolveClientSource(+ source('2001:0db8:0:0:0:0:0:1', ['X-Forwarded-For', '198.51.100.10'])+ )+ ).toEqual({+ ok: true,+ source: '198.51.100.10',+ provenance: 'trusted-proxy',+ })+ })++ it.each(['192.0.2.10', '::ffff:192.0.2.10'])(+ 'trusts a canonical IPv4 proxy when the socket reports %s',+ (directPeer) => {+ const policy = new RemoteExtensionAdmissionPolicy(+ options({ trustedProxyAddresses: ['192.0.2.10'] })+ )++ expect(+ policy.resolveClientSource(+ source(directPeer, ['X-Forwarded-For', '198.51.100.10'])+ )+ ).toEqual({+ ok: true,+ source: '198.51.100.10',+ provenance: 'trusted-proxy',+ })+ }+ )++ it('falls back only to the trusted proxy direct address when no forwarding field exists', () => {+ const policy = new RemoteExtensionAdmissionPolicy(+ options({ trustedProxyAddresses: ['192.0.2.10'] })+ )++ expect(policy.resolveClientSource(source('192.0.2.10'))).toEqual({+ ok: true,+ source: '192.0.2.10',+ provenance: 'direct-peer',+ })+ })++ it.each([+ [+ 'duplicate XFF',+ ['X-Forwarded-For', '198.51.100.1', 'x-forwarded-for', '198.51.100.2'],+ ],+ [+ 'both standards',+ ['Forwarded', 'for=198.51.100.1', 'X-Forwarded-For', '198.51.100.1'],+ ],+ ['XFF list', ['X-Forwarded-For', '198.51.100.1, 198.51.100.2']],+ ['Forwarded list', ['Forwarded', 'for=198.51.100.1,for=198.51.100.2']],+ ['duplicate for', ['Forwarded', 'for=198.51.100.1;for=198.51.100.2']],+ ])('rejects ambiguous trusted-proxy source: %s', (_label, headers) => {+ const policy = new RemoteExtensionAdmissionPolicy(+ options({ trustedProxyAddresses: ['192.0.2.10'] })+ )++ expect(policy.resolveClientSource(source('192.0.2.10', headers))).toEqual({+ ok: false,+ reason: 'ambiguous-forwarded-source',+ })+ })++ it.each([+ ['invalid direct peer', 'not-an-ip', []],+ ['invalid XFF', '192.0.2.10', ['X-Forwarded-For', 'not-an-ip']],+ ['spaced XFF', '192.0.2.10', ['X-Forwarded-For', ' 198.51.100.1']],+ ['XFF port', '192.0.2.10', ['X-Forwarded-For', '198.51.100.1:443']],+ ['unknown Forwarded', '192.0.2.10', ['Forwarded', 'for=unknown']],+ [+ 'spaced Forwarded',+ '192.0.2.10',+ ['Forwarded', 'for=198.51.100.1; proto=https'],+ ],+ [+ 'Forwarded IPv4 port',+ '192.0.2.10',+ ['Forwarded', 'for=198.51.100.1:443'],+ ],+ [+ 'unquoted Forwarded IPv4-mapped IPv6',+ '192.0.2.10',+ ['Forwarded', 'for=::ffff:198.51.100.1'],+ ],+ ['missing for', '192.0.2.10', ['Forwarded', 'proto=https']],+ ['odd raw headers', '192.0.2.10', ['Forwarded']],+ ])('rejects malformed source input: %s', (_label, peer, headers) => {+ const policy = new RemoteExtensionAdmissionPolicy(+ options({ trustedProxyAddresses: ['192.0.2.10'] })+ )+ const decision = policy.resolveClientSource(source(peer, headers))++ expect(decision.ok).toBe(false)+ if (!decision.ok) {+ expect(['invalid-direct-peer', 'malformed-forwarded-source']).toContain(+ decision.reason+ )+ expect(JSON.stringify(decision)).not.toContain('198.51.100.1')+ }+ })++ it('bounds trusted-proxy header parsing', () => {+ const policy = new RemoteExtensionAdmissionPolicy(+ options({ trustedProxyAddresses: ['192.0.2.10'] })+ )++ expect(+ policy.resolveClientSource(+ source(+ '192.0.2.10',+ Array.from({ length: 258 }, () => 'irrelevant')+ )+ )+ ).toEqual({ ok: false, reason: 'malformed-forwarded-source' })+ expect(+ policy.resolveClientSource(+ source('192.0.2.10', ['X-Forwarded-For', '1'.repeat(1_025)])+ )+ ).toEqual({ ok: false, reason: 'malformed-forwarded-source' })+ expect(+ policy.resolveClientSource(+ source('192.0.2.10', ['x'.repeat(129), 'ignored'])+ )+ ).toEqual({ ok: false, reason: 'malformed-forwarded-source' })+ })+})++describe('RemoteExtensionAdmissionPolicy configuration', () => {+ it('requires the exact parser-issued enabled configuration capability', () => {+ const disabled = parseRemoteExtensionConfig({})+ const invalid = parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'https://motrix.example/bridge',+ MOTRIX_PUBLIC_URL: 'https://motrix.example/operator',+ })+ const copied = { ...ENABLED_CONFIG } as RemoteExtensionConfig+ const forged = {+ status: 'enabled',+ publicWebSocketBaseUrl: 'wss://motrix.example/bridge',+ publicWebSocketAuthority: 'motrix.example',+ publicWebSocketBasePath: '/bridge',+ publicOperatorBaseUrl: 'https://motrix.example/operator',+ publicOperatorAuthority: 'motrix.example',+ publicOperatorBasePath: '/operator',+ } as unknown as RemoteExtensionConfig++ for (const config of [disabled, invalid, copied, forged]) {+ expect(+ () => new RemoteExtensionAdmissionPolicy(options({ config }))+ ).toThrowError('invalid remote extension admission configuration')+ }+ expect(+ new RemoteExtensionAdmissionPolicy(options()).snapshot()+ ).toMatchObject({ nonceIssuances: 0, pairPreAuthSockets: 0 })+ })++ it('accepts the exact clock horizon and preserves live state when the next tick overflows', () => {+ let now = 0+ const maximumHorizonMs = 150+ const boundary = Number.MAX_SAFE_INTEGER - maximumHorizonMs+ const policy = new RemoteExtensionAdmissionPolicy(+ options({+ now: () => now,+ nonceIssuanceCap: 2,+ pairPreAuthSocketCap: 2,+ v1PreAuthSocketCap: 2,+ pendingPromptCap: 2,+ discoveryRate: { globalCap: 2, perSourceCap: 2, windowMs: 100 },+ nonceRate: { globalCap: 2, perSourceCap: 2, windowMs: 100 },+ })+ )+ const peer = source('192.0.2.1')+ expect(policy.snapshot().pairPreAuthSockets).toBe(0)++ // The equality boundary is valid. Allocate after reaching it so every+ // table contains live state immediately before the rejected +1 sample.+ now = boundary+ expect(policy.acquirePairPreAuthSocket().ok).toBe(true)+ expect(policy.acquireV1PreAuthSocket().ok).toBe(true)+ expect(policy.admitNonceRequest(peer).ok).toBe(true)+ expect(+ policy.acquirePendingPrompt('chrome-extension://boundary-origin').ok+ ).toBe(true)+ expect(policy.admitDiscoveryRequest(peer)).toEqual({ ok: true })+ const beforeOverflow = policy.snapshot()++ now = boundary + 1+ const fixedError = 'invalid remote extension admission configuration'+ expect(() => policy.snapshot()).toThrowError(fixedError)+ expect(() => policy.acquirePairPreAuthSocket()).toThrowError(fixedError)+ expect(() => policy.admitNonceRequest(peer)).toThrowError(fixedError)+ expect(() =>+ policy.acquirePendingPrompt('chrome-extension://new-origin')+ ).toThrowError(fixedError)++ // A rejected sample cannot advance the high-water mark, sweep leases,+ // prune rates, or allocate anything. Returning to the last safe sample+ // exposes the exact pre-overflow state.+ now = boundary+ expect(policy.snapshot()).toEqual(beforeOverflow)+ })++ it('rejects an unrepresentable clock jump atomically and recovers on a safe sample', () => {+ let now = 0+ const policy = new RemoteExtensionAdmissionPolicy(+ options({+ now: () => now,+ nonceIssuanceCap: 1,+ pairPreAuthSocketCap: 1,+ v1PreAuthSocketCap: 1,+ pendingPromptCap: 1,+ discoveryRate: { globalCap: 1, perSourceCap: 1, windowMs: 100 },+ nonceRate: { globalCap: 1, perSourceCap: 1, windowMs: 100 },+ })+ )+ const peer = source('192.0.2.1')+ const fixedError = 'invalid remote extension admission configuration'++ expect(policy.snapshot()).toMatchObject({+ nonceIssuances: 0,+ pairPreAuthSockets: 0,+ v1PreAuthSockets: 0,+ pendingPrompts: 0,+ discoveryRequestsInWindow: 0,+ nonceRequestsInWindow: 0,+ })+ now = Number.MAX_SAFE_INTEGER+ expect(() => policy.admitNonceRequest(peer)).toThrowError(fixedError)+ expect(() => policy.acquirePairPreAuthSocket()).toThrowError(fixedError)+ expect(() => policy.acquireV1PreAuthSocket()).toThrowError(fixedError)+ expect(() =>+ policy.acquirePendingPrompt('chrome-extension://clock-overflow')+ ).toThrowError(fixedError)+ expect(() => policy.admitDiscoveryRequest(peer)).toThrowError(fixedError)++ now = 0+ expect(policy.snapshot()).toMatchObject({+ nonceIssuances: 0,+ pairPreAuthSockets: 0,+ v1PreAuthSockets: 0,+ pendingPrompts: 0,+ discoveryRequestsInWindow: 0,+ nonceRequestsInWindow: 0,+ })+ now = 1+ expect(policy.admitNonceRequest(peer).ok).toBe(true)+ expect(policy.acquirePairPreAuthSocket().ok).toBe(true)+ expect(policy.acquireV1PreAuthSocket().ok).toBe(true)+ expect(+ policy.acquirePendingPrompt('chrome-extension://clock-overflow').ok+ ).toBe(true)+ expect(policy.admitDiscoveryRequest(peer)).toEqual({ ok: true })+ })++ it.each([+ { nonceIssuanceCap: 0 },+ { pairPreAuthSocketTtlMs: Number.POSITIVE_INFINITY },+ { pendingPromptCap: 1.5 },+ { discoveryRate: { globalCap: 0, perSourceCap: 1, windowMs: 100 } },+ { nonceRate: { globalCap: 1, perSourceCap: -1, windowMs: 100 } },+ ])('fails closed on an invalid numeric bound', (override) => {+ expect(+ () =>+ new RemoteExtensionAdmissionPolicy(+ options(override as Partial<RemoteExtensionAdmissionPolicyOptions>)+ )+ ).toThrowError('invalid remote extension admission configuration')+ })++ it.each([+ ['192.0.2.010'],+ ['::ffff:192.0.2.10'],+ ['2001:0DB8::1'],+ ['[2001:db8::1]'],+ ['proxy.example'],+ ['192.0.2.1', '192.0.2.1'],+ ])('requires a unique canonical exact-IP proxy allowlist', (...entries) => {+ expect(+ () =>+ new RemoteExtensionAdmissionPolicy(+ options({ trustedProxyAddresses: entries })+ )+ ).toThrowError('invalid remote extension admission configuration')+ })++ it('redacts an injected clock failure behind a fixed error', () => {+ const policy = new RemoteExtensionAdmissionPolicy(+ options({+ now: () => {+ throw new Error('request-derived-secret')+ },+ })+ )++ expect(() => policy.snapshot()).toThrowError(+ 'invalid remote extension admission configuration'+ )+ })+})diff --git a/src/server/bridge/remote-extension-admission-policy.ts b/src/server/bridge/remote-extension-admission-policy.tsnew file mode 100644index 00000000..649b5105--- /dev/null+++ b/src/server/bridge/remote-extension-admission-policy.ts@@ -0,0 +1,818 @@+import { isIP } from 'node:net'+import { performance } from 'node:perf_hooks'+import {+ isIssuedRemoteExtensionConfig,+ type RemoteExtensionConfig,+} from './remote-extension-config'++const MAX_RAW_HEADER_ENTRIES = 256+const MAX_RAW_HEADER_NAME_LENGTH = 128+const MAX_FORWARDING_HEADER_LENGTH = 1_024+const MAX_VERIFIED_ORIGIN_LENGTH = 1_024+const MAX_TRUSTED_PROXY_ADDRESSES = 64++export interface RemoteExtensionRateLimit {+ readonly globalCap: number+ readonly perSourceCap: number+ readonly windowMs: number+}++export interface RemoteExtensionAdmissionPolicyOptions {+ /** Parser-issued capability. A copied/deserialized/forged config cannot+ * create admission state, even when it is structurally identical. */+ readonly config: RemoteExtensionConfig+ /** Outstanding, unconsumed nonce reservations. */+ readonly nonceIssuanceCap?: number+ readonly nonceIssuanceTtlMs?: number+ /** Upgraded sockets that have not completed MBP1 first-pair. */+ readonly pairPreAuthSocketCap?: number+ readonly pairPreAuthSocketTtlMs?: number+ /** Upgraded sockets that have not completed MBP1 reconnect. */+ readonly v1PreAuthSocketCap?: number+ readonly v1PreAuthSocketTtlMs?: number+ /** Prompts visible to, but not yet settled by, an authenticated operator. */+ readonly pendingPromptCap?: number+ readonly pendingPromptTtlMs?: number+ /** Public discovery requests. Independent from nonce issuance. */+ readonly discoveryRate?: RemoteExtensionRateLimit+ /** Public nonce requests. Independent from discovery. */+ readonly nonceRate?: RemoteExtensionRateLimit+ /** Exact canonical IP addresses only. Hostnames and CIDRs are not accepted. */+ readonly trustedProxyAddresses?: readonly string[]+ /**+ * Injectable millisecond source. Only progress beyond its observed+ * high-water mark is accumulated, so rollback/replay cannot age entries.+ */+ readonly now?: () => number+}++export interface RemoteExtensionClientSourceInput {+ readonly directPeerAddress: string | undefined+ /** Original HTTP/1 name/value vector, not a coalesced headers object. */+ readonly rawHeaders?: readonly string[]+}++export type RemoteExtensionClientSourceDecision =+ | {+ readonly ok: true+ readonly source: string+ readonly provenance: 'direct-peer' | 'trusted-proxy'+ }+ | {+ readonly ok: false+ readonly reason:+ | 'invalid-direct-peer'+ | 'ambiguous-forwarded-source'+ | 'malformed-forwarded-source'+ }++export type RemoteExtensionAdmissionLeaseKind =+ | 'nonce-issuance'+ | 'pair-pre-auth-socket'+ | 'v1-pre-auth-socket'+ | 'pending-prompt'++export interface RemoteExtensionAdmissionLease {+ readonly kind: RemoteExtensionAdmissionLeaseKind+ /**+ * Idempotent across success, failure, timeout, close, and shutdown paths.+ * The policy's TTL bounds bookkeeping; transport wiring must still close the+ * underlying socket or prompt on its own equal-or-shorter protocol deadline.+ */+ release(): void+}++export type RemoteExtensionAdmissionRejection =+ | 'capacity'+ | 'rate-limited'+ | 'invalid-verified-origin'+ | 'invalid-direct-peer'+ | 'ambiguous-forwarded-source'+ | 'malformed-forwarded-source'+ | 'disposed'++export type RemoteExtensionAdmissionDecision =+ | { readonly ok: true }+ | {+ readonly ok: false+ readonly reason: RemoteExtensionAdmissionRejection+ }++export type RemoteExtensionLeaseDecision =+ | { readonly ok: true; readonly lease: RemoteExtensionAdmissionLease }+ | {+ readonly ok: false+ readonly reason: RemoteExtensionAdmissionRejection+ }++export type RemoteExtensionPromptAdmissionDecision =+ | {+ readonly ok: true+ readonly disposition: 'opened'+ readonly lease: RemoteExtensionAdmissionLease+ }+ | { readonly ok: true; readonly disposition: 'deduplicated' }+ | {+ readonly ok: false+ readonly reason: RemoteExtensionAdmissionRejection+ }++export interface RemoteExtensionAdmissionSnapshot {+ readonly nonceIssuances: number+ readonly pairPreAuthSockets: number+ readonly v1PreAuthSockets: number+ readonly pendingPrompts: number+ readonly discoveryRequestsInWindow: number+ readonly nonceRequestsInWindow: number+ readonly discoverySourcesInWindow: number+ readonly nonceSourcesInWindow: number+}++const DEFAULT_DISCOVERY_RATE: RemoteExtensionRateLimit = Object.freeze({+ globalCap: 120,+ perSourceCap: 30,+ windowMs: 60_000,+})++const DEFAULT_NONCE_RATE: RemoteExtensionRateLimit = Object.freeze({+ globalCap: 60,+ perSourceCap: 10,+ windowMs: 60_000,+})++export const DEFAULT_REMOTE_EXTENSION_ADMISSION_LIMITS = Object.freeze({+ nonceIssuanceCap: 32,+ nonceIssuanceTtlMs: 60_000,+ pairPreAuthSocketCap: 32,+ pairPreAuthSocketTtlMs: 150_000,+ v1PreAuthSocketCap: 32,+ v1PreAuthSocketTtlMs: 15_000,+ pendingPromptCap: 3,+ pendingPromptTtlMs: 120_000,+ discoveryRate: DEFAULT_DISCOVERY_RATE,+ nonceRate: DEFAULT_NONCE_RATE,+})++const ALLOWED: RemoteExtensionAdmissionDecision = Object.freeze({ ok: true })++function rejected(reason: RemoteExtensionAdmissionRejection): {+ readonly ok: false+ readonly reason: RemoteExtensionAdmissionRejection+} {+ return Object.freeze({ ok: false, reason })+}++function invalidConfiguration(): never {+ throw new Error('invalid remote extension admission configuration')+}++function requirePositiveSafeInteger(value: number): number {+ if (!Number.isSafeInteger(value) || value <= 0) invalidConfiguration()+ return value+}++function validateRateLimit(+ value: RemoteExtensionRateLimit+): RemoteExtensionRateLimit {+ return Object.freeze({+ globalCap: requirePositiveSafeInteger(value.globalCap),+ perSourceCap: requirePositiveSafeInteger(value.perSourceCap),+ windowMs: requirePositiveSafeInteger(value.windowMs),+ })+}++function containsUnsafeHeaderCharacter(value: string): boolean {+ for (let index = 0; index < value.length; index += 1) {+ const code = value.charCodeAt(index)+ if (code <= 0x1f || code === 0x7f) return true+ }+ return false+}++function mappedIpv4Address(value: string): string | null {+ const match = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/u.exec(value)+ if (match === null) return null++ const high = Number.parseInt(match[1] ?? '', 16)+ const low = Number.parseInt(match[2] ?? '', 16)+ return [high >>> 8, high & 0xff, low >>> 8, low & 0xff].join('.')+}++/**+ * Canonical dotted IPv4 or lower-case RFC 5952-style IPv6, without brackets.+ * IPv4-mapped IPv6 is deliberately collapsed to dotted IPv4 so one network+ * peer cannot acquire separate allowlist identities or rate-limit buckets via+ * the two socket address representations.+ */+function canonicalIpAddress(value: unknown): string | null {+ if (+ typeof value !== 'string' ||+ value.length === 0 ||+ value.length > 64 ||+ containsUnsafeHeaderCharacter(value) ||+ /\p{White_Space}/u.test(value) ||+ value.includes('%') ||+ value.includes('[') ||+ value.includes(']')+ ) {+ return null+ }++ const version = isIP(value)+ if (version === 4) return value+ if (version !== 6) return null++ try {+ const hostname = new URL(`http://[${value}]/`).hostname+ if (!hostname.startsWith('[') || !hostname.endsWith(']')) return null+ const canonical = hostname.slice(1, -1).toLowerCase()+ return mappedIpv4Address(canonical) ?? canonical+ } catch {+ return null+ }+}++function parseTrustedProxyAddresses(+ values: readonly string[] | undefined+): ReadonlySet<string> {+ if (values === undefined) return new Set()+ if (!Array.isArray(values) || values.length > MAX_TRUSTED_PROXY_ADDRESSES) {+ invalidConfiguration()+ }++ const result = new Set<string>()+ for (const value of values) {+ const canonical = canonicalIpAddress(value)+ if (canonical === null || canonical !== value || result.has(canonical)) {+ invalidConfiguration()+ }+ result.add(canonical)+ }+ return result+}++type ForwardedParseResult =+ | { readonly ok: true; readonly source: string }+ | {+ readonly ok: false+ readonly reason:+ | 'ambiguous-forwarded-source'+ | 'malformed-forwarded-source'+ }++function malformedForwarding(): ForwardedParseResult {+ return Object.freeze({ ok: false, reason: 'malformed-forwarded-source' })+}++function ambiguousForwarding(): ForwardedParseResult {+ return Object.freeze({ ok: false, reason: 'ambiguous-forwarded-source' })+}++function parseXForwardedFor(value: string): ForwardedParseResult {+ if (+ value.length === 0 ||+ value.length > MAX_FORWARDING_HEADER_LENGTH ||+ value.includes(',') ||+ value.trim() !== value ||+ containsUnsafeHeaderCharacter(value)+ ) {+ return value.includes(',') ? ambiguousForwarding() : malformedForwarding()+ }+ const source = canonicalIpAddress(value)+ return source === null ? malformedForwarding() : { ok: true, source }+}++function parseForwardedForValue(value: string): string | null {+ if (value.startsWith('"')) {+ if (!value.endsWith('"') || value.length < 4 || value.includes('\\')) {+ return null+ }+ const inner = value.slice(1, -1)+ if (!inner.startsWith('[') || !inner.endsWith(']')) return null+ const literal = inner.slice(1, -1)+ if (isIP(literal) !== 6) return null+ return canonicalIpAddress(literal)+ }++ if (value.includes('"') || value.includes('[') || value.includes(']')) {+ return null+ }+ if (isIP(value) !== 4) return null+ return canonicalIpAddress(value)+}++function parseForwarded(value: string): ForwardedParseResult {+ if (+ value.length === 0 ||+ value.length > MAX_FORWARDING_HEADER_LENGTH ||+ containsUnsafeHeaderCharacter(value) ||+ /\p{White_Space}/u.test(value)+ ) {+ return malformedForwarding()+ }+ if (value.includes(',')) return ambiguousForwarding()++ const parameters = value.split(';')+ const names = new Set<string>()+ let source: string | null = null+ for (const parameter of parameters) {+ if (parameter.length === 0 || parameter.trim() !== parameter) {+ return malformedForwarding()+ }+ const separator = parameter.indexOf('=')+ if (separator <= 0 || separator === parameter.length - 1) {+ return malformedForwarding()+ }+ const name = parameter.slice(0, separator).toLowerCase()+ const parameterValue = parameter.slice(separator + 1)+ if (!/^[!#$%&'*+.^_`|~0-9a-z-]+$/u.test(name)) {+ return malformedForwarding()+ }+ if (names.has(name)) {+ return name === 'for' ? ambiguousForwarding() : malformedForwarding()+ }+ names.add(name)++ if (name === 'for') {+ source = parseForwardedForValue(parameterValue)+ if (source === null) return malformedForwarding()+ continue+ }+ if (+ parameterValue.length > MAX_FORWARDING_HEADER_LENGTH ||+ containsUnsafeHeaderCharacter(parameterValue) ||+ parameterValue.includes(',')+ ) {+ return malformedForwarding()+ }+ }++ return source === null ? malformedForwarding() : { ok: true, source }+}++function resolveForwardedSource(+ rawHeaders: readonly string[]+): ForwardedParseResult | null {+ if (+ !Array.isArray(rawHeaders) ||+ rawHeaders.length > MAX_RAW_HEADER_ENTRIES ||+ rawHeaders.length % 2 !== 0+ ) {+ return malformedForwarding()+ }++ const forwarded: string[] = []+ const xForwardedFor: string[] = []+ for (let index = 0; index < rawHeaders.length; index += 2) {+ const name = rawHeaders[index]+ const value = rawHeaders[index + 1]+ if (typeof name !== 'string' || typeof value !== 'string') {+ return malformedForwarding()+ }+ if (+ name.length === 0 ||+ name.length > MAX_RAW_HEADER_NAME_LENGTH ||+ containsUnsafeHeaderCharacter(name)+ ) {+ return malformedForwarding()+ }+ const normalizedName = name.toLowerCase()+ if (normalizedName === 'forwarded') forwarded.push(value)+ if (normalizedName === 'x-forwarded-for') xForwardedFor.push(value)+ }++ if (forwarded.length === 0 && xForwardedFor.length === 0) return null+ if (+ forwarded.length > 1 ||+ xForwardedFor.length > 1 ||+ (forwarded.length === 1 && xForwardedFor.length === 1)+ ) {+ return ambiguousForwarding()+ }+ if (forwarded.length === 1) return parseForwarded(forwarded[0] ?? '')+ return parseXForwardedFor(xForwardedFor[0] ?? '')+}++function normalizeVerifiedOrigin(value: unknown): string | null {+ if (+ typeof value !== 'string' ||+ value.length === 0 ||+ value.length > MAX_VERIFIED_ORIGIN_LENGTH ||+ containsUnsafeHeaderCharacter(value) ||+ /\p{White_Space}/u.test(value) ||+ value.includes('\\') ||+ value.includes('%')+ ) {+ return null+ }++ let parsed: URL+ try {+ parsed = new URL(value)+ } catch {+ return null+ }+ if (+ (parsed.protocol !== 'chrome-extension:' &&+ parsed.protocol !== 'moz-extension:') ||+ parsed.host === '' ||+ parsed.hostname !== parsed.host ||+ parsed.username !== '' ||+ parsed.password !== '' ||+ parsed.search !== '' ||+ parsed.hash !== '' ||+ (parsed.pathname !== '' && parsed.pathname !== '/') ||+ !/^[a-z0-9-]+$/u.test(parsed.hostname.toLowerCase())+ ) {+ return null+ }+ return `${parsed.protocol}//${parsed.hostname.toLowerCase()}`+}++class AdmissionLease implements RemoteExtensionAdmissionLease {+ private released = false++ constructor(+ readonly kind: RemoteExtensionAdmissionLeaseKind,+ private readonly releaseSlot: () => void+ ) {}++ release(): void {+ if (this.released) return+ this.released = true+ this.releaseSlot()+ }+}++class ExpiringCapacity {+ private readonly entries = new Map<symbol, number>()++ constructor(+ private readonly cap: number,+ private readonly ttlMs: number,+ private readonly kind: RemoteExtensionAdmissionLeaseKind+ ) {}++ hasCapacity(now: number): boolean {+ this.sweep(now)+ return this.entries.size < this.cap+ }++ acquire(now: number): RemoteExtensionAdmissionLease | null {+ if (!this.hasCapacity(now)) return null+ const leaseId = Symbol(this.kind)+ const expiresAt = now + this.ttlMs+ this.entries.set(leaseId, expiresAt)+ return new AdmissionLease(this.kind, () => {+ this.entries.delete(leaseId)+ })+ }++ size(now: number): number {+ this.sweep(now)+ return this.entries.size+ }++ clear(): void {+ this.entries.clear()+ }++ private sweep(now: number): void {+ for (const [leaseId, expiresAt] of this.entries) {+ if (expiresAt <= now) this.entries.delete(leaseId)+ }+ }+}++class SlidingWindowRate {+ private globalAttempts: number[] = []+ private readonly sourceAttempts = new Map<string, number[]>()++ constructor(private readonly options: RemoteExtensionRateLimit) {}++ admit(source: string, now: number): boolean {+ this.prune(now)+ if (this.globalAttempts.length >= this.options.globalCap) return false++ const perSource = this.sourceAttempts.get(source) ?? []+ if (perSource.length >= this.options.perSourceCap) return false++ this.globalAttempts.push(now)+ perSource.push(now)+ this.sourceAttempts.set(source, perSource)+ return true+ }++ snapshot(now: number): {+ readonly requests: number+ readonly sources: number+ } {+ this.prune(now)+ return {+ requests: this.globalAttempts.length,+ sources: this.sourceAttempts.size,+ }+ }++ clear(): void {+ this.globalAttempts = []+ this.sourceAttempts.clear()+ }++ private prune(now: number): void {+ const cutoff = now - this.options.windowMs+ this.globalAttempts = this.globalAttempts.filter(+ (timestamp) => timestamp > cutoff+ )+ for (const [source, timestamps] of this.sourceAttempts) {+ const recent = timestamps.filter((timestamp) => timestamp > cutoff)+ if (recent.length === 0) this.sourceAttempts.delete(source)+ else this.sourceAttempts.set(source, recent)+ }+ }+}++interface PendingPromptSlot {+ readonly leaseId: symbol+ readonly expiresAt: number+}++class MonotonicElapsedClock {+ private sourceHighWaterMark: number | undefined+ private logicalNow = 0++ constructor(+ private readonly source: () => number,+ private readonly maximumHorizonMs: number+ ) {}++ now(): number {+ let candidate: number+ try {+ candidate = this.source()+ } catch {+ invalidConfiguration()+ }+ if (!Number.isSafeInteger(candidate) || candidate < 0) {+ invalidConfiguration()+ }++ const previousHighWaterMark = this.sourceHighWaterMark+ if (previousHighWaterMark === undefined) {+ this.sourceHighWaterMark = candidate+ return this.logicalNow+ }+ if (candidate <= previousHighWaterMark) return this.logicalNow++ const delta = candidate - previousHighWaterMark+ const maximumSafeNow = Number.MAX_SAFE_INTEGER - this.maximumHorizonMs+ if (delta > maximumSafeNow - this.logicalNow) invalidConfiguration()++ this.sourceHighWaterMark = candidate+ this.logicalNow += delta+ return this.logicalNow+ }+}++/**+ * Pure, unwired admission boundary for the public remote-Extension surface.+ *+ * Every client-controlled cardinality is bounded by an independent global+ * cap. Forwarded source fields affect only an additional per-source rate+ * bucket, and only after the direct socket peer matches an exact configured+ * proxy IP. The class performs no I/O, logging, listening, route registration,+ * or bearer-credential work.+ */+export class RemoteExtensionAdmissionPolicy {+ private readonly trustedProxyAddresses: ReadonlySet<string>+ private readonly clock: MonotonicElapsedClock+ private readonly nonceIssuances: ExpiringCapacity+ private readonly pairPreAuthSockets: ExpiringCapacity+ private readonly v1PreAuthSockets: ExpiringCapacity+ private readonly promptCap: number+ private readonly promptTtlMs: number+ private readonly pendingPrompts = new Map<string, PendingPromptSlot>()+ private readonly discoveryRate: SlidingWindowRate+ private readonly nonceRate: SlidingWindowRate+ private disposed = false++ constructor(options: RemoteExtensionAdmissionPolicyOptions) {+ if (+ !isIssuedRemoteExtensionConfig(options.config) ||+ options.config.status !== 'enabled'+ ) {+ invalidConfiguration()+ }+ const nonceIssuanceCap = requirePositiveSafeInteger(+ options.nonceIssuanceCap ??+ DEFAULT_REMOTE_EXTENSION_ADMISSION_LIMITS.nonceIssuanceCap+ )+ const nonceIssuanceTtlMs = requirePositiveSafeInteger(+ options.nonceIssuanceTtlMs ??+ DEFAULT_REMOTE_EXTENSION_ADMISSION_LIMITS.nonceIssuanceTtlMs+ )+ const pairPreAuthSocketCap = requirePositiveSafeInteger(+ options.pairPreAuthSocketCap ??+ DEFAULT_REMOTE_EXTENSION_ADMISSION_LIMITS.pairPreAuthSocketCap+ )+ const pairPreAuthSocketTtlMs = requirePositiveSafeInteger(+ options.pairPreAuthSocketTtlMs ??+ DEFAULT_REMOTE_EXTENSION_ADMISSION_LIMITS.pairPreAuthSocketTtlMs+ )+ const v1PreAuthSocketCap = requirePositiveSafeInteger(+ options.v1PreAuthSocketCap ??+ DEFAULT_REMOTE_EXTENSION_ADMISSION_LIMITS.v1PreAuthSocketCap+ )+ const v1PreAuthSocketTtlMs = requirePositiveSafeInteger(+ options.v1PreAuthSocketTtlMs ??+ DEFAULT_REMOTE_EXTENSION_ADMISSION_LIMITS.v1PreAuthSocketTtlMs+ )+ this.promptCap = requirePositiveSafeInteger(+ options.pendingPromptCap ??+ DEFAULT_REMOTE_EXTENSION_ADMISSION_LIMITS.pendingPromptCap+ )+ this.promptTtlMs = requirePositiveSafeInteger(+ options.pendingPromptTtlMs ??+ DEFAULT_REMOTE_EXTENSION_ADMISSION_LIMITS.pendingPromptTtlMs+ )+ this.trustedProxyAddresses = parseTrustedProxyAddresses(+ options.trustedProxyAddresses+ )+ const discoveryRate = validateRateLimit(+ options.discoveryRate ?? DEFAULT_DISCOVERY_RATE+ )+ const nonceRate = validateRateLimit(options.nonceRate ?? DEFAULT_NONCE_RATE)+ const nowSource = options.now ?? (() => Math.floor(performance.now()))+ if (typeof nowSource !== 'function') invalidConfiguration()+ this.clock = new MonotonicElapsedClock(+ nowSource,+ Math.max(+ nonceIssuanceTtlMs,+ pairPreAuthSocketTtlMs,+ v1PreAuthSocketTtlMs,+ this.promptTtlMs,+ discoveryRate.windowMs,+ nonceRate.windowMs+ )+ )++ this.nonceIssuances = new ExpiringCapacity(+ nonceIssuanceCap,+ nonceIssuanceTtlMs,+ 'nonce-issuance'+ )+ this.pairPreAuthSockets = new ExpiringCapacity(+ pairPreAuthSocketCap,+ pairPreAuthSocketTtlMs,+ 'pair-pre-auth-socket'+ )+ this.v1PreAuthSockets = new ExpiringCapacity(+ v1PreAuthSocketCap,+ v1PreAuthSocketTtlMs,+ 'v1-pre-auth-socket'+ )+ this.discoveryRate = new SlidingWindowRate(discoveryRate)+ this.nonceRate = new SlidingWindowRate(nonceRate)+ }++ resolveClientSource(+ input: RemoteExtensionClientSourceInput+ ): RemoteExtensionClientSourceDecision {+ const directPeer = canonicalIpAddress(input.directPeerAddress)+ if (directPeer === null) {+ return Object.freeze({ ok: false, reason: 'invalid-direct-peer' })+ }+ if (!this.trustedProxyAddresses.has(directPeer)) {+ return Object.freeze({+ ok: true,+ source: directPeer,+ provenance: 'direct-peer',+ })+ }++ const forwarded = resolveForwardedSource(input.rawHeaders ?? [])+ if (forwarded === null) {+ return Object.freeze({+ ok: true,+ source: directPeer,+ provenance: 'direct-peer',+ })+ }+ if (!forwarded.ok) return forwarded+ return Object.freeze({+ ok: true,+ source: forwarded.source,+ provenance: 'trusted-proxy',+ })+ }++ admitDiscoveryRequest(+ input: RemoteExtensionClientSourceInput+ ): RemoteExtensionAdmissionDecision {+ if (this.disposed) return rejected('disposed')+ const source = this.resolveClientSource(input)+ if (!source.ok) return rejected(source.reason)+ return this.discoveryRate.admit(source.source, this.now())+ ? ALLOWED+ : rejected('rate-limited')+ }++ admitNonceRequest(+ input: RemoteExtensionClientSourceInput+ ): RemoteExtensionLeaseDecision {+ if (this.disposed) return rejected('disposed')+ const source = this.resolveClientSource(input)+ if (!source.ok) return rejected(source.reason)++ const now = this.now()+ if (!this.nonceIssuances.hasCapacity(now)) return rejected('capacity')+ if (!this.nonceRate.admit(source.source, now)) {+ return rejected('rate-limited')+ }+ const lease = this.nonceIssuances.acquire(now)+ if (lease === null) return rejected('capacity')+ return Object.freeze({ ok: true, lease })+ }++ acquirePairPreAuthSocket(): RemoteExtensionLeaseDecision {+ return this.acquireCapacity(this.pairPreAuthSockets)+ }++ acquireV1PreAuthSocket(): RemoteExtensionLeaseDecision {+ return this.acquireCapacity(this.v1PreAuthSockets)+ }++ acquirePendingPrompt(+ verifiedOrigin: string+ ): RemoteExtensionPromptAdmissionDecision {+ if (this.disposed) return rejected('disposed')+ const origin = normalizeVerifiedOrigin(verifiedOrigin)+ if (origin === null) return rejected('invalid-verified-origin')++ const now = this.now()+ this.sweepPrompts(now)+ if (this.pendingPrompts.has(origin)) {+ return Object.freeze({ ok: true, disposition: 'deduplicated' })+ }+ if (this.pendingPrompts.size >= this.promptCap) {+ return rejected('capacity')+ }++ const leaseId = Symbol('pending-prompt')+ const expiresAt = now + this.promptTtlMs+ this.pendingPrompts.set(origin, { leaseId, expiresAt })+ const lease = new AdmissionLease('pending-prompt', () => {+ const current = this.pendingPrompts.get(origin)+ if (current?.leaseId === leaseId) this.pendingPrompts.delete(origin)+ })+ return Object.freeze({ ok: true, disposition: 'opened', lease })+ }++ snapshot(): RemoteExtensionAdmissionSnapshot {+ const now = this.now()+ this.sweepPrompts(now)+ const discovery = this.discoveryRate.snapshot(now)+ const nonce = this.nonceRate.snapshot(now)+ return Object.freeze({+ nonceIssuances: this.nonceIssuances.size(now),+ pairPreAuthSockets: this.pairPreAuthSockets.size(now),+ v1PreAuthSockets: this.v1PreAuthSockets.size(now),+ pendingPrompts: this.pendingPrompts.size,+ discoveryRequestsInWindow: discovery.requests,+ nonceRequestsInWindow: nonce.requests,+ discoverySourcesInWindow: discovery.sources,+ nonceSourcesInWindow: nonce.sources,+ })+ }++ dispose(): void {+ if (this.disposed) return+ this.disposed = true+ this.nonceIssuances.clear()+ this.pairPreAuthSockets.clear()+ this.v1PreAuthSockets.clear()+ this.pendingPrompts.clear()+ this.discoveryRate.clear()+ this.nonceRate.clear()+ }++ private acquireCapacity(+ capacity: ExpiringCapacity+ ): RemoteExtensionLeaseDecision {+ if (this.disposed) return rejected('disposed')+ const lease = capacity.acquire(this.now())+ return lease === null+ ? rejected('capacity')+ : Object.freeze({ ok: true, lease })+ }++ private sweepPrompts(now: number): void {+ for (const [origin, slot] of this.pendingPrompts) {+ if (slot.expiresAt <= now) this.pendingPrompts.delete(origin)+ }+ }++ private now(): number {+ return this.clock.now()+ }+}diff --git a/src/server/bridge/remote-extension-config.test.ts b/src/server/bridge/remote-extension-config.test.tsnew file mode 100644index 00000000..0c95825b--- /dev/null+++ b/src/server/bridge/remote-extension-config.test.ts@@ -0,0 +1,417 @@+import { describe, expect, it } from 'vitest'+import {+ isIssuedRemoteExtensionConfig,+ parseRemoteExtensionConfig,+ RemoteExtensionConfigDiagnosticCode,+ RemoteExtensionEnvironmentVariable,+} from './remote-extension-config'++const enabledEnvironment = {+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'wss://motrix.example/bridge',+ MOTRIX_PUBLIC_URL: 'https://motrix.example/operator',+}++describe('parseRemoteExtensionConfig', () => {+ it('issues ephemeral capabilities and rejects structural copies', () => {+ const parsed = parseRemoteExtensionConfig(enabledEnvironment)++ expect(isIssuedRemoteExtensionConfig(parsed)).toBe(true)+ expect(isIssuedRemoteExtensionConfig({ ...parsed })).toBe(false)+ expect(+ isIssuedRemoteExtensionConfig(JSON.parse(JSON.stringify(parsed)))+ ).toBe(false)+ })++ it.each([+ {},+ { MOTRIX_REMOTE_EXTENSION_ENABLED: '' },+ { MOTRIX_REMOTE_EXTENSION_ENABLED: ' ' },+ { MOTRIX_REMOTE_EXTENSION_ENABLED: 'false' },+ { MOTRIX_REMOTE_EXTENSION_ENABLED: 'FALSE' },+ { MOTRIX_REMOTE_EXTENSION_ENABLED: ' 0 ' },+ ])('keeps the surface disabled for %j', (environment) => {+ expect(parseRemoteExtensionConfig(environment)).toEqual({+ status: 'disabled',+ })+ })++ it.each(['true', ' TRUE ', '1', ' 1 '])(+ 'accepts the existing strict server boolean spelling %j',+ (enabled) => {+ expect(+ parseRemoteExtensionConfig({+ ...enabledEnvironment,+ MOTRIX_REMOTE_EXTENSION_ENABLED: enabled,+ }).status+ ).toBe('enabled')+ }+ )++ it('reports an ambiguous enabled flag without throwing', () => {+ expect(+ parseRemoteExtensionConfig({+ ...enabledEnvironment,+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'yes',+ })+ ).toEqual({+ status: 'invalid',+ diagnostic: {+ variable: RemoteExtensionEnvironmentVariable.Enabled,+ code: RemoteExtensionConfigDiagnosticCode.InvalidEnabledFlag,+ },+ })+ })++ it.each([+ [+ 'MOTRIX_REMOTE_EXTENSION_PUBLIC_URL',+ RemoteExtensionEnvironmentVariable.PublicWebSocketUrl,+ ],+ ['MOTRIX_PUBLIC_URL', RemoteExtensionEnvironmentVariable.PublicOperatorUrl],+ ] as const)('requires %s when enabled', (key, variable) => {+ const environment = { ...enabledEnvironment }+ delete environment[key]++ expect(parseRemoteExtensionConfig(environment)).toEqual({+ status: 'invalid',+ diagnostic: {+ variable,+ code: RemoteExtensionConfigDiagnosticCode.MissingUrl,+ },+ })+ })++ it('canonicalizes default ports, host casing, paths, and IPv6', () => {+ expect(+ parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'WSS://[2001:DB8::1]:443/bridge///',+ MOTRIX_PUBLIC_URL: 'HTTPS://OPERATOR.Example:443/ui///',+ })+ ).toEqual({+ status: 'enabled',+ publicWebSocketBaseUrl: 'wss://[2001:db8::1]/bridge',+ publicWebSocketAuthority: '[2001:db8::1]',+ publicWebSocketBasePath: '/bridge',+ publicOperatorBaseUrl: 'https://operator.example/ui',+ publicOperatorAuthority: 'operator.example',+ publicOperatorBasePath: '/ui',+ })+ })++ it('preserves non-default ports and an empty root prefix', () => {+ expect(+ parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: '1',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'wss://motrix.example:9443/',+ MOTRIX_PUBLIC_URL: 'https://console.example:8443/',+ })+ ).toEqual({+ status: 'enabled',+ publicWebSocketBaseUrl: 'wss://motrix.example:9443',+ publicWebSocketAuthority: 'motrix.example:9443',+ publicWebSocketBasePath: '',+ publicOperatorBaseUrl: 'https://console.example:8443',+ publicOperatorAuthority: 'console.example:8443',+ publicOperatorBasePath: '',+ })+ })++ it('accepts and canonicalizes an explicit WS public endpoint', () => {+ expect(+ parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'WS://NAS.Local:80/bridge///',+ MOTRIX_PUBLIC_URL: 'https://console.example/operator',+ })+ ).toEqual({+ status: 'enabled',+ publicWebSocketBaseUrl: 'ws://nas.local/bridge',+ publicWebSocketAuthority: 'nas.local',+ publicWebSocketBasePath: '/bridge',+ publicOperatorBaseUrl: 'https://console.example/operator',+ publicOperatorAuthority: 'console.example',+ publicOperatorBasePath: '/operator',+ })+ })++ it.each(['true', ' TRUE ', '1', ' 1 '])(+ 'accepts an HTTP operator URL only with explicit insecure-LAN consent %j',+ (consent) => {+ expect(+ parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'ws://nas.local:16801',+ MOTRIX_PUBLIC_URL: 'HTTP://NAS.Local:80/admin///',+ MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP: consent,+ })+ ).toEqual({+ status: 'enabled',+ publicWebSocketBaseUrl: 'ws://nas.local:16801',+ publicWebSocketAuthority: 'nas.local:16801',+ publicWebSocketBasePath: '',+ publicOperatorBaseUrl: 'http://nas.local/admin',+ publicOperatorAuthority: 'nas.local',+ publicOperatorBasePath: '/admin',+ })+ }+ )++ it.each([undefined, '', 'false', 'FALSE', '0'])(+ 'rejects an HTTP operator URL without explicit insecure-LAN consent %j',+ (consent) => {+ expect(+ parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'ws://nas.local:16801',+ MOTRIX_PUBLIC_URL: 'http://nas.local:8080',+ ...(consent === undefined+ ? {}+ : { MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP: consent }),+ })+ ).toEqual({+ status: 'invalid',+ diagnostic: {+ variable:+ RemoteExtensionEnvironmentVariable.AllowInsecureOperatorHttp,+ code: RemoteExtensionConfigDiagnosticCode.InsecureOperatorHttpConsentRequired,+ },+ })+ }+ )++ it('rejects an ambiguous insecure-HTTP consent flag', () => {+ expect(+ parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'ws://nas.local:16801',+ MOTRIX_PUBLIC_URL: 'http://nas.local:8080',+ MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP: 'yes',+ })+ ).toEqual({+ status: 'invalid',+ diagnostic: {+ variable: RemoteExtensionEnvironmentVariable.AllowInsecureOperatorHttp,+ code: RemoteExtensionConfigDiagnosticCode.InvalidInsecureOperatorHttpFlag,+ },+ })+ })++ it('does not require insecure-LAN consent for HTTPS', () => {+ expect(+ parseRemoteExtensionConfig({+ ...enabledEnvironment,+ MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP: 'false',+ }).status+ ).toBe('enabled')+ })++ it.each([+ ['https://motrix.example/bridge', 'https://motrix.example'],+ ['wss://motrix.example/bridge', 'wss://motrix.example'],+ ])(+ 'rejects protocol substitution (%s, %s)',+ (publicWebSocketUrl, publicOperatorUrl) => {+ const result = parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: publicWebSocketUrl,+ MOTRIX_PUBLIC_URL: publicOperatorUrl,+ })+ expect(result.status).toBe('invalid')+ if (result.status === 'invalid') {+ expect(result.diagnostic.code).toBe(+ RemoteExtensionConfigDiagnosticCode.UnsupportedProtocol+ )+ }+ }+ )++ it.each([+ ['wss://user:[email protected]/bridge', 'userinfo'],+ ['wss://@motrix.example/bridge', 'empty userinfo'],+ ['wss://motrix.example/bridge?token=secret', 'query'],+ ['wss://motrix.example/bridge?', 'empty query'],+ ['wss://motrix.example/bridge#fragment', 'fragment'],+ ['wss://motrix.example/bridge#', 'empty fragment'],+ ['wss:\\motrix.example\\bridge', 'backslash'],+ ['wss://motrix.example/bridge\nnext', 'ASCII control'],+ ['wss://motrix.example/bridge%2Fhidden', 'encoded slash'],+ ['wss://motrix.example/bridge%5chidden', 'encoded backslash'],+ ['wss://motrix.example/bridge%252fhidden', 'double-encoded slash'],+ ['wss://motrix.example/bridge%25%32%66hidden', 'split encoded slash'],+ ['wss://motrix.example/bridge%25%35%63hidden', 'split encoded backslash'],+ ['wss://motrix.example/bridge%zz', 'invalid percent encoding'],+ [' wss://motrix.example/bridge', 'leading whitespace'],+ ['wss://motrix.example/bridge ', 'trailing whitespace'],+ ['wss://motrix.example/bridge path', 'embedded whitespace'],+ ['wss://motrix.example/bridge\u00a0path', 'Unicode whitespace'],+ ['wss://motrix.example/bridge\u0085path', 'Unicode White_Space'],+ ['not a URL', 'invalid URL'],+ ])('rejects %s (%s)', (publicWebSocketUrl) => {+ expect(+ parseRemoteExtensionConfig({+ ...enabledEnvironment,+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: publicWebSocketUrl,+ }).status+ ).toBe('invalid')+ })++ it.each([+ 'https://user:[email protected]/operator',+ 'https://@motrix.example/operator',+ 'https://motrix.example/operator?token=secret',+ 'https://motrix.example/operator#fragment',+ 'https:\\motrix.example\\operator',+ 'https://motrix.example/operator\u0000tail',+ 'https://motrix.example/operator%2ftail',+ 'https://motrix.example/operator%255ctail',+ ' https://motrix.example/operator',+ 'https://motrix.example/operator ',+ 'https://motrix.example/operator\u2003path',+ ])('applies the same strict policy to the operator URL %j', (publicUrl) => {+ expect(+ parseRemoteExtensionConfig({+ ...enabledEnvironment,+ MOTRIX_PUBLIC_URL: publicUrl,+ }).status+ ).toBe('invalid')+ })++ it('rejects overlong inputs without echoing them in diagnostics', () => {+ const secretPath = `wss://motrix.example/${'secret'.repeat(700)}`+ const result = parseRemoteExtensionConfig({+ ...enabledEnvironment,+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: secretPath,+ })++ expect(result).toEqual({+ status: 'invalid',+ diagnostic: {+ variable: RemoteExtensionEnvironmentVariable.PublicWebSocketUrl,+ code: RemoteExtensionConfigDiagnosticCode.UrlTooLong,+ },+ })+ expect(JSON.stringify(result)).not.toContain('secret')+ })++ it('rejects a canonical URL that expands beyond the length limit', () => {+ const result = parseRemoteExtensionConfig({+ ...enabledEnvironment,+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: `wss://motrix.example/${'界'.repeat(500)}`,+ })++ expect(result).toEqual({+ status: 'invalid',+ diagnostic: {+ variable: RemoteExtensionEnvironmentVariable.PublicWebSocketUrl,+ code: RemoteExtensionConfigDiagnosticCode.UrlTooLong,+ },+ })+ })++ it('is byte-stable when canonical output is parsed again', () => {+ const first = parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL:+ 'WSS://B\u00dcCHER.example:443/bridge/\u8d44\u6e90///',+ MOTRIX_PUBLIC_URL:+ 'HTTPS://B\u00dcCHER.example:443/operator/\u9875\u9762///',+ })+ expect(first.status).toBe('enabled')+ if (first.status !== 'enabled') return++ expect(+ parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: first.publicWebSocketBaseUrl,+ MOTRIX_PUBLIC_URL: first.publicOperatorBaseUrl,+ })+ ).toEqual(first)+ })++ it('never throws for malformed runtime input or hostile property access', () => {+ const wrongType = {+ ...enabledEnvironment,+ MOTRIX_PUBLIC_URL: 42,+ } as unknown as Record<string, string | undefined>+ expect(() => parseRemoteExtensionConfig(wrongType)).not.toThrow()+ expect(parseRemoteExtensionConfig(wrongType)).toEqual({+ status: 'invalid',+ diagnostic: {+ variable: 'configuration',+ code: RemoteExtensionConfigDiagnosticCode.InvalidEnvironment,+ },+ })++ const hostile = Object.defineProperty(+ {},+ 'MOTRIX_REMOTE_EXTENSION_ENABLED',+ {+ get() {+ throw new Error('operator-secret')+ },+ }+ ) as Record<string, string | undefined>+ expect(() => parseRemoteExtensionConfig(hostile)).not.toThrow()+ expect(JSON.stringify(parseRemoteExtensionConfig(hostile))).not.toContain(+ 'operator-secret'+ )+ })++ it('never consumes or returns a legacy token', () => {+ expect(+ parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_TOKEN: 'legacy-super-secret',+ })+ ).toEqual({ status: 'disabled' })++ expect(+ parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_TOKEN: 'legacy-super-secret',+ })+ ).toEqual({+ status: 'invalid',+ diagnostic: {+ variable: RemoteExtensionEnvironmentVariable.PublicWebSocketUrl,+ code: RemoteExtensionConfigDiagnosticCode.MissingUrl,+ },+ })++ const result = parseRemoteExtensionConfig({+ ...enabledEnvironment,+ MOTRIX_REMOTE_EXTENSION_TOKEN: 'legacy-super-secret',+ })++ expect(result.status).toBe('enabled')+ expect(JSON.stringify(result)).not.toContain('legacy-super-secret')+ expect(result).not.toHaveProperty('token')+ })++ it('does not infer public authority from forwarded headers', () => {+ const missingExplicitAuthority = parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_PUBLIC_URL: 'https://operator.example',+ X_FORWARDED_HOST: 'attacker.example',+ X_FORWARDED_PROTO: 'wss',+ })+ expect(missingExplicitAuthority).toEqual({+ status: 'invalid',+ diagnostic: {+ variable: RemoteExtensionEnvironmentVariable.PublicWebSocketUrl,+ code: RemoteExtensionConfigDiagnosticCode.MissingUrl,+ },+ })++ const configured = parseRemoteExtensionConfig({+ ...enabledEnvironment,+ X_FORWARDED_HOST: 'attacker.example',+ X_FORWARDED_PROTO: 'ws',+ })+ expect(configured).toMatchObject({+ status: 'enabled',+ publicWebSocketAuthority: 'motrix.example',+ })+ })+})diff --git a/src/server/bridge/remote-extension-config.ts b/src/server/bridge/remote-extension-config.tsnew file mode 100644index 00000000..0e7e0eb6--- /dev/null+++ b/src/server/bridge/remote-extension-config.ts@@ -0,0 +1,423 @@+import { z } from 'zod'+import { parseServerBoolean } from '../environment'++export const REMOTE_EXTENSION_PUBLIC_URL_MAX_LENGTH = 4_096++export const RemoteExtensionEnvironmentVariable = {+ Enabled: 'MOTRIX_REMOTE_EXTENSION_ENABLED',+ PublicWebSocketUrl: 'MOTRIX_REMOTE_EXTENSION_PUBLIC_URL',+ PublicOperatorUrl: 'MOTRIX_PUBLIC_URL',+ AllowInsecureOperatorHttp: 'MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP',+} as const++export type RemoteExtensionEnvironmentVariable =+ (typeof RemoteExtensionEnvironmentVariable)[keyof typeof RemoteExtensionEnvironmentVariable]++export interface RemoteExtensionEnvironment {+ readonly [name: string]: string | undefined+}++export enum RemoteExtensionConfigDiagnosticCode {+ InvalidEnvironment = 'invalid-environment',+ InvalidEnabledFlag = 'invalid-enabled-flag',+ InvalidInsecureOperatorHttpFlag = 'invalid-insecure-operator-http-flag',+ InsecureOperatorHttpConsentRequired = 'insecure-operator-http-consent-required',+ MissingUrl = 'missing-url',+ UrlTooLong = 'url-too-long',+ AsciiControlCharacter = 'ascii-control-character',+ Whitespace = 'whitespace',+ Backslash = 'backslash',+ EncodedPathSeparator = 'encoded-path-separator',+ InvalidPercentEncoding = 'invalid-percent-encoding',+ InvalidUrl = 'invalid-url',+ UnsupportedProtocol = 'unsupported-protocol',+ UserInfo = 'userinfo',+ Query = 'query',+ Fragment = 'fragment',+}++export interface RemoteExtensionConfigDiagnostic {+ /** Fixed values only: this object is safe to write to an operator log. */+ readonly code: RemoteExtensionConfigDiagnosticCode+ readonly variable: RemoteExtensionEnvironmentVariable | 'configuration'+}++export interface DisabledRemoteExtensionConfig {+ readonly status: 'disabled'+}++export interface InvalidRemoteExtensionConfig {+ readonly status: 'invalid'+ readonly diagnostic: RemoteExtensionConfigDiagnostic+}++export interface EnabledRemoteExtensionConfig {+ readonly status: 'enabled'+ /** Canonical WS/WSS base, without a trailing slash. */+ readonly publicWebSocketBaseUrl: string+ /** Canonical Host value, including a non-default port when configured. */+ readonly publicWebSocketAuthority: string+ /** Reverse-proxy prefix, empty at the authority root. */+ readonly publicWebSocketBasePath: string+ /** Canonical HTTP/HTTPS operator UI base, without a trailing slash. */+ readonly publicOperatorBaseUrl: string+ readonly publicOperatorAuthority: string+ readonly publicOperatorBasePath: string+}++export type RemoteExtensionConfig =+ | DisabledRemoteExtensionConfig+ | InvalidRemoteExtensionConfig+ | EnabledRemoteExtensionConfig++const issuedRemoteExtensionConfigs = new WeakSet<object>()++function issueConfig<T extends RemoteExtensionConfig>(config: T): T {+ issuedRemoteExtensionConfigs.add(config)+ return config+}++/**+ * Runtime capability check for consumers at the Host/route boundary. A parsed+ * configuration is process-local and ephemeral; copied, deserialized, or+ * structurally manufactured values are not safe substitutes because they can+ * bypass the parser's URL and all-or-nothing operator configuration checks.+ */+export function isIssuedRemoteExtensionConfig(+ value: unknown+): value is RemoteExtensionConfig {+ return (+ typeof value === 'object' &&+ value !== null &&+ issuedRemoteExtensionConfigs.has(value)+ )+}++const remoteExtensionEnvironmentSchema = z.object({+ [RemoteExtensionEnvironmentVariable.Enabled]: z.string().optional(),+ [RemoteExtensionEnvironmentVariable.PublicWebSocketUrl]: z+ .string()+ .optional(),+ [RemoteExtensionEnvironmentVariable.PublicOperatorUrl]: z.string().optional(),+ [RemoteExtensionEnvironmentVariable.AllowInsecureOperatorHttp]: z+ .string()+ .optional(),+})++const DISABLED_CONFIG: DisabledRemoteExtensionConfig = issueConfig(+ Object.freeze({+ status: 'disabled',+ })+)++const ENCODED_PATH_SEPARATOR = /%(?:2f|5c)/iu+const PERCENT_TRIPLET = /%([0-9a-f]{2})/giu+const INVALID_PERCENT_ENCODING = /%(?![0-9a-f]{2})/iu++interface ParsedPublicUrl {+ readonly baseUrl: string+ readonly authority: string+ readonly basePath: string+}++type PublicUrlParseResult =+ | { readonly ok: true; readonly value: ParsedPublicUrl }+ | { readonly ok: false; readonly value: InvalidRemoteExtensionConfig }++function invalid(+ variable: RemoteExtensionConfigDiagnostic['variable'],+ code: RemoteExtensionConfigDiagnosticCode+): InvalidRemoteExtensionConfig {+ return issueConfig(+ Object.freeze({+ status: 'invalid',+ diagnostic: Object.freeze({ variable, code }),+ })+ )+}++function hasUserInfoSyntax(candidate: string): boolean {+ const schemeEnd = candidate.indexOf('://')+ if (schemeEnd === -1) return false++ const authorityStart = schemeEnd + 3+ const suffix = candidate.slice(authorityStart)+ const delimiterOffset = suffix.search(/[/?#]/u)+ const authority =+ delimiterOffset === -1 ? suffix : suffix.slice(0, delimiterOffset)+ return authority.includes('@')+}++function hasAsciiControlCharacter(value: string): boolean {+ for (let index = 0; index < value.length; index += 1) {+ const codePoint = value.charCodeAt(index)+ if (codePoint <= 0x1f || codePoint === 0x7f) return true+ }+ return false+}++function hasEncodedPathSeparator(value: string): boolean {+ let candidate = value+ while (true) {+ if (ENCODED_PATH_SEPARATOR.test(candidate)) return true++ const decoded = candidate.replace(+ PERCENT_TRIPLET,+ (_triplet, hex: string) => String.fromCharCode(Number.parseInt(hex, 16))+ )+ if (decoded === candidate) return false+ candidate = decoded+ }+}++function canonicalBaseUrl(parsed: URL): ParsedPublicUrl {+ const basePath =+ parsed.pathname === '/' ? '' : parsed.pathname.replace(/\/+$/u, '')+ return {+ baseUrl: `${parsed.origin}${basePath}`,+ authority: parsed.host,+ basePath,+ }+}++function parsePublicUrl(+ rawValue: string | undefined,+ variable: RemoteExtensionEnvironmentVariable,+ allowedProtocols: readonly ('http:' | 'https:' | 'ws:' | 'wss:')[]+): PublicUrlParseResult {+ if (rawValue === undefined || rawValue.trim() === '') {+ return {+ ok: false,+ value: invalid(variable, RemoteExtensionConfigDiagnosticCode.MissingUrl),+ }+ }+ if (rawValue.length > REMOTE_EXTENSION_PUBLIC_URL_MAX_LENGTH) {+ return {+ ok: false,+ value: invalid(variable, RemoteExtensionConfigDiagnosticCode.UrlTooLong),+ }+ }+ if (hasAsciiControlCharacter(rawValue)) {+ return {+ ok: false,+ value: invalid(+ variable,+ RemoteExtensionConfigDiagnosticCode.AsciiControlCharacter+ ),+ }+ }+ if (/\p{White_Space}/u.test(rawValue)) {+ return {+ ok: false,+ value: invalid(variable, RemoteExtensionConfigDiagnosticCode.Whitespace),+ }+ }+ if (rawValue.includes('\\')) {+ return {+ ok: false,+ value: invalid(variable, RemoteExtensionConfigDiagnosticCode.Backslash),+ }+ }+ if (hasEncodedPathSeparator(rawValue)) {+ return {+ ok: false,+ value: invalid(+ variable,+ RemoteExtensionConfigDiagnosticCode.EncodedPathSeparator+ ),+ }+ }+ if (INVALID_PERCENT_ENCODING.test(rawValue)) {+ return {+ ok: false,+ value: invalid(+ variable,+ RemoteExtensionConfigDiagnosticCode.InvalidPercentEncoding+ ),+ }+ }++ const candidate = rawValue+ if (hasUserInfoSyntax(candidate)) {+ return {+ ok: false,+ value: invalid(variable, RemoteExtensionConfigDiagnosticCode.UserInfo),+ }+ }+ if (candidate.includes('?')) {+ return {+ ok: false,+ value: invalid(variable, RemoteExtensionConfigDiagnosticCode.Query),+ }+ }+ if (candidate.includes('#')) {+ return {+ ok: false,+ value: invalid(variable, RemoteExtensionConfigDiagnosticCode.Fragment),+ }+ }++ let parsed: URL+ try {+ parsed = new URL(candidate)+ } catch {+ return {+ ok: false,+ value: invalid(variable, RemoteExtensionConfigDiagnosticCode.InvalidUrl),+ }+ }++ if (!allowedProtocols.some((protocol) => protocol === parsed.protocol)) {+ return {+ ok: false,+ value: invalid(+ variable,+ RemoteExtensionConfigDiagnosticCode.UnsupportedProtocol+ ),+ }+ }+ if (parsed.username !== '' || parsed.password !== '') {+ return {+ ok: false,+ value: invalid(variable, RemoteExtensionConfigDiagnosticCode.UserInfo),+ }+ }+ if (parsed.search !== '') {+ return {+ ok: false,+ value: invalid(variable, RemoteExtensionConfigDiagnosticCode.Query),+ }+ }+ if (parsed.hash !== '') {+ return {+ ok: false,+ value: invalid(variable, RemoteExtensionConfigDiagnosticCode.Fragment),+ }+ }++ const canonical = canonicalBaseUrl(parsed)+ if (canonical.baseUrl.length > REMOTE_EXTENSION_PUBLIC_URL_MAX_LENGTH) {+ return {+ ok: false,+ value: invalid(variable, RemoteExtensionConfigDiagnosticCode.UrlTooLong),+ }+ }++ let reparsed: URL+ try {+ reparsed = new URL(canonical.baseUrl)+ } catch {+ return {+ ok: false,+ value: invalid(variable, RemoteExtensionConfigDiagnosticCode.InvalidUrl),+ }+ }+ if (canonicalBaseUrl(reparsed).baseUrl !== canonical.baseUrl) {+ return {+ ok: false,+ value: invalid(variable, RemoteExtensionConfigDiagnosticCode.InvalidUrl),+ }+ }++ return {+ ok: true,+ value: Object.freeze(canonical),+ }+}++function parseBooleanFlag(+ value: string | undefined,+ variable: RemoteExtensionEnvironmentVariable,+ invalidCode: RemoteExtensionConfigDiagnosticCode+): boolean | InvalidRemoteExtensionConfig {+ try {+ return parseServerBoolean(value, variable)+ } catch {+ return invalid(variable, invalidCode)+ }+}++/**+ * Parse the opt-in remote Extension surface without consulting process state.+ *+ * Invalid input is data, not an exception: callers keep the Extension routes+ * closed while the unrelated server surfaces continue to start. Unknown+ * variables, including legacy token and forwarded-host settings, are ignored.+ */+export function parseRemoteExtensionConfig(+ environment: RemoteExtensionEnvironment = {}+): RemoteExtensionConfig {+ try {+ const parsedEnvironment =+ remoteExtensionEnvironmentSchema.safeParse(environment)+ if (!parsedEnvironment.success) {+ return invalid(+ 'configuration',+ RemoteExtensionConfigDiagnosticCode.InvalidEnvironment+ )+ }++ const enabled = parseBooleanFlag(+ parsedEnvironment.data[RemoteExtensionEnvironmentVariable.Enabled],+ RemoteExtensionEnvironmentVariable.Enabled,+ RemoteExtensionConfigDiagnosticCode.InvalidEnabledFlag+ )+ if (typeof enabled !== 'boolean') return enabled+ if (!enabled) return DISABLED_CONFIG++ const webSocket = parsePublicUrl(+ parsedEnvironment.data[+ RemoteExtensionEnvironmentVariable.PublicWebSocketUrl+ ],+ RemoteExtensionEnvironmentVariable.PublicWebSocketUrl,+ ['ws:', 'wss:']+ )+ if (!webSocket.ok) return webSocket.value++ const operator = parsePublicUrl(+ parsedEnvironment.data[+ RemoteExtensionEnvironmentVariable.PublicOperatorUrl+ ],+ RemoteExtensionEnvironmentVariable.PublicOperatorUrl,+ ['http:', 'https:']+ )+ if (!operator.ok) return operator.value++ const allowInsecureOperatorHttp = parseBooleanFlag(+ parsedEnvironment.data[+ RemoteExtensionEnvironmentVariable.AllowInsecureOperatorHttp+ ],+ RemoteExtensionEnvironmentVariable.AllowInsecureOperatorHttp,+ RemoteExtensionConfigDiagnosticCode.InvalidInsecureOperatorHttpFlag+ )+ if (typeof allowInsecureOperatorHttp !== 'boolean') {+ return allowInsecureOperatorHttp+ }+ if (+ operator.value.baseUrl.startsWith('http://') &&+ !allowInsecureOperatorHttp+ ) {+ return invalid(+ RemoteExtensionEnvironmentVariable.AllowInsecureOperatorHttp,+ RemoteExtensionConfigDiagnosticCode.InsecureOperatorHttpConsentRequired+ )+ }++ return issueConfig(+ Object.freeze({+ status: 'enabled',+ publicWebSocketBaseUrl: webSocket.value.baseUrl,+ publicWebSocketAuthority: webSocket.value.authority,+ publicWebSocketBasePath: webSocket.value.basePath,+ publicOperatorBaseUrl: operator.value.baseUrl,+ publicOperatorAuthority: operator.value.authority,+ publicOperatorBasePath: operator.value.basePath,+ })+ )+ } catch {+ return invalid(+ 'configuration',+ RemoteExtensionConfigDiagnosticCode.InvalidEnvironment+ )+ }+}diff --git a/src/server/bridge/remote-extension-host-policy.test.ts b/src/server/bridge/remote-extension-host-policy.test.tsnew file mode 100644index 00000000..07ad2c3a--- /dev/null+++ b/src/server/bridge/remote-extension-host-policy.test.ts@@ -0,0 +1,177 @@+import { describe, expect, it } from 'vitest'+import { parseRemoteExtensionConfig } from './remote-extension-config'+import {+ evaluateRemoteExtensionHost,+ type RemoteExtensionHostRejection,+} from './remote-extension-host-policy'++function enabled(+ websocketUrl = 'wss://motrix.example/bridge'+): ReturnType<typeof parseRemoteExtensionConfig> {+ return parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: websocketUrl,+ MOTRIX_PUBLIC_URL: 'https://motrix.example',+ })+}++function decision(+ headers: readonly string[],+ websocketUrl?: string+): boolean | RemoteExtensionHostRejection {+ const result = evaluateRemoteExtensionHost(enabled(websocketUrl), headers)+ return result.ok ? true : result.reason+}++describe('evaluateRemoteExtensionHost', () => {+ it('accepts the configured authority without exposing request data', () => {+ expect(decision(['Host', 'motrix.example'])).toBe(true)+ expect(+ evaluateRemoteExtensionHost(enabled(), ['Host', 'motrix.example'])+ ).toEqual({ ok: true })+ })++ it.each([+ ['case folding', 'MOTRIX.EXAMPLE'],+ ['explicit default port', 'motrix.example:443'],+ ['case plus default port', 'MoTrIx.ExAmPlE:443'],+ ])('accepts canonical equivalent %s', (_label, host) => {+ expect(decision(['hOsT', host])).toBe(true)+ })++ it('requires an exact non-default effective port', () => {+ expect(+ decision(+ ['Host', 'motrix.example:8443'],+ 'wss://motrix.example:8443/bridge'+ )+ ).toBe(true)+ expect(+ decision(['Host', 'motrix.example'], 'wss://motrix.example:8443/bridge')+ ).toBe('authority-mismatch')+ expect(+ decision(+ ['Host', 'motrix.example:8444'],+ 'wss://motrix.example:8443/bridge'+ )+ ).toBe('authority-mismatch')+ })++ it('uses HTTP default-port semantics for an explicit WS authority', () => {+ expect(decision(['Host', 'nas.local'], 'ws://nas.local:80/bridge')).toBe(+ true+ )+ expect(+ decision(['Host', 'nas.local:8888'], 'ws://nas.local:8888/bridge')+ ).toBe(true)+ expect(decision(['Host', 'nas.local'], 'ws://nas.local:8888/bridge')).toBe(+ 'authority-mismatch'+ )+ expect(+ decision(['Host', 'nas.local:443'], 'ws://nas.local:443/bridge')+ ).toBe(true)+ })++ it('canonicalizes IPv6 and IDNA hostnames before comparison', () => {+ expect(+ decision(+ ['Host', '[2001:0db8:0:0:0:0:0:1]:443'],+ 'wss://[2001:db8::1]/bridge'+ )+ ).toBe(true)+ expect(+ decision(+ ['Host', 'b\u00fccher.example'],+ 'wss://xn--bcher-kva.example/bridge'+ )+ ).toBe(true)+ })++ it('requires exactly one Host field even when duplicate values agree', () => {+ expect(decision([])).toBe('missing-host')+ expect(decision(['Host', 'motrix.example', 'host', 'motrix.example'])).toBe(+ 'duplicate-host'+ )+ })++ it('never lets X-Forwarded-Host define or repair the authority', () => {+ expect(+ decision([+ 'Host',+ 'attacker.example',+ 'X-Forwarded-Host',+ 'motrix.example',+ ])+ ).toBe('authority-mismatch')+ expect(decision(['X-Forwarded-Host', 'motrix.example'])).toBe(+ 'missing-host'+ )+ })++ it.each([+ ['empty', ''],+ ['leading space', ' motrix.example'],+ ['trailing space', 'motrix.example '],+ ['embedded tab', 'motrix\t.example'],+ ['control', 'motrix.example\u007f'],+ ['backslash', 'motrix.example\\alias'],+ ['percent', 'motrix%2eexample'],+ ['userinfo', '[email protected]'],+ ['path', 'motrix.example/path'],+ ['query', 'motrix.example?x=1'],+ ['fragment', 'motrix.example#x'],+ ['comma join', 'motrix.example, attacker.example'],+ ['empty port', 'motrix.example:'],+ ['zero port', 'motrix.example:0'],+ ['leading-zero port', 'motrix.example:0443'],+ ['empty IPv6 port', '[2001:db8::1]:'],+ ['invalid port', 'motrix.example:99999'],+ ])('rejects malformed Host syntax: %s', (_label, host) => {+ expect(decision(['Host', host])).toBe('malformed-host')+ })++ it('bounds and validates the raw header vector', () => {+ expect(decision(['Host', 'motrix.example', 'Dangling-Header-Name'])).toBe(+ 'malformed-headers'+ )+ expect(decision(Array.from({ length: 258 }, () => 'x'))).toBe(+ 'malformed-headers'+ )+ expect(decision(['Host', 'a'.repeat(1_025)])).toBe('malformed-host')+ })++ it('keeps disabled, invalid, and structurally inconsistent configuration closed', () => {+ expect(+ evaluateRemoteExtensionHost(parseRemoteExtensionConfig({}), [+ 'Host',+ 'motrix.example',+ ])+ ).toEqual({ ok: false, reason: 'feature-closed' })+ expect(+ evaluateRemoteExtensionHost(+ parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ }),+ ['Host', 'motrix.example']+ )+ ).toEqual({ ok: false, reason: 'feature-closed' })++ const forged = {+ status: 'enabled',+ publicWebSocketBaseUrl: 'wss://attacker.example/bridge',+ publicWebSocketAuthority: 'motrix.example',+ publicWebSocketBasePath: '/bridge',+ publicOperatorBaseUrl: 'https://motrix.example',+ publicOperatorAuthority: 'motrix.example',+ publicOperatorBasePath: '',+ } as const+ expect(+ evaluateRemoteExtensionHost(forged, ['Host', 'motrix.example'])+ ).toEqual({ ok: false, reason: 'feature-closed' })++ const valid = enabled()+ expect(+ evaluateRemoteExtensionHost({ ...valid }, ['Host', 'motrix.example'])+ ).toEqual({ ok: false, reason: 'feature-closed' })+ })+})diff --git a/src/server/bridge/remote-extension-host-policy.ts b/src/server/bridge/remote-extension-host-policy.tsnew file mode 100644index 00000000..949d2d96--- /dev/null+++ b/src/server/bridge/remote-extension-host-policy.ts@@ -0,0 +1,179 @@+import {+ isIssuedRemoteExtensionConfig,+ type RemoteExtensionConfig,+} from './remote-extension-config'++const MAX_RAW_HEADER_ENTRIES = 256+const MAX_HOST_LENGTH = 1_024++export type RemoteExtensionHostRejection =+ | 'feature-closed'+ | 'malformed-headers'+ | 'missing-host'+ | 'duplicate-host'+ | 'malformed-host'+ | 'authority-mismatch'++export type RemoteExtensionHostDecision =+ | { readonly ok: true }+ | { readonly ok: false; readonly reason: RemoteExtensionHostRejection }++const ALLOWED: RemoteExtensionHostDecision = Object.freeze({ ok: true })++function rejected(+ reason: RemoteExtensionHostRejection+): RemoteExtensionHostDecision {+ return Object.freeze({ ok: false, reason })+}++function containsAsciiControl(value: string): boolean {+ for (let index = 0; index < value.length; index += 1) {+ const codePoint = value.charCodeAt(index)+ if (codePoint <= 0x1f || codePoint === 0x7f) return true+ }+ return false+}++function hasStrictPortSyntax(value: string): boolean {+ let suffix = ''+ if (value.startsWith('[')) {+ const closingBracket = value.indexOf(']')+ if (closingBracket <= 1 || value.indexOf(']', closingBracket + 1) !== -1) {+ return false+ }+ suffix = value.slice(closingBracket + 1)+ if (suffix !== '' && !suffix.startsWith(':')) return false+ } else {+ const firstColon = value.indexOf(':')+ const lastColon = value.lastIndexOf(':')+ if (firstColon !== lastColon) return false+ suffix = firstColon === -1 ? '' : value.slice(firstColon)+ }+ if (suffix === '') return true++ const port = suffix.slice(1)+ if (!/^[1-9]\d{0,4}$/u.test(port)) return false+ return Number(port) <= 65_535+}++/**+ * Parse an HTTP Host value using the configured WebSocket scheme's matching+ * HTTP effective-port semantics. No request-derived path or forwarded-host+ * input reaches this function.+ */+function canonicalRequestAuthority(+ value: string,+ protocol: 'http:' | 'https:'+): string | null {+ if (+ value.length === 0 ||+ value.length > MAX_HOST_LENGTH ||+ containsAsciiControl(value) ||+ /\p{White_Space}/u.test(value) ||+ value.includes('\\') ||+ value.includes('%') ||+ /[/?#@,]/u.test(value) ||+ !hasStrictPortSyntax(value)+ ) {+ return null+ }++ let parsed: URL+ try {+ parsed = new URL(`${protocol}//${value}/`)+ } catch {+ return null+ }+ if (+ parsed.protocol !== protocol ||+ parsed.username !== '' ||+ parsed.password !== '' ||+ parsed.pathname !== '/' ||+ parsed.search !== '' ||+ parsed.hash !== '' ||+ parsed.host === ''+ ) {+ return null+ }+ return parsed.host+}++interface ExpectedAuthority {+ authority: string+ requestProtocol: 'http:' | 'https:'+}++function expectedAuthority(+ config: RemoteExtensionConfig+): ExpectedAuthority | null {+ if (!isIssuedRemoteExtensionConfig(config) || config.status !== 'enabled') {+ return null+ }+ let parsed: URL+ try {+ parsed = new URL(config.publicWebSocketBaseUrl)+ } catch {+ return null+ }+ if (+ (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') ||+ parsed.username !== '' ||+ parsed.password !== '' ||+ parsed.search !== '' ||+ parsed.hash !== '' ||+ parsed.host === '' ||+ parsed.host !== config.publicWebSocketAuthority+ ) {+ return null+ }+ return {+ authority: parsed.host,+ requestProtocol: parsed.protocol === 'wss:' ? 'https:' : 'http:',+ }+}++/**+ * Validate the original HTTP/1 raw header list before admitting any remote+ * Extension route.+ *+ * Exactly one `Host` field is required even when duplicate fields contain the+ * same value. `X-Forwarded-Host` is deliberately ignored: proxy deployment+ * must preserve the configured public Host rather than asking an untrusted+ * request header to redefine the authority. The fixed rejection codes contain+ * no request or configuration value and are safe for diagnostics.+ */+export function evaluateRemoteExtensionHost(+ config: RemoteExtensionConfig,+ rawHeaders: readonly string[]+): RemoteExtensionHostDecision {+ const expected = expectedAuthority(config)+ if (expected === null) return rejected('feature-closed')+ if (+ !Array.isArray(rawHeaders) ||+ rawHeaders.length > MAX_RAW_HEADER_ENTRIES ||+ rawHeaders.length % 2 !== 0+ ) {+ return rejected('malformed-headers')+ }++ const hosts: string[] = []+ for (let index = 0; index < rawHeaders.length; index += 2) {+ const name = rawHeaders[index]+ const value = rawHeaders[index + 1]+ if (typeof name !== 'string' || typeof value !== 'string') {+ return rejected('malformed-headers')+ }+ if (name.toLowerCase() === 'host') hosts.push(value)+ }+ if (hosts.length === 0) return rejected('missing-host')+ if (hosts.length !== 1) return rejected('duplicate-host')++ const actual = canonicalRequestAuthority(+ hosts[0] ?? '',+ expected.requestProtocol+ )+ if (actual === null) return rejected('malformed-host')+ return actual === expected.authority+ ? ALLOWED+ : rejected('authority-mismatch')+}diff --git a/src/server/bridge/remote-extension-route-policy.test.ts b/src/server/bridge/remote-extension-route-policy.test.tsnew file mode 100644index 00000000..30311bfb--- /dev/null+++ b/src/server/bridge/remote-extension-route-policy.test.ts@@ -0,0 +1,306 @@+import { NonceService } from '@core/bridge/mbp1/nonce-service'+import { describe, expect, it } from 'vitest'+import { parseRemoteExtensionConfig } from './remote-extension-config'+import {+ deriveRemoteExtensionRouteTargets,+ evaluateRemoteExtensionRoute,+} from './remote-extension-route-policy'++const NONCE = 'AQIDBAUGBwgJCgsMDQ4PEA'++function enabled(publicWebSocketUrl = 'wss://motrix.example/bridge') {+ return parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: publicWebSocketUrl,+ MOTRIX_PUBLIC_URL: 'https://motrix.example/operator',+ })+}++function decide(+ rawTarget: string,+ options: {+ method?: string+ transport?: 'http' | 'websocket'+ websocketUrl?: string+ } = {}+) {+ return evaluateRemoteExtensionRoute(enabled(options.websocketUrl), {+ rawTarget,+ method: options.method ?? 'GET',+ transport: options.transport ?? 'http',+ })+}++describe('deriveRemoteExtensionRouteTargets', () => {+ it('derives exactly four paths under a configured prefix', () => {+ expect(deriveRemoteExtensionRouteTargets(enabled())).toEqual({+ discovery: '/bridge/discovery',+ nonce: '/bridge/nonce',+ pair: '/bridge/pair',+ v1: '/bridge/v1',+ })+ })++ it('derives root paths without a double slash', () => {+ expect(+ deriveRemoteExtensionRouteTargets(enabled('wss://motrix.example/'))+ ).toEqual({+ discovery: '/discovery',+ nonce: '/nonce',+ pair: '/pair',+ v1: '/v1',+ })+ })++ it('derives the same route surface for an explicit WS endpoint', () => {+ expect(+ deriveRemoteExtensionRouteTargets(enabled('ws://nas.local:8888/bridge'))+ ).toEqual({+ discovery: '/bridge/discovery',+ nonce: '/bridge/nonce',+ pair: '/bridge/pair',+ v1: '/bridge/v1',+ })+ })++ it('preserves the canonical encoded prefix byte-for-byte', () => {+ expect(+ deriveRemoteExtensionRouteTargets(+ enabled('wss://motrix.example/bridge/%E8%B5%84%E6%BA%90')+ )+ ).toMatchObject({+ pair: '/bridge/%E8%B5%84%E6%BA%90/pair',+ })+ })++ it.each([+ parseRemoteExtensionConfig({}),+ parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'https://motrix.example/bridge',+ MOTRIX_PUBLIC_URL: 'https://motrix.example',+ }),+ ])('returns no targets for a closed configuration', (config) => {+ expect(deriveRemoteExtensionRouteTargets(config)).toBeNull()+ })++ it('rejects copied, deserialized, and structurally forged enabled configs', () => {+ const parsed = enabled()+ if (parsed.status !== 'enabled')+ throw new Error('test config is not enabled')+ const selfConsistentEncodedSeparator = {+ ...parsed,+ publicWebSocketBaseUrl: 'wss://motrix.example/bridge%2Fadmin',+ publicWebSocketBasePath: '/bridge%2Fadmin',+ } as const+ const overlongPath = `/${'a'.repeat(5_000)}`+ const selfConsistentOverlong = {+ ...parsed,+ publicWebSocketBaseUrl: `wss://motrix.example${overlongPath}`,+ publicWebSocketBasePath: overlongPath,+ } as const++ expect(deriveRemoteExtensionRouteTargets({ ...parsed })).toBeNull()+ expect(+ deriveRemoteExtensionRouteTargets(JSON.parse(JSON.stringify(parsed)))+ ).toBeNull()+ expect(+ deriveRemoteExtensionRouteTargets(selfConsistentEncodedSeparator)+ ).toBeNull()+ expect(deriveRemoteExtensionRouteTargets(selfConsistentOverlong)).toBeNull()+ })+})++describe('evaluateRemoteExtensionRoute', () => {+ it.each([+ ['/bridge/discovery', 'GET', 'http', 'discovery'],+ ['/bridge/nonce', 'POST', 'http', 'nonce'],+ [`/bridge/pair?nonce=${NONCE}`, 'GET', 'websocket', 'pair'],+ ['/bridge/v1', 'GET', 'websocket', 'v1'],+ ] as const)(+ 'admits the exact %s request',+ (rawTarget, method, transport, route) => {+ expect(decide(rawTarget, { method, transport })).toMatchObject({+ ok: true,+ route,+ })+ }+ )++ it('returns the validated pair nonce without decoding aliases', () => {+ expect(+ decide(`/bridge/pair?nonce=${NONCE}`, { transport: 'websocket' })+ ).toEqual({ ok: true, route: 'pair', pairNonce: NONCE })+ })++ it('accepts every nonce issued by the shared MBP1 NonceService', () => {+ const nonces = new NonceService({ maxOutstanding: 32 })+ for (let index = 0; index < 32; index += 1) {+ const issued = nonces.issue(null)+ expect('nonce' in issued).toBe(true)+ if (!('nonce' in issued)) throw new Error('nonce fixture was limited')+ expect(+ decide(`/bridge/pair?nonce=${issued.nonce}`, {+ transport: 'websocket',+ })+ ).toEqual({ ok: true, route: 'pair', pairNonce: issued.nonce })+ }+ })++ it.each([+ '/bridge',+ '/bridge/',+ '/bridge/pair/',+ '/pair',+ '/bridge//pair',+ '/bridge/./pair',+ '/bridge/x/../pair',+ '/bridge/%2e%2e/pair',+ '/bridge%2Fpair',+ '/bridge/%70air',+ '/BRIDGE/pair',+ ])('rejects non-exact raw path %j', (rawTarget) => {+ expect(decide(rawTarget, { transport: 'websocket' })).toEqual({+ ok: false,+ reason: 'unknown-route',+ })+ })++ it.each([+ `/bridge/pair?nonce=${NONCE}&token=legacy`,+ '/bridge/pair?token=legacy',+ '/bridge/pair',+ '/bridge/pair?',+ `/bridge/pair?nonce=${NONCE}&nonce=${NONCE}`,+ `/bridge/pair?nonce=${NONCE}%00`,+ '/bridge/pair?nonce=AAAAAAAAAAAAAAAAAAAAAB',+ `/bridge/pair?nonce=${NONCE}=`,+ '/bridge/pair?nonce=short',+ `/bridge/pair?nonce%3d${NONCE}`,+ ])('rejects ambiguous or non-canonical pair query %j', (rawTarget) => {+ expect(decide(rawTarget, { transport: 'websocket' })).toEqual({+ ok: false,+ reason: 'malformed-pair-query',+ })+ })++ it.each([+ '/bridge/discovery?',+ '/bridge/discovery?token=legacy',+ '/bridge/nonce?x=1',+ '/bridge/v1?token=legacy',+ ])('rejects a query on non-pair route %j', (rawTarget) => {+ expect(+ decide(rawTarget, {+ method: rawTarget.includes('/nonce') ? 'POST' : 'GET',+ transport: rawTarget.includes('/v1') ? 'websocket' : 'http',+ })+ ).toEqual({ ok: false, reason: 'query-not-allowed' })+ })++ it.each([+ ['/bridge/discovery', 'POST', 'http'],+ ['/bridge/nonce', 'GET', 'http'],+ [`/bridge/pair?nonce=${NONCE}`, 'POST', 'websocket'],+ ['/bridge/v1', 'POST', 'websocket'],+ ] as const)(+ 'rejects the wrong method for %s',+ (rawTarget, method, transport) => {+ expect(decide(rawTarget, { method, transport })).toEqual({+ ok: false,+ reason: 'method-not-allowed',+ })+ }+ )++ it.each([+ ['/bridge/discovery', 'GET', 'websocket'],+ ['/bridge/nonce', 'POST', 'websocket'],+ [`/bridge/pair?nonce=${NONCE}`, 'GET', 'http'],+ ['/bridge/v1', 'GET', 'http'],+ ] as const)(+ 'rejects the wrong transport for %s',+ (rawTarget, method, transport) => {+ expect(decide(rawTarget, { method, transport })).toEqual({+ ok: false,+ reason: 'transport-mismatch',+ })+ }+ )++ it.each([+ `/bridge/pair?nonce=${NONCE}#fragment`,+ `/bridge/pair?nonce=${NONCE}\\suffix`,+ `/bridge/pair?nonce=${NONCE} suffix`,+ `/bridge/pair?nonce=${NONCE}\nnext`,+ ])('rejects malformed raw target %j', (rawTarget) => {+ expect(decide(rawTarget, { transport: 'websocket' })).toEqual({+ ok: false,+ reason: 'malformed-target',+ })+ })++ it.each([+ null,+ 1,+ {},+ { toString: () => '/bridge/v1' },+ '/bridge/服务器/pair',+ `/${'a'.repeat(8_192)}`,+ ])(+ 'rejects an invalid runtime raw target without throwing: %j',+ (rawTarget) => {+ expect(+ evaluateRemoteExtensionRoute(enabled(), {+ rawTarget,+ method: 'GET',+ transport: 'websocket',+ } as never)+ ).toEqual({ ok: false, reason: 'malformed-target' })+ }+ )++ it('rejects a throwing request getter with a fixed result', () => {+ const request = Object.defineProperty({}, 'rawTarget', {+ get() {+ throw new Error('secret-sentinel')+ },+ })+ expect(evaluateRemoteExtensionRoute(enabled(), request as never)).toEqual({+ ok: false,+ reason: 'malformed-target',+ })+ })++ it.each([+ ['https://motrix.example/bridge/v1', 'unknown-route'],+ ['motrix.example:443', 'unknown-route'],+ ['*', 'unknown-route'],+ ] as const)('rejects non-origin-form target %j', (rawTarget, reason) => {+ expect(decide(rawTarget, { transport: 'websocket' })).toEqual({+ ok: false,+ reason,+ })+ })++ it('distinguishes the raw-target length boundary without allocating routes', () => {+ expect(decide(`/${'a'.repeat(8_191)}`)).toEqual({+ ok: false,+ reason: 'unknown-route',+ })+ expect(decide(`/${'a'.repeat(8_192)}`)).toEqual({+ ok: false,+ reason: 'malformed-target',+ })+ })++ it('keeps every route closed for a disabled feature', () => {+ expect(+ evaluateRemoteExtensionRoute(parseRemoteExtensionConfig({}), {+ rawTarget: `/pair?nonce=${NONCE}`,+ method: 'GET',+ transport: 'websocket',+ })+ ).toEqual({ ok: false, reason: 'feature-closed' })+ })+})diff --git a/src/server/bridge/remote-extension-route-policy.ts b/src/server/bridge/remote-extension-route-policy.tsnew file mode 100644index 00000000..aad638b5--- /dev/null+++ b/src/server/bridge/remote-extension-route-policy.ts@@ -0,0 +1,178 @@+import { isCanonicalMbp1PairNonce } from '@core/bridge/mbp1/nonce-service'+import {+ isIssuedRemoteExtensionConfig,+ type RemoteExtensionConfig,+} from './remote-extension-config'++const MAX_RAW_REQUEST_TARGET_LENGTH = 8_192++export type RemoteExtensionRoute = 'discovery' | 'nonce' | 'pair' | 'v1'++export interface RemoteExtensionRouteTargets {+ readonly discovery: string+ readonly nonce: string+ readonly pair: string+ readonly v1: string+}++export type RemoteExtensionRouteRejection =+ | 'feature-closed'+ | 'malformed-target'+ | 'unknown-route'+ | 'method-not-allowed'+ | 'transport-mismatch'+ | 'query-not-allowed'+ | 'malformed-pair-query'++export type RemoteExtensionRouteDecision =+ | {+ readonly ok: true+ readonly route: RemoteExtensionRoute+ readonly pairNonce?: string+ }+ | { readonly ok: false; readonly reason: RemoteExtensionRouteRejection }++function reject(+ reason: RemoteExtensionRouteRejection+): RemoteExtensionRouteDecision {+ return Object.freeze({ ok: false, reason })+}++function canonicalConfiguredBasePath(+ config: RemoteExtensionConfig+): string | null {+ if (!isIssuedRemoteExtensionConfig(config) || config.status !== 'enabled') {+ return null+ }+ let parsed: URL+ try {+ parsed = new URL(config.publicWebSocketBaseUrl)+ } catch {+ return null+ }+ const basePath =+ parsed.pathname === '/' ? '' : parsed.pathname.replace(/\/+$/u, '')+ if (+ (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') ||+ parsed.username !== '' ||+ parsed.password !== '' ||+ parsed.search !== '' ||+ parsed.hash !== '' ||+ parsed.host === '' ||+ parsed.host !== config.publicWebSocketAuthority ||+ `${parsed.origin}${basePath}` !== config.publicWebSocketBaseUrl ||+ basePath !== config.publicWebSocketBasePath+ ) {+ return null+ }+ return basePath+}++/**+ * Derive the only four public request paths from the canonical configured WS/WSS+ * base. The returned strings are raw-path match keys: a proxy must preserve+ * them byte-for-byte and must not decode, normalize, or strip the prefix.+ */+export function deriveRemoteExtensionRouteTargets(+ config: RemoteExtensionConfig+): RemoteExtensionRouteTargets | null {+ const prefix = canonicalConfiguredBasePath(config)+ if (prefix === null) return null+ return Object.freeze({+ discovery: `${prefix}/discovery`,+ nonce: `${prefix}/nonce`,+ pair: `${prefix}/pair`,+ v1: `${prefix}/v1`,+ })+}++function splitRawTarget(+ rawTarget: unknown+): { path: string; query: string | null } | null {+ if (typeof rawTarget !== 'string') return null+ let containsControlOrSpace = false+ for (let index = 0; index < rawTarget.length; index += 1) {+ const codePoint = rawTarget.charCodeAt(index)+ if (codePoint <= 0x20 || codePoint > 0x7e) {+ containsControlOrSpace = true+ break+ }+ }+ if (+ rawTarget.length === 0 ||+ rawTarget.length > MAX_RAW_REQUEST_TARGET_LENGTH ||+ rawTarget.includes('#') ||+ rawTarget.includes('\\') ||+ containsControlOrSpace+ ) {+ return null+ }+ const queryOffset = rawTarget.indexOf('?')+ return queryOffset === -1+ ? { path: rawTarget, query: null }+ : {+ path: rawTarget.slice(0, queryOffset),+ query: rawTarget.slice(queryOffset + 1),+ }+}++/**+ * Fail-closed request-target demultiplexer for the future public listener.+ *+ * This is deliberately pure and remains unwired. It compares the raw path,+ * before a framework or reverse proxy can turn encoded separators/dot segments+ * into an alias. `/pair` accepts one canonical base64url nonce query only;+ * `/v1` accepts no query, so a historical `?token=` can never select an auth+ * mode. Query rejection is not an authentication oracle: it occurs before an+ * MBP1 session or credential lookup exists.+ */+export function evaluateRemoteExtensionRoute(+ config: RemoteExtensionConfig,+ request: {+ readonly rawTarget: string+ readonly method: string+ readonly transport: 'http' | 'websocket'+ }+): RemoteExtensionRouteDecision {+ const routes = deriveRemoteExtensionRouteTargets(config)+ if (routes === null) return reject('feature-closed')+ let rawTarget: unknown+ let method: unknown+ let transport: unknown+ try {+ rawTarget = request?.rawTarget+ method = request?.method+ transport = request?.transport+ } catch {+ return reject('malformed-target')+ }+ const target = splitRawTarget(rawTarget)+ if (target === null) return reject('malformed-target')++ let route: RemoteExtensionRoute+ if (target.path === routes.discovery) route = 'discovery'+ else if (target.path === routes.nonce) route = 'nonce'+ else if (target.path === routes.pair) route = 'pair'+ else if (target.path === routes.v1) route = 'v1'+ else return reject('unknown-route')++ const expectsWebSocket = route === 'pair' || route === 'v1'+ if (transport !== (expectsWebSocket ? 'websocket' : 'http')) {+ return reject('transport-mismatch')+ }+ const expectedMethod = route === 'nonce' ? 'POST' : 'GET'+ if (method !== expectedMethod) return reject('method-not-allowed')++ if (route !== 'pair') {+ if (target.query !== null) return reject('query-not-allowed')+ return Object.freeze({ ok: true, route })+ }+ if (target.query === null || !target.query.startsWith('nonce=')) {+ return reject('malformed-pair-query')+ }+ const nonce = target.query.slice('nonce='.length)+ if (!isCanonicalMbp1PairNonce(nonce)) {+ return reject('malformed-pair-query')+ }+ return Object.freeze({ ok: true, route, pairNonce: nonce })+}diff --git a/src/server/bridge/remote-extension-startup-log.test.ts b/src/server/bridge/remote-extension-startup-log.test.tsnew file mode 100644index 00000000..a8c5f4d7--- /dev/null+++ b/src/server/bridge/remote-extension-startup-log.test.ts@@ -0,0 +1,83 @@+import { describe, expect, it, vi } from 'vitest'+import {+ parseRemoteExtensionConfig,+ type RemoteExtensionConfig,+} from './remote-extension-config'+import { logRemoteExtensionPairingReady } from './remote-extension-startup-log'++function logger() {+ return { info: vi.fn(), warn: vi.fn() }+}++describe('logRemoteExtensionPairingReady', () => {+ it.each([+ ['WS', 'WS://NAS.Local:80/bridge/', 'ws://nas.local/bridge'],+ ['WSS', 'WSS://Motrix.Example:443/', 'wss://motrix.example'],+ ])(+ 'prints the canonical %s address a user can paste into the Extension',+ (_transport, configuredAddress, expectedAddress) => {+ const log = logger()+ const config = parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: configuredAddress,+ MOTRIX_PUBLIC_URL: 'https://operator.example',+ })++ logRemoteExtensionPairingReady(log, config)++ expect(log.info).toHaveBeenCalledWith(+ { extensionServerAddress: expectedAddress },+ `Motrix Extension pairing ready. Enter this Server address in the Extension: ${expectedAddress}`+ )+ expect(log.warn).not.toHaveBeenCalled()+ }+ )++ it('warns when the operator explicitly accepts HTTP on a trusted network', () => {+ const log = logger()+ const config = parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'ws://nas.local:16801',+ MOTRIX_PUBLIC_URL: 'http://nas.local:8080',+ MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP: 'true',+ })++ logRemoteExtensionPairingReady(log, config)++ expect(log.warn).toHaveBeenCalledWith(+ { operatorTransport: 'http' },+ 'Motrix operator UI uses HTTP. The operator token, pairing codes, session cookies, and administrator traffic are not protected by TLS. Use only on a trusted network; HTTPS is recommended.'+ )+ expect(log.info).toHaveBeenCalledWith(+ { extensionServerAddress: 'ws://nas.local:16801' },+ 'Motrix Extension pairing ready. Enter this Server address in the Extension: ws://nas.local:16801'+ )+ })++ it.each([+ parseRemoteExtensionConfig({}),+ parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ }),+ ])('does not advertise a disabled or invalid surface', (config) => {+ const log = logger()++ logRemoteExtensionPairingReady(log, config)++ expect(log.info).not.toHaveBeenCalled()+ expect(log.warn).not.toHaveBeenCalled()+ })++ it('does not advertise a structurally manufactured address', () => {+ const log = logger()+ const forged = {+ status: 'enabled',+ publicWebSocketBaseUrl: 'ws://example.test\nforged-log-entry',+ } as unknown as RemoteExtensionConfig++ logRemoteExtensionPairingReady(log, forged)++ expect(log.info).not.toHaveBeenCalled()+ expect(log.warn).not.toHaveBeenCalled()+ })+})diff --git a/src/server/bridge/remote-extension-startup-log.ts b/src/server/bridge/remote-extension-startup-log.tsnew file mode 100644index 00000000..d32deef1--- /dev/null+++ b/src/server/bridge/remote-extension-startup-log.ts@@ -0,0 +1,35 @@+import type { Logger } from '@core/logger'+import {+ isIssuedRemoteExtensionConfig,+ type RemoteExtensionConfig,+} from './remote-extension-config'++type StartupLogger = Pick<Logger, 'info' | 'warn'>++const INSECURE_OPERATOR_WARNING =+ 'Motrix operator UI uses HTTP. The operator token, pairing codes, session cookies, and administrator traffic are not protected by TLS. Use only on a trusted network; HTTPS is recommended.'++/**+ * Print the exact address a user should copy into Motrix Extension.+ *+ * This runs only after the MBP1 listener and remote Extension routes are ready.+ * Parser issuance is checked again at the log boundary so an untrusted string+ * cannot manufacture a startup message or inject terminal control characters.+ */+export function logRemoteExtensionPairingReady(+ log: StartupLogger,+ config: RemoteExtensionConfig+): void {+ if (!isIssuedRemoteExtensionConfig(config) || config.status !== 'enabled') {+ return+ }++ const extensionServerAddress = config.publicWebSocketBaseUrl+ if (config.publicOperatorBaseUrl.startsWith('http://')) {+ log.warn({ operatorTransport: 'http' }, INSECURE_OPERATOR_WARNING)+ }+ log.info(+ { extensionServerAddress },+ `Motrix Extension pairing ready. Enter this Server address in the Extension: ${extensionServerAddress}`+ )+}diff --git a/src/server/bridge/remote-extension-surface-policy.test.ts b/src/server/bridge/remote-extension-surface-policy.test.tsnew file mode 100644index 00000000..65d86838--- /dev/null+++ b/src/server/bridge/remote-extension-surface-policy.test.ts@@ -0,0 +1,84 @@+import { describe, expect, it } from 'vitest'+import { parseRemoteExtensionConfig } from './remote-extension-config'+import { RemoteExtensionSurfacePolicy } from './remote-extension-surface-policy'++const config = parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'wss://motrix.example/bridge',+ MOTRIX_PUBLIC_URL: 'https://motrix.example',+})+const nonce = (prefix: string) => `${prefix.repeat(21)}Q`++function request(+ rawTarget: string,+ method: string,+ transport: 'http' | 'websocket'+) {+ return {+ rawTarget,+ method,+ transport,+ rawHeaders: ['Host', 'motrix.example'],+ directPeerAddress: '127.0.0.1',+ } as const+}++describe('RemoteExtensionSurfacePolicy', () => {+ it('maps only the canonical public prefix and preserves the pair nonce', () => {+ const policy = new RemoteExtensionSurfacePolicy(config)+ expect(+ policy.evaluate(request('/bridge/discovery', 'GET', 'http'))+ ).toEqual({+ kind: 'route',+ route: 'discovery',+ })+ expect(+ policy.evaluate(+ request(`/bridge/pair?nonce=${nonce('A')}`, 'GET', 'websocket')+ )+ ).toMatchObject({+ kind: 'route',+ route: 'pair',+ pairNonce: nonce('A'),+ })+ expect(policy.evaluate(request('/pair', 'GET', 'websocket'))).toEqual({+ kind: 'not-extension',+ })+ policy.dispose()+ })++ it('rejects Host substitution before opening a route', () => {+ const policy = new RemoteExtensionSurfacePolicy(config)+ expect(+ policy.evaluate({+ ...request('/bridge/discovery', 'GET', 'http'),+ rawHeaders: ['Host', 'attacker.example'],+ })+ ).toEqual({ kind: 'reject', status: 403 })+ policy.dispose()+ })++ it('bounds public pre-auth pair capacity and releases leases', () => {+ const policy = new RemoteExtensionSurfacePolicy(config)+ const leases = Array.from({ length: 32 }, () =>+ policy.evaluate(+ request(`/bridge/pair?nonce=${nonce('B')}`, 'GET', 'websocket')+ )+ )+ expect(leases.every((decision) => decision.kind === 'route')).toBe(true)+ expect(+ policy.evaluate(+ request(`/bridge/pair?nonce=${nonce('C')}`, 'GET', 'websocket')+ )+ ).toEqual({ kind: 'reject', status: 429 })++ const first = leases[0]+ if (first?.kind === 'route') first.releaseAdmission?.()+ expect(+ policy.evaluate(+ request(`/bridge/pair?nonce=${nonce('D')}`, 'GET', 'websocket')+ )+ ).toMatchObject({ kind: 'route', route: 'pair' })+ policy.dispose()+ })+})diff --git a/src/server/bridge/remote-extension-surface-policy.ts b/src/server/bridge/remote-extension-surface-policy.tsnew file mode 100644index 00000000..6d3b45cb--- /dev/null+++ b/src/server/bridge/remote-extension-surface-policy.ts@@ -0,0 +1,98 @@+import type {+ ExtensionMbp1RouteDecision,+ ExtensionMbp1RouteRequest,+} from '@core/bridge/web-socket-bridge-server'+import {+ RemoteExtensionAdmissionPolicy,+ type RemoteExtensionAdmissionRejection,+} from './remote-extension-admission-policy'+import {+ isIssuedRemoteExtensionConfig,+ type RemoteExtensionConfig,+} from './remote-extension-config'+import { evaluateRemoteExtensionHost } from './remote-extension-host-policy'+import { evaluateRemoteExtensionRoute } from './remote-extension-route-policy'++function rejectedAdmission(+ reason: RemoteExtensionAdmissionRejection+): ExtensionMbp1RouteDecision {+ return {+ kind: 'reject',+ status: reason === 'capacity' || reason === 'rate-limited' ? 429 : 403,+ }+}++/**+ * Atomic adapter from the Server's strict public policy modules into core's+ * raw MBP1 route boundary. No normalized framework URL, forwarded Host, query+ * token, or request body participates in routing or authentication.+ */+export class RemoteExtensionSurfacePolicy {+ private readonly admission: RemoteExtensionAdmissionPolicy++ constructor(private readonly config: RemoteExtensionConfig) {+ if (!isIssuedRemoteExtensionConfig(config) || config.status !== 'enabled') {+ throw new Error('remote Extension surface configuration rejected')+ }+ this.admission = new RemoteExtensionAdmissionPolicy({ config })+ }++ evaluate(request: ExtensionMbp1RouteRequest): ExtensionMbp1RouteDecision {+ const route = evaluateRemoteExtensionRoute(this.config, request)+ if (!route.ok) {+ return route.reason === 'unknown-route'+ ? { kind: 'not-extension' }+ : {+ kind: 'reject',+ status: route.reason === 'method-not-allowed' ? 405 : 404,+ }+ }+ const host = evaluateRemoteExtensionHost(this.config, request.rawHeaders)+ if (!host.ok) return { kind: 'reject', status: 403 }++ const source = {+ directPeerAddress: request.directPeerAddress,+ rawHeaders: request.rawHeaders,+ }+ if (route.route === 'discovery') {+ const decision = this.admission.admitDiscoveryRequest(source)+ return decision.ok+ ? { kind: 'route', route: 'discovery' }+ : rejectedAdmission(decision.reason)+ }+ if (route.route === 'nonce') {+ const decision = this.admission.admitNonceRequest(source)+ return decision.ok+ ? {+ kind: 'route',+ route: 'nonce',+ releaseAdmission: () => decision.lease.release(),+ }+ : rejectedAdmission(decision.reason)+ }+ if (route.route === 'pair') {+ const decision = this.admission.acquirePairPreAuthSocket()+ return decision.ok+ ? {+ kind: 'route',+ route: 'pair',+ pairNonce: route.pairNonce,+ releaseAdmission: () => decision.lease.release(),+ }+ : rejectedAdmission(decision.reason)+ }++ const decision = this.admission.acquireV1PreAuthSocket()+ return decision.ok+ ? {+ kind: 'route',+ route: 'v1',+ releaseAdmission: () => decision.lease.release(),+ }+ : rejectedAdmission(decision.reason)+ }++ dispose(): void {+ this.admission.dispose()+ }+}diff --git a/src/server/bridge/remote-extension-wss.integration.test.ts b/src/server/bridge/remote-extension-wss.integration.test.tsnew file mode 100644index 00000000..cadeb8b4--- /dev/null+++ b/src/server/bridge/remote-extension-wss.integration.test.ts@@ -0,0 +1,290 @@+import { mkdtemp, readFile, rm } from 'node:fs/promises'+import { request as httpRequest } from 'node:http'+import {+ createServer as createHttpsServer,+ request as httpsRequest,+} from 'node:https'+import { connect as connectTcp } from 'node:net'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import {+ exchangeCredential,+ initializeParams,+ mdxpOverChannel,+ runPake,+ startPair,+} from '@core/bridge/__tests__/mbp1-client'+import type { ReadHandlerDeps } from '@core/bridge/handlers/read-handlers'+import type { WriteHandlerDeps } from '@core/bridge/handlers/write-handlers'+import { EngineState } from '@shared/types/engine'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import {+ bootstrapBridgeForServer,+ type ServerBridgeRuntime,+ type ServerExtensionReceiver,+} from './bootstrap'+import { parseRemoteExtensionConfig } from './remote-extension-config'++const EXTENSION_ID = 'ibpkjhgpbidfmbmomagmldcdlpbmchgi'++function receiver(): ServerExtensionReceiver {+ return {+ handle: vi.fn(async () => ({ taskId: 'wss-task' })),+ cancel: vi.fn(async () => {}),+ restoreInflight: vi.fn(async () => {}),+ start: vi.fn(),+ stopAndDrain: vi.fn(async () => {}),+ }+}++function readDeps(): ReadHandlerDeps {+ return {+ taskManager: { getAll: () => [], getById: () => undefined },+ statsAggregator: {+ getStats: () => ({+ totalDownloadSpeed: 0,+ totalUploadSpeed: 0,+ activeTasks: 0,+ waitingTasks: 0,+ stoppedTasks: 0,+ }),+ },+ supervisor: {+ getState: () => EngineState.Ready,+ getFeatureReport: () => null,+ },+ }+}++function writeDeps(): WriteHandlerDeps {+ return {+ taskManager: { getById: () => undefined },+ pauseTask: vi.fn(async () => {}),+ resumeTask: vi.fn(async () => {}),+ removeTask: vi.fn(async () => {}),+ createTask: vi.fn(async () => ({ taskId: 'unused' })),+ parseTorrentFileCount: vi.fn(async () => 0),+ }+}++async function startTlsProxy(input: {+ upstreamPort: number+ key: string+ cert: string+}): Promise<{ port: number; close: () => Promise<void> }> {+ const proxy = createHttpsServer({ key: input.key, cert: input.cert })+ proxy.on('request', (request, response) => {+ const upstream = httpRequest(+ {+ host: '127.0.0.1',+ port: input.upstreamPort,+ method: request.method,+ path: request.url,+ headers: request.headers,+ },+ (upstreamResponse) => {+ response.writeHead(+ upstreamResponse.statusCode ?? 502,+ upstreamResponse.headers+ )+ upstreamResponse.pipe(response)+ }+ )+ upstream.once('error', () => {+ if (!response.headersSent) response.writeHead(502)+ response.end()+ })+ request.pipe(upstream)+ })+ proxy.on('upgrade', (request, downstream, head) => {+ const upstream = connectTcp(input.upstreamPort, '127.0.0.1')+ upstream.once('connect', () => {+ upstream.write(+ `${request.method ?? 'GET'} ${request.url ?? '/'} HTTP/${request.httpVersion}\r\n`+ )+ for (let index = 0; index < request.rawHeaders.length; index += 2) {+ upstream.write(+ `${request.rawHeaders[index]}: ${request.rawHeaders[index + 1]}\r\n`+ )+ }+ upstream.write('\r\n')+ if (head.length > 0) upstream.write(head)+ downstream.pipe(upstream).pipe(downstream)+ })+ upstream.once('error', () => downstream.destroy())+ })+ await new Promise<void>((resolve, reject) => {+ proxy.once('error', reject)+ proxy.listen(0, '127.0.0.1', () => resolve())+ })+ const address = proxy.address()+ if (address === null || typeof address === 'string') {+ throw new Error('TLS proxy failed to bind')+ }+ return {+ port: address.port,+ close: () =>+ new Promise<void>((resolve, reject) => {+ proxy.close((error) => (error ? reject(error) : resolve()))+ }),+ }+}++function getDiscovery(input: {+ port: number+ ca?: string+ servername: string+}): Promise<{ status: number; body: unknown }> {+ return new Promise((resolve, reject) => {+ const request = httpsRequest(+ {+ host: '127.0.0.1',+ port: input.port,+ path: '/bridge/discovery',+ method: 'GET',+ headers: { host: 'motrix.test' },+ servername: input.servername,+ ...(input.ca === undefined ? {} : { ca: input.ca }),+ },+ (response) => {+ let body = ''+ response.setEncoding('utf8')+ response.on('data', (chunk) => {+ body += chunk+ })+ response.once('end', () =>+ resolve({+ status: response.statusCode ?? 0,+ body: body === '' ? null : JSON.parse(body),+ })+ )+ }+ )+ request.once('error', reject)+ request.end()+ })+}++describe('remote Extension through a trusted WSS reverse proxy', () => {+ let userDataDir: string+ let runtime: ServerBridgeRuntime | null = null+ let closeProxy: (() => Promise<void>) | null = null++ beforeEach(async () => {+ userDataDir = await mkdtemp(join(tmpdir(), 'motrix-wss-proxy-'))+ })++ afterEach(async () => {+ if (closeProxy !== null) await closeProxy()+ if (runtime !== null) await runtime.shutdown()+ await rm(userDataDir, { recursive: true, force: true })+ })++ it('rejects an expired certificate even when that certificate is explicitly trusted', async () => {+ const fixtureRoot = join(process.cwd(), 'src/server/bridge/__fixtures__')+ const [cert, key] = await Promise.all([+ readFile(join(fixtureRoot, 'expired-motrix.test-cert.pem'), 'utf8'),+ readFile(join(fixtureRoot, 'expired-motrix.test-key.pem'), 'utf8'),+ ])+ const proxy = await startTlsProxy({ upstreamPort: 1, key, cert })+ closeProxy = proxy.close++ await expect(+ getDiscovery({+ port: proxy.port,+ ca: cert,+ servername: 'motrix.test',+ })+ ).rejects.toMatchObject({ code: 'CERT_HAS_EXPIRED' })+ })++ it('validates TLS hostname/CA, preserves Host/base path, pairs, and submits over WSS', async () => {+ const fixtureRoot = join(process.cwd(), 'src/server/bridge/__fixtures__')+ const [ca, cert, key] = await Promise.all([+ readFile(join(fixtureRoot, 'test-ca.pem'), 'utf8'),+ readFile(join(fixtureRoot, 'motrix.test-cert.pem'), 'utf8'),+ readFile(join(fixtureRoot, 'motrix.test-key.pem'), 'utf8'),+ ])+ const extensionReceiver = receiver()+ runtime = await bootstrapBridgeForServer({+ userDataDir,+ host: '127.0.0.1',+ port: 0,+ motrixVersion: '2.0',+ eventBus: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },+ readHandlerDeps: readDeps(),+ writeHandlerDeps: writeDeps(),+ remoteExtensionConfig: parseRemoteExtensionConfig({+ MOTRIX_REMOTE_EXTENSION_ENABLED: 'true',+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: 'wss://motrix.test/bridge',+ MOTRIX_PUBLIC_URL: 'https://motrix.test',+ }),+ createExtensionReceiver: () => extensionReceiver,+ })+ const proxy = await startTlsProxy({+ upstreamPort: runtime.port,+ key,+ cert,+ })+ closeProxy = proxy.close++ await expect(+ getDiscovery({ port: proxy.port, servername: 'motrix.test' })+ ).rejects.toBeDefined()+ await expect(+ getDiscovery({ port: proxy.port, ca, servername: 'wrong.test' })+ ).rejects.toBeDefined()+ await expect(+ getDiscovery({ port: proxy.port, ca, servername: 'motrix.test' })+ ).resolves.toMatchObject({+ status: 200,+ body: { runtime: 'server', extensionPairing: { protocol: 'mbp1' } },+ })++ const secureTransport = { ca, servername: 'motrix.test' }+ const handshake = await startPair({+ port: proxy.port,+ origin: `chrome-extension://${EXTENSION_ID}`,+ browser: 'chromium',+ claimedExtensionId: EXTENSION_ID,+ routePrefix: '/bridge',+ hostHeader: 'motrix.test',+ secureTransport,+ })+ const pending = (await runtime.bridgeQueryHandlers[+ 'bridge:listPendingPairRequests'+ ]()) as Array<{ code?: string }>+ const code = pending[0]?.code+ if (code === undefined) throw new Error('pairing code missing')+ const { channel } = await runPake(handshake, code)+ await exchangeCredential(handshake, channel)+ const connection = mdxpOverChannel(handshake.wire, channel)+ await connection.sendRequest(+ 'motrix/initialize',+ initializeParams(EXTENSION_ID)+ )+ await expect(+ connection.sendRequest('download/submit', {+ source: {+ pageUrl: 'https://example.com/watch',+ pageTitle: 'WSS',+ detectedAt: 1,+ },+ selection: {+ kind: 'direct',+ primary: {+ url: 'https://cdn.example.com/video.mp4',+ headers: {},+ cookies: [],+ refererPolicy: 'strict-origin-when-cross-origin',+ },+ },+ meta: { suggestedFilename: 'video.mp4', qualityLabel: 'source' },+ })+ ).resolves.toEqual({ taskId: 'wss-task' })+ expect(extensionReceiver.handle).toHaveBeenCalledOnce()+ connection.dispose()+ handshake.wire.ws.close()+ await handshake.wire.closed+ })+})diff --git a/src/server/bridge/server-extension-mbp1-runtime.ts b/src/server/bridge/server-extension-mbp1-runtime.tsnew file mode 100644index 00000000..c091d20d--- /dev/null+++ b/src/server/bridge/server-extension-mbp1-runtime.ts@@ -0,0 +1,242 @@+import { join } from 'node:path'+import type { BridgeEventBus } from '@core/bridge/bridge-event-bus'+import { loadOrCreateBridgeInstanceId } from '@core/bridge/bridge-identity'+import {+ type CommittedExtensionCredentialWitness,+ Mbp1CredentialStore,+} from '@core/bridge/credential-store'+import {+ createExtensionIdentityResolver,+ type ExtensionIdentityResolver,+} from '@core/bridge/extension-identity-resolver'+import { ExtensionPairingProjectionService } from '@core/bridge/extension-pairing-projection'+import { FileExtensionPairingProjectionStore } from '@core/bridge/file-extension-pairing-projection-store'+import type {+ ExtensionRevocationLease,+ WebSocketBridgeServer,+} from '@core/bridge/web-socket-bridge-server'+import { AsyncWorkTracker } from '@core/inspector-activity/async-work-tracker'+import type {+ ClientIdentity,+ ResolvePairParams,+ ResolvePairResult,+} from '@shared/protocol/bridge'+import { ServerExtensionPairingPromptAdapter } from './extension-pairing-prompt-adapter'++const CREDENTIAL_SWEEP_INTERVAL_MS = 10 * 60 * 1000++function identityMatchesWitness(+ identity: ClientIdentity & { kind: 'extension' },+ witness: CommittedExtensionCredentialWitness+): boolean {+ return (+ witness.identity.browser === identity.browser &&+ witness.identity.extensionId === identity.extensionId+ )+}++export interface ServerExtensionMbp1RuntimeOptions {+ readonly dataDir: string+ readonly bus: BridgeEventBus+ readonly publicAuthority: string+ readonly credentialSweepIntervalMs?: number+}++/**+ * Durable Server-shell half of Extension MBP1. It intentionally owns no public+ * route policy: bootstrap can prepare/reconcile this runtime while the four+ * routes remain closed, then the remote-surface composition root must open all+ * routes as one separately-reviewed bundle.+ */+export class ServerExtensionMbp1Runtime {+ readonly instanceId: string+ readonly credentials: Mbp1CredentialStore+ readonly extensionPairings: ExtensionPairingProjectionService+ readonly prompts: ServerExtensionPairingPromptAdapter+ readonly identityResolver: ExtensionIdentityResolver++ private readonly asyncWork = new AsyncWorkTracker()+ private readonly sweepTimer: NodeJS.Timeout+ private server: WebSocketBridgeServer | null = null++ private constructor(+ private readonly bus: BridgeEventBus,+ state: {+ instanceId: string+ credentials: Mbp1CredentialStore+ extensionPairings: ExtensionPairingProjectionService+ prompts: ServerExtensionPairingPromptAdapter+ identityResolver: ExtensionIdentityResolver+ credentialSweepIntervalMs: number+ }+ ) {+ this.instanceId = state.instanceId+ this.credentials = state.credentials+ this.extensionPairings = state.extensionPairings+ this.prompts = state.prompts+ this.identityResolver = state.identityResolver+ this.sweepTimer = setInterval(+ () => void this.credentials.sweepExpiredProvisionals(),+ state.credentialSweepIntervalMs+ )+ this.sweepTimer.unref()+ }++ static async load(+ options: ServerExtensionMbp1RuntimeOptions+ ): Promise<ServerExtensionMbp1Runtime> {+ const credentials = await Mbp1CredentialStore.load(+ join(options.dataDir, 'mbp1-credentials.json')+ )+ const extensionPairings = new ExtensionPairingProjectionService(+ new FileExtensionPairingProjectionStore(+ join(options.dataDir, 'extension-pairings.json')+ )+ )+ await extensionPairings.load()+ return new ServerExtensionMbp1Runtime(options.bus, {+ instanceId: await loadOrCreateBridgeInstanceId(+ join(options.dataDir, 'server-instance-id')+ ),+ credentials,+ extensionPairings,+ prompts: new ServerExtensionPairingPromptAdapter(options.bus, {+ publicAuthority: options.publicAuthority,+ }),+ identityResolver: createExtensionIdentityResolver({+ environment: 'production',+ developmentEntries: [],+ }),+ credentialSweepIntervalMs:+ options.credentialSweepIntervalMs ?? CREDENTIAL_SWEEP_INTERVAL_MS,+ })+ }++ attachServer(server: WebSocketBridgeServer): void {+ if (this.server !== null)+ throw new Error('server MBP1 runtime already attached')+ this.server = server+ }++ async recoverBeforeListen(): Promise<void> {+ const server = this.requireServer()+ for (const pending of this.extensionPairings+ .list()+ .filter((record) => record.status === 'cleanup-pending')) {+ const serverLease = server.beginExtensionRevocation(pending.identity)+ const projectionLease =+ await this.extensionPairings.prepareIdentityCleanup(pending.identity)+ try {+ await server.deleteExtensionAuthorization(serverLease, 'user-revoked')+ const absenceWitness =+ await this.credentials.issueExtensionIdentityAbsenceWitness(+ pending.identity.browser,+ pending.identity.extensionId+ )+ await this.extensionPairings.completeCleanup(+ projectionLease,+ absenceWitness+ )+ server.completeExtensionRevocation(serverLease)+ } catch {+ server.retainFailedExtensionRevocation(serverLease)+ throw new Error('extension revocation recovery failed')+ }+ }+ await this.extensionPairings.reconcileCommitted(+ await this.credentials.issueCommittedExtensionSnapshot()+ )+ }++ onAuthenticated(+ identity: ClientIdentity & { kind: 'extension' },+ credentialId: string+ ): void {+ const server = this.requireServer()+ try {+ void this.asyncWork+ .run(async () => {+ const witness =+ await this.credentials.issueCommittedExtensionWitness(credentialId)+ if (!identityMatchesWitness(identity, witness)) {+ throw new Error('authenticated extension identity mismatch')+ }+ await this.extensionPairings.recordAuthenticated(witness, Date.now())+ this.bus.emitPaired({ identity })+ })+ .catch(() => this.quarantineProjectionFailure(server, identity))+ } catch {+ this.quarantineProjectionFailure(server, identity)+ }+ }++ settleExtensionPrompt(+ params: Extract<ResolvePairParams, { kind: 'extension' }>+ ): ResolvePairResult {+ return this.prompts.settle(params)+ }++ async revoke(+ identity: ClientIdentity & { kind: 'extension' }+ ): Promise<void> {+ const server = this.requireServer()+ const serverLease = server.beginExtensionRevocation(identity)+ let markerPersisted = false+ try {+ const cleanupLease =+ await this.extensionPairings.prepareIdentityCleanup(identity)+ markerPersisted = true+ await server.deleteExtensionAuthorization(serverLease, 'user-revoked')+ const absenceWitness =+ await this.credentials.issueExtensionIdentityAbsenceWitness(+ identity.browser,+ identity.extensionId+ )+ await this.extensionPairings.completeCleanup(cleanupLease, absenceWitness)+ server.completeExtensionRevocation(serverLease)+ this.bus.emitRevoked({ identity })+ } catch {+ server.retainFailedExtensionRevocation(serverLease)+ this.bus.emitError({+ code: markerPersisted+ ? 'extensionRevocationIncomplete'+ : 'extensionRevocationMarkerFailed',+ message: markerPersisted+ ? 'Extension revocation is incomplete; access remains closed and startup will retry it.'+ : 'Extension revocation could not be recorded; access is closed for this run, but restart may restore the old credential.',+ })+ throw new Error('extension revocation incomplete')+ }+ }++ async stopAndDrain(): Promise<void> {+ clearInterval(this.sweepTimer)+ await this.asyncWork.stopAndDrain()+ await this.prompts.dispose()+ await this.extensionPairings.stopAndDrain()+ }++ private quarantineProjectionFailure(+ server: WebSocketBridgeServer,+ identity: ClientIdentity & { kind: 'extension' }+ ): void {+ try {+ const lease: ExtensionRevocationLease =+ server.beginExtensionRevocation(identity)+ server.retainFailedExtensionRevocation(lease)+ } catch {+ // The fixed operator signal below remains the observable failure.+ }+ this.bus.emitError({+ code: 'extensionProjectionDegraded',+ message:+ 'Extension pairing state could not be updated; access is closed until startup repair.',+ })+ }++ private requireServer(): WebSocketBridgeServer {+ if (this.server === null)+ throw new Error('server MBP1 runtime is not attached')+ return this.server+ }+}diff --git a/src/server/bridge/server-process-ownership-authority.test.ts b/src/server/bridge/server-process-ownership-authority.test.tsnew file mode 100644index 00000000..62c39ab7--- /dev/null+++ b/src/server/bridge/server-process-ownership-authority.test.ts@@ -0,0 +1,116 @@+import fs from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import { establishServerProcessOwnershipAuthority } from './server-process-ownership-authority'++const roots: string[] = []++async function temporaryDataDir(): Promise<string> {+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'motrix-server-owner-'))+ roots.push(root)+ return root+}++afterEach(async () => {+ await Promise.all(+ roots.splice(0).map((root) => fs.rm(root, { recursive: true }))+ )+})++describe('server process ownership authority', () => {+ it('pins the data directory to an already-owned control-plane port', async () => {+ const userDataDir = await temporaryDataDir()+ let listening = true+ const first = await establishServerProcessOwnershipAuthority({+ userDataDir,+ port: 8080,+ assertControlPlaneOwnership: () => listening,+ })++ expect(first.ownershipEpoch).toMatch(/^[A-Za-z0-9_-]{43}$/u)+ await expect(first.assertExclusiveProcessOwnership()).resolves.toBe(true)++ const restarted = await establishServerProcessOwnershipAuthority({+ userDataDir,+ port: 8080,+ assertControlPlaneOwnership: () => true,+ })+ await expect(restarted.assertExclusiveProcessOwnership()).resolves.toBe(+ true+ )++ listening = false+ await expect(first.assertExclusiveProcessOwnership()).resolves.toBe(false)+ })++ it('rejects a different port for the same data directory', async () => {+ const userDataDir = await temporaryDataDir()+ await establishServerProcessOwnershipAuthority({+ userDataDir,+ port: 8080,+ assertControlPlaneOwnership: () => true,+ })++ await expect(+ establishServerProcessOwnershipAuthority({+ userDataDir,+ port: 8081,+ assertControlPlaneOwnership: () => true,+ })+ ).rejects.toThrow('server bridge process ownership unavailable')+ })++ it('requires the control-plane listener before creating the binding', async () => {+ const userDataDir = await temporaryDataDir()+ await expect(+ establishServerProcessOwnershipAuthority({+ userDataDir,+ port: 8080,+ assertControlPlaneOwnership: () => false,+ })+ ).rejects.toThrow('server bridge process ownership unavailable')++ await expect(+ fs.stat(path.join(userDataDir, '.motrix-server-bridge-owner.json'))+ ).rejects.toMatchObject({ code: 'ENOENT' })+ })++ it('fails closed when the durable binding is replaced after startup', async () => {+ const userDataDir = await temporaryDataDir()+ const authority = await establishServerProcessOwnershipAuthority({+ userDataDir,+ port: 8080,+ assertControlPlaneOwnership: () => true,+ })+ const bindingPath = path.join(+ userDataDir,+ '.motrix-server-bridge-owner.json'+ )+ await fs.unlink(bindingPath)+ await fs.writeFile(bindingPath, '{}\n', { mode: 0o600 })++ await expect(authority.assertExclusiveProcessOwnership()).resolves.toBe(+ false+ )+ })++ it('rejects a symbolic-link binding without following it', async () => {+ if (process.platform === 'win32') return+ const userDataDir = await temporaryDataDir()+ const target = path.join(userDataDir, 'target.json')+ await fs.writeFile(target, '{}\n', { mode: 0o600 })+ await fs.symlink(+ target,+ path.join(userDataDir, '.motrix-server-bridge-owner.json')+ )++ await expect(+ establishServerProcessOwnershipAuthority({+ userDataDir,+ port: 8080,+ assertControlPlaneOwnership: () => true,+ })+ ).rejects.toThrow('server bridge process ownership unavailable')+ })+})diff --git a/src/server/bridge/server-process-ownership-authority.ts b/src/server/bridge/server-process-ownership-authority.tsnew file mode 100644index 00000000..c1e6cf72--- /dev/null+++ b/src/server/bridge/server-process-ownership-authority.ts@@ -0,0 +1,179 @@+import { randomBytes } from 'node:crypto'+import { constants } from 'node:fs'+import fs from 'node:fs/promises'+import path from 'node:path'+import type { BridgeDataDirLockRecoveryAuthority } from '@core/bridge/bridge-data-dir-lock'++const BINDING_VERSION = 1+const BINDING_FILE_NAME = '.motrix-server-bridge-owner.json'+const MAX_BINDING_BYTES = 1024+const NO_FOLLOW = constants.O_NOFOLLOW ?? 0++interface BindingDocument {+ readonly version: typeof BINDING_VERSION+ readonly transport: 'tcp-control-plane'+ readonly host: '0.0.0.0'+ readonly port: number+ readonly bridgeDataDirectory: string+}++export interface ServerProcessOwnershipAuthorityOptions {+ readonly userDataDir: string+ readonly port: number+ /** True only while this process still owns the already-bound control plane. */+ readonly assertControlPlaneOwnership: () => boolean+}++function fail(): Error {+ return new Error('server bridge process ownership unavailable')+}++function serialize(document: BindingDocument): Buffer {+ return Buffer.from(`${JSON.stringify(document)}\n`, 'utf8')+}++function isExactBinding(value: unknown): value is BindingDocument {+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {+ return false+ }+ const record = value as Record<string, unknown>+ if (+ Object.keys(record).length !== 5 ||+ record.version !== BINDING_VERSION ||+ record.transport !== 'tcp-control-plane' ||+ record.host !== '0.0.0.0' ||+ !Number.isSafeInteger(record.port) ||+ (record.port as number) < 1 ||+ (record.port as number) > 65535 ||+ typeof record.bridgeDataDirectory !== 'string' ||+ record.bridgeDataDirectory.length === 0+ ) {+ return false+ }+ return true+}++function sameFile(+ left: { dev: number | bigint; ino: number | bigint },+ right: { dev: number | bigint; ino: number | bigint }+): boolean {+ return (+ BigInt(left.dev) === BigInt(right.dev) &&+ BigInt(left.ino) === BigInt(right.ino)+ )+}++async function readExactBinding(filePath: string): Promise<BindingDocument> {+ let handle: fs.FileHandle | null = null+ try {+ const before = await fs.lstat(filePath, { bigint: true })+ if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1n) {+ throw fail()+ }+ if (process.platform !== 'win32' && (before.mode & 0o777n) !== 0o600n) {+ throw fail()+ }+ const flags = constants.O_RDONLY | NO_FOLLOW+ handle = await fs.open(filePath, flags)+ const during = await handle.stat({ bigint: true })+ if (!sameFile(before, during) || during.size > BigInt(MAX_BINDING_BYTES)) {+ throw fail()+ }+ const bytes = await handle.readFile()+ if (bytes.length === 0 || bytes.length > MAX_BINDING_BYTES) throw fail()+ const parsed: unknown = JSON.parse(bytes.toString('utf8'))+ if (!isExactBinding(parsed) || !bytes.equals(serialize(parsed)))+ throw fail()+ const after = await fs.lstat(filePath, { bigint: true })+ if (!sameFile(during, after)) throw fail()+ return parsed+ } catch {+ throw fail()+ } finally {+ await handle?.close().catch(() => undefined)+ }+}++async function persistBinding(+ filePath: string,+ expected: BindingDocument+): Promise<void> {+ try {+ const handle = await fs.open(filePath, 'wx', 0o600)+ try {+ await handle.writeFile(serialize(expected))+ await handle.sync()+ } finally {+ await handle.close()+ }+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw fail()+ }++ const actual = await readExactBinding(filePath)+ if (+ actual.port !== expected.port ||+ actual.host !== expected.host ||+ actual.transport !== expected.transport ||+ actual.bridgeDataDirectory !== expected.bridgeDataDirectory+ ) {+ throw fail()+ }+}++/**+ * Pins one Server data directory to the main TCP control-plane port. The+ * already-listening socket is the external OS exclusivity proof used to+ * recover a bridge lock left by a crash. A second process cannot substitute a+ * different port for the same data directory, and cannot own the pinned port+ * while the first process is alive.+ */+export async function establishServerProcessOwnershipAuthority(+ options: ServerProcessOwnershipAuthorityOptions+): Promise<BridgeDataDirLockRecoveryAuthority> {+ if (+ !Number.isSafeInteger(options.port) ||+ options.port < 1 ||+ options.port > 65535 ||+ !options.assertControlPlaneOwnership()+ ) {+ throw fail()+ }++ await fs.mkdir(options.userDataDir, { recursive: true })+ const canonicalUserDataDir = await fs.realpath(options.userDataDir)+ const bridgeDataDirectory = path.join(canonicalUserDataDir, 'bridge')+ await fs.mkdir(bridgeDataDirectory, { recursive: true })+ const canonicalBridgeDataDirectory = await fs.realpath(bridgeDataDirectory)+ const binding: BindingDocument = {+ version: BINDING_VERSION,+ transport: 'tcp-control-plane',+ host: '0.0.0.0',+ port: options.port,+ bridgeDataDirectory: canonicalBridgeDataDirectory,+ }+ const bindingPath = path.join(canonicalUserDataDir, BINDING_FILE_NAME)+ await persistBinding(bindingPath, binding)++ const ownershipEpoch = randomBytes(32).toString('base64url')+ return Object.freeze({+ ownershipEpoch,+ assertExclusiveProcessOwnership: async () => {+ if (!options.assertControlPlaneOwnership()) return false+ try {+ const currentBridgeDirectory = await fs.realpath(bridgeDataDirectory)+ if (currentBridgeDirectory !== canonicalBridgeDataDirectory)+ return false+ const current = await readExactBinding(bindingPath)+ return (+ current.port === binding.port &&+ current.host === binding.host &&+ current.transport === binding.transport &&+ current.bridgeDataDirectory === binding.bridgeDataDirectory+ )+ } catch {+ return false+ }+ },+ })+}diff --git a/src/server/http/operator-auth.test.ts b/src/server/http/operator-auth.test.tsindex b3713ef9..4a2f5bd2 100644--- a/src/server/http/operator-auth.test.ts+++ b/src/server/http/operator-auth.test.ts@@ -1,6 +1,6 @@import { DeviceCodeService } from '@core/bridge/device-code-service'import type { PairedClient, PairingService } from '@core/bridge/pairing-service'-import { BridgeCommands } from '@shared/protocol/bridge'+import { BridgeCommands, BridgeQueries } from '@shared/protocol/bridge'import { Commands } from '@shared/protocol/commands'import type { FastifyInstance } from 'fastify'import { afterEach, beforeEach, describe, expect, it } from 'vitest'@@ -226,6 +226,80 @@ describe('device-code approval is gated by the operator (the Codex bypass)', ()expect(dc.poll(requestId).status).toBe('approved')await app.close()})++ it('keeps an Extension pairing code behind operator auth and same-origin CSRF checks', async () => {+ const extensionRequest = {+ kind: 'extension' as const,+ pairingNonce: 'n'.repeat(43),+ extensionId: 'a'.repeat(32),+ browser: 'chromium' as const,+ identity: 'official' as const,+ code: 'JKLM-NPQR',+ createdAt: 1,+ expiresAt: 2,+ }+ const app = await createApp({+ commandHandlers: {},+ queryHandlers: {},+ bridgeQueryHandlers: {+ [BridgeQueries.ListPendingPairRequests]: async () => [extensionRequest],+ },+ bridgeCommandHandlers: {+ [BridgeCommands.ResolvePair]: async () => ({ ok: true }),+ },+ operatorAuth: { operatorToken: TOKEN },+ })+ const pendingUrl = `/rpc/query/${encodeURIComponent(+ BridgeQueries.ListPendingPairRequests+ )}`+ const dismissUrl = `/rpc/command/${encodeURIComponent(+ BridgeCommands.ResolvePair+ )}`++ const anonymous = await app.inject({ method: 'POST', url: pendingUrl })+ expect(anonymous.statusCode).toBe(401)+ expect(anonymous.body).not.toContain(extensionRequest.code)+ expect(anonymous.headers['cache-control']).toBe('no-store')++ const authorized = await app.inject({+ method: 'POST',+ url: pendingUrl,+ headers: { authorization: `Bearer ${TOKEN}` },+ payload: { args: [] },+ })+ expect(authorized.statusCode).toBe(200)+ expect(authorized.json()).toEqual([extensionRequest])+ expect(authorized.headers['cache-control']).toBe('no-store')+ expect(authorized.headers.pragma).toBe('no-cache')+ expect(pendingUrl).not.toContain(extensionRequest.code)++ const login = await app.inject({+ method: 'POST',+ url: '/rpc/auth/login',+ payload: { token: TOKEN },+ })+ const crossOriginDismiss = await app.inject({+ method: 'POST',+ url: dismissUrl,+ headers: {+ cookie: sessionCookie(login),+ origin: 'https://evil.example',+ host: 'motrix.example',+ },+ payload: {+ args: [+ {+ kind: 'extension',+ pairingNonce: extensionRequest.pairingNonce,+ extensionId: extensionRequest.extensionId,+ browser: extensionRequest.browser,+ },+ ],+ },+ })+ expect(crossOriginDismiss.statusCode).toBe(403)+ await app.close()+ })})describe('operator auth disabled (no operatorAuth option)', () => {diff --git a/src/server/http/operator-auth.ts b/src/server/http/operator-auth.tsindex 3cd8192c..0c0705fb 100644--- a/src/server/http/operator-auth.ts+++ b/src/server/http/operator-auth.ts@@ -31,6 +31,10 @@ export interface OperatorAuthOptions {* and the control plane never depends on the (non-fatal) bridge bootstrap.*/operatorToken: string+ /** Public operator URL advertised by MOTRIX_PUBLIC_URL. Cookie-authenticated+ * event WebSockets must present this exact URL origin; scripts using Bearer+ * authentication remain independent of browser Origin semantics. */+ publicUrl?: string/** Injectable clock (tests). */now?: () => number}@@ -69,6 +73,47 @@ function isSecure(req: FastifyRequest): boolean {)}+function isWebSocketUpgrade(req: FastifyRequest): boolean {+ return String(req.headers.upgrade ?? '').toLowerCase() === 'websocket'+}++function configuredPublicOrigin(value: string | undefined): string | null {+ if (value === undefined) return null+ try {+ const parsed = new URL(value)+ if (+ (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') ||+ parsed.username !== '' ||+ parsed.password !== ''+ ) {+ return null+ }+ return parsed.origin+ } catch {+ return null+ }+}++function exactBrowserOrigin(+ req: FastifyRequest,+ publicOrigin: string | null+): boolean {+ const presented = req.headers.origin+ if (typeof presented !== 'string' || presented.length === 0) return false+ const expected =+ publicOrigin ??+ (() => {+ const host = req.headers.host+ if (typeof host !== 'string' || host.length === 0) return null+ try {+ return new URL(`${isSecure(req) ? 'https' : 'http'}://${host}`).origin+ } catch {+ return null+ }+ })()+ return expected !== null && presented === expected+}+/** Deny a request. A normal `reply.send()` does NOT yield a clean HTTP response* on a WebSocket UPGRADE request (the client just hangs), so for an upgrade we* hijack and write a raw status line so the `ws` client gets `unexpected-response`. */@@ -78,8 +123,7 @@ function deny(code: number,message: string): FastifyReply | undefined {- const isUpgrade =- String(req.headers.upgrade ?? '').toLowerCase() === 'websocket'+ const isUpgrade = isWebSocketUpgrade(req)if (isUpgrade) {reply.hijack()const text = code === 403 ? 'Forbidden' : 'Unauthorized'@@ -117,6 +161,7 @@ export function registerOperatorAuth(opts: OperatorAuthOptions): void {const now = opts.now ?? Date.now+ const publicOrigin = configuredPublicOrigin(opts.publicUrl)const sessions = new Map<string, number>() // sessionId -> expiresAtlet failedLogins: number[] = [] // timestamps of FAILED attempts only@@ -132,15 +177,26 @@ export function registerOperatorAuth(return true}- const isOperator = (req: FastifyRequest): boolean => {+ const authenticate = (req: FastifyRequest): 'bearer' | 'cookie' | null => {const tok = bearerToken(req)- if (tok && safeEqual(tok, opts.operatorToken)) return true+ if (tok && safeEqual(tok, opts.operatorToken)) return 'bearer'return validSession(parseCookies(req.headers.cookie)[COOKIE])+ ? 'cookie'+ : null}// ── deny-by-default gate ────────────────────────────────────────────────app.addHook('onRequest', async (req, reply) => {+ const path = req.url.split('?')[0]+ if (path.startsWith('/rpc/') || path.startsWith('/api/')) {+ // Operator responses can contain live pairing codes, task metadata, and+ // other machine-owner state. Keep them out of browser/proxy caches even+ // when the request is rejected or the caller used Bearer auth.+ reply.header('cache-control', 'no-store')+ reply.header('pragma', 'no-cache')+ }if (isPublic(req.method, req.url)) return+ const authentication = authenticate(req)// CSRF defense-in-depth on mutations: reject a present-but-cross-origin// Origin. SameSite=Strict is the primary defense; non-browser callers omit// Origin and authenticate by Bearer.@@ -158,9 +214,16 @@ export function registerOperatorAuth(}}}- if (!isOperator(req)) {+ if (authentication === null) {return deny(req, reply, 401, 'unauthorized')}+ if (+ isWebSocketUpgrade(req) &&+ authentication === 'cookie' &&+ !exactBrowserOrigin(req, publicOrigin)+ ) {+ return deny(req, reply, 403, 'cross-origin forbidden')+ }})// ── auth routes ─────────────────────────────────────────────────────────@@ -197,7 +260,9 @@ export function registerOperatorAuth(})- app.get('/rpc/auth/status', async (req) => ({ authed: isOperator(req) }))+ app.get('/rpc/auth/status', async (req) => ({+ authed: authenticate(req) !== null,+ }))app.post('/rpc/auth/logout', async (req, reply) => {const id = parseCookies(req.headers.cookie)[COOKIE]diff --git a/src/server/http/rpc-ws-auth.test.ts b/src/server/http/rpc-ws-auth.test.tsindex 34afd03d..048638af 100644--- a/src/server/http/rpc-ws-auth.test.ts+++ b/src/server/http/rpc-ws-auth.test.ts@@ -17,7 +17,10 @@ describe('/rpc/events WebSocket auth', () => {bus = new EventBus()app = await createApp({eventBus: bus,- operatorAuth: { operatorToken: TOKEN },+ operatorAuth: {+ operatorToken: TOKEN,+ publicUrl: 'https://motrix.example/operator',+ },})await app.listen({ port: 0, host: '127.0.0.1' })port = (app.server.address() as AddressInfo).port@@ -51,7 +54,10 @@ describe('/rpc/events WebSocket auth', () => {})it('accepts an upgrade carrying the operator cookie and streams events', async () => {- const ws = await connect({ cookie: await cookie() })+ const ws = await connect({+ cookie: await cookie(),+ origin: 'https://motrix.example',+ })const frame = new Promise<unknown>((resolve) => {ws.once('message', (data) => resolve(JSON.parse(String(data))))})@@ -63,6 +69,16 @@ describe('/rpc/events WebSocket auth', () => {ws.close()})+ it.each([+ ['missing Origin', {}],+ ['wrong origin', { origin: 'https://evil.example' }],+ ['wrong scheme', { origin: 'http://motrix.example' }],+ ])('rejects a cookie upgrade with %s', async (_label, headers) => {+ await expect(+ connect({ cookie: await cookie(), ...headers })+ ).rejects.toThrow('http 403')+ })+it('accepts an upgrade with a Bearer operator token (host script)', async () => {const ws = await connect({ authorization: `Bearer ${TOKEN}` })expect(ws.readyState).toBe(WebSocket.OPEN)diff --git a/src/server/index.ts b/src/server/index.tsindex f96ef0fc..b9564b40 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -3,6 +3,8 @@ import os from 'node:os'import path from 'node:path'import { fileURLToPath } from 'node:url'import { TaskActivityService, TaskActivityStore } from '@core/activity'+import { BridgeReceiver } from '@core/bridge-receiver/bridge-receiver'+import { Aria2SegmentClient } from '@core/download/aria2-segment-client'import { Aria2Adapter } from '@core/engine/aria2/aria2-adapter'import { Aria2ConfigBuilder } from '@core/engine/aria2/aria2-config-builder'import { Aria2ProcessManager } from '@core/engine/aria2/aria2-process-manager'@@ -114,6 +116,9 @@ import {type ServerBridgeRuntime,} from './bridge/bootstrap'import { diagnoseMdxpPublicUrl } from './bridge/public-url-diagnostic'+import { parseRemoteExtensionConfig } from './bridge/remote-extension-config'+import { logRemoteExtensionPairingReady } from './bridge/remote-extension-startup-log'+import { establishServerProcessOwnershipAuthority } from './bridge/server-process-ownership-authority'import {createServerDownloadPathPolicy,resolveServerDefaultSaveDir,@@ -1031,7 +1036,10 @@ async function main() {bridgeQueryHandlers,eventBus,rendererDir,- operatorAuth: { operatorToken: operator.token },+ operatorAuth: {+ operatorToken: operator.token,+ publicUrl: process.env.MOTRIX_PUBLIC_URL,+ },healthCheck: () =>serverHealthSnapshot({accepting: shellAsyncWork.isAccepting(),@@ -1545,6 +1553,16 @@ async function main() {{ allowZero: true })const mdxpHost = process.env.MOTRIX_MDXP_HOST ?? '127.0.0.1'+ const remoteExtensionConfig = parseRemoteExtensionConfig(process.env)+ if (remoteExtensionConfig.status === 'invalid') {+ log.warn(+ {+ code: remoteExtensionConfig.diagnostic.code,+ variable: remoteExtensionConfig.diagnostic.variable,+ },+ 'remote Extension configuration rejected; routes remain closed'+ )+ }const publicUrlWarning = diagnoseMdxpPublicUrl({mdxpHost,publicUrl: process.env.MOTRIX_PUBLIC_URL,@@ -1558,12 +1576,80 @@ async function main() {'non-loopback MDXP bind has no usable MOTRIX_PUBLIC_URL; remote clients may not receive a usable approval URL')}+ const bridgeDataDirLockRecoveryAuthority =+ await establishServerProcessOwnershipAuthority({+ userDataDir: platform.userDataDir,+ port,+ assertControlPlaneOwnership: () => {+ if (!app.server.listening) return false+ const address = app.server.address()+ return (+ typeof address === 'object' &&+ address !== null &&+ address.port === port+ )+ },+ })const candidateBridgeRuntime = await bootstrapBridgeForServer({userDataDir: platform.userDataDir,host: mdxpHost,port: mdxpPort,motrixVersion: appVersion,eventBus,+ bridgeDataDirLockRecoveryAuthority,+ remoteExtensionConfig,+ createExtensionReceiver: ({ dataDir, bridgeBus }) =>+ new BridgeReceiver({+ dataDir,+ defaultSaveDir: settingsManager.getApp().defaultSaveDir,+ pickName: (saveDir, desired) =>+ finalNamePicker.pick(saveDir, desired),+ createTask: (request, _deps, options) =>+ handleCreateTask(request, createTaskDeps, options),+ removeTask: async (taskId) => {+ if (!taskManager.getById(taskId)) return+ await removeTask(+ taskId,+ { deleteWithFiles: false },+ removeTaskDeps+ )+ },+ submitMagnetForFileSelection: (uri, saveDir, sourceMeta) =>+ magnetTracker.submit(uri, saveDir, {+ source: 'bridge',+ sourceMeta,+ }),+ isMagnetFileSelectionEnabled: () =>+ settingsManager.getApp().magnetFileSelection,+ eventBus,+ bridgeBus,+ localize: (code) => code,+ // The Server currently advertises direct selection only. Keeping+ // media disabled here makes that capability statement executable,+ // while direct/magnet submissions reuse the same validated paths+ // and cookie/header hygiene as Desktop.+ ffmpegBinaryPath: null,+ publishTaskUpdate,+ publishTaskUpdateNow,+ taskManager,+ activityRecorder: taskActivityService,+ segmentAria2: new Aria2SegmentClient(rpcClient),+ tmpRoot: runtimeDirectories.tempDir,+ persistTask,+ persistTaskWithOccurrence,+ occurrenceDispatcher,+ parentTaskCreated: (task, persistParent) =>+ taskInspectorActivityRuntime.parentTaskCreated(+ task,+ persistParent+ ),+ recordTransition: (input) =>+ taskInspectorActivityRuntime.recordTransition(input),+ runTaskMutation: (taskIds, operation) =>+ taskInspectorActivityRuntime.runTaskMutation(taskIds, operation),+ waitForReady: () =>+ supervisor.waitUntilReady(ENGINE_READY_TIMEOUT_MS),+ }),// The web approval UI is a separate (Fastify) service; the operator points// device-code clients at it via MOTRIX_PUBLIC_URL. Unset → no URL printed.verificationUri: process.env.MOTRIX_PUBLIC_URL,@@ -1593,6 +1679,7 @@ async function main() {Object.assign(bridgeCommandHandlers, bridgeRuntime.bridgeCommandHandlers)Object.assign(bridgeQueryHandlers, bridgeRuntime.bridgeQueryHandlers)log.info({ port: bridgeRuntime.port }, 'MDXP bridge listening')+ logRemoteExtensionPairingReady(log, remoteExtensionConfig)} catch (err) {log.error({ err }, 'MDXP bridge bootstrap failed — continuing without it')}diff --git a/src/server/operator-admin.test.ts b/src/server/operator-admin.test.tsindex 0db47d9b..d4498750 100644--- a/src/server/operator-admin.test.ts+++ b/src/server/operator-admin.test.ts@@ -43,6 +43,30 @@ function request(}}+function extensionRequest(+ overrides: Partial<{+ pairingNonce: string+ extensionId: string+ browser: 'chromium' | 'firefox'+ identity: 'official' | 'attested-non-official' | 'unverified'+ code: string+ createdAt: number+ expiresAt: number+ }> = {}+) {+ return {+ kind: 'extension' as const,+ pairingNonce: 'n'.repeat(43),+ extensionId: 'a'.repeat(32),+ browser: 'chromium' as const,+ identity: 'official' as const,+ code: 'JKLM-NPQR',+ createdAt: NOW - 500,+ expiresAt: NOW + 59_500,+ ...overrides,+ }+}+function harness(fetchMock: ReturnType<typeof vi.fn>,overrides: AdminOptions = {}@@ -254,6 +278,51 @@ describe('runOperatorAdmin', () => {expect(output).not.toContain(TOKEN)})+ it('validates the pending union but prints only CLI requests', async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValue(jsonResponse([extensionRequest(), request()]))+ const h = harness(fetchMock)++ await expect(+ runOperatorAdmin(['pairing', 'pending', '--json'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Success)++ const output = h.stdout.join('')+ expect(JSON.parse(output).requests).toHaveLength(1)+ expect(output).toContain('ABCD-EFGH')+ expect(output).not.toContain('JKLM-NPQR')+ expect(output).not.toContain('extension')+ })++ it('reports no CLI requests when only Extension pairing is pending', async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValue(jsonResponse([extensionRequest()]))+ const h = harness(fetchMock)++ await expect(+ runOperatorAdmin(['pairing', 'pending'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Success)+ expect(h.stdout).toEqual(['No pending pairing requests.'])+ expect(h.stdout.join('')).not.toContain('JKLM-NPQR')+ })++ it('fails closed on a malformed Extension row instead of silently dropping it', async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValue(+ jsonResponse([extensionRequest({ browser: 'safari' as never })])+ )+ const h = harness(fetchMock)++ await expect(+ runOperatorAdmin(['pairing', 'pending'], h.options)+ ).resolves.toBe(OperatorAdminExitCode.Server)+ expect(h.stdout).toEqual([])+ expect(h.stderr.join('')).not.toContain('JKLM-NPQR')+ })+it('sanitizes and bounds untrusted client metadata in JSON output', async () => {const fetchMock = vi.fn().mockResolvedValue(jsonResponse([diff --git a/src/server/operator-admin.ts b/src/server/operator-admin.tsindex 92c86427..46d41204 100644--- a/src/server/operator-admin.ts+++ b/src/server/operator-admin.ts@@ -31,6 +31,10 @@ const MAX_CLIENT_NAME_LENGTH = 80const MAX_CLIENT_VERSION_LENGTH = 32type PendingCliRequest = Extract<PendingPairRequestInfo, { kind: 'cli' }>+type PendingExtensionRequest = Extract<+ PendingPairRequestInfo,+ { kind: 'extension' }+>type Translate = (key: string,values?: Readonly<Record<string, string | number>>@@ -48,7 +52,34 @@ const pendingCliRequestSchema: z.ZodType<PendingCliRequest> = z}).strict()-const pendingResponseSchema = z.array(pendingCliRequestSchema).max(1_000)+const pendingExtensionRequestSchema: z.ZodType<PendingExtensionRequest> = z+ .object({+ kind: z.literal('extension'),+ pairingNonce: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),+ extensionId: z.string().min(1).max(256),+ browser: z.enum(['chromium', 'firefox']),+ identity: z.enum(['official', 'attested-non-official', 'unverified']),+ code: z.string().regex(WIRE_USER_CODE_PATTERN),+ verifiedOrigin: z.string().min(1).max(512).optional(),+ originHost: z.string().min(1).max(256).optional(),+ claimedExtensionId: z.string().min(1).max(256).optional(),+ attestationClass: z+ .enum(['official', 'attested-non-official', 'unverified'])+ .optional(),+ publicAuthority: z.string().min(1).max(512).optional(),+ createdAt: z.number().int().nonnegative(),+ expiresAt: z.number().int().nonnegative(),+ })+ .strict()++const pendingPairRequestSchema: z.ZodType<PendingPairRequestInfo> = z.union([+ pendingCliRequestSchema,+ pendingExtensionRequestSchema,+])++const pendingResponseSchema: z.ZodType<PendingPairRequestInfo[]> = z+ .array(pendingPairRequestSchema)+ .max(1_000)const resolvePairResultSchema: z.ZodType<ResolvePairResult> =z.discriminatedUnion('ok', [@@ -521,7 +552,14 @@ async function listPendingRequests(OperatorAdminErrorCode.PendingResponseInvalid)}- return parsed.data+ // `motrix-admin` is intentionally CLI-only: Extension pairing approval is+ // code-entry in the browser, not an operator allow/deny action. Validate+ // the complete renderer-safe union first so a malformed Server response+ // still fails closed, then project only CLI rows. In particular, never+ // print or match an Extension's PAKE code.+ return parsed.data.filter(+ (request): request is PendingCliRequest => request.kind === 'cli'+ )}throw new OperatorAdminError(diff --git a/src/server/shutdown.test.ts b/src/server/shutdown.test.tsindex bd14378a..45a72e5a 100644--- a/src/server/shutdown.test.ts+++ b/src/server/shutdown.test.ts@@ -394,6 +394,33 @@ describe('server lifecycle production wiring', () => {expect(listeningLog).toBeGreaterThan(0)})+ it('advertises the Extension address only after the remote bridge is ready', () => {+ const source = readFileSync(+ path.resolve(process.cwd(), 'src/server/index.ts'),+ 'utf8'+ )+ const runtimeAccepted = source.indexOf(+ 'bridgeRuntime = candidateBridgeRuntime'+ )+ const commandHandlersPublished = source.indexOf(+ 'Object.assign(bridgeCommandHandlers, bridgeRuntime.bridgeCommandHandlers)',+ runtimeAccepted+ )+ const queryHandlersPublished = source.indexOf(+ 'Object.assign(bridgeQueryHandlers, bridgeRuntime.bridgeQueryHandlers)',+ commandHandlersPublished+ )+ const pairingAddressLog = source.indexOf(+ 'logRemoteExtensionPairingReady(log, remoteExtensionConfig)',+ queryHandlersPublished+ )++ expect(runtimeAccepted).toBeGreaterThan(-1)+ expect(commandHandlersPublished).toBeGreaterThan(runtimeAccepted)+ expect(queryHandlersPublished).toBeGreaterThan(commandHandlersPublished)+ expect(pairingAddressLog).toBeGreaterThan(queryHandlersPublished)+ })+it('wires TrackerManager stopAndDrain into production shutdown', () => {const source = readFileSync(path.resolve(process.cwd(), 'src/server/index.ts'),diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex d7a3f858..f06ef93c 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -1455,6 +1455,7 @@"pairedEmpty": "No extensions connected yet.","lastActive": "Last active","revoke": "Disconnect",+ "disconnecting": "Disconnecting…","addTrusted": {"add": "Add extension","idPlaceholder": "Extension ID",@@ -1496,6 +1497,10 @@"degradedPort": {"title": "Bridge running on a fallback port","description": "Ports 16802–16806 were unavailable, so the bridge bound port {{port}} instead. Browser extensions won't find it by probing the standard range — pair using native messaging, or set a fixed port. The Motrix CLI and native host are unaffected."+ },+ "pairingStateDegraded": {+ "title": "Extension access is temporarily closed",+ "description": "Motrix could not safely update its paired-extension records. Existing Extension sessions are closed and new access is blocked for this run. Restart Motrix to retry the repair; do not rely on the list below until this message clears."}},"cli": {diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex 7beafa91..cce1e2a2 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -1442,6 +1442,7 @@"pairedEmpty": "还没有扩展连接到 Motrix。","lastActive": "上次活跃","revoke": "断开",+ "disconnecting": "正在断开…","addTrusted": {"add": "添加扩展","idPlaceholder": "扩展 ID",@@ -1483,6 +1484,10 @@"degradedPort": {"title": "Bridge 正在使用备用端口运行","description": "端口 16802–16806 均不可用,Bridge 改用端口 {{port}}。浏览器扩展按标准端口范围探测将无法自动发现它——请通过 Native Messaging 配对,或设置固定端口。Motrix CLI 与 Native Host 不受影响。"+ },+ "pairingStateDegraded": {+ "title": "扩展访问已暂时关闭",+ "description": "Motrix 无法安全更新已配对扩展记录。本次运行中的现有扩展会话已关闭,新访问也已阻止。请重启 Motrix 以重试修复;此提示消失前,不要将下方列表视为完整记录。"}},"cli": {diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex 594890d3..c233db49 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -1442,6 +1442,7 @@"pairedEmpty": "尚未連線任何擴充功能。","lastActive": "上次使用","revoke": "中斷連線",+ "disconnecting": "正在中斷連線…","addTrusted": {"add": "新增擴充功能","idPlaceholder": "擴充功能 ID",@@ -1483,6 +1484,10 @@"degradedPort": {"title": "Bridge 正在使用備用連接埠運行","description": "連接埠 16802–16806 皆無法使用,Bridge 改用連接埠 {{port}}。瀏覽器擴充功能依標準連接埠範圍偵測將無法自動找到它——請透過 Native Messaging 配對,或設定固定連接埠。Motrix CLI 與 Native Host 不受影響。"+ },+ "pairingStateDegraded": {+ "title": "擴充功能存取已暫時關閉",+ "description": "Motrix 無法安全更新已配對擴充功能記錄。本次執行中的既有擴充功能工作階段已關閉,新存取也已封鎖。請重新啟動 Motrix 以重試修復;此提示消失前,請勿將下方清單視為完整記錄。"}},"cli": {diff --git a/src/shared/protocol/bridge.ts b/src/shared/protocol/bridge.tsindex 01a90cb5..a62ddea8 100644--- a/src/shared/protocol/bridge.ts+++ b/src/shared/protocol/bridge.ts@@ -67,7 +67,7 @@ export const BridgeEvents = {Paired: 'bridge:paired',Revoked: 'bridge:revoked',Error: 'bridge:error',- /** A pending pair request (cli or extension) reached a final decision. */+ /** A pending request reached a non-TTL terminal outcome. */PairRequestSettled: 'bridge:pairRequestSettled',/** A pending pair request lapsed past its TTL without a decision. */PairRequestExpired: 'bridge:pairRequestExpired',@@ -89,6 +89,8 @@ export type PairedClientInfo =id: stringbrowser: Browsername: string+ identityTrust: IdentityTriState+ status: 'ready' | 'cleanup-pending'pairedAt: numberlastActiveAt: number | null}@@ -124,6 +126,10 @@ export interface BridgeStatusInfo {* `fixedPort`) was taken and the bridge fell back to an ephemeral port —* extension port-probing can no longer find it. */degraded: boolean+ /** Whether the durable Extension credential-to-management projection is+ * healthy. `degraded` means Extension access has been gated for this run and+ * the paired list must not be interpreted as complete. */+ extensionPairingHealth: 'ready' | 'degraded'/** The persisted port policy (`BridgeSettings.fixedPort`) that produced* `port`/`degraded`. */fixedPort: 'auto' | number@@ -224,6 +230,13 @@ export type PendingPairRequestInfo =browser: Browseridentity: IdentityTriStatecode: string+ /** Server operator evidence. Optional because the Desktop shell does+ * not have a public authority and keeps its existing prompt shape. */+ verifiedOrigin?: string+ originHost?: string+ claimedExtensionId?: string+ attestationClass?: IdentityTriState+ publicAuthority?: stringcreatedAt: numberexpiresAt: number}@@ -253,10 +266,11 @@ export function pairRequestKey(}/** Payload for {@link BridgeEvents.PairRequestSettled}: a pending pair- * request (identified by {@link pairRequestKey}) reached a final decision. */+ * request (identified by {@link pairRequestKey}) reached a non-TTL terminal+ * outcome. `aborted` is transport/session teardown, never operator denial. */export interface PairRequestSettledPayload {key: string- outcome: 'allowed' | 'denied'+ outcome: 'allowed' | 'denied' | 'aborted'}/** Payload for {@link BridgeEvents.PairRequestExpired}: a pending pairdiff --git a/tests/scripts/compose-server.test.ts b/tests/scripts/compose-server.test.tsindex 2c5b8a7a..df624483 100644--- a/tests/scripts/compose-server.test.ts+++ b/tests/scripts/compose-server.test.ts@@ -18,6 +18,15 @@ const MDXP_BIND_IP = interpolation(`MOTRIX_MDXP_BIND_IP:-${LEGACY_BIND_IP}`)const HTTP_PORT = interpolation('MOTRIX_HTTP_PORT:-8080')const MDXP_PORT = interpolation('MOTRIX_MDXP_PUBLIC_PORT:-16801')const PUBLIC_URL = interpolation('MOTRIX_PUBLIC_URL:-')+const REMOTE_EXTENSION_ENABLED = interpolation(+ 'MOTRIX_REMOTE_EXTENSION_ENABLED:-false'+)+const REMOTE_EXTENSION_PUBLIC_URL = interpolation(+ 'MOTRIX_REMOTE_EXTENSION_PUBLIC_URL:-'+)+const ALLOW_INSECURE_OPERATOR_HTTP = interpolation(+ 'MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP:-false'+)const ARIA2_RPC_LISTEN_ALL = interpolation('MOTRIX_ARIA2_RPC_LISTEN_ALL:-false')function record(value: unknown, label: string): LooseRecord {@@ -59,6 +68,7 @@ describe('NAS-importable Compose contract', () => {])expect(service.environment).toEqual({MOTRIX_ALLOWED_SAVE_DIRS: '/downloads',+ MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP: ALLOW_INSECURE_OPERATOR_HTTP,MOTRIX_ARIA2_RPC_LISTEN_ALL: ARIA2_RPC_LISTEN_ALL,MOTRIX_DATA_DIR: '/data',MOTRIX_DEFAULT_SAVE_DIR: '/downloads',@@ -66,6 +76,8 @@ describe('NAS-importable Compose contract', () => {MOTRIX_MDXP_PORT: 16801,MOTRIX_PLUGIN_DIR: '/data/plugins',MOTRIX_PUBLIC_URL: PUBLIC_URL,+ MOTRIX_REMOTE_EXTENSION_ENABLED: REMOTE_EXTENSION_ENABLED,+ MOTRIX_REMOTE_EXTENSION_PUBLIC_URL: REMOTE_EXTENSION_PUBLIC_URL,MOTRIX_TEMP_DIR: '/data/tmp',})}diff --git a/tests/scripts/docker-server-docs.test.ts b/tests/scripts/docker-server-docs.test.tsindex d7910a24..1c366e95 100644--- a/tests/scripts/docker-server-docs.test.ts+++ b/tests/scripts/docker-server-docs.test.ts@@ -31,6 +31,9 @@ describe('public Docker Server documentation', () => {'operator-token','motrix-admin pairing approve ABCD-EFGH','MOTRIX_PUBLIC_URL',+ 'MOTRIX_REMOTE_EXTENSION_ENABLED',+ 'MOTRIX_REMOTE_EXTENSION_PUBLIC_URL',+ 'MOTRIX_ALLOW_INSECURE_OPERATOR_HTTP','MOTRIX_WEB_BIND_IP','MOTRIX_MDXP_BIND_IP','MOTRIX_BIND_IP',diff --git a/tests/scripts/run-remote-extension-release-soak.test.ts b/tests/scripts/run-remote-extension-release-soak.test.tsnew file mode 100644index 00000000..e5a4fd2c--- /dev/null+++ b/tests/scripts/run-remote-extension-release-soak.test.ts@@ -0,0 +1,314 @@+import { describe, expect, it, vi } from 'vitest'+// @ts-expect-error -- JavaScript runner intentionally has no declarations+import {+ runRemoteExtensionReleaseSoak,+ validateReleaseBuildLocation,+ validateReleaseManifestLocation,+ validateReleasePlaywrightReport,+ validateReleaseSoakState,+} from '../../scripts/run-remote-extension-release-soak.mjs'++const PIN = '1'.repeat(40)+const MOTRIX_PIN = '2'.repeat(40)+const MOTRIX_HEAD = '3'.repeat(40)+const MANIFEST = 'e2e/bridge/remote-extension-compatibility.json'++function validState() {+ return {+ repeats: 20,+ extensionDirty: false,+ motrixDirty: false,+ extensionHead: PIN,+ extensionPin: PIN,+ motrixChangedFiles: [MANIFEST],+ manifestRelativePath: MANIFEST,+ }+}++function context() {+ return {+ protocol: 'MDXP-over-MBP1',+ compatibilityManifest: MANIFEST,+ pins: { extension: PIN, motrix: MOTRIX_PIN },+ heads: { extension: PIN, motrix: MOTRIX_HEAD },+ }+}++function report(browserCases = 100, resultStatus = 'passed') {+ return {+ errors: [],+ suites: [+ {+ specs: [+ {+ tests: Array.from({ length: browserCases }, () => ({+ expectedStatus: 'passed',+ status: resultStatus === 'passed' ? 'expected' : 'unexpected',+ results: [{ status: resultStatus, errors: [] }],+ })),+ },+ ],+ },+ ],+ }+}++describe('remote Extension release soak', () => {+ it('requires exactly twenty repetitions', () => {+ expect(() =>+ validateReleaseSoakState({ ...validState(), repeats: 19 })+ ).toThrow(/exactly 20/)+ })++ it('rejects either dirty repository', () => {+ expect(() =>+ validateReleaseSoakState({ ...validState(), extensionDirty: true })+ ).toThrow(/clean Extension and Motrix/)+ expect(() =>+ validateReleaseSoakState({ ...validState(), motrixDirty: true })+ ).toThrow(/clean Extension and Motrix/)+ })++ it('requires Extension HEAD to equal its pin', () => {+ expect(() =>+ validateReleaseSoakState({+ ...validState(),+ extensionHead: '4'.repeat(40),+ })+ ).toThrow(/exactly match/)+ })++ it('allows only the compatibility manifest after the Motrix pin', () => {+ expect(() =>+ validateReleaseSoakState({+ ...validState(),+ motrixChangedFiles: [MANIFEST, 'src/server/index.ts'],+ })+ ).toThrow(/only the pinned manifest/)+ expect(() =>+ validateReleaseSoakState({ ...validState(), motrixChangedFiles: [] })+ ).toThrow(/only the pinned manifest/)+ })++ it('requires the canonical compatibility manifest path', () => {+ expect(() =>+ validateReleaseSoakState({+ ...validState(),+ manifestRelativePath: 'e2e/bridge/alternate.json',+ motrixChangedFiles: ['e2e/bridge/alternate.json'],+ })+ ).toThrow(/release manifest must be/)+ })++ it('requires a regular, non-symlink compatibility manifest', () => {+ expect(+ validateReleaseManifestLocation({+ relativePath: MANIFEST,+ isFile: true,+ isSymbolicLink: false,+ })+ ).toBe(MANIFEST)+ expect(() =>+ validateReleaseManifestLocation({+ relativePath: MANIFEST,+ isFile: false,+ isSymbolicLink: true,+ })+ ).toThrow(/regular non-symlink/)+ })++ it('rejects an external or symlinked Extension build directory', () => {+ expect(+ validateReleaseBuildLocation({+ kind: 'chromium',+ actualPath: '/repo/packages/ext/dist/chromium',+ expectedPath: '/repo/packages/ext/dist/chromium',+ isSymbolicLink: false,+ })+ ).toBe('/repo/packages/ext/dist/chromium')+ expect(() =>+ validateReleaseBuildLocation({+ kind: 'chromium',+ actualPath: '/tmp/stale-build',+ expectedPath: '/repo/packages/ext/dist/chromium',+ isSymbolicLink: false,+ })+ ).toThrow(/inside the pinned Extension checkout/)+ expect(() =>+ validateReleaseBuildLocation({+ kind: 'firefox',+ actualPath: '/repo/packages/ext/dist/firefox',+ expectedPath: '/repo/packages/ext/dist/firefox',+ isSymbolicLink: true,+ })+ ).toThrow(/must not be a symbolic link/)+ })++ it('accepts exactly one hundred clean passed browser results', () => {+ expect(validateReleasePlaywrightReport(report())).toEqual({+ testEntries: 100,+ browserCases: 100,+ passed: 100,+ failed: 0,+ })+ })++ it('rejects missing, failed, or top-level-error browser evidence', () => {+ expect(() => validateReleasePlaywrightReport(report(99))).toThrow(+ /exactly 100/+ )+ expect(() =>+ validateReleasePlaywrightReport(report(100, 'failed'))+ ).toThrow(/exactly 100/)+ expect(() =>+ validateReleasePlaywrightReport({ ...report(), errors: [{}] })+ ).toThrow(/top-level errors/)+ })++ it('runs the normal soak with a JSON reporter and writes passing evidence', () => {+ const spawn = vi.fn(() => ({ status: 0 }))+ const writeEvidence = vi.fn(() => '/evidence/evidence.json')+ const first = new Date('2026-08-31T00:00:00.000Z')+ const second = new Date('2026-08-31T00:12:24.000Z')+ const now = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second)++ const result = runRemoteExtensionReleaseSoak({+ env: { MOTRIX_REMOTE_EXTENSION_SOAK_EVIDENCE_DIR: '/evidence' },+ context: context(),+ spawn,+ now,+ writeEvidence,+ reportExists: () => true,+ validateReport: () => ({+ testEntries: 100,+ browserCases: 100,+ passed: 100,+ failed: 0,+ }),+ prepareEvidenceDirectory: () => {},+ })++ expect(spawn).toHaveBeenCalledWith(+ expect.stringMatching(/^pnpm(?:\.cmd)?$/u),+ ['test:e2e:remote-extension:soak'],+ expect.objectContaining({+ stdio: 'inherit',+ env: expect.objectContaining({+ MOTRIX_REMOTE_EXTENSION_SOAK_REPEATS: '20',+ MOTRIX_REMOTE_EXTENSION_EVIDENCE_DIR: '/evidence',+ }),+ })+ )+ expect(result.evidence).toMatchObject({+ status: 'passed',+ repeats: 20,+ browserCases: 100,+ durationMs: 744_000,+ })+ expect(writeEvidence).toHaveBeenCalledOnce()+ })++ it('preflights, rebuilds both artifacts, then recollects their digests', () => {+ const collectContext = vi.fn(() => context())+ const prepareBuild = vi.fn()+ runRemoteExtensionReleaseSoak({+ env: { MOTRIX_REMOTE_EXTENSION_SOAK_EVIDENCE_DIR: '/evidence' },+ collectContext,+ prepareBuild,+ spawn: () => ({ status: 0 }),+ now: () => new Date('2026-08-31T00:00:00.000Z'),+ writeEvidence: () => '/evidence/evidence.json',+ reportExists: () => true,+ validateReport: () => ({+ testEntries: 100,+ browserCases: 100,+ passed: 100,+ failed: 0,+ }),+ prepareEvidenceDirectory: () => {},+ })++ expect(collectContext).toHaveBeenCalledTimes(2)+ expect(collectContext).toHaveBeenNthCalledWith(1, expect.anything(), {+ includeBuilds: false,+ })+ expect(collectContext).toHaveBeenNthCalledWith(2, expect.anything(), {+ includeBuilds: true,+ })+ expect(prepareBuild).toHaveBeenCalledOnce()+ expect(collectContext.mock.invocationCallOrder[0]).toBeLessThan(+ prepareBuild.mock.invocationCallOrder[0] ?? 0+ )+ expect(prepareBuild.mock.invocationCallOrder[0]).toBeLessThan(+ collectContext.mock.invocationCallOrder[1] ?? 0+ )+ })++ it('archives a failed result before rejecting it', () => {+ const writeEvidence = vi.fn(() => '/evidence/evidence.json')+ expect(() =>+ runRemoteExtensionReleaseSoak({+ env: { MOTRIX_REMOTE_EXTENSION_SOAK_EVIDENCE_DIR: '/evidence' },+ context: context(),+ spawn: () => ({ status: 1 }),+ now: () => new Date('2026-08-31T00:00:00.000Z'),+ writeEvidence,+ reportExists: () => true,+ prepareEvidenceDirectory: () => {},+ })+ ).toThrow(/release soak failed/)+ expect(writeEvidence).toHaveBeenCalledWith(+ '/evidence',+ expect.objectContaining({ status: 'failed' })+ )+ })++ it('marks a zero-exit run incomplete when its JSON report is missing', () => {+ const writeEvidence = vi.fn(() => '/evidence/evidence.json')+ expect(() =>+ runRemoteExtensionReleaseSoak({+ env: { MOTRIX_REMOTE_EXTENSION_SOAK_EVIDENCE_DIR: '/evidence' },+ context: context(),+ spawn: () => ({ status: 0 }),+ now: () => new Date('2026-08-31T00:00:00.000Z'),+ writeEvidence,+ reportExists: () => false,+ prepareEvidenceDirectory: () => {},+ })+ ).toThrow(/JSON report missing/)+ expect(writeEvidence).toHaveBeenCalledWith(+ '/evidence',+ expect.objectContaining({+ status: 'incomplete',+ artifacts: expect.objectContaining({ reportPresent: false }),+ })+ )+ })++ it('marks a zero-exit run incomplete when the JSON report is not 100/100', () => {+ const writeEvidence = vi.fn(() => '/evidence/evidence.json')+ expect(() =>+ runRemoteExtensionReleaseSoak({+ env: { MOTRIX_REMOTE_EXTENSION_SOAK_EVIDENCE_DIR: '/evidence' },+ context: context(),+ spawn: () => ({ status: 0 }),+ now: () => new Date('2026-08-31T00:00:00.000Z'),+ writeEvidence,+ reportExists: () => true,+ validateReport: () => {+ throw new Error('expected 100 passed cases; got 99')+ },+ prepareEvidenceDirectory: () => {},+ })+ ).toThrow(/JSON report invalid/)+ expect(writeEvidence).toHaveBeenCalledWith(+ '/evidence',+ expect.objectContaining({+ status: 'incomplete',+ artifacts: expect.objectContaining({+ reportValidationError: expect.stringMatching(/got 99/),+ }),+ })+ )+ })+})diff --git a/tests/scripts/run-remote-extension-soak.test.ts b/tests/scripts/run-remote-extension-soak.test.tsnew file mode 100644index 00000000..1970b476--- /dev/null+++ b/tests/scripts/run-remote-extension-soak.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it, vi } from 'vitest'+// @ts-expect-error -- JavaScript runner intentionally has no declarations+import {+ parseRemoteExtensionSoakRepeats,+ runRemoteExtensionSoak,+} from '../../scripts/run-remote-extension-soak.mjs'++describe('remote Extension soak runner', () => {+ it('defaults to twenty complete five-browser repetitions', () => {+ expect(parseRemoteExtensionSoakRepeats(undefined)).toBe(20)+ expect(parseRemoteExtensionSoakRepeats('')).toBe(20)+ })++ it.each(['0', '-1', '1.5', ' 2', '2 ', '101', '9007199254740992'])(+ 'rejects unsafe repeat count %j',+ (value) => {+ expect(() => parseRemoteExtensionSoakRepeats(value)).toThrow()+ }+ )++ it('runs the regular threat-gated E2E command with Playwright repeat-each', () => {+ const spawn = vi.fn(() => ({ status: 0 }))++ expect(runRemoteExtensionSoak({ repeats: 3, spawn })).toEqual({+ repeats: 3,+ browserCases: 15,+ })+ expect(spawn).toHaveBeenCalledWith(+ expect.stringMatching(/^pnpm(?:\.cmd)?$/u),+ ['test:e2e:remote-extension', '--repeat-each=3'],+ expect.objectContaining({ stdio: 'inherit' })+ )+ })++ it('fails the soak when any repeated browser case fails', () => {+ expect(() =>+ runRemoteExtensionSoak({+ repeats: 2,+ spawn: () => ({ status: 1 }),+ })+ ).toThrow(/soak failed with exit code 1/)+ })+})diff --git a/tests/scripts/verify-remote-extension-compatibility.test.ts b/tests/scripts/verify-remote-extension-compatibility.test.tsnew file mode 100644index 00000000..0591f754--- /dev/null+++ b/tests/scripts/verify-remote-extension-compatibility.test.ts@@ -0,0 +1,143 @@+import { execFileSync } from 'node:child_process'+import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { describe, expect, it } from 'vitest'+// @ts-expect-error -- JavaScript verification script intentionally has no declarations+import {+ validateRemoteExtensionCompatibilityManifest,+ verifyPinnedCommit,+ verifyRemoteExtensionCompatibility,+} from '../../scripts/verify-remote-extension-compatibility.mjs'++function validManifest(+ extensionCommit = 'a'.repeat(40),+ motrixCommit = 'b'.repeat(40)+) {+ return {+ schemaVersion: 1,+ protocol: 'MDXP-over-MBP1',+ extension: {+ repository: 'motrix-extension',+ commit: extensionCommit,+ },+ motrix: {+ repository: 'motrix-app',+ commit: motrixCommit,+ },+ e2e: {+ browserCases: 5,+ command: 'pnpm test:e2e:remote-extension',+ },+ }+}++function createRepository(root: string, name: string) {+ const repository = join(root, name)+ execFileSync('git', ['init', repository], { stdio: 'ignore' })+ writeFileSync(join(repository, 'evidence.txt'), `${name}\n`)+ execFileSync('git', ['-C', repository, 'add', 'evidence.txt'])+ execFileSync(+ 'git',+ [+ '-C',+ repository,+ '-c',+ 'user.name=Compatibility Test',+ '-c',+ '[email protected]',+ 'commit',+ '-m',+ 'test: implementation evidence',+ ],+ { stdio: 'ignore' }+ )+ return {+ repository,+ commit: execFileSync('git', ['-C', repository, 'rev-parse', 'HEAD'], {+ encoding: 'utf8',+ }).trim(),+ }+}++describe('remote Extension compatibility manifest', () => {+ it('accepts only the exact v1 compatibility contract', () => {+ expect(+ validateRemoteExtensionCompatibilityManifest(validManifest())+ ).toEqual(validManifest())+ })++ it.each([+ 'abc123',+ 'A'.repeat(40),+ '0'.repeat(40),+ 'f'.repeat(40),+ 'REPLACE_WITH_EXTENSION_IMPLEMENTATION_COMMIT',+ ])('rejects unsafe commit value %j', (commit) => {+ expect(() =>+ validateRemoteExtensionCompatibilityManifest(validManifest(commit))+ ).toThrow(/full lowercase SHA/)+ })++ it('rejects protocol drift, insufficient browser cases, and unknown fields', () => {+ expect(() =>+ validateRemoteExtensionCompatibilityManifest({+ ...validManifest(),+ protocol: 'legacy-token',+ })+ ).toThrow(/MDXP-over-MBP1/)+ expect(() =>+ validateRemoteExtensionCompatibilityManifest({+ ...validManifest(),+ e2e: {+ browserCases: 4,+ command: 'pnpm test:e2e:remote-extension',+ },+ })+ ).toThrow(/integer >= 5/)+ expect(() =>+ validateRemoteExtensionCompatibilityManifest({+ ...validManifest(),+ fallback: 'token',+ })+ ).toThrow(/exactly/)+ })++ it('requires each pin to resolve as a commit in the matching repository', () => {+ const root = mkdtempSync(join(tmpdir(), 'motrix-compatibility-'))+ const extension = createRepository(root, 'extension')+ const motrix = createRepository(root, 'motrix')+ const manifestPath = join(root, 'compatibility.json')+ writeFileSync(+ manifestPath,+ `${JSON.stringify(validManifest(extension.commit, motrix.commit), null, 2)}\n`+ )++ expect(+ verifyRemoteExtensionCompatibility({+ manifestPath,+ extensionRepository: extension.repository,+ motrixRepository: motrix.repository,+ })+ ).toEqual(validManifest(extension.commit, motrix.commit))++ expect(() =>+ verifyPinnedCommit(extension.repository, motrix.commit, 'Extension')+ ).toThrow(/does not resolve/)+ })++ it('keeps the checked-in example intentionally unpinned', () => {+ const example = JSON.parse(+ readFileSync(+ join(+ process.cwd(),+ 'e2e/bridge/remote-extension-compatibility.example.json'+ ),+ 'utf8'+ )+ )+ expect(() => validateRemoteExtensionCompatibilityManifest(example)).toThrow(+ /full lowercase SHA/+ )+ })+})diff --git a/tests/scripts/verify-remote-extension-threat-evidence.test.ts b/tests/scripts/verify-remote-extension-threat-evidence.test.tsnew file mode 100644index 00000000..bc25d182--- /dev/null+++ b/tests/scripts/verify-remote-extension-threat-evidence.test.ts@@ -0,0 +1,85 @@+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { describe, expect, it } from 'vitest'+// @ts-expect-error -- JavaScript verification script intentionally has no declarations+import {+ validateThreatEvidenceManifest,+ verifyThreatEvidence,+} from '../../scripts/verify-remote-extension-threat-evidence.mjs'++function completeManifest(+ path = 'tests/security.test.ts',+ testName = 'blocks attack'+) {+ return {+ schemaVersion: 1,+ threats: Array.from({ length: 29 }, (_, index) => ({+ id: `T${String(index + 1).padStart(2, '0')}`,+ evidence: [{ repository: 'motrix', path, testName }],+ })),+ }+}++describe('remote Extension threat evidence', () => {+ it('requires an exact, complete T01-T29 mapping', () => {+ expect(+ validateThreatEvidenceManifest(completeManifest()).threats+ ).toHaveLength(29)+ expect(() =>+ validateThreatEvidenceManifest({+ ...completeManifest(),+ threats: completeManifest().threats.slice(0, 28),+ })+ ).toThrow(/missing: T29/)+ expect(() =>+ validateThreatEvidenceManifest({+ ...completeManifest(),+ threats: [+ ...completeManifest().threats.slice(0, 28),+ completeManifest().threats[0],+ ],+ })+ ).toThrow(/unique T01-T29/)+ })++ it.each([+ '../security.test.ts',+ '/tmp/security.test.ts',+ 'tests/security.ts',+ 'tests\\security.test.ts',+ ])('rejects unsafe evidence path %j', (path) => {+ expect(() =>+ validateThreatEvidenceManifest(completeManifest(path))+ ).toThrow(/relative test file/)+ })++ it('verifies that every mapped file and title still exists', () => {+ const root = mkdtempSync(join(tmpdir(), 'motrix-threat-evidence-'))+ const motrixRepository = join(root, 'motrix')+ const extensionRepository = join(root, 'extension')+ const evidencePath = join(motrixRepository, 'tests/security.test.ts')+ const manifestPath = join(root, 'manifest.json')+ mkdirSync(dirname(evidencePath), { recursive: true })+ mkdirSync(extensionRepository, { recursive: true })+ writeFileSync(evidencePath, "it('blocks attack', () => {})\n")+ writeFileSync(manifestPath, JSON.stringify(completeManifest()))++ expect(+ verifyThreatEvidence({+ manifestPath,+ motrixRepository,+ extensionRepository,+ })+ ).toEqual({ threatCount: 29, evidenceCount: 29 })++ writeFileSync(evidencePath, "it('renamed test', () => {})\n")+ expect(() =>+ verifyThreatEvidence({+ manifestPath,+ motrixRepository,+ extensionRepository,+ })+ ).toThrow(/evidence title is missing/)+ })+})