diff --git a/.dockerignore b/.dockerignore index 273ac7a..b945e71 100644 --- a/.dockerignore +++ b/.dockerignore @@ -6,3 +6,5 @@ docs Android server +crypto/target +web/public/mls diff --git a/.gitignore b/.gitignore index 7421f7f..561845b 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ dist/ test-results/ playwright-report/ /crypto/target/ +/web/public/mls/ diff --git a/Desktop/src/identity.ts b/Desktop/src/identity.ts index 8f93a61..5089c7b 100644 --- a/Desktop/src/identity.ts +++ b/Desktop/src/identity.ts @@ -25,6 +25,13 @@ export async function signChallenge(server: string, username: string, challenge: if (!/^[a-z0-9_]{3,32}$/.test(username) || !/^[A-Za-z0-9_-]{43}$/.test(challenge)) { throw new Error('设备验证参数无效') } + const key = await deviceKey(server, username) + const publicKey = createPublicKey(key).export({ format: 'jwk' }).x! + const signature = sign(null, Buffer.from('XHChat device authentication v1\n' + challenge), key).toString('base64url') + return { publicKey, signature } +} + +async function deviceKey(server: string, username: string) { const directory = join(app.getPath('userData'), 'device-keys') await mkdir(directory, { recursive: true }) const file = join(directory, createHash('sha256').update(server + '\n' + username).digest('hex')) @@ -33,8 +40,17 @@ export async function signChallenge(server: string, username: string, challenge: pending = readOrCreate(file).finally(() => active.delete(file)) active.set(file, pending) } - const key = await pending - const publicKey = createPublicKey(key).export({ format: 'jwk' }).x! - const signature = sign(null, Buffer.from('XHChat device authentication v1\n' + challenge), key).toString('base64url') - return { publicKey, signature } + return pending +} + +export async function signMls(server: string, username: string, kind: string, user: string, device: string, value: Uint8Array) { + const id = /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/ + if (!/^[a-z0-9_]{3,32}$/.test(username) || !id.test(user) || !id.test(device) || + !(value instanceof Uint8Array) || + !(kind === 'credential' && value.length === 32 || + kind === 'KeyPackage' && value.length >= 32 && value.length <= 8192)) { + throw new Error('MLS 签名参数无效') + } + const key = await deviceKey(server, username) + return new Uint8Array(sign(null, Buffer.concat([Buffer.from('XHChat MLS ' + kind + ' v1\n' + user + '\n' + device + '\n'), value]), key)) } diff --git a/Desktop/src/main.ts b/Desktop/src/main.ts index a46c6f1..d9c5383 100644 --- a/Desktop/src/main.ts +++ b/Desktop/src/main.ts @@ -1,7 +1,7 @@ -import { app, BrowserWindow, ipcMain, protocol, session } from 'electron' +import { app, BrowserWindow, ipcMain, protocol, safeStorage, session } from 'electron' import { readFile } from 'node:fs/promises' import { join } from 'node:path' -import { signChallenge } from './identity' +import { signChallenge, signMls } from './identity' import { openBrowser, registerBrowserHandlers } from './browser' const appURL = 'xhchat://app/' @@ -35,17 +35,21 @@ async function start() { ['/browser', 'index.html'], ['/browser/style.css', 'style.css'], ['/browser/ui.js', 'ui.js'], ]) const browserAsset = browserPaths.get(url.pathname) + const mlsAsset = /^\/mls\/xhchat_mls_check(?:\.js|_bg\.wasm)$/.test(url.pathname) if (url.host !== 'app' || request.method !== 'GET' || - (!root && !browserAsset && !/^\/assets\/[a-zA-Z0-9_.-]+\.(?:js|css)$/.test(url.pathname))) { + (!root && !browserAsset && !mlsAsset && !/^\/assets\/[a-zA-Z0-9_.-]+\.(?:js|css)$/.test(url.pathname))) { return new Response(null, { status: 404 }) } try { const bytes = await readFile(browserAsset ? join(browserUI, browserAsset) : join(renderer, root ? 'index.html' : url.pathname.slice(1))) const html = root || url.pathname === '/browser' - const policy = "default-src 'none'; script-src 'self'; style-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" + const policy = "default-src 'none'; script-src 'self'" + (browserAsset ? '' : " 'wasm-unsafe-eval'") + + "; style-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" + const type = html ? 'text/html; charset=utf-8' : url.pathname.endsWith('.css') ? 'text/css' : + url.pathname.endsWith('.wasm') ? 'application/wasm' : 'application/javascript' return new Response(bytes, { headers: { - 'Content-Type': html ? 'text/html; charset=utf-8' : url.pathname.endsWith('.css') ? 'text/css' : 'application/javascript', - 'Content-Security-Policy': browserAsset ? policy : policy + '; connect-src ' + api + ' ' + websocket, + 'Content-Type': type, + 'Content-Security-Policy': browserAsset ? policy : policy + "; connect-src 'self' " + api + ' ' + websocket, 'X-Content-Type-Options': 'nosniff', } }) } catch { @@ -75,6 +79,28 @@ async function start() { } return signChallenge(api, username, challenge) }) + ipcMain.handle('device:sign-mls', (event, username: string, kind: string, user: string, device: string, value: Uint8Array) => { + if (!trustedSender(event) || [username, kind, user, device].some((input) => typeof input !== 'string')) { + throw new Error('设备签名请求来源无效') + } + return signMls(api, username, kind, user, device, value) + }) + ipcMain.handle('device:protect-mls', (event, key: unknown) => { + if (!trustedSender(event) || !safeStorage.isEncryptionAvailable() || + typeof key !== 'string' || !/^[A-Za-z0-9+/]{43}=$/.test(key)) { + throw new Error('系统密钥保护不可用') + } + return safeStorage.encryptString(key).toString('base64') + }) + ipcMain.handle('device:unprotect-mls', (event, wrapped: unknown) => { + if (!trustedSender(event) || !safeStorage.isEncryptionAvailable() || + typeof wrapped !== 'string' || wrapped.length > 2048 || !/^[A-Za-z0-9+/=]+$/.test(wrapped)) { + throw new Error('系统密钥保护不可用') + } + const key = safeStorage.decryptString(Buffer.from(wrapped, 'base64')) + if (!/^[A-Za-z0-9+/]{43}=$/.test(key)) throw new Error('会话存储密钥无效') + return key + }) registerBrowserHandlers(trusted) ipcMain.handle('browser:open', (event) => { if (!trustedSender(event)) throw new Error('浏览器入口来源无效') diff --git a/Desktop/src/preload.ts b/Desktop/src/preload.ts index 1bc0fc5..f28ccd6 100644 --- a/Desktop/src/preload.ts +++ b/Desktop/src/preload.ts @@ -6,4 +6,8 @@ contextBridge.exposeInMainWorld('xhchat', { apiBase: apiArgument?.slice('--xhchat-api='.length), signChallenge: (username: string, challenge: string) => ipcRenderer.invoke('device:sign', username, challenge), openBrowser: () => ipcRenderer.invoke('browser:open'), + signMls: (username: string, kind: string, user: string, device: string, value: Uint8Array) => + ipcRenderer.invoke('device:sign-mls', username, kind, user, device, value), + protectMls: (key: string) => ipcRenderer.invoke('device:protect-mls', key), + unprotectMls: (key: string) => ipcRenderer.invoke('device:unprotect-mls', key), }) diff --git a/README.md b/README.md index ab1e836..36c459f 100644 --- a/README.md +++ b/README.md @@ -16,9 +16,11 @@ | --- | --- | | 账号与设备 | Windows 和 Web 共用账号,支持用户名注册、登录、查看设备和远程撤销。 | | 联系人 | 按用户名查找、处理好友申请、管理备注与分组,以及拉黑。变更可在双端实时同步。 | +| 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 | +| 加密附件 | 两端可发送和下载最多 8 MiB 的文件,下载时验证完整性。 | | Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索和隐私窗口,网页运行在独立会话中。 | -当前为开发预览。OpenMLS 已完成原生与浏览器的协议验证。应用内加密聊天、群聊和音视频仍在开发,Windows 安装包尚未发布。 [开发进度与验收记录](docs/progress.md) +当前为开发预览。大文件分片、群聊、音视频和多设备历史同步仍在开发,Windows 安装包尚未发布。 [开发进度与验收记录](docs/progress.md) ## 本地预览 @@ -38,12 +40,16 @@ docker compose up -d --build --wait ```powershell npm.cmd ci +New-Item -ItemType Directory -Path web/public/mls -Force | Out-Null +docker compose cp web:/usr/share/nginx/html/mls/. web/public/mls npm.cmd run build npm.cmd run desktop ``` 在 Windows 端使用同一账号登录。在「设备管理」中可以看到 Web 和 Windows 的独立设备记录。部署到自定义域名和配置 HTTPS 的步骤见 [部署文档](docs/deployment.md)。 +体验加密文字聊天时,注册两个账号并互加好友。在双方的联系人详情中打开「加密聊天」,启用本机加密,通过另一可信渠道交换安全码,分别核验对方设备后即可互发消息。 + ## 开发文档 | 主题 | 文档 | diff --git a/deploy/nginx.conf b/deploy/nginx.conf index c7a37e2..1cceea4 100644 --- a/deploy/nginx.conf +++ b/deploy/nginx.conf @@ -21,8 +21,13 @@ server { proxy_pass http://api:8080; proxy_set_header Host $http_host; } + location /api/v1/attachments/ { + client_max_body_size 9m; + proxy_pass http://api:8080; + proxy_set_header Host $http_host; + } - 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 Content-Security-Policy "default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; 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; diff --git a/docs/api.md b/docs/api.md index 83b507a..311ca21 100644 --- a/docs/api.md +++ b/docs/api.md @@ -21,6 +21,10 @@ | GET | /api/v1/inbox?after= | 按当前设备和递增游标取最多 64 条封包 | | GET | /api/v1/contacts/{id}/devices | 返回已接受联系人的有效设备与公开身份密钥 | | POST | /api/v1/key-packages | 当前设备发布带设备签名的 MLS KeyPackage,成功返回 204 | +| GET | /api/v1/mls-local-key | 读取当前设备的公开认证密钥,供本机安全码计算 | +| POST | /api/v1/mls-credential | 当前设备登记带认证密钥签名的 MLS 签名公钥 | +| POST | /api/v1/attachments/{id}?recipient= | 已接受好友设备上传附件密文,使用 application/octet-stream,成功返回 204 | +| GET | /api/v1/attachments/{id} | 原发送或接收设备获取附件密文 | | POST | /api/v1/contacts/{id}/devices/{device}/claim | 为当前设备原子领取一个联系人的未使用 KeyPackage | 用户名为 3–32 位 ASCII 字母、数字或下划线,忽略大小写。密码最少 12 个 Unicode 字符,最多 256 字节。platform 为 web 或 windows。公钥、签名和 challenge 使用无填充 Base64URL。设备使用 Ed25519 签名 UTF-8 字符串 `XHChat device authentication v1\n` 后紧接 challenge。该签名仅用于证明基础设备密钥持有权。 @@ -31,4 +35,8 @@ 密钥包与签名均使用标准 Base64。设备以已有的 Ed25519 密钥签名 UTF-8 前缀 `XHChat MLS KeyPackage v1\n{userId}\n{deviceId}\n` 和原始 MLS 封包的拼接。服务端验证签名和外层格式,密钥包可在发布后的 24 小时内领取一次。客户端仍需独立验证设备公钥信任和完整 MLS 对象。重试发布同一封包不会再次开放领取。 -下一阶段将增加 /conversations 和 /attachments。后续加入 /groups、/calls、/posts、/backups、/push 与独立的管理接口。 +MLS 凭据由标准 Base64 的 publicKey 和 signature 组成,使用 UTF-8 前缀 `XHChat MLS credential v1\n{userId}\n{deviceId}\n` 后接 32 字节 MLS Ed25519 公钥。设备目录返回可选的 mls 对象。已登记公钥仅允许原值重试。 + +附件密文上限为 8 MiB 加 16 字节认证标签。重复提交相同 ID 和密文为幂等操作。附件按投递保留期清理,文件名和密钥只通过 MLS 消息传递。 + +下一阶段将增加 /conversations。后续加入 /groups、/calls、/posts、/backups、/push 与独立的管理接口。 diff --git a/docs/database.md b/docs/database.md index 9f7300b..4e4ccff 100644 --- a/docs/database.md +++ b/docs/database.md @@ -9,6 +9,7 @@ | conversations、memberships | 会话与成员关系,记录角色和生效世代 | | devices、device_key_packages | 公开设备凭据及签名的一次性密钥包,事务领取,撤销后停止发放 | | device_envelopes | 二进制协议封包、投递游标和目标设备,按发送设备、接收设备和客户端消息 ID 幂等 | +| device_attachments | 预览版 8 MiB 附件密文与设备访问范围,按附件 ID 幂等,跟随消息保留期 | | attachments、backups | 对象存储标识、密文尺寸、配额和版本,密钥由端侧传递 | | calls、call_participants | 通话状态、参与设备和时间,不存媒体 | | posts、post_audiences、reactions | 私人动态正文为密文,受众变更触发重新分发或换钥 | diff --git a/docs/deployment.md b/docs/deployment.md index e99a606..12d47d9 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -6,4 +6,13 @@ 使用 `docker compose logs api` 检查应用日志。停止服务用 `docker compose down`。PostgreSQL 的数据由 Compose 命名卷保存。 -使用 `pg_dump` 生成数据库备份,备份包含账号与设备元数据,应在受控环境加密保存。使用 `pg_restore` 恢复到独立数据库,执行迁移与 API 验证后切换服务。恢复时清除历史会话并重建 Redis 短期状态。阶段一暂无聊天和附件数据。 +使用 `pg_dump` 生成数据库备份,备份包含账号、设备元数据和未过期的 MLS 封包,应在受控环境加密保存。使用 `pg_restore` 恢复到独立数据库,执行迁移与 API 验证后切换服务。恢复时清除历史会话并重建 Redis 短期状态。 + +Compose 会构建并在 Web 镜像中提供 MLS WASM。构建 Windows 客户端前,可从运行中的 Web 容器同步绑定到本地,再构建 Vue 渲染层。 + +```powershell +New-Item -ItemType Directory -Path web/public/mls -Force | Out-Null +docker compose cp web:/usr/share/nginx/html/mls/. web/public/mls +npm.cmd run build +npm.cmd run desktop +``` diff --git a/docs/encryption.md b/docs/encryption.md index 9b6b982..837dda4 100644 --- a/docs/encryption.md +++ b/docs/encryption.md @@ -9,3 +9,5 @@ OpenMLS 0.9.2 兼容性用例已在 Linux 原生和 Windows Chrome WebAssembly 中通过,覆盖三设备 Welcome、密文往返、重放拒绝和移除后无法读取新世代消息。OpenMLS 发布过 SRLabs 安全审计,应用层的身份绑定、WASM 封装、存储和投递仍需独立验证。 [OpenMLS 审计公告](https://blog.openmls.tech/) 附件采用公开的分块认证加密格式,评估带明确结束认证与大文件恢复语义的实现。每份附件生成独立随机密钥,密文通过对象存储分发,文件密钥及完整性元数据放在 E2EE 消息中。备份使用独立随机恢复秘密,显式确认恢复权限和完整性,服务端只存密文及版本。私人动态按受众分发密钥。Web 应用以同源、受控发布和严格 CSP 管理脚本信任,当前页面的恶意同源脚本属于独立威胁。 + +预览版附件使用 Web Crypto 的整文件 AES-256-GCM,限制 8 MiB。每份文件独立随机密钥和 96 位 IV,附件 ID、文件名和字节数纳入认证数据。下载在完整验证后才生成本地文件,服务端只持有密文及投递元数据。生产版仍需分块认证、断点续传和对象存储。 diff --git a/docs/progress.md b/docs/progress.md index 20dad72..86676ee 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -19,7 +19,7 @@ Web 和 Electron 共用 Vue 客户端,独立接入同一 Go API。真实 Postg ## 尚待实现 - 阶段一还需邮箱和手机号注册、验证码服务、找回密码和双重验证。真实联调需要 SMTP 与短信供应商配置。 -- 阶段二与三还需定版并验证双端 E2EE,交付私聊、附件、离线消息、群聊、多设备可信授权、加密备份与同步。当前基础设备认证没有消息密钥能力。 +- 阶段二与三还需分片附件、消息操作、群聊、多设备可信授权、加密备份与跨设备历史同步。两设备文字和小附件私聊已进入开发预览。 - 阶段四还需 WebRTC 音视频、TURN、SFU、屏幕共享及媒体 E2EE。 - 阶段五还需持久书签和历史、下载记录、逐站授权、反钓鱼及聊天联动。 - 阶段六到八还需社交、扩展生态、独立管理后台、推送、生产部署与备份演练、压力测试、安全评估、签名安装包和发布流程。 @@ -44,3 +44,13 @@ Web 和 Electron 共用 Vue 客户端,独立接入同一 Go API。真实 Postg ## 两设备 MLS 引擎 OpenMLS WASM 提供两设备会话创建、加入、消息加解密和端侧状态快照。原生 Rust 和 Windows Chrome WebAssembly 各通过两项测试,覆盖错误公钥、错误消息关联数据、恢复后的正常收发和重放拒绝。界面、设备身份验证、快照加密保存和发送队列仍在接入。 + +## Windows 与 Web 加密文字预览 + +互为好友后,双方在聊天页分别启用本机加密,并通过其他可信渠道核验对方设备安全码。设备认证密钥签署 MLS 公钥和密钥包,OpenMLS 处理会话与加解密。服务端投递 MLS 封包。浏览器使用不可导出的 Web Crypto AES-GCM 密钥,Windows 使用 DPAPI 封装本地加密密钥。协议状态、历史、待发送封包和收件游标持久化在端侧加密记录中。 + +Edge 与 Electron 集成测试覆盖错误安全码、双向文字、网络封包无测试正文、重新登录后离线接收和 Windows 本地密文存储。当前预览按设备建立会话,支持最多 1000 条本机消息。账号级密钥认证、跨设备同步、定期 MLS 更新、可信设备授权与安全评估待后续交付。 + +## 端到端加密附件预览 + +Windows 与 Web 支持发送和下载最多 8 MiB 的附件。文件名、长度、密钥和 IV 位于 MLS 消息中,附件服务只存密文。下载先验证认证标签,再提供本地保存。跨端用例覆盖上传密文、篡改拒绝和下载字节一致性。对象存储、分片断点续传和媒体专用界面仍待完成。 diff --git a/server/internal/database/005_mls_credentials.sql b/server/internal/database/005_mls_credentials.sql new file mode 100644 index 0000000..a0b9ad1 --- /dev/null +++ b/server/internal/database/005_mls_credentials.sql @@ -0,0 +1,5 @@ +CREATE TABLE device_mls_credentials ( + device_id uuid PRIMARY KEY REFERENCES devices(id) ON DELETE CASCADE, + public_key bytea NOT NULL CHECK (octet_length(public_key)=32), + signature bytea NOT NULL CHECK (octet_length(signature)=64) +); diff --git a/server/internal/database/006_attachments.sql b/server/internal/database/006_attachments.sql new file mode 100644 index 0000000..9fcada7 --- /dev/null +++ b/server/internal/database/006_attachments.sql @@ -0,0 +1,10 @@ +CREATE TABLE device_attachments ( + id uuid PRIMARY KEY, + sender_device uuid NOT NULL REFERENCES devices(id) ON DELETE CASCADE, + recipient_device uuid NOT NULL REFERENCES devices(id) ON DELETE CASCADE, + ciphertext bytea NOT NULL CHECK (octet_length(ciphertext) BETWEEN 16 AND 8388624), + created_at timestamptz NOT NULL DEFAULT now(), + CHECK (sender_device <> recipient_device) +); + +CREATE INDEX device_attachments_expiry ON device_attachments(created_at); diff --git a/server/internal/database/database.go b/server/internal/database/database.go index ff39ecc..2933ae7 100644 --- a/server/internal/database/database.go +++ b/server/internal/database/database.go @@ -19,6 +19,12 @@ var deliveryMigration string //go:embed 004_key_packages.sql var keyPackagesMigration string +//go:embed 005_mls_credentials.sql +var mlsCredentialsMigration string + +//go:embed 006_attachments.sql +var attachmentsMigration string + func Migrate(ctx context.Context, pool *pgxpool.Pool) error { tx, err := pool.Begin(ctx) if err != nil { @@ -31,7 +37,7 @@ func Migrate(ctx context.Context, pool *pgxpool.Pool) error { 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, deliveryMigration, keyPackagesMigration} { + for index, migration := range []string{identityMigration, contactsMigration, deliveryMigration, keyPackagesMigration, mlsCredentialsMigration, attachmentsMigration} { 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 { diff --git a/server/internal/delivery/attachments.go b/server/internal/delivery/attachments.go new file mode 100644 index 0000000..b0c1f20 --- /dev/null +++ b/server/internal/delivery/attachments.go @@ -0,0 +1,55 @@ +package delivery + +import ( + "bytes" + "context" + "errors" + + "github.com/jackc/pgx/v5" +) + +const AttachmentLimit = 8<<20 + 16 + +func (s *Store) UploadAttachment(ctx context.Context, sender, recipient, id string, ciphertext []byte) error { + tx, err := s.db.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + if err = authorizeDelivery(ctx, tx, sender, recipient); err != nil { + return err + } + result, err := tx.Exec(ctx, ` + INSERT INTO device_attachments(id,sender_device,recipient_device,ciphertext) + VALUES($1,$2,$3,$4) ON CONFLICT(id) DO NOTHING + `, id, sender, recipient, ciphertext) + if err != nil { + return err + } + if result.RowsAffected() == 0 { + var stored []byte + err = tx.QueryRow(ctx, ` + SELECT ciphertext FROM device_attachments WHERE id=$1 AND sender_device=$2 AND recipient_device=$3 + `, id, sender, recipient).Scan(&stored) + if errors.Is(err, pgx.ErrNoRows) || err == nil && !bytes.Equal(stored, ciphertext) { + return ErrConflict + } + if err != nil { + return err + } + } + return tx.Commit(ctx) +} + +func (s *Store) DownloadAttachment(ctx context.Context, device, id string) ([]byte, error) { + var ciphertext []byte + err := s.db.QueryRow(ctx, ` + SELECT attachment.ciphertext FROM device_attachments attachment JOIN devices d ON d.id=$2 + WHERE attachment.id=$1 AND d.revoked_at IS NULL + AND d.id IN (attachment.sender_device,attachment.recipient_device) + `, id, device).Scan(&ciphertext) + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrUnavailable + } + return ciphertext, err +} diff --git a/server/internal/delivery/directory.go b/server/internal/delivery/directory.go index 724b256..10dbbae 100644 --- a/server/internal/delivery/directory.go +++ b/server/internal/delivery/directory.go @@ -10,9 +10,15 @@ import ( ) type DirectoryDevice struct { - ID string `json:"id"` - Name string `json:"name"` + ID string `json:"id"` + Name string `json:"name"` + PublicKey []byte `json:"publicKey"` + MLS *Credential `json:"mls,omitempty"` +} + +type Credential struct { PublicKey []byte `json:"publicKey"` + Signature []byte `json:"signature"` } type KeyPackage struct { @@ -23,6 +29,15 @@ type KeyPackage struct { var ErrSignature = errors.New("invalid key package device signature") var ErrPackageLimit = errors.New("device key package limit reached") +func (s *Store) LocalIdentityKey(ctx context.Context, device string) ([]byte, error) { + var key []byte + err := s.db.QueryRow(ctx, "SELECT public_key FROM devices WHERE id=$1 AND revoked_at IS NULL", device).Scan(&key) + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrUnavailable + } + return key, err +} + const acceptedContact = ` EXISTS (SELECT 1 FROM contact_relationships WHERE first_user=LEAST($1::uuid,$2::uuid) AND second_user=GREATEST($1::uuid,$2::uuid) @@ -31,7 +46,8 @@ const acceptedContact = ` func (s *Store) Directory(ctx context.Context, owner, contact string) ([]DirectoryDevice, error) { rows, err := s.db.Query(ctx, ` - SELECT id,name,public_key FROM devices + SELECT id,name,devices.public_key, m.public_key, m.signature FROM devices + LEFT JOIN device_mls_credentials m ON m.device_id=devices.id WHERE user_id=$2 AND revoked_at IS NULL AND `+acceptedContact+` ORDER BY id LIMIT 128`, owner, contact) if err != nil { @@ -41,14 +57,50 @@ func (s *Store) Directory(ctx context.Context, owner, contact string) ([]Directo result := make([]DirectoryDevice, 0) for rows.Next() { var device DirectoryDevice - if err := rows.Scan(&device.ID, &device.Name, &device.PublicKey); err != nil { + var credential Credential + if err := rows.Scan(&device.ID, &device.Name, &device.PublicKey, &credential.PublicKey, &credential.Signature); err != nil { return nil, err } + if credential.PublicKey != nil { + device.MLS = &credential + } result = append(result, device) } return result, rows.Err() } +func (s *Store) PublishCredential(ctx context.Context, owner, device string, credential Credential) error { + tx, err := s.db.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + var public []byte + err = tx.QueryRow(ctx, "SELECT public_key FROM devices WHERE id=$1 AND user_id=$2 AND revoked_at IS NULL FOR UPDATE", device, owner).Scan(&public) + if errors.Is(err, pgx.ErrNoRows) { + return ErrUnavailable + } + if err != nil { + return err + } + binding := append([]byte("XHChat MLS credential v1\n"+owner+"\n"+device+"\n"), credential.PublicKey...) + if !ed25519.Verify(public, binding, credential.Signature) { + return ErrSignature + } + tag, err := tx.Exec(ctx, ` + INSERT INTO device_mls_credentials VALUES($1,$2,$3) + ON CONFLICT(device_id) DO UPDATE SET signature=EXCLUDED.signature + WHERE device_mls_credentials.public_key=EXCLUDED.public_key + `, device, credential.PublicKey, credential.Signature) + if err != nil { + return err + } + if tag.RowsAffected() == 0 { + return ErrConflict + } + return tx.Commit(ctx) +} + func (s *Store) PublishPackage(ctx context.Context, owner, device string, item KeyPackage) error { tx, err := s.db.Begin(ctx) if err != nil { diff --git a/server/internal/delivery/store.go b/server/internal/delivery/store.go index 5216763..b80c108 100644 --- a/server/internal/delivery/store.go +++ b/server/internal/delivery/store.go @@ -34,47 +34,10 @@ func (s *Store) Send(ctx context.Context, sender, recipient, message string, cip } defer tx.Rollback(ctx) - var senderUser, recipientUser string - err = tx.QueryRow(ctx, ` - SELECT sender.user_id, recipient.user_id FROM devices sender CROSS JOIN devices recipient - WHERE sender.id=$1 AND recipient.id=$2 AND sender.id<>recipient.id - `, sender, recipient).Scan(&senderUser, &recipientUser) - if errors.Is(err, pgx.ErrNoRows) { - return "", ErrUnavailable - } - if err != nil { + if err = authorizeDelivery(ctx, tx, sender, recipient); err != nil { return "", err } - // Use the same account lock order as contact changes. Locking both devices also - // serializes writes for each recipient and prevents a cursor passing an uncommitted write. - if _, err = tx.Exec(ctx, "SELECT id FROM users WHERE id IN ($1,$2) ORDER BY id FOR UPDATE", senderUser, recipientUser); err != nil { - return "", err - } - var active int - err = tx.QueryRow(ctx, ` - SELECT count(*) FROM ( - SELECT id FROM devices WHERE id IN ($1,$2) AND revoked_at IS NULL ORDER BY id FOR UPDATE - ) AS active_devices - `, sender, recipient).Scan(&active) - if err != nil { - return "", err - } - if active != 2 { - return "", ErrUnavailable - } - - // This direct-message endpoint only connects accepted contacts. - // A separate authorization flow is needed for same-account device transfers. - var friends bool - err = tx.QueryRow(ctx, "SELECT "+acceptedContact, senderUser, recipientUser).Scan(&friends) - if err != nil { - return "", err - } - if !friends { - return "", ErrUnavailable - } - var seq string err = tx.QueryRow(ctx, ` INSERT INTO device_envelopes(message_id, sender_device, recipient_device, ciphertext) @@ -122,10 +85,59 @@ func (s *Store) Inbox(ctx context.Context, recipient string, after int64) ([]Env } func (s *Store) Cleanup(ctx context.Context, retention time.Duration) error { - if _, err := s.db.Exec(ctx, "DELETE FROM device_envelopes WHERE created_at < $1", time.Now().Add(-retention)); err != nil { + cutoff := time.Now().Add(-retention) + if _, err := s.db.Exec(ctx, "DELETE FROM device_envelopes WHERE created_at < $1", cutoff); err != nil { + return err + } + if _, err := s.db.Exec(ctx, "DELETE FROM device_attachments WHERE created_at < $1", cutoff); err != nil { return err } // Keep issued package hashes past the validity window of an individual upload. _, err := s.db.Exec(ctx, "DELETE FROM device_key_packages WHERE created_at < now() - interval '90 days'") return err } + +func authorizeDelivery(ctx context.Context, tx pgx.Tx, sender, recipient string) error { + var senderUser, recipientUser string + err := tx.QueryRow(ctx, ` + SELECT sender.user_id, recipient.user_id FROM devices sender CROSS JOIN devices recipient + WHERE sender.id=$1 AND recipient.id=$2 AND sender.id<>recipient.id + `, sender, recipient).Scan(&senderUser, &recipientUser) + if errors.Is(err, pgx.ErrNoRows) { + return ErrUnavailable + } + if err != nil { + return err + } + + // Use the same account lock order as contact changes. Locking both devices also + // serializes writes for each recipient and prevents a cursor passing an uncommitted write. + if _, err = tx.Exec(ctx, "SELECT id FROM users WHERE id IN ($1,$2) ORDER BY id FOR UPDATE", senderUser, recipientUser); err != nil { + return err + } + var active int + err = tx.QueryRow(ctx, ` + SELECT count(*) FROM ( + SELECT id FROM devices WHERE id IN ($1,$2) AND revoked_at IS NULL ORDER BY id FOR UPDATE + ) AS active_devices + `, sender, recipient).Scan(&active) + if err != nil { + return err + } + if active != 2 { + return ErrUnavailable + } + + // This direct-message endpoint only connects accepted contacts. + // A separate authorization flow is needed for same-account device transfers. + var friends bool + err = tx.QueryRow(ctx, "SELECT "+acceptedContact, senderUser, recipientUser).Scan(&friends) + if err != nil { + return err + } + if !friends { + return ErrUnavailable + } + + return nil +} diff --git a/server/internal/httpapi/api.go b/server/internal/httpapi/api.go index 52dde20..b0c739f 100644 --- a/server/internal/httpapi/api.go +++ b/server/internal/httpapi/api.go @@ -53,6 +53,10 @@ func New(accounts *account.Store, contactStore *contacts.Store, envelopeStore *d mux.HandleFunc("GET /api/v1/contacts/{id}/devices", a.authorized(a.contactDevices)) mux.HandleFunc("POST /api/v1/contacts/{id}/devices/{device}/claim", a.authorized(a.claimPackage)) mux.HandleFunc("POST /api/v1/key-packages", a.authorized(a.publishPackage)) + mux.HandleFunc("POST /api/v1/mls-credential", a.authorized(a.publishCredential)) + mux.HandleFunc("POST /api/v1/attachments/{id}", a.authorized(a.uploadAttachment)) + mux.HandleFunc("GET /api/v1/attachments/{id}", a.authorized(a.downloadAttachment)) + mux.HandleFunc("GET /api/v1/mls-local-key", a.authorized(a.localMLSKey)) return a.boundary(mux) } diff --git a/server/internal/httpapi/attachments.go b/server/internal/httpapi/attachments.go new file mode 100644 index 0000000..092d8d9 --- /dev/null +++ b/server/internal/httpapi/attachments.go @@ -0,0 +1,65 @@ +package httpapi + +import ( + "errors" + "io" + "net/http" + + "xhchat/server/internal/account" + "xhchat/server/internal/delivery" +) + +func (a *API) uploadAttachment(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) { + id, recipient := r.PathValue("id"), r.URL.Query().Get("recipient") + if !uuidPattern.MatchString(id) || !uuidPattern.MatchString(recipient) || + r.Header.Get("Content-Type") != "application/octet-stream" { + problem(w, 400, "invalid_attachment", "附件请求格式无效") + return + } + if !a.limit(w, r, "attachment-upload:"+identity.Device.ID, 12) { + return + } + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, delivery.AttachmentLimit)) + var tooLarge *http.MaxBytesError + switch { + case errors.As(err, &tooLarge): + problem(w, 413, "attachment_too_large", "附件超过 8 MiB") + return + case err != nil || len(body) < 16: + problem(w, 400, "invalid_attachment", "附件请求格式无效") + return + } + err = a.delivery.UploadAttachment(r.Context(), identity.Device.ID, recipient, id, body) + switch { + case errors.Is(err, delivery.ErrUnavailable): + problem(w, 404, "attachment_unavailable", "无法向指定设备发送附件") + case errors.Is(err, delivery.ErrConflict): + problem(w, 409, "attachment_conflict", "附件 ID 已使用") + case err != nil: + unavailable(w, err) + default: + w.WriteHeader(204) + } +} + +func (a *API) downloadAttachment(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) { + id := r.PathValue("id") + if !uuidPattern.MatchString(id) { + problem(w, 404, "attachment_unavailable", "附件不可用") + return + } + if !a.limit(w, r, "attachment-download:"+identity.Device.ID, 30) { + return + } + body, err := a.delivery.DownloadAttachment(r.Context(), identity.Device.ID, id) + switch { + case errors.Is(err, delivery.ErrUnavailable): + problem(w, 404, "attachment_unavailable", "附件不可用或已过期") + case err != nil: + unavailable(w, err) + default: + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Disposition", "attachment") + _, _ = w.Write(body) + } +} diff --git a/server/internal/httpapi/mls_credentials.go b/server/internal/httpapi/mls_credentials.go new file mode 100644 index 0000000..c5b2fbe --- /dev/null +++ b/server/internal/httpapi/mls_credentials.go @@ -0,0 +1,46 @@ +package httpapi + +import ( + "errors" + "net/http" + + "xhchat/server/internal/account" + "xhchat/server/internal/delivery" +) + +func (a *API) localMLSKey(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) { + key, err := a.delivery.LocalIdentityKey(r.Context(), identity.Device.ID) + if errors.Is(err, delivery.ErrUnavailable) { + problem(w, 404, "device_not_found", "设备不可用") + return + } + if err != nil { + unavailable(w, err) + return + } + respond(w, 200, map[string][]byte{"publicKey": key}) +} + +func (a *API) publishCredential(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) { + var input delivery.Credential + if !parse(w, r, &input) { + return + } + if len(input.PublicKey) != 32 || len(input.Signature) != 64 { + problem(w, 400, "invalid_credential", "MLS 设备凭据格式无效") + return + } + err := a.delivery.PublishCredential(r.Context(), identity.User.ID, identity.Device.ID, input) + switch { + case errors.Is(err, delivery.ErrSignature): + problem(w, 400, "invalid_credential_signature", "MLS 设备凭据签名无效") + case errors.Is(err, delivery.ErrConflict): + problem(w, 409, "credential_changed", "该设备已绑定其他 MLS 密钥") + case errors.Is(err, delivery.ErrUnavailable): + problem(w, 404, "device_not_found", "设备不可用") + case err != nil: + unavailable(w, err) + default: + w.WriteHeader(204) + } +} diff --git a/tests/delivery.test.mjs b/tests/delivery.test.mjs index db8a2f0..cf23302 100644 --- a/tests/delivery.test.mjs +++ b/tests/delivery.test.mjs @@ -116,3 +116,33 @@ test('设备密钥包验证签名并只领取一次', { timeout: 25000 }, async assert.equal((await call('/devices/' + owner.device.id, 'DELETE', owner.token)).status, 204) assert.deepEqual(await json(directory, 'GET', contactUser.token), []) }) + +test('附件访问按设备授权并支持相同密文重试', { timeout: 15000 }, async () => { + const sender = await register() + const recipient = await register() + const stranger = await register() + const path = '/api/v1/attachments/' + randomUUID() + const bytes = randomBytes(256) + const upload = (body) => fetch(base + path + '?recipient=' + recipient.device.id, { + method: 'POST', + headers: { Authorization: 'Bearer ' + sender.token, 'Content-Type': 'application/octet-stream' }, + body, + signal: AbortSignal.timeout(10_000), + }) + const download = (token) => fetch(base + path, { + headers: { Authorization: 'Bearer ' + token }, + signal: AbortSignal.timeout(10_000), + }) + assert.equal((await upload(bytes)).status, 404) + await contact(sender, recipient, 'request') + await contact(recipient, sender, 'accept') + assert.equal((await upload(bytes)).status, 204) + assert.equal((await upload(bytes)).status, 204) + assert.equal((await upload(randomBytes(256))).status, 409) + assert.equal((await download(stranger.token)).status, 404) + const response = await download(recipient.token) + assert.equal(response.status, 200) + assert.deepEqual(Buffer.from(await response.arrayBuffer()), bytes) + assert.equal((await call('/devices/' + recipient.device.id, 'DELETE', recipient.token)).status, 204) + assert.equal((await download(recipient.token)).status, 401) +}) diff --git a/tests/encrypted-chat.test.mjs b/tests/encrypted-chat.test.mjs new file mode 100644 index 0000000..5abfb19 --- /dev/null +++ b/tests/encrypted-chat.test.mjs @@ -0,0 +1,168 @@ +import assert from 'node:assert/strict' +import { randomBytes } from 'node:crypto' +import { mkdtemp, readFile, 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' +const work = (page) => page.getByRole('navigation', { name: '工作区' }) +const testUser = () => 'qa_' + randomBytes(6).toString('hex') + +async function login(page, username, password, register) { + if (register) await page.getByRole('button', { name: '注册', exact: true }).click() + await page.getByLabel('用户名').fill(username) + await page.getByLabel('密码', { exact: true }).fill(password) + await page.locator('button.primary').click() + await page.getByText('实时连接已建立').waitFor() +} + +async function enable(page) { + await page.getByRole('button', { name: '启用本机加密聊天' }).click() + await page.locator('.security-code').waitFor({ timeout: 10_000 }) + return page.locator('.security-code').textContent() +} + +async function trust(page, code) { + await page.getByLabel('对方安全码').fill(code) + await page.getByRole('button', { name: '核验设备' }).click() + await page.getByText('设备已验证').waitFor() +} + +async function send(page, text) { + await page.getByRole('textbox', { name: '消息', exact: true }).fill(text) + await page.getByRole('button', { name: '发送', exact: true }).click() + try { + await page.getByText(text, { exact: true }).waitFor({ timeout: 10_000 }) + } catch (error) { + throw new Error(JSON.stringify(await page.locator('[role=alert]').allTextContents()), { cause: error }) + } +} + +test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢复', { timeout: 90000 }, async () => { + const browser = await chromium.launch({ channel: process.env.XHCHAT_TEST_BROWSER ?? 'msedge' }) + const profile = await mkdtemp(join(tmpdir(), 'xhchat-mls-test-')) + let desktop + try { + const web = await browser.newPage({ acceptDownloads: true }) + await web.goto(base) + 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() + const clientErrors = [] + for (const [label, page] of [['web', web], ['windows', windows]]) { + page.on('pageerror', (error) => clientErrors.push(label + ': ' + error.message)) + page.on('console', (message) => { if (message.type() === 'error') clientErrors.push(label + ': ' + message.text()) }) + } + const a = testUser(), b = testUser() + const password = randomBytes(24).toString('hex') + await login(web, a, password, true) + await login(windows, b, password, true) + await work(web).getByRole('link', { name: '联系人' }).click() + await work(windows).getByRole('link', { name: '联系人' }).click() + await web.getByLabel('按用户名查找').fill(b) + await web.getByRole('button', { name: '查找' }).click() + await web.getByRole('button', { name: '添加好友' }).click() + await windows.getByRole('button', { name: new RegExp(a) }).click() + await windows.getByRole('button', { name: '接受申请' }).click() + await web.getByRole('link', { name: '打开加密聊天' }).click() + await windows.getByRole('link', { name: '打开加密聊天' }).click() + const windowsChat = windows.url() + let webCode, desktopCode + try { + ;[webCode, desktopCode] = await Promise.all([enable(web), enable(windows)]) + } catch (error) { + throw new Error(JSON.stringify({ web: await web.locator('[role=alert]').allTextContents(), windows: await windows.locator('[role=alert]').allTextContents(), clientErrors }), { cause: error }) + } + assert.match(webCode, /^[0-9a-f]{64}$/) + assert.match(desktopCode, /^[0-9a-f]{64}$/) + assert.notEqual(webCode, desktopCode) + await web.getByRole('button', { name: '刷新' }).click() + await windows.getByRole('button', { name: '刷新' }).click() + await web.getByLabel('对方安全码').fill('0'.repeat(64)) + await web.getByRole('button', { name: '核验设备' }).click() + await web.getByText('安全码不匹配').waitFor() + assert.equal(await web.getByRole('button', { name: '发送', exact: true }).count(), 0) + await trust(web, desktopCode) + await trust(windows, webCode) + + const text = 'Web 到 Windows ' + randomBytes(8).toString('hex') + const packets = [] + web.on('request', (req) => { + if (req.method() === 'POST' && req.url().endsWith('/api/v1/inbox')) packets.push(req.postDataJSON()) + }) + await send(web, text) + const packet = packets.find((entry) => Buffer.from(entry.ciphertext, 'base64')[3] === 2) + assert.ok(packet) + assert.ok(!Buffer.from(packet.ciphertext, 'base64').includes(Buffer.from(text))) + assert.deepEqual(Object.keys(packet).sort(), ['ciphertext', 'messageId', 'recipientDevice']) + await windows.getByText(text, { exact: true }).waitFor() + const reply = 'Windows 到 Web ' + randomBytes(8).toString('hex') + await send(windows, reply) + await web.getByText(reply, { exact: true }).waitFor() + + const contents = Buffer.from('端到端文件 ' + randomBytes(32).toString('hex')) + const fileName = '跨端验收.txt' + const upload = windows.waitForRequest((req) => req.method() === 'POST' && req.url().includes('/api/v1/attachments/')) + await windows.locator('input[type=file]').setInputFiles({ name: fileName, mimeType: 'text/plain', buffer: contents }) + const fileRequest = await upload + const uploaded = fileRequest.postDataBuffer() + assert.ok(uploaded) + assert.equal(uploaded.length, contents.length + 16) + assert.ok(!uploaded.includes(contents)) + assert.ok(!fileRequest.url().includes(encodeURIComponent(fileName))) + const fileButton = web.getByRole('button', { name: '下载 ' + fileName, exact: true }) + await fileButton.waitFor() + const fileURL = new URL(fileRequest.url()) + await web.route(fileURL.origin + fileURL.pathname, async (route) => { + const response = await route.fetch() + const corrupted = await response.body() + corrupted[0] ^= 1 + await route.fulfill({ response, body: corrupted }) + }, { times: 1 }) + await fileButton.click() + await web.getByText('附件完整性校验失败').waitFor() + const downloaded = web.waitForEvent('download') + await fileButton.click() + const file = await downloaded + assert.equal(file.suggestedFilename(), fileName) + assert.deepEqual(await readFile(await file.path()), contents) + + await windows.getByRole('button', { name: '退出登录' }).click() + await windows.getByRole('heading', { name: '登录 XHChat' }).waitFor() + const offline = '离线补拉 ' + randomBytes(8).toString('hex') + await send(web, offline) + await login(windows, b, password, false) + await windows.evaluate((url) => { location.hash = new URL(url).hash }, windowsChat) + assert.equal(await enable(windows), desktopCode) + await windows.getByText(offline, { exact: true }).waitFor() + const stored = await windows.evaluate(async () => { + const db = await new Promise((resolve, reject) => { + const request = indexedDB.open('xhchat-encrypted-chat', 1) + request.onsuccess = () => resolve(request.result) + request.onerror = () => reject(request.error) + }) + try { + return await new Promise((resolve, reject) => { + const request = db.transaction('vaults').objectStore('vaults').getAll() + request.onsuccess = () => resolve(request.result.map((value) => ({ + wrapped: typeof value.key === 'string', + encrypted: value.sealed instanceof ArrayBuffer && value.sealed.byteLength > 0, + fields: Object.keys(value).sort(), + }))) + request.onerror = () => reject(request.error) + }) + } finally { db.close() } + }) + assert.deepEqual(stored, [{ wrapped: true, encrypted: true, fields: ['iv', 'key', 'sealed'] }]) + } finally { + await desktop?.close() + await browser.close() + await rm(profile, { recursive: true, maxRetries: 5, retryDelay: 200, force: true }) + } +}) diff --git a/web/Dockerfile b/web/Dockerfile index ef53131..3ab7b1b 100644 --- a/web/Dockerfile +++ b/web/Dockerfile @@ -1,3 +1,12 @@ +FROM rust:1.95-bookworm AS mls +WORKDIR /src +RUN rustup target add wasm32-unknown-unknown +RUN cargo install --locked wasm-bindgen-cli --version 0.2.130 +COPY crypto/Cargo.toml crypto/Cargo.lock ./ +COPY crypto/src ./src +RUN cargo build --locked --release --target wasm32-unknown-unknown \ + && wasm-bindgen --target web --out-dir /mls target/wasm32-unknown-unknown/release/xhchat_mls_check.wasm + FROM node:24-alpine AS build WORKDIR /src COPY package.json package-lock.json ./ @@ -5,6 +14,7 @@ COPY web/package.json web/ COPY Desktop/package.json Desktop/ RUN npm ci --workspace web --include-workspace-root=false --no-audit COPY web/ web/ +COPY --from=mls /mls/ web/public/mls/ RUN npm run build -w web FROM nginx:alpine diff --git a/web/src/api.ts b/web/src/api.ts index 8df5adc..1827c87 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -6,20 +6,39 @@ export class APIError extends Error { } } -export async function request(path: string, method = 'GET', token = '', body?: object): Promise { +export async function request(path: string, method = 'GET', token = '', body?: object, binary = false): Promise { const headers: Record = { Accept: 'application/json' } if (token) headers.Authorization = 'Bearer ' + token - if (body) headers['Content-Type'] = 'application/json' + const bytes = body instanceof ArrayBuffer + if (body) headers['Content-Type'] = bytes ? 'application/octet-stream' : '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), + method, headers, body: bytes ? body : body ? JSON.stringify(body) : undefined, + credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(binary || bytes ? 60_000 : 12_000), }) } catch { throw new Error('无法连接 XHChat 服务,请检查网络后重试') } if (response.status === 204) return undefined as T + if (binary && response.ok) { + if (Number(response.headers.get('Content-Length')) > 8 * 1024 * 1024 + 16) throw new Error('附件超过大小限制') + const reader = response.body?.getReader() + if (!reader) throw new Error('附件下载失败') + const chunks: Uint8Array[] = [] + let length = 0 + for (;;) { + const { value, done } = await reader.read() + if (done) break + length += value.byteLength + if (length > 8 * 1024 * 1024 + 16) { + await reader.cancel() + throw new Error('附件超过大小限制') + } + chunks.push(value) + } + return await new Blob(chunks).arrayBuffer() as T + } const data = await response.json().catch(() => null) if (!response.ok) throw new APIError(response.status, data?.error?.message ?? '请求失败,请稍后重试') return data as T diff --git a/web/src/chat/attachments.ts b/web/src/chat/attachments.ts new file mode 100644 index 0000000..eb12f2d --- /dev/null +++ b/web/src/chat/attachments.ts @@ -0,0 +1,89 @@ +import { base64, decode } from './engine' +import type { Call } from './chat' + +const maxSize = 8 * 1024 * 1024 +const encoder = new TextEncoder() +const decoder = new TextDecoder('utf-8', { fatal: true }) + +export interface Attachment { + id: string + name: string + size: number + key: string + iv: string +} + +function attachmentPath(id: string) { + return '/attachments/' + encodeURIComponent(id) +} + +function authenticatedData(file: Pick) { + return encoder.encode(JSON.stringify(['XHChat attachment v1', file.id, file.name, file.size])) +} + +function safeName(name: string) { + return name.replace(/[\u0000-\u001f\u007f\u202a-\u202e\u2066-\u2069<>:"/\\|?*]/g, '_').trim().slice(0, 180) || 'attachment' +} + +export async function sealAttachment(file: File) { + if (file.size > maxSize) throw new Error('附件超过 8 MiB') + const key = crypto.getRandomValues(new Uint8Array(32)) + const iv = crypto.getRandomValues(new Uint8Array(12)) + const attachment = { id: crypto.randomUUID(), name: safeName(file.name), size: file.size, key: base64(key), iv: base64(iv) } + try { + const imported = await crypto.subtle.importKey('raw', key, 'AES-GCM', false, ['encrypt']) + const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: authenticatedData(attachment) }, imported, await file.arrayBuffer()) + return { attachment, ciphertext } + } finally { + key.fill(0) + } +} + +export function uploadAttachment(attachment: Attachment, ciphertext: ArrayBuffer, peer: string, call: Call) { + return call(attachmentPath(attachment.id) + '?recipient=' + encodeURIComponent(peer), 'POST', ciphertext) +} + +export function encodeAttachment(attachment: Attachment) { + const body = encoder.encode(JSON.stringify(attachment)) + const message = new Uint8Array(body.length + 2) + // An invalid UTF-8 prefix keeps attachment messages distinct from older text payloads. + message[0] = 255 + message[1] = 1 + message.set(body, 2) + return message +} + +export function decodeMessage(message: Uint8Array): { text: string; attachment?: Attachment } { + if (message[0] !== 255) return { text: decoder.decode(message) } + if (message[1] !== 1 || message.length > 4096) throw new Error('附件描述格式无效') + const value = JSON.parse(decoder.decode(message.subarray(2))) as Attachment | null + if (!value || typeof value.id !== 'string' || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(value.id) || + typeof value.name !== 'string' || value.name !== safeName(value.name) || + !Number.isInteger(value.size) || value.size < 0 || value.size > maxSize || + typeof value.key !== 'string' || decode(value.key).length !== 32 || + typeof value.iv !== 'string' || decode(value.iv).length !== 12) { + throw new Error('附件描述格式无效') + } + return { text: '', attachment: value } +} + +export async function downloadAttachment(attachment: Attachment, call: Call) { + const ciphertext = await call(attachmentPath(attachment.id), 'GET', undefined, true) + if (ciphertext.byteLength !== attachment.size + 16) throw new Error('附件完整性校验失败') + const raw = decode(attachment.key) + let bytes: ArrayBuffer + try { + const key = await crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['decrypt']) + bytes = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: decode(attachment.iv), additionalData: authenticatedData(attachment) }, key, ciphertext) + } catch { + throw new Error('附件完整性校验失败') + } finally { + raw.fill(0) + } + const url = URL.createObjectURL(new Blob([bytes], { type: 'application/octet-stream' })) + const link = document.createElement('a') + link.download = attachment.name + link.href = url + link.click() + setTimeout(() => URL.revokeObjectURL(url), 30_000) +} diff --git a/web/src/chat/chat.ts b/web/src/chat/chat.ts new file mode 100644 index 0000000..caba034 --- /dev/null +++ b/web/src/chat/chat.ts @@ -0,0 +1,246 @@ +import { APIError } from '../api' +import { mlsBinding, signMls } from '../identity' +import { base64, decode, fingerprint, loadEngine } from './engine' +import type { DeviceMls } from './engine' +import { withVault } from './vault' +import { decodeMessage, encodeAttachment, sealAttachment, uploadAttachment } from './attachments' +import type { Attachment } from './attachments' + +export interface Peer { + id: string + name: string + publicKey: string + mls?: { publicKey: string; signature: string } +} + +export interface ChatIdentity { + user: { id: string; username: string } + device: { id: string } +} + +interface Package { package: string; signature: string } +interface Outgoing { messageId: string; recipientDevice: string; ciphertext: string } +interface Incoming { messageId: string; senderDevice: string; ciphertext: string; sequence: string; createdAt: string } + +export interface ChatLine { + id: string + peer: string + text: string + attachment?: Attachment + time: string + own: boolean +} + +interface ChatState { + engine: string + cursor: string + pending: Incoming[] + outbox: Outgoing[] + lines: ChatLine[] + pinned: Record + groups: Record + package?: { lastPublished: number; item: Package } + rejected: number +} + +export type Call = (path: string, method?: string, body?: object, binary?: boolean) => Promise +const encoder = new TextEncoder() + +function aad(id: string, sender: string, recipient: string) { + return encoder.encode('XHChat message v1\n' + id + '\n' + sender + '\n' + recipient) +} + +async function verify(peer: Peer, user: string, type: 'credential' | 'KeyPackage', value: Uint8Array, signature: string) { + const key = await crypto.subtle.importKey('raw', decode(peer.publicKey), 'Ed25519', false, ['verify']) + if (!await crypto.subtle.verify('Ed25519', key, decode(signature), mlsBinding(type, user, peer.id, value))) { + throw new Error('对方设备签名验证失败') + } +} + +async function verifiedPeer(peer: Peer, user: string) { + if (!peer.mls) throw new Error('此设备尚未启用加密聊天') + const key = decode(peer.mls.publicKey) + await verify(peer, user, 'credential', key, peer.mls.signature) + return key +} + +export function directory(call: Call, user: string) { + return call('/contacts/' + user + '/devices') +} + +function update(identity: ChatIdentity, operation: (s: ChatState, save: (s: ChatState) => Promise, factory: Awaited>) => Promise) { + return withVault(identity.device.id, async (state, save) => { + const factory = await loadEngine() + if (!state) { + const engine = new factory.DeviceMls(identity.device.id) + try { + state = { engine: base64(engine.snapshot()), cursor: '0', pending: [], outbox: [], lines: [], pinned: {}, groups: {}, rejected: 0 } + await save(state) + } finally { + engine.free() + } + } + return operation(state, save, factory) + }) +} + +async function signed(identity: ChatIdentity, kind: 'credential' | 'KeyPackage', value: Uint8Array) { + return base64(await signMls(identity.user.username, kind, identity.user.id, identity.device.id, value)) +} + +export async function enableChat(identity: ChatIdentity, call: Call) { + return update(identity, async (state, save, factory) => { + const engine = factory.DeviceMls.restore(decode(state.engine)) + try { + if (engine.device() !== identity.device.id) throw new Error('本机加密状态属于其他设备') + const key = engine.public_key() + await call('/mls-credential', 'POST', { publicKey: base64(key), signature: await signed(identity, 'credential', key) }) + if (!state.package || Date.now() - state.package.lastPublished >= 6 * 3600_000) { + if (!state.package || state.package.lastPublished) { + const pack = engine.key_package() + state.package = { lastPublished: 0, item: { package: base64(pack), signature: await signed(identity, 'KeyPackage', pack) } } + state.engine = base64(engine.snapshot()) + await save(state) + } + await call('/key-packages', 'POST', state.package.item) + state.package.lastPublished = Date.now() + await save(state) + } + return fingerprint(decode(await localIdentityKey(identity, call))) + } finally { + engine.free() + } + }) +} + +async function localIdentityKey(identity: ChatIdentity, call: Call) { + const { publicKey } = await call<{ publicKey: string }>('/mls-local-key') + const credential = decode(publicKey) + const proof = await signed(identity, 'credential', credential) + await verify({ id: identity.device.id, name: '', publicKey }, identity.user.id, 'credential', credential, proof) + return publicKey +} + +export async function trust(identity: ChatIdentity, user: string, peer: Peer, code: string) { + await verifiedPeer(peer, user) + const expected = await fingerprint(decode(peer.publicKey)) + if (code.replace(/\s+/g, '').toLowerCase() !== expected) throw new Error('安全码不匹配') + await update(identity, async (state, save) => { + const previous = state.pinned[peer.id] + if (previous && previous !== peer.publicKey) throw new Error('该设备身份已变更,请使用新设备重新建立会话') + state.pinned[peer.id] = peer.publicKey + await save(state) + }) +} + +async function flush(state: ChatState, save: (state: ChatState) => Promise, call: Call) { + const unavailable = new Set() + for (const item of [...state.outbox]) { + if (unavailable.has(item.recipientDevice)) continue + try { + await call('/inbox', 'POST', item) + state.outbox = state.outbox.filter((pending) => pending.messageId !== item.messageId) + await save(state) + } catch (error) { + if (!(error instanceof APIError) || error.status !== 404) throw error + unavailable.add(item.recipientDevice) + } + } + return unavailable +} + +export function send(identity: ChatIdentity, user: string, peer: Peer, content: string | File, call: Call) { + return update(identity, async (state, save, factory) => { + const current = (await directory(call, user)).find((item) => item.id === peer.id) + if (!current || state.pinned[current.id] !== current.publicKey) throw new Error('发送前请核验对方设备安全码') + const key = await verifiedPeer(current, user) + const unavailable = await flush(state, save, call) + if (unavailable.has(current.id)) throw new Error('该设备暂不可接收消息') + const text = typeof content === 'string' ? content.trim() : '' + let plaintext = encoder.encode(text) + if (typeof content === 'string' && (!plaintext.length || plaintext.length > 8000)) { + throw new Error('消息须为 1 至 8000 字节') + } + if (state.lines.length >= 1000) throw new Error('本机预览版消息容量已达上限') + const engine = factory.DeviceMls.restore(decode(state.engine)) + try { + let group = state.groups[current.id] ? decode(state.groups[current.id]) : undefined + let attachment: Attachment | undefined + if (typeof content !== 'string') { + const sealed = await sealAttachment(content) + attachment = sealed.attachment + await uploadAttachment(attachment, sealed.ciphertext, current.id, call) + plaintext = encodeAttachment(attachment) + } + if (!group) { + const pack = await call('/contacts/' + user + '/devices/' + current.id + '/claim', 'POST') + const wire = decode(pack.package) + await verify(current, user, 'KeyPackage', wire, pack.signature) + group = crypto.getRandomValues(new Uint8Array(32)) + const welcome = engine.start(group, current.id, key, wire) + state.groups[current.id] = base64(group) + state.outbox.push({ messageId: crypto.randomUUID(), recipientDevice: current.id, ciphertext: base64(welcome) }) + } + const id = crypto.randomUUID() + const ciphertext = engine.encrypt(group, aad(id, identity.device.id, current.id), plaintext) + state.outbox.push({ messageId: id, recipientDevice: current.id, ciphertext: base64(ciphertext) }) + state.lines.push({ id, peer: current.id, text, attachment, time: new Date().toISOString(), own: true }) + state.engine = base64(engine.snapshot()) + await save(state) + await flush(state, save, call) + } finally { + engine.free() + } + }) +} + +export function synchronize(identity: ChatIdentity, user: string, call: Call) { + return update(identity, async (state, save, factory) => { + const peers = await directory(call, user) + for (let page = 0; page < 4; page++) { + const inbox = await call('/inbox?after=' + state.cursor) + if (!inbox.length) break + if (state.pending.length + inbox.length > 512) throw new Error('待验证消息已达上限,请先打开相应联系人的聊天') + state.pending.push(...inbox) + state.cursor = inbox.at(-1)!.sequence + await save(state) + if (inbox.length < 64) break + } + for (const item of [...state.pending]) { + const peer = peers.find((device) => device.id === item.senderDevice) + if (!peer || !peer.mls || state.pinned[peer.id] !== peer.publicKey) continue + const engine = factory.DeviceMls.restore(decode(state.engine)) + try { + const key = await verifiedPeer(peer, user) + const wire = decode(item.ciphertext) + if (wire[3] === 3) { + const group = base64(engine.join(peer.id, key, wire)) + const previous = state.groups[peer.id] + if (!previous || group < previous) state.groups[peer.id] = group + } else { + const plaintext = engine.decrypt(peer.id, key, aad(item.messageId, peer.id, identity.device.id), wire) + if (state.lines.length < 1000) state.lines.push({ + id: item.messageId, peer: peer.id, ...decodeMessage(plaintext), + time: item.createdAt, own: false, + }) + } + state.engine = base64(engine.snapshot()) + } catch { + state.rejected++ + } finally { + engine.free() + } + state.pending = state.pending.filter((pending) => pending.sequence !== item.sequence) + await save(state) + } + let deliveryError = '' + try { + const unavailable = await flush(state, save, call) + if (unavailable.size) deliveryError = '部分待发消息的设备已不可用' + } catch (cause) { + deliveryError = cause instanceof APIError && cause.status === 404 ? '部分待发消息的设备已不可用' : '部分消息等待重试' + } + return { lines: state.lines, pinned: state.pinned, peers, rejected: state.rejected, deliveryError, + unsent: state.outbox.map((item) => item.messageId) } + }) +} diff --git a/web/src/chat/engine.ts b/web/src/chat/engine.ts new file mode 100644 index 0000000..3cd733d --- /dev/null +++ b/web/src/chat/engine.ts @@ -0,0 +1,48 @@ +export interface DeviceMls { + free(): void + snapshot(): Uint8Array + device(): string + public_key(): Uint8Array + key_package(): Uint8Array + start(id: Uint8Array, peer: string, key: Uint8Array, wire: Uint8Array): Uint8Array + join(peer: string, key: Uint8Array, wire: Uint8Array): Uint8Array + encrypt(id: Uint8Array, aad: Uint8Array, value: Uint8Array): Uint8Array + decrypt(peer: string, key: Uint8Array, aad: Uint8Array, wire: Uint8Array): Uint8Array +} + +interface Module { + default(): Promise + DeviceMls: { + new (device: string): DeviceMls + restore(bytes: Uint8Array): DeviceMls + } +} + +let pending: Promise | undefined + +export function loadEngine() { + const path = '/mls/xhchat_mls_check.js' + pending ??= import(/* @vite-ignore */ path).then(async (module: Module) => { + await module.default() + return module + }).catch((error) => { + pending = undefined + throw error + }) + return pending +} + +export function base64(bytes: Uint8Array) { + let binary = '' + for (let i = 0; i < bytes.length; i += 4096) binary += String.fromCharCode(...bytes.subarray(i, i + 4096)) + return btoa(binary) +} + +export function decode(value: string) { + return Uint8Array.from(atob(value), (character) => character.charCodeAt(0)) +} + +export async function fingerprint(key: Uint8Array) { + return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', key)), + (byte) => byte.toString(16).padStart(2, '0')).join('') +} diff --git a/web/src/chat/vault.ts b/web/src/chat/vault.ts new file mode 100644 index 0000000..df3de40 --- /dev/null +++ b/web/src/chat/vault.ts @@ -0,0 +1,71 @@ +import { base64, decode } from './engine' + +interface VaultRecord { + key: CryptoKey | string + iv?: Uint8Array + sealed?: ArrayBuffer +} + +function database(): Promise { + return new Promise((resolve, reject) => { + const request = indexedDB.open('xhchat-encrypted-chat', 1) + request.onupgradeneeded = () => request.result.createObjectStore('vaults') + request.onsuccess = () => resolve(request.result) + request.onerror = () => reject(request.error) + request.onblocked = () => reject(new Error('请关闭其他 XHChat 页面后重试')) + }) +} + +function record(db: IDBDatabase, scope: string, value?: VaultRecord): Promise { + return new Promise((resolve, reject) => { + const transaction = db.transaction('vaults', value ? 'readwrite' : 'readonly') + const store = transaction.objectStore('vaults') + const request = value ? store.put(value, scope) : store.get(scope) + transaction.oncomplete = () => resolve(value ?? request.result) + transaction.onabort = () => reject(transaction.error) + }) +} + +async function newKey(): Promise { + if (!window.xhchat) return crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']) + const raw = crypto.getRandomValues(new Uint8Array(32)) + try { + return await window.xhchat.protectMls(base64(raw)) + } finally { + raw.fill(0) + } +} + +async function unsealKey(value: VaultRecord['key']) { + if (!window.xhchat && typeof value !== 'string') return value + if (!window.xhchat || typeof value !== 'string') throw new Error('会话存储密钥无效') + const raw = decode(await window.xhchat.unprotectMls(value)) + try { + return await crypto.subtle.importKey('raw', raw, 'AES-GCM', false, ['encrypt', 'decrypt']) + } finally { + raw.fill(0) + } +} + +export async function withVault(device: string, update: (state: T | undefined, save: (state: T) => Promise) => Promise) { + const scope = (window.xhchat?.apiBase ?? location.origin) + '/' + device + const additionalData = new TextEncoder().encode(scope) + return navigator.locks.request('xhchat-chat:' + scope, async () => { + const db = await database() + try { + const stored = await record(db, scope) + const wrapped = stored?.key ?? await newKey() + const key = await unsealKey(wrapped) + const state = stored?.iv && stored.sealed + ? JSON.parse(new TextDecoder().decode(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: stored.iv, additionalData }, key, stored.sealed))) as T + : undefined + return await update(state, async (next) => { + const iv = crypto.getRandomValues(new Uint8Array(12)) + const sealed = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData }, key, new TextEncoder().encode(JSON.stringify(next))) + await record(db, scope, { key: wrapped, iv, sealed }) + }) + } finally { + db.close() + } + }) +} diff --git a/web/src/identity.ts b/web/src/identity.ts index 35b6beb..1288ecd 100644 --- a/web/src/identity.ts +++ b/web/src/identity.ts @@ -7,6 +7,9 @@ interface DesktopBridge { apiBase: string signChallenge: (username: string, challenge: string) => Promise openBrowser?: () => Promise + signMls: (username: string, kind: 'credential' | 'KeyPackage', user: string, device: string, value: Uint8Array) => Promise> + protectMls: (key: string) => Promise + unprotectMls: (key: string) => Promise } declare global { @@ -53,6 +56,20 @@ async function browserKey(username: string): Promise { export const platform = window.xhchat ? 'windows' : 'web' +export function mlsBinding(kind: 'credential' | 'KeyPackage', user: string, device: string, value: Uint8Array) { + const prefix = new TextEncoder().encode('XHChat MLS ' + kind + ' v1\n' + user + '\n' + device + '\n') + const bytes = new Uint8Array(prefix.length + value.length) + bytes.set(prefix) + bytes.set(value, prefix.length) + return bytes +} + +export async function signMls(username: string, kind: 'credential' | 'KeyPackage', user: string, device: string, value: Uint8Array) { + if (window.xhchat) return window.xhchat.signMls(username, kind, user, device, value) + const pair = await browserKey(username) + return new Uint8Array(await crypto.subtle.sign('Ed25519', pair.privateKey, mlsBinding(kind, user, device, value))) +} + export async function signChallenge(username: string, challenge: string): Promise { if (window.xhchat) return window.xhchat.signChallenge(username, challenge) try { diff --git a/web/src/main.ts b/web/src/main.ts index 43d8e6e..7300b43 100644 --- a/web/src/main.ts +++ b/web/src/main.ts @@ -5,6 +5,7 @@ import App from './App.vue' import AuthView from './views/AuthView.vue' import DeviceView from './views/DeviceView.vue' import ContactsView from './views/ContactsView.vue' +import ChatView from './views/ChatView.vue' import Workspace from './views/Workspace.vue' import { useSession } from './session' import './style.css' @@ -18,6 +19,7 @@ const router = createRouter({ { path: '/', component: Workspace, children: [ { path: 'devices', component: DeviceView }, { path: 'contacts', component: ContactsView }, + { path: 'chat/:user?', component: ChatView }, ] }, { path: '/:pathMatch(.*)*', redirect: '/' }, ], diff --git a/web/src/session.ts b/web/src/session.ts index d872746..737a4b9 100644 --- a/web/src/session.ts +++ b/web/src/session.ts @@ -25,6 +25,7 @@ export const useSession = defineStore('session', () => { const identity = shallowRef() const connection = ref('离线') const contactChanges = ref(0) + const inboxChanges = ref(0) let token = '' let socket: WebSocket | undefined let retry: ReturnType | undefined @@ -56,6 +57,7 @@ export const useSession = defineStore('session', () => { attempts = 0 } if (type === 'contacts_changed') contactChanges.value++ + if (type === 'inbox_changed') inboxChanges.value++ } active.onclose = (event) => { if (socket !== active) return @@ -89,11 +91,14 @@ export const useSession = defineStore('session', () => { void connect(token) } - async function authorized(path: string, method = 'GET', body?: object) { + async function authorized(path: string, method = 'GET', body?: object, binary = false) { + const current = token try { - return await request(path, method, token, body) + const response = await request(path, method, current, body, binary) + if (token !== current) throw new Error('登录会话已变更') + return response } catch (error) { - if (error instanceof APIError && error.status === 401) clear() + if (token === current && error instanceof APIError && error.status === 401) clear() throw error } } @@ -104,7 +109,7 @@ export const useSession = defineStore('session', () => { } return { - identity, connection, contactChanges, authenticate, logout, + identity, connection, contactChanges, inboxChanges, authenticate, logout, authorized, devices: () => authorized('/devices'), revoke: (id: string) => authorized('/devices/' + encodeURIComponent(id), 'DELETE'), contacts: () => authorized('/contacts'), diff --git a/web/src/style.css b/web/src/style.css index 3d28623..56e1561 100644 --- a/web/src/style.css +++ b/web/src/style.css @@ -73,6 +73,18 @@ input { width: 100%; color: var(--text); background: var(--base); border: 1px so .contact-heading h1 { font-size: 22px; } .contact-detail > button { margin-bottom: 18px; } .contact-preferences { max-width: 340px; } +.chat-page { display: grid; gap: 14px; } +.chat-page > button { justify-self: start; } +.chat-page details p { margin: 8px 0; } +.security-code { overflow-wrap: anywhere; color: var(--green); } +.chat-page select, .chat-compose textarea { font: inherit; border: 1px solid var(--line); border-radius: 8px; background: var(--base); color: var(--text); padding: 8px; } +.verified-label { color: var(--green); font-weight: 600; } +.chat-lines { list-style: none; padding: 0; margin: 0; min-height: 90px; max-height: 45vh; overflow: auto; display: flex; flex-direction: column; gap: 8px; } +.chat-lines li { align-self: start; border-radius: 9px; background: var(--base); padding: 8px 11px; max-width: 85%; white-space: pre-wrap; overflow-wrap: anywhere; } +.chat-lines li.own { align-self: end; background: var(--green-soft); } +.chat-lines small { display: block; text-align: end; } +.chat-compose { display: grid; gap: 8px; } +.chat-compose button { justify-self: end; } .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; } diff --git a/web/src/views/ChatView.vue b/web/src/views/ChatView.vue new file mode 100644 index 0000000..057847b --- /dev/null +++ b/web/src/views/ChatView.vue @@ -0,0 +1,156 @@ + + + diff --git a/web/src/views/ContactsView.vue b/web/src/views/ContactsView.vue index fbf95af..67f347b 100644 --- a/web/src/views/ContactsView.vue +++ b/web/src/views/ContactsView.vue @@ -115,6 +115,7 @@ async function change(action: ContactAction) {
+ 打开加密聊天 diff --git a/web/src/views/Workspace.vue b/web/src/views/Workspace.vue index a3c4945..832cd55 100644 --- a/web/src/views/Workspace.vue +++ b/web/src/views/Workspace.vue @@ -24,6 +24,7 @@ async function act(action: () => Promise) {