接通 Windows 与 Web 设备间加密文字聊天

This commit is contained in:
xhgit committed 2026-11-13 18:43:04 +08:00
1 parent b04034ee89
commit d1efdedc57
27 files changed
+880 -22

No files matched your search

+20 -4
View File
@@ -25,6 +25,13 @@ export async function signChallenge(server: string, username: string, challenge:
if (!/^[a-z0-9_]{3,32}$/.test(username) || !/^[A-Za-z0-9_-]{43}$/.test(challenge)) {
throw new Error('设备验证参数无效')
}
const key = await deviceKey(server, username)
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 }
}
async function deviceKey(server: string, username: string) {
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'))
@@ -33,8 +40,17 @@ export async function signChallenge(server: string, username: string, challenge:
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 }
return pending
}
export async function signMls(server: string, username: string, kind: string, user: string, device: string, value: Uint8Array) {
const id = /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/
if (!/^[a-z0-9_]{3,32}$/.test(username) || !id.test(user) || !id.test(device) ||
!(value instanceof Uint8Array) ||
!(kind === 'credential' && value.length === 32 ||
kind === 'KeyPackage' && value.length >= 32 && value.length <= 8192)) {
throw new Error('MLS 签名参数无效')
}
const key = await deviceKey(server, username)
return new Uint8Array(sign(null, Buffer.concat([Buffer.from('XHChat MLS ' + kind + ' v1\n' + user + '\n' + device + '\n'), value]), key))
}
+32 -6
View File
@@ -1,7 +1,7 @@
import { app, BrowserWindow, ipcMain, protocol, session } from 'electron'
import { app, BrowserWindow, ipcMain, protocol, safeStorage, session } from 'electron'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { signChallenge } from './identity'
import { signChallenge, signMls } from './identity'
import { openBrowser, registerBrowserHandlers } from './browser'
const appURL = 'xhchat://app/'
@@ -35,17 +35,21 @@ async function start() {
['/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 && !/^\/assets\/[a-zA-Z0-9_.-]+\.(?:js|css)$/.test(url.pathname))) {
(!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'; style-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
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': html ? 'text/html; charset=utf-8' : url.pathname.endsWith('.css') ? 'text/css' : 'application/javascript',
'Content-Security-Policy': browserAsset ? policy : policy + '; connect-src ' + api + ' ' + websocket,
'Content-Type': type,
'Content-Security-Policy': browserAsset ? policy : policy + "; connect-src 'self' " + api + ' ' + websocket,
'X-Content-Type-Options': 'nosniff',
} })
} catch {
@@ -75,6 +79,28 @@ async function start() {
}
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) => {
if (!trustedSender(event)) throw new Error('浏览器入口来源无效')
+4
View File
@@ -6,4 +6,8 @@ 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'),
signMls: (username: string, kind: string, user: string, device: string, value: Uint8Array) =>
ipcRenderer.invoke('device:sign-mls', username, kind, user, device, value),
protectMls: (key: string) => ipcRenderer.invoke('device:protect-mls', key),
unprotectMls: (key: string) => ipcRenderer.invoke('device:unprotect-mls', key),
})