增加加密群公告和群主转让 #36
No files matched your search
@@ -19,7 +19,7 @@
|
||||
| 账号与设备 | Windows 和 Web 共用账号,支持用户名注册、登录、查看设备和远程撤销。 |
|
||||
| 联系人 | 按用户名查找、处理好友申请、管理备注与分组,以及拉黑。变更可在双端实时同步。 |
|
||||
| 加密文字聊天 | 在两个已核验设备之间发送 MLS 加密消息,支持离线接收。 |
|
||||
| 加密群聊 | 创建群组、邀请联系人和管理成员。群列表显示本机未读,并按账号同步置顶和免打扰。每个账号选一台已核验设备参与 MLS 加密文字聊天。 |
|
||||
| 加密群聊 | 创建群组、邀请联系人、管理成员和转让群主。群主可发布加密公告。群列表显示本机未读,并按账号同步置顶和免打扰。 |
|
||||
| 加密附件 | 两端可在私聊和群聊发送、下载最多 8 MiB 的文件,并在本机预览图片和视频。群聊提供文件、图片和视频的分类视图。 |
|
||||
| 加密语音 | 两端可在私聊和群聊录制、取消或发送最长 60 秒的语音消息,接收方在本机解密播放。 |
|
||||
| 消息管理 | 私聊和群聊支持引用回复、编辑文字、撤回、本机搜索和收藏。消息可转发到已建立加密会话的群或已核验的联系人设备。私聊支持可选加密已读回执。 |
|
||||
@@ -55,7 +55,7 @@ npm.cmd run desktop
|
||||
|
||||
体验加密文字聊天时,注册两个账号并互加好友。在双方的联系人详情中打开「加密聊天」,启用本机加密,通过另一可信渠道交换安全码,分别核验对方设备后即可互发消息。
|
||||
|
||||
体验群聊时,在「群组」中邀请联系人。成员接受邀请后启用本机群聊,通过可信渠道核验群内设备。群主选好设备后点击「建立群加密会话」。成员加入、离开或已选设备被撤销时,群主需要重新建立加密会话。
|
||||
体验群聊时,在「群组」中邀请联系人。成员接受邀请后启用本机群聊,通过可信渠道为每个账号核验一台参与设备。群主选好设备后点击「建立群加密会话」。成员加入、离开、群主转让或已选设备被撤销时,由当时的群主重新建立加密会话。
|
||||
|
||||
## 开发文档
|
||||
|
||||
|
||||
+3
-1
@@ -27,7 +27,7 @@
|
||||
| POST | /api/v1/attachments/{id}?recipient= | 已接受好友设备上传附件密文,使用 application/octet-stream,成功返回 204 |
|
||||
| GET | /api/v1/attachments/{id} | 原发送或接收设备获取附件密文 |
|
||||
| GET / POST | /api/v1/groups | 列出当前账号所属群组与邀请,或创建群组 |
|
||||
| GET / POST | /api/v1/groups/{id} | 查看群组详情或执行邀请、接受、拒绝、改名、升降管理员、移除、退出或解散 |
|
||||
| GET / POST | /api/v1/groups/{id} | 查看群组详情或执行邀请、接受、拒绝、改名、升降管理员、转让群主、移除、退出或解散 |
|
||||
| POST | /api/v1/groups/{id}/preferences | 更新当前账号的 `pinned` 和 `muted`,可只传其中一项 |
|
||||
| POST | /api/v1/groups/{id}/seen | 提交当前设备已同步的消息游标 `sequence`,成功返回 204 |
|
||||
| GET | /api/v1/groups/{id}/devices | 获取群成员的有效设备与 MLS 公钥 |
|
||||
@@ -52,6 +52,8 @@ MLS 凭据由标准 Base64 的 publicKey 和 signature 组成,使用 UTF-8 前
|
||||
|
||||
群组详情包含十进制字符串 membershipVersion。已接受成员变化会递增版本,待处理邀请和角色变化保留版本。active 成员可以查看其他有效成员,群主与管理员还可查看待处理邀请。群主可解散、调整管理员和移除成员。管理员可改名、邀请好友和移除普通成员。
|
||||
|
||||
群主可使用 `transfer` 和有效成员的 `target` 转让群主。转让会将原群主设为普通成员,更新群版本,由新群主创建后续 MLS 会话。公告使用现有 MLS 密文投递接口,客户端验证公告来自该会话经核验的群主设备。
|
||||
|
||||
创建或更新群资料和成员后,受影响账号的在线客户端收到 `{"type":"group_list_changed"}`,再用授权 API 刷新。邀请相关提示发送给管理者和被邀请人。提示只包含类型字段,不传群号、群名或成员资料。
|
||||
|
||||
群组密文投递使用 `/groups/{id}/epochs` 和 `/groups/{id}/messages`。群主发布带 membershipVersion 的世代,选取每个有效成员的一台已登记 MLS 设备,提交其他设备的 Welcome。GET epochs 返回当前有效世代的设备名单和本设备获准接收的 Welcome,旧世代仅向在本次成员资格期间加入过该世代的设备返回。POST messages 接受当前世代的 MLS PrivateMessage,GET messages 通过 after 游标返回本设备有权读取的密文。
|
||||
|
||||
@@ -174,3 +174,9 @@ Windows Electron 和 Edge 验证了群组页在兜底轮询前显示邀请、成
|
||||
Windows 和 Web 的群列表按当前设备显示未读投递数量,免打扰群使用低强调角标。打开可见的群聊并同步后,客户端提交本机游标。统计排除本机发送的消息,页面后台时保留角标。游标由服务端按设备保存,其他成员看不到逐条已读状态。编辑和撤回也是群密文投递,会计入尚未同步的数量。
|
||||
|
||||
接口测试覆盖发送设备排除、游标单调递增、越权及重新入群隔离。Windows Electron 与 Edge 验证免打扰时显示未读、启用群安全会话后同步并清除角标,以及群消息和私聊附件回归。私聊文件选择在同步繁忙时也会排队提交。
|
||||
|
||||
## 群公告和群主转让
|
||||
|
||||
群主可用当前群会话设备发布、编辑和清除公告,公告正文通过 MLS 群密文传递。已经同步的公告保存在本机,新加入的设备从其加入后的会话获取公告,群主可以重新发布。群主可以把管理权转让给已接受邀请的成员,原群主成为普通成员,可以主动退出。转让更新群版本,新群主建立新会话前旧会话停止发送。
|
||||
|
||||
Windows 和 Edge 验证加密发布与清除公告、群主转让、原群主退出和新群主建立会话。服务端测试覆盖普通成员、管理员、外部账号、受邀未入群成员及向自己转让的拒绝路径。
|
||||
@@ -273,6 +273,24 @@ func changeActive(ctx context.Context, tx pgx.Tx, user, id, owner, role string,
|
||||
return false, ErrAction
|
||||
}
|
||||
return false, invite(ctx, tx, user, id, change.Target)
|
||||
case "transfer":
|
||||
if role != "owner" || change.Target == owner {
|
||||
return false, ErrAction
|
||||
}
|
||||
tag, err := tx.Exec(ctx, `
|
||||
UPDATE chat_groups SET owner_id=$2 WHERE id=$1 AND EXISTS (
|
||||
SELECT 1 FROM group_members WHERE group_id=$1 AND user_id=$2 AND state='active'
|
||||
)
|
||||
`, id, change.Target)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return false, ErrAction
|
||||
}
|
||||
_, err = tx.Exec(ctx, "UPDATE group_members SET role='member' WHERE group_id=$1 AND user_id IN ($2,$3)", id, owner, change.Target)
|
||||
// The new owner establishes a new authenticated MLS session for the same roster.
|
||||
return true, err
|
||||
case "remove", "promote", "demote":
|
||||
if !manage || change.Target == owner || change.Target == user {
|
||||
return false, ErrAction
|
||||
|
||||
@@ -92,7 +92,7 @@ func (a *API) changeGroup(w http.ResponseWriter, r *http.Request, _ string, id a
|
||||
return
|
||||
}
|
||||
switch change.Action {
|
||||
case "invite", "remove", "promote", "demote":
|
||||
case "invite", "remove", "promote", "demote", "transfer":
|
||||
if !uuidPattern.MatchString(change.Target) {
|
||||
problem(w, 400, "invalid_member", "群成员 ID 无效")
|
||||
return
|
||||
|
||||
+13
-1
@@ -108,6 +108,7 @@ test('群组邀请、授权、成员移除、版本变更与实时提示', { tim
|
||||
})
|
||||
assert.equal(active.membershipVersion, '2')
|
||||
assert.deepEqual(active.members.map((item) => item.role).sort(), ['member', 'owner'])
|
||||
await act(member, 'transfer', owner.user.id, 409)
|
||||
await act(member, 'remove', owner.user.id, 409)
|
||||
await act(member, 'rename', undefined, 409, '未授权名称')
|
||||
const candidate = await register()
|
||||
@@ -130,12 +131,23 @@ test('群组邀请、授权、成员移除、版本变更与实时提示', { tim
|
||||
const renamed = await json(path, 'GET', owner.token)
|
||||
assert.equal(renamed.name, '管理员改名')
|
||||
assert.equal(renamed.membershipVersion, '2')
|
||||
await act(member, 'transfer', owner.user.id, 409)
|
||||
await act(owner, 'transfer', other.user.id, 409)
|
||||
await act(owner, 'transfer', owner.user.id, 409)
|
||||
await expectHint([ownerSocket, memberSocket], () => act(owner, 'transfer', member.user.id))
|
||||
assert.equal((await json(path, 'GET', owner.token)).role, 'member')
|
||||
const newOwner = await json(path, 'GET', member.token)
|
||||
assert.equal(newOwner.role, 'owner')
|
||||
assert.equal(newOwner.membershipVersion, '3')
|
||||
await act(owner, 'disband', undefined, 409)
|
||||
await expectHint([ownerSocket, memberSocket], () => act(member, 'transfer', owner.user.id))
|
||||
await act(member, 'disband', undefined, 409)
|
||||
await expectHint([ownerSocket, memberSocket], () => act(owner, 'remove', member.user.id))
|
||||
await json(path, 'GET', member.token, undefined, 404)
|
||||
assert.deepEqual(await json('/groups', 'GET', member.token), [])
|
||||
assert.equal((await json(path, 'GET', owner.token)).membershipVersion, '3')
|
||||
assert.equal((await json(path, 'GET', owner.token)).membershipVersion, '5')
|
||||
await expectHint([ownerSocket, memberSocket], () => act(owner, 'invite', member.user.id))
|
||||
await act(owner, 'transfer', member.user.id, 409)
|
||||
await expectHint([ownerSocket, memberSocket], () => act(owner, 'disband'))
|
||||
await json(path, 'GET', owner.token, undefined, 404)
|
||||
assert.deepEqual(await json('/groups', 'GET', member.token), [])
|
||||
|
||||
@@ -210,6 +210,21 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
|
||||
await unreadGroup.waitFor({ state: 'detached', timeout: 4500 })
|
||||
assert.equal(await windows.getByRole('link', { name: new RegExp(group + '.*未读') }).count(), 0)
|
||||
|
||||
const announcement = '群公告 ' + id()
|
||||
const ownerAnnouncement = chat(owner).getByRole('region', { name: '群公告' })
|
||||
await ownerAnnouncement.getByRole('button', { name: '写群公告' }).click()
|
||||
await ownerAnnouncement.getByLabel('公告内容').fill(announcement)
|
||||
const announcementPost = owner.waitForRequest((request) => /\/groups\/[^/]+\/messages$/.test(request.url()) && request.method() === 'POST')
|
||||
await ownerAnnouncement.getByRole('button', { name: '发布公告' }).click()
|
||||
assert.ok(!Buffer.from((await announcementPost).postDataJSON().wire, 'base64').includes(Buffer.from(announcement)))
|
||||
const windowsAnnouncement = chat(windows).getByRole('region', { name: '群公告' })
|
||||
await windowsAnnouncement.getByText(announcement, { exact: true }).waitFor()
|
||||
assert.equal(await windowsAnnouncement.getByRole('button').count(), 0)
|
||||
await ownerAnnouncement.getByRole('button', { name: '编辑群公告' }).click()
|
||||
await ownerAnnouncement.getByLabel('公告内容').clear()
|
||||
await ownerAnnouncement.getByRole('button', { name: '清除公告' }).click()
|
||||
await windowsAnnouncement.waitFor({ state: 'detached' })
|
||||
|
||||
const original = chat(owner).getByRole('listitem').filter({ hasText: first })
|
||||
assert.equal(await original.getByRole('button', { name: '编辑', exact: true }).count(), 0)
|
||||
assert.equal(await original.getByRole('button', { name: '撤回', exact: true }).count(), 0)
|
||||
@@ -524,6 +539,25 @@ test('Windows 与 Web 加密群聊支持消息操作、附件、语音和成员
|
||||
await chat(owner).getByRole('button', { name: '下载 ' + privateFile, exact: true }).click()
|
||||
assert.notDeepEqual(await (await groupFileResponse).body(), originalBytes)
|
||||
assert.deepEqual(await readFile(await (await groupDownload).path()), contents)
|
||||
|
||||
await work(windows).getByRole('link', { name: '群组' }).click()
|
||||
await windows.getByRole('link', { name: new RegExp(targetGroup) }).click()
|
||||
const successor = owner.getByRole('list', { name: '群成员' }).getByRole('listitem').filter({ hasText: names[1] })
|
||||
await successor.getByRole('button', { name: '转让群主', exact: true }).click()
|
||||
await owner.getByRole('button', { name: '确认操作', exact: true }).click()
|
||||
await windows.getByRole('list', { name: '群成员' }).getByText(names[1] + ' · 群主', { exact: true }).waitFor()
|
||||
await owner.getByRole('button', { name: '退出群组', exact: true }).waitFor()
|
||||
await owner.getByRole('button', { name: '退出群组', exact: true }).click()
|
||||
await owner.getByRole('button', { name: '确认操作', exact: true }).click()
|
||||
await owner.getByRole('heading', { name: targetGroup }).waitFor({ state: 'detached' })
|
||||
await windows.getByRole('list', { name: '群成员' }).getByText(names[0] + ' · 成员', { exact: true }).waitFor({ state: 'detached' })
|
||||
await chat(windows).getByRole('button', { name: '启用本机群聊' }).click()
|
||||
await publish(windows, [windows])
|
||||
const successorAnnouncement = chat(windows).getByRole('region', { name: '群公告' })
|
||||
await successorAnnouncement.getByRole('button', { name: '写群公告' }).click()
|
||||
await successorAnnouncement.getByLabel('公告内容').fill('新群主公告')
|
||||
await successorAnnouncement.getByRole('button', { name: '发布公告' }).click()
|
||||
await successorAnnouncement.getByText('新群主公告', { exact: true }).waitFor()
|
||||
} catch (error) {
|
||||
const status = await Promise.all(pages.map((page) => page.locator('[role=alert], .group-chat [role=status]').allTextContents()))
|
||||
throw new Error(JSON.stringify(status), { cause: error })
|
||||
|
||||
@@ -20,6 +20,7 @@ const code = ref('')
|
||||
const codes = ref<Record<string, string>>({})
|
||||
const selected = ref<Record<string, string>>({})
|
||||
const draft = ref('')
|
||||
const announcementDraft = ref<string>()
|
||||
const search = ref('')
|
||||
const favoritesOnly = ref(false)
|
||||
const historyViews = [
|
||||
@@ -146,6 +147,17 @@ function establish() {
|
||||
})
|
||||
}
|
||||
|
||||
function saveAnnouncement() {
|
||||
const identity = session.identity
|
||||
const announcement = announcementDraft.value
|
||||
if (!identity || announcement === undefined) return
|
||||
void run(async () => {
|
||||
await sendGroupMessage(identity, props.group, { announcement }, session.authorized)
|
||||
announcementDraft.value = undefined
|
||||
await refresh()
|
||||
})
|
||||
}
|
||||
|
||||
function send() {
|
||||
const identity = session.identity
|
||||
if (identity) void run(async () => {
|
||||
@@ -239,6 +251,7 @@ watch(() => session.groupChange, (event) => { if (event?.groupId === props.group
|
||||
watch(() => session.connection, (connection) => { if (connection === '实时连接已建立') queueRefresh() })
|
||||
watch(currentEpoch, (epoch, previous) => {
|
||||
if (!previous || epoch === previous) return
|
||||
announcementDraft.value = undefined
|
||||
if (editing.value || replying.value) draft.value = ''
|
||||
editing.value = undefined
|
||||
replying.value = undefined
|
||||
@@ -283,6 +296,24 @@ onBeforeUnmount(() => {
|
||||
<p v-if="ready" role="status">群加密已建立</p>
|
||||
<p v-else-if="view?.current && !view.current.welcome">当前设备未获分配群密钥。</p>
|
||||
<p v-else-if="!view?.current && group.role !== 'owner'">等待群主建立群加密会话。</p>
|
||||
<section v-if="view && (view.announcement || (ready && group.role === 'owner'))" class="group-announcement" aria-label="群公告">
|
||||
<h4>群公告</h4>
|
||||
<p v-if="view.announcement" class="announcement-text">{{ view.announcement }}</p>
|
||||
<p v-else class="muted">暂无群公告。</p>
|
||||
<template v-if="ready && group.role === 'owner'">
|
||||
<button v-if="announcementDraft === undefined" type="button" class="plain" :disabled="busy || view.hasPending"
|
||||
@click="announcementDraft = view.announcement ?? ''">{{ view.announcement ? '编辑群公告' : '写群公告' }}</button>
|
||||
<form v-else class="group-chat-composer" @submit.prevent="saveAnnouncement">
|
||||
<label>公告内容<textarea v-model="announcementDraft" rows="3" maxlength="2000" /></label>
|
||||
<div class="message-actions">
|
||||
<button class="primary" :disabled="busy || view.hasPending || announcementDraft.trim() === (view.announcement ?? '')">
|
||||
{{ announcementDraft.trim() ? '发布公告' : '清除公告' }}
|
||||
</button>
|
||||
<button type="button" class="plain" @click="announcementDraft = undefined">取消</button>
|
||||
</div>
|
||||
</form>
|
||||
</template>
|
||||
</section>
|
||||
<details :open="!ready">
|
||||
<summary>群设备和安全码</summary>
|
||||
<p>本机安全码 <code class="group-security-code">{{ code }}</code></p>
|
||||
@@ -385,6 +416,9 @@ onBeforeUnmount(() => {
|
||||
<style scoped>
|
||||
.group-chat { display: grid; gap: .7rem; padding-block: 1rem; }
|
||||
.group-chat p, .group-chat h3 { margin: 0; }
|
||||
.group-announcement { display: grid; gap: .45rem; padding: .65rem .8rem; border: 1px solid var(--line); border-radius: .45rem; }
|
||||
.group-announcement h4 { margin: 0; }
|
||||
.announcement-text { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.group-security-code { overflow-wrap: anywhere; }
|
||||
.group-device-member { margin-block: .75rem; }
|
||||
.group-chat-lines { display: grid; gap: .75rem; max-height: 24rem; overflow-y: auto; margin: 0; padding: .7rem 0; list-style: none; }
|
||||
|
||||
+49
-17
@@ -21,18 +21,22 @@ export type GroupLine = {
|
||||
}
|
||||
type LineRef = Pick<GroupLine, 'id' | 'sender' | 'epoch'>
|
||||
export type ForwardDestination = { group: string } | { user: string; device: Peer }
|
||||
type GroupContent = string | File | { text: string; reply: LineRef } | (Mutation & { epoch: string })
|
||||
type GroupContent = string | File | { text: string; reply: LineRef } | (Mutation & { epoch: string }) | { announcement: string }
|
||||
type Verified = { user: string; key: string; name: string }
|
||||
type VerifiedEpoch = { version: string; roster: Record<string, Verified> }
|
||||
type VerifiedEpoch = { version: string; roster: Record<string, Verified>; ownerDevice?: string }
|
||||
export type GroupChatState = {
|
||||
cursor: string
|
||||
lines: GroupLine[]
|
||||
epochs: Record<string, VerifiedEpoch>
|
||||
announcement?: { text: string; sequence: string }
|
||||
pendingEpoch?: Publishing
|
||||
pendingMessage?: Outgoing & { line: GroupLine; mutation?: Mutation }
|
||||
pendingMessage?: Outgoing & { line: GroupLine; mutation?: Mutation; announcement?: string }
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder()
|
||||
const decoder = new TextDecoder('utf-8', { fatal: true })
|
||||
const announcementPrefix = [255, 5]
|
||||
const maxAnnouncementBytes = 2000
|
||||
const path = (group: GroupDetail) => '/groups/' + encodeURIComponent(group.id)
|
||||
export const groupAttachmentPath = (group: GroupDetail, id: string) => path(group) + '/attachments/' + encodeURIComponent(id)
|
||||
const aad = (group: string, epoch: string, id: string, sender: string) =>
|
||||
@@ -42,9 +46,14 @@ function local(chats: Record<string, GroupChatState>, group: string) {
|
||||
return chats[group] ??= { cursor: '0', lines: [], epochs: {} }
|
||||
}
|
||||
|
||||
function finishPending(chat: GroupChatState, pending: NonNullable<GroupChatState['pendingMessage']>) {
|
||||
function applyAnnouncement(chat: GroupChatState, text: string, sequence: string) {
|
||||
if (!chat.announcement || BigInt(sequence) > BigInt(chat.announcement.sequence)) chat.announcement = { text, sequence }
|
||||
}
|
||||
|
||||
function finishPending(chat: GroupChatState, pending: NonNullable<GroupChatState['pendingMessage']>, sequence: string) {
|
||||
pending.line.epoch ??= pending.epoch
|
||||
if (pending.mutation) applyGroupMutation(chat, pending.epoch, pending.line.sender, pending.mutation)
|
||||
if (pending.announcement !== undefined) applyAnnouncement(chat, pending.announcement, sequence)
|
||||
else if (pending.mutation) applyGroupMutation(chat, pending.epoch, pending.line.sender, pending.mutation)
|
||||
else chat.lines.push(pending.line)
|
||||
delete chat.pendingMessage
|
||||
}
|
||||
@@ -86,9 +95,12 @@ function matchesEpoch(known: VerifiedEpoch | undefined, epoch: Epoch, group: Gro
|
||||
if (!known || known.version !== epoch.membershipVersion) return false
|
||||
const members = activeMembers(group)
|
||||
const expected = Object.keys(known.roster)
|
||||
return expected.length === members.length && epoch.roster.length === expected.length &&
|
||||
const owner = members.find((member) => member.role === 'owner')
|
||||
return Boolean(owner && known.roster[epoch.creatorDevice]?.user === owner.id &&
|
||||
(!known.ownerDevice || known.ownerDevice === epoch.creatorDevice) &&
|
||||
expected.length === members.length && epoch.roster.length === expected.length &&
|
||||
expected.every((id) => epoch.roster.includes(id)) &&
|
||||
members.every((member) => Object.values(known.roster).some((device) => device.user === member.id))
|
||||
members.every((member) => Object.values(known.roster).some((device) => device.user === member.id)))
|
||||
}
|
||||
|
||||
async function groupID(group: string, epoch: string) {
|
||||
@@ -164,7 +176,7 @@ export function publishGroup(identity: ChatIdentity, group: GroupDetail, selecti
|
||||
}
|
||||
const id = crypto.randomUUID()
|
||||
const welcome = base64(engine.start_group(await groupID(group.id, id), JSON.stringify(enrollments)))
|
||||
chat.epochs[id] = { version: group.membershipVersion, roster }
|
||||
chat.epochs[id] = { version: group.membershipVersion, roster, ownerDevice: identity.device.id }
|
||||
chat.pendingEpoch = { id, membershipVersion: group.membershipVersion,
|
||||
devices: selection.map((device) => ({ device: device.id, wire: device.id === identity.device.id ? undefined : welcome })) }
|
||||
state.engine = base64(engine.snapshot())
|
||||
@@ -179,10 +191,10 @@ export function publishGroup(identity: ChatIdentity, group: GroupDetail, selecti
|
||||
async function sendPending(group: GroupDetail, chat: GroupChatState, call: Call) {
|
||||
const pending = chat.pendingMessage
|
||||
if (!pending) return
|
||||
await call(path(group) + '/messages', 'POST', {
|
||||
const { sequence } = await call<{ sequence: string }>(path(group) + '/messages', 'POST', {
|
||||
id: pending.id, epoch: pending.epoch, wire: pending.wire, attachmentId: pending.line.attachment?.id,
|
||||
})
|
||||
finishPending(chat, pending)
|
||||
finishPending(chat, pending, sequence)
|
||||
}
|
||||
|
||||
export function synchronizeGroup(identity: ChatIdentity, group: GroupDetail, call: Call) {
|
||||
@@ -209,7 +221,7 @@ export function synchronizeGroup(identity: ChatIdentity, group: GroupDetail, cal
|
||||
const members = Object.entries(roster).map(([device, { key }]) => ({ device, key: Array.from(decode(key)) }))
|
||||
engine.join_group(await groupID(group.id, current.id), current.creatorDevice, JSON.stringify(members), decode(current.welcome))
|
||||
state.engine = base64(engine.snapshot())
|
||||
chat.epochs[current.id] = { version: group.membershipVersion, roster }
|
||||
chat.epochs[current.id] = { version: group.membershipVersion, roster, ownerDevice: current.creatorDevice }
|
||||
state.packageChecked = 0
|
||||
await save(state)
|
||||
} finally {
|
||||
@@ -220,6 +232,10 @@ export function synchronizeGroup(identity: ChatIdentity, group: GroupDetail, cal
|
||||
}
|
||||
}
|
||||
const ready = Boolean(current && matchesEpoch(chat.epochs[current.id], current, group))
|
||||
if (ready && current && !chat.epochs[current.id]!.ownerDevice) {
|
||||
chat.epochs[current.id]!.ownerDevice = current.creatorDevice
|
||||
await save(state)
|
||||
}
|
||||
if (current && chat.epochs[current.id] && !ready) warning = '群设备名单与本机核验记录不匹配'
|
||||
if (ready && chat.pendingMessage && chat.pendingMessage.epoch === current?.id) {
|
||||
try {
|
||||
@@ -236,7 +252,7 @@ export function synchronizeGroup(identity: ChatIdentity, group: GroupDetail, cal
|
||||
const pending = chat.pendingMessage
|
||||
if (pending && pending.id === item.id && pending.epoch === item.epoch && pending.wire === item.wire &&
|
||||
pending.line.attachment?.id === item.attachmentId) {
|
||||
finishPending(chat, pending)
|
||||
finishPending(chat, pending, item.sequence)
|
||||
}
|
||||
} else {
|
||||
if (item.epoch === current?.id && !ready) break
|
||||
@@ -247,6 +263,13 @@ export function synchronizeGroup(identity: ChatIdentity, group: GroupDetail, cal
|
||||
const bytes = engine.decrypt_group(await groupID(group.id, item.epoch), item.senderDevice, decode(sender.key),
|
||||
aad(group.id, item.epoch, item.id, item.senderDevice), decode(item.wire))
|
||||
state.engine = base64(engine.snapshot())
|
||||
if (bytes[0] === announcementPrefix[0] && bytes[1] === announcementPrefix[1]) {
|
||||
if (item.attachmentId || bytes.length > maxAnnouncementBytes + 2 ||
|
||||
chat.epochs[item.epoch]?.ownerDevice !== item.senderDevice) throw new Error('群公告身份或格式无效')
|
||||
applyAnnouncement(chat, decoder.decode(bytes.subarray(2)), item.sequence)
|
||||
chat.cursor = item.sequence
|
||||
continue
|
||||
}
|
||||
const { text, attachment, quote, mutation } = decodeMessage(bytes)
|
||||
if (attachment?.id !== item.attachmentId) throw new Error('群附件标识不匹配')
|
||||
if (mutation) {
|
||||
@@ -273,7 +296,7 @@ export function synchronizeGroup(identity: ChatIdentity, group: GroupDetail, cal
|
||||
try { await replenishPackages(identity, call, state, save, engine) } catch { warning ||= '密钥包补充失败' } finally { engine.free() }
|
||||
}
|
||||
const hasMore = packets.length === 64 && packets.at(-1)?.sequence === chat.cursor
|
||||
return { devices, lines: chat.lines, pinned: state.pinned, ready, current, warning, cursor: chat.cursor, hasMore,
|
||||
return { devices, lines: chat.lines, pinned: state.pinned, ready, current, warning, cursor: chat.cursor, hasMore, announcement: chat.announcement?.text,
|
||||
hasPending: Boolean(chat.pendingMessage), stalePending: Boolean(chat.pendingMessage && chat.pendingMessage.epoch !== current?.id) }
|
||||
})
|
||||
}
|
||||
@@ -319,9 +342,10 @@ export async function forwardContent(identity: ChatIdentity, destination: Forwar
|
||||
|
||||
export function sendGroupMessage(identity: ChatIdentity, group: GroupDetail, message: GroupContent, call: Call, expectedEpoch?: string) {
|
||||
return update(identity, async (state, save, factory) => {
|
||||
const text = (typeof message === 'string' ? message : message instanceof File ? '' : message.text ?? '').trim()
|
||||
const announcement = typeof message === 'object' && 'announcement' in message ? message.announcement.trim() : undefined
|
||||
const text = (typeof message === 'string' ? message : !(message instanceof File) && 'text' in message ? message.text ?? '' : '').trim()
|
||||
let content: Uint8Array = encoder.encode(text)
|
||||
if (!(message instanceof File) && !(typeof message === 'object' && 'action' in message && message.action === 'recall') &&
|
||||
if (announcement === undefined && !(message instanceof File) && !(typeof message === 'object' && 'action' in message && message.action === 'recall') &&
|
||||
(content.length === 0 || content.length > 8000)) throw new Error('消息须为 1 至 8000 字节')
|
||||
const chat = local(state.groupChats ??= {}, group.id)
|
||||
const epochs = await call<Epoch[]>(path(group) + '/epochs')
|
||||
@@ -346,17 +370,25 @@ export function sendGroupMessage(identity: ChatIdentity, group: GroupDetail, mes
|
||||
if (!target || target.recalled) throw new Error('当前会话中没有可引用的消息')
|
||||
quote = groupQuote(target)
|
||||
content = encodeReply(text, quote)
|
||||
} else if (typeof message === 'object') {
|
||||
} else if (typeof message === 'object' && 'action' in message) {
|
||||
const target = chat.lines.find((line) => line.epoch === epoch.id && line.epoch === message.epoch &&
|
||||
line.id === message.id && line.sender === identity.device.id)
|
||||
if (!target || target.recalled || (message.action === 'edit' && target.attachment)) throw new Error('此群消息无法更新')
|
||||
mutation = message.action === 'edit' ? { action: 'edit', id: target.id, text } : { action: 'recall', id: target.id }
|
||||
content = encodeMutation(mutation)
|
||||
}
|
||||
if (announcement !== undefined) {
|
||||
if (group.role !== 'owner' || epoch.creatorDevice !== identity.device.id) throw new Error('请使用群主的会话设备发布公告')
|
||||
const body = encoder.encode(announcement)
|
||||
if (body.length > maxAnnouncementBytes) throw new Error('群公告不能超过 2,000 字节')
|
||||
content = new Uint8Array(body.length + 2)
|
||||
content.set(announcementPrefix)
|
||||
content.set(body, 2)
|
||||
}
|
||||
const engine = factory.DeviceMls.restore(decode(state.engine))
|
||||
try {
|
||||
const wire = engine.encrypt(await groupID(group.id, epoch.id), aad(group.id, epoch.id, id, identity.device.id), content)
|
||||
chat.pendingMessage = { id, epoch: epoch.id, wire: base64(wire), mutation,
|
||||
chat.pendingMessage = { id, epoch: epoch.id, wire: base64(wire), mutation, announcement,
|
||||
line: { id, epoch: epoch.id, user: identity.user.id, name: own.name, sender: identity.device.id,
|
||||
text, quote, attachment, time: new Date().toISOString() } }
|
||||
state.engine = base64(engine.snapshot())
|
||||
|
||||
@@ -203,6 +203,8 @@ onBeforeUnmount(() => {
|
||||
@click="change(member.role === 'admin' ? 'demote' : 'promote', member.id)">
|
||||
{{ member.role === 'admin' ? '取消管理员' : '设为管理员' }}
|
||||
</button>
|
||||
<button v-if="detail.role === 'owner' && member.state === 'active'" type="button" class="plain" :disabled="busy"
|
||||
@click="confirmation = { action: 'transfer', target: member.id, label: '将群主转让给 ' + member.username }">转让群主</button>
|
||||
<button v-if="detail.role === 'owner' || member.role === 'member'" class="plain" :disabled="busy"
|
||||
@click="confirmation = { action: 'remove', target: member.id, label: member.state === 'invited' ? '撤销此邀请' : '移除此成员' }">
|
||||
{{ member.state === 'invited' ? '撤销邀请' : '移除成员' }}
|
||||
@@ -214,6 +216,7 @@ onBeforeUnmount(() => {
|
||||
<button v-else class="plain" :disabled="busy" @click="confirmation = { action: 'leave', label: '退出群组' }">退出群组</button>
|
||||
<div v-if="confirmation" class="confirmation">
|
||||
<p>确认{{ confirmation.label }}?</p>
|
||||
<p v-if="confirmation.action === 'transfer'" class="muted">转让完成后,你将成为普通成员,由新群主重新建立加密会话。</p>
|
||||
<button class="plain" :disabled="busy" @click="change(confirmation.action, confirmation.target)">确认操作</button>
|
||||
<button class="plain" @click="confirmation = undefined">取消</button>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user