import { app, BrowserWindow, ipcMain, protocol, safeStorage, session } from 'electron' import { readFile } from 'node:fs/promises' import { join } from 'node:path' import { signChallenge, signMls } from './identity' import { openBrowser, registerBrowserHandlers, website } 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) const mlsAsset = /^\/mls\/xhchat_mls_check(?:\.js|_bg\.wasm)$/.test(url.pathname) if (url.host !== 'app' || request.method !== 'GET' || (!root && !browserAsset && !mlsAsset && !/^\/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'" + (browserAsset ? '' : " 'wasm-unsafe-eval'") + "; style-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" const type = html ? 'text/html; charset=utf-8' : url.pathname.endsWith('.css') ? 'text/css' : url.pathname.endsWith('.wasm') ? 'application/wasm' : 'application/javascript' return new Response(bytes, { headers: { 'Content-Type': type, 'Content-Security-Policy': browserAsset ? policy : policy + "; img-src blob:; media-src blob:; connect-src 'self' " + 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 } let microphoneUntil = 0 function voicePermission(contents: Electron.WebContents | null, url: string, mainFrame: boolean, permission: string, types: string[]) { return !win.isDestroyed() && contents === win.webContents && mainFrame && url.split('#')[0] === appURL && win.webContents.getURL().startsWith(appURL + '#/chat/') && Date.now() <= microphoneUntil && permission === 'media' && types.length === 1 && types[0] === 'audio' } trusted.setPermissionCheckHandler((contents, permission, _origin, details) => voicePermission(contents, details.requestingUrl ?? '', details.isMainFrame, permission, details.mediaType ? [details.mediaType] : [])) trusted.setPermissionRequestHandler((contents, permission, callback, details) => callback(voicePermission(contents, details.requestingUrl, details.isMainFrame, permission, 'mediaTypes' in details ? details.mediaTypes ?? [] : []))) ipcMain.handle('voice:allow', (event) => { if (!trustedSender(event) || !event.senderFrame?.url.startsWith(appURL + '#/chat/')) { throw new Error('录音请求来源无效') } microphoneUntil = Date.now() + 30_000 }) ipcMain.handle('voice:end', (event) => { if (!trustedSender(event)) throw new Error('录音请求来源无效') microphoneUntil = 0 }) 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) }) ipcMain.handle('device:sign-mls', (event, username: string, kind: string, user: string, device: string, value: Uint8Array) => { if (!trustedSender(event) || [username, kind, user, device].some((input) => typeof input !== 'string')) { throw new Error('设备签名请求来源无效') } return signMls(api, username, kind, user, device, value) }) ipcMain.handle('device:protect-mls', (event, key: unknown) => { if (!trustedSender(event) || !safeStorage.isEncryptionAvailable() || typeof key !== 'string' || !/^[A-Za-z0-9+/]{43}=$/.test(key)) { throw new Error('系统密钥保护不可用') } return safeStorage.encryptString(key).toString('base64') }) ipcMain.handle('device:unprotect-mls', (event, wrapped: unknown) => { if (!trustedSender(event) || !safeStorage.isEncryptionAvailable() || typeof wrapped !== 'string' || wrapped.length > 2048 || !/^[A-Za-z0-9+/=]+$/.test(wrapped)) { throw new Error('系统密钥保护不可用') } const key = safeStorage.decryptString(Buffer.from(wrapped, 'base64')) if (!/^[A-Za-z0-9+/]{43}=$/.test(key)) throw new Error('会话存储密钥无效') return key }) registerBrowserHandlers(trusted) ipcMain.handle('browser:open', (event, url: unknown) => { if (!trustedSender(event)) throw new Error('浏览器入口来源无效') const initial = typeof url === 'string' && url.length <= 4096 ? website(url) : undefined if (url !== undefined && !initial) throw new Error('网页地址无效') openBrowser(trusted, false, initial) }) 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()) }