交付双端基础、实时联系人和隔离浏览器

This commit is contained in:
xhgit committed 2026-11-13 18:03:32 +08:00
1 parent 43687d5e7e
commit 67fef3ff87
59 files changed
+5094 -1

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
import { contextBridge, ipcRenderer } from 'electron'
contextBridge.exposeInMainWorld('xhchatBrowser', {
command: (action: string, value?: string) => ipcRenderer.invoke('browser:command', action, value),
onState: (callback: (state: unknown) => void) => {
ipcRenderer.on('browser:state', (_event, state: unknown) => callback(state))
},
})
+260
View File
@@ -0,0 +1,260 @@
import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, session, shell, WebContentsView } from 'electron'
import type { Session } from 'electron'
import { randomUUID } from 'node:crypto'
import { join } from 'node:path'
const browserURL = 'xhchat://app/browser'
const height = 102
const maximumTabs = 16
type Tab = { id: string; view: WebContentsView; error: string }
type BrowserWindowState = {
window: BrowserWindow
sites: Session
privateMode: boolean
tabs: Tab[]
active?: Tab
}
const windows = new Map<number, BrowserWindowState>()
export function website(value: string): URL | undefined {
try {
const url = new URL(value)
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) return
if (url.protocol === 'http:' && !['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)) return
return url
} catch {
return undefined
}
}
function address(value: string): URL | undefined {
const input = value.trim()
if (!input || input.length > 4096) return
if (/^[a-z][a-z0-9+.-]*:/i.test(input)) return website(input)
if (!/\s/.test(input) && input.includes('.')) return website('https://' + input)
return website('https://www.bing.com/search?' + new URLSearchParams({ q: input }))
}
function state(browser: BrowserWindowState) {
const contents = browser.active?.view.webContents
return {
privateMode: browser.privateMode,
active: browser.active?.id,
tabs: browser.tabs.map(({ id, view }) => ({ id, title: view.webContents.getTitle() || '新标签页' })),
url: contents?.getURL() ?? '',
back: contents?.navigationHistory.canGoBack() ?? false,
forward: contents?.navigationHistory.canGoForward() ?? false,
loading: contents?.isLoading() ?? false,
error: browser.active?.error ?? '',
}
}
function update(browser: BrowserWindowState) {
if (!browser.window.isDestroyed()) browser.window.webContents.send('browser:state', state(browser))
}
function resize(browser: BrowserWindowState) {
const [width, total] = browser.window.getContentSize()
const top = browser.window.isFullScreen() ? 0 : height
browser.active?.view.setBounds({ x: 0, y: top, width, height: Math.max(0, total - top) })
}
function activate(browser: BrowserWindowState, tab?: Tab) {
if (browser.active) browser.window.contentView.removeChildView(browser.active.view)
browser.active = tab
if (tab) {
browser.window.contentView.addChildView(tab.view)
resize(browser)
}
update(browser)
}
async function navigate(tab: Tab, url: URL) {
tab.error = ''
try {
await tab.view.webContents.loadURL(url.href)
} catch {
// The navigation events carry details for the toolbar.
}
}
function addTab(browser: BrowserWindowState, url?: URL) {
if (browser.tabs.length >= maximumTabs) return
const view = new WebContentsView({ webPreferences: {
session: browser.sites, sandbox: true, contextIsolation: true, nodeIntegration: false,
webSecurity: true, webviewTag: false, allowRunningInsecureContent: false,
} })
const tab = { id: randomUUID(), view, error: '' }
const contents = view.webContents
contents.setWindowOpenHandler(({ url }) => {
const target = website(url)
if (target) setImmediate(() => {
if (!browser.window.isDestroyed()) addTab(browser, target)
})
return { action: 'deny' }
})
contents.on('will-frame-navigate', (event) => {
if (!website(event.url)) event.preventDefault()
})
contents.on('will-redirect', (event) => {
if (!website(event.url)) event.preventDefault()
})
contents.on('will-attach-webview', (event) => event.preventDefault())
contents.on('did-fail-load', (_event, code, _description, _url, mainFrame) => {
if (mainFrame && code !== -3) tab.error = '网页加载失败,请检查地址或网络。'
update(browser)
})
contents.on('did-navigate', () => { tab.error = ''; update(browser) })
contents.on('did-navigate-in-page', () => update(browser))
contents.on('page-title-updated', () => update(browser))
contents.on('did-start-loading', () => update(browser))
contents.on('did-stop-loading', () => update(browser))
contents.on('enter-html-full-screen', () => resize(browser))
contents.on('leave-html-full-screen', () => resize(browser))
contents.on('before-input-event', (event, input) => {
if (input.type === 'keyDown' && input.key === 'F11') {
event.preventDefault()
browser.window.setFullScreen(!browser.window.isFullScreen())
}
})
contents.on('context-menu', (_event, info) => {
const link = website(info.linkURL)
const current = website(contents.getURL())
Menu.buildFromTemplate([
{ label: '在新标签页打开链接', enabled: Boolean(link), click: () => { if (link) addTab(browser, link) } },
{ label: '复制链接', enabled: Boolean(link ?? current), click: () => clipboard.writeText((link ?? current)?.href ?? '') },
{ label: '复制选中文字', enabled: Boolean(info.selectionText), click: () => contents.copy() },
{ label: '在系统浏览器打开', enabled: Boolean(current), click: () => { if (current) void shell.openExternal(current.href).catch(() => {}) } },
]).popup({ window: browser.window })
})
browser.tabs.push(tab)
activate(browser, tab)
if (url) void navigate(tab, url)
}
function closeTab(browser: BrowserWindowState, tab: Tab) {
const index = browser.tabs.indexOf(tab)
browser.tabs.splice(index, 1)
if (browser.active === tab) activate(browser, browser.tabs[Math.min(index, browser.tabs.length - 1)])
tab.view.webContents.close()
if (!browser.tabs.length) addTab(browser)
update(browser)
}
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)
const defaultUA = sites.getUserAgent()
.replace(/\sElectron\/\S+/g, '')
.replace(/\s(?:XHChat|xhchat)\/\S+/g, '')
sites.setUserAgent(defaultUA + ' XHChat/' + app.getVersion())
sites.webRequest.onBeforeRequest((details, callback) => {
const scheme = new URL(details.url).protocol
callback({ cancel: !['https:', 'http:', 'wss:', 'ws:', 'data:', 'blob:', 'about:'].includes(scheme) })
})
sites.on('will-download', (event, item, contents) => {
const browser = [...windows.values()].find((window) => window.tabs.some((tab) => tab.view.webContents === contents))
if (!browser || privateMode || !item.getURLChain().every(website)) {
event.preventDefault()
return
}
item.setSaveDialogOptions({ title: '保存网页下载', buttonLabel: '保存' })
})
}
export function openBrowser(trusted: Session, privateMode = false) {
const sites = session.fromPartition(privateMode ? 'xhchat-private-' + randomUUID() : 'persist:xhchat-sites')
configureSites(sites, privateMode)
const window = new BrowserWindow({
title: privateMode ? 'XHChat 浏览器 · 隐私窗口' : 'XHChat 浏览器',
width: 1050, height: 720, minWidth: 620, minHeight: 430,
webPreferences: {
session: trusted, preload: join(__dirname, 'browser-preload.js'),
sandbox: true, contextIsolation: true, nodeIntegration: false, webviewTag: false,
},
})
const browser: BrowserWindowState = { window, sites, privateMode, tabs: [] }
const id = window.webContents.id
windows.set(id, browser)
window.setMenuBarVisibility(false)
window.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
window.webContents.on('will-navigate', (event) => event.preventDefault())
window.webContents.on('will-attach-webview', (event) => event.preventDefault())
window.on('resize', () => resize(browser))
window.on('enter-full-screen', () => resize(browser))
window.on('leave-full-screen', () => resize(browser))
window.on('closed', () => {
windows.delete(id)
for (const tab of browser.tabs) tab.view.webContents.close()
if (privateMode) void sites.clearData().catch(() => {})
})
window.webContents.on('did-finish-load', () => addTab(browser))
void window.loadURL(browserURL).catch(() => {
if (!window.isDestroyed()) window.close()
})
}
export function registerBrowserHandlers(trusted: Session) {
ipcMain.handle('browser:command', async (event, action: unknown, value: unknown) => {
const browser = windows.get(event.sender.id)
if (!browser || event.senderFrame !== event.sender.mainFrame || event.senderFrame?.url !== browserURL) {
throw new Error('浏览器命令来源无效')
}
const tab = browser.active
const contents = tab?.view.webContents
const current = website(contents?.getURL() ?? '')
switch (action) {
case 'new': addTab(browser); break
case 'private': openBrowser(trusted, true); break
case 'activate': {
const selected = browser.tabs.find(({ id }) => id === value)
if (selected) activate(browser, selected)
break
}
case 'close': {
const selected = browser.tabs.find(({ id }) => id === value)
if (selected) closeTab(browser, selected)
break
}
case 'go': {
const target = typeof value === 'string' ? address(value) : undefined
if (!target) throw new Error('请输入 HTTPS 地址或搜索关键词。')
if (tab) void navigate(tab, target)
break
}
case 'back': contents?.navigationHistory.goBack(); break
case 'forward': contents?.navigationHistory.goForward(); break
case 'reload': contents?.reload(); break
case 'stop': contents?.stop(); break
case 'copy': if (current) clipboard.writeText(current.href); break
case 'external': if (current) await shell.openExternal(current.href); break
case 'zoomIn': if (contents) contents.setZoomLevel(Math.min(4, contents.getZoomLevel() + 1)); break
case 'zoomOut': if (contents) contents.setZoomLevel(Math.max(-3, contents.getZoomLevel() - 1)); break
case 'fullscreen': browser.window.setFullScreen(!browser.window.isFullScreen()); break
case 'clear': {
const answer = await dialog.showMessageBox(browser.window, {
type: 'question', message: '清除浏览器 Cookie、缓存和网站数据?',
buttons: ['取消', '清除'], defaultId: 0, cancelId: 0,
})
if (answer.response === 1) {
await browser.sites.clearData()
for (const candidate of windows.values()) {
if (candidate.sites !== browser.sites) continue
for (const tab of candidate.tabs) tab.view.webContents.navigationHistory.clear()
update(candidate)
}
}
break
}
case 'state': break
default: throw new Error('未知浏览器命令')
}
return state(browser)
})
}
+40
View File
@@ -0,0 +1,40 @@
import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, sign } from 'node:crypto'
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { app, safeStorage } from 'electron'
const active = new Map<string, Promise<ReturnType<typeof createPrivateKey>>>()
async function readOrCreate(file: string) {
if (!safeStorage.isEncryptionAvailable()) throw new Error('系统密钥保护不可用')
try {
const sealed = await readFile(file)
return createPrivateKey(safeStorage.decryptString(sealed))
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
}
const { privateKey } = generateKeyPairSync('ed25519')
const pem = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString()
const temporary = file + '.tmp'
await writeFile(temporary, safeStorage.encryptString(pem), { mode: 0o600 })
await rename(temporary, file)
return privateKey
}
export async function signChallenge(server: string, username: string, challenge: string) {
if (!/^[a-z0-9_]{3,32}$/.test(username) || !/^[A-Za-z0-9_-]{43}$/.test(challenge)) {
throw new Error('设备验证参数无效')
}
const directory = join(app.getPath('userData'), 'device-keys')
await mkdir(directory, { recursive: true })
const file = join(directory, createHash('sha256').update(server + '\n' + username).digest('hex'))
let pending = active.get(file)
if (!pending) {
pending = readOrCreate(file).finally(() => active.delete(file))
active.set(file, pending)
}
const key = await pending
const publicKey = createPublicKey(key).export({ format: 'jwk' }).x!
const signature = sign(null, Buffer.from('XHChat device authentication v1\n' + challenge), key).toString('base64url')
return { publicKey, signature }
}
+99
View File
@@ -0,0 +1,99 @@
import { app, BrowserWindow, ipcMain, protocol, session } from 'electron'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { signChallenge } from './identity'
import { openBrowser, registerBrowserHandlers } from './browser'
const appURL = 'xhchat://app/'
app.enableSandbox()
protocol.registerSchemesAsPrivileged([{
scheme: 'xhchat', privileges: { standard: true, secure: true, supportFetchAPI: true, corsEnabled: true },
}])
function serviceOrigin() {
const url = new URL(process.env.XHCHAT_SERVER_URL ?? 'http://127.0.0.1:8080')
const local = ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)
if ((url.protocol !== 'https:' && !(local && url.protocol === 'http:')) ||
url.username || url.password || url.pathname !== '/' || url.search || url.hash) {
throw new Error('XHCHAT_SERVER_URL 必须是 HTTPS 服务源或本机开发服务源')
}
return url.origin
}
async function start() {
const api = serviceOrigin()
const websocket = api.replace(/^http/, 'ws')
const renderer = app.isPackaged ? join(app.getAppPath(), 'renderer') : join(__dirname, '../../web/dist')
const browserUI = join(app.getAppPath(), 'browser')
const trusted = session.fromPartition('persist:xhchat-application')
trusted.setPermissionRequestHandler((_contents, _permission, callback) => callback(false))
trusted.setPermissionCheckHandler(() => false)
trusted.protocol.handle('xhchat', async (request) => {
const url = new URL(request.url)
const root = url.pathname === '/'
const browserPaths = new Map([
['/browser', 'index.html'], ['/browser/style.css', 'style.css'], ['/browser/ui.js', 'ui.js'],
])
const browserAsset = browserPaths.get(url.pathname)
if (url.host !== 'app' || request.method !== 'GET' ||
(!root && !browserAsset && !/^\/assets\/[a-zA-Z0-9_.-]+\.(?:js|css)$/.test(url.pathname))) {
return new Response(null, { status: 404 })
}
try {
const bytes = await readFile(browserAsset ? join(browserUI, browserAsset) : join(renderer, root ? 'index.html' : url.pathname.slice(1)))
const html = root || url.pathname === '/browser'
const policy = "default-src 'none'; script-src 'self'; style-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
return new Response(bytes, { headers: {
'Content-Type': html ? 'text/html; charset=utf-8' : url.pathname.endsWith('.css') ? 'text/css' : 'application/javascript',
'Content-Security-Policy': browserAsset ? policy : policy + '; connect-src ' + api + ' ' + websocket,
'X-Content-Type-Options': 'nosniff',
} })
} catch {
return new Response(null, { status: 404 })
}
})
const win = new BrowserWindow({
title: 'XHChat', width: 1120, height: 740, minWidth: 480, minHeight: 570,
webPreferences: {
session: trusted, preload: join(__dirname, 'preload.js'),
additionalArguments: ['--xhchat-api=' + api],
sandbox: true, contextIsolation: true, nodeIntegration: false, webviewTag: false,
},
})
win.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))
win.webContents.on('will-navigate', (event) => event.preventDefault())
win.webContents.on('will-attach-webview', (event) => event.preventDefault())
function trustedSender(event: Electron.IpcMainInvokeEvent) {
const frame = event.senderFrame
return !win.isDestroyed() && event.sender === win.webContents && frame && frame === win.webContents.mainFrame &&
frame.url.split('#')[0] === appURL
}
ipcMain.handle('device:sign', (event, username: unknown, challenge: unknown) => {
if (!trustedSender(event) || typeof username !== 'string' || typeof challenge !== 'string') {
throw new Error('设备签名请求来源无效')
}
return signChallenge(api, username, challenge)
})
registerBrowserHandlers(trusted)
ipcMain.handle('browser:open', (event) => {
if (!trustedSender(event)) throw new Error('浏览器入口来源无效')
openBrowser(trusted)
})
await win.loadURL(appURL)
}
if (!app.requestSingleInstanceLock()) {
app.quit()
} else {
app.whenReady().then(start).catch((error: Error) => {
console.error(error.message)
app.exit(1)
})
app.on('second-instance', () => {
const win = BrowserWindow.getAllWindows()[0]
if (win?.isMinimized()) win.restore()
win?.focus()
})
app.on('window-all-closed', () => app.quit())
}
+9
View File
@@ -0,0 +1,9 @@
import { contextBridge, ipcRenderer } from 'electron'
const apiArgument = process.argv.find((value) => value.startsWith('--xhchat-api='))
contextBridge.exposeInMainWorld('xhchat', {
apiBase: apiArgument?.slice('--xhchat-api='.length),
signChallenge: (username: string, challenge: string) => ipcRenderer.invoke('device:sign', username, challenge),
openBrowser: () => ipcRenderer.invoke('browser:open'),
})