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

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

+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())
}