dsh-codex-style-computer-use 2.3.5 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,99 @@
1
+ // lib/browser/extension/popup.js — the popup shown from the toolbar icon.
2
+ //
3
+ // Its only real jobs: show the pairing code the human compares, and let them
4
+ // change the port or turn the connection off. There is no annotate button and no
5
+ // app management here, because this plugin has neither.
6
+
7
+ const enabled = document.querySelector('#enabled')
8
+ const status = document.querySelector('#status')
9
+ const pairing = document.querySelector('#pairing')
10
+ const code = document.querySelector('#code')
11
+ const port = document.querySelector('#port')
12
+ const savePort = document.querySelector('#save-port')
13
+ const unpair = document.querySelector('#unpair')
14
+ let connected = false
15
+ let refreshPending = false
16
+ let statusError = false
17
+
18
+ document.querySelector('#setup').addEventListener('click', async () => {
19
+ try {
20
+ const state = await chrome.runtime.sendMessage({ type: 'status' })
21
+ const selected = state.port ?? 43188
22
+ if (!Number.isSafeInteger(selected) || selected < 1 || selected > 65535) throw new Error('连接端口无效')
23
+ await chrome.tabs.create({ url: `http://127.0.0.1:${selected}/setup` })
24
+ } catch (error) { showError(error) }
25
+ })
26
+
27
+ // A rejected probe must not abort module evaluation: everything below is listener
28
+ // registration, and a top-level throw would leave every control inert.
29
+ chrome.extension.isAllowedFileSchemeAccess().catch(() => false).then(allowed => {
30
+ document.querySelector('#file-access').textContent = allowed
31
+ ? '已允许引用本地 HTML 页面'
32
+ : '引用本地 HTML:请在扩展详情中开启「允许访问文件网址」。'
33
+ })
34
+
35
+ function showError (error) {
36
+ statusError = true
37
+ status.dataset.state = 'error'
38
+ status.textContent = error.message
39
+ }
40
+
41
+ async function refresh () {
42
+ if (refreshPending) return
43
+ refreshPending = true
44
+ try {
45
+ const state = await chrome.runtime.sendMessage({ type: 'status' })
46
+ if (state.error) throw new Error(state.error)
47
+ connected = state.connected
48
+ const compatibility = document.querySelector('#compatibility')
49
+ compatibility.hidden = !state.compatibilityWarning
50
+ compatibility.textContent = state.compatibilityWarning || ''
51
+ document.querySelector('#version').textContent = '扩展 ' + chrome.runtime.getManifest().version +
52
+ ' · 主机 ' + (state.connected ? state.hostVersion || '等待版本信息' : '未连接')
53
+ const waiting = state.pairing !== undefined && !state.stopped
54
+ // Do not fight the user's own toggle while its request is in flight.
55
+ if (!enabled.disabled) enabled.checked = !state.stopped
56
+ if (document.activeElement !== port) port.value = String(state.port ?? 43188)
57
+ unpair.hidden = !state.paired
58
+ pairing.hidden = !waiting
59
+ code.textContent = state.pairing?.code ?? ''
60
+ // An error the user just triggered stays visible until the next action; the
61
+ // 2 s poll would otherwise erase it before it could be read.
62
+ if (statusError) return
63
+ status.dataset.state = state.connected ? 'connected' : waiting ? 'waiting' : 'offline'
64
+ status.textContent = waiting ? '等待 DSH 确认验证码'
65
+ : state.connected ? `已连接 · ${state.availableTabs} 个标签页 · ${state.controlledTabs} 个受控`
66
+ : state.stopped ? '已暂停' : state.paired ? '等待 DSH' : '未配对'
67
+ } finally { refreshPending = false }
68
+ }
69
+
70
+ async function send (message) {
71
+ statusError = false
72
+ const result = await chrome.runtime.sendMessage(message)
73
+ if (result.error) throw new Error(result.error)
74
+ await refresh()
75
+ }
76
+
77
+ enabled.addEventListener('change', async () => {
78
+ enabled.disabled = true
79
+ try { await send({ type: 'toggle', stopped: !enabled.checked }) } catch (error) { showError(error) } finally { enabled.disabled = false }
80
+ })
81
+
82
+ savePort.addEventListener('click', async () => {
83
+ if (!port.reportValidity()) return
84
+ try { await send({ type: 'port', port: Number(port.value) }) } catch (error) { showError(error) }
85
+ })
86
+
87
+ unpair.addEventListener('click', async () => {
88
+ try { await send({ type: 'unpair' }) } catch (error) { showError(error) }
89
+ })
90
+
91
+ await refresh().catch(showError)
92
+ // Each tick wakes the MV3 worker, so poll only while the popup is visible and
93
+ // stop as soon as it is hidden.
94
+ let timer
95
+ const startPolling = () => { clearInterval(timer); timer = setInterval(() => void refresh().catch(showError), 2000) }
96
+ const stopPolling = () => clearInterval(timer)
97
+ document.addEventListener('visibilitychange', () => document.hidden ? stopPolling() : startPolling())
98
+ window.addEventListener('pagehide', stopPolling, { once: true })
99
+ if (!document.hidden) startPolling()
@@ -0,0 +1,132 @@
1
+ // lib/browser/host-protocol.js — the host-side admission gate and output helpers.
2
+ //
3
+ // `lib/browser/protocol.js` (transport partition) owns the URL contract: `sessionWebUrl` already
4
+ // refuses every non-web scheme, credentials, the browser stores, the loopback ports it is given,
5
+ // and any `file:` page that is not a local `.html`/`.htm` document (`file://server/share` is a UNC
6
+ // path and `isLocalHtml` says no). This module does NOT re-implement those rules — it CALLS them
7
+ // with the real option-object signature and adds only what the host layer knows:
8
+ //
9
+ // * which local ports serve DSH/plugin surfaces in THIS process (`guardedPorts`), i.e. the
10
+ // harness web UI and the bridge's own pairing page;
11
+ // * the per-tab/per-conversation `allowFile` opt-in, which is an AUTHORIZATION decision made here
12
+ // (human setting × the human's own @ citation), not a URL-syntax question;
13
+ // * the bounded-output helpers (`clip`/`serialize`/`jsonValue`) and origin readers the read/write
14
+ // engine needs.
15
+ //
16
+ // Keeping one implementation of the URL rule is the point: a drift between "may this tab be
17
+ // listed" and "may this tab be driven" is exactly how a forbidden page becomes reachable.
18
+
19
+ import { effectivePort, isLoopbackHost, sessionWebUrl, urlRefusal as protocolRefusal } from './protocol.js'
20
+
21
+ export { isLoopbackHost, effectivePort }
22
+
23
+ /**
24
+ * A `file:` URL whose PATH is a network share.
25
+ *
26
+ * `file://server/share/x.html` is the obvious UNC spelling and transport's `isLocalHtml` already
27
+ * refuses it (non-empty hostname). The one that slips through is the MULTI-slash form:
28
+ * `file:////server/share/x.html` parses with an EMPTY hostname and a pathname of
29
+ * `//server/share/x.html` — the same network share, spelled as a path. Every slash above three
30
+ * collapses into the pathname (`file://///server/…` ⇒ `////server/…`), so the test is "the decoded
31
+ * path starts with TWO OR MORE separators", not "exactly two". A genuine local page
32
+ * (`file:///C:/x.html`) has exactly one leading slash and never matches.
33
+ *
34
+ * Decoding happens FIRST: a Windows path with spaces or non-ASCII arrives percent-encoded, and a
35
+ * share can be smuggled as `%5C%5Cserver` or `%2F%2Fserver`. An undecodable path is refused.
36
+ */
37
+ export function isNetworkSharePath (url) {
38
+ if (String(url?.protocol) !== 'file:') return false
39
+ let pathname = String(url?.pathname ?? '')
40
+ try { pathname = decodeURIComponent(pathname) } catch { return true } // undecodable: refuse
41
+ if (pathname.includes('\0')) return true
42
+ const slashed = pathname.replace(/\\/g, '/')
43
+ // Two or more leading separators is a UNC prefix in every spelling Windows accepts.
44
+ return /^\/{2,}/.test(slashed)
45
+ }
46
+
47
+ /**
48
+ * May this page be READ or DRIVEN in this conversation?
49
+ *
50
+ * @param {string} value absolute URL
51
+ * @param {{bridgePort?: number, allowFile?: boolean, guardedPorts?: Iterable<number>}} options
52
+ * `bridgePort` — the bridge's own port (its setup/pairing page is never a target);
53
+ * `allowFile` — the human has enabled local HTML AND the human cited this very tab with @;
54
+ * `guardedPorts` — local ports serving DSH or plugin surfaces (the harness UI, the settings route).
55
+ * @returns {URL|null} the normalised URL, or null when the page is never a target
56
+ */
57
+ export function admitUrl (value, { bridgePort, allowFile = false, guardedPorts = [] } = {}) {
58
+ const ports = [...guardedPorts].map(Number).filter(port => Number.isSafeInteger(port) && port > 0)
59
+ const url = sessionWebUrl(value, {
60
+ ports: Number.isSafeInteger(Number(bridgePort)) ? [...ports, Number(bridgePort)] : ports,
61
+ // Transport's `file` is the per-URL opt-in and already implies "an .html/.htm document on this
62
+ // machine"; UNC shares, directories, executables and scripts are refused there.
63
+ file: allowFile === true,
64
+ allowFile: allowFile === true,
65
+ })
66
+ if (!url) return null
67
+ // The four-slash share spelling survives `isLocalHtml` (its hostname is empty), so the host layer
68
+ // refuses it explicitly: a network share is not a local page the human opened.
69
+ if (url.protocol === 'file:' && isNetworkSharePath(url)) return null
70
+ return url
71
+ }
72
+
73
+ /** Is this a local HTML document on THIS machine? (not a share, not a script, not a directory) */
74
+ export function isLocalHtmlPath (value) {
75
+ const url = value instanceof URL ? value : (() => { try { return new URL(String(value ?? '')) } catch { return null } })()
76
+ if (!url || url.protocol !== 'file:') return false
77
+ if (isNetworkSharePath(url)) return false
78
+ return sessionWebUrl(url.href, { file: true, allowFile: true }) !== null
79
+ }
80
+
81
+ /** Why a page was refused, in words a model can act on rather than a bare "denied". */
82
+ export function urlRefusal (value, { allowFile = false, bridgePort, guardedPorts = [] } = {}) {
83
+ const ports = [...guardedPorts].map(Number).filter(Number.isSafeInteger)
84
+ if (Number.isSafeInteger(Number(bridgePort))) ports.push(Number(bridgePort))
85
+ // A four-slash UNC path would otherwise be told "enable local HTML", which it never can be.
86
+ let url = null
87
+ try { url = new URL(String(value ?? '')) } catch { /* protocolRefusal explains it */ }
88
+ if (url && url.protocol === 'file:' && isNetworkSharePath(url)) {
89
+ return 'A network share (\\\\server\\share or file:////server/share) is never a browser target; only a local .html/.htm page on this machine can be used'
90
+ }
91
+ return protocolRefusal(value, { ports, file: allowFile === true, allowFile: allowFile === true })
92
+ }
93
+
94
+ /** Origin, or '' for a URL that has none (`file:` pages are origin-opaque). */
95
+ export function originOf (value) {
96
+ try {
97
+ const url = new URL(String(value))
98
+ return url.origin === 'null' ? '' : url.origin
99
+ } catch { return '' }
100
+ }
101
+
102
+ export function hostOf (value) {
103
+ try { return new URL(String(value)).hostname } catch { return '' }
104
+ }
105
+
106
+ export function serialize (value) {
107
+ return JSON.stringify(value).replace(/</g, '\\u003c')
108
+ }
109
+
110
+ /** DSH accepts JSON values, not objects containing undefined, BigInt or cycles. */
111
+ export function jsonValue (value, ancestors = new Set()) {
112
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return value
113
+ if (typeof value === 'number') return Number.isFinite(value) ? value : null
114
+ if (typeof value === 'bigint') return value.toString()
115
+ if (typeof value !== 'object') return null
116
+ if (ancestors.has(value)) return null
117
+ ancestors.add(value)
118
+ const result = Array.isArray(value)
119
+ ? value.map(item => jsonValue(item, ancestors))
120
+ : Object.fromEntries(Object.entries(value)
121
+ .filter(([, item]) => item !== undefined && typeof item !== 'function' && typeof item !== 'symbol')
122
+ .map(([key, item]) => [key, jsonValue(item, ancestors)]))
123
+ ancestors.delete(value)
124
+ return result
125
+ }
126
+
127
+ export function clip (value, limit) {
128
+ const text = String(value ?? '')
129
+ if (text.length <= limit) return text
130
+ if (limit < 3) return '.'.repeat(Math.max(0, limit))
131
+ return `${text.slice(0, limit - 3)}...`
132
+ }