Merge pull request '自动补充 MLS 一次性密钥包' (#19) from xhgit/mls-key-package-pool into main
Reviewed-on: http://git.xhmcl.com/xhgit/XHChat/pulls/19
This commit was merged in pull request #19.
This commit is contained in:
commit
b1f55df263
8 files changed
+69
-11
No files matched your search
@@ -21,6 +21,7 @@
|
||||
| GET | /api/v1/inbox?after= | 按当前设备和递增游标取最多 64 条封包 |
|
||||
| GET | /api/v1/contacts/{id}/devices | 返回已接受联系人的有效设备与公开身份密钥 |
|
||||
| POST | /api/v1/key-packages | 当前设备发布带设备签名的 MLS KeyPackage,成功返回 204 |
|
||||
| GET | /api/v1/key-packages | 返回当前设备尚可领取的密钥包数量 available |
|
||||
| GET | /api/v1/mls-local-key | 读取当前设备的公开认证密钥,供本机安全码计算 |
|
||||
| POST | /api/v1/mls-credential | 当前设备登记带认证密钥签名的 MLS 签名公钥 |
|
||||
| POST | /api/v1/attachments/{id}?recipient= | 已接受好友设备上传附件密文,使用 application/octet-stream,成功返回 204 |
|
||||
|
||||
@@ -88,3 +88,7 @@ Windows 和 Web 使用 MediaRecorder 录制 Opus,支持取消、计时和最
|
||||
## 加密图片和视频预览
|
||||
|
||||
两端支持在聊天内预览 JPEG、PNG、WebP、GIF、MP4 和 WebM 附件。预览需主动打开,先在本机验证完整性,再使用临时 Blob URL 加载。关闭预览或离开聊天会释放 URL。自动化验收覆盖 Web 发送 PNG 到 Windows 端实际解码和关闭预览。视频预览已构建,仍需独立验证不同编码格式。
|
||||
|
||||
## 一次性密钥包补充
|
||||
|
||||
客户端启用加密聊天时补足四个可领取密钥包。聊天同步期间定时检查,接收新的 Welcome 后立即补充。私钥先落入本机加密记录,公网部分再上传。API 和双端测试验证密钥包领取后的计数变化,以及客户端收到 Welcome 后重新发布。
|
||||
@@ -29,6 +29,16 @@ type KeyPackage struct {
|
||||
var ErrSignature = errors.New("invalid key package device signature")
|
||||
var ErrPackageLimit = errors.New("device key package limit reached")
|
||||
|
||||
func (s *Store) AvailablePackages(ctx context.Context, device string) (int, error) {
|
||||
var available int
|
||||
err := s.db.QueryRow(ctx, `
|
||||
SELECT count(*) FROM device_key_packages k JOIN devices d ON d.id=k.device_id
|
||||
WHERE d.id=$1 AND d.revoked_at IS NULL AND k.claimed_at IS NULL
|
||||
AND k.created_at > now() - interval '24 hours'
|
||||
`, device).Scan(&available)
|
||||
return available, err
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
@@ -53,6 +53,7 @@ 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("GET /api/v1/key-packages", a.authorized(a.packageStatus))
|
||||
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))
|
||||
|
||||
@@ -51,6 +51,18 @@ func (a *API) publishPackage(w http.ResponseWriter, r *http.Request, _ string, i
|
||||
}
|
||||
}
|
||||
|
||||
func (a *API) packageStatus(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
|
||||
if !a.limit(w, r, "package-status:"+identity.Device.ID, 60) {
|
||||
return
|
||||
}
|
||||
available, err := a.delivery.AvailablePackages(r.Context(), identity.Device.ID)
|
||||
if err != nil {
|
||||
unavailable(w, err)
|
||||
return
|
||||
}
|
||||
respond(w, 200, map[string]int{"available": available})
|
||||
}
|
||||
|
||||
func (a *API) claimPackage(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
|
||||
id, device := strings.ToLower(r.PathValue("id")), strings.ToLower(r.PathValue("device"))
|
||||
if !uuidPattern.MatchString(id) || !uuidPattern.MatchString(device) {
|
||||
|
||||
@@ -98,8 +98,11 @@ test('设备密钥包验证签名并只领取一次', { timeout: 25000 }, async
|
||||
const bytes = Buffer.concat([Buffer.from([0, 1, 0, 5]), randomBytes(96)])
|
||||
const binding = Buffer.concat([Buffer.from('XHChat MLS KeyPackage v1\n' + owner.user.id + '\n' + owner.device.id + '\n'), bytes])
|
||||
const packageData = { package: bytes.toString('base64'), signature: sign(null, binding, keys.privateKey).toString('base64') }
|
||||
assert.deepEqual(await json('/key-packages', 'GET', owner.token), { available: 0 })
|
||||
await json('/key-packages', 'POST', owner.token, { ...packageData, signature: randomBytes(64).toString('base64') }, 400)
|
||||
assert.equal((await call('/key-packages', 'POST', owner.token, packageData)).status, 204)
|
||||
assert.deepEqual(await json('/key-packages', 'GET', owner.token), { available: 1 })
|
||||
assert.deepEqual(await json('/key-packages', 'GET', stranger.token), { available: 0 })
|
||||
assert.deepEqual(await json(directory, 'GET', contactUser.token), [])
|
||||
await json(claim, 'POST', contactUser.token, null, 404)
|
||||
await contact(owner, contactUser, 'request')
|
||||
@@ -111,6 +114,7 @@ test('设备密钥包验证签名并只领取一次', { timeout: 25000 }, async
|
||||
const attempts = await Promise.all([call(claim, 'POST', contactUser.token), call(claim, 'POST', contactUser.token)])
|
||||
assert.deepEqual(attempts.map((reply) => reply.status).sort(), [200, 404])
|
||||
assert.deepEqual(await attempts.find((reply) => reply.ok).json(), packageData)
|
||||
assert.deepEqual(await json('/key-packages', 'GET', owner.token), { available: 0 })
|
||||
assert.equal((await call('/key-packages', 'POST', owner.token, packageData)).status, 204)
|
||||
await json(claim, 'POST', contactUser.token, null, 404)
|
||||
assert.equal((await call('/devices/' + owner.device.id, 'DELETE', owner.token)).status, 204)
|
||||
|
||||
@@ -89,6 +89,8 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
|
||||
assert.match(webCode, /^[0-9a-f]{64}$/)
|
||||
assert.match(desktopCode, /^[0-9a-f]{64}$/)
|
||||
assert.notEqual(webCode, desktopCode)
|
||||
const packageRefill = windows.waitForResponse((response) => response.request().method() === 'POST' &&
|
||||
response.url().endsWith('/api/v1/key-packages') && response.status() === 204)
|
||||
await web.getByRole('button', { name: '刷新' }).click()
|
||||
await windows.getByRole('button', { name: '刷新' }).click()
|
||||
await web.getByLabel('对方安全码').fill('0'.repeat(64))
|
||||
@@ -109,6 +111,7 @@ test('Web 与 Windows 安全码校验、加密互发、离线接收和状态恢
|
||||
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()
|
||||
await packageRefill
|
||||
const sentLine = web.getByRole('listitem').filter({ hasText: text })
|
||||
assert.equal(await sentLine.getByText('已读', { exact: true }).count(), 0)
|
||||
assert.equal(await windows.getByLabel('发送已读回执').isChecked(), false)
|
||||
|
||||
+34
-11
@@ -46,6 +46,7 @@ interface ChatState {
|
||||
pinned: Record<string, string>
|
||||
groups: Record<string, string>
|
||||
package?: { lastPublished: number; item: Package }
|
||||
packageChecked?: number
|
||||
rejected: number
|
||||
shareRead?: boolean
|
||||
}
|
||||
@@ -102,17 +103,7 @@ export async function enableChat(identity: ChatIdentity, call: Call) {
|
||||
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)
|
||||
}
|
||||
await replenishPackages(identity, call, state, save, engine)
|
||||
return fingerprint(decode(await localIdentityKey(identity, call)))
|
||||
} finally {
|
||||
engine.free()
|
||||
@@ -120,6 +111,27 @@ export async function enableChat(identity: ChatIdentity, call: Call) {
|
||||
})
|
||||
}
|
||||
|
||||
async function replenishPackages(identity: ChatIdentity, call: Call, state: ChatState, save: (s: ChatState) => Promise<void>, engine: DeviceMls) {
|
||||
// Persist generated private material before sending any public package.
|
||||
if (state.package && state.package.lastPublished === 0) {
|
||||
await call('/key-packages', 'POST', state.package.item)
|
||||
delete state.package
|
||||
await save(state)
|
||||
}
|
||||
const { available } = await call<{ available: number }>('/key-packages')
|
||||
for (let count = available; count < 4; count++) {
|
||||
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)
|
||||
delete state.package
|
||||
await save(state)
|
||||
}
|
||||
state.packageChecked = Date.now()
|
||||
await save(state)
|
||||
}
|
||||
|
||||
async function localIdentityKey(identity: ChatIdentity, call: Call) {
|
||||
const { publicKey } = await call<{ publicKey: string }>('/mls-local-key')
|
||||
const credential = decode(publicKey)
|
||||
@@ -343,6 +355,7 @@ export function synchronize(identity: ChatIdentity, user: string, call: Call) {
|
||||
const wire = decode(item.ciphertext)
|
||||
if (wire[3] === 3) {
|
||||
const group = base64(engine.join(peer.id, key, wire))
|
||||
state.packageChecked = 0
|
||||
const previous = state.groups[peer.id]
|
||||
if (!previous || group < previous) state.groups[peer.id] = group
|
||||
} else {
|
||||
@@ -378,6 +391,16 @@ export function synchronize(identity: ChatIdentity, user: string, call: Call) {
|
||||
} catch (cause) {
|
||||
deliveryError = cause instanceof APIError && cause.status === 404 ? '部分待发消息的设备已不可用' : '部分消息等待重试'
|
||||
}
|
||||
if (Date.now() - (state.packageChecked ?? 0) >= 60_000) {
|
||||
const engine = factory.DeviceMls.restore(decode(state.engine))
|
||||
try {
|
||||
await replenishPackages(identity, call, state, save, engine)
|
||||
} catch {
|
||||
deliveryError ||= '密钥包补充失败,将自动重试'
|
||||
} finally {
|
||||
engine.free()
|
||||
}
|
||||
}
|
||||
return { lines: state.lines, pinned: state.pinned, peers, rejected: state.rejected, deliveryError, shareRead: state.shareRead === true,
|
||||
unsent: state.outbox.map((item) => item.mutationTarget ?? item.messageId) }
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user