diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..273ac7a --- /dev/null +++ b/.dockerignore @@ -0,0 +1,8 @@ +**/node_modules +**/dist +**/test-results +.env +.git +docs +Android +server diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..51d9768 --- /dev/null +++ b/.env.example @@ -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 diff --git a/Desktop/browser/index.html b/Desktop/browser/index.html new file mode 100644 index 0000000..9c78239 --- /dev/null +++ b/Desktop/browser/index.html @@ -0,0 +1,30 @@ + + + + + + XHChat 浏览器 + + + + +
+
+
+ + + + + + + + + + + + +
+
+
+ + diff --git a/Desktop/browser/style.css b/Desktop/browser/style.css new file mode 100644 index 0000000..7e8afed --- /dev/null +++ b/Desktop/browser/style.css @@ -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; } } diff --git a/Desktop/browser/ui.js b/Desktop/browser/ui.js new file mode 100644 index 0000000..0e1929c --- /dev/null +++ b/Desktop/browser/ui.js @@ -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') diff --git a/Desktop/package.json b/Desktop/package.json new file mode 100644 index 0000000..e9eafc6 --- /dev/null +++ b/Desktop/package.json @@ -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"}} diff --git a/Desktop/src/browser-preload.ts b/Desktop/src/browser-preload.ts new file mode 100644 index 0000000..889eb2c --- /dev/null +++ b/Desktop/src/browser-preload.ts @@ -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)) + }, +}) diff --git a/Desktop/src/browser.ts b/Desktop/src/browser.ts new file mode 100644 index 0000000..5abcb26 --- /dev/null +++ b/Desktop/src/browser.ts @@ -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() + +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() + +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) + }) +} diff --git a/Desktop/src/identity.ts b/Desktop/src/identity.ts new file mode 100644 index 0000000..8f93a61 --- /dev/null +++ b/Desktop/src/identity.ts @@ -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>>() + +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 } +} diff --git a/Desktop/src/main.ts b/Desktop/src/main.ts new file mode 100644 index 0000000..a46c6f1 --- /dev/null +++ b/Desktop/src/main.ts @@ -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()) +} diff --git a/Desktop/src/preload.ts b/Desktop/src/preload.ts new file mode 100644 index 0000000..1bc0fc5 --- /dev/null +++ b/Desktop/src/preload.ts @@ -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'), +}) diff --git a/Desktop/tsconfig.json b/Desktop/tsconfig.json new file mode 100644 index 0000000..669d586 --- /dev/null +++ b/Desktop/tsconfig.json @@ -0,0 +1,8 @@ +{ + "compilerOptions": { + "target":"ES2022", "module":"Node16", "moduleResolution":"Node16", + "strict":true, "rootDir":"src", "outDir":"dist", + "esModuleInterop":true, "skipLibCheck":true + }, + "include":["src/**/*.ts"] +} diff --git a/README.md b/README.md index 9f66748..37cc89c 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ 本仓库公开源码供查阅,修改、分发与部署需经权利人书面授权。禁止将查阅权限用于违法活动。详见 [XHChat 源码查阅许可协议](LICENSE)。 -Windows 桌面端位于 `Desktop`,Web 客户端位于 `web`。当前版本实现用户名注册和登录、独立设备身份、设备查看与撤销、退出登录及经认证的实时连接。完整产品按 [阶段进度](docs/progress.md) 交付。 +Windows 桌面端位于 `Desktop`,Web 客户端位于 `web`。当前版本实现用户名注册与登录、设备管理、实时联系人管理和隔离的 Chromium 浏览器窗口。完整产品按 [阶段进度](docs/progress.md) 交付。 ## 本地运行 diff --git a/deploy/nginx.conf b/deploy/nginx.conf new file mode 100644 index 0000000..669ede3 --- /dev/null +++ b/deploy/nginx.conf @@ -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; } +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..dc1f0e1 --- /dev/null +++ b/docker-compose.yml @@ -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: diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 0000000..d727d0f --- /dev/null +++ b/docs/api.md @@ -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 与独立的管理接口。 diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..5ad9425 --- /dev/null +++ b/docs/architecture.md @@ -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 +``` + +管理端计划使用独立域名、凭据和数据库角色。指标聚合使用投递计数、调用状态和基础设施容量。管理角色只需接触运营元数据。 diff --git a/docs/browser-security.md b/docs/browser-security.md new file mode 100644 index 0000000..d8f6170 --- /dev/null +++ b/docs/browser-security.md @@ -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 与最小权限用于降低执行恶意代码的风险。设备已解锁且被完全控制时,应用不能保护当前可解密内容。 diff --git a/docs/database.md b/docs/database.md new file mode 100644 index 0000000..1b540de --- /dev/null +++ b/docs/database.md @@ -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 添加联系人关系、黑名单和备注。设备撤销和会话清除在同一个事务内处理。阶段二以事务分配单调投递游标,连接恢复后从持久层补拉。消息保留和附件清理分别由后台作业处理,下载授权按目标设备和对象关联重新检查。 diff --git a/docs/deployment.md b/docs/deployment.md new file mode 100644 index 0000000..e99a606 --- /dev/null +++ b/docs/deployment.md @@ -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 短期状态。阶段一暂无聊天和附件数据。 diff --git a/docs/encryption.md b/docs/encryption.md new file mode 100644 index 0000000..79314e1 --- /dev/null +++ b/docs/encryption.md @@ -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 管理脚本信任,当前页面的恶意同源脚本属于独立威胁。 diff --git a/docs/progress.md b/docs/progress.md new file mode 100644 index 0000000..5756b07 --- /dev/null +++ b/docs/progress.md @@ -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 标识。测试同时验证地址栏拒绝本地文件协议。 diff --git a/docs/realtime-media.md b/docs/realtime-media.md new file mode 100644 index 0000000..ed23572 --- /dev/null +++ b/docs/realtime-media.md @@ -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 无法解密及不支持环境阻止发布。 diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..8e72c24 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,2067 @@ +{ + "name": "xhchat", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "xhchat", + "workspaces": [ + "web", + "Desktop" + ], + "devDependencies": { + "playwright": "1.65.0", + "ws": "8.23.0" + } + }, + "Desktop": { + "name": "@xhchat/desktop", + "version": "0.1.0", + "devDependencies": { + "@types/node": "^24.0.0", + "electron": "45.3.1", + "typescript": "~6.0.3" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", + "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", + "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.14" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", + "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.14", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@electron-internal/extract-zip": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@electron-internal/extract-zip/-/extract-zip-1.0.8.tgz", + "integrity": "sha512-8iajeLFbzNwM0m3AsQZSZgYREWglAImyGvvFSWU34FgMW8sHlzdwj9QKvv9dgN7jMP591EFUF/sLOC3Jl9YIjQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/@electron/get": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@electron/get/-/get-5.1.0.tgz", + "integrity": "sha512-3kSBtG8ObcTVfXanm5vVJ6UnBLEVmVsRk1M+vGqCuMBV+XLCbJYuWQful+yIy0GQDsSlK0kHEriEHn7SPk4EnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.1.1", + "env-paths": "^3.0.0", + "graceful-fs": "^4.2.11", + "progress": "^2.0.3", + "semver": "^7.6.3", + "sumchecker": "^3.0.1" + }, + "engines": { + "node": ">=22.12.0" + }, + "optionalDependencies": { + "undici": "^7.24.4" + } + }, + "node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "devOptional": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==", + "cpu": [ + "wasm32" + ], + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz", + "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==", + "license": "MIT" + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz", + "integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.19.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz", + "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, + "node_modules/@vitejs/plugin-vue": { + "version": "6.0.11", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-6.0.11.tgz", + "integrity": "sha512-m48lskIUJGlB6qUiYhDMI8nd2ngeidz2U4nKTjqI13cFMu5rH8JeEILPkDtK9Fk/TjBA2pkj8AlbenqDaKu+ww==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0", + "vue": "^3.2.25 || ^3.6.0-rc.15" + } + }, + "node_modules/@volar/language-core": { + "version": "2.4.30", + "resolved": "https://registry.npmjs.org/@volar/language-core/-/language-core-2.4.30.tgz", + "integrity": "sha512-73fjwEV8wat6aOZ6U/y/hqtE30ocrIWECg67b0txGczOMNw+MffLmvJ5fnFfN9drVUEYZzLdaNo6VAy6G6avMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/source-map": "2.4.30" + } + }, + "node_modules/@volar/language-service": { + "version": "2.4.30", + "resolved": "https://registry.npmjs.org/@volar/language-service/-/language-service-2.4.30.tgz", + "integrity": "sha512-w/xDsASiqC71ggCOm7sTDXDNk/l72XEptodeRC68tgZ0e5QM4hM3zAqBGC7mBctvhrpYwKfMG+t9xcUo2hEFtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "2.4.30", + "vscode-languageserver-protocol": "^3.17.5", + "vscode-languageserver-textdocument": "^1.0.11", + "vscode-uri": "^3.0.8" + }, + "peerDependencies": { + "typescript": "<7" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@volar/source-map": { + "version": "2.4.30", + "resolved": "https://registry.npmjs.org/@volar/source-map/-/source-map-2.4.30.tgz", + "integrity": "sha512-zym1ob/KwDDyN+0jGVtxwbxJSRRnUvv5HspCtz3yEfVVdCG4/dzxJktMGPAgemqRuVs81O0o/y0q3qOUErR8kg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@volar/typescript": { + "version": "2.4.30", + "resolved": "https://registry.npmjs.org/@volar/typescript/-/typescript-2.4.30.tgz", + "integrity": "sha512-/DgA5tgYFPfrLFuSjIMXMGHk1LQv2+P8eny6+BhGNzFJELWIW7UZlc56ZLIRFhLsPpMfIFxM8/HvOPBggrjTZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "2.4.30", + "@volar/language-service": "2.4.30", + "path-browserify": "^1.0.1", + "vscode-uri": "^3.0.8" + }, + "peerDependencies": { + "typescript": "<7" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@vue-macros/common": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/@vue-macros/common/-/common-3.1.4.tgz", + "integrity": "sha512-/5Fv+6DgIcM9ajY05ZmKBv+LMX1M9A0X+IUwDRVdt67ciw8OV9bvG2r34p3RiEadlsQybjhKPRKNXDC8Bp23cw==", + "license": "MIT", + "dependencies": { + "@vue/compiler-sfc": "^3.5.22", + "ast-kit": "^2.1.2", + "local-pkg": "^1.1.2", + "magic-string-ast": "^1.0.2", + "unplugin-utils": "^0.3.0" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/sponsors/vue-macros" + }, + "peerDependencies": { + "vue": "^2.7.0 || ^3.2.25" + }, + "peerDependenciesMeta": { + "vue": { + "optional": true + } + } + }, + "node_modules/@vue/compiler-core": { + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.45.tgz", + "integrity": "sha512-XGHJrM6ufZARAc/w+tyOswStw9tdKiqCKBScI4gGaNxD+aaGu/HQWgKJ+JItjRLPqenQ7iE7G8AJC7T5ew1p+g==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.12", + "@vue/shared": "3.5.45", + "entities": "^7.0.1", + "estree-walker": "^2.0.2", + "source-map-js": "^1.2.2" + } + }, + "node_modules/@vue/compiler-dom": { + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.45.tgz", + "integrity": "sha512-LbP2d19GSOYGPmvMBBCVJVlv7TKtjM1Cfeyu3cYia720pknZP+1cLX7H5MVatvruT6MuJhiPuNbQBW/MDn/EwA==", + "license": "MIT", + "dependencies": { + "@vue/compiler-core": "3.5.45", + "@vue/shared": "3.5.45" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.45.tgz", + "integrity": "sha512-MKFjb2UX0M/l/jhfzqMLrI8VM4pfvFKG3pqFZkSZFHRLtNld/O4RtUPZFWSwhro/14qP88UQEkWzHxAZAQ0tsw==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.12", + "@vue/compiler-core": "3.5.45", + "@vue/compiler-dom": "3.5.45", + "@vue/compiler-ssr": "3.5.45", + "@vue/shared": "3.5.45", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.21", + "postcss": "^8.5.32", + "source-map-js": "^1.2.2" + } + }, + "node_modules/@vue/compiler-ssr": { + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.45.tgz", + "integrity": "sha512-RF5sbZOfYz5AK00tOJUn2PwFXR2fS1u2HVzI8D9VF9rGAFxuGBqg2bB1kJ3ZHMprqSltXnT9MZE1IsqjSM8oew==", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.45", + "@vue/shared": "3.5.45" + } + }, + "node_modules/@vue/devtools-api": { + "version": "8.2.1", + "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-8.2.1.tgz", + "integrity": "sha512-6u4vXBlIBAC1wMplIZgpyPn7uh/s4Bf6F5bMzvLv+EdJ0aHs/+4B7Ygv864EStQSjRbsRzTko/kUG1A1IejQ3A==", + "license": "MIT", + "dependencies": { + "@vue/devtools-kit": "^8.2.1" + } + }, + "node_modules/@vue/devtools-kit": { + "version": "8.2.1", + "resolved": "https://registry.npmjs.org/@vue/devtools-kit/-/devtools-kit-8.2.1.tgz", + "integrity": "sha512-FIGIuq3AWReEpbAHY/cRGeHDfI0qOb8OCQ3YjbEAX04uaxIDbGc9rhkbVcG7rnfHPXE3RsU5KrWOu9V/okd8AQ==", + "license": "MIT", + "dependencies": { + "@vue/devtools-shared": "^8.2.1", + "birpc": "^2.6.1", + "hookable": "^5.5.3", + "perfect-debounce": "^2.0.0" + } + }, + "node_modules/@vue/devtools-shared": { + "version": "8.2.1", + "resolved": "https://registry.npmjs.org/@vue/devtools-shared/-/devtools-shared-8.2.1.tgz", + "integrity": "sha512-Fkac7lUdGReh6pVOi3AYPRGe82LQqRmAfThW7RRligOAP0ZA/Z1z9XLHDM9dv34pV2HRc79DK8uKPeG2fLnA/g==", + "license": "MIT" + }, + "node_modules/@vue/language-core": { + "version": "3.3.14", + "resolved": "https://registry.npmjs.org/@vue/language-core/-/language-core-3.3.14.tgz", + "integrity": "sha512-kRB+3hHg0c+BdD1XLAvwjVMQd5pC05zijSlPDRI3ERvC/s04JlRs5upy2KjeMg/9m9oD5zuMVh9yVvkKfZqoJg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/language-core": "2.4.30", + "@vue/compiler-dom": "^3.5.0", + "@vue/shared": "^3.5.0", + "alien-signals": "^3.2.1", + "muggle-string": "^0.4.1", + "path-browserify": "^1.0.1", + "picomatch": "^4.0.4" + } + }, + "node_modules/@vue/reactivity": { + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.45.tgz", + "integrity": "sha512-WqkyubNWpI4OYBOipSrjIssMdJO8K1i9Zts/Wm8Er10/0msOEwCyWWWvZnAI7WW3kQsTong6DJp8Cbb+vd4cPA==", + "license": "MIT", + "dependencies": { + "@vue/shared": "3.5.45" + } + }, + "node_modules/@vue/runtime-core": { + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.45.tgz", + "integrity": "sha512-bzIO3+FABjpj85uIKSc+Qnj36/sxDNI3tcH9i6w6xKA1k6e0ejv0G0jMCfeJBvK3yGL5XbJ3DMZj+ClqyCHFYw==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.45", + "@vue/shared": "3.5.45" + } + }, + "node_modules/@vue/runtime-dom": { + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.45.tgz", + "integrity": "sha512-ZvRTFMDgfqTDYWvJfoVpQTJx1RN5M6l7Pyd6wfdY2NaXzbPQVh9ezeQYFbNPP6bIcRVn2SqSSR25N/jSW69BFw==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.45", + "@vue/runtime-core": "3.5.45", + "@vue/shared": "3.5.45", + "csstype": "^3.2.3" + } + }, + "node_modules/@vue/server-renderer": { + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.45.tgz", + "integrity": "sha512-1fNXUHhhsWf4EVL4XixbGBU5mKdiIXJAB82feHRTyPPo6ZUEYWIJuEeUl3mVV6QDBp50HJOX4obLhxYXlrjrzA==", + "license": "MIT", + "dependencies": { + "@vue/compiler-ssr": "3.5.45", + "@vue/runtime-dom": "3.5.45", + "@vue/shared": "3.5.45" + } + }, + "node_modules/@vue/shared": { + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.45.tgz", + "integrity": "sha512-ue9fgHmVNPlP7iW3+cxoBX/Cnlw53dHlVSw0JKGY6z1lObg8pHoj928M2nzG4/yVsMZ3NaRZ2s2z61uC16NDwQ==", + "license": "MIT" + }, + "node_modules/@xhchat/desktop": { + "resolved": "Desktop", + "link": true + }, + "node_modules/@xhchat/web": { + "resolved": "web", + "link": true + }, + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/alien-signals": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/alien-signals/-/alien-signals-3.2.1.tgz", + "integrity": "sha512-I8FjmltrfnDFoZedi5CG8DghVYNhzb/Ijluz7tCSJH0xpd0484Kowhbb1XDYOxfJpU1p5wnM2X54dA+IfGyD1g==", + "dev": true, + "license": "MIT" + }, + "node_modules/ast-kit": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/ast-kit/-/ast-kit-2.2.0.tgz", + "integrity": "sha512-m1Q/RaVOnTp9JxPX+F+Zn7IcLYMzM8kZofDImfsKZd8MbR+ikdOzTeztStWqfrqIxZnYWryyI9ePm3NGjnZgGw==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.28.5", + "pathe": "^2.0.3" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/sponsors/sxzz" + } + }, + "node_modules/ast-walker-scope": { + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/ast-walker-scope/-/ast-walker-scope-0.10.0.tgz", + "integrity": "sha512-KzvoxDfXNz2Gm8KYLh47K3qcY3Zza3WKOuh2xoqa7LBu6MDKWAZLovJtU9DuAd/Er+rhQHCRn619lHS5U+qmhw==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^8.0.0", + "@babel/types": "^8.0.0", + "ast-kit": "^3.0.0" + }, + "engines": { + "node": "^22.18.0 || >=24.11.0" + }, + "funding": { + "url": "https://github.com/sponsors/sxzz" + } + }, + "node_modules/ast-walker-scope/node_modules/@babel/helper-string-parser": { + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.1.2.tgz", + "integrity": "sha512-TRz5Z0MgfIfWqwEIq/pCpUpEXQxUt2Ig2ZbxG3SdmhSbHMAFFYGOix0kI4JLV371/TA+qWnQ4xWHPWjojkyRFA==", + "license": "MIT", + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/ast-walker-scope/node_modules/@babel/helper-validator-identifier": { + "version": "8.0.6", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.6.tgz", + "integrity": "sha512-HYx0YmuchRxRSpnjvcNffnPS8DCauKNmnumIuHG3jnQAVewRA7kfJGwF13ayEpSZs7s4R/oBH4eppuXcAQd5JQ==", + "license": "MIT", + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/ast-walker-scope/node_modules/@babel/parser": { + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.1.2.tgz", + "integrity": "sha512-ZDKU7vaX0VORd2BhaO+3FKr/30TKjbUy3SMZcydiPngnAb+MesgUoh5SJcE5EwEyBj14M5J6fK56GuBqvYmOpw==", + "license": "MIT", + "dependencies": { + "@babel/types": "^8.1.2" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/ast-walker-scope/node_modules/@babel/types": { + "version": "8.1.2", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-8.1.2.tgz", + "integrity": "sha512-uXt6qt2f5G61jZwNIzK1RKu7l5Xjt1VXtPPOGuVveha9fxbx0QM94U1kM4pFZKTRLjWK+X8vmwjwbIemJjiQTA==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^8.1.2", + "@babel/helper-validator-identifier": "^8.0.6" + }, + "engines": { + "node": "^22.18.0 || >=24.11.0" + } + }, + "node_modules/ast-walker-scope/node_modules/ast-kit": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ast-kit/-/ast-kit-3.0.1.tgz", + "integrity": "sha512-fCGiQvmHghhf858e/SVGh2aUo/FsbtB5qB8bifo6ygHK5OMcGna56FUvS0IrYvo+unYwIi1nCklEh/KUaOKVmg==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^8.1.0", + "estree-walker": "^3.0.3", + "pathe": "^2.0.3" + }, + "engines": { + "node": "^22.18.0 || >=24.11.0" + }, + "funding": { + "url": "https://github.com/sponsors/sxzz" + } + }, + "node_modules/ast-walker-scope/node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/birpc": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/birpc/-/birpc-2.9.0.tgz", + "integrity": "sha512-KrayHS5pBi69Xi9JmvoqrIgYGDkD6mcSe/i6YKi3w5kekCLzrX4+nawcXqrj2tIp50Kw/mT/s3p+GVK0A0sKxw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/chokidar": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", + "license": "MIT", + "dependencies": { + "readdirp": "^5.0.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/confbox": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.3.2.tgz", + "integrity": "sha512-ZUAKhKlkCOrIGKc8cj7zek9s9z1mveHif/25nUshI2BzCRzF7KH7KHa+Lnh2ubq+e1tIlaFuP763mzW4qVoehg==", + "license": "MIT" + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "devOptional": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/electron": { + "version": "45.3.1", + "resolved": "https://registry.npmjs.org/electron/-/electron-45.3.1.tgz", + "integrity": "sha512-1oYau2B4RXF27Df2fzvrFDJoy8AOSVlgS6gklo6wkLZ/QWJemJCJHkY4+uuacvSFUtR8IimiLukLNFoYP0fmjA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@electron-internal/extract-zip": "^1.0.1", + "@electron/get": "^5.0.0", + "@types/node": "^24.9.0" + }, + "bin": { + "electron": "cli.js", + "install-electron": "install.js" + }, + "engines": { + "node": ">= 22.12.0" + } + }, + "node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/env-paths": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz", + "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "license": "MIT" + }, + "node_modules/exsolve": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/exsolve/-/exsolve-1.2.0.tgz", + "integrity": "sha512-h1pQPR9XoeSMdntRNCjyTznaume4UpfXrULBnlkZ2CUM/G5eSa+pBByGldO5uR8dxbPC+OuJXsPPNf+JZ81ADg==", + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.12", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.12.tgz", + "integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, + "node_modules/hookable": { + "version": "5.5.3", + "resolved": "https://registry.npmjs.org/hookable/-/hookable-5.5.3.tgz", + "integrity": "sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==", + "license": "MIT" + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "devOptional": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/local-pkg": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-1.2.1.tgz", + "integrity": "sha512-++gUqRDEvcnN6Zhqrr+y/CkVEHhlrR96vZn3nZZPYzMcBUyBtTKzB9NadClFIsIVSsu+3i9tfk/erqy9kAmt7Q==", + "license": "MIT", + "dependencies": { + "mlly": "^1.7.4", + "pkg-types": "^2.3.0", + "quansync": "^0.2.11" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/magic-string-ast": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/magic-string-ast/-/magic-string-ast-1.0.3.tgz", + "integrity": "sha512-CvkkH1i81zl7mmb94DsRiFeG9V2fR2JeuK8yDgS8oiZSFa++wWLEgZ5ufEOyLHbvSbD1gTRKv9NdX69Rnvr9JA==", + "license": "MIT", + "dependencies": { + "magic-string": "^0.30.19" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/sponsors/sxzz" + } + }, + "node_modules/mlly": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.2.tgz", + "integrity": "sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==", + "license": "MIT", + "dependencies": { + "acorn": "^8.16.0", + "pathe": "^2.0.3", + "pkg-types": "^1.3.1", + "ufo": "^1.6.3" + } + }, + "node_modules/mlly/node_modules/confbox": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz", + "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", + "license": "MIT" + }, + "node_modules/mlly/node_modules/pkg-types": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz", + "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==", + "license": "MIT", + "dependencies": { + "confbox": "^0.1.8", + "mlly": "^1.7.4", + "pathe": "^2.0.1" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/muggle-string": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/muggle-string/-/muggle-string-0.4.1.tgz", + "integrity": "sha512-VNTrAak/KhO2i8dqqnqnAHOa3cYBwXEZe9h+D5h/1ZqFSTEFHdM65lR7RoIqq3tBBYavsOXV84NoHXZ0AkPyqQ==", + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/nostics": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/nostics/-/nostics-1.3.0.tgz", + "integrity": "sha512-wzRsrJwNlFbqIRQt8aCeL2WE8USip/uuvGSOZV1D02CxX8ABTMbw8IywKjH7yWHETMXbWJI4OBpihg9rmz2Vyg==", + "license": "MIT" + }, + "node_modules/path-browserify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", + "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "license": "MIT" + }, + "node_modules/perfect-debounce": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-2.1.0.tgz", + "integrity": "sha512-LjgdTytVFXeUgtHZr9WYViYSM/g8MkcTPYDlPa3cDqMirHjKiSZPYd6DoL7pK8AJQr+uWkQvCjHNdiMqsrJs+g==", + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pinia": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/pinia/-/pinia-4.1.0.tgz", + "integrity": "sha512-+5/HMuVjYQfKlCD5xQ7zfXn1xUzYFEa7pd0DQK5SaMfZCaFRTHlaH/c02N1FoGOdlzSiwf5EOPgJx//1QDw6gw==", + "license": "MIT", + "dependencies": { + "nostics": "^1.2.0" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "@vue/devtools-api": "^8.2.1", + "typescript": ">=5.6.0", + "vue": "^3.5.11" + }, + "peerDependenciesMeta": { + "@vue/devtools-api": { + "optional": false + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/pkg-types": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.4.0.tgz", + "integrity": "sha512-07Fys7iVx0X6TcviMOgogM1Lk33ZyqOezMnU79S+kffWqwolG/5W9V8EgQSeYCIfFTYVgssRbnH630Oa2+soBA==", + "license": "MIT", + "dependencies": { + "confbox": "^0.3.1", + "exsolve": "^1.1.3", + "pathe": "^2.0.3" + } + }, + "node_modules/playwright": { + "version": "1.65.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.0.tgz", + "integrity": "sha512-F3AMWcR44qMBt4kq+6Kb6mX7bjGXshktKFOPULd7reED6ZJWevjbNRqysP7q+AATE9kdPEZBibex1BYsvpVoeA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.65.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.65.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.0.tgz", + "integrity": "sha512-vNSKgH6YqtN7cdT/L334zo0a+YwkrpicyrHJlWWPIm/Q+Nn2SWInil01oT0mbu96U4GgoRtCYQD9CzJQgju+lA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/quansync": { + "version": "0.2.11", + "resolved": "https://registry.npmjs.org/quansync/-/quansync-0.2.11.tgz", + "integrity": "sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/antfu" + }, + { + "type": "individual", + "url": "https://github.com/sponsors/sxzz" + } + ], + "license": "MIT" + }, + "node_modules/readdirp": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", + "integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/rolldown": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.19", + "@rolldown/binding-android-arm64": "1.2.19", + "@rolldown/binding-darwin-arm64": "1.2.19", + "@rolldown/binding-darwin-x64": "1.2.19", + "@rolldown/binding-freebsd-x64": "1.2.19", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", + "@rolldown/binding-linux-arm64-gnu": "1.2.19", + "@rolldown/binding-linux-arm64-musl": "1.2.19", + "@rolldown/binding-linux-ppc64-gnu": "1.2.19", + "@rolldown/binding-linux-s390x-gnu": "1.2.19", + "@rolldown/binding-linux-x64-gnu": "1.2.19", + "@rolldown/binding-linux-x64-musl": "1.2.19", + "@rolldown/binding-openharmony-arm64": "1.2.19", + "@rolldown/binding-wasm32-wasi": "1.2.19", + "@rolldown/binding-win32-arm64-msvc": "1.2.19", + "@rolldown/binding-win32-x64-msvc": "1.2.19" + } + }, + "node_modules/scule": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/scule/-/scule-1.3.0.tgz", + "integrity": "sha512-6FtHJEvt+pVMIB9IBY+IcCJ6Z5f1iQnytgyfKMhDKgmzYG+TeH/wx1y3l27rshSbLiSanrR9ffZDrEsmjlQF2g==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/sumchecker": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz", + "integrity": "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "debug": "^4.1.0" + }, + "engines": { + "node": ">= 8.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "license": "0BSD", + "optional": true + }, + "node_modules/typescript": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/ufo": { + "version": "1.6.4", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.4.tgz", + "integrity": "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==", + "license": "MIT" + }, + "node_modules/undici": { + "version": "7.30.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.2.tgz", + "integrity": "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/undici-types": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/unplugin": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/unplugin/-/unplugin-3.7.0.tgz", + "integrity": "sha512-GrM2uq3DQo3hvLU2FjeYhooJ8BY9N6j1Fbzgx7Pta3VVJevsD3VP4dPjZkZOS0mLvN8w9zzr9OlP+31bSMyuLw==", + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "@rolldown/pluginutils": "^1.0.1", + "picomatch": "^4.0.7", + "webpack-virtual-modules": "^0.6.2" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@farmfe/core": "*", + "@rsbuild/core": "*", + "@rspack/core": "*", + "bun-types-no-globals": "*", + "esbuild": "*", + "rolldown": "*", + "rollup": "*", + "unloader": "*", + "vite": "*", + "webpack": "*" + }, + "peerDependenciesMeta": { + "@farmfe/core": { + "optional": true + }, + "@rsbuild/core": { + "optional": true + }, + "@rspack/core": { + "optional": true + }, + "bun-types-no-globals": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "rolldown": { + "optional": true + }, + "rollup": { + "optional": true + }, + "unloader": { + "optional": true + }, + "vite": { + "optional": true + }, + "webpack": { + "optional": true + } + } + }, + "node_modules/unplugin-utils": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/unplugin-utils/-/unplugin-utils-0.3.2.tgz", + "integrity": "sha512-xVToRh2CTmLk2HnEG7ac4rl1MJTT3RFkpS8B++/SnB0kXvuaavD+n3m/vrzyWQOdJNSZQACnbz01pnppbwV5BA==", + "license": "MIT", + "dependencies": { + "pathe": "^2.0.3", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/sponsors/sxzz" + } + }, + "node_modules/vite": { + "version": "8.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz", + "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vscode-jsonrpc": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-10.0.0.tgz", + "integrity": "sha512-USSfxg0vDIpTQqlQBGxF3mBARyoS8cU7LHLpbYNh6dOJt32dlskxPWB0Irrh5TllTmyf7oNLAvqDqzklbwwnpA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.17.0" + } + }, + "node_modules/vscode-languageserver-protocol": { + "version": "3.18.5", + "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.18.5.tgz", + "integrity": "sha512-FW4fBMzZ99N8xeob4py0l050wgCoRgTpEq5Xcsb9lM1bc29UKGR/wSV+4knaqFxssFHajy7OzNiKP/m3U1ZEuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "vscode-jsonrpc": "10.0.0", + "vscode-languageserver-types": "3.18.5" + } + }, + "node_modules/vscode-languageserver-textdocument": { + "version": "1.0.16", + "resolved": "https://registry.npmjs.org/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.16.tgz", + "integrity": "sha512-qeNEuOi9a3qkqRf7Gfez2WL2VwlBTLCNekHBGO9kxPVUp9XuY15yfTJ9jwvOwKI0I2MhUUfZq95NSp+LK1CLQg==", + "dev": true, + "license": "MIT" + }, + "node_modules/vscode-languageserver-types": { + "version": "3.18.5", + "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.18.5.tgz", + "integrity": "sha512-kPd6+JQNz3HMJvjKlqUxERSlZHAntl/aGpsk7ImwIh0ewDKDcjgAEyVSYciPiOJD3ftbK9IrfiqUeTZLSbCizw==", + "dev": true, + "license": "MIT" + }, + "node_modules/vscode-uri": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-3.2.0.tgz", + "integrity": "sha512-m2gXo3bn0G1kT9InzMf07fTbqMbGtyckj3bH5ktLO+1Ssv+yiATZ4dhwaQv9UZWxJh6E9IFGnQyjgWVDWVBDrg==", + "dev": true, + "license": "MIT" + }, + "node_modules/vue": { + "version": "3.5.45", + "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.45.tgz", + "integrity": "sha512-3cvsib8m9c0vB24+MDKsgcW4+Da4xaBl9Z/5Tbm2pmSIsRPxcil4cdXjXlVsmJ2g64XJo5h+IRd7rsdGT9pZaw==", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.45", + "@vue/compiler-sfc": "3.5.45", + "@vue/runtime-dom": "3.5.45", + "@vue/server-renderer": "3.5.45", + "@vue/shared": "3.5.45" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/vue-router": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-5.5.0.tgz", + "integrity": "sha512-nYhG+YzLcrO5Z7KbH1H/xvBeBzhCWhQG0z5DYNLuaJULhavZBmEgoQ5xVHGxwe65c5hnJQHZpBxWdQhnOBzHmw==", + "license": "MIT", + "dependencies": { + "@vue-macros/common": "^3.1.3", + "@vue/devtools-api": "^8.1.5", + "ast-walker-scope": "^0.10.0", + "chokidar": "^5.0.0", + "confbox": "^0.3.1", + "local-pkg": "^1.2.1", + "magic-string": "^1.4.3", + "mlly": "^1.8.2", + "muggle-string": "^0.4.1", + "nostics": "^1.3.0", + "pathe": "^2.0.3", + "picomatch": "^4.0.7", + "scule": "^1.3.0", + "tinyglobby": "^0.2.17", + "unplugin": "^3.4.0", + "unplugin-utils": "^0.3.2" + }, + "funding": { + "url": "https://github.com/sponsors/posva" + }, + "peerDependencies": { + "@pinia/colada": ">=0.21.2", + "@vue/compiler-sfc": "^3.5.34 || ^4.0.0", + "pinia": "^3.0.4 || ^4.0.2", + "vite": "^7.3.0 || ^8.0.0", + "vue": "^3.5.34 || ^4.0.0" + }, + "peerDependenciesMeta": { + "@pinia/colada": { + "optional": true + }, + "@vue/compiler-sfc": { + "optional": true + }, + "pinia": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/vue-router/node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/vue-tsc": { + "version": "3.3.14", + "resolved": "https://registry.npmjs.org/vue-tsc/-/vue-tsc-3.3.14.tgz", + "integrity": "sha512-URAu2H9AuMZMg9GCgnqbaHHHd8pBZRAwNV2e2yYS8VDsoTVXHiOSo663OS6DkEvauQ2yixn5TPFJ9WV9QIspkA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@volar/typescript": "2.4.30", + "@vue/language-core": "3.3.14" + }, + "bin": { + "vue-tsc": "bin/vue-tsc.js" + }, + "peerDependencies": { + "typescript": ">=5.0.0" + } + }, + "node_modules/webpack-virtual-modules": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz", + "integrity": "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==", + "license": "MIT" + }, + "node_modules/ws": { + "version": "8.23.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz", + "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "web": { + "name": "@xhchat/web", + "dependencies": { + "pinia": "4.1.0", + "vue": "3.5.45", + "vue-router": "5.5.0" + }, + "devDependencies": { + "@types/node": "^24.0.0", + "@vitejs/plugin-vue": "6.0.11", + "typescript": "~6.0.3", + "vite": "8.3.8", + "vue-tsc": "3.3.14" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..fd7dd25 --- /dev/null +++ b/package.json @@ -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"}} \ No newline at end of file diff --git a/server/Dockerfile b/server/Dockerfile new file mode 100644 index 0000000..010b69c --- /dev/null +++ b/server/Dockerfile @@ -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"] diff --git a/server/cmd/api/main.go b/server/cmd/api/main.go new file mode 100644 index 0000000..40511de --- /dev/null +++ b/server/cmd/api/main.go @@ -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) + } +} diff --git a/server/go.mod b/server/go.mod new file mode 100644 index 0000000..43b759e --- /dev/null +++ b/server/go.mod @@ -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 +) diff --git a/server/go.sum b/server/go.sum new file mode 100644 index 0000000..6ce591c --- /dev/null +++ b/server/go.sum @@ -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= diff --git a/server/internal/account/security.go b/server/internal/account/security.go new file mode 100644 index 0000000..2c62869 --- /dev/null +++ b/server/internal/account/security.go @@ -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) +} diff --git a/server/internal/account/security_test.go b/server/internal/account/security_test.go new file mode 100644 index 0000000..4b840db --- /dev/null +++ b/server/internal/account/security_test.go @@ -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") + } +} diff --git a/server/internal/account/store.go b/server/internal/account/store.go new file mode 100644 index 0000000..05814f4 --- /dev/null +++ b/server/internal/account/store.go @@ -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) +} diff --git a/server/internal/config/config.go b/server/internal/config/config.go new file mode 100644 index 0000000..529ac9c --- /dev/null +++ b/server/internal/config/config.go @@ -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 +} diff --git a/server/internal/contacts/store.go b/server/internal/contacts/store.go new file mode 100644 index 0000000..fabbc1c --- /dev/null +++ b/server/internal/contacts/store.go @@ -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 +} diff --git a/server/internal/database/001_identity.sql b/server/internal/database/001_identity.sql new file mode 100644 index 0000000..23ab982 --- /dev/null +++ b/server/internal/database/001_identity.sql @@ -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); diff --git a/server/internal/database/002_contacts.sql b/server/internal/database/002_contacts.sql new file mode 100644 index 0000000..7f69817 --- /dev/null +++ b/server/internal/database/002_contacts.sql @@ -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) +); diff --git a/server/internal/database/database.go b/server/internal/database/database.go new file mode 100644 index 0000000..e0fe2f3 --- /dev/null +++ b/server/internal/database/database.go @@ -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) +} diff --git a/server/internal/httpapi/api.go b/server/internal/httpapi/api.go new file mode 100644 index 0000000..c2a7edb --- /dev/null +++ b/server/internal/httpapi/api.go @@ -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", "服务暂不可用") +} diff --git a/server/internal/httpapi/contacts.go b/server/internal/httpapi/contacts.go new file mode 100644 index 0000000..aea9dbd --- /dev/null +++ b/server/internal/httpapi/contacts.go @@ -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) +} diff --git a/server/internal/httpapi/realtime.go b/server/internal/httpapi/realtime.go new file mode 100644 index 0000000..912cf13 --- /dev/null +++ b/server/internal/httpapi/realtime.go @@ -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 + } + } + } +} diff --git a/tests/api.test.mjs b/tests/api.test.mjs new file mode 100644 index 0000000..4ee7fca --- /dev/null +++ b/tests/api.test.mjs @@ -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() + } +}) diff --git a/tests/clients.test.mjs b/tests/clients.test.mjs new file mode 100644 index 0000000..64953d9 --- /dev/null +++ b/tests/clients.test.mjs @@ -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 }) + } +}) diff --git a/tests/contacts-browser.test.mjs b/tests/contacts-browser.test.mjs new file mode 100644 index 0000000..47f481d --- /dev/null +++ b/tests/contacts-browser.test.mjs @@ -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('隔离测试站

OK

') + }) + 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 }) + } +}) diff --git a/web/Dockerfile b/web/Dockerfile new file mode 100644 index 0000000..ef53131 --- /dev/null +++ b/web/Dockerfile @@ -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/ diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..a452028 --- /dev/null +++ b/web/index.html @@ -0,0 +1,13 @@ + + + + + + + XHChat + + +
+ + + diff --git a/web/package.json b/web/package.json new file mode 100644 index 0000000..49da3db --- /dev/null +++ b/web/package.json @@ -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"}} diff --git a/web/src/App.vue b/web/src/App.vue new file mode 100644 index 0000000..8fbc6bf --- /dev/null +++ b/web/src/App.vue @@ -0,0 +1,13 @@ + + + diff --git a/web/src/api.ts b/web/src/api.ts new file mode 100644 index 0000000..8df5adc --- /dev/null +++ b/web/src/api.ts @@ -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(path: string, method = 'GET', token = '', body?: object): Promise { + const headers: Record = { 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]) +} diff --git a/web/src/contacts.ts b/web/src/contacts.ts new file mode 100644 index 0000000..d8bf3c8 --- /dev/null +++ b/web/src/contacts.ts @@ -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' diff --git a/web/src/identity.ts b/web/src/identity.ts new file mode 100644 index 0000000..35b6beb --- /dev/null +++ b/web/src/identity.ts @@ -0,0 +1,66 @@ +interface DeviceProof { + publicKey: string + signature: string +} + +interface DesktopBridge { + apiBase: string + signChallenge: (username: string, challenge: string) => Promise + openBrowser?: () => Promise +} + +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 { + 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 { + 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 { + 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('无法使用本机设备密钥,请检查浏览器是否支持安全密钥存储') + } +} diff --git a/web/src/main.ts b/web/src/main.ts new file mode 100644 index 0000000..43d8e6e --- /dev/null +++ b/web/src/main.ts @@ -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') diff --git a/web/src/session.ts b/web/src/session.ts new file mode 100644 index 0000000..d872746 --- /dev/null +++ b/web/src/session.ts @@ -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() + const connection = ref('离线') + const contactChanges = ref(0) + let token = '' + let socket: WebSocket | undefined + let retry: ReturnType | 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/' + 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(path: string, method = 'GET', body?: object) { + try { + return await request(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('/devices'), + revoke: (id: string) => authorized('/devices/' + encodeURIComponent(id), 'DELETE'), + contacts: () => authorized('/contacts'), + searchContact: (username: string) => authorized('/contacts/search?' + new URLSearchParams({ username })), + changeContact: (id: string, action: ContactAction, alias: string, category: string) => + authorized('/contacts/' + encodeURIComponent(id), 'POST', { action, alias, category }), + } +}) diff --git a/web/src/style.css b/web/src/style.css new file mode 100644 index 0000000..3d28623 --- /dev/null +++ b/web/src/style.css @@ -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; } +} diff --git a/web/src/views/AuthView.vue b/web/src/views/AuthView.vue new file mode 100644 index 0000000..05d4108 --- /dev/null +++ b/web/src/views/AuthView.vue @@ -0,0 +1,55 @@ + + + diff --git a/web/src/views/ContactsView.vue b/web/src/views/ContactsView.vue new file mode 100644 index 0000000..fbf95af --- /dev/null +++ b/web/src/views/ContactsView.vue @@ -0,0 +1,135 @@ + + + diff --git a/web/src/views/DeviceView.vue b/web/src/views/DeviceView.vue new file mode 100644 index 0000000..e1721c9 --- /dev/null +++ b/web/src/views/DeviceView.vue @@ -0,0 +1,62 @@ + + + diff --git a/web/src/views/Workspace.vue b/web/src/views/Workspace.vue new file mode 100644 index 0000000..a3c4945 --- /dev/null +++ b/web/src/views/Workspace.vue @@ -0,0 +1,49 @@ + + + diff --git a/web/tsconfig.json b/web/tsconfig.json new file mode 100644 index 0000000..c8e7238 --- /dev/null +++ b/web/tsconfig.json @@ -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"] +} diff --git a/web/vite.config.ts b/web/vite.config.ts new file mode 100644 index 0000000..27a9b91 --- /dev/null +++ b/web/vite.config.ts @@ -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 }, + }, + }, +})