dsh-chrome-bridge 1.19.0 → 2.0.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.
- package/README.en.md +6 -2
- package/README.md +6 -2
- package/client.js +110 -29
- package/core/ext.js +119 -0
- package/core/hosts.js +277 -0
- package/core/locale.js +8 -0
- package/core/receipt.js +56 -0
- package/core/session.js +157 -0
- package/core/shots.js +56 -0
- package/core/tooldef.js +142 -0
- package/core/transport.js +212 -0
- package/core/upload.js +59 -0
- package/devtools.js +37 -16
- package/download.js +895 -69
- package/drag.js +68 -30
- package/features/frames.js +58 -0
- package/features/gif.js +203 -0
- package/features/index.js +1 -0
- package/features/mock-har.js +85 -0
- package/features/record.js +225 -0
- package/i18n/en.js +312 -16
- package/i18n/index.js +17 -0
- package/i18n/ru.js +312 -16
- package/i18n/zh.js +310 -14
- package/image-guard.js +13 -6
- package/index.js +21 -1073
- package/locale/ru.json +7 -0
- package/nav.js +56 -10
- package/package.json +8 -1
- package/panel.js +14 -4
- package/refs.js +293 -240
- package/setup.js +248 -74
- package/tools/click.js +58 -0
- package/tools/devtools.js +61 -0
- package/tools/dialog.js +22 -0
- package/tools/download.js +50 -0
- package/tools/drag.js +61 -0
- package/tools/eval.js +22 -0
- package/tools/fill.js +77 -0
- package/tools/handoff.js +40 -0
- package/tools/index.js +38 -0
- package/tools/input.js +147 -0
- package/tools/nav.js +57 -0
- package/tools/read.js +87 -0
- package/tools/record.js +120 -0
- package/tools/screenshot.js +223 -0
- package/tools/tabs.js +131 -0
- package/tools/wait.js +56 -0
- package/vendor/cb +616 -35
- package/vendor/extension/_locales/en/messages.json +3 -0
- package/vendor/extension/_locales/ru/messages.json +3 -0
- package/vendor/extension/_locales/zh_CN/messages.json +3 -0
- package/vendor/extension/_locales/zh_TW/messages.json +3 -0
- package/vendor/extension/background.js +2 -1969
- package/vendor/extension/confirm.css +148 -0
- package/vendor/extension/confirm.html +49 -0
- package/vendor/extension/confirm.js +188 -0
- package/vendor/extension/in-page-cursor.js +599 -0
- package/vendor/extension/manifest.json +11 -2
- package/vendor/extension/popup.css +99 -5
- package/vendor/extension/popup.html +28 -2
- package/vendor/extension/popup.js +430 -45
- package/vendor/extension/sw/boot.js +111 -0
- package/vendor/extension/sw/cdp.js +411 -0
- package/vendor/extension/sw/chooser.js +192 -0
- package/vendor/extension/sw/confirm.js +608 -0
- package/vendor/extension/sw/cursor.js +241 -0
- package/vendor/extension/sw/dispatch.js +129 -0
- package/vendor/extension/sw/download.js +279 -0
- package/vendor/extension/sw/fetch-hub.js +224 -0
- package/vendor/extension/sw/frames.js +651 -0
- package/vendor/extension/sw/imaging.js +361 -0
- package/vendor/extension/sw/native.js +111 -0
- package/vendor/extension/sw/net-tools.js +525 -0
- package/vendor/extension/sw/ops.js +829 -0
- package/vendor/extension/sw/popup-api.js +303 -0
- package/vendor/extension/sw/profile.js +166 -0
- package/vendor/extension/sw/record.js +494 -0
- package/vendor/extension/sw/state.js +161 -0
- package/vendor/extension/sw/tabui.js +219 -0
- package/vendor/extension/sw/util.js +166 -0
- package/vendor/extension/sw/welcome.js +26 -0
- package/vendor/extension/sw/windows.js +94 -0
- package/vendor/extension/welcome.css +189 -0
- package/vendor/extension/welcome.html +70 -0
- package/vendor/extension/welcome.js +157 -0
- package/vendor/host/host.js +476 -71
- package/vendor/in-page-cursor.js +309 -37
- package/vendor/skill/SKILL.md +34 -16
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import {
|
|
2
|
+
addProtectedSite, getPendingConfirm, getProtectedSites, matchesProtectedSite, normalizeSitePattern,
|
|
3
|
+
removeProtectedSite, resolveConfirmation, revokeAllGrants, revokeTabGrants,
|
|
4
|
+
} from './confirm.js'
|
|
5
|
+
import { hidePageCursor, markCursor } from './cursor.js'
|
|
6
|
+
import { connect, post } from './native.js'
|
|
7
|
+
import { getOps } from './ops.js'
|
|
8
|
+
import { ACTIVITY_MAX, DETACH_IDLE_MS, S } from './state.js'
|
|
9
|
+
import { CURSOR_FAVICON } from './tabui.js'
|
|
10
|
+
import { controlledCount, isExtUrl, log, updateBadge } from './util.js'
|
|
11
|
+
|
|
12
|
+
function restorePrefs() {
|
|
13
|
+
S.prefsReady = chrome.storage.local.get(['paused', 'pauseReason', 'showCursor', 'ownWindow']).then((v) => {
|
|
14
|
+
S.paused = !!(v && v.paused)
|
|
15
|
+
S.pauseReason = S.paused ? v.pauseReason || null : null
|
|
16
|
+
S.showCursor = !(v && v.showCursor === false)
|
|
17
|
+
S.ownWindow = !(v && v.ownWindow === false)
|
|
18
|
+
updateBadge()
|
|
19
|
+
}).catch(() => {})
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// ── 弹窗(popup.html)的接口 ─────────────────────────────────────────────────
|
|
23
|
+
|
|
24
|
+
/** 用户眼前那个普通窗口里的当前标签页(只要 http/https 的):弹窗里「保护当前网站」用 */
|
|
25
|
+
async function activeTab() {
|
|
26
|
+
try {
|
|
27
|
+
let windowId
|
|
28
|
+
try { windowId = (await chrome.windows.getLastFocused({ windowTypes: ['normal'] })).id } catch {}
|
|
29
|
+
const [t] = await chrome.tabs.query(windowId != null ? { active: true, windowId } : { active: true, lastFocusedWindow: true })
|
|
30
|
+
const url = t && (t.url || t.pendingUrl)
|
|
31
|
+
return url && /^https?:/i.test(url) && !isExtUrl(url) ? { id: t.id, url } : null
|
|
32
|
+
} catch {
|
|
33
|
+
return null
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 这个 Chrome(用户资料)报给宿主的身份:多个 Chrome 同时连着时 DSH 靠它分辨 */
|
|
38
|
+
function profileOf() {
|
|
39
|
+
const m = S.helloMetadata || {}
|
|
40
|
+
return { instanceId: m.instanceId || '', label: m.label || '', browser: m.browser || '' }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 名字:去掉控制字符、合并空白,最多 24 个字 */
|
|
44
|
+
function cleanLabel(v) {
|
|
45
|
+
const s = String(v ?? '').replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2066-\u2069]/g, '').replace(/\s+/g, ' ').trim()
|
|
46
|
+
return [...s].slice(0, 24).join('')
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function setProfileLabel(label) {
|
|
50
|
+
const clean = cleanLabel(label)
|
|
51
|
+
// 冷启动时 profile.js 还在读存储:等它读完再写,免得它读出来的旧名字后到、把刚改的名字盖回去
|
|
52
|
+
try { await S.profileReady } catch {}
|
|
53
|
+
await chrome.storage.local.set({ profileLabel: clean })
|
|
54
|
+
S.helloMetadata = { ...(S.helloMetadata || {}), label: clean }
|
|
55
|
+
if (S.port) post({ ...S.helloMetadata, hostMeta: true })
|
|
56
|
+
log(clean ? `这个 Chrome 改名为「${clean}」` : '清掉了这个 Chrome 的名字')
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 真正的工具栏弹窗:不在任何标签页里,页面是 popup.html(弹窗页被当成普通标签页打开时有 sender.tab) */
|
|
60
|
+
function fromToolbarPopup(sender) {
|
|
61
|
+
return !sender.tab && typeof sender.url === 'string' && sender.url.startsWith(chrome.runtime.getURL('popup.html'))
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 确认小窗:页面是 confirm.html,网址里的 id 就是它要问的那一个 */
|
|
65
|
+
function fromConfirmPage(sender, id) {
|
|
66
|
+
const base = chrome.runtime.getURL('confirm.html')
|
|
67
|
+
if (sender.id !== chrome.runtime.id || typeof sender.url !== 'string' || !sender.url.startsWith(base)) return false
|
|
68
|
+
// 按字符串拆(chrome-extension: 在有的环境里解析不出 origin):路径必须正好是 confirm.html,查询串里的 id 对得上
|
|
69
|
+
const url = sender.url.replace(/#.*$/, '')
|
|
70
|
+
const q = url.indexOf('?')
|
|
71
|
+
if ((q < 0 ? url : url.slice(0, q)) !== base) return false
|
|
72
|
+
return new URLSearchParams(q < 0 ? '' : url.slice(q + 1)).get('id') === String(id)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function buildState() {
|
|
76
|
+
if (S.port && (!S.hostInfo || Date.now() - S.hostInfo.at > 5000)) post({ hostPing: true })
|
|
77
|
+
const now = Date.now()
|
|
78
|
+
const tabInfo = new Map()
|
|
79
|
+
for (const t of await chrome.tabs.query({})) tabInfo.set(t.id, t)
|
|
80
|
+
let shortcut = 'Alt+Shift+X'
|
|
81
|
+
try { shortcut = (await chrome.commands.getAll()).find(c => c.name === 'emergency-stop')?.shortcut ?? shortcut } catch {}
|
|
82
|
+
const tabView = (id) => {
|
|
83
|
+
const t = tabInfo.get(id)
|
|
84
|
+
if (!t || isExtUrl(t.url) || isExtUrl(t.pendingUrl)) return null // 弹窗页自己不算
|
|
85
|
+
return {
|
|
86
|
+
// 我们给受控标签页换上的小鼠标图标不是网站自己的,别拿来当它的图标
|
|
87
|
+
id, title: t.title || '', url: t.url || '', favIconUrl: t.favIconUrl === CURSOR_FAVICON ? '' : t.favIconUrl || '',
|
|
88
|
+
attached: S.attached.has(id), busy: S.inflight.has(id), lastUsed: S.lastUsed.get(id) || 0,
|
|
89
|
+
dialog: S.dialogs.get(id) || null,
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const owned = new Set()
|
|
93
|
+
const sessions = []
|
|
94
|
+
for (const [k, s] of [...S.SESSIONS].sort((a, b) => b[1].last - a[1].last)) {
|
|
95
|
+
for (const id of s.tabs) if (!tabInfo.has(id)) s.tabs.delete(id)
|
|
96
|
+
const tabs = [...s.tabs].map(tabView).filter(Boolean)
|
|
97
|
+
.sort((a, b) => (b.attached - a.attached) || (b.lastUsed - a.lastUsed))
|
|
98
|
+
// 两小时没动静、手上也没有标签页的会话就不显示了
|
|
99
|
+
if (!tabs.some((t) => t.attached) && now - s.last > 2 * 3600e3) { S.SESSIONS.delete(k); continue }
|
|
100
|
+
tabs.forEach((t) => owned.add(t.id))
|
|
101
|
+
sessions.push({ key: s.key, kind: s.kind, session: s.session, pid: s.pid,
|
|
102
|
+
first: s.first, last: s.last, ops: s.ops, errors: s.errors, tabs })
|
|
103
|
+
}
|
|
104
|
+
const orphans = [...S.attached].filter((id) => !owned.has(id)).map(tabView).filter(Boolean)
|
|
105
|
+
const protectedSites = await getProtectedSites()
|
|
106
|
+
const active = await activeTab()
|
|
107
|
+
let activeTabHost = ''
|
|
108
|
+
try { activeTabHost = active ? normalizeSitePattern(active.url) : '' } catch {}
|
|
109
|
+
return {
|
|
110
|
+
now,
|
|
111
|
+
version: chrome.runtime.getManifest().version,
|
|
112
|
+
connected: !!S.port,
|
|
113
|
+
paused: S.paused,
|
|
114
|
+
disconnectReason: S.disconnectReason, disconnectError: S.disconnectError, pauseReason: S.pauseReason, shortcut,
|
|
115
|
+
handoff: S.activeHandoff ? { id: S.activeHandoff.id, tabId: S.activeHandoff.tabId, at: S.activeHandoff.at,
|
|
116
|
+
reason: S.activeHandoff.reason, title: tabInfo.get(S.activeHandoff.tabId)?.title || '',
|
|
117
|
+
url: tabInfo.get(S.activeHandoff.tabId)?.url || '' } : null,
|
|
118
|
+
host: S.hostInfo,
|
|
119
|
+
idleMs: DETACH_IDLE_MS,
|
|
120
|
+
attachedCount: controlledCount(),
|
|
121
|
+
showCursor: S.showCursor,
|
|
122
|
+
ownWindow: S.ownWindow,
|
|
123
|
+
protectedSites,
|
|
124
|
+
activeTabHost,
|
|
125
|
+
activeTabProtected: !!(active && matchesProtectedSite(active.url)),
|
|
126
|
+
profile: profileOf(),
|
|
127
|
+
sessions,
|
|
128
|
+
orphans,
|
|
129
|
+
activity: S.ACTIVITY.slice(-30).reverse().map((a) => ({
|
|
130
|
+
...a, title: a.tabId != null && tabInfo.has(a.tabId) ? tabInfo.get(a.tabId).title : '',
|
|
131
|
+
})),
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function releaseTab(tabId) {
|
|
136
|
+
revokeTabGrants(tabId) // 用户放开 = 解绑:受保护网站的放行跟着作废
|
|
137
|
+
await getOps().detach({ tabId })
|
|
138
|
+
S.ACTIVITY.push({ at: Date.now(), last: Date.now(), key: 'user', call: null, tool: null, hint: '',
|
|
139
|
+
op: 'userRelease', tabId: Number(tabId), ok: true, ms: 0, ops: 1 })
|
|
140
|
+
if (S.ACTIVITY.length > ACTIVITY_MAX) S.ACTIVITY.shift()
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function diagnostics(state) {
|
|
144
|
+
const st = state || await buildState()
|
|
145
|
+
const h = st.host
|
|
146
|
+
const lines = [
|
|
147
|
+
`DSH Bridge ${st.version}(${chrome.runtime.id})`,
|
|
148
|
+
`浏览器:${navigator.userAgent}`,
|
|
149
|
+
`宿主:${st.connected ? '已连接' : '没连上'}${h ? `,pid ${h.pid},socket ${h.socketOk ? '在听' : '没在听'}(${h.socket}),已处理 ${h.served} 次请求` : ''}`,
|
|
150
|
+
`暂停:${st.paused ? '是' : '否'};页内光标:${st.showCursor ? '显示' : '关闭'};新页开在:${st.ownWindow ? '单独窗口' : '当前窗口'};受控标签页:${st.attachedCount};受保护网站:${(st.protectedSites || []).length} 个`,
|
|
151
|
+
`会话:${st.sessions.map((s) => `${s.key}(${s.ops} 次操作,${s.errors} 次失败,${s.tabs.length} 个标签页)`).join(';') || '无'}`,
|
|
152
|
+
'',
|
|
153
|
+
'最近失败:',
|
|
154
|
+
...S.ACTIVITY.filter((a) => !a.ok).slice(-10).map((a) =>
|
|
155
|
+
` ${new Date(a.at).toTimeString().slice(0, 8)} ${a.tool || a.op} ${a.hint || ''} → ${a.error}`),
|
|
156
|
+
'',
|
|
157
|
+
'扩展日志(最近 30 行):',
|
|
158
|
+
...S.LOG.slice(-30).map((l) => ` ${l}`),
|
|
159
|
+
]
|
|
160
|
+
return lines.join('\n')
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// ── 用户开关(弹窗和 DSH 设置页共用)────────────────────────────────────────
|
|
164
|
+
|
|
165
|
+
async function releaseAllTabs() {
|
|
166
|
+
revokeAllGrants('detached') // 全部放开 = 全部解绑:受保护网站的放行和正在等的确认一起作废
|
|
167
|
+
await Promise.all([...new Set([...S.attached, ...S.ensureInflight.keys()])].map(releaseTab))
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** where:谁按的(写进日志)。暂停时顺手全部松手。 */
|
|
171
|
+
async function setPaused(on, where) {
|
|
172
|
+
S.paused = !!on
|
|
173
|
+
S.pauseReason = S.paused ? where : null
|
|
174
|
+
if (S.paused) {
|
|
175
|
+
S.activeHandoff?.resolve({ done: false, aborted: true })
|
|
176
|
+
revokeAllGrants('paused') // 受保护网站:放行全作废,正在等的确认按拒绝收掉
|
|
177
|
+
}
|
|
178
|
+
updateBadge()
|
|
179
|
+
const saved = chrome.storage.local.set({ paused: S.paused, pauseReason: S.pauseReason })
|
|
180
|
+
log(`${S.paused ? '暂停' : '恢复'}了浏览器控制(${where})`)
|
|
181
|
+
await Promise.all([saved, S.paused && releaseAllTabs()])
|
|
182
|
+
updateBadge()
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async function setShowCursor(on, where) {
|
|
186
|
+
S.showCursor = !!on
|
|
187
|
+
await chrome.storage.local.set({ showCursor: S.showCursor })
|
|
188
|
+
log(`${S.showCursor ? '打开' : '关掉'}了页内光标(${where})`)
|
|
189
|
+
if (!S.showCursor) {
|
|
190
|
+
for (const id of [...S.cursorReady]) {
|
|
191
|
+
S.cursorReady.delete(id)
|
|
192
|
+
S.cursorPos.delete(id)
|
|
193
|
+
await hidePageCursor(id)
|
|
194
|
+
await markCursor(id, false)
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function setOwnWindow(on, where) {
|
|
200
|
+
S.ownWindow = !!on
|
|
201
|
+
await chrome.storage.local.set({ ownWindow: S.ownWindow })
|
|
202
|
+
log(`新开的页改成开在${S.ownWindow ? '单独窗口' : '当前窗口'}(${where})`)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function handleRuntimeMessage(msg, sender, sendResponse) {
|
|
206
|
+
if (!msg || sender.id !== chrome.runtime.id) return
|
|
207
|
+
if (msg.bridgeEvent && sender.tab) {
|
|
208
|
+
const tabId = sender.tab.id
|
|
209
|
+
if (msg.bridgeEvent === 'userInput' && S.attached.has(tabId) && ['pointerdown', 'keydown'].includes(msg.type) &&
|
|
210
|
+
Date.now() >= (S.agentInputUntil.get(tabId) || 0)) {
|
|
211
|
+
S.userTakeover.set(tabId, { at: Date.now(), type: msg.type })
|
|
212
|
+
if (S.cursorReady.has(tabId)) void hidePageCursor(tabId)
|
|
213
|
+
}
|
|
214
|
+
if (msg.bridgeEvent === 'handoffDone' && S.activeHandoff?.tabId === tabId && S.activeHandoff.id === msg.id)
|
|
215
|
+
S.activeHandoff.resolve({ done: true, by: 'page' })
|
|
216
|
+
return
|
|
217
|
+
}
|
|
218
|
+
if (msg.confirm) {
|
|
219
|
+
// 只有确认小窗自己(confirm.html?id=同一个 id)能取详情、能点放行;别的页面一概不理、不回话
|
|
220
|
+
if (!fromConfirmPage(sender, msg.id)) return
|
|
221
|
+
if (msg.confirm === 'get') sendResponse(getPendingConfirm(msg.id) || { expired: true })
|
|
222
|
+
else if (msg.confirm === 'decide') sendResponse(resolveConfirmation({ id: msg.id, nonce: msg.nonce, allow: msg.allow }, sender))
|
|
223
|
+
else sendResponse({ error: 'unknown' })
|
|
224
|
+
return
|
|
225
|
+
}
|
|
226
|
+
if (msg.welcome === 'state') {
|
|
227
|
+
// 欢迎页只要连没连上、快捷键是什么:不用整份状态
|
|
228
|
+
Promise.resolve(S.prefsReady).then(buildState).then((st) => sendResponse({
|
|
229
|
+
connected: st.connected, paused: st.paused, version: st.version, shortcut: st.shortcut,
|
|
230
|
+
disconnectReason: st.disconnectReason, protectedCount: st.protectedSites.length,
|
|
231
|
+
}), (e) => sendResponse({ error: String((e && e.message) || e) }))
|
|
232
|
+
return true
|
|
233
|
+
}
|
|
234
|
+
if (!msg.popup) return
|
|
235
|
+
const run = async () => {
|
|
236
|
+
await S.prefsReady
|
|
237
|
+
switch (msg.popup) {
|
|
238
|
+
case 'emergencyStop':
|
|
239
|
+
await setPaused(true, 'popup-stop')
|
|
240
|
+
return buildState()
|
|
241
|
+
case 'handoffDone': {
|
|
242
|
+
const entry = S.activeHandoff
|
|
243
|
+
const matched = !sender.tab && entry && msg.id === entry.id && entry.resolve({ done: true, by: 'popup' })
|
|
244
|
+
if (matched) await entry.cleaned
|
|
245
|
+
return { ...(await buildState()), handoffConfirmed: Boolean(matched) }
|
|
246
|
+
}
|
|
247
|
+
case 'state':
|
|
248
|
+
return buildState()
|
|
249
|
+
case 'reconnect':
|
|
250
|
+
if (S.port) { try { S.port.disconnect() } catch {} ; S.port = null; S.hostInfo = null }
|
|
251
|
+
connect()
|
|
252
|
+
await new Promise((r) => setTimeout(r, 700))
|
|
253
|
+
return buildState()
|
|
254
|
+
case 'release':
|
|
255
|
+
await releaseTab(msg.tabId)
|
|
256
|
+
return buildState()
|
|
257
|
+
case 'releaseAll':
|
|
258
|
+
await releaseAllTabs()
|
|
259
|
+
return buildState()
|
|
260
|
+
case 'focus':
|
|
261
|
+
await getOps().activate({ tabId: msg.tabId })
|
|
262
|
+
return buildState()
|
|
263
|
+
case 'pause':
|
|
264
|
+
// 解除暂停只认真正的工具栏弹窗(sender.tab 为空);弹窗页被当成普通标签页打开时不算
|
|
265
|
+
if (!msg.on && sender.tab) throw new Error('恢复控制只能在 Chrome 工具栏的 DSH Bridge 弹窗里点')
|
|
266
|
+
await setPaused(!!msg.on, '弹窗')
|
|
267
|
+
return buildState()
|
|
268
|
+
case 'cursor':
|
|
269
|
+
await setShowCursor(!!msg.on, '弹窗')
|
|
270
|
+
return buildState()
|
|
271
|
+
case 'window':
|
|
272
|
+
await setOwnWindow(!!msg.on, '弹窗')
|
|
273
|
+
return buildState()
|
|
274
|
+
case 'diagnostics':
|
|
275
|
+
return { text: await diagnostics() }
|
|
276
|
+
// 受保护网站、这个 Chrome 的名字:只认真正的工具栏弹窗(不在标签页里的 popup.html)。
|
|
277
|
+
// DSH 设置页(panel)、socket、cb 都走不到这里;弹窗页被当成普通标签页打开也不行
|
|
278
|
+
case 'addProtectedSite': {
|
|
279
|
+
if (!fromToolbarPopup(sender)) throw new Error('受保护网站只能在 Chrome 工具栏的 DSH Bridge 弹窗里改')
|
|
280
|
+
const r = await addProtectedSite(msg.site)
|
|
281
|
+
return { ...(await buildState()), siteResult: { added: r.added, pattern: r.pattern } }
|
|
282
|
+
}
|
|
283
|
+
case 'removeProtectedSite': {
|
|
284
|
+
if (!fromToolbarPopup(sender)) throw new Error('受保护网站只能在 Chrome 工具栏的 DSH Bridge 弹窗里改')
|
|
285
|
+
const r = await removeProtectedSite(msg.site)
|
|
286
|
+
return { ...(await buildState()), siteResult: { removed: r.removed } }
|
|
287
|
+
}
|
|
288
|
+
case 'setProfileLabel':
|
|
289
|
+
if (!fromToolbarPopup(sender)) throw new Error('名字只能在 Chrome 工具栏的 DSH Bridge 弹窗里改')
|
|
290
|
+
await setProfileLabel(msg.label)
|
|
291
|
+
return buildState()
|
|
292
|
+
default:
|
|
293
|
+
throw new Error(`弹窗发了不认识的请求: ${msg.popup}`)
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
run().then(sendResponse, (e) => sendResponse({ error: String((e && e.message) || e) }))
|
|
297
|
+
return true
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export {
|
|
301
|
+
restorePrefs, buildState, releaseTab, diagnostics, releaseAllTabs, setPaused, setShowCursor,
|
|
302
|
+
setOwnWindow, setProfileLabel, handleRuntimeMessage,
|
|
303
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { post } from './native.js'
|
|
2
|
+
import { S } from './state.js'
|
|
3
|
+
import { log } from './util.js'
|
|
4
|
+
|
|
5
|
+
const STORAGE_KEYS = ['instanceId', 'profileLabel']
|
|
6
|
+
const INSTANCE_ID_RE = /^[A-Za-z0-9_-]{1,48}$/
|
|
7
|
+
|
|
8
|
+
let focusListenerBound = false
|
|
9
|
+
|
|
10
|
+
function randomInstanceId() {
|
|
11
|
+
const bytes = new Uint8Array(4)
|
|
12
|
+
globalThis.crypto.getRandomValues(bytes)
|
|
13
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** 自动探测当前运行的 Chromium 系浏览器名称 */
|
|
17
|
+
function detectBrowser(nav = globalThis.navigator) {
|
|
18
|
+
if (!nav) return 'Chrome'
|
|
19
|
+
const brands = Array.isArray(nav.userAgentData?.brands)
|
|
20
|
+
? nav.userAgentData.brands.map((b) => String(b?.brand || ''))
|
|
21
|
+
: []
|
|
22
|
+
const ua = String(nav.userAgent || '')
|
|
23
|
+
if (brands.some((b) => /Microsoft Edge|Edge/i.test(b)) || /\bEdg(?:A|iOS)?\//i.test(ua)) return 'Edge'
|
|
24
|
+
if (nav.brave || brands.some((b) => /Brave/i.test(b)) || /\bBrave\b/i.test(ua)) return 'Brave'
|
|
25
|
+
if (brands.some((b) => /\bArc\b/i.test(b)) || /\bArc\//i.test(ua)) return 'Arc'
|
|
26
|
+
if (brands.some((b) => /Vivaldi/i.test(b)) || /\bVivaldi\//i.test(ua)) return 'Vivaldi'
|
|
27
|
+
if (brands.some((b) => /Google Chrome/i.test(b))) return 'Chrome'
|
|
28
|
+
if (brands.some((b) => /Chromium/i.test(b)) || /\bChromium\//i.test(ua)) return 'Chromium'
|
|
29
|
+
if (/\bChrome\//i.test(ua)) return 'Chrome'
|
|
30
|
+
return 'Chrome'
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function readExtMeta() {
|
|
34
|
+
let extId = ''
|
|
35
|
+
let extVersion = ''
|
|
36
|
+
try { extId = String(chrome.runtime?.id || '') } catch {}
|
|
37
|
+
try { extVersion = String(chrome.runtime?.getManifest?.()?.version || '') } catch {}
|
|
38
|
+
return { extId, extVersion }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function normalizeLabel(label) {
|
|
42
|
+
return typeof label === 'string' ? label.trim().slice(0, 128) : ''
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function getProfileInfo() {
|
|
46
|
+
const meta = S.helloMetadata || {}
|
|
47
|
+
const { extId, extVersion } = readExtMeta()
|
|
48
|
+
return {
|
|
49
|
+
instanceId: typeof meta.instanceId === 'string' ? meta.instanceId : '',
|
|
50
|
+
label: typeof meta.label === 'string' ? meta.label : '',
|
|
51
|
+
browser: typeof meta.browser === 'string' && meta.browser ? meta.browser : detectBrowser(),
|
|
52
|
+
extId: typeof meta.extId === 'string' && meta.extId ? meta.extId : extId,
|
|
53
|
+
extVersion: typeof meta.extVersion === 'string' && meta.extVersion ? meta.extVersion : extVersion,
|
|
54
|
+
focusedAt: typeof meta.focusedAt === 'number' && Number.isFinite(meta.focusedAt) ? meta.focusedAt : 0,
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function sendHostMeta() {
|
|
59
|
+
if (!S.port) return false
|
|
60
|
+
const info = getProfileInfo()
|
|
61
|
+
return post({ hostMeta: true, ...info })
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function onWindowFocusChanged(windowId) {
|
|
65
|
+
const noneId = chrome.windows?.WINDOW_ID_NONE ?? -1
|
|
66
|
+
if (windowId === noneId || typeof windowId !== 'number' || windowId < 0) return
|
|
67
|
+
const now = Date.now()
|
|
68
|
+
if (!S.helloMetadata || typeof S.helloMetadata !== 'object') S.helloMetadata = {}
|
|
69
|
+
S.helloMetadata.focusedAt = now
|
|
70
|
+
sendHostMeta()
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function bindFocusListener() {
|
|
74
|
+
if (focusListenerBound) return
|
|
75
|
+
try {
|
|
76
|
+
if (chrome.windows?.onFocusChanged?.addListener) {
|
|
77
|
+
chrome.windows.onFocusChanged.addListener(onWindowFocusChanged)
|
|
78
|
+
focusListenerBound = true
|
|
79
|
+
}
|
|
80
|
+
} catch (e) {
|
|
81
|
+
log('绑定窗口焦点监听失败:', String(e))
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function probeInitialFocus() {
|
|
86
|
+
try {
|
|
87
|
+
const win = await chrome.windows?.getLastFocused?.()
|
|
88
|
+
if (win && win.focused) return Date.now()
|
|
89
|
+
} catch {}
|
|
90
|
+
return 0
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* 初始化本 Profile 的稳定身份(instanceId / label / browser / extId / extVersion / focusedAt),
|
|
95
|
+
* 写入 S.helloMetadata 并在已连上宿主或窗口切换焦点时实时上报 hostMeta。
|
|
96
|
+
*/
|
|
97
|
+
function initProfile() {
|
|
98
|
+
const { extId, extVersion } = readExtMeta()
|
|
99
|
+
const browser = detectBrowser()
|
|
100
|
+
const prev = S.helloMetadata && typeof S.helloMetadata === 'object' ? S.helloMetadata : {}
|
|
101
|
+
S.helloMetadata = {
|
|
102
|
+
instanceId: typeof prev.instanceId === 'string' ? prev.instanceId : '',
|
|
103
|
+
label: typeof prev.label === 'string' ? prev.label : '',
|
|
104
|
+
browser: prev.browser || browser,
|
|
105
|
+
extId: prev.extId || extId,
|
|
106
|
+
extVersion: prev.extVersion || extVersion,
|
|
107
|
+
focusedAt: typeof prev.focusedAt === 'number' && Number.isFinite(prev.focusedAt) ? prev.focusedAt : 0,
|
|
108
|
+
}
|
|
109
|
+
bindFocusListener()
|
|
110
|
+
|
|
111
|
+
const ready = (async () => {
|
|
112
|
+
let stored = {}
|
|
113
|
+
try {
|
|
114
|
+
stored = (await chrome.storage?.local?.get(STORAGE_KEYS)) || {}
|
|
115
|
+
} catch (e) {
|
|
116
|
+
log('读取 Profile 信息失败:', String(e))
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
let instanceId = typeof stored.instanceId === 'string' && INSTANCE_ID_RE.test(stored.instanceId)
|
|
120
|
+
? stored.instanceId
|
|
121
|
+
: ''
|
|
122
|
+
if (!instanceId) {
|
|
123
|
+
instanceId = randomInstanceId()
|
|
124
|
+
try {
|
|
125
|
+
await chrome.storage?.local?.set({ instanceId })
|
|
126
|
+
} catch (e) {
|
|
127
|
+
log('保存 instanceId 失败:', String(e))
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const label = normalizeLabel(stored.profileLabel)
|
|
132
|
+
const initialFocus = await probeInitialFocus()
|
|
133
|
+
const focusedAt = Math.max(Number(S.helloMetadata?.focusedAt) || 0, initialFocus)
|
|
134
|
+
|
|
135
|
+
S.helloMetadata = {
|
|
136
|
+
instanceId,
|
|
137
|
+
label,
|
|
138
|
+
browser,
|
|
139
|
+
extId,
|
|
140
|
+
extVersion,
|
|
141
|
+
focusedAt,
|
|
142
|
+
}
|
|
143
|
+
sendHostMeta()
|
|
144
|
+
return getProfileInfo()
|
|
145
|
+
})()
|
|
146
|
+
|
|
147
|
+
S.profileReady = ready
|
|
148
|
+
return ready
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function setProfileLabel(label) {
|
|
152
|
+
const clean = normalizeLabel(label)
|
|
153
|
+
if (!S.helloMetadata || typeof S.helloMetadata !== 'object') S.helloMetadata = getProfileInfo()
|
|
154
|
+
S.helloMetadata.label = clean
|
|
155
|
+
try {
|
|
156
|
+
await chrome.storage?.local?.set({ profileLabel: clean })
|
|
157
|
+
} catch (e) {
|
|
158
|
+
log('保存 profileLabel 失败:', String(e))
|
|
159
|
+
}
|
|
160
|
+
sendHostMeta()
|
|
161
|
+
return getProfileInfo()
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export {
|
|
165
|
+
detectBrowser, getProfileInfo, initProfile, sendHostMeta, setProfileLabel,
|
|
166
|
+
}
|