接通 Windows 与 Web 设备间加密文字聊天
This commit is contained in:
1 parent
b04034ee89
commit
d1efdedc57
27 files changed
+880
-22
No files matched your search
@@ -6,3 +6,5 @@
|
||||
docs
|
||||
Android
|
||||
server
|
||||
crypto/target
|
||||
web/public/mls
|
||||
@@ -6,3 +6,4 @@ dist/
|
||||
test-results/
|
||||
playwright-report/
|
||||
/crypto/target/
|
||||
/web/public/mls/
|
||||
+20
-4
@@ -25,6 +25,13 @@ export async function signChallenge(server: string, username: string, challenge:
|
||||
if (!/^[a-z0-9_]{3,32}$/.test(username) || !/^[A-Za-z0-9_-]{43}$/.test(challenge)) {
|
||||
throw new Error('设备验证参数无效')
|
||||
}
|
||||
const key = await deviceKey(server, username)
|
||||
const publicKey = createPublicKey(key).export({ format: 'jwk' }).x!
|
||||
const signature = sign(null, Buffer.from('XHChat device authentication v1\n' + challenge), key).toString('base64url')
|
||||
return { publicKey, signature }
|
||||
}
|
||||
|
||||
async function deviceKey(server: string, username: string) {
|
||||
const directory = join(app.getPath('userData'), 'device-keys')
|
||||
await mkdir(directory, { recursive: true })
|
||||
const file = join(directory, createHash('sha256').update(server + '\n' + username).digest('hex'))
|
||||
@@ -33,8 +40,17 @@ export async function signChallenge(server: string, username: string, challenge:
|
||||
pending = readOrCreate(file).finally(() => active.delete(file))
|
||||
active.set(file, pending)
|
||||
}
|
||||
const key = await pending
|
||||
const publicKey = createPublicKey(key).export({ format: 'jwk' }).x!
|
||||
const signature = sign(null, Buffer.from('XHChat device authentication v1\n' + challenge), key).toString('base64url')
|
||||
return { publicKey, signature }
|
||||
return pending
|
||||
}
|
||||
|
||||
export async function signMls(server: string, username: string, kind: string, user: string, device: string, value: Uint8Array) {
|
||||
const id = /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/
|
||||
if (!/^[a-z0-9_]{3,32}$/.test(username) || !id.test(user) || !id.test(device) ||
|
||||
!(value instanceof Uint8Array) ||
|
||||
!(kind === 'credential' && value.length === 32 ||
|
||||
kind === 'KeyPackage' && value.length >= 32 && value.length <= 8192)) {
|
||||
throw new Error('MLS 签名参数无效')
|
||||
}
|
||||
const key = await deviceKey(server, username)
|
||||
return new Uint8Array(sign(null, Buffer.concat([Buffer.from('XHChat MLS ' + kind + ' v1\n' + user + '\n' + device + '\n'), value]), key))
|
||||
}
|
||||
+32
-6
@@ -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('浏览器入口来源无效')
|
||||
|
||||
@@ -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),
|
||||
})
|
||||
@@ -16,9 +16,10 @@
|
||||
| --- | --- |
|
||||
| 账号与设备 | Windows 和 Web 共用账号,支持用户名注册、登录、查看设备和远程撤销。 |
|
||||
| 联系人 | 按用户名查找、处理好友申请、管理备注与分组,以及拉黑。变更可在双端实时同步。 |
|
||||
| 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 |
|
||||
| Chromium 浏览器 | Windows 端支持独立窗口、多标签、导航、搜索和隐私窗口,网页运行在独立会话中。 |
|
||||
|
||||
当前为开发预览。OpenMLS 已完成原生与浏览器的协议验证。应用内加密聊天、群聊和音视频仍在开发,Windows 安装包尚未发布。 [开发进度与验收记录](docs/progress.md)
|
||||
当前为开发预览。附件、群聊、音视频和多设备历史同步仍在开发,Windows 安装包尚未发布。 [开发进度与验收记录](docs/progress.md)
|
||||
|
||||
## 本地预览
|
||||
|
||||
@@ -38,12 +39,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)。
|
||||
|
||||
体验加密文字聊天时,注册两个账号并互加好友。在双方的联系人详情中打开「加密聊天」,启用本机加密,通过另一可信渠道交换安全码,分别核验对方设备后即可互发消息。
|
||||
|
||||
## 开发文档
|
||||
|
||||
| 主题 | 文档 |
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ server {
|
||||
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;
|
||||
|
||||
@@ -21,6 +21,8 @@
|
||||
| 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/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 +33,6 @@
|
||||
|
||||
密钥包与签名均使用标准 Base64。设备以已有的 Ed25519 密钥签名 UTF-8 前缀 `XHChat MLS KeyPackage v1\n{userId}\n{deviceId}\n` 和原始 MLS 封包的拼接。服务端验证签名和外层格式,密钥包可在发布后的 24 小时内领取一次。客户端仍需独立验证设备公钥信任和完整 MLS 对象。重试发布同一封包不会再次开放领取。
|
||||
|
||||
MLS 凭据由标准 Base64 的 publicKey 和 signature 组成,使用 UTF-8 前缀 `XHChat MLS credential v1\n{userId}\n{deviceId}\n` 后接 32 字节 MLS Ed25519 公钥。设备目录返回可选的 mls 对象。已登记公钥仅允许原值重试。
|
||||
|
||||
下一阶段将增加 /conversations 和 /attachments。后续加入 /groups、/calls、/posts、/backups、/push 与独立的管理接口。
|
||||
+10
-1
@@ -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
|
||||
```
|
||||
+7
-1
@@ -19,7 +19,7 @@ Web 和 Electron 共用 Vue 客户端,独立接入同一 Go API。真实 Postg
|
||||
## 尚待实现
|
||||
|
||||
- 阶段一还需邮箱和手机号注册、验证码服务、找回密码和双重验证。真实联调需要 SMTP 与短信供应商配置。
|
||||
- 阶段二与三还需定版并验证双端 E2EE,交付私聊、附件、离线消息、群聊、多设备可信授权、加密备份与同步。当前基础设备认证没有消息密钥能力。
|
||||
- 阶段二与三还需附件、消息操作、群聊、多设备可信授权、加密备份与跨设备历史同步。两设备文字私聊已进入开发预览。
|
||||
- 阶段四还需 WebRTC 音视频、TURN、SFU、屏幕共享及媒体 E2EE。
|
||||
- 阶段五还需持久书签和历史、下载记录、逐站授权、反钓鱼及聊天联动。
|
||||
- 阶段六到八还需社交、扩展生态、独立管理后台、推送、生产部署与备份演练、压力测试、安全评估、签名安装包和发布流程。
|
||||
@@ -44,3 +44,9 @@ 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 更新、可信设备授权与安全评估待后续交付。
|
||||
@@ -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)
|
||||
);
|
||||
@@ -19,6 +19,9 @@ var deliveryMigration string
|
||||
//go:embed 004_key_packages.sql
|
||||
var keyPackagesMigration string
|
||||
|
||||
//go:embed 005_mls_credentials.sql
|
||||
var mlsCredentialsMigration string
|
||||
|
||||
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
@@ -31,7 +34,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} {
|
||||
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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -53,6 +53,8 @@ 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("GET /api/v1/mls-local-key", a.authorized(a.localMLSKey))
|
||||
return a.boundary(mux)
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
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'
|
||||
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()
|
||||
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()
|
||||
|
||||
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 })
|
||||
}
|
||||
})
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
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'
|
||||
|
||||
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
|
||||
time: string
|
||||
own: boolean
|
||||
}
|
||||
|
||||
interface ChatState {
|
||||
engine: string
|
||||
cursor: string
|
||||
pending: Incoming[]
|
||||
outbox: Outgoing[]
|
||||
lines: ChatLine[]
|
||||
pinned: Record<string, string>
|
||||
groups: Record<string, string>
|
||||
package?: { lastPublished: number; item: Package }
|
||||
rejected: number
|
||||
}
|
||||
|
||||
export type Call = <T>(path: string, method?: string, body?: object) => Promise<T>
|
||||
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<Peer[]>('/contacts/' + user + '/devices')
|
||||
}
|
||||
|
||||
function update<R>(identity: ChatIdentity, operation: (s: ChatState, save: (s: ChatState) => Promise<void>, factory: Awaited<ReturnType<typeof loadEngine>>) => Promise<R>) {
|
||||
return withVault<ChatState, R>(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<ArrayBuffer>) {
|
||||
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<void>, call: Call) {
|
||||
const unavailable = new Set<string>()
|
||||
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, text: string, 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 plaintext = encoder.encode(text.trim())
|
||||
if (!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
|
||||
if (!group) {
|
||||
const pack = await call<Package>('/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: text.trim(), 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<Incoming[]>('/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, text: new TextDecoder('utf-8', { fatal: true }).decode(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) }
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
export interface DeviceMls {
|
||||
free(): void
|
||||
snapshot(): Uint8Array<ArrayBuffer>
|
||||
device(): string
|
||||
public_key(): Uint8Array<ArrayBuffer>
|
||||
key_package(): Uint8Array<ArrayBuffer>
|
||||
start(id: Uint8Array, peer: string, key: Uint8Array, wire: Uint8Array): Uint8Array<ArrayBuffer>
|
||||
join(peer: string, key: Uint8Array, wire: Uint8Array): Uint8Array<ArrayBuffer>
|
||||
encrypt(id: Uint8Array, aad: Uint8Array, value: Uint8Array): Uint8Array<ArrayBuffer>
|
||||
decrypt(peer: string, key: Uint8Array, aad: Uint8Array, wire: Uint8Array): Uint8Array<ArrayBuffer>
|
||||
}
|
||||
|
||||
interface Module {
|
||||
default(): Promise<unknown>
|
||||
DeviceMls: {
|
||||
new (device: string): DeviceMls
|
||||
restore(bytes: Uint8Array): DeviceMls
|
||||
}
|
||||
}
|
||||
|
||||
let pending: Promise<Module> | 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<ArrayBuffer>) {
|
||||
return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', key)),
|
||||
(byte) => byte.toString(16).padStart(2, '0')).join('')
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { base64, decode } from './engine'
|
||||
|
||||
interface VaultRecord {
|
||||
key: CryptoKey | string
|
||||
iv?: Uint8Array<ArrayBuffer>
|
||||
sealed?: ArrayBuffer
|
||||
}
|
||||
|
||||
function database(): Promise<IDBDatabase> {
|
||||
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<VaultRecord | undefined> {
|
||||
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<VaultRecord['key']> {
|
||||
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<T, R>(device: string, update: (state: T | undefined, save: (state: T) => Promise<void>) => Promise<R>) {
|
||||
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()
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -7,6 +7,9 @@ interface DesktopBridge {
|
||||
apiBase: string
|
||||
signChallenge: (username: string, challenge: string) => Promise<DeviceProof>
|
||||
openBrowser?: () => Promise<void>
|
||||
signMls: (username: string, kind: 'credential' | 'KeyPackage', user: string, device: string, value: Uint8Array<ArrayBuffer>) => Promise<Uint8Array<ArrayBuffer>>
|
||||
protectMls: (key: string) => Promise<string>
|
||||
unprotectMls: (key: string) => Promise<string>
|
||||
}
|
||||
|
||||
declare global {
|
||||
@@ -53,6 +56,20 @@ async function browserKey(username: string): Promise<CryptoKeyPair> {
|
||||
|
||||
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<ArrayBuffer>) {
|
||||
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<DeviceProof> {
|
||||
if (window.xhchat) return window.xhchat.signChallenge(username, challenge)
|
||||
try {
|
||||
|
||||
@@ -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: '/' },
|
||||
],
|
||||
|
||||
+8
-3
@@ -25,6 +25,7 @@ export const useSession = defineStore('session', () => {
|
||||
const identity = shallowRef<Identity>()
|
||||
const connection = ref('离线')
|
||||
const contactChanges = ref(0)
|
||||
const inboxChanges = ref(0)
|
||||
let token = ''
|
||||
let socket: WebSocket | undefined
|
||||
let retry: ReturnType<typeof setTimeout> | 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
|
||||
@@ -90,10 +92,13 @@ export const useSession = defineStore('session', () => {
|
||||
}
|
||||
|
||||
async function authorized<T>(path: string, method = 'GET', body?: object) {
|
||||
const current = token
|
||||
try {
|
||||
return await request<T>(path, method, token, body)
|
||||
const response = await request<T>(path, method, current, body)
|
||||
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<Device[]>('/devices'),
|
||||
revoke: (id: string) => authorized<void>('/devices/' + encodeURIComponent(id), 'DELETE'),
|
||||
contacts: () => authorized<Contact[]>('/contacts'),
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { useSession } from '../session'
|
||||
import { enableChat, send, synchronize, trust } from '../chat/chat'
|
||||
|
||||
const session = useSession()
|
||||
const route = useRoute()
|
||||
const ownCode = ref('')
|
||||
const code = ref('')
|
||||
const selected = ref('')
|
||||
const draft = ref('')
|
||||
const error = ref('')
|
||||
const busy = ref(false)
|
||||
const view = ref<Awaited<ReturnType<typeof synchronize>>>()
|
||||
const target = computed(() => typeof route.params.user === 'string' ? route.params.user : '')
|
||||
const peer = computed(() => view.value?.peers.find((item) => item.id === selected.value))
|
||||
const trusted = computed(() => peer.value && view.value?.pinned[peer.value.id] === peer.value.publicKey)
|
||||
const changed = computed(() => peer.value && view.value?.pinned[peer.value.id] && !trusted.value)
|
||||
const lines = computed(() => (view.value?.lines ?? []).filter((line) => line.peer === selected.value))
|
||||
let timer: ReturnType<typeof setInterval>
|
||||
|
||||
async function execute(action: () => Promise<void>) {
|
||||
if (busy.value || !session.identity) return
|
||||
busy.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await action()
|
||||
} catch (cause) {
|
||||
error.value = cause instanceof Error ? cause.message : '加密聊天暂不可用'
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
const identity = session.identity
|
||||
if (!identity || !target.value || !ownCode.value) return
|
||||
const contact = target.value
|
||||
const current = await synchronize(identity, contact, session.authorized)
|
||||
if (target.value !== contact) return
|
||||
view.value = current
|
||||
if (!current.peers.some((device) => device.id === selected.value)) selected.value = current.peers[0]?.id ?? ''
|
||||
}
|
||||
|
||||
function enable() {
|
||||
void execute(async () => {
|
||||
if (!session.identity) return
|
||||
ownCode.value = await enableChat(session.identity, session.authorized)
|
||||
await refresh()
|
||||
})
|
||||
}
|
||||
|
||||
function confirm() {
|
||||
void execute(async () => {
|
||||
if (!session.identity || !peer.value) return
|
||||
await trust(session.identity, target.value, peer.value, code.value)
|
||||
code.value = ''
|
||||
await refresh()
|
||||
})
|
||||
}
|
||||
|
||||
function submit() {
|
||||
void execute(async () => {
|
||||
if (!session.identity || !peer.value) return
|
||||
await send(session.identity, target.value, peer.value, draft.value, session.authorized)
|
||||
draft.value = ''
|
||||
await refresh()
|
||||
})
|
||||
}
|
||||
|
||||
function sync() {
|
||||
if (ownCode.value) void execute(refresh)
|
||||
}
|
||||
|
||||
watch(target, () => {
|
||||
view.value = undefined
|
||||
selected.value = ''
|
||||
code.value = ''
|
||||
draft.value = ''
|
||||
sync()
|
||||
})
|
||||
watch(() => [session.inboxChanges, session.contactChanges, session.connection], sync)
|
||||
onMounted(() => { timer = setInterval(sync, 10_000) })
|
||||
onBeforeUnmount(() => clearInterval(timer))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="device-page">
|
||||
<header class="page-header">
|
||||
<h1>加密聊天</h1>
|
||||
<button v-if="ownCode" class="plain" :disabled="busy" @click="sync">刷新</button>
|
||||
</header>
|
||||
<div class="device-content chat-page">
|
||||
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||
<button v-if="!ownCode" type="button" class="primary" :disabled="busy" @click="enable">启用本机加密聊天</button>
|
||||
<template v-else>
|
||||
<details open>
|
||||
<summary>本机安全码</summary>
|
||||
<p>请通过另一可信渠道将此安全码告知对方。双方都需验证。</p>
|
||||
<code class="security-code">{{ ownCode }}</code>
|
||||
</details>
|
||||
<template v-if="target">
|
||||
<label v-if="view?.peers.length">对方设备
|
||||
<select v-model="selected" :disabled="busy">
|
||||
<option v-for="device in view.peers" :key="device.id" :value="device.id">{{ device.name }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<p v-else>对方设备出现后可开始验证。</p>
|
||||
<p v-if="changed" class="error" role="alert">设备身份已变更,请重新核验。</p>
|
||||
<p v-if="peer && !peer.mls">等待对方启用本机加密聊天。</p>
|
||||
<form v-if="peer?.mls && !trusted" class="contact-preferences" @submit.prevent="confirm">
|
||||
<label>对方安全码<input v-model="code" required maxlength="100" autocomplete="off"></label>
|
||||
<button class="plain" :disabled="busy">核验设备</button>
|
||||
</form>
|
||||
<template v-if="trusted">
|
||||
<p class="verified-label">设备已验证</p>
|
||||
<p v-if="view?.deliveryError" class="error">{{ view.deliveryError }}</p>
|
||||
<p v-if="view?.rejected" class="muted">已拒绝 {{ view.rejected }} 个无法验证的封包。</p>
|
||||
<ol class="chat-lines" aria-label="消息记录" aria-live="polite">
|
||||
<li v-for="line in lines" :key="line.id" :class="{ own: line.own }">
|
||||
<span>{{ line.text }}</span><small v-if="view?.unsent.includes(line.id)">待发送</small>
|
||||
</li>
|
||||
</ol>
|
||||
<form class="chat-compose" @submit.prevent="submit">
|
||||
<label>消息<textarea v-model="draft" required rows="3" maxlength="4000"></textarea></label>
|
||||
<button class="primary" :disabled="busy || !draft.trim()">发送</button>
|
||||
</form>
|
||||
</template>
|
||||
</template>
|
||||
<p v-else>在联系人详情打开聊天。</p>
|
||||
</template>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -115,6 +115,7 @@ async function change(action: ContactAction) {
|
||||
<button v-if="detail.state === 'outgoing'" class="plain" :disabled="busy" @click="change('cancel')">取消申请</button>
|
||||
<button v-if="detail.state === 'blocked'" class="plain" :disabled="busy" @click="change('unblock')">解除拉黑</button>
|
||||
<form v-if="detail.state === 'friend'" class="contact-preferences" @submit.prevent="change('preferences')">
|
||||
<RouterLink class="plain" :to="'/chat/' + detail.id">打开加密聊天</RouterLink>
|
||||
<label>备注<input v-model="alias" maxlength="64"></label>
|
||||
<label>分组<input v-model="category" maxlength="32"></label>
|
||||
<button class="plain" :disabled="busy">保存</button>
|
||||
|
||||
@@ -24,6 +24,7 @@ async function act(action: () => Promise<void>) {
|
||||
<main v-if="session.identity" class="workspace">
|
||||
<nav class="rail" aria-label="主导航">
|
||||
<RouterLink class="mark" to="/devices" aria-label="XHChat">X</RouterLink>
|
||||
<RouterLink class="rail-link" to="/chat" title="消息" aria-label="消息">◇</RouterLink>
|
||||
<RouterLink class="rail-link" to="/contacts" title="联系人" aria-label="联系人">人</RouterLink>
|
||||
<RouterLink class="rail-link" to="/devices" title="设备管理" aria-label="设备管理">▣</RouterLink>
|
||||
<button v-if="browser" type="button" class="rail-link browser-button" title="浏览器" aria-label="浏览器" @click="act(browser)">◎</button>
|
||||
@@ -34,6 +35,7 @@ async function act(action: () => Promise<void>) {
|
||||
<div><strong>{{ session.identity.user.username }}</strong><small>我的账号</small></div>
|
||||
</div>
|
||||
<nav class="panel-links" aria-label="工作区">
|
||||
<RouterLink to="/chat">消息</RouterLink>
|
||||
<RouterLink to="/contacts">联系人</RouterLink>
|
||||
<RouterLink to="/devices">设备管理</RouterLink>
|
||||
<button v-if="browser" class="plain mobile-browser" @click="act(browser)">浏览器</button>
|
||||
|
||||
Reference in new issue
Block a user