实现 MLS 设备封包投递与离线同步 #3

Merged
xhgit merged 1 commits from xhgit/mls-direct-messages into main 2026-11-13 18:22:10 +08:00
15 changed files with 366 additions and 16 deletions

No files matched your search

+1
View File
@@ -2,4 +2,5 @@
XHCHAT_DB_PASSWORD=
XHCHAT_PORT=8080
XHCHAT_WEB_ORIGIN=http://127.0.0.1:8080
XHCHAT_ENVELOPE_RETENTION=720h
# XHCHAT_GOPROXY=https://proxy.golang.org,direct
+6
View File
@@ -11,6 +11,12 @@ server {
access_log off;
client_max_body_size 8k;
location = /api/v1/inbox {
client_max_body_size 96k;
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 Referrer-Policy no-referrer always;
add_header X-Content-Type-Options nosniff always;
+1
View File
@@ -30,6 +30,7 @@ services:
XHCHAT_ADDR: 0.0.0.0:8080
DATABASE_URL: postgres://xhchat:${XHCHAT_DB_PASSWORD}@postgres:5432/xhchat?sslmode=disable
REDIS_URL: redis://redis:6379/0
XHCHAT_ENVELOPE_RETENTION: ${XHCHAT_ENVELOPE_RETENTION:-720h}
XHCHAT_ORIGINS: ${XHCHAT_WEB_ORIGIN:-http://127.0.0.1:8080},xhchat://app
depends_on:
postgres:
+5 -1
View File
@@ -17,9 +17,13 @@
| GET | /api/v1/contacts | 返回好友、来往申请和当前账号的黑名单 |
| GET | /api/v1/contacts/search?username= | 按完整用户名查找,返回可见的联系人状态 |
| POST | /api/v1/contacts/{id} | 请求体包含 action,可选 alias 和 category,成功返回 204 |
| POST | /api/v1/inbox | 接收 messageId、recipientDevice 和 Base64 编码的 MLS 封包,返回字符串 sequence |
| GET | /api/v1/inbox?after= | 按当前设备和递增游标取最多 64 条封包 |
用户名为 3–32 位 ASCII 字母、数字或下划线,忽略大小写。密码最少 12 个 Unicode 字符,最多 256 字节。platform 为 web 或 windows。公钥、签名和 challenge 使用无填充 Base64URL。设备使用 Ed25519 签名 UTF-8 字符串 `XHChat device authentication v1\n` 后紧接 challenge。该签名仅用于证明基础设备密钥持有权。
联系人操作包含 request、accept、reject、cancel、delete、block、unblock 和 preferences。变更后 WebSocket 发送 contacts_changed,客户端重新获取授权后的列表。
下一阶段接口为 /conversations、/conversations/{id}/envelopes、/sync、/attachments、/key-packages。消息接口接受版本化协议密文、目标会话和幂等 ID。WebSocket 发出同步提示,客户端按持久游标补拉。后续加入 /groups、/calls、/posts、/backups、/push 与独立的管理接口。
设备投递当前要求双方是已接受的联系人,且两个设备均未撤销。接口校验 MLS 1.0 PrivateMessage 和 Welcome 的外层类型与长度,客户端负责完整协议验证。相同发送设备、接收设备、消息 ID 和封包的重试返回原游标,内容不同返回 409。WebSocket 的 inbox_changed 仅提示当前设备补拉。投递保留期由 XHCHAT_ENVELOPE_RETENTION 配置,默认 720 小时。
下一阶段将增加 /conversations、/attachments 和 /key-packages。后续加入 /groups、/calls、/posts、/backups、/push 与独立的管理接口。
+2 -2
View File
@@ -8,10 +8,10 @@
| contact_relationships、contact_blocks、contact_preferences | 关系按账号对去重,拉黑有方向,私有备注按拥有者授权 |
| conversations、memberships | 会话与成员关系,记录角色和生效世代 |
| device_credentials、key_packages | 公开凭据及一次性密钥包,事务领取,撤销后停止发放 |
| envelopes、deliveries | 二进制协议密文、投递游标和目标设备,按客户端消息 ID 幂等 |
| device_envelopes | 二进制协议封包、投递游标和目标设备,按发送设备、接收设备和客户端消息 ID 幂等 |
| attachments、backups | 对象存储标识、密文尺寸、配额和版本,密钥由端侧传递 |
| calls、call_participants | 通话状态、参与设备和时间,不存媒体 |
| posts、post_audiences、reactions | 私人动态正文为密文,受众变更触发重新分发或换钥 |
| admin_audit | 管理员、行为、目标标识、时间和结果 |
迁移 001 创建身份相关表。迁移 002 添加联系人关系、黑名单和备注。设备撤销和会话清除在同一个事务内处理。阶段二以事务分配单调投递游标,连接恢复后从持久层补拉。消息保留和附件清理分别由后台作业处理,下载授权按目标设备和对象关联重新检查。
迁移 001 创建身份相关表。迁移 002 添加联系人关系、黑名单和备注。迁移 003 添加设备封包队列。投递事务按固定顺序锁定账号和设备,使同一目标设备的游标按提交顺序可见。设备撤销和会话清除在同一个事务内处理。后台作业清理超出保留期的封包。后续的附件下载将按目标设备和对象关联重新检查授权。
+4
View File
@@ -32,3 +32,7 @@ Web 和 Electron 共用 Vue 客户端,独立接入同一 Go API。真实 Postg
## OpenMLS 兼容性
锁定 OpenMLS 0.9.2。Linux 原生 Rust 与 Windows Chrome WebAssembly 用例验证三台设备加入、消息加解密、重放拒绝和成员移除后新世代保密。应用消息接口、端侧持久化、可信设备绑定及 Electron 中的聊天互通仍待实现。
## 设备密文投递
服务端已实现联系人设备之间的 MLS 封包队列、幂等提交、离线游标补拉、实时同步提示和保留期。集成测试覆盖跨账号收件箱隔离、设备撤销及非封包请求拒绝。客户端会话与可操作的聊天界面尚待接入。
+6 -1
View File
@@ -16,6 +16,7 @@ import (
"xhchat/server/internal/config"
"xhchat/server/internal/contacts"
"xhchat/server/internal/database"
"xhchat/server/internal/delivery"
"xhchat/server/internal/httpapi"
"github.com/jackc/pgx/v5/pgxpool"
@@ -63,6 +64,7 @@ func run() error {
}
cancel()
accounts := account.New(db, cfg.SessionTTL)
envelopes := delivery.New(db)
go func() {
ticker := time.NewTicker(15 * time.Minute)
defer ticker.Stop()
@@ -75,12 +77,15 @@ func run() error {
if err := accounts.Cleanup(cleanup); err != nil {
slog.Warn("session cleanup failed")
}
if err := envelopes.Cleanup(cleanup, cfg.EnvelopeRetention); err != nil {
slog.Warn("delivery cleanup failed")
}
cancel()
}
}
}()
server := &http.Server{
Addr: cfg.Addr, Handler: httpapi.New(accounts, contacts.New(db), cache, cfg.Origins, ready),
Addr: cfg.Addr, Handler: httpapi.New(accounts, contacts.New(db), envelopes, cache, cfg.Origins, ready),
ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second,
WriteTimeout: 15 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10,
BaseContext: func(net.Listener) context.Context { return ctx },
+14 -5
View File
@@ -11,19 +11,28 @@ type Config struct {
Addr, DatabaseURL, RedisURL string
Origins map[string]bool
SessionTTL time.Duration
EnvelopeRetention time.Duration
}
func Load() (Config, error) {
c := Config{
Addr: os.Getenv("XHCHAT_ADDR"),
DatabaseURL: os.Getenv("DATABASE_URL"),
RedisURL: os.Getenv("REDIS_URL"),
Origins: make(map[string]bool),
SessionTTL: 12 * time.Hour,
Addr: os.Getenv("XHCHAT_ADDR"),
DatabaseURL: os.Getenv("DATABASE_URL"),
RedisURL: os.Getenv("REDIS_URL"),
Origins: make(map[string]bool),
SessionTTL: 12 * time.Hour,
EnvelopeRetention: 30 * 24 * time.Hour,
}
if c.Addr == "" {
c.Addr = "127.0.0.1:8080"
}
if raw := os.Getenv("XHCHAT_ENVELOPE_RETENTION"); raw != "" {
retention, err := time.ParseDuration(raw)
if err != nil || retention < time.Hour || retention > 365*24*time.Hour {
return Config{}, errors.New("XHCHAT_ENVELOPE_RETENTION must be between 1h and 8760h")
}
c.EnvelopeRetention = retention
}
for _, origin := range strings.Split(os.Getenv("XHCHAT_ORIGINS"), ",") {
if origin = strings.TrimSpace(origin); origin != "" {
c.Origins[origin] = true
+13
View File
@@ -0,0 +1,13 @@
CREATE TABLE device_envelopes (
sequence bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
message_id uuid NOT NULL,
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 65536),
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (sender_device, recipient_device, message_id),
CHECK (sender_device <> recipient_device)
);
CREATE INDEX device_envelopes_inbox ON device_envelopes(recipient_device, sequence);
CREATE INDEX device_envelopes_expiry ON device_envelopes(created_at);
+4 -1
View File
@@ -13,6 +13,9 @@ var identityMigration string
//go:embed 002_contacts.sql
var contactsMigration string
//go:embed 003_delivery.sql
var deliveryMigration string
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
tx, err := pool.Begin(ctx)
if err != nil {
@@ -25,7 +28,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} {
for index, migration := range []string{identityMigration, contactsMigration, deliveryMigration} {
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 {
+131
View File
@@ -0,0 +1,131 @@
package delivery
import (
"bytes"
"context"
"errors"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
var (
ErrUnavailable = errors.New("delivery unavailable")
ErrConflict = errors.New("message identifier already used for different bytes")
)
type Envelope struct {
Sequence string `json:"sequence"`
MessageID string `json:"messageId"`
SenderDevice string `json:"senderDevice"`
Ciphertext []byte `json:"ciphertext"`
CreatedAt time.Time `json:"createdAt"`
}
type Store struct{ db *pgxpool.Pool }
func New(db *pgxpool.Pool) *Store { return &Store{db: db} }
func (s *Store) Send(ctx context.Context, sender, recipient, message string, ciphertext []byte) (string, error) {
tx, err := s.db.Begin(ctx)
if err != nil {
return "", err
}
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 {
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 EXISTS (SELECT 1 FROM contact_relationships
WHERE first_user=LEAST($1::uuid,$2::uuid) AND second_user=GREATEST($1::uuid,$2::uuid)
AND status='accepted')
`, 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)
VALUES ($1,$2,$3,$4)
ON CONFLICT (sender_device, recipient_device, message_id) DO NOTHING
RETURNING sequence::text
`, message, sender, recipient, ciphertext).Scan(&seq)
if errors.Is(err, pgx.ErrNoRows) {
var previous []byte
err = tx.QueryRow(ctx, `
SELECT sequence::text,ciphertext FROM device_envelopes
WHERE message_id=$1 AND sender_device=$2 AND recipient_device=$3
`, message, sender, recipient).Scan(&seq, &previous)
if err == nil && !bytes.Equal(previous, ciphertext) {
return "", ErrConflict
}
}
if err != nil {
return "", err
}
return seq, tx.Commit(ctx)
}
func (s *Store) Inbox(ctx context.Context, recipient string, after int64) ([]Envelope, error) {
rows, err := s.db.Query(ctx, `
SELECT e.sequence::text,e.message_id,e.sender_device,e.ciphertext,e.created_at
FROM device_envelopes e JOIN devices d ON e.recipient_device=d.id
WHERE d.id=$1 AND d.revoked_at IS NULL AND e.sequence>$2
ORDER BY e.sequence LIMIT 64
`, recipient, after)
if err != nil {
return nil, err
}
defer rows.Close()
envelopes := make([]Envelope, 0)
for rows.Next() {
var envelope Envelope
if err := rows.Scan(&envelope.Sequence, &envelope.MessageID, &envelope.SenderDevice,
&envelope.Ciphertext, &envelope.CreatedAt); err != nil {
return nil, err
}
envelopes = append(envelopes, envelope)
}
return envelopes, rows.Err()
}
func (s *Store) Cleanup(ctx context.Context, retention time.Duration) error {
_, err := s.db.Exec(ctx, "DELETE FROM device_envelopes WHERE created_at < $1", time.Now().Add(-retention))
return err
}
+11 -3
View File
@@ -15,6 +15,7 @@ import (
"xhchat/server/internal/account"
"xhchat/server/internal/contacts"
"xhchat/server/internal/delivery"
"github.com/jackc/pgx/v5"
"github.com/redis/go-redis/v9"
@@ -23,14 +24,15 @@ import (
type API struct {
accounts *account.Store
contacts *contacts.Store
delivery *delivery.Store
redis *redis.Client
origins map[string]bool
hashSlots chan struct{}
ready func(context.Context) error
}
func New(accounts *account.Store, contactStore *contacts.Store, cache *redis.Client, origins map[string]bool, ready func(context.Context) error) http.Handler {
a := &API{accounts: accounts, contacts: contactStore, redis: cache, origins: origins, hashSlots: make(chan struct{}, 4), ready: ready}
func New(accounts *account.Store, contactStore *contacts.Store, envelopeStore *delivery.Store, cache *redis.Client, origins map[string]bool, ready func(context.Context) error) http.Handler {
a := &API{accounts: accounts, contacts: contactStore, delivery: envelopeStore, redis: cache, origins: origins, hashSlots: make(chan struct{}, 4), ready: ready}
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { respond(w, 200, map[string]string{"status": "ok"}) })
mux.HandleFunc("GET /readyz", a.readiness)
@@ -46,6 +48,8 @@ func New(accounts *account.Store, contactStore *contacts.Store, cache *redis.Cli
mux.HandleFunc("GET /api/v1/contacts", a.authorized(a.listContacts))
mux.HandleFunc("GET /api/v1/contacts/search", a.authorized(a.searchContact))
mux.HandleFunc("POST /api/v1/contacts/{id}", a.authorized(a.changeContact))
mux.HandleFunc("GET /api/v1/inbox", a.authorized(a.inbox))
mux.HandleFunc("POST /api/v1/inbox", a.authorized(a.sendEnvelope))
return a.boundary(mux)
}
@@ -236,7 +240,11 @@ func (a *API) limit(w http.ResponseWriter, r *http.Request, key string, max int)
}
func parse(w http.ResponseWriter, r *http.Request, value any) bool {
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096))
return parseLimit(w, r, value, 4096)
}
func parseLimit(w http.ResponseWriter, r *http.Request, value any, maximum int64) bool {
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maximum))
decoder.DisallowUnknownFields()
if err := decoder.Decode(value); err != nil || decoder.Decode(new(any)) != io.EOF {
problem(w, 400, "invalid_json", "请求格式错误")
+70
View File
@@ -0,0 +1,70 @@
package httpapi
import (
"errors"
"net/http"
"strconv"
"strings"
"xhchat/server/internal/account"
"xhchat/server/internal/delivery"
)
func (a *API) sendEnvelope(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
var input struct {
MessageID string `json:"messageId"`
RecipientDevice string `json:"recipientDevice"`
Ciphertext []byte `json:"ciphertext"`
}
if !parseLimit(w, r, &input, 96<<10) {
return
}
if !uuidPattern.MatchString(input.MessageID) || !uuidPattern.MatchString(input.RecipientDevice) || !mlsFrame(input.Ciphertext) {
problem(w, 400, "invalid_envelope", "请输入有效的 MLS 密文封包")
return
}
if !a.limit(w, r, "envelope-send:"+identity.Device.ID, 180) {
return
}
recipient := strings.ToLower(input.RecipientDevice)
seq, err := a.delivery.Send(r.Context(), identity.Device.ID, recipient, input.MessageID, input.Ciphertext)
switch {
case errors.Is(err, delivery.ErrUnavailable):
problem(w, 404, "delivery_unavailable", "无法向指定设备投递")
case errors.Is(err, delivery.ErrConflict):
problem(w, 409, "message_id_conflict", "消息 ID 已关联其他密文")
case err != nil:
unavailable(w, err)
default:
_ = a.redis.Publish(r.Context(), "xhchat:inbox:"+recipient, "changed").Err()
respond(w, 200, map[string]string{"sequence": seq})
}
}
func mlsFrame(wire []byte) bool {
// RFC 9420 MLSMessage header. The delivery service routes PrivateMessage and
// Welcome. Recipients validate the complete message and authenticate its contents.
return len(wire) >= 16 && len(wire) <= 65536 && wire[0] == 0 && wire[1] == 1 &&
wire[2] == 0 && (wire[3] == 2 || wire[3] == 3)
}
func (a *API) inbox(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
var after int64
if raw := r.URL.Query().Get("after"); raw != "" {
var err error
after, err = strconv.ParseInt(raw, 10, 64)
if err != nil || after < 0 {
problem(w, 400, "invalid_cursor", "无效的投递游标")
return
}
}
if !a.limit(w, r, "inbox:"+identity.Device.ID, 180) {
return
}
items, err := a.delivery.Inbox(r.Context(), identity.Device.ID, after)
if err != nil {
unavailable(w, err)
return
}
respond(w, 200, items)
}
+8 -3
View File
@@ -63,7 +63,8 @@ func (a *API) realtime(w http.ResponseWriter, r *http.Request) {
unavailable(w, err)
return
}
subscription := a.redis.Subscribe(r.Context(), "xhchat:contacts:"+identity.User.ID)
inboxChannel := "xhchat:inbox:" + identity.Device.ID
subscription := a.redis.Subscribe(r.Context(), "xhchat:contacts:"+identity.User.ID, inboxChannel)
defer subscription.Close()
if _, err = subscription.Receive(r.Context()); err != nil {
unavailable(w, err)
@@ -94,12 +95,16 @@ func (a *API) realtime(w http.ResponseWriter, r *http.Request) {
select {
case <-ctx.Done():
return
case _, ok := <-changes:
case change, ok := <-changes:
if !ok {
return
}
writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
err := wsjson.Write(writeCtx, conn, map[string]string{"type": "contacts_changed"})
event := "contacts_changed"
if change.Channel == inboxChannel {
event = "inbox_changed"
}
err := wsjson.Write(writeCtx, conn, map[string]string{"type": event})
cancel()
if err != nil {
return
+90
View File
@@ -0,0 +1,90 @@
import assert from 'node:assert/strict'
import { generateKeyPairSync, randomBytes, randomUUID, sign } from 'node:crypto'
import { once } from 'node:events'
import test from 'node:test'
import { WebSocket } from 'ws'
const base = process.env.XHCHAT_TEST_URL ?? 'http://127.0.0.1:8080'
function call(path, method = 'GET', token, body) {
return fetch(base + '/api/v1' + path, {
method,
headers: {
...(token && { Authorization: 'Bearer ' + token }),
...(body && { 'Content-Type': 'application/json' }),
},
body: body && JSON.stringify(body),
signal: AbortSignal.timeout(10_000),
})
}
async function json(path, method, token, body, status = 200) {
const response = await call(path, method, token, body)
assert.equal(response.status, status, await response.clone().text())
return response.json()
}
async function register() {
const { challenge } = await json('/auth/challenge', 'POST')
const { publicKey, privateKey } = generateKeyPairSync('ed25519')
return json('/auth/register', 'POST', null, {
username: 'qa_' + randomBytes(6).toString('hex'),
password: randomBytes(24).toString('hex'),
deviceName: '投递验收设备',
platform: 'web',
challenge,
publicKey: publicKey.export({ format: 'jwk' }).x,
signature: sign(null, Buffer.from('XHChat device authentication v1\n' + challenge), privateKey).toString('base64url'),
}, 201)
}
async function contact(actor, target, action) {
const reply = await call('/contacts/' + target.user.id, 'POST', actor.token, { action })
assert.equal(reply.status, 204, await reply.text())
}
// Opaque fixture with the MLS header. Crypto interoperability is tested separately in crypto/.
function frame() {
return Buffer.concat([Buffer.from([0, 1, 0, 2]), randomBytes(96)]).toString('base64')
}
test('设备密文投递、幂等、离线补拉、实时提示和撤销', { timeout: 25000 }, async () => {
const sender = await register()
const recipient = await register()
const other = await register()
const payload = { messageId: randomUUID(), recipientDevice: recipient.device.id, ciphertext: frame() }
await json('/inbox', 'POST', sender.token, payload, 404)
await contact(sender, recipient, 'request')
await contact(recipient, sender, 'accept')
await json('/inbox', 'POST', sender.token, { ...payload, ciphertext: Buffer.from('plaintext').toString('base64') }, 400)
await json('/inbox', 'POST', sender.token, { ...payload, text: 'plaintext' }, 400)
const first = await json('/inbox', 'POST', sender.token, payload)
assert.deepEqual(await json('/inbox', 'POST', sender.token, payload), first)
await json('/inbox', 'POST', sender.token, { ...payload, ciphertext: frame() }, 409)
const [item] = await json('/inbox', 'GET', recipient.token)
assert.equal(item.sequence, first.sequence)
assert.equal(item.ciphertext, payload.ciphertext)
assert.equal(item.senderDevice, sender.device.id)
assert.deepEqual(await json('/inbox?after=' + first.sequence, 'GET', recipient.token), [])
assert.deepEqual(await json('/inbox', 'GET', sender.token), [])
assert.deepEqual(await json('/inbox', 'GET', other.token), [])
const { ticket } = await json('/realtime/ticket', 'POST', recipient.token)
const ws = new WebSocket(base.replace(/^http/, 'ws') + '/api/v1/realtime', ['xhchat.v1', 'ticket.' + ticket], { origin: base })
try {
assert.equal(JSON.parse((await once(ws, 'message'))[0]).type, 'ready')
const changed = once(ws, 'message')
const second = { ...payload, messageId: randomUUID(), ciphertext: frame() }
await json('/inbox', 'POST', sender.token, second)
assert.equal(JSON.parse((await changed)[0]).type, 'inbox_changed')
const pending = await json('/inbox?after=' + first.sequence, 'GET', recipient.token)
assert.equal(pending.length, 1)
assert.equal(pending[0].ciphertext, second.ciphertext)
assert.equal((await call('/devices/' + recipient.device.id, 'DELETE', recipient.token)).status, 204)
await json('/inbox', 'GET', recipient.token, undefined, 401)
await json('/inbox', 'POST', sender.token, { ...payload, messageId: randomUUID() }, 404)
} finally {
ws.terminate()
}
})