Files
XHChat/Desktop/src/main.ts
T

191 lines
9.1 KiB
TypeScript

import { app, BrowserWindow, ipcMain, Notification, 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()
if (process.platform === 'win32' && !app.isPackaged) app.setAppUserModelId(process.execPath)
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)
const brandAsset = url.pathname === '/brand/xhchat.png' || url.pathname === '/brand/xhchat.ico'
if (url.host !== 'app' || request.method !== 'GET' ||
(!root && !browserAsset && !mlsAsset && !brandAsset && !/^\/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' : brandAsset ? (url.pathname.endsWith('.ico') ? 'image/x-icon' : 'image/png') :
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 'self' 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({
icon: join(renderer, 'brand/xhchat.ico'),
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 groupNotification: Notification | undefined
let lastGroupNotification = 0
ipcMain.handle('notification:group-supported', (event) => trustedSender(event) && Notification.isSupported())
ipcMain.handle('notification:group-show', (event) => {
if (!trustedSender(event) || !Notification.isSupported() || (win.isFocused() && !win.isMinimized())) return
const now = Date.now()
if (now - lastGroupNotification < 2500) return
lastGroupNotification = now
groupNotification?.close()
const notification = new Notification({ title: 'XHChat', body: '有新的群消息', icon: join(renderer, 'brand/xhchat.png') })
groupNotification = notification
const release = () => { if (groupNotification === notification) groupNotification = undefined }
notification.once('close', release)
notification.once('failed', release)
notification.once('click', () => {
release()
if (win.isDestroyed()) return
if (win.isMinimized()) win.restore()
win.show()
win.focus()
})
notification.show()
})
ipcMain.handle('notification:group-close', (event) => {
if (!trustedSender(event)) return
groupNotification?.close()
groupNotification = undefined
})
win.on('closed', () => groupNotification?.close())
let microphoneUntil = 0
let microphonePage = ''
function recordingPage(url: string) {
if (!url.startsWith(appURL)) return false
return /^#\/(chat|groups)\/[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(url.slice(appURL.length))
}
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() === microphonePage &&
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) => {
const page = event.senderFrame?.url ?? ''
if (!trustedSender(event) || !recordingPage(page)) {
throw new Error('录音请求来源无效')
}
microphonePage = page
microphoneUntil = Date.now() + 30_000
})
ipcMain.handle('voice:end', (event) => {
if (!trustedSender(event)) throw new Error('录音请求来源无效')
microphonePage = ''
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())
}