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

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 @@
**/node_modules
**/dist
**/test-results
.env
.git
docs
Android
server
+5
View File
@@ -0,0 +1,5 @@
# Generate a random hex value before startup.
XHCHAT_DB_PASSWORD=
XHCHAT_PORT=8080
XHCHAT_WEB_ORIGIN=http://127.0.0.1:8080
# XHCHAT_GOPROXY=https://proxy.golang.org,direct
+30
View File
@@ -0,0 +1,30 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>XHChat 浏览器</title>
<link rel="stylesheet" href="/browser/style.css">
<script defer src="/browser/ui.js"></script>
</head>
<body>
<header>
<div class="tabs"><div id="tabs" aria-label="标签页"></div><button data-action="new" aria-label="新建标签页">+</button><span id="mode"></span></div>
<form id="address-form">
<button type="button" data-action="back" aria-label="后退">←</button>
<button type="button" data-action="forward" aria-label="前进">→</button>
<button type="button" data-action="reload" aria-label="刷新">↻</button>
<input id="address" aria-label="网址或搜索关键词" placeholder="输入网址或搜索关键词" autocomplete="off" maxlength="4096">
<button>打开</button>
<button type="button" data-action="copy" aria-label="复制网址">复制</button>
<button type="button" data-action="external" aria-label="系统浏览器打开">↗</button>
<button type="button" data-action="zoomOut" aria-label="缩小">−</button>
<button type="button" data-action="zoomIn" aria-label="放大">+</button>
<button type="button" data-action="fullscreen" aria-label="全屏">⛶</button>
<button type="button" data-action="private">隐私窗口</button>
<button type="button" data-action="clear">清除数据</button>
</form>
<div id="status" role="status"></div>
</header>
</body>
</html>
+19
View File
@@ -0,0 +1,19 @@
* { box-sizing: border-box; }
:root { color-scheme: light dark; font: 13px/1.4 system-ui, "Microsoft YaHei UI", sans-serif; }
body { margin: 0; background: Canvas; color: CanvasText; }
header { height: 102px; background: light-dark(#f0f5f2,#1e2924); }
.tabs, #tabs, form { display: flex; align-items: center; gap: 5px; min-width: 0; }
.tabs { padding: 5px 8px 0; height: 34px; }
#tabs { overflow-x: auto; scrollbar-width: thin; }
.tab { display: flex; align-items: center; border-radius: 6px; background: light-dark(#e2ebe5,#293d33); }
.tab.active { background: light-dark(#cde4d6,#3f6050); }
.tab button:first-child { max-width: 140px; overflow: hidden; text-overflow: ellipsis; }
button, input { font: inherit; color: inherit; border: 1px solid light-dark(#cbd8d0,#4a6154); border-radius: 6px; background: Canvas; padding: 4px 7px; }
button { cursor: pointer; white-space: nowrap; }
button:disabled { opacity: .5; cursor: default; }
.tab button { border: 0; background: transparent; }
form { padding: 6px 8px 2px; }
input { flex: 1; min-width: 0; }
#status { padding: 0 10px; color: light-dark(#943f42,#ffb3b9); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
#mode { margin-left: auto; white-space: nowrap; }
@media (max-width: 750px) { form [data-action="zoomIn"], form [data-action="zoomOut"] { display: none; } }
+57
View File
@@ -0,0 +1,57 @@
const api = window.xhchatBrowser
const tabs = document.querySelector('#tabs')
const address = document.querySelector('#address')
const status = document.querySelector('#status')
const button = (action) => document.querySelector(`[data-action="${action}"]`)
let current
function render(state) {
current = state
tabs.replaceChildren(...state.tabs.map((tab) => {
const element = document.createElement('span')
element.className = tab.id === state.active ? 'tab active' : 'tab'
const title = document.createElement('button')
title.textContent = tab.title
title.setAttribute('aria-pressed', String(tab.id === state.active))
title.onclick = () => { address.blur(); void command('activate', tab.id) }
const close = document.createElement('button')
close.textContent = '×'
close.setAttribute('aria-label', '关闭 ' + tab.title)
close.onclick = () => void command('close', tab.id)
element.append(title, close)
return element
}))
if (document.activeElement !== address) address.value = state.url
button('back').disabled = !state.back
button('forward').disabled = !state.forward
button('reload').textContent = state.loading ? '×' : '↻'
button('reload').setAttribute('aria-label', state.loading ? '停止加载' : '刷新')
for (const action of ['copy', 'external', 'zoomIn', 'zoomOut']) button(action).disabled = !state.url
document.querySelector('#mode').textContent = state.privateMode ? '隐私窗口' : ''
status.textContent = state.error
}
async function command(action, value) {
try {
render(await api.command(action, value))
} catch (error) {
status.textContent = error.message
}
}
for (const element of document.querySelectorAll('[data-action]')) {
element.onclick = () => {
const action = element.dataset.action
void command(action === 'reload' && current?.loading ? 'stop' : action)
}
}
document.querySelector('#address-form').onsubmit = (event) => {
event.preventDefault()
const value = address.value
address.blur()
void command('go', value)
}
api.onState(render)
void command('state')
+1
View File
@@ -0,0 +1 @@
{"name":"@xhchat/desktop","productName":"XHChat","version":"0.1.0","private":true,"main":"dist/main.js","scripts":{"check":"tsc --noEmit","build":"tsc","start":"npm run build && electron ."},"devDependencies":{"electron":"45.3.1","typescript":"~6.0.3","@types/node":"^24.0.0"}}
+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'),
})
+8
View File
@@ -0,0 +1,8 @@
{
"compilerOptions": {
"target":"ES2022", "module":"Node16", "moduleResolution":"Node16",
"strict":true, "rootDir":"src", "outDir":"dist",
"esModuleInterop":true, "skipLibCheck":true
},
"include":["src/**/*.ts"]
}
+1 -1
View File
@@ -2,7 +2,7 @@
本仓库公开源码供查阅,修改、分发与部署需经权利人书面授权。禁止将查阅权限用于违法活动。详见 [XHChat 源码查阅许可协议](LICENSE)。
Windows 桌面端位于 `Desktop`,Web 客户端位于 `web`。当前版本实现用户名注册和登录、独立设备身份、设备查看与撤销、退出登录及经认证的实时连接。完整产品按 [阶段进度](docs/progress.md) 交付。
Windows 桌面端位于 `Desktop`,Web 客户端位于 `web`。当前版本实现用户名注册与登录、设备管理、实时联系人管理和隔离的 Chromium 浏览器窗口。完整产品按 [阶段进度](docs/progress.md) 交付。
## 本地运行
+30
View File
@@ -0,0 +1,30 @@
map $http_upgrade $xhchat_connection {
default upgrade;
'' close;
}
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
server_tokens off;
access_log off;
client_max_body_size 8k;
add_header Content-Security-Policy "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'" always;
add_header Referrer-Policy no-referrer always;
add_header X-Content-Type-Options nosniff always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
location /api/ {
proxy_pass http://api:8080;
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $xhchat_connection;
proxy_read_timeout 90s;
}
location = /healthz { proxy_pass http://api:8080; }
location = /readyz { proxy_pass http://api:8080; }
location / { try_files $uri $uri/ =404; }
}
+60
View File
@@ -0,0 +1,60 @@
name: xhchat
services:
postgres:
image: postgres:18-alpine
environment:
POSTGRES_DB: xhchat
POSTGRES_USER: xhchat
POSTGRES_PASSWORD: ${XHCHAT_DB_PASSWORD:?Set XHCHAT_DB_PASSWORD in .env}
volumes:
- postgres:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U xhchat -d xhchat"]
interval: 5s
timeout: 3s
retries: 15
redis:
image: redis:8-alpine
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 15
api:
build:
context: ./server
args:
GOPROXY: ${XHCHAT_GOPROXY:-https://proxy.golang.org,direct}
environment:
XHCHAT_ADDR: 0.0.0.0:8080
DATABASE_URL: postgres://xhchat:${XHCHAT_DB_PASSWORD}@postgres:5432/xhchat?sslmode=disable
REDIS_URL: redis://redis:6379/0
XHCHAT_ORIGINS: ${XHCHAT_WEB_ORIGIN:-http://127.0.0.1:8080},xhchat://app
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "-qO", "/dev/null", "http://127.0.0.1:8080/readyz"]
interval: 5s
timeout: 3s
retries: 15
web:
build:
context: .
dockerfile: web/Dockerfile
depends_on:
api:
condition: service_healthy
ports:
- "127.0.0.1:${XHCHAT_PORT:-8080}:80"
healthcheck:
test: ["CMD", "wget", "-qO", "/dev/null", "http://127.0.0.1/readyz"]
interval: 5s
timeout: 3s
retries: 10
volumes:
postgres:
+25
View File
@@ -0,0 +1,25 @@
# API 设计
所有业务接口使用 /api/v1,JSON 请求及响应。受保护接口通过 Authorization Bearer 接收短期会话令牌。错误结构为 `{"error":{"code":"…","message":"…"}}`。Web 与桌面端各自持有会话。服务端只保存令牌摘要。
| 方法 | 路径 | 请求与响应 |
|---|---|---|
| GET | /healthz、/readyz | 分别检查进程和 PostgreSQL、Redis |
| POST | /api/v1/auth/challenge | 返回 2 分钟单次使用的 challenge |
| POST | /api/v1/auth/register | 接收 username、password、deviceName、platform、publicKey、challenge、signature,返回 201 和 token、user、device |
| POST | /api/v1/auth/login | 同上,返回 200 |
| POST | /api/v1/auth/logout | 使当前会话失效,返回 204 |
| GET | /api/v1/me | 返回账号和当前设备 |
| GET | /api/v1/devices | 返回当前账号的设备列表,signedIn 表示有未过期会话,lastActiveAt 来自登录与 WebSocket 心跳 |
| DELETE | /api/v1/devices/{id} | 撤销指定设备和其全部会话,返回 204 |
| POST | /api/v1/realtime/ticket | 返回 30 秒单次 WebSocket 票据 |
| GET | /api/v1/realtime | 通过子协议 xhchat.v1 和 ticket.票据升级,服务器选择 xhchat.v1,连接建立后发送 ready 事件 |
| GET | /api/v1/contacts | 返回好友、来往申请和当前账号的黑名单 |
| GET | /api/v1/contacts/search?username= | 按完整用户名查找,返回可见的联系人状态 |
| POST | /api/v1/contacts/{id} | 请求体包含 action,可选 alias 和 category,成功返回 204 |
用户名为 3–32 位 ASCII 字母、数字或下划线,忽略大小写。密码最少 12 个 Unicode 字符,最多 256 字节。platform 为 web 或 windows。公钥、签名和 challenge 使用无填充 Base64URL。设备使用 Ed25519 签名 UTF-8 字符串 `XHChat device authentication v1\n` 后紧接 challenge。该签名仅用于证明基础设备密钥持有权。
联系人操作包含 request、accept、reject、cancel、delete、block、unblock 和 preferences。变更后 WebSocket 发送 contacts_changed,客户端重新获取授权后的列表。
下一阶段接口为 /conversations、/conversations/{id}/envelopes、/sync、/attachments、/key-packages。消息接口接受版本化协议密文、目标会话和幂等 ID。WebSocket 发出同步提示,客户端按持久游标补拉。后续加入 /groups、/calls、/posts、/backups、/push 与独立的管理接口。
+30
View File
@@ -0,0 +1,30 @@
# XHChat 技术可行性与总体架构
Windows 和 Web 可共用 Vue 3、TypeScript、Pinia 和 Vue Router。Go 服务以模块化单体起步,按身份、设备、联系人、投递、群组、文件、信令、动态与管理划定接口。PostgreSQL 保存权威状态,Redis 负责限流、短期票据和实时事件分发,S3 兼容存储承载附件密文。服务按部署量拆分时保持相同的 REST 和 WebSocket 契约。桌面端使用随包发布的受信任应用资源,网页通过 Nginx 与 API 同源部署。Android、iOS 和其他桌面系统使用同一协议,各自实现平台密钥存储。
功能交付按需求的八阶段推进。阶段一优先闭环用户名注册、密码登录、独立设备身份、设备列表与撤销、WebSocket 会话及容器部署。阶段二到三交付加密私聊、附件、离线投递、加密群组、可信设备授权和备份。阶段四交付 WebRTC、TURN、SFU 与媒体 E2EE。阶段五交付内置浏览器。阶段六到八交付社交、扩展生态、独立管理后台完善、发布与运维。短信、邮件、支付和推送使用各部署方的凭据,验收使用实际接通的服务。
端到端加密的可行性取决于同一协议库在浏览器和桌面的兼容性,以及设备认证、密钥持久化和撤销的集成验证。音视频需要验证目标浏览器的编码帧变换支持及跨网络 TURN 转发。普通网页浏览与通讯端的密钥和会话数据使用不同 Electron 会话。网页客户端通过系统浏览器打开第三方链接。
## 目录设计
```text
XHChat/
Desktop/ Electron 主进程、preload、打包、独立浏览器
web/ Vue 客户端与可打包的渲染层
Android/ 后续 Android 客户端
server/
cmd/api/ API 入口
internal/config/ 环境配置
internal/account/ 账号、会话、设备身份
internal/httpapi/ HTTP 和 WebSocket 边界
internal/database/ 迁移与连接
internal/{contacts,delivery,groups,files,calls,social,admin}/ 后续模块
admin/ 独立管理前端
deploy/ Nginx、TLS、TURN、SFU、备份恢复
tests/ 双端集成、隔离和验收脚本
docs/ API、数据库、安全设计与验收记录
docker-compose.yml
```
管理端计划使用独立域名、凭据和数据库角色。指标聚合使用投递计数、调用状态和基础设施容量。管理角色只需接触运营元数据。
+11
View File
@@ -0,0 +1,11 @@
# 浏览器安全架构
受信任的聊天与浏览器工具栏从随包静态资源加载。第三方网页进入独立 WebContentsView 和单独 Session,禁用 Node、preload 与 webview,启用 sandbox、contextIsolation、webSecurity。普通与隐私模式使用不同分区,隐私窗口销毁后清理其临时分区。主进程校验 IPC 的 WebContents、主帧、来源和参数。应用自定义协议只注册到受信任会话,资源查找使用固定目录和可访问资源边界。 [Electron 安全指南](https://www.electronjs.org/docs/latest/tutorial/security) · [Electron Web 嵌入](https://www.electronjs.org/docs/latest/tutorial/web-embeds/)
内置浏览器将以 Chromium 的真实 UA 追加 XHChat/版本,保留 UA-CH 默认协商并用测试站检查一致性。导航、重定向和新窗口只接受允许的网络协议。摄像头、麦克风、剪贴板、通知与位置默认拒绝,后续按可信 UI 中的顶级网站授权。下载由可信 UI 确认路径及来源。恶意站点警告机制需要评估信誉服务、误报与隐私影响。
聊天链接卡片由发送者主动请求预览。若采用代理,部署独立网络出口并在每次重定向及实际建连时校验公网目的地址,限制响应类型、体积、超时与跳转次数。代理只接收明确提交的 URL,卡片由客户端随 E2EE 消息传输。安全验收包含远程网页的权限拒绝、无特权对象、无通讯存储可见性和自定义协议隔离。
## 威胁模型
攻击者包括被动窃听者、恶意联系人、被撤销设备、第三方网页、服务端入侵者和能修改 Web 发布内容的操作者。服务端可见投递及账号元数据,不能解密内容。服务端若能操纵设备目录,端侧必须通过可信设备授权与可验证身份限制密钥替换。受控发布、签名安装包、依赖锁定、CSP 与最小权限用于降低执行恶意代码的风险。设备已解锁且被完全控制时,应用不能保护当前可解密内容。
+17
View File
@@ -0,0 +1,17 @@
# 数据库设计
| 关系 | 关键约束与职责 |
|---|---|
| users | UUID 主键,规范化用户名唯一,密码保存 Argon2id PHC,记录创建时间 |
| devices | UUID 主键,用户外键,用户内公钥唯一,记录平台、首次和最近活动时间、撤销时间 |
| sessions | 高熵令牌的 SHA-256 摘要为主键,关联设备,包含到期时间 |
| contact_relationships、contact_blocks、contact_preferences | 关系按账号对去重,拉黑有方向,私有备注按拥有者授权 |
| conversations、memberships | 会话与成员关系,记录角色和生效世代 |
| device_credentials、key_packages | 公开凭据及一次性密钥包,事务领取,撤销后停止发放 |
| envelopes、deliveries | 二进制协议密文、投递游标和目标设备,按客户端消息 ID 幂等 |
| attachments、backups | 对象存储标识、密文尺寸、配额和版本,密钥由端侧传递 |
| calls、call_participants | 通话状态、参与设备和时间,不存媒体 |
| posts、post_audiences、reactions | 私人动态正文为密文,受众变更触发重新分发或换钥 |
| admin_audit | 管理员、行为、目标标识、时间和结果 |
迁移 001 创建身份相关表。迁移 002 添加联系人关系、黑名单和备注。设备撤销和会话清除在同一个事务内处理。阶段二以事务分配单调投递游标,连接恢复后从持久层补拉。消息保留和附件清理分别由后台作业处理,下载授权按目标设备和对象关联重新检查。
+9
View File
@@ -0,0 +1,9 @@
# 部署与维护
当前 Compose 启动 Nginx、Go API、PostgreSQL 和 Redis。PostgreSQL 与 Redis 仅供 Compose 网络使用。Nginx 的端口默认绑定本机。所有服务健康后,通过 /readyz 验证数据库与缓存。
使用自定义域名时,将 XHCHAT_WEB_ORIGIN 设置为实际的 HTTPS 源,使用 TLS 反向代理转发到 127.0.0.1 上的 Compose 端口。反向代理应转发 Host、WebSocket Upgrade 与 Connection,配置证书续期和 HSTS。桌面端的 XHCHAT_SERVER_URL 指向同一 HTTPS 源。应用凭据及数据库连接信息由部署方提供。数据库密码使用十六进制字符串,避免连接 URL 的保留字符。正式环境需要数据库角色分离、备份演练、容量与限流调优。
使用 `docker compose logs api` 检查应用日志。停止服务用 `docker compose down`。PostgreSQL 的数据由 Compose 命名卷保存。
使用 `pg_dump` 生成数据库备份,备份包含账号与设备元数据,应在受控环境加密保存。使用 `pg_restore` 恢复到独立数据库,执行迁移与 API 验证后切换服务。恢复时清除历史会话并重建 Redis 短期状态。阶段一暂无聊天和附件数据。
+9
View File
@@ -0,0 +1,9 @@
# 加密架构
优先验证 RFC 9420 MLS。私聊以两个账号的可信设备组成会话,群聊采用同一协议。每台设备单独作为成员加入,安全码和二维码验证绑定账号信任根。X3DH / PQXDH、Double Ratchet 与 Sesame 是 Signal 私聊和多设备的候选组合。官方 libsignal 提供原生及 Node.js 等绑定,采用 AGPL,Web 构建及分发模式需要额外评估。OpenMLS 采用 MIT,公开 CI 将 WASM 列为构建但未测试的平台。mls-rs 支持 RFC 9420,公开文档将 Web Crypto 提供者标为实验性并说明尚无完整第三方安全审计。实现暂未定版。 [Signal 规范](https://signal.org/docs/) · [libsignal](https://github.com/signalapp/libsignal) · [MLS 协议](https://datatracker.ietf.org/doc/html/rfc9420) · [MLS 架构](https://datatracker.ietf.org/doc/html/rfc9750) · [OpenMLS](https://github.com/openmls/openmls) · [mls-rs](https://github.com/awslabs/mls-rs)
基础设备密钥使用 Ed25519 及标准库。Web 用不可导出的 CryptoKey 持久化到 IndexedDB,桌面用系统安全存储加密私钥。阶段一账号登录创建的设备身份仅用于服务认证。加入 E2EE 会话还需要既有可信设备授权或显式重建信任。服务端只保存公钥。账号找回不能重建聊天密钥。设备撤销必须同时取消投递权限与 MLS 成员资格,客户端完成新世代提交后才可发送。新成员默认只能读取加入后的内容。
协议选型验收包括固定版本与依赖、公开审计覆盖、RFC 向量、独立实现互通、离线 Commit 重放、并发世代、恶意服务端替换密钥、存储中断与恢复、已撤销设备不能解密新内容。客户端需要原子提交协议状态与待发送密文,避免重试时复用发送状态。前向保密与入侵后恢复取决于 MLS 世代更新、旧秘密清除和对手退出设备。
附件采用公开的分块认证加密格式,评估带明确结束认证与大文件恢复语义的实现。每份附件生成独立随机密钥,密文通过对象存储分发,文件密钥及完整性元数据放在 E2EE 消息中。备份使用独立随机恢复秘密,显式确认恢复权限和完整性,服务端只存密文及版本。私人动态按受众分发密钥。Web 应用以同源、受控发布和严格 CSP 管理脚本信任,当前页面的恶意同源脚本属于独立威胁。
+30
View File
@@ -0,0 +1,30 @@
# 开发与验收记录
## 2026-11-13 · 阶段一基础交付
Web 和 Electron 共用 Vue 客户端,独立接入同一 Go API。真实 PostgreSQL 迁移创建账号、设备和会话表。Redis 用于限流、单次设备验证挑战和 WebSocket 票据。Windows 使用 Electron safeStorage 持久化设备私钥。Web 使用 IndexedDB 中的不可导出 Ed25519 CryptoKey。会话令牌只保存在客户端进程内存中,刷新网页或重启应用需要重新登录。
| 验收项 | 结果 |
|---|---|
| Go 单元测试 | 覆盖 Ed25519 签名、挑战绑定、Argon2id 密码验证与盐值 |
| Web、Electron 构建 | Vue 与 TypeScript 构建通过 |
| Compose 启动 | Nginx、Go API、PostgreSQL、Redis 健康检查通过 |
| 真实 API 集成 | 覆盖注册、重复用户名、错误密码、登录、设备状态、跨账号撤销拒绝、来源校验、挑战与票据重放拒绝、退出和撤销 |
| Edge 与 Electron 交叉测试 | Web 注册后用 Windows 登录,从 Web 撤销 Windows 设备,实时会话结束并返回登录页 |
| 端侧检查 | Web 私钥不可导出,Electron 渲染层没有 Node require,390px Web 设备页无横向溢出 |
| 依赖扫描 | Go 1.27.1 升级至 1.27.4 后,govulncheck 未报告漏洞。npm audit 未报告漏洞 |
两套集成测试使用随机账号和随机密码。测试账号留在本机开发数据库中,复跑时使用新账号。
## 尚待实现
- 阶段一还需邮箱和手机号注册、验证码服务、找回密码和双重验证。真实联调需要 SMTP 与短信供应商配置。
- 阶段二与三还需定版并验证双端 E2EE,交付私聊、附件、离线消息、群聊、多设备可信授权、加密备份与同步。当前基础设备认证没有消息密钥能力。
- 阶段四还需 WebRTC 音视频、TURN、SFU、屏幕共享及媒体 E2EE。
- 阶段五还需持久书签和历史、下载记录、逐站授权、反钓鱼及聊天联动。
- 阶段六到八还需社交、扩展生态、独立管理后台、推送、生产部署与备份演练、压力测试、安全评估、签名安装包和发布流程。
## 联系人和 Chromium 浏览器
- 双端支持用户名查找、申请、接受、拒绝、撤回申请、备注、分组、删除、拉黑和解除拉黑。测试以 Web 与 Electron 两个账号验证申请和变更实时同步。
- 桌面端提供隔离浏览器窗口,支持地址栏、搜索、标签、导航、缩放、全屏、复制链接、普通窗口下载、隐私窗口和清除站点数据。集成测试确认远程网页位于独立 Session,Sandbox 生效,网页无 IPC 桥和 Node require,UA 保留真实 Chromium 版本并追加 XHChat 标识。测试同时验证地址栏拒绝本地文件协议。
+7
View File
@@ -0,0 +1,7 @@
# 音视频架构
信令经 Go API 和 WebSocket 传输,按参与设备授权。通话状态机处理邀请、响铃、接听、拒绝、占线、重连和结束。邀请及 SDP 指纹应由已验证的设备绑定至 E2EE 会话,ICE 及信令日志只记录必要状态。
一对一使用 WebRTC 和 ICE,直连失败时通过 coturn 转发。TURN 凭据短期有效,并配置目的地址限制、带宽配额和公开中继端口。多人通话选型优先验证 LiveKit SFU 与其 Web SDK 的媒体 E2EE,核查固定版本、许可证、加密实现及浏览器支持。通过 RFC 9605 SFrame 或通过评估的等效实现保护音频、视频和屏幕共享。密钥由端侧授权会话提供,加入、退出或撤销时轮换。客户端在加密能力缺失或变换失败时停止发布媒体。TURN 转发数据和 SFU 可观察的网络元数据纳入威胁模型。 [coturn](https://github.com/coturn/coturn) · [SFrame RFC](https://www.rfc-editor.org/info/rfc9605/) · [LiveKit 加密](https://docs.livekit.io/transport/encryption/)
验收覆盖 Windows↔Web 两个发起方向、直连和强制 TURN、多人加入与移除、媒体权限拒绝、屏幕共享、切网恢复、SFU 无法解密及不支持环境阻止发布。
+2067
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
{"name":"xhchat","private":true,"workspaces":["web","Desktop"],"scripts":{"build":"npm run build -w web","desktop":"npm run start -w Desktop","check":"npm run check -w web && npm run check -w Desktop"},"devDependencies":{"playwright":"1.65.0","ws":"8.23.0"}}
+14
View File
@@ -0,0 +1,14 @@
FROM golang:1.27.4-alpine AS build
WORKDIR /src
ARG GOPROXY=https://proxy.golang.org,direct
ENV GOPROXY=${GOPROXY}
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -o /out/xhchat-api ./cmd/api
FROM alpine:3.23
COPY --from=build /out/xhchat-api /usr/local/bin/xhchat-api
USER 65532:65532
EXPOSE 8080
ENTRYPOINT ["xhchat-api"]
+99
View File
@@ -0,0 +1,99 @@
package main
import (
"context"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"xhchat/server/internal/account"
"xhchat/server/internal/config"
"xhchat/server/internal/contacts"
"xhchat/server/internal/database"
"xhchat/server/internal/httpapi"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
)
func main() {
if err := run(); err != nil {
slog.Error("XHChat API stopped", "error", err)
os.Exit(1)
}
}
func run() error {
cfg, err := config.Load()
if err != nil {
return err
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
startup, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
db, err := pgxpool.New(startup, cfg.DatabaseURL)
if err != nil {
return errors.New("invalid database configuration")
}
defer db.Close()
options, err := redis.ParseURL(cfg.RedisURL)
if err != nil {
return errors.New("invalid Redis configuration")
}
cache := redis.NewClient(options)
defer cache.Close()
ready := func(ctx context.Context) error {
if err := db.Ping(ctx); err != nil {
return err
}
return cache.Ping(ctx).Err()
}
if err := ready(startup); err != nil {
return fmt.Errorf("dependencies not ready (%T)", err)
}
if err := database.Migrate(startup, db); err != nil {
return fmt.Errorf("database migration failed (%T)", err)
}
cancel()
accounts := account.New(db, cfg.SessionTTL)
go func() {
ticker := time.NewTicker(15 * time.Minute)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
cleanup, cancel := context.WithTimeout(ctx, 10*time.Second)
if err := accounts.Cleanup(cleanup); err != nil {
slog.Warn("session cleanup failed")
}
cancel()
}
}
}()
server := &http.Server{
Addr: cfg.Addr, Handler: httpapi.New(accounts, contacts.New(db), cache, cfg.Origins, ready),
ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second,
WriteTimeout: 15 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10,
BaseContext: func(net.Listener) context.Context { return ctx },
}
server.RegisterOnShutdown(stop)
done := make(chan error, 1)
go func() { done <- server.ListenAndServe() }()
select {
case err := <-done:
return err
case <-ctx.Done():
shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return server.Shutdown(shutdown)
}
}
+21
View File
@@ -0,0 +1,21 @@
module xhchat/server
go 1.27.4
require (
github.com/coder/websocket v1.8.15
github.com/jackc/pgx/v5 v5.13.0
github.com/redis/go-redis/v9 v9.23.0
golang.org/x/crypto v0.59.0
)
require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.3 // indirect
go.uber.org/atomic v1.12.0 // indirect
golang.org/x/sync v0.25.0 // indirect
golang.org/x/sys v0.50.0 // indirect
golang.org/x/text v0.44.0 // indirect
)
+43
View File
@@ -0,0 +1,43 @@
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao=
github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+57
View File
@@ -0,0 +1,57 @@
package account
import (
"crypto/ed25519"
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"fmt"
"strings"
"golang.org/x/crypto/argon2"
)
const deviceProof = "XHChat device authentication v1\n"
var Encoding = base64.RawURLEncoding
func Secret() string {
var bytes [32]byte
rand.Read(bytes[:])
return Encoding.EncodeToString(bytes[:])
}
func Proof(publicKey, challenge, signature string) ([]byte, bool) {
key, keyErr := Encoding.DecodeString(publicKey)
sig, sigErr := Encoding.DecodeString(signature)
nonce, nonceErr := Encoding.DecodeString(challenge)
if keyErr != nil || sigErr != nil || nonceErr != nil || len(key) != ed25519.PublicKeySize || len(nonce) != 32 {
return nil, false
}
return key, ed25519.Verify(key, []byte(deviceProof+challenge), sig)
}
func PasswordHash(password string) string {
var salt [16]byte
rand.Read(salt[:])
key := derive(password, salt[:])
return fmt.Sprintf("$argon2id$v=19$m=65536,t=3,p=2$%s$%s",
base64.RawStdEncoding.EncodeToString(salt[:]), base64.RawStdEncoding.EncodeToString(key))
}
func VerifyPassword(password, hash string) bool {
fields := strings.Split(hash, "$")
if len(fields) != 6 || strings.Join(fields[:4], "$") != "$argon2id$v=19$m=65536,t=3,p=2" {
return false
}
salt, saltErr := base64.RawStdEncoding.DecodeString(fields[4])
key, keyErr := base64.RawStdEncoding.DecodeString(fields[5])
if saltErr != nil || keyErr != nil || len(salt) != 16 || len(key) != 32 {
return false
}
return subtle.ConstantTimeCompare(derive(password, salt), key) == 1
}
func derive(password string, salt []byte) []byte {
return argon2.IDKey([]byte(password), salt, 3, 64*1024, 2, 32)
}
+37
View File
@@ -0,0 +1,37 @@
package account
import (
"crypto/ed25519"
"crypto/rand"
"testing"
)
func TestDeviceProof(t *testing.T) {
public, private, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
challenge := Secret()
signature := Encoding.EncodeToString(ed25519.Sign(private, []byte(deviceProof+challenge)))
key := Encoding.EncodeToString(public)
if _, ok := Proof(key, challenge, signature); !ok {
t.Fatal("valid signature rejected")
}
if _, ok := Proof(key, Secret(), signature); ok {
t.Fatal("signature accepted for a different challenge")
}
if _, ok := Proof("invalid", challenge, signature); ok {
t.Fatal("invalid public key accepted")
}
}
func TestPasswordHash(t *testing.T) {
const password = "test password with sufficient length"
hash := PasswordHash(password)
if hash == PasswordHash(password) {
t.Fatal("salt was reused")
}
if !VerifyPassword(password, hash) || VerifyPassword("wrong", hash) || VerifyPassword(password, "malformed") {
t.Fatal("unexpected password verification result")
}
}
+210
View File
@@ -0,0 +1,210 @@
package account
import (
"context"
"crypto/sha256"
"errors"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
var (
ErrCredentials = errors.New("invalid credentials")
ErrDuplicate = errors.New("username already in use")
ErrRevoked = errors.New("device revoked")
)
type User struct {
ID string `json:"id"`
Username string `json:"username"`
}
type Device struct {
ID string `json:"id"`
Name string `json:"name"`
Platform string `json:"platform"`
CreatedAt time.Time `json:"createdAt"`
LastActiveAt time.Time `json:"lastActiveAt"`
RevokedAt *time.Time `json:"revokedAt,omitempty"`
SignedIn bool `json:"signedIn"`
}
type Identity struct {
User User `json:"user"`
Device Device `json:"device"`
}
type Auth struct {
Identity
Token string `json:"token"`
}
type Store struct {
db *pgxpool.Pool
ttl time.Duration
dummyHash string
}
func New(db *pgxpool.Pool, ttl time.Duration) *Store {
return &Store{db: db, ttl: ttl, dummyHash: PasswordHash(Secret())}
}
func (s *Store) Open(ctx context.Context, register bool, username, password, name, platform string, publicKey []byte) (Auth, error) {
var result Auth
result.User.Username = username
var hash string
if register {
hash = PasswordHash(password)
} else {
err := s.db.QueryRow(ctx, "SELECT id, password_hash FROM users WHERE username=$1", username).Scan(&result.User.ID, &hash)
if errors.Is(err, pgx.ErrNoRows) {
VerifyPassword(password, s.dummyHash)
return Auth{}, ErrCredentials
}
if err != nil {
return Auth{}, err
}
if !VerifyPassword(password, hash) {
return Auth{}, ErrCredentials
}
}
tx, err := s.db.Begin(ctx)
if err != nil {
return Auth{}, err
}
defer tx.Rollback(ctx)
if register {
err = tx.QueryRow(ctx, "INSERT INTO users(username,password_hash) VALUES ($1,$2) RETURNING id", username, hash).Scan(&result.User.ID)
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return Auth{}, ErrDuplicate
}
if err != nil {
return Auth{}, err
}
}
row := tx.QueryRow(ctx, `
INSERT INTO devices(user_id, public_key, name, platform)
VALUES ($1,$2,$3,$4)
ON CONFLICT (user_id, public_key) DO UPDATE
SET last_active_at=now(), name=EXCLUDED.name
WHERE devices.revoked_at IS NULL AND devices.platform=EXCLUDED.platform
RETURNING id, name, platform, created_at, last_active_at, revoked_at
`, result.User.ID, publicKey, name, platform)
if err = scanDevice(row, &result.Device); errors.Is(err, pgx.ErrNoRows) {
return Auth{}, ErrRevoked
}
if err != nil {
return Auth{}, err
}
result.Token = Secret()
digest := sha256.Sum256([]byte(result.Token))
if _, err = tx.Exec(ctx, "INSERT INTO sessions VALUES ($1,$2,$3)", digest[:], result.Device.ID, time.Now().Add(s.ttl)); err != nil {
return Auth{}, err
}
result.Device.SignedIn = true
return result, tx.Commit(ctx)
}
func (s *Store) Session(ctx context.Context, token string) (Identity, error) {
digest, err := SessionDigest(token)
if err != nil {
return Identity{}, err
}
return s.SessionByDigest(ctx, digest[:])
}
func SessionDigest(token string) ([32]byte, error) {
raw, err := Encoding.Strict().DecodeString(token)
if err != nil || len(raw) != 32 {
return [32]byte{}, ErrCredentials
}
return sha256.Sum256([]byte(token)), nil
}
func (s *Store) SessionByDigest(ctx context.Context, digest []byte) (Identity, error) {
var identity Identity
d := &identity.Device
err := s.db.QueryRow(ctx, `
SELECT u.id, u.username, d.id, d.name, d.platform, d.created_at, d.last_active_at, d.revoked_at
FROM sessions s JOIN devices d ON d.id=s.device_id JOIN users u ON u.id=d.user_id
WHERE token_hash=$1 AND expires_at > now() AND d.revoked_at IS NULL
`, digest).Scan(&identity.User.ID, &identity.User.Username, &d.ID, &d.Name, &d.Platform, &d.CreatedAt, &d.LastActiveAt, &d.RevokedAt)
if errors.Is(err, pgx.ErrNoRows) {
return Identity{}, ErrCredentials
}
d.SignedIn = err == nil
return identity, err
}
func (s *Store) Logout(ctx context.Context, token string) error {
digest := sha256.Sum256([]byte(token))
_, err := s.db.Exec(ctx, "DELETE FROM sessions WHERE token_hash=$1", digest[:])
return err
}
func (s *Store) Devices(ctx context.Context, user string) ([]Device, error) {
rows, err := s.db.Query(ctx, `
SELECT id, name, platform, created_at, last_active_at, revoked_at,
revoked_at IS NULL AND EXISTS (
SELECT 1 FROM sessions WHERE device_id=devices.id AND expires_at > now()
)
FROM devices
WHERE user_id=$1 ORDER BY created_at DESC
`, user)
if err != nil {
return nil, err
}
defer rows.Close()
devices := make([]Device, 0)
for rows.Next() {
var device Device
if err := rows.Scan(&device.ID, &device.Name, &device.Platform, &device.CreatedAt,
&device.LastActiveAt, &device.RevokedAt, &device.SignedIn); err != nil {
return nil, err
}
devices = append(devices, device)
}
return devices, rows.Err()
}
func (s *Store) TouchDevice(ctx context.Context, device string) error {
_, err := s.db.Exec(ctx, `
UPDATE devices SET last_active_at=now()
WHERE id=$1 AND revoked_at IS NULL AND last_active_at < now() - interval '1 minute'
`, device)
return err
}
func (s *Store) Revoke(ctx context.Context, user, device string) error {
tx, err := s.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
result, err := tx.Exec(ctx, "UPDATE devices SET revoked_at=COALESCE(revoked_at,now()) WHERE user_id=$1 AND id=$2", user, device)
if err != nil {
return err
}
if result.RowsAffected() == 0 {
return pgx.ErrNoRows
}
if _, err := tx.Exec(ctx, "DELETE FROM sessions WHERE device_id=$1", device); err != nil {
return err
}
return tx.Commit(ctx)
}
func (s *Store) Cleanup(ctx context.Context) error {
_, err := s.db.Exec(ctx, "DELETE FROM sessions WHERE expires_at <= now()")
return err
}
func scanDevice(row pgx.Row, d *Device) error {
return row.Scan(&d.ID, &d.Name, &d.Platform, &d.CreatedAt, &d.LastActiveAt, &d.RevokedAt)
}
+36
View File
@@ -0,0 +1,36 @@
package config
import (
"errors"
"os"
"strings"
"time"
)
type Config struct {
Addr, DatabaseURL, RedisURL string
Origins map[string]bool
SessionTTL time.Duration
}
func Load() (Config, error) {
c := Config{
Addr: os.Getenv("XHCHAT_ADDR"),
DatabaseURL: os.Getenv("DATABASE_URL"),
RedisURL: os.Getenv("REDIS_URL"),
Origins: make(map[string]bool),
SessionTTL: 12 * time.Hour,
}
if c.Addr == "" {
c.Addr = "127.0.0.1:8080"
}
for _, origin := range strings.Split(os.Getenv("XHCHAT_ORIGINS"), ",") {
if origin = strings.TrimSpace(origin); origin != "" {
c.Origins[origin] = true
}
}
if c.DatabaseURL == "" || c.RedisURL == "" || len(c.Origins) == 0 {
return Config{}, errors.New("DATABASE_URL, REDIS_URL and XHCHAT_ORIGINS are required")
}
return c, nil
}
+165
View File
@@ -0,0 +1,165 @@
package contacts
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
var ErrUnavailable = errors.New("contact action unavailable")
type Contact struct {
ID string `json:"id"`
Username string `json:"username"`
State string `json:"state"`
Alias string `json:"alias"`
Category string `json:"category"`
}
type Store struct{ db *pgxpool.Pool }
func New(db *pgxpool.Pool) *Store { return &Store{db: db} }
const selectContact = `
SELECT u.id, u.username,
CASE WHEN mine.owner_id IS NOT NULL THEN 'blocked'
WHEN r.status = 'accepted' THEN 'friend'
WHEN r.requested_by = $1 THEN 'outgoing'
WHEN r.status = 'pending' THEN 'incoming'
ELSE 'none' END,
COALESCE(p.alias,''), COALESCE(p.category,'')
FROM users u
LEFT JOIN contact_relationships r ON r.first_user = LEAST($1::uuid, u.id)
AND r.second_user = GREATEST($1::uuid, u.id)
LEFT JOIN contact_blocks mine ON mine.owner_id=$1 AND mine.blocked_id=u.id
LEFT JOIN contact_blocks theirs ON theirs.owner_id=u.id AND theirs.blocked_id=$1
LEFT JOIN contact_preferences p ON p.owner_id=$1 AND p.contact_id=u.id
WHERE u.id <> $1 AND (theirs.owner_id IS NULL OR mine.owner_id IS NOT NULL)
`
func (s *Store) Search(ctx context.Context, owner, username string) (Contact, error) {
var c Contact
err := s.db.QueryRow(ctx, selectContact+" AND u.username=$2", owner, username).
Scan(&c.ID, &c.Username, &c.State, &c.Alias, &c.Category)
return c, err
}
func (s *Store) List(ctx context.Context, owner string) ([]Contact, error) {
rows, err := s.db.Query(ctx, selectContact+`
AND (mine.owner_id IS NOT NULL OR r.status IS NOT NULL)
ORDER BY u.username LIMIT 1000`, owner)
if err != nil {
return nil, err
}
defer rows.Close()
result := make([]Contact, 0)
for rows.Next() {
var c Contact
if err := rows.Scan(&c.ID, &c.Username, &c.State, &c.Alias, &c.Category); err != nil {
return nil, err
}
result = append(result, c)
}
return result, rows.Err()
}
func (s *Store) Change(ctx context.Context, owner, target, action, alias, category string) error {
tx, err := s.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
// Lock the same two rows in the same order for all transitions of a pair.
var count int
err = tx.QueryRow(ctx, `
SELECT count(*) FROM (
SELECT id FROM users WHERE id IN ($1,$2) ORDER BY id FOR UPDATE
) AS participants`, owner, target).Scan(&count)
if err != nil {
return err
}
if count != 2 {
return ErrUnavailable
}
const pair = "first_user=LEAST($1::uuid,$2::uuid) AND second_user=GREATEST($1::uuid,$2::uuid)"
const remove = "DELETE FROM contact_relationships WHERE " + pair
switch action {
case "request":
var blocked bool
err = tx.QueryRow(ctx, `
SELECT EXISTS(SELECT 1 FROM contact_blocks
WHERE (owner_id=$1 AND blocked_id=$2) OR (owner_id=$2 AND blocked_id=$1))
`, owner, target).Scan(&blocked)
if err != nil {
return err
}
if blocked {
return ErrUnavailable
}
var state string
err = tx.QueryRow(ctx, `
INSERT INTO contact_relationships(first_user,second_user,requested_by,status)
VALUES(LEAST($1::uuid,$2::uuid),GREATEST($1::uuid,$2::uuid),$1,'pending')
ON CONFLICT(first_user,second_user) DO UPDATE
SET updated_at=contact_relationships.updated_at
WHERE contact_relationships.requested_by=$1 AND contact_relationships.status='pending'
RETURNING status`, owner, target).Scan(&state)
if errors.Is(err, pgx.ErrNoRows) {
return ErrUnavailable
}
case "accept":
tag, updateErr := tx.Exec(ctx, "UPDATE contact_relationships SET status='accepted',updated_at=now() WHERE "+pair+" AND requested_by=$2 AND status='pending'", owner, target)
err = updateErr
if err == nil && tag.RowsAffected() == 0 {
return ErrUnavailable
}
case "reject":
_, err = tx.Exec(ctx, remove+" AND requested_by=$2 AND status='pending'", owner, target)
case "cancel":
_, err = tx.Exec(ctx, remove+" AND requested_by=$1 AND status='pending'", owner, target)
case "delete":
tag, deleteErr := tx.Exec(ctx, remove+" AND status='accepted'", owner, target)
err = deleteErr
if err == nil && tag.RowsAffected() > 0 {
err = clearPreferences(ctx, tx, owner, target)
}
case "block":
_, err = tx.Exec(ctx, "INSERT INTO contact_blocks VALUES($1,$2) ON CONFLICT DO NOTHING", owner, target)
if err == nil {
_, err = tx.Exec(ctx, remove, owner, target)
}
if err == nil {
err = clearPreferences(ctx, tx, owner, target)
}
case "unblock":
_, err = tx.Exec(ctx, "DELETE FROM contact_blocks WHERE owner_id=$1 AND blocked_id=$2", owner, target)
case "preferences":
tag, writeErr := tx.Exec(ctx, `
INSERT INTO contact_preferences(owner_id,contact_id,alias,category)
SELECT $1,$2,$3,$4 FROM contact_relationships WHERE `+pair+` AND status='accepted'
ON CONFLICT (owner_id,contact_id) DO UPDATE SET alias=EXCLUDED.alias,category=EXCLUDED.category
`, owner, target, alias, category)
err = writeErr
if err == nil && tag.RowsAffected() == 0 {
return ErrUnavailable
}
default:
return ErrUnavailable
}
if err != nil {
return err
}
return tx.Commit(ctx)
}
func clearPreferences(ctx context.Context, tx pgx.Tx, owner, target string) error {
_, err := tx.Exec(ctx, `
DELETE FROM contact_preferences WHERE
(owner_id=$1 AND contact_id=$2) OR (owner_id=$2 AND contact_id=$1)
`, owner, target)
return err
}
+27
View File
@@ -0,0 +1,27 @@
CREATE TABLE users (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
username text UNIQUE NOT NULL CHECK (username ~ '^[a-z0-9_]{3,32}$'),
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE devices (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
public_key bytea NOT NULL CHECK (octet_length(public_key) = 32),
name text NOT NULL,
platform text NOT NULL CHECK (platform IN ('web', 'windows')),
created_at timestamptz NOT NULL DEFAULT now(),
last_active_at timestamptz NOT NULL DEFAULT now(),
revoked_at timestamptz,
UNIQUE (user_id, public_key)
);
CREATE TABLE sessions (
token_hash bytea PRIMARY KEY CHECK (octet_length(token_hash) = 32),
device_id uuid NOT NULL REFERENCES devices(id) ON DELETE CASCADE,
expires_at timestamptz NOT NULL
);
CREATE INDEX sessions_device ON sessions(device_id);
CREATE INDEX sessions_expiry ON sessions(expires_at);
+28
View File
@@ -0,0 +1,28 @@
CREATE TABLE contact_relationships (
first_user uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
second_user uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
requested_by uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
status text NOT NULL CHECK (status IN ('pending','accepted')),
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (first_user, second_user),
CHECK (first_user < second_user),
CHECK (requested_by IN (first_user, second_user))
);
CREATE INDEX contact_relationships_second_user ON contact_relationships(second_user);
CREATE TABLE contact_blocks (
owner_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
blocked_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
PRIMARY KEY (owner_id, blocked_id),
CHECK (owner_id <> blocked_id)
);
CREATE TABLE contact_preferences (
owner_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
contact_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
alias text NOT NULL,
category text NOT NULL,
PRIMARY KEY (owner_id, contact_id),
CHECK (owner_id <> contact_id)
);
+45
View File
@@ -0,0 +1,45 @@
package database
import (
"context"
_ "embed"
"github.com/jackc/pgx/v5/pgxpool"
)
//go:embed 001_identity.sql
var identityMigration string
//go:embed 002_contacts.sql
var contactsMigration string
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
tx, err := pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(749109272)"); err != nil {
return err
}
if _, err = tx.Exec(ctx, "CREATE TABLE IF NOT EXISTS schema_migrations (version integer PRIMARY KEY)"); err != nil {
return err
}
for index, migration := range []string{identityMigration, contactsMigration} {
version := index + 1
var applied bool
if err = tx.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version=$1)", version).Scan(&applied); err != nil {
return err
}
if applied {
continue
}
if _, err = tx.Exec(ctx, migration); err != nil {
return err
}
if _, err = tx.Exec(ctx, "INSERT INTO schema_migrations VALUES ($1)", version); err != nil {
return err
}
}
return tx.Commit(ctx)
}
+261
View File
@@ -0,0 +1,261 @@
package httpapi
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"regexp"
"strings"
"time"
"unicode"
"unicode/utf8"
"xhchat/server/internal/account"
"xhchat/server/internal/contacts"
"github.com/jackc/pgx/v5"
"github.com/redis/go-redis/v9"
)
type API struct {
accounts *account.Store
contacts *contacts.Store
redis *redis.Client
origins map[string]bool
hashSlots chan struct{}
ready func(context.Context) error
}
func New(accounts *account.Store, contactStore *contacts.Store, cache *redis.Client, origins map[string]bool, ready func(context.Context) error) http.Handler {
a := &API{accounts: accounts, contacts: contactStore, redis: cache, origins: origins, hashSlots: make(chan struct{}, 4), ready: ready}
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { respond(w, 200, map[string]string{"status": "ok"}) })
mux.HandleFunc("GET /readyz", a.readiness)
mux.HandleFunc("POST /api/v1/auth/challenge", a.challenge)
mux.HandleFunc("POST /api/v1/auth/register", a.auth(true))
mux.HandleFunc("POST /api/v1/auth/login", a.auth(false))
mux.HandleFunc("POST /api/v1/auth/logout", a.authorized(a.logout))
mux.HandleFunc("GET /api/v1/me", a.authorized(a.me))
mux.HandleFunc("GET /api/v1/devices", a.authorized(a.devices))
mux.HandleFunc("DELETE /api/v1/devices/{id}", a.authorized(a.revoke))
mux.HandleFunc("POST /api/v1/realtime/ticket", a.authorized(a.ticket))
mux.HandleFunc("GET /api/v1/realtime", a.realtime)
mux.HandleFunc("GET /api/v1/contacts", a.authorized(a.listContacts))
mux.HandleFunc("GET /api/v1/contacts/search", a.authorized(a.searchContact))
mux.HandleFunc("POST /api/v1/contacts/{id}", a.authorized(a.changeContact))
return a.boundary(mux)
}
func (a *API) boundary(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Add("Vary", "Origin")
if origin := r.Header.Get("Origin"); origin != "" {
if !a.origins[origin] {
problem(w, 403, "origin_denied", "此来源未获授权")
return
}
w.Header().Set("Access-Control-Allow-Origin", origin)
}
if r.Method == http.MethodOptions && r.Header.Get("Origin") != "" {
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
func (a *API) readiness(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if a.ready(ctx) != nil {
problem(w, 503, "unavailable", "服务暂不可用")
return
}
respond(w, 200, map[string]string{"status": "ready"})
}
func (a *API) challenge(w http.ResponseWriter, r *http.Request) {
if !a.limit(w, r, "challenge", 300) {
return
}
challenge := account.Secret()
if err := a.redis.Set(r.Context(), "xhchat:challenge:"+challenge, "1", 2*time.Minute).Err(); err != nil {
unavailable(w, err)
return
}
respond(w, 200, map[string]string{"challenge": challenge})
}
type credentials struct {
Username, Password, DeviceName, Platform, PublicKey, Challenge, Signature string
}
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$`)
func (a *API) auth(register bool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var input credentials
if !parse(w, r, &input) {
return
}
input.Username = strings.ToLower(strings.TrimSpace(input.Username))
input.DeviceName = strings.TrimSpace(input.DeviceName)
if !usernamePattern.MatchString(input.Username) ||
len(input.Password) > 256 || utf8.RuneCountInString(input.Password) < 12 ||
len(input.DeviceName) == 0 || utf8.RuneCountInString(input.DeviceName) > 64 ||
strings.ContainsFunc(input.DeviceName, unicode.IsControl) ||
(input.Platform != "web" && input.Platform != "windows") {
problem(w, 400, "invalid_credentials_format", "请检查用户名、密码和设备名称的格式")
return
}
key, ok := account.Proof(input.PublicKey, input.Challenge, input.Signature)
if !ok {
problem(w, 400, "invalid_device_proof", "设备签名验证失败")
return
}
if !a.limit(w, r, "auth", 120) || !a.limit(w, r, "account:"+input.Username, 10) {
return
}
err := a.redis.GetDel(r.Context(), "xhchat:challenge:"+input.Challenge).Err()
if errors.Is(err, redis.Nil) {
problem(w, 400, "expired_challenge", "设备验证已失效,请重试")
return
}
if err != nil {
unavailable(w, err)
return
}
select {
case a.hashSlots <- struct{}{}:
defer func() { <-a.hashSlots }()
default:
problem(w, 429, "busy", "登录服务繁忙,请稍后重试")
return
}
result, err := a.accounts.Open(r.Context(), register, input.Username, input.Password, input.DeviceName, input.Platform, key)
switch {
case errors.Is(err, account.ErrCredentials):
problem(w, 401, "invalid_credentials", "用户名或密码错误")
case errors.Is(err, account.ErrDuplicate):
problem(w, 409, "duplicate_username", "用户名已被使用")
case errors.Is(err, account.ErrRevoked):
problem(w, 403, "device_revoked", "此设备已撤销")
case err != nil:
unavailable(w, err)
case register:
respond(w, 201, result)
default:
respond(w, 200, result)
}
}
}
type sessionHandler func(http.ResponseWriter, *http.Request, string, account.Identity)
func (a *API) authorized(next sessionHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token, _ := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
identity, err := a.accounts.Session(r.Context(), token)
if errors.Is(err, account.ErrCredentials) {
problem(w, 401, "unauthorized", "登录会话已失效")
return
}
if err != nil {
unavailable(w, err)
return
}
next(w, r, token, identity)
}
}
func (a *API) me(w http.ResponseWriter, _ *http.Request, _ string, identity account.Identity) {
respond(w, 200, identity)
}
func (a *API) devices(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
devices, err := a.accounts.Devices(r.Context(), identity.User.ID)
if err != nil {
unavailable(w, err)
return
}
respond(w, 200, devices)
}
func (a *API) logout(w http.ResponseWriter, r *http.Request, token string, _ account.Identity) {
if err := a.accounts.Logout(r.Context(), token); err != nil {
unavailable(w, err)
return
}
w.WriteHeader(204)
}
func (a *API) revoke(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
id := r.PathValue("id")
if !uuidPattern.MatchString(id) {
problem(w, 404, "device_not_found", "设备不存在")
return
}
err := a.accounts.Revoke(r.Context(), identity.User.ID, id)
if errors.Is(err, pgx.ErrNoRows) {
problem(w, 404, "device_not_found", "设备不存在")
return
}
if err != nil {
unavailable(w, err)
return
}
w.WriteHeader(204)
}
var increment = redis.NewScript(`
local count = redis.call('INCR', KEYS[1])
if count == 1 then redis.call('EXPIRE', KEYS[1], 60) end
return count
`)
func (a *API) limit(w http.ResponseWriter, r *http.Request, key string, max int) bool {
count, err := increment.Run(r.Context(), a.redis, []string{"xhchat:limit:" + key}).Int()
if err != nil {
unavailable(w, err)
return false
}
if count > max {
w.Header().Set("Retry-After", "60")
problem(w, 429, "rate_limited", "操作过于频繁,请稍后重试")
return false
}
return true
}
func parse(w http.ResponseWriter, r *http.Request, value any) bool {
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096))
decoder.DisallowUnknownFields()
if err := decoder.Decode(value); err != nil || decoder.Decode(new(any)) != io.EOF {
problem(w, 400, "invalid_json", "请求格式错误")
return false
}
return true
}
func respond(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func problem(w http.ResponseWriter, status int, code, message string) {
respond(w, status, map[string]any{"error": map[string]string{"code": code, "message": message}})
}
func unavailable(w http.ResponseWriter, err error) {
slog.Error("request dependency failed", "error_type", errorType(err))
problem(w, 503, "unavailable", "服务暂不可用")
}
+86
View File
@@ -0,0 +1,86 @@
package httpapi
import (
"errors"
"net/http"
"strings"
"unicode"
"unicode/utf8"
"xhchat/server/internal/account"
"xhchat/server/internal/contacts"
"github.com/jackc/pgx/v5"
)
func (a *API) listContacts(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
result, err := a.contacts.List(r.Context(), identity.User.ID)
if err != nil {
unavailable(w, err)
return
}
respond(w, 200, result)
}
func (a *API) searchContact(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
username := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("username")))
if !usernamePattern.MatchString(username) {
problem(w, 400, "invalid_username", "请输入完整用户名")
return
}
if !a.limit(w, r, "contact-search:"+identity.User.ID, 60) {
return
}
result, err := a.contacts.Search(r.Context(), identity.User.ID, username)
if errors.Is(err, pgx.ErrNoRows) {
problem(w, 404, "contact_not_found", "找不到该用户")
return
}
if err != nil {
unavailable(w, err)
return
}
respond(w, 200, result)
}
func (a *API) changeContact(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
target := r.PathValue("id")
if !uuidPattern.MatchString(target) {
problem(w, 404, "contact_not_found", "找不到该用户")
return
}
var input struct {
Action string `json:"action"`
Alias string `json:"alias"`
Category string `json:"category"`
}
if !parse(w, r, &input) {
return
}
input.Alias = strings.TrimSpace(input.Alias)
input.Category = strings.TrimSpace(input.Category)
if utf8.RuneCountInString(input.Alias) > 64 || utf8.RuneCountInString(input.Category) > 32 ||
strings.ContainsFunc(input.Alias, unicode.IsControl) || strings.ContainsFunc(input.Category, unicode.IsControl) {
problem(w, 400, "invalid_contact_preferences", "请检查备注和分组")
return
}
if !a.limit(w, r, "contact-change:"+identity.User.ID, 60) {
return
}
err := a.contacts.Change(r.Context(), identity.User.ID, target, input.Action, input.Alias, input.Category)
if errors.Is(err, contacts.ErrUnavailable) {
problem(w, 409, "contact_action_unavailable", "当前无法执行此联系人操作,请刷新后重试")
return
}
if err != nil {
unavailable(w, err)
return
}
pipe := a.redis.Pipeline()
pipe.Publish(r.Context(), "xhchat:contacts:"+identity.User.ID, "changed")
if input.Action != "preferences" {
pipe.Publish(r.Context(), "xhchat:contacts:"+strings.ToLower(target), "changed")
}
_, _ = pipe.Exec(r.Context())
w.WriteHeader(204)
}
+135
View File
@@ -0,0 +1,135 @@
package httpapi
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
"time"
"xhchat/server/internal/account"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
"github.com/redis/go-redis/v9"
)
func errorType(err error) string { return fmt.Sprintf("%T", err) }
func (a *API) ticket(w http.ResponseWriter, r *http.Request, token string, identity account.Identity) {
if !a.limit(w, r, "ticket:"+identity.Device.ID, 30) {
return
}
ticket := account.Secret()
digest, _ := account.SessionDigest(token)
if err := a.redis.Set(r.Context(), "xhchat:ticket:"+ticket, digest[:], 30*time.Second).Err(); err != nil {
unavailable(w, err)
return
}
respond(w, 200, map[string]string{"ticket": ticket})
}
func (a *API) realtime(w http.ResponseWriter, r *http.Request) {
if !a.origins[r.Header.Get("Origin")] {
problem(w, 403, "origin_denied", "此来源未获授权")
return
}
protocols := strings.Split(r.Header.Get("Sec-WebSocket-Protocol"), ",")
var ticket string
if len(protocols) == 2 && strings.TrimSpace(protocols[0]) == "xhchat.v1" {
ticket, _ = strings.CutPrefix(strings.TrimSpace(protocols[1]), "ticket.")
}
raw, err := account.Encoding.DecodeString(ticket)
if err != nil || len(raw) != 32 {
problem(w, 401, "invalid_ticket", "连接凭据无效")
return
}
digest, err := a.redis.GetDel(r.Context(), "xhchat:ticket:"+ticket).Bytes()
if errors.Is(err, redis.Nil) {
problem(w, 401, "invalid_ticket", "连接凭据已失效")
return
}
if err != nil {
unavailable(w, err)
return
}
identity, err := a.accounts.SessionByDigest(r.Context(), digest)
if errors.Is(err, account.ErrCredentials) {
problem(w, 401, "unauthorized", "登录会话已失效")
return
}
if err != nil {
unavailable(w, err)
return
}
subscription := a.redis.Subscribe(r.Context(), "xhchat:contacts:"+identity.User.ID)
defer subscription.Close()
if _, err = subscription.Receive(r.Context()); err != nil {
unavailable(w, err)
return
}
changes := subscription.Channel()
// The exact Origin was checked before consuming the ticket.
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{
Subprotocols: []string{"xhchat.v1"}, InsecureSkipVerify: true,
})
if err != nil {
return
}
defer conn.CloseNow()
conn.SetReadLimit(1024)
ctx := conn.CloseRead(r.Context())
writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
err = wsjson.Write(writeCtx, conn, map[string]string{"type": "ready", "deviceId": identity.Device.ID})
cancel()
if err != nil {
return
}
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
heartbeat := time.NewTicker(30 * time.Second)
defer heartbeat.Stop()
for {
select {
case <-ctx.Done():
return
case _, ok := <-changes:
if !ok {
return
}
writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
err := wsjson.Write(writeCtx, conn, map[string]string{"type": "contacts_changed"})
cancel()
if err != nil {
return
}
case <-heartbeat.C:
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
err := conn.Ping(pingCtx)
cancel()
if err != nil {
return
}
updateCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
err = a.accounts.TouchDevice(updateCtx, identity.Device.ID)
cancel()
if err != nil {
_ = conn.Close(websocket.StatusInternalError, "dependency unavailable")
return
}
case <-ticker.C:
checkCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
_, err := a.accounts.SessionByDigest(checkCtx, digest)
cancel()
if errors.Is(err, account.ErrCredentials) {
_ = conn.Close(websocket.StatusPolicyViolation, "session ended")
return
}
if err != nil {
_ = conn.Close(websocket.StatusInternalError, "dependency unavailable")
return
}
}
}
}
+93
View File
@@ -0,0 +1,93 @@
import assert from 'node:assert/strict'
import { generateKeyPairSync, randomBytes, sign } from 'node:crypto'
import { once } from 'node:events'
import test from 'node:test'
const base = process.env.XHCHAT_TEST_URL ?? 'http://127.0.0.1:8080'
const wsBase = base.replace(/^http/, 'ws')
const newUsername = () => 'qa_' + randomBytes(6).toString('hex')
const newDevice = () => generateKeyPairSync('ed25519')
const password = randomBytes(24).toString('base64url')
async function call(path, { method = 'GET', token, body, origin } = {}) {
return fetch(base + '/api/v1' + path, {
method,
headers: {
...(token && { Authorization: 'Bearer ' + token }),
...(origin && { Origin: origin }),
...(body && { 'Content-Type': 'application/json' }),
},
body: body && JSON.stringify(body),
signal: AbortSignal.timeout(10_000),
})
}
async function proof(username, pair, platform = 'web') {
const reply = await call('/auth/challenge', { method: 'POST' })
assert.equal(reply.status, 200)
const { challenge } = await reply.json()
return {
username, password, challenge, platform, deviceName: '测试设备',
publicKey: pair.publicKey.export({ format: 'jwk' }).x,
signature: sign(null, Buffer.from('XHChat device authentication v1\n' + challenge), pair.privateKey).toString('base64url'),
}
}
async function login(route, body, expected) {
const reply = await call('/auth/' + route, { method: 'POST', body })
assert.equal(reply.status, expected, await reply.clone().text())
return reply.json()
}
async function upgrade(ticket, origin = base) {
const { WebSocket } = await import('ws')
return new WebSocket(wsBase + '/api/v1/realtime', ['xhchat.v1', 'ticket.' + ticket], { origin })
}
test('真实数据库注册、跨平台设备、单次挑战及 WebSocket 票据、撤销与退出', { timeout: 25000 }, async () => {
assert.equal((await fetch(base + '/readyz')).status, 200)
const username = newUsername()
const web = newDevice()
const desktop = newDevice()
const other = newDevice()
const initial = await proof(username, web)
const registered = await login('register', initial, 201)
await login('register', initial, 400)
await login('register', await proof(username, other), 409)
const wrong = await proof(username, web)
await login('login', { ...wrong, password: password + 'bad' }, 401)
const second = await login('login', await proof(username, desktop, 'windows'), 200)
assert.equal(second.user.id, registered.user.id)
assert.notEqual(second.device.id, registered.device.id)
const foreign = await login('register', await proof(newUsername(), other), 201)
const token = registered.token
const ticketReply = await call('/realtime/ticket', { method: 'POST', token: second.token })
assert.equal(ticketReply.status, 200)
const { ticket } = await ticketReply.json()
const socket = await upgrade(ticket)
try {
const [event] = await once(socket, 'message')
assert.deepEqual(JSON.parse(event), { type: 'ready', deviceId: second.device.id })
const replay = await upgrade(ticket)
const [, denied] = await once(replay, 'unexpected-response')
assert.equal(denied.statusCode, 401)
replay.on('error', () => {})
replay.terminate()
const devices = await (await call('/devices', { token })).json()
assert.equal(devices.length, 2)
assert.ok(devices.every((device) => device.signedIn))
assert.equal((await call('/devices/' + second.device.id, { method: 'DELETE', token: foreign.token })).status, 404)
assert.equal((await call('/me', { token, origin: 'https://untrusted.invalid' })).status, 403)
const closed = once(socket, 'close')
assert.equal((await call('/devices/' + second.device.id, { method: 'DELETE', token })).status, 204)
assert.equal((await call('/me', { token: second.token })).status, 401)
const afterRevoke = await (await call('/devices', { token })).json()
assert.equal(afterRevoke.find((device) => device.id === second.device.id).signedIn, false)
assert.equal((await closed)[0], 1008)
await login('login', await proof(username, desktop, 'windows'), 403)
assert.equal((await call('/auth/logout', { method: 'POST', token })).status, 204)
assert.equal((await call('/me', { token })).status, 401)
} finally {
socket.terminate()
}
})
+73
View File
@@ -0,0 +1,73 @@
import assert from 'node:assert/strict'
import { randomBytes } from 'node:crypto'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import test from 'node:test'
import { _electron, chromium } from 'playwright'
import electron from 'electron'
const base = process.env.XHCHAT_TEST_URL ?? 'http://127.0.0.1:8080'
async function form(page, username, password) {
await page.getByLabel('用户名').fill(username)
await page.getByLabel('密码', { exact: true }).fill(password)
}
test('Web 注册,Windows 登录,Web 撤销 Windows 设备', { timeout: 45000 }, async () => {
const browser = await chromium.launch({ channel: process.env.XHCHAT_TEST_BROWSER ?? 'msedge' })
const profile = await mkdtemp(join(tmpdir(), 'xhchat-client-test-'))
let desktop
try {
const web = await browser.newPage({ viewport: { width: 390, height: 844 } })
await web.goto(base)
await web.getByRole('button', { name: '注册', exact: true }).click()
const username = 'qa_' + randomBytes(6).toString('hex')
const password = randomBytes(24).toString('base64url')
await form(web, username, password)
await web.getByRole('button', { name: '创建账号' }).click()
await web.getByText('实时连接已建立').waitFor()
assert.equal(await web.evaluate(() => document.documentElement.scrollWidth), 390)
const privateKeyExtractable = await web.evaluate(async (username) => {
const db = await new Promise((resolve, reject) => {
const request = indexedDB.open('xhchat-device', 1)
request.onsuccess = () => resolve(request.result)
request.onerror = () => reject(request.error)
})
try {
return await new Promise((resolve, reject) => {
const request = db.transaction('keys').objectStore('keys').get(username)
request.onsuccess = () => resolve(request.result.privateKey.extractable)
request.onerror = () => reject(request.error)
})
} finally {
db.close()
}
}, username)
assert.equal(privateKeyExtractable, false)
desktop = await _electron.launch({
executablePath: electron,
args: [join(import.meta.dirname, '..', 'Desktop'), '--user-data-dir=' + profile],
env: { ...process.env, XHCHAT_SERVER_URL: base },
})
const windows = await desktop.firstWindow()
await form(windows, username, password)
await windows.locator('button.primary').click()
await windows.getByText('实时连接已建立').waitFor()
await windows.getByText('Windows 电脑').waitFor()
assert.equal(await windows.evaluate(() => typeof window.require), 'undefined')
await web.getByRole('button', { name: '刷新' }).click()
await web.getByText('Windows 电脑').waitFor()
await web.getByRole('button', { name: '撤销', exact: true }).click()
await web.getByRole('button', { name: '确认撤销' }).click()
await web.getByText('已撤销').waitFor()
await windows.getByRole('heading', { name: '登录 XHChat' }).waitFor()
await web.getByRole('button', { name: '退出登录' }).click()
await web.getByRole('heading', { name: '登录 XHChat' }).waitFor()
} finally {
await desktop?.close()
await browser.close()
await rm(profile, { recursive: true, maxRetries: 5, retryDelay: 200, force: true })
}
})
+104
View File
@@ -0,0 +1,104 @@
import assert from 'node:assert/strict'
import { randomBytes } from 'node:crypto'
import { mkdtemp, rm } from 'node:fs/promises'
import { createServer } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import test from 'node:test'
import { _electron, chromium } from 'playwright'
import electron from 'electron'
const base = process.env.XHCHAT_TEST_URL ?? 'http://127.0.0.1:8080'
async function register(page, desktop = false) {
if (!desktop) await page.goto(base)
const username = 'qa_' + randomBytes(6).toString('hex')
await page.getByRole('button', { name: '注册', exact: true }).click()
await page.getByLabel('用户名').fill(username)
await page.getByLabel('密码', { exact: true }).fill(randomBytes(24).toString('hex'))
await page.getByRole('button', { name: '创建账号' }).click()
await page.getByText('实时连接已建立').waitFor()
await page.getByRole('navigation', { name: '工作区' }).getByRole('link', { name: '联系人' }).click()
return username
}
test('双端联系人实时同步,桌面浏览器独立分区与 UA', { timeout: 60000 }, async () => {
const browser = await chromium.launch({ channel: process.env.XHCHAT_TEST_BROWSER ?? 'msedge' })
const profile = await mkdtemp(join(tmpdir(), 'xhchat-browser-test-'))
const requests = []
const local = createServer((request, response) => {
requests.push({ path: request.url, userAgent: request.headers['user-agent'] })
response.setHeader('Content-Type', 'text/html; charset=utf-8')
response.end('<title>隔离测试站</title><h1>OK</h1>')
})
let app
try {
await new Promise((resolve) => local.listen(0, '127.0.0.1', resolve))
const url = 'http://127.0.0.1:' + local.address().port
const web = await browser.newPage()
const webName = await register(web)
app = await _electron.launch({
executablePath: electron,
args: [join(import.meta.dirname, '..', 'Desktop'), '--user-data-dir=' + profile],
env: { ...process.env, XHCHAT_SERVER_URL: base },
})
const desktop = await app.firstWindow()
const desktopName = await register(desktop, true)
await web.getByLabel('按用户名查找').fill(desktopName)
await web.getByRole('button', { name: '查找' }).click()
await web.getByRole('button', { name: '添加好友' }).click()
await desktop.getByRole('button', { name: new RegExp(webName) }).click()
await desktop.getByRole('button', { name: '接受申请' }).click()
await web.getByLabel('备注').fill('跨端好友')
await web.getByLabel('分组').fill('验收')
await web.getByRole('button', { name: '保存' }).click()
await web.getByRole('heading', { name: '跨端好友' }).waitFor()
await desktop.getByRole('heading', { name: webName }).waitFor()
await web.getByRole('button', { name: '拉黑', exact: true }).click()
await web.getByRole('button', { name: '确认', exact: true }).click()
await web.getByText('已拉黑').waitFor()
await desktop.getByText('还没有联系人').waitFor()
await web.getByRole('button', { name: '解除拉黑' }).click()
await web.getByText('还没有联系人').waitFor()
const opened = app.waitForEvent('window')
await desktop.getByRole('navigation', { name: '主导航' }).getByRole('button', { name: '浏览器' }).click()
const toolbar = await opened
await toolbar.getByRole('button', { name: '新标签页', exact: true }).waitFor()
const address = toolbar.getByRole('textbox', { name: '网址或搜索关键词' })
await address.fill(url + '/first')
await address.press('Enter')
try {
await toolbar.getByRole('button', { name: '隔离测试站', exact: true }).waitFor({ timeout: 8000 })
} catch (error) {
const pages = await app.evaluate(({ webContents }) => webContents.getAllWebContents().map((entry) => ({ url: entry.getURL(), title: entry.getTitle() })))
throw new Error(JSON.stringify({ pages, requests, status: await toolbar.locator('#status').textContent() }), { cause: error })
}
const site = await app.evaluate(async ({ webContents }, url) => {
const view = webContents.getAllWebContents().find((contents) => contents.getURL() === url + '/first')
if (!view) throw new Error('找不到网页视图')
return {
version: process.versions.chrome,
isolated: await view.executeJavaScript('typeof window.xhchat + ":" + typeof window.xhchatBrowser + ":" + typeof window.require'),
sandbox: view.getLastWebPreferences().sandbox,
separateSession: view.session !== webContents.getAllWebContents().find((contents) => contents.getURL().startsWith('xhchat://app/#'))?.session,
}
}, url)
assert.equal(site.isolated, 'undefined:undefined:undefined')
assert.equal(site.sandbox, true)
assert.equal(site.separateSession, true)
const userAgent = requests.find((entry) => entry.path === '/first').userAgent
assert.ok(userAgent.includes('Chrome/' + site.version))
assert.match(userAgent, /XHChat\/0\.1\.0/)
await toolbar.getByRole('button', { name: '新建标签页' }).click()
await toolbar.getByRole('button', { name: '新标签页', exact: true }).waitFor()
await address.fill('file:///C:/Windows/win.ini')
await address.press('Enter')
await toolbar.getByText('请输入 HTTPS 地址或搜索关键词。').waitFor()
} finally {
await app?.close()
await browser.close()
await new Promise((resolve) => local.close(resolve))
await rm(profile, { recursive: true, maxRetries: 5, retryDelay: 200, force: true })
}
})
+12
View File
@@ -0,0 +1,12 @@
FROM node:24-alpine AS build
WORKDIR /src
COPY package.json package-lock.json ./
COPY web/package.json web/
COPY Desktop/package.json Desktop/
RUN npm ci --workspace web --include-workspace-root=false --no-audit
COPY web/ web/
RUN npm run build -w web
FROM nginx:alpine
COPY deploy/nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /src/web/dist/ /usr/share/nginx/html/
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#f1f5f3">
<title>XHChat</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+1
View File
@@ -0,0 +1 @@
{"name":"@xhchat/web","private":true,"type":"module","scripts":{"dev":"vite","build":"vue-tsc --noEmit && vite build","check":"vue-tsc --noEmit"},"dependencies":{"vue":"3.5.45","vue-router":"5.5.0","pinia":"4.1.0"},"devDependencies":{"vite":"8.3.8","@vitejs/plugin-vue":"6.0.11","typescript":"~6.0.3","vue-tsc":"3.3.14","@types/node":"^24.0.0"}}
+13
View File
@@ -0,0 +1,13 @@
<script setup lang="ts">
import { watch } from 'vue'
import { useRouter } from 'vue-router'
import { useSession } from './session'
const session = useSession()
const router = useRouter()
watch(() => session.identity, (identity) => {
void router.replace(identity ? '/devices' : '/login')
})
</script>
<template><RouterView /></template>
+32
View File
@@ -0,0 +1,32 @@
const base = window.xhchat?.apiBase ?? ''
export class APIError extends Error {
constructor(public status: number, message: string) {
super(message)
}
}
export async function request<T>(path: string, method = 'GET', token = '', body?: object): Promise<T> {
const headers: Record<string, string> = { Accept: 'application/json' }
if (token) headers.Authorization = 'Bearer ' + token
if (body) headers['Content-Type'] = 'application/json'
let response: Response
try {
response = await fetch(base + '/api/v1' + path, {
method, headers, body: body ? JSON.stringify(body) : undefined,
credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(12000),
})
} catch {
throw new Error('无法连接 XHChat 服务,请检查网络后重试')
}
if (response.status === 204) return undefined as T
const data = await response.json().catch(() => null)
if (!response.ok) throw new APIError(response.status, data?.error?.message ?? '请求失败,请稍后重试')
return data as T
}
export function realtime(ticket: string) {
const url = new URL((base || location.origin) + '/api/v1/realtime')
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
return new WebSocket(url, ['xhchat.v1', 'ticket.' + ticket])
}
+9
View File
@@ -0,0 +1,9 @@
export interface Contact {
id: string
username: string
state: 'none' | 'incoming' | 'outgoing' | 'friend' | 'blocked'
alias: string
category: string
}
export type ContactAction = 'request' | 'accept' | 'reject' | 'cancel' | 'delete' | 'block' | 'unblock' | 'preferences'
+66
View File
@@ -0,0 +1,66 @@
interface DeviceProof {
publicKey: string
signature: string
}
interface DesktopBridge {
apiBase: string
signChallenge: (username: string, challenge: string) => Promise<DeviceProof>
openBrowser?: () => Promise<void>
}
declare global {
interface Window { xhchat?: DesktopBridge }
}
const prefix = 'XHChat device authentication v1\n'
function base64url(bytes: ArrayBuffer) {
return btoa(String.fromCharCode(...new Uint8Array(bytes)))
.replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '')
}
function openDatabase(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open('xhchat-device', 1)
request.onupgradeneeded = () => request.result.createObjectStore('keys')
request.onsuccess = () => resolve(request.result)
request.onerror = () => reject(request.error)
request.onblocked = () => reject(new Error('请关闭其他 XHChat 页面后重试'))
})
}
async function browserKey(username: string): Promise<CryptoKeyPair> {
const candidate = await crypto.subtle.generateKey('Ed25519', false, ['sign', 'verify'])
const db = await openDatabase()
try {
return await new Promise((resolve, reject) => {
const transaction = db.transaction('keys', 'readwrite')
const keys = transaction.objectStore('keys')
const read = keys.get(username)
let result = candidate
read.onsuccess = () => {
if (read.result) result = read.result
else keys.add(candidate, username)
}
transaction.oncomplete = () => resolve(result)
transaction.onabort = () => reject(transaction.error)
})
} finally {
db.close()
}
}
export const platform = window.xhchat ? 'windows' : 'web'
export async function signChallenge(username: string, challenge: string): Promise<DeviceProof> {
if (window.xhchat) return window.xhchat.signChallenge(username, challenge)
try {
const pair = await browserKey(username)
const publicKey = await crypto.subtle.exportKey('raw', pair.publicKey)
const signature = await crypto.subtle.sign('Ed25519', pair.privateKey, new TextEncoder().encode(prefix + challenge))
return { publicKey: base64url(publicKey), signature: base64url(signature) }
} catch {
throw new Error('无法使用本机设备密钥,请检查浏览器是否支持安全密钥存储')
}
}
+32
View File
@@ -0,0 +1,32 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import { createRouter, createWebHashHistory } from 'vue-router'
import App from './App.vue'
import AuthView from './views/AuthView.vue'
import DeviceView from './views/DeviceView.vue'
import ContactsView from './views/ContactsView.vue'
import Workspace from './views/Workspace.vue'
import { useSession } from './session'
import './style.css'
const pinia = createPinia()
const router = createRouter({
history: createWebHashHistory(),
routes: [
{ path: '/', redirect: '/devices' },
{ path: '/login', component: AuthView },
{ path: '/', component: Workspace, children: [
{ path: 'devices', component: DeviceView },
{ path: 'contacts', component: ContactsView },
] },
{ path: '/:pathMatch(.*)*', redirect: '/' },
],
})
router.beforeEach((to) => {
const signedIn = Boolean(useSession(pinia).identity)
if (!signedIn && to.path !== '/login') return '/login'
if (signedIn && to.path === '/login') return '/devices'
})
createApp(App).use(pinia).use(router).mount('#app')
+115
View File
@@ -0,0 +1,115 @@
import { defineStore } from 'pinia'
import { ref, shallowRef } from 'vue'
import { APIError, realtime, request } from './api'
import { platform, signChallenge } from './identity'
import type { Contact, ContactAction } from './contacts'
export interface Device {
id: string
name: string
platform: 'web' | 'windows'
createdAt: string
lastActiveAt: string
revokedAt?: string
signedIn: boolean
}
interface Identity {
user: { id: string; username: string }
device: Device
}
interface Auth extends Identity { token: string }
export const useSession = defineStore('session', () => {
const identity = shallowRef<Identity>()
const connection = ref('离线')
const contactChanges = ref(0)
let token = ''
let socket: WebSocket | undefined
let retry: ReturnType<typeof setTimeout> | undefined
let attempts = 0
function clear() {
token = ''
identity.value = undefined
connection.value = '离线'
clearTimeout(retry)
const previous = socket
socket = undefined
previous?.close()
}
async function connect(current: string) {
if (current !== token) return
connection.value = '正在连接'
try {
const { ticket } = await request<{ ticket: string }>('/realtime/ticket', 'POST', current)
if (current !== token) return
const active = realtime(ticket)
socket = active
active.onmessage = (event) => {
if (socket !== active) return
const { type } = JSON.parse(event.data)
if (type === 'ready') {
connection.value = '实时连接已建立'
attempts = 0
}
if (type === 'contacts_changed') contactChanges.value++
}
active.onclose = (event) => {
if (socket !== active) return
socket = undefined
if (event.code === 1008) clear()
else reconnect(current)
}
} catch (error) {
if (current !== token) return
if (error instanceof APIError && error.status === 401) clear()
else reconnect(current)
}
}
function reconnect(current: string) {
connection.value = '正在重连'
retry = setTimeout(() => void connect(current), Math.min(30_000, 1000 * 2 ** attempts++))
}
async function authenticate(mode: 'login' | 'register', username: string, password: string, deviceName: string) {
username = username.trim().toLowerCase()
const { challenge } = await request<{ challenge: string }>('/auth/challenge', 'POST')
const proof = await signChallenge(username, challenge)
const result = await request<Auth>('/auth/' + mode, 'POST', '', {
username, password, deviceName, platform, challenge, ...proof,
})
clear()
token = result.token
identity.value = { user: result.user, device: result.device }
attempts = 0
void connect(token)
}
async function authorized<T>(path: string, method = 'GET', body?: object) {
try {
return await request<T>(path, method, token, body)
} catch (error) {
if (error instanceof APIError && error.status === 401) clear()
throw error
}
}
async function logout() {
await authorized('/auth/logout', 'POST')
clear()
}
return {
identity, connection, contactChanges, authenticate, logout,
devices: () => authorized<Device[]>('/devices'),
revoke: (id: string) => authorized<void>('/devices/' + encodeURIComponent(id), 'DELETE'),
contacts: () => authorized<Contact[]>('/contacts'),
searchContact: (username: string) => authorized<Contact>('/contacts/search?' + new URLSearchParams({ username })),
changeContact: (id: string, action: ContactAction, alias: string, category: string) =>
authorized<void>('/contacts/' + encodeURIComponent(id), 'POST', { action, alias, category }),
}
})
+103
View File
@@ -0,0 +1,103 @@
* { box-sizing: border-box; }
:root {
color-scheme: light dark;
--surface: #ffffff;
--base: #f1f5f3;
--text: #182822;
--muted: #596c62;
--line: #dce6e0;
--green: #14664c;
--green-soft: #e1f0e8;
--danger: #a62e38;
font: 15px/1.5 "Segoe UI", "Microsoft YaHei UI", system-ui, sans-serif;
color: var(--text);
background: var(--base);
}
@media (prefers-color-scheme: dark) {
:root {
--surface: #182520; --base: #101a16; --text: #edf4ef; --muted: #a8bcb0;
--line: #34483d; --green: #7ed8b1; --green-soft: #244236; --danger: #ff9aa2;
}
}
body { margin: 0; }
button, input { font: inherit; }
button, a { -webkit-tap-highlight-color: transparent; }
button { cursor: pointer; }
button:disabled { cursor: wait; opacity: .65; }
:focus-visible { outline: 2px solid var(--green); outline-offset: 3px; }
h1, p { margin: 0; }
h1 { font-size: clamp(25px, 3vw, 32px); letter-spacing: -.02em; line-height: 1.25; }
small, .muted { color: var(--muted); }
.auth-shell { display: grid; grid-template-columns: 1fr 1.1fr; min-height: 100vh; }
.auth-brand { position: relative; overflow: hidden; display: grid; align-content: space-between; padding: clamp(26px, 6vw, 80px); background: #12372d; color: #ecf8ee; min-height: 100%; }
.brand { display: flex; align-items: center; gap: 14px; font-size: 23px; font-weight: 700; }
.mark { display: grid; place-items: center; width: 40px; height: 40px; border-radius: 12px; background: #ceef9a; color: #12372d; font: 800 22px/1 system-ui, sans-serif; text-decoration: none; }
.platform { color: #bad5c5; }
.brand-art { width: min(100%, 430px); aspect-ratio: 1; position: relative; margin: 36px auto; }
.brand-art span { position: absolute; inset: 5% 11% 11% 5%; border: 1px solid #7aab94; border-radius: 45% 45% 10% 45%; }
.brand-art span:nth-child(2) { inset: 16% 4% 0% 16%; }
.brand-art span:nth-child(3) { inset: 24% 23% 24% 23%; background: #ceef9a; border-color: #ceef9a; border-radius: 50% 50% 50% 10%; }
.brand-art span:nth-child(4) { inset: 45% 38% 45% 38%; background: #12372d; border: 0; border-radius: 20px; }
.auth-content { display: grid; align-items: center; justify-items: center; background: var(--surface); padding: 32px clamp(22px, 6vw, 72px); }
.auth-form { display: grid; gap: 19px; width: min(100%, 390px); }
.tabs { display: flex; gap: 16px; border-bottom: 1px solid var(--line); margin-bottom: 8px; }
.tabs button { border: 0; border-bottom: 2px solid transparent; padding: 9px 3px; color: var(--muted); background: none; }
.tabs button[aria-pressed="true"] { border-color: var(--green); color: var(--green); font-weight: 700; }
label { display: grid; gap: 7px; font-weight: 600; }
input { width: 100%; color: var(--text); background: var(--base); border: 1px solid var(--line); border-radius: 8px; padding: 11px 12px; }
.primary { border: 0; border-radius: 8px; background: #14664c; color: white; padding: 11px 16px; font-weight: 700; margin-top: 7px; }
.error { color: var(--danger); }
.workspace { display: grid; grid-template-columns: 66px 250px minmax(0, 1fr); min-height: 100vh; }
.rail { display: flex; flex-direction: column; align-items: center; gap: 25px; padding: 18px 8px; background: #12372d; }
.rail-link { display: grid; place-items: center; color: #ceef9a; background: #275346; width: 38px; height: 38px; border-radius: 9px; text-decoration: none; }
.account-panel { display: flex; flex-direction: column; gap: 28px; border-right: 1px solid var(--line); padding: 20px 13px; }
.account-summary { display: flex; align-items: center; gap: 12px; padding: 0 6px; overflow-wrap: anywhere; }
.account-summary small, .device-meta small { display: block; }
.avatar, .device-icon { display: grid; place-items: center; flex-shrink: 0; width: 42px; height: 42px; border-radius: 10px; color: var(--green); background: var(--green-soft); font-weight: 700; }
.panel-nav { padding: 10px 12px; border-radius: 8px; color: var(--green); background: var(--green-soft); font-weight: 700; }
.panel-links { display: grid; gap: 4px; }
.panel-links a { color: var(--text); text-decoration: none; padding: 9px 11px; border-radius: 8px; }
.panel-links a.router-link-active { color: var(--green); background: var(--green-soft); font-weight: 700; }
.browser-button { border: 0; }
.mobile-browser { display: none; }
.contacts-layout { display: grid; grid-template-columns: minmax(155px, 255px) minmax(0, 1fr); background: var(--surface); }
.contact-list { min-width: 0; padding: 16px; border-right: 1px solid var(--line); }
.contact-search, .contact-preferences { display: grid; justify-items: start; gap: 10px; margin-bottom: 20px; }
.contact-search label, .contact-preferences label { width: 100%; }
.contact-group h2 { margin: 16px 0 7px; color: var(--muted); font-size: 13px; }
.contact-item { display: flex; align-items: center; gap: 8px; width: 100%; text-align: left; padding: 8px; border-radius: 8px; border: 0; background: transparent; color: var(--text); overflow-wrap: anywhere; }
.contact-item[aria-pressed="true"] { background: var(--green-soft); }
.contact-item small { display: block; }
.contact-detail { padding: 24px clamp(12px, 4vw, 36px); min-width: 0; overflow-wrap: anywhere; }
.contact-heading, .contact-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 18px; }
.contact-heading h1 { font-size: 22px; }
.contact-detail > button { margin-bottom: 18px; }
.contact-preferences { max-width: 340px; }
.account-footer { display: grid; gap: 12px; margin-top: auto; }
.account-footer p { color: var(--muted); font-size: 13px; }
.dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: var(--muted); margin: 0 8px 1px 4px; }
.dot.online { background: var(--green); }
.device-page { background: var(--surface); }
.page-header { display: flex; justify-content: space-between; gap: 12px; align-items: center; padding: 20px clamp(15px, 4vw, 42px); border-bottom: 1px solid var(--line); }
.page-header h1 { font-size: 22px; }
.device-content { max-width: 950px; padding: 15px clamp(15px, 4vw, 42px); }
.device-row { display: flex; align-items: center; gap: 12px; padding: 17px 0; border-bottom: 1px solid var(--line); }
.device-meta { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.tag { display: inline-block; margin-left: 8px; padding: 1px 5px; background: var(--green-soft); color: var(--green); font-size: 11px; border-radius: 4px; }
.plain { border: 1px solid var(--line); border-radius: 7px; padding: 6px 10px; background: var(--surface); color: var(--text); white-space: nowrap; }
.danger { color: var(--danger); }
.confirmation { margin-top: 16px; padding: 16px; border: 1px solid var(--line); border-radius: 8px; }
.confirmation button { margin: 9px 8px 0 0; }
@media (max-width: 700px) {
.auth-shell { grid-template-columns: 1fr; grid-template-rows: auto 1fr; }
.auth-brand { padding: 16px 22px; display: flex; justify-content: space-between; align-items: center; gap: 12px; }
.brand-art, .rail, .panel-nav { display: none; }
.workspace { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto 1fr; }
.account-panel { padding: 12px; flex-direction: row; align-items: center; justify-content: space-between; border-right: 0; border-bottom: 1px solid var(--line); }
.panel-links { grid-auto-flow: column; grid-column: 1 / -1; grid-row: 2; justify-content: start; gap: 5px; }
.account-panel { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; }
.mobile-browser { display: block; }
.contacts-layout { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto 1fr; }
.contact-list { border-right: 0; border-bottom: 1px solid var(--line); }
.account-footer { margin: 0; justify-items: end; gap: 4px; }
}
+55
View File
@@ -0,0 +1,55 @@
<script setup lang="ts">
import { ref } from 'vue'
import { platform } from '../identity'
import { useSession } from '../session'
const session = useSession()
const mode = ref<'login' | 'register'>('login')
const username = ref('')
const password = ref('')
const deviceName = ref(platform === 'windows' ? 'Windows 电脑' : '网页浏览器')
const error = ref('')
const busy = ref(false)
function changeMode(value: 'login' | 'register') {
mode.value = value
error.value = ''
password.value = ''
}
async function submit() {
busy.value = true
error.value = ''
try {
await session.authenticate(mode.value, username.value, password.value, deviceName.value)
} catch (cause) {
error.value = cause instanceof Error ? cause.message : '操作失败,请稍后重试'
} finally {
busy.value = false
}
}
</script>
<template>
<main class="auth-shell">
<aside class="auth-brand">
<div class="brand"><span class="mark" aria-hidden="true">X</span>XHChat</div>
<div class="brand-art" aria-hidden="true"><span></span><span></span><span></span><span></span></div>
<p class="platform">{{ platform === 'windows' ? 'Windows 客户端' : 'Web 客户端' }}</p>
</aside>
<section class="auth-content">
<form class="auth-form" @submit.prevent="submit">
<div class="tabs" aria-label="账号操作">
<button type="button" :disabled="busy" :aria-pressed="mode === 'login'" @click="changeMode('login')">登录</button>
<button type="button" :disabled="busy" :aria-pressed="mode === 'register'" @click="changeMode('register')">注册</button>
</div>
<h1>{{ mode === 'login' ? '登录 XHChat' : '创建 XHChat 账号' }}</h1>
<label>用户名<input v-model="username" autocomplete="username" maxlength="32" pattern="[A-Za-z0-9_]{3,32}" placeholder="3–32 位字母、数字或下划线" required></label>
<label>密码<input v-model="password" :autocomplete="mode === 'login' ? 'current-password' : 'new-password'" type="password" minlength="12" maxlength="256" placeholder="至少 12 个字符" required></label>
<label>设备名称<input v-model="deviceName" maxlength="64" autocomplete="off" required></label>
<p v-if="error" class="error" role="alert">{{ error }}</p>
<button class="primary" :disabled="busy">{{ busy ? '正在验证设备…' : mode === 'login' ? '登录' : '创建账号' }}</button>
</form>
</section>
</main>
</template>
+135
View File
@@ -0,0 +1,135 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useSession } from '../session'
import type { Contact, ContactAction } from '../contacts'
const session = useSession()
const list = ref<Contact[]>([])
const search = ref('')
const result = ref<Contact>()
const selected = ref('')
const error = ref('')
const busy = ref(false)
const alias = ref('')
const category = ref('')
const detail = computed(() => list.value.find((contact) => contact.id === selected.value) ??
(result.value?.id === selected.value ? result.value : undefined))
const labels = { none: '可添加', incoming: '收到申请', outgoing: '等待接受', friend: '联系人', blocked: '已拉黑' }
const sections = [
{ state: 'incoming', label: '好友申请' },
{ state: 'friend', label: '好友' },
{ state: 'outgoing', label: '发出的申请' },
{ state: 'blocked', label: '黑名单' },
] as const
const pendingAction = ref<'delete' | 'block'>()
let refreshVersion = 0
async function refresh() {
const version = ++refreshVersion
const next = await session.contacts()
if (version === refreshVersion) list.value = next
}
async function operation(callback: () => Promise<void>) {
busy.value = true
error.value = ''
try {
await callback()
} catch (cause) {
error.value = cause instanceof Error ? cause.message : '操作失败,请稍后重试'
} finally {
busy.value = false
}
}
function refreshQuietly() {
void refresh().catch((cause: unknown) => {
error.value = cause instanceof Error ? cause.message : '无法加载联系人'
})
}
onMounted(refreshQuietly)
watch(() => [session.contactChanges, session.connection], ([, connection]) => {
if (connection === '实时连接已建立') refreshQuietly()
})
watch(selected, () => {
alias.value = detail.value?.alias ?? ''
category.value = detail.value?.category ?? ''
pendingAction.value = undefined
})
async function find() {
await operation(async () => {
const contact = await session.searchContact(search.value.trim())
result.value = contact
selected.value = contact.id
})
}
async function change(action: ContactAction) {
const contact = detail.value
if (!contact) return
await operation(async () => {
await session.changeContact(contact.id, action, alias.value, category.value)
pendingAction.value = undefined
if (['cancel', 'reject', 'delete', 'unblock'].includes(action)) {
result.value = undefined
selected.value = ''
}
await refresh()
})
}
</script>
<template>
<section class="contacts-layout">
<div class="contact-list">
<form class="contact-search" @submit.prevent="find">
<label>按用户名查找<input v-model="search" required maxlength="32" placeholder="输入完整用户名"></label>
<button class="plain" :disabled="busy">查找</button>
</form>
<section v-for="section in sections" :key="section.state" class="contact-group">
<template v-if="list.some((contact) => contact.state === section.state)">
<h2>{{ section.label }}</h2>
<button v-for="contact in list.filter((item) => item.state === section.state)" :key="contact.id"
type="button" class="contact-item" :aria-pressed="selected === contact.id" @click="selected = contact.id">
<span class="avatar" aria-hidden="true">{{ contact.username[0]?.toUpperCase() }}</span>
<span><strong>{{ contact.alias || contact.username }}</strong><small>{{ contact.category || '@' + contact.username }}</small></span>
</button>
</template>
</section>
<p v-if="!list.length" class="muted">还没有联系人</p>
</div>
<section class="contact-detail">
<p v-if="error" class="error" role="alert">{{ error }}</p>
<template v-if="detail">
<div class="contact-heading">
<span class="avatar" aria-hidden="true">{{ detail.username[0]?.toUpperCase() }}</span>
<div><h1>{{ detail.alias || detail.username }}</h1><small>@{{ detail.username }} · {{ labels[detail.state] }}</small></div>
</div>
<div v-if="detail.state === 'incoming'" class="contact-actions">
<button class="plain" :disabled="busy" @click="change('accept')">接受申请</button>
<button class="plain" :disabled="busy" @click="change('reject')">拒绝申请</button>
</div>
<button v-if="detail.state === 'none'" class="primary" :disabled="busy" @click="change('request')">添加好友</button>
<button v-if="detail.state === 'outgoing'" class="plain" :disabled="busy" @click="change('cancel')">取消申请</button>
<button v-if="detail.state === 'blocked'" class="plain" :disabled="busy" @click="change('unblock')">解除拉黑</button>
<form v-if="detail.state === 'friend'" class="contact-preferences" @submit.prevent="change('preferences')">
<label>备注<input v-model="alias" maxlength="64"></label>
<label>分组<input v-model="category" maxlength="32"></label>
<button class="plain" :disabled="busy">保存</button>
</form>
<div v-if="detail.state !== 'blocked'" class="contact-actions">
<button v-if="detail.state === 'friend'" class="plain danger" :disabled="busy" @click="pendingAction = 'delete'">删除好友</button>
<button class="plain danger" :disabled="busy" @click="pendingAction = 'block'">拉黑</button>
</div>
<section v-if="pendingAction" class="confirmation" aria-label="确认联系人操作">
<p>{{ pendingAction === 'block' ? '拉黑将移除好友关系并阻止新的好友申请。' : '删除后,双方的好友关系将解除。' }}</p>
<button class="plain" @click="pendingAction = undefined">取消</button>
<button class="plain danger" :disabled="busy" @click="change(pendingAction)">确认</button>
</section>
</template>
<p v-else-if="!error" class="muted">选择联系人,或按用户名查找。</p>
</section>
</section>
</template>
+62
View File
@@ -0,0 +1,62 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useSession } from '../session'
import type { Device } from '../session'
const session = useSession()
const devices = ref<Device[]>([])
const error = ref('')
const busy = ref(false)
const target = ref<Device>()
const dates = new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium', timeStyle: 'short' })
async function perform(operation: () => Promise<void>) {
busy.value = true
error.value = ''
try {
await operation()
} catch (cause) {
error.value = cause instanceof Error ? cause.message : '操作失败,请稍后重试'
} finally {
busy.value = false
}
}
const refresh = () => perform(async () => { devices.value = await session.devices() })
onMounted(refresh)
async function revoke() {
if (!target.value) return
const id = target.value.id
target.value = undefined
await perform(async () => {
await session.revoke(id)
devices.value = await session.devices()
})
}
</script>
<template>
<section v-if="session.identity" class="device-page">
<header class="page-header"><h1>设备管理</h1><button class="plain" :disabled="busy" @click="refresh">刷新</button></header>
<div class="device-content">
<p v-if="error" class="error" role="alert">{{ error }}</p>
<p v-if="busy && !devices.length" role="status">正在载入设备…</p>
<article v-for="device in devices" :key="device.id" class="device-row">
<span class="device-icon" aria-hidden="true">▣</span>
<div class="device-meta">
<div><strong>{{ device.name }}</strong><span v-if="device.id === session.identity.device.id" class="tag">当前设备</span></div>
<small>{{ device.platform === 'windows' ? 'Windows · 桌面端' : 'Web · 浏览器' }} · {{ device.signedIn ? '已登录' : '已退出' }}</small>
<small>首次登录 {{ dates.format(new Date(device.createdAt)) }} · 最近活动 {{ dates.format(new Date(device.lastActiveAt)) }}</small>
</div>
<span v-if="device.revokedAt" class="muted">已撤销</span>
<button v-else-if="device.id !== session.identity.device.id" class="plain danger" :disabled="busy" @click="target = device">撤销</button>
</article>
<section v-if="target" class="confirmation" aria-label="确认撤销">
<p>撤销「{{ target.name }}」后,该设备的登录会话将结束。</p>
<button class="plain" @click="target = undefined">取消</button>
<button class="plain danger" @click="revoke">确认撤销</button>
</section>
</div>
</section>
</template>
+49
View File
@@ -0,0 +1,49 @@
<script setup lang="ts">
import { ref } from 'vue'
import { useSession } from '../session'
const session = useSession()
const error = ref('')
const busy = ref(false)
const browser = window.xhchat?.openBrowser
async function act(action: () => Promise<void>) {
busy.value = true
error.value = ''
try {
await action()
} catch (cause) {
error.value = cause instanceof Error ? cause.message : '操作失败,请稍后重试'
} finally {
busy.value = false
}
}
</script>
<template>
<main v-if="session.identity" class="workspace">
<nav class="rail" aria-label="主导航">
<RouterLink class="mark" to="/devices" aria-label="XHChat">X</RouterLink>
<RouterLink class="rail-link" to="/contacts" title="联系人" aria-label="联系人">人</RouterLink>
<RouterLink class="rail-link" to="/devices" title="设备管理" aria-label="设备管理">▣</RouterLink>
<button v-if="browser" type="button" class="rail-link browser-button" title="浏览器" aria-label="浏览器" @click="act(browser)">◎</button>
</nav>
<aside class="account-panel">
<div class="account-summary">
<span class="avatar" aria-hidden="true">{{ session.identity.user.username[0]?.toUpperCase() }}</span>
<div><strong>{{ session.identity.user.username }}</strong><small>我的账号</small></div>
</div>
<nav class="panel-links" aria-label="工作区">
<RouterLink to="/contacts">联系人</RouterLink>
<RouterLink to="/devices">设备管理</RouterLink>
<button v-if="browser" class="plain mobile-browser" @click="act(browser)">浏览器</button>
</nav>
<div class="account-footer">
<p aria-live="polite"><span class="dot" :class="{ online: session.connection === '实时连接已建立' }"></span>{{ session.connection }}</p>
<p v-if="error" class="error" role="alert">{{ error }}</p>
<button class="plain" :disabled="busy" @click="act(session.logout)">退出登录</button>
</div>
</aside>
<RouterView />
</main>
</template>
+9
View File
@@ -0,0 +1,9 @@
{
"compilerOptions": {
"target": "ES2022", "module": "ESNext", "moduleResolution": "Bundler",
"strict": true, "noEmit": true, "verbatimModuleSyntax": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"], "types": ["vite/client", "node"],
"skipLibCheck": true
},
"include": ["src/**/*.ts", "src/**/*.vue", "vite.config.ts"]
}
+13
View File
@@ -0,0 +1,13 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
server: {
host: '127.0.0.1',
strictPort: true,
proxy: {
'/api': { target: 'http://127.0.0.1:8080', ws: true },
},
},
})