Merge pull request '增加 Chromium 浏览器逐站权限管理' (#14) from xhgit/browser-site-permissions into main
Reviewed-on: http://git.xhmcl.com/xhgit/XHChat/pulls/14
This commit was merged in pull request #14.
This commit is contained in:
commit
d39b51703d
8 files changed
+165
-6
No files matched your search
@@ -9,7 +9,7 @@
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<div class="tabs"><div id="tabs" aria-label="标签页"></div><button data-action="new" aria-label="新建标签页">+</button><span id="mode"></span><button data-action="bookmark">添加书签</button><button data-action="library">书签与历史</button><button id="show-downloads">下载</button></div>
|
||||
<div class="tabs"><div id="tabs" aria-label="标签页"></div><button data-action="new" aria-label="新建标签页">+</button><span id="mode"></span><button data-action="bookmark">添加书签</button><button data-action="library">书签与历史</button><button id="show-downloads">下载</button><button id="show-permissions">网站权限</button></div>
|
||||
<form id="address-form">
|
||||
<button type="button" data-action="back" aria-label="后退">←</button>
|
||||
<button type="button" data-action="forward" aria-label="前进">→</button>
|
||||
@@ -35,5 +35,17 @@
|
||||
<button data-action="clearDownloads">清除下载记录</button>
|
||||
<ul id="download-list"></ul>
|
||||
</section>
|
||||
<section id="permission-panel" hidden>
|
||||
<h1>网站权限</h1>
|
||||
<p id="permission-origin"></p>
|
||||
<fieldset id="site-grants">
|
||||
<legend>允许当前网站使用</legend>
|
||||
<label><input type="checkbox" value="camera">摄像头</label>
|
||||
<label><input type="checkbox" value="microphone">麦克风</label>
|
||||
<label><input type="checkbox" value="location">位置</label>
|
||||
<label><input type="checkbox" value="notifications">通知</label>
|
||||
<label><input type="checkbox" value="clipboard">剪贴板</label>
|
||||
</fieldset>
|
||||
</section>
|
||||
</body>
|
||||
</html>
|
||||
@@ -28,4 +28,9 @@ input { flex: 1; min-width: 0; }
|
||||
#download-list { list-style: none; padding: 0; }
|
||||
#download-list li { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-bottom: 8px; }
|
||||
#download-list strong { overflow-wrap: anywhere; }
|
||||
#permission-panel { padding: 18px; }
|
||||
#permission-panel h1 { margin: 0 0 10px; font-size: 18px; }
|
||||
#permission-origin { overflow-wrap: anywhere; }
|
||||
#site-grants { display: grid; gap: 8px; max-width: 340px; }
|
||||
#site-grants input { margin-right: 8px; }
|
||||
@media (max-width: 750px) { form [data-action="zoomIn"], form [data-action="zoomOut"] { display: none; } }
|
||||
@@ -92,10 +92,16 @@ function render(state) {
|
||||
button('bookmark').textContent = state.bookmarked ? '取消书签' : '添加书签'
|
||||
button('library').hidden = state.privateMode
|
||||
document.querySelector('#show-downloads').hidden = state.privateMode
|
||||
document.querySelector('#show-permissions').hidden = state.privateMode
|
||||
button('library').setAttribute('aria-pressed', String(state.libraryMode && panel === 'library'))
|
||||
document.querySelector('#show-downloads').setAttribute('aria-pressed', String(state.libraryMode && panel === 'downloads'))
|
||||
document.querySelector('#show-permissions').setAttribute('aria-pressed', String(state.libraryMode && panel === 'permissions'))
|
||||
document.querySelector('#library').hidden = !(state.libraryMode && panel === 'library')
|
||||
document.querySelector('#download-panel').hidden = !(state.libraryMode && panel === 'downloads')
|
||||
document.querySelector('#permission-panel').hidden = !(state.libraryMode && panel === 'permissions')
|
||||
document.querySelector('#permission-origin').textContent = state.origin || '请先打开一个网站。'
|
||||
document.querySelector('#site-grants').disabled = !state.origin
|
||||
for (const input of document.querySelectorAll('#site-grants input')) input.checked = state.grants[input.value] === true
|
||||
if (state.libraryMode && panel === 'library') {
|
||||
renderEntries('#bookmarks', state.bookmarks, true)
|
||||
renderEntries('#history', state.history, false)
|
||||
@@ -108,6 +114,7 @@ async function command(action, value) {
|
||||
try {
|
||||
render(await api.command(action, value))
|
||||
} catch (error) {
|
||||
if (current) render(current)
|
||||
status.textContent = error.message
|
||||
}
|
||||
}
|
||||
@@ -131,6 +138,10 @@ function showPanel(next) {
|
||||
|
||||
button('library').onclick = () => showPanel('library')
|
||||
document.querySelector('#show-downloads').onclick = () => showPanel('downloads')
|
||||
document.querySelector('#show-permissions').onclick = () => showPanel('permissions')
|
||||
for (const input of document.querySelectorAll('#site-grants input')) {
|
||||
input.onchange = () => void command('siteGrant', [current.origin, input.value, input.checked ? 'allow' : 'block'].join('\n'))
|
||||
}
|
||||
|
||||
document.querySelector('#address-form').onsubmit = (event) => {
|
||||
event.preventDefault()
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { app } from 'electron'
|
||||
import type { Session, WebContents } from 'electron'
|
||||
import { readFileSync, renameSync, writeFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
|
||||
export const sitePermissions = ['camera', 'microphone', 'location', 'notifications', 'clipboard'] as const
|
||||
type Permission = typeof sitePermissions[number]
|
||||
type PermissionMap = Partial<Record<Permission, true>>
|
||||
type Site = { origin: string; grants: PermissionMap }
|
||||
|
||||
let cache: Site[] | undefined
|
||||
const path = () => join(app.getPath('userData'), 'browser-permissions.json')
|
||||
|
||||
function sites(): Site[] {
|
||||
if (cache) return cache
|
||||
try {
|
||||
const saved: unknown = JSON.parse(readFileSync(path(), 'utf8'))
|
||||
cache = Array.isArray(saved) ? saved.slice(0, 200).filter((site) =>
|
||||
typeof site?.origin === 'string' && typeof site?.grants === 'object' && site.grants !== null) : []
|
||||
} catch {
|
||||
cache = []
|
||||
}
|
||||
return cache
|
||||
}
|
||||
|
||||
export function grants(origin: string) {
|
||||
return sites().find((site) => site.origin === origin)?.grants ?? {}
|
||||
}
|
||||
|
||||
export function setGrant(origin: string, key: string, allowed: boolean) {
|
||||
const permission = sitePermissions.find((item) => item === key)
|
||||
if (!permission) throw new Error('未知网站权限')
|
||||
const next = sites().filter((item) => item.origin !== origin)
|
||||
const updated = { ...grants(origin) }
|
||||
if (allowed) updated[permission] = true
|
||||
else delete updated[permission]
|
||||
if (sitePermissions.some((item) => updated[item] === true)) next.push({ origin, grants: updated })
|
||||
if (next.length > 200) throw new Error('网站权限记录已达上限')
|
||||
save(next)
|
||||
}
|
||||
|
||||
export function clearGrants() {
|
||||
save([])
|
||||
}
|
||||
|
||||
function save(next: Site[]) {
|
||||
const file = path()
|
||||
writeFileSync(file + '.tmp', JSON.stringify(next), { mode: 0o600 })
|
||||
renameSync(file + '.tmp', file)
|
||||
cache = next
|
||||
}
|
||||
|
||||
export function configurePermissions(session: Session, privateMode: boolean, visible: (contents: WebContents) => boolean) {
|
||||
function approved(contents: WebContents | null, requester: string, mainFrame: boolean, permission: string, media: string[]) {
|
||||
if (!contents || !mainFrame || !visible(contents)) return false
|
||||
let origin: string
|
||||
try {
|
||||
const source = new URL(requester)
|
||||
const page = new URL(contents.getURL())
|
||||
if (source.origin !== page.origin || !['https:', 'http:'].includes(source.protocol)) return false
|
||||
origin = source.origin
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
if (permission === 'fullscreen') return true
|
||||
if (privateMode) return false
|
||||
const current = grants(origin)
|
||||
switch (permission) {
|
||||
case 'media':
|
||||
return media.length > 0 && media.every((type) => type === 'audio' && current.microphone === true ||
|
||||
type === 'video' && current.camera === true)
|
||||
case 'geolocation':
|
||||
case 'geolocation-approximate': return current.location === true
|
||||
case 'notifications': return current.notifications === true
|
||||
case 'clipboard-read':
|
||||
case 'clipboard-sanitized-write': return current.clipboard === true
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
|
||||
session.setPermissionCheckHandler((contents, permission, origin, details) =>
|
||||
approved(contents, origin, details.isMainFrame, permission, details.mediaType ? [details.mediaType] : []))
|
||||
session.setPermissionRequestHandler((contents, permission, callback, details) =>
|
||||
callback(approved(contents, details.requestingUrl, details.isMainFrame, permission,
|
||||
'mediaTypes' in details ? details.mediaTypes ?? [] : [])))
|
||||
}
|
||||
+29
-3
@@ -3,6 +3,7 @@ import type { DownloadItem, Session } from 'electron'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { join } from 'node:path'
|
||||
import { clearDownloads, clearHistory, library, recordDownload, removeBookmark, toggleBookmark, visit } from './browser-library'
|
||||
import { clearGrants, configurePermissions, grants, setGrant } from './browser-permissions'
|
||||
|
||||
const browserURL = 'xhchat://app/browser'
|
||||
const height = 102
|
||||
@@ -43,6 +44,7 @@ function address(value: string): URL | undefined {
|
||||
function state(browser: BrowserWindowState) {
|
||||
const contents = browser.active?.view.webContents
|
||||
const collection = browser.privateMode ? { bookmarks: [], history: [], downloads: [] } : library()
|
||||
const origin = website(contents?.getURL() ?? '')?.origin ?? ''
|
||||
return {
|
||||
privateMode: browser.privateMode,
|
||||
active: browser.active?.id,
|
||||
@@ -53,6 +55,8 @@ function state(browser: BrowserWindowState) {
|
||||
loading: contents?.isLoading() ?? false,
|
||||
error: browser.active?.error ?? '',
|
||||
libraryMode: browser.libraryMode,
|
||||
origin,
|
||||
grants: browser.privateMode || !origin ? {} : grants(origin),
|
||||
bookmarked: collection.bookmarks.some((item) => item.url === contents?.getURL()),
|
||||
...collection,
|
||||
downloads: browser.privateMode ? [] : [
|
||||
@@ -179,8 +183,8 @@ const configured = new WeakSet<Session>()
|
||||
function configureSites(sites: Session, privateMode: boolean) {
|
||||
if (configured.has(sites)) return
|
||||
configured.add(sites)
|
||||
sites.setPermissionRequestHandler((_contents, _permission, callback) => callback(false))
|
||||
sites.setPermissionCheckHandler(() => false)
|
||||
configurePermissions(sites, privateMode, (contents) => [...windows.values()].some((browser) =>
|
||||
!browser.libraryMode && browser.active?.view.webContents === contents && browser.window.isVisible()))
|
||||
const defaultUA = sites.getUserAgent()
|
||||
.replace(/\sElectron\/\S+/g, '')
|
||||
.replace(/\s(?:XHChat|xhchat)\/\S+/g, '')
|
||||
@@ -320,6 +324,25 @@ export function registerBrowserHandlers(trusted: Session) {
|
||||
if (item?.path) shell.showItemInFolder(item.path)
|
||||
break
|
||||
}
|
||||
case 'siteGrant': {
|
||||
if (browser.privateMode || !browser.libraryMode || !current || typeof value !== 'string') break
|
||||
const [origin, permission, desired, ...rest] = value.split('\n')
|
||||
if (origin !== current.origin || rest.length || !['allow', 'block'].includes(desired)) {
|
||||
throw new Error('网页已切换,请重新检查网站权限')
|
||||
}
|
||||
setGrant(origin, permission, desired === 'allow')
|
||||
if (desired === 'block') {
|
||||
for (const candidate of windows.values()) {
|
||||
if (candidate.sites !== browser.sites) continue
|
||||
for (const tab of candidate.tabs) {
|
||||
const page = tab.view.webContents
|
||||
if (website(page.getURL())?.origin === origin) page.reload()
|
||||
}
|
||||
}
|
||||
}
|
||||
updateNormalWindows()
|
||||
break
|
||||
}
|
||||
case 'clearDownloads': {
|
||||
if (browser.privateMode) break
|
||||
clearDownloads()
|
||||
@@ -344,7 +367,10 @@ export function registerBrowserHandlers(trusted: Session) {
|
||||
})
|
||||
if (answer.response === 1) {
|
||||
await browser.sites.clearData()
|
||||
if (!browser.privateMode) clearHistory()
|
||||
if (!browser.privateMode) {
|
||||
clearHistory()
|
||||
clearGrants()
|
||||
}
|
||||
for (const candidate of windows.values()) {
|
||||
if (candidate.sites !== browser.sites) continue
|
||||
for (const tab of candidate.tabs) tab.view.webContents.navigationHistory.clear()
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
受信任的聊天与浏览器工具栏从随包静态资源加载。第三方网页进入独立 WebContentsView 和单独 Session,禁用 Node、preload 与 webview,启用 sandbox、contextIsolation、webSecurity。普通与隐私模式使用不同分区,隐私窗口销毁后清理其临时分区。主进程校验 IPC 的 WebContents、主帧、来源和参数。应用自定义协议只注册到受信任会话,资源查找使用固定目录和可访问资源边界。 [Electron 安全指南](https://www.electronjs.org/docs/latest/tutorial/security) · [Electron Web 嵌入](https://www.electronjs.org/docs/latest/tutorial/web-embeds/)
|
||||
|
||||
内置浏览器将以 Chromium 的真实 UA 追加 XHChat/版本,保留 UA-CH 默认协商并用测试站检查一致性。导航、重定向和新窗口只接受允许的网络协议。摄像头、麦克风、剪贴板、通知与位置默认拒绝,后续按可信 UI 中的顶级网站授权。下载由可信 UI 确认路径及来源。恶意站点警告机制需要评估信誉服务、误报与隐私影响。
|
||||
内置浏览器使用 Chromium 的真实 UA 并追加 XHChat/版本,保留 UA-CH 默认协商。导航、重定向和新窗口只接受允许的网络协议。摄像头、麦克风、剪贴板、通知与位置默认拒绝。可信工具栏可以给当前网站授予或撤销权限,权限检查与请求同时限制为可见顶级网页和同源。撤销单项权限后重新加载该站已打开的网页。隐私窗口不继承普通窗口授权。下载由可信 UI 确认路径及来源。恶意站点警告机制需要评估信誉服务、误报与隐私影响。
|
||||
|
||||
普通窗口的书签和历史保存在 Electron 用户目录,独立于通讯存储。可信工具栏展示标题和地址时使用纯文本。打开收藏或历史项会在主进程重新校验 URL。隐私窗口使用临时分区,关闭后清理网站数据,不写入浏览记录。
|
||||
|
||||
|
||||
+5
-1
@@ -21,7 +21,7 @@ Web 和 Electron 共用 Vue 客户端,独立接入同一 Go API。真实 Postg
|
||||
- 阶段一还需邮箱和手机号注册、验证码服务、找回密码和双重验证。真实联调需要 SMTP 与短信供应商配置。
|
||||
- 阶段二与三还需分片附件、消息操作、群聊、多设备可信授权、加密备份与跨设备历史同步。两设备文字和小附件私聊已进入开发预览。
|
||||
- 阶段四还需 WebRTC 音视频、TURN、SFU、屏幕共享及媒体 E2EE。
|
||||
- 阶段五还需逐站授权、反钓鱼及聊天联动。
|
||||
- 阶段五还需反钓鱼及聊天联动。
|
||||
- 阶段六到八还需社交、扩展生态、独立管理后台、推送、生产部署与备份演练、压力测试、安全评估、签名安装包和发布流程。
|
||||
|
||||
## 联系人和 Chromium 浏览器
|
||||
@@ -68,3 +68,7 @@ Windows 浏览器新增可跨窗口保留的本地书签和历史,每类最多
|
||||
## 浏览器下载管理
|
||||
|
||||
普通窗口下载支持保存对话框、进度、暂停、可恢复时继续、取消和完成后定位文件。最多保存 150 条记录,清除记录不删除已下载文件。Electron 集成测试确认真实文件写入、状态记录和清除。
|
||||
|
||||
## 浏览器逐站权限
|
||||
|
||||
普通窗口可按当前网站的协议、主机与端口单独授权或撤销摄像头、麦克风、位置、通知和剪贴板权限。默认拒绝,授权只用于可见的顶级网页。隐私窗口不继承授权。Electron 集成测试通过 Chromium 权限查询验证通知权限默认拒绝、显式授权和撤销。
|
||||
@@ -96,6 +96,21 @@ test('双端联系人实时同步,桌面浏览器独立分区与 UA', { timeou
|
||||
const userAgent = requests.find((entry) => entry.path === '/first').userAgent
|
||||
assert.ok(userAgent.includes('Chrome/' + site.version))
|
||||
assert.match(userAgent, /XHChat\/0\.1\.0/)
|
||||
const permission = (location) => app.evaluate(async ({ webContents }, location) => {
|
||||
const page = webContents.getAllWebContents().find((entry) => entry.getURL() === location)
|
||||
if (!page) throw new Error('找不到权限测试网页')
|
||||
return page.executeJavaScript('navigator.permissions.query({name:"notifications"}).then(x=>x.state)')
|
||||
}, location)
|
||||
assert.notEqual(await permission(url + '/first'), 'granted')
|
||||
await toolbar.getByRole('button', { name: '网站权限', exact: true }).click()
|
||||
await toolbar.locator('#permission-origin').getByText(url, { exact: true }).waitFor()
|
||||
await toolbar.getByLabel('通知', { exact: true }).check()
|
||||
await toolbar.getByRole('button', { name: '网站权限', exact: true }).click()
|
||||
assert.equal(await permission(url + '/first'), 'granted')
|
||||
await toolbar.getByRole('button', { name: '网站权限', exact: true }).click()
|
||||
await toolbar.getByLabel('通知', { exact: true }).uncheck()
|
||||
await toolbar.getByRole('button', { name: '网站权限', exact: true }).click()
|
||||
assert.notEqual(await permission(url + '/first'), 'granted')
|
||||
await toolbar.getByRole('button', { name: '添加书签', exact: true }).click()
|
||||
await toolbar.getByRole('button', { name: '取消书签', exact: true }).waitFor()
|
||||
await toolbar.getByRole('button', { name: '书签与历史', exact: true }).click()
|
||||
|
||||
Reference in new issue
Block a user