@agentunion/fastaun 0.2.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +17 -0
- package/README.md +78 -0
- package/dist/auth.d.ts +287 -0
- package/dist/auth.js +1668 -0
- package/dist/auth.js.map +1 -0
- package/dist/client.d.ts +359 -0
- package/dist/client.js +3918 -0
- package/dist/client.js.map +1 -0
- package/dist/config.d.ts +43 -0
- package/dist/config.js +119 -0
- package/dist/config.js.map +1 -0
- package/dist/crypto.d.ts +41 -0
- package/dist/crypto.js +85 -0
- package/dist/crypto.js.map +1 -0
- package/dist/discovery.d.ts +22 -0
- package/dist/discovery.js +110 -0
- package/dist/discovery.js.map +1 -0
- package/dist/e2ee-group.d.ts +192 -0
- package/dist/e2ee-group.js +1134 -0
- package/dist/e2ee-group.js.map +1 -0
- package/dist/e2ee.d.ts +120 -0
- package/dist/e2ee.js +890 -0
- package/dist/e2ee.js.map +1 -0
- package/dist/errors.d.ts +115 -0
- package/dist/errors.js +253 -0
- package/dist/errors.js.map +1 -0
- package/dist/events.d.ts +39 -0
- package/dist/events.js +82 -0
- package/dist/events.js.map +1 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +32 -0
- package/dist/index.js.map +1 -0
- package/dist/keystore/aid-db.d.ts +79 -0
- package/dist/keystore/aid-db.js +621 -0
- package/dist/keystore/aid-db.js.map +1 -0
- package/dist/keystore/file.d.ts +82 -0
- package/dist/keystore/file.js +395 -0
- package/dist/keystore/file.js.map +1 -0
- package/dist/keystore/index.d.ts +88 -0
- package/dist/keystore/index.js +7 -0
- package/dist/keystore/index.js.map +1 -0
- package/dist/keystore/sqlite-backup.d.ts +40 -0
- package/dist/keystore/sqlite-backup.js +379 -0
- package/dist/keystore/sqlite-backup.js.map +1 -0
- package/dist/logger.d.ts +6 -0
- package/dist/logger.js +53 -0
- package/dist/logger.js.map +1 -0
- package/dist/namespaces/auth.d.ts +49 -0
- package/dist/namespaces/auth.js +248 -0
- package/dist/namespaces/auth.js.map +1 -0
- package/dist/namespaces/custody.d.ts +47 -0
- package/dist/namespaces/custody.js +231 -0
- package/dist/namespaces/custody.js.map +1 -0
- package/dist/secret-store/file-store.d.ts +25 -0
- package/dist/secret-store/file-store.js +124 -0
- package/dist/secret-store/file-store.js.map +1 -0
- package/dist/secret-store/index.d.ts +28 -0
- package/dist/secret-store/index.js +19 -0
- package/dist/secret-store/index.js.map +1 -0
- package/dist/seq-tracker.d.ts +29 -0
- package/dist/seq-tracker.js +221 -0
- package/dist/seq-tracker.js.map +1 -0
- package/dist/transport.d.ts +60 -0
- package/dist/transport.js +355 -0
- package/dist/transport.js.map +1 -0
- package/dist/types.d.ts +170 -0
- package/dist/types.js +12 -0
- package/dist/types.js.map +1 -0
- package/package.json +42 -0
package/dist/client.js
ADDED
|
@@ -0,0 +1,3918 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AUNClient — AUN Core SDK 主客户端
|
|
3
|
+
*
|
|
4
|
+
* 完整实现,与 Python SDK client.py 对齐。
|
|
5
|
+
* 功能:
|
|
6
|
+
* - 连接/断线重连/关闭
|
|
7
|
+
* - RPC 调用(含 E2EE 自动加解密编排)
|
|
8
|
+
* - 事件自动解密管线(P2P + 群组)
|
|
9
|
+
* - 后台任务(心跳、token 刷新、prekey 轮换、epoch 清理/轮换)
|
|
10
|
+
* - 客户端签名(关键操作)
|
|
11
|
+
* - 群组 E2EE 全自动编排(建群/加人/踢人/退出)
|
|
12
|
+
*/
|
|
13
|
+
import * as crypto from 'node:crypto';
|
|
14
|
+
import * as http from 'node:http';
|
|
15
|
+
import * as https from 'node:https';
|
|
16
|
+
import { join } from 'node:path';
|
|
17
|
+
import { URL } from 'node:url';
|
|
18
|
+
import { configFromMap, getDeviceId, normalizeInstanceId } from './config.js';
|
|
19
|
+
import { CryptoProvider } from './crypto.js';
|
|
20
|
+
import { GatewayDiscovery } from './discovery.js';
|
|
21
|
+
import { E2EEManager } from './e2ee.js';
|
|
22
|
+
import { GroupE2EEManager, computeMembershipCommitment, storeGroupSecret, buildKeyDistribution, buildKeyRequest, buildMembershipManifest, signMembershipManifest, } from './e2ee-group.js';
|
|
23
|
+
import { AUNError, AuthError, ConnectionError, E2EEError, PermissionError, StateError, TimeoutError, ValidationError, } from './errors.js';
|
|
24
|
+
import { EventDispatcher } from './events.js';
|
|
25
|
+
import { FileKeyStore } from './keystore/file.js';
|
|
26
|
+
import { AUNLogger } from './logger.js';
|
|
27
|
+
import { SQLiteBackup } from './keystore/sqlite-backup.js';
|
|
28
|
+
import { AuthNamespace } from './namespaces/auth.js';
|
|
29
|
+
import { CustodyNamespace } from './namespaces/custody.js';
|
|
30
|
+
import { RPCTransport } from './transport.js';
|
|
31
|
+
import { AuthFlow } from './auth.js';
|
|
32
|
+
import { SeqTracker } from './seq-tracker.js';
|
|
33
|
+
import { isJsonObject, } from './types.js';
|
|
34
|
+
// ── 日志辅助 ──────────────────────────────────────────────────
|
|
35
|
+
/** 文件日志(模块级单例) */
|
|
36
|
+
let _debugLogger = null;
|
|
37
|
+
/** 简易日志:前缀 [aun_core.client] */
|
|
38
|
+
function _clientLog(level, msg, ...args) {
|
|
39
|
+
const ts = new Date().toISOString();
|
|
40
|
+
const formatted = args.reduce((s, a) => s.replace('%s', String(a)), msg);
|
|
41
|
+
// eslint-disable-next-line no-console
|
|
42
|
+
console.log(`[${ts}] [aun_core.client] ${level}: ${formatted}`);
|
|
43
|
+
if (_debugLogger)
|
|
44
|
+
_debugLogger.log(`${level}: ${formatted}`);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* 递归排序键的 JSON 序列化(Canonical JSON for AUN)
|
|
48
|
+
* 等价于 Python json.dumps(sort_keys=True, separators=(",",":"), ensure_ascii=False)
|
|
49
|
+
* 非 ASCII 字符直接以 UTF-8 输出,与 AAD 序列化规则一致。
|
|
50
|
+
*/
|
|
51
|
+
export function stableStringify(obj) {
|
|
52
|
+
if (obj === null || obj === undefined)
|
|
53
|
+
return 'null';
|
|
54
|
+
if (typeof obj === 'boolean' || typeof obj === 'number')
|
|
55
|
+
return JSON.stringify(obj);
|
|
56
|
+
if (typeof obj === 'string')
|
|
57
|
+
return JSON.stringify(obj);
|
|
58
|
+
if (Array.isArray(obj)) {
|
|
59
|
+
return '[' + obj.map(v => stableStringify(v)).join(',') + ']';
|
|
60
|
+
}
|
|
61
|
+
if (isJsonObject(obj)) {
|
|
62
|
+
const keys = Object.keys(obj).sort();
|
|
63
|
+
// 跳过值为 undefined 的 key,与 JSON.stringify 行为一致(ISSUE-TS-001)
|
|
64
|
+
const entries = keys
|
|
65
|
+
.filter(k => obj[k] !== undefined)
|
|
66
|
+
.map(k => stableStringify(k) + ':' + stableStringify(obj[k]));
|
|
67
|
+
return '{' + entries.join(',') + '}';
|
|
68
|
+
}
|
|
69
|
+
return JSON.stringify(obj);
|
|
70
|
+
}
|
|
71
|
+
// ── 常量 ──────────────────────────────────────────────────────
|
|
72
|
+
/** 内部专用方法,禁止外部直接调用 */
|
|
73
|
+
const INTERNAL_ONLY_METHODS = new Set([
|
|
74
|
+
'auth.login1',
|
|
75
|
+
'auth.aid_login1',
|
|
76
|
+
'auth.login2',
|
|
77
|
+
'auth.aid_login2',
|
|
78
|
+
'auth.connect',
|
|
79
|
+
'auth.refresh_token',
|
|
80
|
+
'initialize',
|
|
81
|
+
]);
|
|
82
|
+
const DEFAULT_SESSION_OPTIONS = {
|
|
83
|
+
auto_reconnect: true,
|
|
84
|
+
heartbeat_interval: 30.0,
|
|
85
|
+
token_refresh_before: 60.0,
|
|
86
|
+
retry: {
|
|
87
|
+
initial_delay: 1.0,
|
|
88
|
+
max_delay: 64.0,
|
|
89
|
+
// M25: 0 表示无限重试,与 Go/Python 对齐
|
|
90
|
+
max_attempts: 0,
|
|
91
|
+
},
|
|
92
|
+
timeouts: {
|
|
93
|
+
connect: 5.0,
|
|
94
|
+
call: 10.0,
|
|
95
|
+
http: 30.0,
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
const RECONNECT_MIN_BASE_DELAY_MS = 1_000;
|
|
99
|
+
const RECONNECT_MAX_BASE_DELAY_MS = 64_000;
|
|
100
|
+
const GROUP_ROTATION_LEASE_MS = 120_000;
|
|
101
|
+
const GROUP_ROTATION_RETRY_MAX_DELAY_MS = 300_000;
|
|
102
|
+
function clampReconnectDelayMs(value, fallback, upper = RECONNECT_MAX_BASE_DELAY_MS) {
|
|
103
|
+
const parsed = Number(value);
|
|
104
|
+
const ms = Number.isFinite(parsed) ? parsed : fallback;
|
|
105
|
+
return Math.min(Math.max(ms, RECONNECT_MIN_BASE_DELAY_MS), upper);
|
|
106
|
+
}
|
|
107
|
+
function reconnectSleepDelayMs(baseDelay, maxBaseDelay) {
|
|
108
|
+
return baseDelay + Math.random() * maxBaseDelay;
|
|
109
|
+
}
|
|
110
|
+
/** 需要客户端签名的关键方法 */
|
|
111
|
+
const SIGNED_METHODS = new Set([
|
|
112
|
+
'group.send', 'group.kick', 'group.add_member',
|
|
113
|
+
'group.leave', 'group.remove_member', 'group.update_rules',
|
|
114
|
+
'group.update', 'group.update_announcement',
|
|
115
|
+
'group.update_join_requirements', 'group.set_role',
|
|
116
|
+
'group.transfer_owner', 'group.review_join_request',
|
|
117
|
+
'group.batch_review_join_request',
|
|
118
|
+
'group.request_join', 'group.use_invite_code',
|
|
119
|
+
'group.resources.put', 'group.resources.update',
|
|
120
|
+
'group.resources.delete', 'group.resources.request_add',
|
|
121
|
+
'group.resources.direct_add', 'group.resources.approve_request',
|
|
122
|
+
'group.resources.reject_request',
|
|
123
|
+
]);
|
|
124
|
+
/** peer 证书缓存 TTL(10 分钟) */
|
|
125
|
+
const PEER_CERT_CACHE_TTL = 600;
|
|
126
|
+
function isGroupServiceAid(value) {
|
|
127
|
+
const text = String(value ?? '').trim();
|
|
128
|
+
if (!text.includes('.'))
|
|
129
|
+
return false;
|
|
130
|
+
const [name, ...issuerParts] = text.split('.');
|
|
131
|
+
return name === 'group' && issuerParts.join('.').length > 0;
|
|
132
|
+
}
|
|
133
|
+
function isPeerPrekeyMaterial(value) {
|
|
134
|
+
if (!isJsonObject(value))
|
|
135
|
+
return false;
|
|
136
|
+
const candidate = value;
|
|
137
|
+
return (typeof candidate.prekey_id === 'string'
|
|
138
|
+
&& typeof candidate.public_key === 'string'
|
|
139
|
+
&& typeof candidate.signature === 'string'
|
|
140
|
+
&& (candidate.created_at === undefined || typeof candidate.created_at === 'number'));
|
|
141
|
+
}
|
|
142
|
+
function isPeerPrekeyResponse(value) {
|
|
143
|
+
if (!isJsonObject(value))
|
|
144
|
+
return false;
|
|
145
|
+
const candidate = value;
|
|
146
|
+
if (typeof candidate.found !== 'boolean')
|
|
147
|
+
return false;
|
|
148
|
+
return candidate.prekey === undefined || isPeerPrekeyMaterial(candidate.prekey);
|
|
149
|
+
}
|
|
150
|
+
function formatCaughtError(error) {
|
|
151
|
+
return error instanceof Error ? error : String(error);
|
|
152
|
+
}
|
|
153
|
+
function normalizeDeliveryModeConfig(raw, opts = {}) {
|
|
154
|
+
const defaultMode = String(opts.defaultMode ?? 'fanout').trim().toLowerCase() || 'fanout';
|
|
155
|
+
const defaultRouting = String(opts.defaultRouting ?? 'round_robin').trim().toLowerCase() || 'round_robin';
|
|
156
|
+
const defaultAffinityTtlMs = Number(opts.defaultAffinityTtlMs ?? 0);
|
|
157
|
+
let candidate;
|
|
158
|
+
if (typeof raw === 'string') {
|
|
159
|
+
candidate = { mode: raw };
|
|
160
|
+
}
|
|
161
|
+
else if (isJsonObject(raw)) {
|
|
162
|
+
candidate = { ...raw };
|
|
163
|
+
}
|
|
164
|
+
else {
|
|
165
|
+
candidate = {};
|
|
166
|
+
}
|
|
167
|
+
const mode = String(candidate.mode ?? defaultMode).trim().toLowerCase() || 'fanout';
|
|
168
|
+
if (mode !== 'fanout' && mode !== 'queue') {
|
|
169
|
+
throw new ValidationError("delivery_mode must be 'fanout' or 'queue'");
|
|
170
|
+
}
|
|
171
|
+
let routing = String(candidate.routing ?? (mode === 'queue' ? defaultRouting : '')).trim().toLowerCase();
|
|
172
|
+
if (mode !== 'queue') {
|
|
173
|
+
routing = '';
|
|
174
|
+
}
|
|
175
|
+
else if (routing && routing !== 'round_robin' && routing !== 'sender_affinity') {
|
|
176
|
+
throw new ValidationError("queue_routing must be 'round_robin' or 'sender_affinity'");
|
|
177
|
+
}
|
|
178
|
+
else if (!routing) {
|
|
179
|
+
routing = 'round_robin';
|
|
180
|
+
}
|
|
181
|
+
const ttlRaw = candidate.affinity_ttl_ms ?? (mode === 'queue' ? defaultAffinityTtlMs : 0);
|
|
182
|
+
const affinityTtlMs = Math.max(0, Number(ttlRaw ?? 0));
|
|
183
|
+
if (!Number.isFinite(affinityTtlMs)) {
|
|
184
|
+
throw new ValidationError('affinity_ttl_ms must be an integer');
|
|
185
|
+
}
|
|
186
|
+
return {
|
|
187
|
+
mode,
|
|
188
|
+
routing,
|
|
189
|
+
affinity_ttl_ms: affinityTtlMs,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
// ── HTTP 辅助 ─────────────────────────────────────────────────
|
|
193
|
+
/** 发起 HTTP GET 请求,返回文本内容 */
|
|
194
|
+
function _httpGetText(url, verifySsl) {
|
|
195
|
+
return new Promise((resolve, reject) => {
|
|
196
|
+
const parsed = new URL(url);
|
|
197
|
+
const mod = parsed.protocol === 'https:' ? https : http;
|
|
198
|
+
const options = { timeout: 30_000 };
|
|
199
|
+
if (!verifySsl) {
|
|
200
|
+
options.rejectUnauthorized = false;
|
|
201
|
+
}
|
|
202
|
+
const req = mod.get(url, options, (res) => {
|
|
203
|
+
if (res.statusCode && (res.statusCode < 200 || res.statusCode >= 300)) {
|
|
204
|
+
reject(new Error(`HTTP ${res.statusCode} from ${url}`));
|
|
205
|
+
res.resume();
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const chunks = [];
|
|
209
|
+
res.on('data', (chunk) => chunks.push(chunk));
|
|
210
|
+
res.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));
|
|
211
|
+
res.on('error', reject);
|
|
212
|
+
});
|
|
213
|
+
req.on('error', reject);
|
|
214
|
+
req.on('timeout', () => {
|
|
215
|
+
req.destroy();
|
|
216
|
+
reject(new Error(`timeout fetching ${url}`));
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* AUN Core SDK 主客户端
|
|
222
|
+
*/
|
|
223
|
+
export class AUNClient {
|
|
224
|
+
/** 原始配置 */
|
|
225
|
+
config;
|
|
226
|
+
/** 解析后的配置模型 */
|
|
227
|
+
_configModel;
|
|
228
|
+
/** 当前 AID */
|
|
229
|
+
_aid = null;
|
|
230
|
+
/** 当前身份信息(内存缓存) */
|
|
231
|
+
_identity = null;
|
|
232
|
+
/** 连接状态 */
|
|
233
|
+
_state = 'idle';
|
|
234
|
+
/** Gateway URL */
|
|
235
|
+
_gatewayUrl = null;
|
|
236
|
+
/** 是否正在关闭 */
|
|
237
|
+
_closing = false;
|
|
238
|
+
/** 事件调度器 */
|
|
239
|
+
_dispatcher;
|
|
240
|
+
/** Gateway 发现 */
|
|
241
|
+
_discovery;
|
|
242
|
+
/** 传输层 */
|
|
243
|
+
_transport;
|
|
244
|
+
/** 认证流程 */
|
|
245
|
+
_auth;
|
|
246
|
+
/** 密钥存储 */
|
|
247
|
+
_keystore;
|
|
248
|
+
/** E2EE 管理器 */
|
|
249
|
+
_e2ee;
|
|
250
|
+
/** 群组 E2EE 管理器 */
|
|
251
|
+
_groupE2ee;
|
|
252
|
+
/** Auth 命名空间 */
|
|
253
|
+
auth;
|
|
254
|
+
/** AID 托管命名空间 */
|
|
255
|
+
custody;
|
|
256
|
+
/** 会话参数(重连用) */
|
|
257
|
+
_sessionParams = null;
|
|
258
|
+
/** 会话选项 */
|
|
259
|
+
_sessionOptions = { ...DEFAULT_SESSION_OPTIONS };
|
|
260
|
+
/** 当前实例上下文 */
|
|
261
|
+
_deviceId;
|
|
262
|
+
_slotId;
|
|
263
|
+
_connectDeliveryMode;
|
|
264
|
+
_defaultConnectDeliveryMode;
|
|
265
|
+
/** peer 证书缓存 */
|
|
266
|
+
_certCache = new Map();
|
|
267
|
+
_peerPrekeysCache = new Map();
|
|
268
|
+
_prekeyReplenishInflight = new Set();
|
|
269
|
+
_prekeyReplenished = new Set();
|
|
270
|
+
/** 消息序列号跟踪器(群消息 + P2P 空洞检测) */
|
|
271
|
+
_seqTracker = new SeqTracker();
|
|
272
|
+
_seqTrackerContext = null;
|
|
273
|
+
/** 惰性群同步:已同步过的 group_id 集合 */
|
|
274
|
+
_groupSynced = new Set();
|
|
275
|
+
/** 惰性 P2P 同步:是否已同步过 */
|
|
276
|
+
_p2pSynced = false;
|
|
277
|
+
/** 补洞去重:已完成/进行中的 key -> 开始时间戳,防止重复 pull 同一区间 */
|
|
278
|
+
_gapFillDone = new Map();
|
|
279
|
+
/** 推送路径已分发的 seq 集合(按命名空间),补洞路径 publish 前检查以避免重复分发 */
|
|
280
|
+
_pushedSeqs = new Map();
|
|
281
|
+
_pendingDecryptMsgs = new Map();
|
|
282
|
+
_groupEpochRotationInflight = new Set();
|
|
283
|
+
_groupEpochRecoveryInflight = new Map();
|
|
284
|
+
_groupMembershipRotationDone = new Set();
|
|
285
|
+
_groupEpochRotationRetryTimers = new Map();
|
|
286
|
+
// ── 后台任务定时器 ──────────────────────────────────────────
|
|
287
|
+
_heartbeatTimer = null;
|
|
288
|
+
_tokenRefreshTimer = null;
|
|
289
|
+
_tokenRefreshFailures = 0;
|
|
290
|
+
_prekeyRefreshTimer = null;
|
|
291
|
+
_groupEpochCleanupTimer = null;
|
|
292
|
+
_groupEpochRotateTimer = null;
|
|
293
|
+
_cacheCleanupTimer = null;
|
|
294
|
+
_reconnectActive = false;
|
|
295
|
+
_reconnectAbort = null;
|
|
296
|
+
_serverKicked = false;
|
|
297
|
+
constructor(config, debug = false) {
|
|
298
|
+
const rawConfig = { ...(config ?? {}) };
|
|
299
|
+
this._configModel = configFromMap(rawConfig);
|
|
300
|
+
this.config = {
|
|
301
|
+
aun_path: this._configModel.aunPath,
|
|
302
|
+
root_ca_path: this._configModel.rootCaPath,
|
|
303
|
+
seed_password: this._configModel.seedPassword,
|
|
304
|
+
};
|
|
305
|
+
this._dispatcher = new EventDispatcher();
|
|
306
|
+
this._discovery = new GatewayDiscovery({ verifySsl: this._configModel.verifySsl });
|
|
307
|
+
const defaultSQLiteBackup = new SQLiteBackup(join(this._configModel.aunPath, '.aun_backup', 'aun_backup.db'));
|
|
308
|
+
const keystore = new FileKeyStore(this._configModel.aunPath, {
|
|
309
|
+
encryptionSeed: this._configModel.seedPassword ?? undefined,
|
|
310
|
+
sqliteBackup: defaultSQLiteBackup,
|
|
311
|
+
});
|
|
312
|
+
this._keystore = keystore;
|
|
313
|
+
this._deviceId = getDeviceId(this._configModel.aunPath);
|
|
314
|
+
// 初始化文件日志(仅 debug 模式)
|
|
315
|
+
if (debug) {
|
|
316
|
+
_debugLogger = new AUNLogger();
|
|
317
|
+
_clientLog('info', 'AUNClient 初始化完成 (debug=true, aunPath=%s)', this._configModel.aunPath);
|
|
318
|
+
}
|
|
319
|
+
this._slotId = '';
|
|
320
|
+
this._connectDeliveryMode = normalizeDeliveryModeConfig({ mode: 'fanout' });
|
|
321
|
+
this._defaultConnectDeliveryMode = { ...this._connectDeliveryMode };
|
|
322
|
+
this._auth = new AuthFlow({
|
|
323
|
+
keystore,
|
|
324
|
+
crypto: new CryptoProvider(),
|
|
325
|
+
aid: null,
|
|
326
|
+
deviceId: this._deviceId,
|
|
327
|
+
slotId: this._slotId,
|
|
328
|
+
rootCaPath: this._configModel.rootCaPath ?? undefined,
|
|
329
|
+
verifySsl: this._configModel.verifySsl,
|
|
330
|
+
});
|
|
331
|
+
this._transport = new RPCTransport({
|
|
332
|
+
eventDispatcher: this._dispatcher,
|
|
333
|
+
timeout: 10_000,
|
|
334
|
+
onDisconnect: (err, closeCode) => this._handleTransportDisconnect(err, closeCode),
|
|
335
|
+
verifySsl: this._configModel.verifySsl,
|
|
336
|
+
});
|
|
337
|
+
this._e2ee = new E2EEManager({
|
|
338
|
+
identityFn: () => this._identity ?? {},
|
|
339
|
+
deviceIdFn: () => this._deviceId,
|
|
340
|
+
keystore,
|
|
341
|
+
replayWindowSeconds: this._configModel.replayWindowSeconds,
|
|
342
|
+
});
|
|
343
|
+
this._groupE2ee = new GroupE2EEManager({
|
|
344
|
+
identityFn: () => this._identity ?? {},
|
|
345
|
+
keystore,
|
|
346
|
+
senderCertResolver: (aid) => this._getVerifiedPeerCert(aid),
|
|
347
|
+
initiatorCertResolver: (aid) => this._getVerifiedPeerCert(aid),
|
|
348
|
+
});
|
|
349
|
+
this.auth = new AuthNamespace(this);
|
|
350
|
+
this.custody = new CustodyNamespace(this);
|
|
351
|
+
// 内部订阅:推送消息自动解密后 re-publish 给用户
|
|
352
|
+
this._dispatcher.subscribe('_raw.message.received', (data) => this._onRawMessageReceived(data));
|
|
353
|
+
// 群组消息推送:自动解密后 re-publish
|
|
354
|
+
this._dispatcher.subscribe('_raw.group.message_created', (data) => this._onRawGroupMessageCreated(data));
|
|
355
|
+
// 群组变更事件:拦截处理成员变更触发的 epoch 轮换,然后透传
|
|
356
|
+
this._dispatcher.subscribe('_raw.group.changed', (data) => this._onRawGroupChanged(data));
|
|
357
|
+
// 其他事件直接透传
|
|
358
|
+
for (const evt of ['message.recalled', 'message.ack']) {
|
|
359
|
+
this._dispatcher.subscribe(`_raw.${evt}`, (data) => this._dispatcher.publish(evt, data));
|
|
360
|
+
}
|
|
361
|
+
// 服务端主动断开通知:记录日志并标记不重连
|
|
362
|
+
this._dispatcher.subscribe('_raw.gateway.disconnect', (data) => this._onGatewayDisconnect(data));
|
|
363
|
+
}
|
|
364
|
+
// ── 属性 ──────────────────────────────────────────────────
|
|
365
|
+
/** 当前 AID */
|
|
366
|
+
get aid() {
|
|
367
|
+
return this._aid;
|
|
368
|
+
}
|
|
369
|
+
/** 连接状态 */
|
|
370
|
+
get state() {
|
|
371
|
+
return this._state;
|
|
372
|
+
}
|
|
373
|
+
/** E2EE 管理器 */
|
|
374
|
+
get e2ee() {
|
|
375
|
+
return this._e2ee;
|
|
376
|
+
}
|
|
377
|
+
/** 群组 E2EE 管理器 */
|
|
378
|
+
get groupE2ee() {
|
|
379
|
+
return this._groupE2ee;
|
|
380
|
+
}
|
|
381
|
+
/** 最近一次 gateway health check 结果,null 表示尚未检查 */
|
|
382
|
+
get gatewayHealth() {
|
|
383
|
+
return this._discovery.lastHealthy;
|
|
384
|
+
}
|
|
385
|
+
/** 向 gatewayUrl 的 /health 端点发送 GET 请求,检查网关可用性 */
|
|
386
|
+
async checkGatewayHealth(gatewayUrl, timeout = 5_000) {
|
|
387
|
+
return this._discovery.checkHealth(gatewayUrl, timeout);
|
|
388
|
+
}
|
|
389
|
+
// ── 生命周期 ──────────────────────────────────────────────
|
|
390
|
+
/**
|
|
391
|
+
* 连接到 Gateway。
|
|
392
|
+
*
|
|
393
|
+
* @param auth - 认证参数(必须包含 access_token 和 gateway)
|
|
394
|
+
* @param options - 会话选项(auto_reconnect、heartbeat_interval 等)
|
|
395
|
+
*/
|
|
396
|
+
async connect(auth, options) {
|
|
397
|
+
if (this._state !== 'idle' && this._state !== 'closed' && this._state !== 'disconnected') {
|
|
398
|
+
throw new StateError(`connect not allowed in state ${this._state}`);
|
|
399
|
+
}
|
|
400
|
+
const params = { ...auth };
|
|
401
|
+
if (options)
|
|
402
|
+
Object.assign(params, options);
|
|
403
|
+
const normalized = this._normalizeConnectParams(params);
|
|
404
|
+
this._sessionParams = normalized;
|
|
405
|
+
this._sessionOptions = this._buildSessionOptions(normalized);
|
|
406
|
+
const callTimeoutSec = this._sessionOptions.timeouts.call;
|
|
407
|
+
this._transport.setTimeout(callTimeoutSec != null ? callTimeoutSec * 1000 : 10_000);
|
|
408
|
+
this._closing = false;
|
|
409
|
+
await this._connectOnce(normalized, false);
|
|
410
|
+
}
|
|
411
|
+
/** 关闭连接 */
|
|
412
|
+
async close() {
|
|
413
|
+
this._closing = true;
|
|
414
|
+
this._saveSeqTrackerState();
|
|
415
|
+
this._stopBackgroundTasks();
|
|
416
|
+
this._stopReconnect();
|
|
417
|
+
if (this._state === 'idle' || this._state === 'closed') {
|
|
418
|
+
const closableKeyStore = this._keystore;
|
|
419
|
+
closableKeyStore.close?.();
|
|
420
|
+
this._state = 'closed';
|
|
421
|
+
this._resetSeqTrackingState();
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
await this._transport.close();
|
|
425
|
+
const closableKeyStore = this._keystore;
|
|
426
|
+
closableKeyStore.close?.();
|
|
427
|
+
this._state = 'closed';
|
|
428
|
+
await this._dispatcher.publish('connection.state', { state: this._state });
|
|
429
|
+
this._resetSeqTrackingState();
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* 断开连接但不关闭客户端(可重新 connect,对齐 Python disconnect)。
|
|
433
|
+
* disconnect 是可恢复的:停止心跳、关闭 WebSocket,但不清理 keystore 等状态。
|
|
434
|
+
*/
|
|
435
|
+
async disconnect() {
|
|
436
|
+
// 若 close() 已在执行中,跳过 disconnect 避免竞态
|
|
437
|
+
if (this._closing)
|
|
438
|
+
return;
|
|
439
|
+
if (this._state !== 'connected' && this._state !== 'reconnecting')
|
|
440
|
+
return;
|
|
441
|
+
this._saveSeqTrackerState();
|
|
442
|
+
this._stopBackgroundTasks();
|
|
443
|
+
this._stopReconnect();
|
|
444
|
+
await this._transport.close();
|
|
445
|
+
this._state = 'disconnected';
|
|
446
|
+
await this._dispatcher.publish('connection.state', { state: this._state });
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* 列出本地所有已存储的身份摘要(仅返回有有效私钥的 AID)。
|
|
450
|
+
*/
|
|
451
|
+
listIdentities() {
|
|
452
|
+
const listFn = this._keystore.listIdentities;
|
|
453
|
+
if (typeof listFn !== 'function')
|
|
454
|
+
return [];
|
|
455
|
+
const aids = listFn.call(this._keystore);
|
|
456
|
+
const summaries = [];
|
|
457
|
+
for (const aid of [...aids].sort()) {
|
|
458
|
+
const identity = this._keystore.loadIdentity(aid);
|
|
459
|
+
if (!identity || !identity.private_key_pem)
|
|
460
|
+
continue;
|
|
461
|
+
const summary = { aid };
|
|
462
|
+
const loadMetadata = this._keystore.loadMetadata;
|
|
463
|
+
if (typeof loadMetadata === 'function') {
|
|
464
|
+
const md = loadMetadata.call(this._keystore, aid);
|
|
465
|
+
if (md)
|
|
466
|
+
summary.metadata = md;
|
|
467
|
+
}
|
|
468
|
+
summaries.push(summary);
|
|
469
|
+
}
|
|
470
|
+
return summaries;
|
|
471
|
+
}
|
|
472
|
+
// ── RPC ───────────────────────────────────────────────────
|
|
473
|
+
/**
|
|
474
|
+
* 发送 JSON-RPC 调用。
|
|
475
|
+
* 自动处理内部方法限制、E2EE 加解密、客户端签名等。
|
|
476
|
+
*/
|
|
477
|
+
async call(method, params) {
|
|
478
|
+
if (this._state !== 'connected') {
|
|
479
|
+
throw new ConnectionError('client is not connected');
|
|
480
|
+
}
|
|
481
|
+
if (INTERNAL_ONLY_METHODS.has(method)) {
|
|
482
|
+
throw new PermissionError(`method is internal_only: ${method}`);
|
|
483
|
+
}
|
|
484
|
+
const p = { ...(params ?? {}) };
|
|
485
|
+
this._validateOutboundCall(method, p);
|
|
486
|
+
this._injectMessageCursorContext(method, p);
|
|
487
|
+
// group.* 方法注入 device_id(服务端用于多设备消息路由)
|
|
488
|
+
if (method.startsWith('group.') && this._deviceId && p.device_id === undefined) {
|
|
489
|
+
p.device_id = this._deviceId;
|
|
490
|
+
}
|
|
491
|
+
if (method.startsWith('group.') && p.slot_id === undefined) {
|
|
492
|
+
p.slot_id = this._slotId;
|
|
493
|
+
}
|
|
494
|
+
// 自动加密:message.send 默认加密(encrypt 默认 True)
|
|
495
|
+
if (method === 'message.send') {
|
|
496
|
+
const encrypt = p.encrypt ?? true;
|
|
497
|
+
delete p.encrypt;
|
|
498
|
+
if (encrypt) {
|
|
499
|
+
return await this._sendEncrypted(p);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
// 自动加密:group.send 默认加密(encrypt 默认 True)
|
|
503
|
+
if (method === 'group.send') {
|
|
504
|
+
const encrypt = p.encrypt ?? true;
|
|
505
|
+
delete p.encrypt;
|
|
506
|
+
if (encrypt) {
|
|
507
|
+
return await this._sendGroupEncrypted(p);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
// 关键操作自动附加客户端签名
|
|
511
|
+
if (SIGNED_METHODS.has(method)) {
|
|
512
|
+
this._signClientOperation(method, p);
|
|
513
|
+
}
|
|
514
|
+
let result = await this._transport.call(method, p);
|
|
515
|
+
// 自动解密:message.pull 返回的消息
|
|
516
|
+
if (method === 'message.pull' && isJsonObject(result)) {
|
|
517
|
+
const r = result;
|
|
518
|
+
const messages = r.messages;
|
|
519
|
+
const rawMessages = Array.isArray(messages) ? messages.filter(isJsonObject) : [];
|
|
520
|
+
if (rawMessages.length > 0) {
|
|
521
|
+
r.messages = await this._decryptMessages(rawMessages);
|
|
522
|
+
}
|
|
523
|
+
if (this._aid) {
|
|
524
|
+
const ns = `p2p:${this._aid}`;
|
|
525
|
+
if (rawMessages.length > 0) {
|
|
526
|
+
this._seqTracker.onPullResult(ns, rawMessages);
|
|
527
|
+
}
|
|
528
|
+
// ⚠️ 逻辑边界 L1/L3:P2P retention floor 通道 = server_ack_seq
|
|
529
|
+
// 服务端在持久化/设备视图分支返回 server_ack_seq,客户端若 contiguous 落后必须 force 跳过
|
|
530
|
+
// retention window 外的空洞。与 S2 [1,seq-1] 历史 gap 配合;若去掉 force,首条消息建的 gap 会
|
|
531
|
+
// 永远悬挂触发无限 pull。临时消息淘汰走 ephemeral_earliest_available_seq(当前仅提示),与此互斥。
|
|
532
|
+
const serverAck = Number(r.server_ack_seq ?? 0);
|
|
533
|
+
if (serverAck > 0) {
|
|
534
|
+
const contig = this._seqTracker.getContiguousSeq(ns);
|
|
535
|
+
if (contig < serverAck) {
|
|
536
|
+
_clientLog('info', 'message.pull retention-floor 推进: ns=%s contiguous=%d -> server_ack_seq=%d', ns, contig, serverAck);
|
|
537
|
+
this._seqTracker.forceContiguousSeq(ns, serverAck);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
this._saveSeqTrackerState();
|
|
541
|
+
// auto-ack contiguous_seq
|
|
542
|
+
const contig = this._seqTracker.getContiguousSeq(ns);
|
|
543
|
+
if (contig > 0 && (rawMessages.length > 0 || serverAck > 0)) {
|
|
544
|
+
this._transport.call('message.ack', {
|
|
545
|
+
seq: contig,
|
|
546
|
+
device_id: this._deviceId,
|
|
547
|
+
}).catch((e) => { _clientLog('debug', 'message.pull auto-ack 失败: %s', formatCaughtError(e)); });
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
// 自动解密:group.pull 返回的群消息
|
|
552
|
+
if (method === 'group.pull' && isJsonObject(result)) {
|
|
553
|
+
const r = result;
|
|
554
|
+
const messages = r.messages;
|
|
555
|
+
const rawMessages = Array.isArray(messages) ? messages.filter(isJsonObject) : [];
|
|
556
|
+
if (rawMessages.length > 0) {
|
|
557
|
+
r.messages = await this._decryptGroupMessages(rawMessages);
|
|
558
|
+
}
|
|
559
|
+
const gid = (p.group_id ?? '');
|
|
560
|
+
if (gid) {
|
|
561
|
+
const ns = `group:${gid}`;
|
|
562
|
+
if (rawMessages.length > 0) {
|
|
563
|
+
this._seqTracker.onPullResult(ns, rawMessages);
|
|
564
|
+
}
|
|
565
|
+
// ⚠️ 逻辑边界 L4:group retention floor 通道 = cursor.current_seq
|
|
566
|
+
// 群路径目前无独立 earliest_available_seq 字段;若未来引入 group retention,需新增字段并同步更新此处。
|
|
567
|
+
// 与 S2 [1,seq-1] 历史 gap 配合使用,force_contiguous_seq 是跳过空洞的唯一手段。
|
|
568
|
+
const cursor = isJsonObject(r.cursor) ? r.cursor : null;
|
|
569
|
+
if (cursor) {
|
|
570
|
+
const serverAck = Number(cursor.current_seq ?? 0);
|
|
571
|
+
if (serverAck > 0) {
|
|
572
|
+
const contig = this._seqTracker.getContiguousSeq(ns);
|
|
573
|
+
if (contig < serverAck) {
|
|
574
|
+
_clientLog('info', 'group.pull retention-floor 推进: ns=%s contiguous=%d -> cursor.current_seq=%d', ns, contig, serverAck);
|
|
575
|
+
this._seqTracker.forceContiguousSeq(ns, serverAck);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
this._saveSeqTrackerState();
|
|
580
|
+
// auto-ack contiguous_seq
|
|
581
|
+
const contig = this._seqTracker.getContiguousSeq(ns);
|
|
582
|
+
const shouldAck = rawMessages.length > 0 || (cursor !== null && Number(cursor.current_seq ?? 0) > 0);
|
|
583
|
+
if (contig > 0 && shouldAck) {
|
|
584
|
+
this._transport.call('group.ack_messages', {
|
|
585
|
+
group_id: gid,
|
|
586
|
+
msg_seq: contig,
|
|
587
|
+
device_id: this._deviceId,
|
|
588
|
+
slot_id: this._slotId,
|
|
589
|
+
}).catch((e) => { _clientLog('debug', 'group.pull auto-ack 失败: group=%s %s', gid, formatCaughtError(e)); });
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
// ── Group E2EE 自动编排(必备能力,始终启用)────────
|
|
594
|
+
{
|
|
595
|
+
// 建群后自动创建 epoch(幂等:已有 secret 时跳过)
|
|
596
|
+
if (method === 'group.create' && isJsonObject(result)) {
|
|
597
|
+
const group = isJsonObject(result.group) ? result.group : null;
|
|
598
|
+
const gid = group ? String(group.group_id ?? '') : '';
|
|
599
|
+
if (gid && this._aid && !this._groupE2ee.hasSecret(gid)) {
|
|
600
|
+
try {
|
|
601
|
+
this._groupE2ee.createEpoch(gid, [this._aid]);
|
|
602
|
+
// 同步到服务端:将服务端 epoch 从 0 推到 1;必须在 group.create 返回前完成,
|
|
603
|
+
// 否则调用方紧接着加成员时会让初始 rotation 因成员集变化而提交失败。
|
|
604
|
+
await this._syncEpochToServer(gid);
|
|
605
|
+
}
|
|
606
|
+
catch (exc) {
|
|
607
|
+
this._logE2eeError('create_epoch', gid, '', exc);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
// 入群类 RPC 的成员集变更统一由 group.changed 事件驱动 epoch 轮换。
|
|
612
|
+
}
|
|
613
|
+
// 成员集变更主要由 group.changed 事件驱动;RPC 成功返回路径做幂等兜底,避免事件丢失或延迟时不轮换。
|
|
614
|
+
const membershipMethods = new Set([
|
|
615
|
+
'group.add_member', 'group.kick', 'group.remove_member', 'group.leave',
|
|
616
|
+
'group.review_join_request', 'group.batch_review_join_request',
|
|
617
|
+
'group.use_invite_code', 'group.request_join',
|
|
618
|
+
]);
|
|
619
|
+
if (membershipMethods.has(method) && isJsonObject(result) && !('error' in result)) {
|
|
620
|
+
const groupId = this._extractGroupIdFromResult(result) || String(p.group_id ?? '');
|
|
621
|
+
if (groupId && this._membershipRotationChanged(method, result)) {
|
|
622
|
+
const expectedEpoch = this._membershipRotationExpectedEpoch(result);
|
|
623
|
+
this._maybeLeadRotateGroupEpoch(groupId, this._membershipRotationTriggerId(groupId, result), expectedEpoch).catch((exc) => _clientLog('warn', 'membership RPC epoch rotation fallback failed: %s', formatCaughtError(exc)));
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
return result;
|
|
627
|
+
}
|
|
628
|
+
// ── 便利方法 ──────────────────────────────────────────────
|
|
629
|
+
/** 心跳检测 */
|
|
630
|
+
async ping(params) {
|
|
631
|
+
return await this.call('meta.ping', params ?? {});
|
|
632
|
+
}
|
|
633
|
+
/** 获取服务端状态 */
|
|
634
|
+
async status(params) {
|
|
635
|
+
return await this.call('meta.status', params ?? {});
|
|
636
|
+
}
|
|
637
|
+
/** 获取信任根证书列表 */
|
|
638
|
+
async trustRoots(params) {
|
|
639
|
+
return await this.call('meta.trust_roots', params ?? {});
|
|
640
|
+
}
|
|
641
|
+
// ── 事件 ──────────────────────────────────────────────────
|
|
642
|
+
/** 订阅事件 */
|
|
643
|
+
on(event, handler) {
|
|
644
|
+
return this._dispatcher.subscribe(event, handler);
|
|
645
|
+
}
|
|
646
|
+
// ── E2EE 加密发送 ────────────────────────────────────────
|
|
647
|
+
/** 自动加密并发送 P2P 消息 */
|
|
648
|
+
async _sendEncrypted(params) {
|
|
649
|
+
const toAid = String(params.to ?? '');
|
|
650
|
+
this._validateMessageRecipient(toAid);
|
|
651
|
+
const payload = isJsonObject(params.payload) ? params.payload : null;
|
|
652
|
+
const messageId = String(params.message_id ?? '') || crypto.randomUUID();
|
|
653
|
+
const timestamp = params.timestamp ?? Date.now();
|
|
654
|
+
if (payload === null) {
|
|
655
|
+
throw new ValidationError('message.send payload must be an object when encrypt=true');
|
|
656
|
+
}
|
|
657
|
+
const persistRequired = Boolean(params.persist_required || params.durable);
|
|
658
|
+
// 惰性同步:首次发送 P2P 消息时先 pull 一次
|
|
659
|
+
if (!this._p2pSynced) {
|
|
660
|
+
await this._lazySyncP2p();
|
|
661
|
+
}
|
|
662
|
+
const recipientPrekeys = await this._fetchPeerPrekeys(toAid);
|
|
663
|
+
const selfSyncCopies = await this._buildSelfSyncCopies({
|
|
664
|
+
logicalToAid: toAid,
|
|
665
|
+
payload,
|
|
666
|
+
messageId,
|
|
667
|
+
timestamp,
|
|
668
|
+
});
|
|
669
|
+
if (recipientPrekeys.length <= 1 && selfSyncCopies.length === 0) {
|
|
670
|
+
return await this._sendEncryptedSingle({
|
|
671
|
+
toAid,
|
|
672
|
+
payload,
|
|
673
|
+
messageId,
|
|
674
|
+
timestamp,
|
|
675
|
+
prekey: recipientPrekeys[0],
|
|
676
|
+
persistRequired,
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
const recipientCopies = await this._buildRecipientDeviceCopies({
|
|
680
|
+
toAid,
|
|
681
|
+
payload,
|
|
682
|
+
messageId,
|
|
683
|
+
timestamp,
|
|
684
|
+
prekeys: recipientPrekeys,
|
|
685
|
+
});
|
|
686
|
+
const sendParams = {
|
|
687
|
+
to: toAid,
|
|
688
|
+
payload: {
|
|
689
|
+
type: 'e2ee.multi_device',
|
|
690
|
+
logical_message_id: messageId,
|
|
691
|
+
recipient_copies: recipientCopies,
|
|
692
|
+
self_copies: selfSyncCopies,
|
|
693
|
+
},
|
|
694
|
+
type: 'e2ee.multi_device',
|
|
695
|
+
encrypted: true,
|
|
696
|
+
message_id: messageId,
|
|
697
|
+
timestamp,
|
|
698
|
+
};
|
|
699
|
+
if (persistRequired) {
|
|
700
|
+
sendParams.persist_required = true;
|
|
701
|
+
}
|
|
702
|
+
return await this._transport.call('message.send', sendParams);
|
|
703
|
+
}
|
|
704
|
+
async _sendEncryptedSingle(opts) {
|
|
705
|
+
let prekey = opts.prekey ?? null;
|
|
706
|
+
if (!prekey) {
|
|
707
|
+
prekey = await this._fetchPeerPrekey(opts.toAid);
|
|
708
|
+
}
|
|
709
|
+
const peerCertFingerprint = typeof prekey?.cert_fingerprint === 'string' ? prekey.cert_fingerprint : undefined;
|
|
710
|
+
const peerCertPem = await this._fetchPeerCert(opts.toAid, peerCertFingerprint);
|
|
711
|
+
const [envelope, encryptResult] = this._encryptCopyPayload({
|
|
712
|
+
logicalToAid: opts.toAid,
|
|
713
|
+
payload: opts.payload,
|
|
714
|
+
peerCertPem,
|
|
715
|
+
prekey,
|
|
716
|
+
messageId: opts.messageId,
|
|
717
|
+
timestamp: opts.timestamp,
|
|
718
|
+
});
|
|
719
|
+
this._ensureEncryptResult(opts.toAid, encryptResult);
|
|
720
|
+
const sendParams = {
|
|
721
|
+
to: opts.toAid,
|
|
722
|
+
payload: envelope,
|
|
723
|
+
type: 'e2ee.encrypted',
|
|
724
|
+
encrypted: true,
|
|
725
|
+
message_id: opts.messageId,
|
|
726
|
+
timestamp: opts.timestamp,
|
|
727
|
+
};
|
|
728
|
+
if (opts.persistRequired) {
|
|
729
|
+
sendParams.persist_required = true;
|
|
730
|
+
}
|
|
731
|
+
return await this._transport.call('message.send', sendParams);
|
|
732
|
+
}
|
|
733
|
+
async _buildRecipientDeviceCopies(opts) {
|
|
734
|
+
const recipientCopies = [];
|
|
735
|
+
const certCache = new Map();
|
|
736
|
+
for (const prekey of opts.prekeys) {
|
|
737
|
+
const deviceId = String(prekey.device_id ?? '').trim();
|
|
738
|
+
const peerCertFingerprint = String(prekey.cert_fingerprint ?? '').trim().toLowerCase();
|
|
739
|
+
const cacheKey = peerCertFingerprint || '__default__';
|
|
740
|
+
let peerCertPem = certCache.get(cacheKey);
|
|
741
|
+
if (!peerCertPem) {
|
|
742
|
+
peerCertPem = await this._fetchPeerCert(opts.toAid, peerCertFingerprint || undefined);
|
|
743
|
+
certCache.set(cacheKey, peerCertPem);
|
|
744
|
+
}
|
|
745
|
+
const [envelope, encryptResult] = this._encryptCopyPayload({
|
|
746
|
+
logicalToAid: opts.toAid,
|
|
747
|
+
payload: opts.payload,
|
|
748
|
+
peerCertPem,
|
|
749
|
+
prekey,
|
|
750
|
+
messageId: opts.messageId,
|
|
751
|
+
timestamp: opts.timestamp,
|
|
752
|
+
});
|
|
753
|
+
this._ensureEncryptResult(opts.toAid, encryptResult);
|
|
754
|
+
recipientCopies.push({
|
|
755
|
+
device_id: deviceId,
|
|
756
|
+
envelope,
|
|
757
|
+
});
|
|
758
|
+
}
|
|
759
|
+
if (recipientCopies.length === 0) {
|
|
760
|
+
throw new E2EEError(`no recipient device copies generated for ${opts.toAid}`);
|
|
761
|
+
}
|
|
762
|
+
return recipientCopies;
|
|
763
|
+
}
|
|
764
|
+
async _resolveSelfCopyPeerCert(certFingerprint) {
|
|
765
|
+
const myAid = this._aid;
|
|
766
|
+
if (!myAid) {
|
|
767
|
+
throw new E2EEError('self sync copy requires current aid');
|
|
768
|
+
}
|
|
769
|
+
const normalizedFingerprint = String(certFingerprint ?? '').trim().toLowerCase();
|
|
770
|
+
const identityCert = typeof this._identity?.cert === 'string' ? this._identity.cert : '';
|
|
771
|
+
if (identityCert) {
|
|
772
|
+
const identityFingerprint = `sha256:${new crypto.X509Certificate(identityCert).fingerprint256.replace(/:/g, '').toLowerCase()}`;
|
|
773
|
+
if (!normalizedFingerprint || identityFingerprint === normalizedFingerprint) {
|
|
774
|
+
return identityCert;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
const localCert = this._keystore.loadCert(myAid, normalizedFingerprint || undefined);
|
|
778
|
+
if (localCert) {
|
|
779
|
+
if (!normalizedFingerprint) {
|
|
780
|
+
return localCert;
|
|
781
|
+
}
|
|
782
|
+
const actualFingerprint = `sha256:${new crypto.X509Certificate(localCert).fingerprint256.replace(/:/g, '').toLowerCase()}`;
|
|
783
|
+
if (actualFingerprint === normalizedFingerprint) {
|
|
784
|
+
return localCert;
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
return await this._fetchPeerCert(myAid, normalizedFingerprint || undefined);
|
|
788
|
+
}
|
|
789
|
+
async _buildSelfSyncCopies(opts) {
|
|
790
|
+
const myAid = this._aid;
|
|
791
|
+
if (!myAid) {
|
|
792
|
+
return [];
|
|
793
|
+
}
|
|
794
|
+
const prekeys = await this._fetchPeerPrekeys(myAid);
|
|
795
|
+
if (prekeys.length === 0) {
|
|
796
|
+
return [];
|
|
797
|
+
}
|
|
798
|
+
const copies = [];
|
|
799
|
+
for (const prekey of prekeys) {
|
|
800
|
+
const deviceId = String(prekey.device_id ?? '').trim();
|
|
801
|
+
if (deviceId === this._deviceId) {
|
|
802
|
+
continue;
|
|
803
|
+
}
|
|
804
|
+
const peerCertPem = await this._resolveSelfCopyPeerCert(String(prekey.cert_fingerprint ?? '').trim().toLowerCase() || undefined);
|
|
805
|
+
const [envelope, encryptResult] = this._encryptCopyPayload({
|
|
806
|
+
logicalToAid: opts.logicalToAid,
|
|
807
|
+
payload: opts.payload,
|
|
808
|
+
peerCertPem,
|
|
809
|
+
prekey,
|
|
810
|
+
messageId: opts.messageId,
|
|
811
|
+
timestamp: opts.timestamp,
|
|
812
|
+
});
|
|
813
|
+
this._ensureEncryptResult(myAid, encryptResult);
|
|
814
|
+
copies.push({
|
|
815
|
+
device_id: deviceId,
|
|
816
|
+
envelope,
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
return copies;
|
|
820
|
+
}
|
|
821
|
+
_encryptCopyPayload(opts) {
|
|
822
|
+
const [envelope, encryptResult] = this._e2ee.encryptOutbound(opts.logicalToAid, opts.payload, opts.peerCertPem, opts.prekey ?? null, opts.messageId, opts.timestamp);
|
|
823
|
+
return [envelope, encryptResult];
|
|
824
|
+
}
|
|
825
|
+
_ensureEncryptResult(toAid, encryptResult) {
|
|
826
|
+
if (!encryptResult.encrypted) {
|
|
827
|
+
throw new E2EEError(`failed to encrypt message to ${toAid}`);
|
|
828
|
+
}
|
|
829
|
+
if (this._configModel.requireForwardSecrecy && !encryptResult.forward_secrecy) {
|
|
830
|
+
throw new E2EEError(`forward secrecy required but unavailable for ${toAid} ` +
|
|
831
|
+
`(mode=${encryptResult.mode})`);
|
|
832
|
+
}
|
|
833
|
+
if (encryptResult.degraded) {
|
|
834
|
+
this._dispatcher.publish('e2ee.degraded', {
|
|
835
|
+
peer_aid: toAid,
|
|
836
|
+
mode: encryptResult.mode,
|
|
837
|
+
reason: encryptResult.degradation_reason,
|
|
838
|
+
}).catch((exc) => {
|
|
839
|
+
_clientLog('warn', '发布 e2ee.degraded 事件失败: %s', formatCaughtError(exc));
|
|
840
|
+
});
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
/** 自动加密并发送群组消息 */
|
|
844
|
+
async _sendGroupEncrypted(params) {
|
|
845
|
+
const groupId = String(params.group_id ?? '');
|
|
846
|
+
const payload = isJsonObject(params.payload) ? params.payload : null;
|
|
847
|
+
if (!groupId) {
|
|
848
|
+
throw new ValidationError('group.send requires group_id');
|
|
849
|
+
}
|
|
850
|
+
if (payload === null) {
|
|
851
|
+
throw new ValidationError('group.send payload must be an object when encrypt=true');
|
|
852
|
+
}
|
|
853
|
+
// 惰性同步:首次发送该群消息时先 pull 一次
|
|
854
|
+
if (!this._groupSynced.has(groupId)) {
|
|
855
|
+
await this._lazySyncGroup(groupId);
|
|
856
|
+
}
|
|
857
|
+
await this._ensureGroupEpochReady(groupId, false);
|
|
858
|
+
await this._waitForGroupMembershipEpochFloor(groupId, 2000);
|
|
859
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
860
|
+
const epochResult = await this._committedGroupEpochState(groupId);
|
|
861
|
+
const committedEpoch = Number(epochResult.committed_epoch ?? epochResult.epoch ?? 0);
|
|
862
|
+
const envelope = committedEpoch > 0
|
|
863
|
+
? this._groupE2ee.encryptWithEpoch(groupId, await this._ensureCommittedGroupSecretForSend(groupId, committedEpoch, epochResult), payload)
|
|
864
|
+
: await this._groupE2ee.encrypt(groupId, payload);
|
|
865
|
+
const sendParams = {
|
|
866
|
+
group_id: groupId,
|
|
867
|
+
payload: envelope,
|
|
868
|
+
type: 'e2ee.group_encrypted',
|
|
869
|
+
encrypted: true,
|
|
870
|
+
};
|
|
871
|
+
if (this._deviceId && sendParams.device_id === undefined) {
|
|
872
|
+
sendParams.device_id = this._deviceId;
|
|
873
|
+
}
|
|
874
|
+
await this._signClientOperation('group.send', sendParams);
|
|
875
|
+
try {
|
|
876
|
+
return await this._transport.call('group.send', sendParams);
|
|
877
|
+
}
|
|
878
|
+
catch (exc) {
|
|
879
|
+
if (attempt === 0 && this._isRecoverableGroupEpochError(exc)) {
|
|
880
|
+
_clientLog('warn', '群 %s 发送时 epoch 已过旧,恢复密钥后重加密重发一次: %s', groupId, formatCaughtError(exc));
|
|
881
|
+
await this._ensureGroupEpochReady(groupId, true);
|
|
882
|
+
continue;
|
|
883
|
+
}
|
|
884
|
+
throw exc;
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
throw new StateError(`group ${groupId} send failed after epoch recovery retry`);
|
|
888
|
+
}
|
|
889
|
+
/** 惰性同步:首次激活群时 pull 最近消息,建立 seq 基线 */
|
|
890
|
+
async _lazySyncGroup(groupId) {
|
|
891
|
+
this._groupSynced.add(groupId);
|
|
892
|
+
try {
|
|
893
|
+
const ns = `group:${groupId}`;
|
|
894
|
+
const afterSeq = this._seqTracker.getContiguousSeq(ns);
|
|
895
|
+
const result = await this._transport.call('group.pull', {
|
|
896
|
+
group_id: groupId,
|
|
897
|
+
after_message_seq: afterSeq,
|
|
898
|
+
limit: 200,
|
|
899
|
+
});
|
|
900
|
+
const messages = Array.isArray(result?.messages) ? result.messages : [];
|
|
901
|
+
for (const msg of messages) {
|
|
902
|
+
const seq = msg?.seq;
|
|
903
|
+
if (seq != null)
|
|
904
|
+
this._seqTracker.onMessageSeq(ns, Number(seq));
|
|
905
|
+
}
|
|
906
|
+
if (messages.length > 0) {
|
|
907
|
+
this._saveSeqTrackerState();
|
|
908
|
+
_clientLog('info', '惰性同步群 %s: pull %d 条消息, after_seq=%d', groupId, messages.length, afterSeq);
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
catch (exc) {
|
|
912
|
+
_clientLog('warn', '惰性同步群 %s 失败: %s', groupId, formatCaughtError(exc));
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
/** 惰性同步:首次激活 P2P 通道时 pull 最近消息,建立 seq 基线 */
|
|
916
|
+
async _lazySyncP2p() {
|
|
917
|
+
this._p2pSynced = true;
|
|
918
|
+
if (!this._aid)
|
|
919
|
+
return;
|
|
920
|
+
try {
|
|
921
|
+
const ns = `p2p:${this._aid}`;
|
|
922
|
+
const afterSeq = this._seqTracker.getContiguousSeq(ns);
|
|
923
|
+
const result = await this._transport.call('message.pull', {
|
|
924
|
+
after_seq: afterSeq,
|
|
925
|
+
limit: 200,
|
|
926
|
+
});
|
|
927
|
+
const messages = Array.isArray(result?.messages) ? result.messages : [];
|
|
928
|
+
for (const msg of messages) {
|
|
929
|
+
const seq = msg?.seq;
|
|
930
|
+
if (seq != null)
|
|
931
|
+
this._seqTracker.onMessageSeq(ns, Number(seq));
|
|
932
|
+
}
|
|
933
|
+
if (messages.length > 0) {
|
|
934
|
+
this._saveSeqTrackerState();
|
|
935
|
+
_clientLog('info', '惰性同步 P2P: pull %d 条消息, after_seq=%d', messages.length, afterSeq);
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
catch (exc) {
|
|
939
|
+
_clientLog('warn', '惰性同步 P2P 失败: %s', formatCaughtError(exc));
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
_isGroupEpochTooOldError(exc) {
|
|
943
|
+
const text = String(exc).toLowerCase();
|
|
944
|
+
return text.includes('e2ee epoch too old') || text.includes('epoch below sender membership floor');
|
|
945
|
+
}
|
|
946
|
+
_isGroupEpochRotationPendingError(exc) {
|
|
947
|
+
const text = String(exc).toLowerCase();
|
|
948
|
+
return text.includes('e2ee epoch rotation pending') || text.includes('e2ee epoch not committed');
|
|
949
|
+
}
|
|
950
|
+
_isGroupEpochChangedDuringSendError(exc) {
|
|
951
|
+
return String(exc).toLowerCase().includes('e2ee epoch changed during send');
|
|
952
|
+
}
|
|
953
|
+
_isRecoverableGroupEpochError(exc) {
|
|
954
|
+
return this._isGroupEpochTooOldError(exc)
|
|
955
|
+
|| this._isGroupEpochRotationPendingError(exc)
|
|
956
|
+
|| this._isGroupEpochChangedDuringSendError(exc);
|
|
957
|
+
}
|
|
958
|
+
_groupKeyRecoveryCandidates(groupId, epochResult) {
|
|
959
|
+
const candidates = [];
|
|
960
|
+
const add = (value) => {
|
|
961
|
+
if (typeof value !== 'string')
|
|
962
|
+
return;
|
|
963
|
+
const aid = value.trim();
|
|
964
|
+
if (aid && aid !== this._aid && !candidates.includes(aid))
|
|
965
|
+
candidates.push(aid);
|
|
966
|
+
};
|
|
967
|
+
add(epochResult.rotated_by);
|
|
968
|
+
add(epochResult.owner_aid);
|
|
969
|
+
for (const key of ['recovery_candidates', 'admins', 'members']) {
|
|
970
|
+
const values = epochResult[key];
|
|
971
|
+
if (Array.isArray(values)) {
|
|
972
|
+
for (const value of values) {
|
|
973
|
+
if (typeof value === 'string')
|
|
974
|
+
add(value);
|
|
975
|
+
else if (isJsonObject(value))
|
|
976
|
+
add(value.aid);
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
const localMembers = this._groupE2ee.getMemberAids(groupId);
|
|
981
|
+
for (const aid of localMembers)
|
|
982
|
+
add(aid);
|
|
983
|
+
return candidates;
|
|
984
|
+
}
|
|
985
|
+
async _requestGroupKeyFrom(groupId, targetAid, epoch = 0) {
|
|
986
|
+
try {
|
|
987
|
+
const reqPayload = buildKeyRequest(groupId, epoch, this._aid || '');
|
|
988
|
+
this._groupE2ee.rememberKeyRequest(reqPayload, targetAid);
|
|
989
|
+
await this.call('message.send', {
|
|
990
|
+
to: targetAid,
|
|
991
|
+
payload: reqPayload,
|
|
992
|
+
encrypt: true,
|
|
993
|
+
persist_required: true,
|
|
994
|
+
});
|
|
995
|
+
_clientLog('info', '已向 %s 请求群 %s 的 epoch %s 密钥', targetAid, groupId, epoch);
|
|
996
|
+
}
|
|
997
|
+
catch (exc) {
|
|
998
|
+
_clientLog('warn', '向 %s 请求群 %s 密钥失败: %s', targetAid, groupId, formatCaughtError(exc));
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
async _requestGroupKeyFromCandidates(groupId, serverEpoch, epochResult) {
|
|
1002
|
+
for (const targetAid of this._groupKeyRecoveryCandidates(groupId, epochResult)) {
|
|
1003
|
+
await this._requestGroupKeyFrom(groupId, targetAid, serverEpoch);
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
async _recoverInitialGroupEpochIfNeeded(groupId, localEpoch, epochResult) {
|
|
1007
|
+
const serverEpoch = Number(epochResult.epoch ?? 0);
|
|
1008
|
+
if (serverEpoch !== 0 || localEpoch !== 1)
|
|
1009
|
+
return epochResult;
|
|
1010
|
+
const secretData = this._groupE2ee.loadSecret(groupId, 1);
|
|
1011
|
+
if (!secretData || secretData.pending_rotation_id)
|
|
1012
|
+
return epochResult;
|
|
1013
|
+
_clientLog('warn', '群 %s 检测到本地 epoch 1 已存在但服务端 epoch 仍为 0,尝试补同步初始 epoch', groupId);
|
|
1014
|
+
await this._syncEpochToServer(groupId);
|
|
1015
|
+
try {
|
|
1016
|
+
const refreshed = await this.call('group.e2ee.get_epoch', { group_id: groupId });
|
|
1017
|
+
if (isJsonObject(refreshed))
|
|
1018
|
+
return refreshed;
|
|
1019
|
+
}
|
|
1020
|
+
catch (exc) {
|
|
1021
|
+
_clientLog('warn', '群 %s 初始 epoch 补同步后刷新服务端 epoch 失败: %s', groupId, formatCaughtError(exc));
|
|
1022
|
+
}
|
|
1023
|
+
return epochResult;
|
|
1024
|
+
}
|
|
1025
|
+
async _ensureGroupEpochReady(groupId, strict) {
|
|
1026
|
+
const localEpoch = await this._groupE2ee.currentEpoch(groupId);
|
|
1027
|
+
const initialLocalEpoch = localEpoch ?? 0;
|
|
1028
|
+
let epochResult;
|
|
1029
|
+
try {
|
|
1030
|
+
const rawEpochResult = await this.call('group.e2ee.get_epoch', { group_id: groupId });
|
|
1031
|
+
if (!isJsonObject(rawEpochResult))
|
|
1032
|
+
return;
|
|
1033
|
+
epochResult = rawEpochResult;
|
|
1034
|
+
}
|
|
1035
|
+
catch (exc) {
|
|
1036
|
+
if (strict)
|
|
1037
|
+
throw new StateError(`group ${groupId} failed to query server epoch before retry: ${formatCaughtError(exc)}`);
|
|
1038
|
+
_clientLog('warn', 'group %s epoch precheck failed: %s', groupId, formatCaughtError(exc));
|
|
1039
|
+
return;
|
|
1040
|
+
}
|
|
1041
|
+
let serverEpoch = Number(epochResult.epoch ?? 0);
|
|
1042
|
+
if (!Number.isFinite(serverEpoch))
|
|
1043
|
+
return;
|
|
1044
|
+
const pending = isJsonObject(epochResult.pending_rotation) ? epochResult.pending_rotation : null;
|
|
1045
|
+
if (pending && !pending.expired) {
|
|
1046
|
+
const pendingBaseEpoch = Number(pending.base_epoch ?? serverEpoch);
|
|
1047
|
+
this._scheduleGroupRotationRetry(groupId, {
|
|
1048
|
+
reason: 'pending_recovery',
|
|
1049
|
+
triggerId: String(pending.rotation_id ?? ''),
|
|
1050
|
+
expectedEpoch: Number.isFinite(pendingBaseEpoch) ? pendingBaseEpoch : serverEpoch,
|
|
1051
|
+
pending,
|
|
1052
|
+
});
|
|
1053
|
+
}
|
|
1054
|
+
let effectiveLocalEpoch = initialLocalEpoch;
|
|
1055
|
+
if (serverEpoch === 0 && effectiveLocalEpoch === 1) {
|
|
1056
|
+
epochResult = await this._recoverInitialGroupEpochIfNeeded(groupId, effectiveLocalEpoch, epochResult);
|
|
1057
|
+
serverEpoch = Number(epochResult.epoch ?? 0);
|
|
1058
|
+
if (serverEpoch === 0) {
|
|
1059
|
+
throw new StateError(`group ${groupId} initial epoch sync has not completed; refuse to send with local epoch 1 while server epoch is 0`);
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
if (serverEpoch <= effectiveLocalEpoch) {
|
|
1063
|
+
if (!strict || serverEpoch <= 0)
|
|
1064
|
+
return;
|
|
1065
|
+
const waitDeadline = Date.now() + 5000;
|
|
1066
|
+
while (Date.now() < waitDeadline) {
|
|
1067
|
+
await new Promise(resolve => setTimeout(resolve, 150));
|
|
1068
|
+
const refreshed = await this.call('group.e2ee.get_epoch', { group_id: groupId });
|
|
1069
|
+
const refreshedEpoch = isJsonObject(refreshed) ? Number(refreshed.epoch ?? 0) : 0;
|
|
1070
|
+
const currentLocal = await this._groupE2ee.currentEpoch(groupId);
|
|
1071
|
+
if (Number.isFinite(refreshedEpoch) && refreshedEpoch > serverEpoch) {
|
|
1072
|
+
epochResult = refreshed;
|
|
1073
|
+
serverEpoch = refreshedEpoch;
|
|
1074
|
+
effectiveLocalEpoch = currentLocal ?? 0;
|
|
1075
|
+
break;
|
|
1076
|
+
}
|
|
1077
|
+
if (currentLocal !== null && currentLocal > effectiveLocalEpoch)
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
1080
|
+
if (serverEpoch <= effectiveLocalEpoch) {
|
|
1081
|
+
throw new StateError(`group ${groupId} epoch rotation has not completed`);
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
_clientLog('warn', 'group %s local epoch=%s < server epoch=%s; requesting key recovery', groupId, effectiveLocalEpoch, serverEpoch);
|
|
1085
|
+
await this._requestGroupKeyFromCandidates(groupId, serverEpoch, epochResult);
|
|
1086
|
+
const deadline = Date.now() + 5000;
|
|
1087
|
+
while (Date.now() < deadline) {
|
|
1088
|
+
await new Promise(resolve => setTimeout(resolve, 150));
|
|
1089
|
+
const refreshedEpoch = await this._groupE2ee.currentEpoch(groupId);
|
|
1090
|
+
if (refreshedEpoch !== null && refreshedEpoch >= serverEpoch)
|
|
1091
|
+
return;
|
|
1092
|
+
}
|
|
1093
|
+
const refreshedEpoch = await this._groupE2ee.currentEpoch(groupId);
|
|
1094
|
+
throw new StateError(`group ${groupId} local epoch ${refreshedEpoch} is behind server epoch ${serverEpoch}; key recovery has not completed`);
|
|
1095
|
+
}
|
|
1096
|
+
async _waitForGroupMembershipEpochFloor(groupId, timeoutMs) {
|
|
1097
|
+
void timeoutMs;
|
|
1098
|
+
while (true) {
|
|
1099
|
+
let committedEpoch = 0;
|
|
1100
|
+
let members = null;
|
|
1101
|
+
try {
|
|
1102
|
+
const epochResult = await this.call('group.e2ee.get_epoch', { group_id: groupId });
|
|
1103
|
+
committedEpoch = isJsonObject(epochResult) ? Number(epochResult.committed_epoch ?? epochResult.epoch ?? 0) : 0;
|
|
1104
|
+
const membersResult = await this.call('group.get_members', { group_id: groupId });
|
|
1105
|
+
members = isJsonObject(membersResult) ? membersResult.members : null;
|
|
1106
|
+
}
|
|
1107
|
+
catch (exc) {
|
|
1108
|
+
_clientLog('debug', '群 %s 成员 epoch floor 预检跳过: %s', groupId, formatCaughtError(exc));
|
|
1109
|
+
return;
|
|
1110
|
+
}
|
|
1111
|
+
let maxMinReadEpoch = 0;
|
|
1112
|
+
if (Array.isArray(members)) {
|
|
1113
|
+
for (const member of members) {
|
|
1114
|
+
if (!isJsonObject(member))
|
|
1115
|
+
continue;
|
|
1116
|
+
const value = Number(member.min_read_epoch ?? 0);
|
|
1117
|
+
if (Number.isFinite(value))
|
|
1118
|
+
maxMinReadEpoch = Math.max(maxMinReadEpoch, value);
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
if (maxMinReadEpoch <= committedEpoch)
|
|
1122
|
+
return;
|
|
1123
|
+
_clientLog('warn', '群 %s 成员 min_read_epoch 高于 committed epoch,按 committed epoch 继续发送: committed=%s floor=%s', groupId, committedEpoch, maxMinReadEpoch);
|
|
1124
|
+
return;
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
async _committedGroupEpochState(groupId) {
|
|
1128
|
+
try {
|
|
1129
|
+
const epochResult = await this.call('group.e2ee.get_epoch', { group_id: groupId });
|
|
1130
|
+
if (isJsonObject(epochResult))
|
|
1131
|
+
return epochResult;
|
|
1132
|
+
}
|
|
1133
|
+
catch (exc) {
|
|
1134
|
+
_clientLog('warn', '群 %s 查询 committed epoch 状态失败,回退本地 epoch: %s', groupId, formatCaughtError(exc));
|
|
1135
|
+
}
|
|
1136
|
+
const localEpoch = await this._groupE2ee.currentEpoch(groupId);
|
|
1137
|
+
return { epoch: localEpoch ?? 0, committed_epoch: localEpoch ?? 0 };
|
|
1138
|
+
}
|
|
1139
|
+
_groupSecretMatchesCommittedRotation(secretData, committedRotation) {
|
|
1140
|
+
if (!secretData)
|
|
1141
|
+
return false;
|
|
1142
|
+
const committedCommitment = committedRotation ? String(committedRotation.key_commitment ?? '').trim() : '';
|
|
1143
|
+
const localCommitment = String(secretData.commitment ?? '').trim();
|
|
1144
|
+
if (committedCommitment && committedCommitment !== localCommitment)
|
|
1145
|
+
return false;
|
|
1146
|
+
const pendingRotationId = String(secretData.pending_rotation_id ?? '').trim();
|
|
1147
|
+
if (!pendingRotationId)
|
|
1148
|
+
return true;
|
|
1149
|
+
if (!committedRotation)
|
|
1150
|
+
return false;
|
|
1151
|
+
if (String(committedRotation.rotation_id ?? '').trim() !== pendingRotationId)
|
|
1152
|
+
return false;
|
|
1153
|
+
return true;
|
|
1154
|
+
}
|
|
1155
|
+
async _ensureCommittedGroupSecretForSend(groupId, committedEpoch, epochResult) {
|
|
1156
|
+
if (committedEpoch <= 0)
|
|
1157
|
+
return committedEpoch;
|
|
1158
|
+
const secretData = await this._groupE2ee.loadSecret(groupId, committedEpoch);
|
|
1159
|
+
const committedRotation = isJsonObject(epochResult.committed_rotation) ? epochResult.committed_rotation : null;
|
|
1160
|
+
if (this._groupSecretMatchesCommittedRotation(secretData, committedRotation)) {
|
|
1161
|
+
return committedEpoch;
|
|
1162
|
+
}
|
|
1163
|
+
const pendingRotationId = secretData ? String(secretData.pending_rotation_id ?? '') : '';
|
|
1164
|
+
_clientLog('warn', '群 %s epoch %s 本地 pending key 未匹配服务端 committed rotation,先恢复密钥: local_rotation=%s', groupId, committedEpoch, pendingRotationId || '-');
|
|
1165
|
+
await this._recoverGroupEpochKey(groupId, committedEpoch, '', 5000);
|
|
1166
|
+
let refreshed = await this._committedGroupEpochState(groupId);
|
|
1167
|
+
const refreshedCommittedEpoch = Number(refreshed.committed_epoch ?? refreshed.epoch ?? committedEpoch);
|
|
1168
|
+
if (Number.isFinite(refreshedCommittedEpoch) && refreshedCommittedEpoch > committedEpoch) {
|
|
1169
|
+
committedEpoch = refreshedCommittedEpoch;
|
|
1170
|
+
await this._recoverGroupEpochKey(groupId, committedEpoch, '', 5000);
|
|
1171
|
+
refreshed = await this._committedGroupEpochState(groupId);
|
|
1172
|
+
}
|
|
1173
|
+
const refreshedRotation = isJsonObject(refreshed.committed_rotation) ? refreshed.committed_rotation : null;
|
|
1174
|
+
const refreshedSecret = await this._groupE2ee.loadSecret(groupId, committedEpoch);
|
|
1175
|
+
if (!this._groupSecretMatchesCommittedRotation(refreshedSecret, refreshedRotation)) {
|
|
1176
|
+
throw new StateError(`group ${groupId} epoch ${committedEpoch} local key is pending or mismatched; refuse to send with uncommitted group key`);
|
|
1177
|
+
}
|
|
1178
|
+
return committedEpoch;
|
|
1179
|
+
}
|
|
1180
|
+
// ── 客户端签名 ────────────────────────────────────────────
|
|
1181
|
+
/**
|
|
1182
|
+
* 为关键操作附加客户端 ECDSA 签名(client_signature 字段)。
|
|
1183
|
+
* 签名覆盖所有非 _ 前缀且非 client_signature 的业务字段。
|
|
1184
|
+
*/
|
|
1185
|
+
_signClientOperation(method, params) {
|
|
1186
|
+
const identity = this._identity;
|
|
1187
|
+
if (!identity || !identity.private_key_pem)
|
|
1188
|
+
return;
|
|
1189
|
+
try {
|
|
1190
|
+
const aid = String(identity.aid ?? '');
|
|
1191
|
+
const ts = String(Math.floor(Date.now() / 1000));
|
|
1192
|
+
// 计算 params hash — 必须递归排序所有键(与 Python json.dumps(sort_keys=True, separators=(",",":")) 一致)
|
|
1193
|
+
const paramsForHash = {};
|
|
1194
|
+
for (const [k, v] of Object.entries(params)) {
|
|
1195
|
+
if (k !== 'client_signature' && !k.startsWith('_')) {
|
|
1196
|
+
paramsForHash[k] = v;
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
const paramsJson = stableStringify(paramsForHash);
|
|
1200
|
+
const paramsHash = crypto.createHash('sha256').update(paramsJson, 'utf-8').digest('hex');
|
|
1201
|
+
const signData = Buffer.from(`${method}|${aid}|${ts}|${paramsHash}`, 'utf-8');
|
|
1202
|
+
const privateKey = crypto.createPrivateKey(String(identity.private_key_pem));
|
|
1203
|
+
const signature = crypto.sign('SHA256', signData, privateKey);
|
|
1204
|
+
// 证书指纹
|
|
1205
|
+
let certFingerprint = '';
|
|
1206
|
+
const certPem = String(identity.cert ?? '');
|
|
1207
|
+
if (certPem) {
|
|
1208
|
+
const certObj = new crypto.X509Certificate(certPem);
|
|
1209
|
+
certFingerprint = 'sha256:' + certObj.fingerprint256.replace(/:/g, '').toLowerCase();
|
|
1210
|
+
}
|
|
1211
|
+
params.client_signature = {
|
|
1212
|
+
aid,
|
|
1213
|
+
cert_fingerprint: certFingerprint,
|
|
1214
|
+
timestamp: ts,
|
|
1215
|
+
params_hash: paramsHash,
|
|
1216
|
+
signature: signature.toString('base64'),
|
|
1217
|
+
};
|
|
1218
|
+
}
|
|
1219
|
+
catch (exc) {
|
|
1220
|
+
throw new Error(`客户端签名失败,拒绝发送无签名请求: ${formatCaughtError(exc)}`);
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
// ── 事件自动解密管线 ──────────────────────────────────────
|
|
1224
|
+
/** 处理 transport 层推送的原始 P2P 消息 */
|
|
1225
|
+
async _onRawMessageReceived(data) {
|
|
1226
|
+
// 异步处理,不阻塞事件调度
|
|
1227
|
+
this._processAndPublishMessage(data).catch((exc) => {
|
|
1228
|
+
_clientLog('warn', 'P2P 消息解密失败: %s', formatCaughtError(exc));
|
|
1229
|
+
// H26: 不再投递原始密文 payload;改发 message.undecryptable 事件,仅携带安全 header
|
|
1230
|
+
if (isJsonObject(data)) {
|
|
1231
|
+
const safeEvent = {
|
|
1232
|
+
message_id: data.message_id,
|
|
1233
|
+
from: data.from,
|
|
1234
|
+
to: data.to,
|
|
1235
|
+
seq: data.seq,
|
|
1236
|
+
timestamp: data.timestamp,
|
|
1237
|
+
_decrypt_error: String(exc),
|
|
1238
|
+
};
|
|
1239
|
+
this._dispatcher.publish('message.undecryptable', safeEvent).catch(() => { });
|
|
1240
|
+
}
|
|
1241
|
+
});
|
|
1242
|
+
}
|
|
1243
|
+
/** 实际处理推送消息的异步任务 */
|
|
1244
|
+
async _processAndPublishMessage(data) {
|
|
1245
|
+
if (!isJsonObject(data)) {
|
|
1246
|
+
await this._dispatcher.publish('message.received', data);
|
|
1247
|
+
return;
|
|
1248
|
+
}
|
|
1249
|
+
const msg = { ...data };
|
|
1250
|
+
// 拦截 P2P 传输的群组密钥分发/请求/响应消息
|
|
1251
|
+
if (await this._tryHandleGroupKeyMessage(msg)) {
|
|
1252
|
+
return;
|
|
1253
|
+
}
|
|
1254
|
+
// P2P 空洞检测
|
|
1255
|
+
const seq = msg.seq;
|
|
1256
|
+
if (seq !== undefined && seq !== null && this._aid) {
|
|
1257
|
+
this._p2pSynced = true; // 收到推送即视为已激活
|
|
1258
|
+
const ns = `p2p:${this._aid}`;
|
|
1259
|
+
const needPull = this._seqTracker.onMessageSeq(ns, seq);
|
|
1260
|
+
if (needPull) {
|
|
1261
|
+
this._fillP2pGap().catch(exc => _clientLog('warn', '后台补洞触发失败: %s', formatCaughtError(exc)));
|
|
1262
|
+
}
|
|
1263
|
+
// auto-ack contiguous_seq
|
|
1264
|
+
const contig = this._seqTracker.getContiguousSeq(ns);
|
|
1265
|
+
if (contig > 0) {
|
|
1266
|
+
this._transport.call('message.ack', {
|
|
1267
|
+
seq: contig,
|
|
1268
|
+
device_id: this._deviceId,
|
|
1269
|
+
}).catch((e) => { _clientLog('debug', 'P2P auto-ack 失败: %s', formatCaughtError(e)); });
|
|
1270
|
+
}
|
|
1271
|
+
// 即时持久化 cursor,异常断连后不回退
|
|
1272
|
+
this._saveSeqTrackerState();
|
|
1273
|
+
}
|
|
1274
|
+
const decrypted = await this._decryptSingleMessage(msg);
|
|
1275
|
+
// 记录已推送的 seq,补洞路径据此去重
|
|
1276
|
+
if (seq !== undefined && seq !== null && this._aid) {
|
|
1277
|
+
const ns = `p2p:${this._aid}`;
|
|
1278
|
+
if (!this._pushedSeqs.has(ns))
|
|
1279
|
+
this._pushedSeqs.set(ns, new Set());
|
|
1280
|
+
this._pushedSeqs.get(ns).add(seq);
|
|
1281
|
+
}
|
|
1282
|
+
await this._dispatcher.publish('message.received', decrypted);
|
|
1283
|
+
}
|
|
1284
|
+
/** 处理群组消息推送:自动解密后 re-publish */
|
|
1285
|
+
async _onRawGroupMessageCreated(data) {
|
|
1286
|
+
this._processAndPublishGroupMessage(data).catch((exc) => {
|
|
1287
|
+
_clientLog('warn', '群消息解密失败: %s', formatCaughtError(exc));
|
|
1288
|
+
// H26: 不再投递原始密文 payload;改发 group.message_undecryptable 事件
|
|
1289
|
+
if (isJsonObject(data)) {
|
|
1290
|
+
const safeEvent = {
|
|
1291
|
+
message_id: data.message_id,
|
|
1292
|
+
group_id: data.group_id,
|
|
1293
|
+
from: data.from,
|
|
1294
|
+
seq: data.seq,
|
|
1295
|
+
timestamp: data.timestamp,
|
|
1296
|
+
_decrypt_error: String(exc),
|
|
1297
|
+
};
|
|
1298
|
+
this._dispatcher.publish('group.message_undecryptable', safeEvent).catch(() => { });
|
|
1299
|
+
}
|
|
1300
|
+
});
|
|
1301
|
+
}
|
|
1302
|
+
/**
|
|
1303
|
+
* 处理群组推送消息的异步任务。
|
|
1304
|
+
*
|
|
1305
|
+
* 带 payload 的事件(消息推送):解密后 re-publish。
|
|
1306
|
+
* 不带 payload 的事件(通知):自动 pull 最新消息,逐条解密后 re-publish。
|
|
1307
|
+
*/
|
|
1308
|
+
async _processAndPublishGroupMessage(data) {
|
|
1309
|
+
if (!isJsonObject(data)) {
|
|
1310
|
+
await this._dispatcher.publish('group.message_created', data);
|
|
1311
|
+
return;
|
|
1312
|
+
}
|
|
1313
|
+
const msg = { ...data };
|
|
1314
|
+
const groupId = (msg.group_id ?? '');
|
|
1315
|
+
const seq = msg.seq;
|
|
1316
|
+
const payload = msg.payload;
|
|
1317
|
+
if (groupId) {
|
|
1318
|
+
this._groupSynced.add(groupId); // 收到推送即视为已激活
|
|
1319
|
+
}
|
|
1320
|
+
if (payload === undefined || payload === null
|
|
1321
|
+
|| (typeof payload === 'object' && Object.keys(payload).length === 0)) {
|
|
1322
|
+
// 不带 payload 的通知不能先推进 seq,否则 auto-pull 会用推进后的 cursor 跳过该消息。
|
|
1323
|
+
await this._autoPullGroupMessages(msg);
|
|
1324
|
+
return;
|
|
1325
|
+
}
|
|
1326
|
+
const decrypted = await this._decryptGroupMessage(msg);
|
|
1327
|
+
// 只有带 payload 的真实消息,在同步解密/恢复尝试结束后才推进游标。
|
|
1328
|
+
if (groupId && seq !== undefined && seq !== null) {
|
|
1329
|
+
const ns = `group:${groupId}`;
|
|
1330
|
+
const needPull = this._seqTracker.onMessageSeq(ns, seq);
|
|
1331
|
+
if (needPull) {
|
|
1332
|
+
this._fillGroupGap(groupId).catch(exc => _clientLog('warn', '后台补洞触发失败: %s', formatCaughtError(exc)));
|
|
1333
|
+
}
|
|
1334
|
+
const contig = this._seqTracker.getContiguousSeq(ns);
|
|
1335
|
+
if (contig > 0) {
|
|
1336
|
+
this._transport.call('group.ack_messages', {
|
|
1337
|
+
group_id: groupId,
|
|
1338
|
+
msg_seq: contig,
|
|
1339
|
+
device_id: this._deviceId,
|
|
1340
|
+
slot_id: this._slotId,
|
|
1341
|
+
}).catch((e) => { _clientLog('debug', '群消息 auto-ack 失败: group=%s %s', groupId, formatCaughtError(e)); });
|
|
1342
|
+
}
|
|
1343
|
+
this._saveSeqTrackerState();
|
|
1344
|
+
}
|
|
1345
|
+
// 记录已推送的 seq,补洞路径据此去重
|
|
1346
|
+
if (groupId && seq !== undefined && seq !== null) {
|
|
1347
|
+
const nsKey = `group:${groupId}`;
|
|
1348
|
+
if (!this._pushedSeqs.has(nsKey))
|
|
1349
|
+
this._pushedSeqs.set(nsKey, new Set());
|
|
1350
|
+
this._pushedSeqs.get(nsKey).add(seq);
|
|
1351
|
+
}
|
|
1352
|
+
// R3: 解密失败 → 不 publish 密文给应用层,入 pending 队列 + 发 undecryptable 事件
|
|
1353
|
+
const payloadForCheck = isJsonObject(msg.payload) ? msg.payload : null;
|
|
1354
|
+
if (payloadForCheck?.type === 'e2ee.group_encrypted' && !decrypted.e2ee) {
|
|
1355
|
+
if (groupId)
|
|
1356
|
+
this._enqueuePendingDecrypt(groupId, msg);
|
|
1357
|
+
await this._dispatcher.publish('group.message_undecryptable', {
|
|
1358
|
+
message_id: msg.message_id,
|
|
1359
|
+
group_id: groupId,
|
|
1360
|
+
from: msg.from,
|
|
1361
|
+
seq,
|
|
1362
|
+
timestamp: msg.timestamp,
|
|
1363
|
+
_decrypt_error: 'group secret unavailable',
|
|
1364
|
+
});
|
|
1365
|
+
return;
|
|
1366
|
+
}
|
|
1367
|
+
await this._dispatcher.publish('group.message_created', decrypted);
|
|
1368
|
+
}
|
|
1369
|
+
/** 收到不带 payload 的 group.message_created 通知后,自动 pull 最新消息 */
|
|
1370
|
+
async _autoPullGroupMessages(notification) {
|
|
1371
|
+
const groupId = (notification.group_id ?? '');
|
|
1372
|
+
if (!groupId) {
|
|
1373
|
+
await this._dispatcher.publish('group.message_created', notification);
|
|
1374
|
+
return;
|
|
1375
|
+
}
|
|
1376
|
+
const ns = `group:${groupId}`;
|
|
1377
|
+
const afterSeq = this._seqTracker.getContiguousSeq(ns);
|
|
1378
|
+
try {
|
|
1379
|
+
const result = await this.call('group.pull', {
|
|
1380
|
+
group_id: groupId,
|
|
1381
|
+
after_message_seq: afterSeq,
|
|
1382
|
+
device_id: this._deviceId,
|
|
1383
|
+
limit: 50,
|
|
1384
|
+
});
|
|
1385
|
+
if (isJsonObject(result)) {
|
|
1386
|
+
const messages = result.messages;
|
|
1387
|
+
if (Array.isArray(messages)) {
|
|
1388
|
+
// onPullResult 已在 call() 拦截器中调用,此处不再重复
|
|
1389
|
+
// pushedSeqs 去重:跳过已通过推送路径分发的消息
|
|
1390
|
+
const pushed = this._pushedSeqs.get(ns);
|
|
1391
|
+
for (const msg of messages) {
|
|
1392
|
+
if (isJsonObject(msg)) {
|
|
1393
|
+
const s = msg.seq;
|
|
1394
|
+
if (pushed && s !== undefined && s !== null && pushed.has(s)) {
|
|
1395
|
+
continue; // 已通过推送路径分发,跳过
|
|
1396
|
+
}
|
|
1397
|
+
await this._dispatcher.publish('group.message_created', msg);
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
this._prunePushedSeqs(ns);
|
|
1401
|
+
return;
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
catch (exc) {
|
|
1406
|
+
_clientLog('debug', '自动 pull 群消息失败: %s', formatCaughtError(exc));
|
|
1407
|
+
}
|
|
1408
|
+
await this._dispatcher.publish('group.message_created', notification);
|
|
1409
|
+
}
|
|
1410
|
+
/** 后台补齐群消息空洞 */
|
|
1411
|
+
async _fillGroupGap(groupId) {
|
|
1412
|
+
const ns = `group:${groupId}`;
|
|
1413
|
+
const afterSeq = this._seqTracker.getContiguousSeq(ns);
|
|
1414
|
+
// 冷启动(seq=0):服务端推送会带全量消息,SDK 不主动补洞避免重复拉取
|
|
1415
|
+
if (afterSeq === 0) {
|
|
1416
|
+
return;
|
|
1417
|
+
}
|
|
1418
|
+
// 去重:同一 (group:id:after_seq) 只补一次
|
|
1419
|
+
const dedupKey = `group_msg:${groupId}:${afterSeq}`;
|
|
1420
|
+
if (this._gapFillDone.has(dedupKey))
|
|
1421
|
+
return;
|
|
1422
|
+
this._gapFillDone.set(dedupKey, Date.now());
|
|
1423
|
+
// S1: 成功/失败双路径都需要根据"是否真正前进"决定是否保留 dedup 标记,
|
|
1424
|
+
// 避免 pull 返空、contiguous 未推进时标记被永久污染。
|
|
1425
|
+
let success = false;
|
|
1426
|
+
try {
|
|
1427
|
+
const result = await this.call('group.pull', {
|
|
1428
|
+
group_id: groupId,
|
|
1429
|
+
after_message_seq: afterSeq,
|
|
1430
|
+
device_id: this._deviceId,
|
|
1431
|
+
limit: 50,
|
|
1432
|
+
});
|
|
1433
|
+
if (isJsonObject(result)) {
|
|
1434
|
+
const messages = result.messages;
|
|
1435
|
+
if (Array.isArray(messages)) {
|
|
1436
|
+
// onPullResult 已在 call() 拦截器中调用,此处不再重复
|
|
1437
|
+
const pushed = this._pushedSeqs.get(ns);
|
|
1438
|
+
for (const msg of messages) {
|
|
1439
|
+
if (isJsonObject(msg)) {
|
|
1440
|
+
const s = msg.seq;
|
|
1441
|
+
if (pushed && s !== undefined && s !== null && pushed.has(s))
|
|
1442
|
+
continue;
|
|
1443
|
+
await this._dispatcher.publish('group.message_created', msg);
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
this._prunePushedSeqs(ns);
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
success = true;
|
|
1450
|
+
}
|
|
1451
|
+
catch (exc) {
|
|
1452
|
+
_clientLog('warn', '群消息补洞失败: %s', formatCaughtError(exc));
|
|
1453
|
+
}
|
|
1454
|
+
finally {
|
|
1455
|
+
// S1: 仅当 contiguous 已真正越过 afterSeq 时才保留标记;
|
|
1456
|
+
// 否则(异常 / 空结果)清除,避免后续相同 after_seq 的补洞被跳过。
|
|
1457
|
+
const contigAfter = this._seqTracker.getContiguousSeq(ns);
|
|
1458
|
+
if (!success || contigAfter <= afterSeq) {
|
|
1459
|
+
this._gapFillDone.delete(dedupKey);
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
/** 后台补齐 P2P 消息空洞 */
|
|
1464
|
+
async _fillP2pGap() {
|
|
1465
|
+
if (!this._aid)
|
|
1466
|
+
return;
|
|
1467
|
+
const ns = `p2p:${this._aid}`;
|
|
1468
|
+
const afterSeq = this._seqTracker.getContiguousSeq(ns);
|
|
1469
|
+
// 新设备(seq=0)没有历史 prekey,拉旧消息也解不了
|
|
1470
|
+
if (afterSeq === 0) {
|
|
1471
|
+
return;
|
|
1472
|
+
}
|
|
1473
|
+
// 去重:同一 (type:after_seq) 只补一次
|
|
1474
|
+
const dedupKey = `p2p:${afterSeq}`;
|
|
1475
|
+
if (this._gapFillDone.has(dedupKey))
|
|
1476
|
+
return;
|
|
1477
|
+
this._gapFillDone.set(dedupKey, Date.now());
|
|
1478
|
+
// S1: 成功路径也要判断是否真正前进;pull 返空时必须清除标记,
|
|
1479
|
+
// 否则下一次相同 afterSeq 触发的补洞会被永久跳过。
|
|
1480
|
+
let success = false;
|
|
1481
|
+
try {
|
|
1482
|
+
const result = await this.call('message.pull', {
|
|
1483
|
+
after_seq: afterSeq,
|
|
1484
|
+
limit: 50,
|
|
1485
|
+
});
|
|
1486
|
+
if (isJsonObject(result)) {
|
|
1487
|
+
const messages = result.messages;
|
|
1488
|
+
if (Array.isArray(messages)) {
|
|
1489
|
+
// onPullResult 已在 call() 拦截器中调用,此处不再重复
|
|
1490
|
+
const pushed = this._pushedSeqs.get(ns);
|
|
1491
|
+
for (const msg of messages) {
|
|
1492
|
+
if (isJsonObject(msg)) {
|
|
1493
|
+
const s = msg.seq;
|
|
1494
|
+
if (pushed && s !== undefined && s !== null && pushed.has(s))
|
|
1495
|
+
continue;
|
|
1496
|
+
await this._dispatcher.publish('message.received', msg);
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
this._prunePushedSeqs(ns);
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
success = true;
|
|
1503
|
+
}
|
|
1504
|
+
catch (exc) {
|
|
1505
|
+
_clientLog('warn', 'P2P 消息补洞失败: %s', formatCaughtError(exc));
|
|
1506
|
+
}
|
|
1507
|
+
finally {
|
|
1508
|
+
// S1: contiguous 未越过 afterSeq → 清除标记,允许后续重试
|
|
1509
|
+
const contigAfter = this._seqTracker.getContiguousSeq(ns);
|
|
1510
|
+
if (!success || contigAfter <= afterSeq) {
|
|
1511
|
+
this._gapFillDone.delete(dedupKey);
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
/** 清理 pushedSeqs 中 <= contiguousSeq 的条目,防止无限增长 */
|
|
1516
|
+
_prunePushedSeqs(ns) {
|
|
1517
|
+
const pushed = this._pushedSeqs.get(ns);
|
|
1518
|
+
if (!pushed)
|
|
1519
|
+
return;
|
|
1520
|
+
const contig = this._seqTracker.getContiguousSeq(ns);
|
|
1521
|
+
for (const s of pushed) {
|
|
1522
|
+
if (s <= contig)
|
|
1523
|
+
pushed.delete(s);
|
|
1524
|
+
}
|
|
1525
|
+
if (pushed.size === 0)
|
|
1526
|
+
this._pushedSeqs.delete(ns);
|
|
1527
|
+
}
|
|
1528
|
+
/** 后台补齐群事件空洞 */
|
|
1529
|
+
async _fillGroupEventGap(groupId) {
|
|
1530
|
+
const ns = `group_event:${groupId}`;
|
|
1531
|
+
const afterSeq = this._seqTracker.getContiguousSeq(ns);
|
|
1532
|
+
// 冷启动(seq=0):服务端推送会带全量事件,SDK 不主动补洞避免重复拉取
|
|
1533
|
+
if (afterSeq === 0) {
|
|
1534
|
+
return;
|
|
1535
|
+
}
|
|
1536
|
+
// 去重:同一 (group_evt:id:after_seq) 只补一次
|
|
1537
|
+
const dedupKey = `group_evt:${groupId}:${afterSeq}`;
|
|
1538
|
+
if (this._gapFillDone.has(dedupKey))
|
|
1539
|
+
return;
|
|
1540
|
+
this._gapFillDone.set(dedupKey, Date.now());
|
|
1541
|
+
// S1: 成功/失败均按"是否真正前进"决定是否保留标记
|
|
1542
|
+
let success = false;
|
|
1543
|
+
try {
|
|
1544
|
+
const result = await this.call('group.pull_events', {
|
|
1545
|
+
group_id: groupId,
|
|
1546
|
+
after_event_seq: afterSeq,
|
|
1547
|
+
device_id: this._deviceId,
|
|
1548
|
+
limit: 50,
|
|
1549
|
+
});
|
|
1550
|
+
if (isJsonObject(result)) {
|
|
1551
|
+
const events = result.events;
|
|
1552
|
+
if (Array.isArray(events)) {
|
|
1553
|
+
this._seqTracker.onPullResult(ns, events.filter(isJsonObject));
|
|
1554
|
+
// 持久化 cursor + ack_events(与 Python 对齐)
|
|
1555
|
+
this._saveSeqTrackerState();
|
|
1556
|
+
const contig = this._seqTracker.getContiguousSeq(ns);
|
|
1557
|
+
if (contig > 0) {
|
|
1558
|
+
this._transport.call('group.ack_events', {
|
|
1559
|
+
group_id: groupId,
|
|
1560
|
+
event_seq: contig,
|
|
1561
|
+
device_id: this._deviceId,
|
|
1562
|
+
}).catch((e) => { _clientLog('debug', '群事件 auto-ack 失败: group=%s %s', groupId, formatCaughtError(e)); });
|
|
1563
|
+
}
|
|
1564
|
+
for (const evt of events) {
|
|
1565
|
+
if (isJsonObject(evt)) {
|
|
1566
|
+
evt._from_gap_fill = true;
|
|
1567
|
+
const et = String(evt.event_type ?? '');
|
|
1568
|
+
// 消息事件由 _fillGroupGap 负责,事件补洞不重复投递
|
|
1569
|
+
if (et === 'group.message_created')
|
|
1570
|
+
continue;
|
|
1571
|
+
// group.changed 或缺失/其他 → 发布到 group.changed(向后兼容)
|
|
1572
|
+
await this._dispatcher.publish('group.changed', evt);
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
success = true;
|
|
1578
|
+
}
|
|
1579
|
+
catch (exc) {
|
|
1580
|
+
_clientLog('warn', '群事件补洞失败: %s', formatCaughtError(exc));
|
|
1581
|
+
}
|
|
1582
|
+
finally {
|
|
1583
|
+
const contigAfter = this._seqTracker.getContiguousSeq(ns);
|
|
1584
|
+
if (!success || contigAfter <= afterSeq) {
|
|
1585
|
+
this._gapFillDone.delete(dedupKey);
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
/**
|
|
1590
|
+
* 上线/重连后一次性同步所有已加入群:
|
|
1591
|
+
* 1. 有 epoch key 的群 → 补消息 + 补事件
|
|
1592
|
+
* 2. 无 epoch key 的群 → 仅补事件(事件不加密,等推送触发密钥恢复)
|
|
1593
|
+
*/
|
|
1594
|
+
async _syncAllGroupsOnce() {
|
|
1595
|
+
try {
|
|
1596
|
+
const result = await this.call('group.list_my', {});
|
|
1597
|
+
if (!isJsonObject(result))
|
|
1598
|
+
return;
|
|
1599
|
+
const items = result.items;
|
|
1600
|
+
if (!Array.isArray(items))
|
|
1601
|
+
return;
|
|
1602
|
+
for (const g of items) {
|
|
1603
|
+
if (isJsonObject(g)) {
|
|
1604
|
+
const gid = String(g.group_id ?? '');
|
|
1605
|
+
if (gid) {
|
|
1606
|
+
// 有 epoch key → 补消息
|
|
1607
|
+
if (this._groupE2ee.hasSecret(gid)) {
|
|
1608
|
+
await this._fillGroupGap(gid);
|
|
1609
|
+
}
|
|
1610
|
+
// 所有群都补事件(事件不加密)
|
|
1611
|
+
await this._fillGroupEventGap(gid);
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
catch (exc) {
|
|
1617
|
+
_clientLog('debug', '批量同步群失败: %s', formatCaughtError(exc));
|
|
1618
|
+
}
|
|
1619
|
+
}
|
|
1620
|
+
/**
|
|
1621
|
+
* 处理群组变更事件:透传给用户,并在成员离开/被踢时自动触发 epoch 轮换。
|
|
1622
|
+
* 按协议,轮换由剩余在线 admin/owner 负责。
|
|
1623
|
+
*/
|
|
1624
|
+
_membershipRotationExpectedEpoch(payload) {
|
|
1625
|
+
for (const key of ['old_epoch', 'current_epoch', 'e2ee_epoch']) {
|
|
1626
|
+
const value = payload[key];
|
|
1627
|
+
if (value !== undefined && value !== null) {
|
|
1628
|
+
const n = Number(value);
|
|
1629
|
+
if (Number.isFinite(n))
|
|
1630
|
+
return n;
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
const group = payload.group;
|
|
1634
|
+
if (isJsonObject(group)) {
|
|
1635
|
+
for (const key of ['old_epoch', 'current_epoch', 'e2ee_epoch']) {
|
|
1636
|
+
const value = group[key];
|
|
1637
|
+
if (value !== undefined && value !== null) {
|
|
1638
|
+
const n = Number(value);
|
|
1639
|
+
if (Number.isFinite(n))
|
|
1640
|
+
return n;
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
return null;
|
|
1645
|
+
}
|
|
1646
|
+
_membershipRotationTriggerId(groupId, payload) {
|
|
1647
|
+
let action = String(payload.action ?? '').trim();
|
|
1648
|
+
if (!action) {
|
|
1649
|
+
if (payload.removed_aid)
|
|
1650
|
+
action = 'member_removed';
|
|
1651
|
+
else if (payload.left_aid)
|
|
1652
|
+
action = 'member_left';
|
|
1653
|
+
else if (isJsonObject(payload.member))
|
|
1654
|
+
action = 'member_added';
|
|
1655
|
+
else
|
|
1656
|
+
action = String(payload.status ?? payload.reason ?? 'membership_changed');
|
|
1657
|
+
}
|
|
1658
|
+
const group = isJsonObject(payload.group) ? payload.group : null;
|
|
1659
|
+
const eventSeq = payload.event_seq ?? payload.seq ?? group?.event_seq ?? '';
|
|
1660
|
+
const changedAids = new Set();
|
|
1661
|
+
let changedAid = String(payload.aid ?? payload.removed_aid ?? payload.left_aid ?? payload.member_aid ?? payload.target_aid ?? '');
|
|
1662
|
+
if (changedAid)
|
|
1663
|
+
changedAids.add(changedAid);
|
|
1664
|
+
const member = isJsonObject(payload.member) ? payload.member : null;
|
|
1665
|
+
if (member?.aid)
|
|
1666
|
+
changedAids.add(String(member.aid));
|
|
1667
|
+
if (!changedAid && member)
|
|
1668
|
+
changedAid = String(member.aid ?? '');
|
|
1669
|
+
const request = isJsonObject(payload.request) ? payload.request : null;
|
|
1670
|
+
if (request?.aid)
|
|
1671
|
+
changedAids.add(String(request.aid));
|
|
1672
|
+
if (!changedAid && request)
|
|
1673
|
+
changedAid = String(request.aid ?? '');
|
|
1674
|
+
const inviteCode = isJsonObject(payload.invite_code) ? payload.invite_code : null;
|
|
1675
|
+
if (inviteCode?.used_by)
|
|
1676
|
+
changedAids.add(String(inviteCode.used_by));
|
|
1677
|
+
if (inviteCode?.aid)
|
|
1678
|
+
changedAids.add(String(inviteCode.aid));
|
|
1679
|
+
if (!changedAid && inviteCode)
|
|
1680
|
+
changedAid = String(inviteCode.used_by ?? inviteCode.aid ?? '');
|
|
1681
|
+
if (Array.isArray(payload.results)) {
|
|
1682
|
+
for (const item of payload.results) {
|
|
1683
|
+
if (!isJsonObject(item))
|
|
1684
|
+
continue;
|
|
1685
|
+
const status = String(item.status ?? '').trim().toLowerCase();
|
|
1686
|
+
if (status !== 'approved' && item.approved !== true)
|
|
1687
|
+
continue;
|
|
1688
|
+
for (const key of ['aid', 'member_aid', 'target_aid']) {
|
|
1689
|
+
const value = item[key];
|
|
1690
|
+
if (value !== undefined && value !== null && String(value))
|
|
1691
|
+
changedAids.add(String(value));
|
|
1692
|
+
}
|
|
1693
|
+
for (const key of ['member', 'request']) {
|
|
1694
|
+
const nested = isJsonObject(item[key]) ? item[key] : null;
|
|
1695
|
+
if (nested?.aid)
|
|
1696
|
+
changedAids.add(String(nested.aid));
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
const changedAidKey = Array.from(changedAids).filter(Boolean).sort().join(',');
|
|
1701
|
+
const expectedEpoch = this._membershipRotationExpectedEpoch(payload);
|
|
1702
|
+
if (changedAidKey && expectedEpoch !== null)
|
|
1703
|
+
return `${groupId}:${action}:aid:${changedAidKey}:epoch:${expectedEpoch}`;
|
|
1704
|
+
if (eventSeq !== undefined && eventSeq !== null && String(eventSeq) !== '')
|
|
1705
|
+
return `${groupId}:${action}:event:${String(eventSeq)}`;
|
|
1706
|
+
return `${groupId}:${action}:aid:${changedAidKey || changedAid || '-'}`;
|
|
1707
|
+
}
|
|
1708
|
+
_membershipRotationChanged(method, payload) {
|
|
1709
|
+
if (['group.add_member', 'group.kick', 'group.remove_member', 'group.leave'].includes(method)) {
|
|
1710
|
+
return true;
|
|
1711
|
+
}
|
|
1712
|
+
const status = String(payload.status ?? '').trim().toLowerCase();
|
|
1713
|
+
if (['group.use_invite_code', 'group.request_join'].includes(method)) {
|
|
1714
|
+
return ['joined', 'approved'].includes(status) || isJsonObject(payload.member);
|
|
1715
|
+
}
|
|
1716
|
+
if (method === 'group.review_join_request') {
|
|
1717
|
+
return status === 'approved' || payload.approved === true || isJsonObject(payload.member);
|
|
1718
|
+
}
|
|
1719
|
+
if (method === 'group.batch_review_join_request') {
|
|
1720
|
+
const results = payload.results;
|
|
1721
|
+
if (!Array.isArray(results))
|
|
1722
|
+
return false;
|
|
1723
|
+
return results.some((item) => {
|
|
1724
|
+
if (!isJsonObject(item))
|
|
1725
|
+
return false;
|
|
1726
|
+
const itemStatus = String(item.status ?? '').trim().toLowerCase();
|
|
1727
|
+
return itemStatus === 'approved' || item.approved === true;
|
|
1728
|
+
});
|
|
1729
|
+
}
|
|
1730
|
+
return false;
|
|
1731
|
+
}
|
|
1732
|
+
_extractGroupIdFromResult(result) {
|
|
1733
|
+
const group = isJsonObject(result.group) ? result.group : null;
|
|
1734
|
+
const gid = group ? String(group.group_id ?? '') : '';
|
|
1735
|
+
if (gid)
|
|
1736
|
+
return gid;
|
|
1737
|
+
const directGid = String(result.group_id ?? '');
|
|
1738
|
+
if (directGid)
|
|
1739
|
+
return directGid;
|
|
1740
|
+
const member = isJsonObject(result.member) ? result.member : null;
|
|
1741
|
+
return member ? String(member.group_id ?? '') : '';
|
|
1742
|
+
}
|
|
1743
|
+
async _onRawGroupChanged(data) {
|
|
1744
|
+
if (isJsonObject(data)) {
|
|
1745
|
+
const d = data;
|
|
1746
|
+
// 验签:有 client_signature 就验,没有默认安全(H20: 严格 boolean)
|
|
1747
|
+
const cs = d.client_signature;
|
|
1748
|
+
if (cs && isJsonObject(cs)) {
|
|
1749
|
+
d._verified = await this._verifyEventSignatureAsync(d, cs);
|
|
1750
|
+
}
|
|
1751
|
+
await this._dispatcher.publish('group.changed', d);
|
|
1752
|
+
const groupId = String(d.group_id ?? '');
|
|
1753
|
+
// event_seq 空洞检测:持久化后的 group.changed 会携带 event_seq。
|
|
1754
|
+
// 用 onMessageSeq 返回值决定是否补拉,与 P2P / group.message 路径对齐。
|
|
1755
|
+
let needPull = false;
|
|
1756
|
+
const rawEventSeq = d.event_seq;
|
|
1757
|
+
if (rawEventSeq != null && groupId) {
|
|
1758
|
+
const es = Number(rawEventSeq);
|
|
1759
|
+
if (Number.isFinite(es) && es > 0) {
|
|
1760
|
+
needPull = this._seqTracker.onMessageSeq(`group_event:${groupId}`, es);
|
|
1761
|
+
}
|
|
1762
|
+
// ISSUE-TS-002: 群事件推送路径 ack + 持久化,与 P2P/群消息路径对齐
|
|
1763
|
+
this._saveSeqTrackerState();
|
|
1764
|
+
const contig = this._seqTracker.getContiguousSeq(`group_event:${groupId}`);
|
|
1765
|
+
if (contig > 0) {
|
|
1766
|
+
this._transport.call('group.ack_events', {
|
|
1767
|
+
group_id: groupId,
|
|
1768
|
+
event_seq: contig,
|
|
1769
|
+
device_id: this._deviceId,
|
|
1770
|
+
}).catch((e) => { _clientLog('debug', '群事件推送 auto-ack 失败: group=%s %s', groupId, formatCaughtError(e)); });
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
// 仅在真实 event gap 时才触发补拉(补洞回来的事件不再触发新补洞)
|
|
1774
|
+
if (needPull && groupId && !d._from_gap_fill) {
|
|
1775
|
+
this._fillGroupEventGap(groupId).catch(exc => _clientLog('warn', '后台补洞触发失败: %s', formatCaughtError(exc)));
|
|
1776
|
+
}
|
|
1777
|
+
// 成员退出或被踢 → 剩余 admin/owner 自动补位轮换
|
|
1778
|
+
// H21: 避免 epoch 轮换风暴——所有剩余 admin 同时收到事件不能都发起轮换,
|
|
1779
|
+
// 否则 CAS 冲突激增。策略:本地 AID 为"排序最小 admin"时才发起,其他 admin
|
|
1780
|
+
// 叠加随机 jitter 作为超时兜底(本地最小 admin 失败时由下一位顶上)。
|
|
1781
|
+
if (d.action === 'member_left' || d.action === 'member_removed') {
|
|
1782
|
+
if (groupId) {
|
|
1783
|
+
{
|
|
1784
|
+
const expectedEpoch = this._membershipRotationExpectedEpoch(d);
|
|
1785
|
+
if (expectedEpoch === null) {
|
|
1786
|
+
_clientLog('debug', 'membership event without old_epoch skipped for epoch rotation: aid=%s group=%s action=%s event_seq=%s', this._aid ?? '', groupId, String(d.action ?? ''), String(d.event_seq ?? ''));
|
|
1787
|
+
}
|
|
1788
|
+
else {
|
|
1789
|
+
this._maybeLeadRotateGroupEpoch(groupId, this._membershipRotationTriggerId(groupId, d), expectedEpoch).catch((exc) => this._logE2eeError('rotate_epoch', groupId, '', exc));
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1793
|
+
}
|
|
1794
|
+
if (['member_added', 'joined', 'join_approved', 'invite_code_used'].includes(String(d.action ?? ''))) {
|
|
1795
|
+
if (groupId) {
|
|
1796
|
+
{
|
|
1797
|
+
const expectedEpoch = this._membershipRotationExpectedEpoch(d);
|
|
1798
|
+
if (expectedEpoch === null) {
|
|
1799
|
+
_clientLog('debug', 'membership event without old_epoch skipped for epoch rotation: aid=%s group=%s action=%s event_seq=%s', this._aid ?? '', groupId, String(d.action ?? ''), String(d.event_seq ?? ''));
|
|
1800
|
+
}
|
|
1801
|
+
else {
|
|
1802
|
+
this._maybeLeadRotateGroupEpoch(groupId, this._membershipRotationTriggerId(groupId, d), expectedEpoch).catch((exc) => this._logE2eeError('rotate_epoch', groupId, '', exc));
|
|
1803
|
+
}
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
// 群组解散 → 清理本地 epoch key、seq_tracker、补洞去重缓存
|
|
1808
|
+
if (d.action === 'dissolved') {
|
|
1809
|
+
if (groupId) {
|
|
1810
|
+
this._cleanupDissolvedGroup(groupId);
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
else {
|
|
1815
|
+
// data 非对象也透传给用户(兼容旧版)
|
|
1816
|
+
await this._dispatcher.publish('group.changed', data);
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
/**
|
|
1820
|
+
* 成员退出/被踢后,判断本地是否为 leader admin 并发起 epoch 轮换。
|
|
1821
|
+
* 避免所有剩余 admin 同时触发 `_rotateGroupEpoch` 造成 CAS 风暴。
|
|
1822
|
+
*/
|
|
1823
|
+
async _maybeLeadRotateGroupEpoch(groupId, triggerId = '', expectedEpoch = null) {
|
|
1824
|
+
const myAid = this._aid;
|
|
1825
|
+
if (!myAid || this._closing || this._state !== 'connected')
|
|
1826
|
+
return;
|
|
1827
|
+
const started = Date.now();
|
|
1828
|
+
while (this._groupEpochRotationInflight.has(groupId)) {
|
|
1829
|
+
if (triggerId && this._groupMembershipRotationDone.has(triggerId))
|
|
1830
|
+
return;
|
|
1831
|
+
if (this._closing || this._state !== 'connected')
|
|
1832
|
+
return;
|
|
1833
|
+
if (Date.now() - started > 20000) {
|
|
1834
|
+
_clientLog('warn', 'group epoch rotation still in-flight; skip pending trigger (group=%s trigger=%s)', groupId, triggerId || '-');
|
|
1835
|
+
return;
|
|
1836
|
+
}
|
|
1837
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
1838
|
+
}
|
|
1839
|
+
if (this._closing || this._state !== 'connected')
|
|
1840
|
+
return;
|
|
1841
|
+
this._groupEpochRotationInflight.add(groupId);
|
|
1842
|
+
try {
|
|
1843
|
+
if (this._closing || this._state !== 'connected')
|
|
1844
|
+
return;
|
|
1845
|
+
const membersResp = await this.call('group.get_members', { group_id: groupId });
|
|
1846
|
+
if (!isJsonObject(membersResp))
|
|
1847
|
+
return;
|
|
1848
|
+
const rawList = membersResp.members ?? membersResp.items;
|
|
1849
|
+
if (!Array.isArray(rawList))
|
|
1850
|
+
return;
|
|
1851
|
+
const admins = [];
|
|
1852
|
+
for (const m of rawList) {
|
|
1853
|
+
if (!isJsonObject(m))
|
|
1854
|
+
continue;
|
|
1855
|
+
const role = String(m.role ?? '');
|
|
1856
|
+
const aid = String(m.aid ?? '');
|
|
1857
|
+
if (aid && (role === 'admin' || role === 'owner'))
|
|
1858
|
+
admins.push(aid);
|
|
1859
|
+
}
|
|
1860
|
+
if (admins.length === 0)
|
|
1861
|
+
return;
|
|
1862
|
+
admins.sort();
|
|
1863
|
+
const leader = admins[0];
|
|
1864
|
+
if (leader === myAid) {
|
|
1865
|
+
// 我是 leader,直接发起
|
|
1866
|
+
await this._rotateGroupEpoch(groupId, triggerId, expectedEpoch);
|
|
1867
|
+
return;
|
|
1868
|
+
}
|
|
1869
|
+
if (!admins.includes(myAid))
|
|
1870
|
+
return;
|
|
1871
|
+
// 非 leader:随机 jitter(2~6s)后查询服务端 epoch 是否已被 leader 推进
|
|
1872
|
+
const jitterMs = 2000 + Math.floor(Math.random() * 4000);
|
|
1873
|
+
let beforeEpoch = 0;
|
|
1874
|
+
try {
|
|
1875
|
+
const resp = await this.call('group.e2ee.get_epoch', { group_id: groupId });
|
|
1876
|
+
if (isJsonObject(resp))
|
|
1877
|
+
beforeEpoch = Number(resp.epoch ?? 0);
|
|
1878
|
+
}
|
|
1879
|
+
catch {
|
|
1880
|
+
beforeEpoch = (await this._groupE2ee.currentEpoch(groupId)) ?? 0;
|
|
1881
|
+
}
|
|
1882
|
+
await new Promise((r) => setTimeout(r, jitterMs));
|
|
1883
|
+
if (this._closing || this._state !== 'connected')
|
|
1884
|
+
return;
|
|
1885
|
+
let afterEpoch = 0;
|
|
1886
|
+
let afterResp = {};
|
|
1887
|
+
try {
|
|
1888
|
+
afterResp = await this.call('group.e2ee.get_epoch', { group_id: groupId });
|
|
1889
|
+
if (isJsonObject(afterResp))
|
|
1890
|
+
afterEpoch = Number(afterResp.epoch ?? 0);
|
|
1891
|
+
}
|
|
1892
|
+
catch {
|
|
1893
|
+
afterEpoch = (await this._groupE2ee.currentEpoch(groupId)) ?? 0;
|
|
1894
|
+
}
|
|
1895
|
+
if (afterEpoch > beforeEpoch)
|
|
1896
|
+
return; // leader 已完成
|
|
1897
|
+
const pending = isJsonObject(afterResp) && isJsonObject(afterResp.pending_rotation) ? afterResp.pending_rotation : null;
|
|
1898
|
+
if (pending && !pending.expired) {
|
|
1899
|
+
this._scheduleGroupRotationRetry(groupId, {
|
|
1900
|
+
reason: 'membership_changed',
|
|
1901
|
+
triggerId,
|
|
1902
|
+
expectedEpoch,
|
|
1903
|
+
pending,
|
|
1904
|
+
});
|
|
1905
|
+
return;
|
|
1906
|
+
}
|
|
1907
|
+
_clientLog('info', '[H21] leader 未完成 epoch 轮换,非 leader 兜底: group=%s myAid=%s', groupId, myAid);
|
|
1908
|
+
await this._rotateGroupEpoch(groupId, triggerId, expectedEpoch);
|
|
1909
|
+
}
|
|
1910
|
+
catch (exc) {
|
|
1911
|
+
_clientLog('warn', '_maybeLeadRotateGroupEpoch 失败: %s', formatCaughtError(exc));
|
|
1912
|
+
}
|
|
1913
|
+
finally {
|
|
1914
|
+
this._groupEpochRotationInflight.delete(groupId);
|
|
1915
|
+
}
|
|
1916
|
+
}
|
|
1917
|
+
/**
|
|
1918
|
+
* 群组解散后清理本地状态:
|
|
1919
|
+
* - keystore 中的 epoch key 数据
|
|
1920
|
+
* - seq_tracker 中的群消息和群事件 seq 记录
|
|
1921
|
+
* - 补洞去重缓存中的相关条目
|
|
1922
|
+
*/
|
|
1923
|
+
_cleanupDissolvedGroup(groupId) {
|
|
1924
|
+
// 1. 清理 GroupE2EEManager / keystore 中的 epoch 密钥
|
|
1925
|
+
try {
|
|
1926
|
+
this._groupE2ee.removeGroup(groupId);
|
|
1927
|
+
}
|
|
1928
|
+
catch (exc) {
|
|
1929
|
+
_clientLog('warn', '清理解散群组 %s epoch 密钥失败: %s', groupId, formatCaughtError(exc));
|
|
1930
|
+
}
|
|
1931
|
+
// 2. 清理 seq_tracker 中的群消息和群事件命名空间
|
|
1932
|
+
this._seqTracker.removeNamespace(`group:${groupId}`);
|
|
1933
|
+
this._seqTracker.removeNamespace(`group_event:${groupId}`);
|
|
1934
|
+
this._saveSeqTrackerState();
|
|
1935
|
+
// 3. 清理补洞去重缓存中的相关条目
|
|
1936
|
+
for (const key of this._gapFillDone.keys()) {
|
|
1937
|
+
if (key.includes(groupId)) {
|
|
1938
|
+
this._gapFillDone.delete(key);
|
|
1939
|
+
}
|
|
1940
|
+
}
|
|
1941
|
+
// 4. 清理推送 seq 去重缓存
|
|
1942
|
+
this._pushedSeqs.delete(`group:${groupId}`);
|
|
1943
|
+
this._pushedSeqs.delete(`group_event:${groupId}`);
|
|
1944
|
+
_clientLog('info', '已清理解散群组 %s 的本地状态', groupId);
|
|
1945
|
+
}
|
|
1946
|
+
/** 同步验签群事件 client_signature。返回 true/false/"pending"。 */
|
|
1947
|
+
/**
|
|
1948
|
+
* H20 修复:原来返回 `string | boolean` 的三态;`_verified = 'pending'` 是 truthy
|
|
1949
|
+
* 字符串,业务写 `if (event._verified)` 会把"证书未到"当成"已验证"。
|
|
1950
|
+
* 改为严格 boolean,证书缺失时 await `_fetchPeerCert` 再判定;若仍失败返回 false
|
|
1951
|
+
* 并触发 `signature_pending` 事件让上层感知。
|
|
1952
|
+
*/
|
|
1953
|
+
async _verifyEventSignatureAsync(event, cs) {
|
|
1954
|
+
try {
|
|
1955
|
+
const sigAid = String(cs.aid ?? '');
|
|
1956
|
+
const method = String(cs._method ?? '');
|
|
1957
|
+
const expectedFP = String(cs.cert_fingerprint ?? '').trim().toLowerCase();
|
|
1958
|
+
if (!sigAid || !method)
|
|
1959
|
+
return false;
|
|
1960
|
+
// 先查缓存;缺失则 await 拉取,避免 truthy string 歧义
|
|
1961
|
+
let certPem = '';
|
|
1962
|
+
const cached = this._certCache.get(AUNClient._certCacheKey(sigAid, expectedFP || undefined));
|
|
1963
|
+
if (cached && cached.certPem) {
|
|
1964
|
+
certPem = cached.certPem;
|
|
1965
|
+
}
|
|
1966
|
+
else {
|
|
1967
|
+
try {
|
|
1968
|
+
certPem = await this._fetchPeerCert(sigAid, expectedFP || undefined);
|
|
1969
|
+
}
|
|
1970
|
+
catch {
|
|
1971
|
+
this._dispatcher.publish('signature_pending', { aid: sigAid, method }).catch(() => { });
|
|
1972
|
+
return false;
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
const certObj = new crypto.X509Certificate(certPem);
|
|
1976
|
+
if (expectedFP) {
|
|
1977
|
+
const actualFP = 'sha256:' + certObj.fingerprint256.replace(/:/g, '').toLowerCase();
|
|
1978
|
+
if (actualFP !== expectedFP) {
|
|
1979
|
+
_clientLog('warn', '验签失败:证书指纹不匹配 aid=%s', sigAid);
|
|
1980
|
+
return false;
|
|
1981
|
+
}
|
|
1982
|
+
}
|
|
1983
|
+
const paramsHash = String(cs.params_hash ?? '');
|
|
1984
|
+
const timestamp = String(cs.timestamp ?? '');
|
|
1985
|
+
const signData = Buffer.from(`${method}|${sigAid}|${timestamp}|${paramsHash}`, 'utf-8');
|
|
1986
|
+
const sigB64 = String(cs.signature ?? '');
|
|
1987
|
+
const pubKey = certObj.publicKey;
|
|
1988
|
+
const ok = crypto.verify('SHA256', signData, pubKey, Buffer.from(sigB64, 'base64'));
|
|
1989
|
+
if (!ok) {
|
|
1990
|
+
_clientLog('warn', '群事件验签失败 aid=%s method=%s', sigAid, method);
|
|
1991
|
+
}
|
|
1992
|
+
return ok;
|
|
1993
|
+
}
|
|
1994
|
+
catch (exc) {
|
|
1995
|
+
_clientLog('warn', '群事件验签异常: %s', formatCaughtError(exc));
|
|
1996
|
+
return false;
|
|
1997
|
+
}
|
|
1998
|
+
}
|
|
1999
|
+
/** 尝试处理 P2P 传输的群组密钥消息。返回 true 表示已处理(不再传播)。 */
|
|
2000
|
+
async _tryHandleGroupKeyMessage(message) {
|
|
2001
|
+
const payload = message.payload;
|
|
2002
|
+
if (!isJsonObject(payload))
|
|
2003
|
+
return false;
|
|
2004
|
+
const payloadObj = payload;
|
|
2005
|
+
// 控制面消息类型识别:只有明文 type 或 P2P 解密后内层 type 命中时才拦截。
|
|
2006
|
+
const GROUP_KEY_TYPES = new Set([
|
|
2007
|
+
'e2ee.group_key_distribution',
|
|
2008
|
+
'e2ee.group_key_request',
|
|
2009
|
+
'e2ee.group_key_response',
|
|
2010
|
+
]);
|
|
2011
|
+
let isControlPlane = typeof payloadObj.type === 'string'
|
|
2012
|
+
&& GROUP_KEY_TYPES.has(payloadObj.type);
|
|
2013
|
+
// 先解密 P2P E2EE(如果是加密的)
|
|
2014
|
+
// 注意:用 _decrypt_message 而非 decrypt_message,避免消耗 seen set
|
|
2015
|
+
let actualPayload = payloadObj;
|
|
2016
|
+
if (payloadObj.type === 'e2ee.encrypted') {
|
|
2017
|
+
const fromAid = String(message.from ?? '');
|
|
2018
|
+
const senderCertFingerprint = String(payloadObj.sender_cert_fingerprint ?? payloadObj.aad?.sender_cert_fingerprint ?? '').trim().toLowerCase();
|
|
2019
|
+
if (fromAid) {
|
|
2020
|
+
await this._ensureSenderCertCached(fromAid, senderCertFingerprint || undefined);
|
|
2021
|
+
}
|
|
2022
|
+
const decrypted = this._e2ee._decryptMessage(message);
|
|
2023
|
+
if (decrypted === null)
|
|
2024
|
+
return false;
|
|
2025
|
+
this._schedulePrekeyReplenishIfConsumed(decrypted);
|
|
2026
|
+
actualPayload = isJsonObject(decrypted.payload) ? decrypted.payload : null;
|
|
2027
|
+
if (actualPayload === null)
|
|
2028
|
+
return false;
|
|
2029
|
+
const innerType = actualPayload.type;
|
|
2030
|
+
if (typeof innerType === 'string' && GROUP_KEY_TYPES.has(innerType)) {
|
|
2031
|
+
isControlPlane = true;
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
let result;
|
|
2035
|
+
if (actualPayload.type === 'e2ee.group_key_distribution') {
|
|
2036
|
+
if (!await this._verifyActiveGroupRotationDistribution(actualPayload)) {
|
|
2037
|
+
return true;
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
2040
|
+
else if (actualPayload.type === 'e2ee.group_key_response') {
|
|
2041
|
+
if (!await this._verifyGroupKeyResponseEpoch(actualPayload)) {
|
|
2042
|
+
return true;
|
|
2043
|
+
}
|
|
2044
|
+
}
|
|
2045
|
+
result = this._groupE2ee.handleIncoming(actualPayload);
|
|
2046
|
+
if (result === 'distribution') {
|
|
2047
|
+
await this._discardGroupDistributionIfStale(actualPayload);
|
|
2048
|
+
}
|
|
2049
|
+
// S14: 非控制面消息且 handleIncoming 不识别 → 不拦截
|
|
2050
|
+
if (!isControlPlane && result === null)
|
|
2051
|
+
return false;
|
|
2052
|
+
if (result === 'request') {
|
|
2053
|
+
// 处理密钥请求并回复
|
|
2054
|
+
const groupId = String(actualPayload.group_id ?? '');
|
|
2055
|
+
const requester = String(actualPayload.requester_aid ?? '');
|
|
2056
|
+
let members = this._groupE2ee.getMemberAids(groupId);
|
|
2057
|
+
// 请求者不在本地成员列表时,回源查询服务端最新成员列表
|
|
2058
|
+
if (requester && !members.includes(requester)) {
|
|
2059
|
+
try {
|
|
2060
|
+
const membersResult = await this.call('group.get_members', { group_id: groupId });
|
|
2061
|
+
const memberList = isJsonObject(membersResult) && Array.isArray(membersResult.members)
|
|
2062
|
+
? membersResult.members
|
|
2063
|
+
: [];
|
|
2064
|
+
members = memberList.map((m) => String(m.aid));
|
|
2065
|
+
// 更新本地当前 epoch 的 member_aids/commitment
|
|
2066
|
+
if (members.includes(requester)) {
|
|
2067
|
+
const secretData = this._groupE2ee.loadSecret(groupId);
|
|
2068
|
+
if (secretData && this._aid) {
|
|
2069
|
+
const epoch = secretData.epoch;
|
|
2070
|
+
const commitment = computeMembershipCommitment(members, epoch, groupId, secretData.secret);
|
|
2071
|
+
storeGroupSecret(this._keystore, this._aid, groupId, epoch, secretData.secret, commitment, members);
|
|
2072
|
+
}
|
|
2073
|
+
}
|
|
2074
|
+
}
|
|
2075
|
+
catch (exc) {
|
|
2076
|
+
_clientLog('warn', '群组 %s 成员列表回源失败: %s', groupId, formatCaughtError(exc));
|
|
2077
|
+
}
|
|
2078
|
+
}
|
|
2079
|
+
const response = this._groupE2ee.handleKeyRequestMsg(actualPayload, members);
|
|
2080
|
+
if (response && requester) {
|
|
2081
|
+
try {
|
|
2082
|
+
await this.call('message.send', {
|
|
2083
|
+
to: requester,
|
|
2084
|
+
payload: response,
|
|
2085
|
+
encrypt: true,
|
|
2086
|
+
persist_required: true,
|
|
2087
|
+
});
|
|
2088
|
+
}
|
|
2089
|
+
catch (exc) {
|
|
2090
|
+
_clientLog('warn', '向 %s 回复群组密钥失败: %s', requester, formatCaughtError(exc));
|
|
2091
|
+
}
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
// R4: 收到 distribution/response 后触发 pending 消息重试
|
|
2095
|
+
if (result === 'distribution' || result === 'response') {
|
|
2096
|
+
const groupId = String(actualPayload.group_id ?? '');
|
|
2097
|
+
const rotationId = String(actualPayload.rotation_id ?? '');
|
|
2098
|
+
const keyCommitment = String(actualPayload.commitment ?? '');
|
|
2099
|
+
if (rotationId && keyCommitment) {
|
|
2100
|
+
this._ackGroupRotationKey(rotationId, keyCommitment)
|
|
2101
|
+
.catch((exc) => _clientLog('warn', '提交 epoch key ack 失败: %s', formatCaughtError(exc)));
|
|
2102
|
+
}
|
|
2103
|
+
this._scheduleRetryPendingDecryptMsgs(groupId);
|
|
2104
|
+
}
|
|
2105
|
+
return true;
|
|
2106
|
+
}
|
|
2107
|
+
// ── E2EE 编排辅助 ─────────────────────────────────────────
|
|
2108
|
+
/**
|
|
2109
|
+
* 获取对方证书(带缓存 + 完整 PKI 验证)。
|
|
2110
|
+
* 跨域时自动路由到 peer 所在域的 Gateway。
|
|
2111
|
+
*/
|
|
2112
|
+
async _fetchPeerCert(aid, certFingerprint) {
|
|
2113
|
+
const cacheKey = AUNClient._certCacheKey(aid, certFingerprint);
|
|
2114
|
+
const cached = this._certCache.get(cacheKey);
|
|
2115
|
+
const now = Date.now() / 1000;
|
|
2116
|
+
if (cached && now < cached.refreshAfter) {
|
|
2117
|
+
return cached.certPem;
|
|
2118
|
+
}
|
|
2119
|
+
const gatewayUrl = this._gatewayUrl;
|
|
2120
|
+
if (!gatewayUrl) {
|
|
2121
|
+
throw new ValidationError('gateway url unavailable for e2ee cert fetch');
|
|
2122
|
+
}
|
|
2123
|
+
// 跨域时用 peer 所在域的 Gateway URL
|
|
2124
|
+
const peerGatewayUrl = AUNClient._resolvePeerGatewayUrl(gatewayUrl, aid);
|
|
2125
|
+
let certPem;
|
|
2126
|
+
try {
|
|
2127
|
+
const certUrl = AUNClient._buildCertUrl(peerGatewayUrl, aid, certFingerprint);
|
|
2128
|
+
certPem = await _httpGetText(certUrl, this._configModel.verifySsl);
|
|
2129
|
+
}
|
|
2130
|
+
catch (exc) {
|
|
2131
|
+
if (!certFingerprint) {
|
|
2132
|
+
throw exc;
|
|
2133
|
+
}
|
|
2134
|
+
const fallbackCert = await _httpGetText(AUNClient._buildCertUrl(peerGatewayUrl, aid), this._configModel.verifySsl);
|
|
2135
|
+
certPem = fallbackCert;
|
|
2136
|
+
}
|
|
2137
|
+
// H7: 严格校验指纹(DER SHA-256 或 SPKI SHA-256 任一匹配即可)
|
|
2138
|
+
if (certFingerprint) {
|
|
2139
|
+
const expectedFP = String(certFingerprint).trim().toLowerCase();
|
|
2140
|
+
if (!expectedFP.startsWith('sha256:')) {
|
|
2141
|
+
throw new ValidationError(`unsupported cert_fingerprint format for ${aid}: ${expectedFP.slice(0, 24)}`);
|
|
2142
|
+
}
|
|
2143
|
+
const expectedHex = expectedFP.slice('sha256:'.length);
|
|
2144
|
+
const x509Cert = new crypto.X509Certificate(certPem);
|
|
2145
|
+
const derHex = x509Cert.fingerprint256.replace(/:/g, '').toLowerCase();
|
|
2146
|
+
let spkiHex = '';
|
|
2147
|
+
try {
|
|
2148
|
+
const spkiDer = x509Cert.publicKey.export({ type: 'spki', format: 'der' });
|
|
2149
|
+
spkiHex = crypto.createHash('sha256').update(spkiDer).digest('hex');
|
|
2150
|
+
}
|
|
2151
|
+
catch {
|
|
2152
|
+
spkiHex = '';
|
|
2153
|
+
}
|
|
2154
|
+
if (expectedHex !== derHex && (!spkiHex || expectedHex !== spkiHex)) {
|
|
2155
|
+
throw new ValidationError(`peer cert fingerprint mismatch for ${aid}: expected=${expectedFP.slice(0, 24)}...`);
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
// 完整 PKI 验证
|
|
2159
|
+
try {
|
|
2160
|
+
await this._auth.verifyPeerCertificate(peerGatewayUrl, certPem, aid);
|
|
2161
|
+
}
|
|
2162
|
+
catch (exc) {
|
|
2163
|
+
throw new ValidationError(`peer cert verification failed for ${aid}: ${exc instanceof Error ? exc.message : String(exc)}`);
|
|
2164
|
+
}
|
|
2165
|
+
const nowSec = Date.now() / 1000;
|
|
2166
|
+
this._certCache.set(cacheKey, {
|
|
2167
|
+
certPem,
|
|
2168
|
+
validatedAt: nowSec,
|
|
2169
|
+
refreshAfter: nowSec + PEER_CERT_CACHE_TTL,
|
|
2170
|
+
});
|
|
2171
|
+
try {
|
|
2172
|
+
// peer 证书只存版本目录,不覆盖 cert.pem
|
|
2173
|
+
this._keystore.saveCert(aid, certPem, certFingerprint, { makeActive: false });
|
|
2174
|
+
}
|
|
2175
|
+
catch (exc) {
|
|
2176
|
+
_clientLog('error', '写入证书到 keystore 失败 (aid=%s, fp=%s): %s', aid, certFingerprint ?? '', formatCaughtError(exc));
|
|
2177
|
+
}
|
|
2178
|
+
return certPem;
|
|
2179
|
+
}
|
|
2180
|
+
/** 获取对方所有设备的 prekey 列表。 */
|
|
2181
|
+
async _fetchPeerPrekeys(peerAid) {
|
|
2182
|
+
const cachedList = this._peerPrekeysCache.get(peerAid);
|
|
2183
|
+
if (cachedList && Date.now() / 1000 < cachedList.expireAt) {
|
|
2184
|
+
return cachedList.items.map((item) => ({ ...item }));
|
|
2185
|
+
}
|
|
2186
|
+
const cached = this._e2ee.getCachedPrekey(peerAid);
|
|
2187
|
+
if (cached !== null)
|
|
2188
|
+
return [{ ...cached }];
|
|
2189
|
+
try {
|
|
2190
|
+
const result = await this._transport.call('message.e2ee.get_prekey', { aid: peerAid });
|
|
2191
|
+
if (!isJsonObject(result)) {
|
|
2192
|
+
throw new ValidationError(`invalid prekey response for ${peerAid}`);
|
|
2193
|
+
}
|
|
2194
|
+
if (result.found === false) {
|
|
2195
|
+
return [];
|
|
2196
|
+
}
|
|
2197
|
+
const devicePrekeys = Array.isArray(result.device_prekeys) ? result.device_prekeys : null;
|
|
2198
|
+
if (devicePrekeys) {
|
|
2199
|
+
const normalized = [];
|
|
2200
|
+
for (const item of devicePrekeys) {
|
|
2201
|
+
if (!isPeerPrekeyMaterial(item)) {
|
|
2202
|
+
continue;
|
|
2203
|
+
}
|
|
2204
|
+
normalized.push({ ...item });
|
|
2205
|
+
}
|
|
2206
|
+
if (normalized.length > 0) {
|
|
2207
|
+
this._peerPrekeysCache.set(peerAid, {
|
|
2208
|
+
items: normalized.map((item) => ({ ...item })),
|
|
2209
|
+
expireAt: Date.now() / 1000 + 300,
|
|
2210
|
+
});
|
|
2211
|
+
this._e2ee.cachePrekey(peerAid, normalized[0]);
|
|
2212
|
+
return normalized;
|
|
2213
|
+
}
|
|
2214
|
+
}
|
|
2215
|
+
if (!isPeerPrekeyResponse(result)) {
|
|
2216
|
+
throw new ValidationError(`invalid prekey response for ${peerAid}`);
|
|
2217
|
+
}
|
|
2218
|
+
const prekey = result.prekey;
|
|
2219
|
+
if (prekey) {
|
|
2220
|
+
this._peerPrekeysCache.set(peerAid, {
|
|
2221
|
+
items: [{ ...prekey }],
|
|
2222
|
+
expireAt: Date.now() / 1000 + 300,
|
|
2223
|
+
});
|
|
2224
|
+
this._e2ee.cachePrekey(peerAid, prekey);
|
|
2225
|
+
return [{ ...prekey }];
|
|
2226
|
+
}
|
|
2227
|
+
if (result.found) {
|
|
2228
|
+
throw new ValidationError(`invalid prekey response for ${peerAid}`);
|
|
2229
|
+
}
|
|
2230
|
+
return [];
|
|
2231
|
+
}
|
|
2232
|
+
catch (exc) {
|
|
2233
|
+
if (exc instanceof ValidationError) {
|
|
2234
|
+
throw exc;
|
|
2235
|
+
}
|
|
2236
|
+
throw new ValidationError(`failed to fetch peer prekey for ${peerAid}: ${exc instanceof Error ? exc.message : String(exc)}`);
|
|
2237
|
+
}
|
|
2238
|
+
}
|
|
2239
|
+
/** 获取对方的单个 prekey(兼容接口,优先返回第一条 device prekey)。 */
|
|
2240
|
+
async _fetchPeerPrekey(peerAid) {
|
|
2241
|
+
const cachedList = this._peerPrekeysCache.get(peerAid);
|
|
2242
|
+
if (cachedList && Date.now() / 1000 < cachedList.expireAt && cachedList.items.length > 0) {
|
|
2243
|
+
return { ...cachedList.items[0] };
|
|
2244
|
+
}
|
|
2245
|
+
const prekeys = await this._fetchPeerPrekeys(peerAid);
|
|
2246
|
+
if (prekeys.length === 0) {
|
|
2247
|
+
return null;
|
|
2248
|
+
}
|
|
2249
|
+
return { ...prekeys[0] };
|
|
2250
|
+
}
|
|
2251
|
+
/** 生成 prekey 并上传到服务端 */
|
|
2252
|
+
async _uploadPrekey() {
|
|
2253
|
+
const prekeyMaterial = this._e2ee.generatePrekey();
|
|
2254
|
+
const result = await this._transport.call('message.e2ee.put_prekey', prekeyMaterial);
|
|
2255
|
+
return isJsonObject(result) ? { ...result } : { ok: true };
|
|
2256
|
+
}
|
|
2257
|
+
/**
|
|
2258
|
+
* 确保发送方证书在本地 keystore 中可用且未过期。
|
|
2259
|
+
* 返回 true 表示证书已就绪(PKI 验证通过),false 表示不可用。
|
|
2260
|
+
*/
|
|
2261
|
+
async _ensureSenderCertCached(aid, certFingerprint) {
|
|
2262
|
+
const cacheKey = AUNClient._certCacheKey(aid, certFingerprint);
|
|
2263
|
+
const cached = this._certCache.get(cacheKey);
|
|
2264
|
+
const now = Date.now() / 1000;
|
|
2265
|
+
if (cached && now < cached.refreshAfter) {
|
|
2266
|
+
return true;
|
|
2267
|
+
}
|
|
2268
|
+
const localCert = this._keystore.loadCert(aid, certFingerprint);
|
|
2269
|
+
if (localCert) {
|
|
2270
|
+
if (certFingerprint) {
|
|
2271
|
+
const actualFingerprint = `sha256:${new crypto.X509Certificate(localCert).fingerprint256.replace(/:/g, '').toLowerCase()}`;
|
|
2272
|
+
if (actualFingerprint !== String(certFingerprint).trim().toLowerCase()) {
|
|
2273
|
+
// 本地 active cert 与请求指纹不匹配,继续走远端获取
|
|
2274
|
+
}
|
|
2275
|
+
else {
|
|
2276
|
+
this._certCache.set(cacheKey, {
|
|
2277
|
+
certPem: localCert,
|
|
2278
|
+
validatedAt: now,
|
|
2279
|
+
refreshAfter: now + PEER_CERT_CACHE_TTL,
|
|
2280
|
+
});
|
|
2281
|
+
return true;
|
|
2282
|
+
}
|
|
2283
|
+
}
|
|
2284
|
+
else {
|
|
2285
|
+
this._certCache.set(cacheKey, {
|
|
2286
|
+
certPem: localCert,
|
|
2287
|
+
validatedAt: now,
|
|
2288
|
+
refreshAfter: now + PEER_CERT_CACHE_TTL,
|
|
2289
|
+
});
|
|
2290
|
+
return true;
|
|
2291
|
+
}
|
|
2292
|
+
}
|
|
2293
|
+
try {
|
|
2294
|
+
const certPem = await this._fetchPeerCert(aid, certFingerprint);
|
|
2295
|
+
// peer 证书只存版本目录,不覆盖 cert.pem
|
|
2296
|
+
this._keystore.saveCert(aid, certPem, certFingerprint, { makeActive: false });
|
|
2297
|
+
return true;
|
|
2298
|
+
}
|
|
2299
|
+
catch (exc) {
|
|
2300
|
+
// 刷新失败时:若内存缓存有 PKI 验证过的证书(未过期 x2 倍 TTL)则继续用
|
|
2301
|
+
if (cached && now < cached.validatedAt + PEER_CERT_CACHE_TTL * 2) {
|
|
2302
|
+
_clientLog('debug', '刷新发送方 %s 证书失败,继续使用已验证的内存缓存: %s', aid, formatCaughtError(exc));
|
|
2303
|
+
return true;
|
|
2304
|
+
}
|
|
2305
|
+
_clientLog('warn', '获取发送方 %s 证书失败且无已验证缓存,拒绝信任: %s', aid, formatCaughtError(exc));
|
|
2306
|
+
return false;
|
|
2307
|
+
}
|
|
2308
|
+
}
|
|
2309
|
+
/**
|
|
2310
|
+
* 获取经过 PKI 验证的 peer 证书(仅信任内存缓存中已验证的证书)。
|
|
2311
|
+
* 零信任:不直接信任 keystore 中可能由恶意服务端注入的证书。
|
|
2312
|
+
*/
|
|
2313
|
+
_getVerifiedPeerCert(aid, certFingerprint) {
|
|
2314
|
+
const cached = this._certCache.get(AUNClient._certCacheKey(aid, certFingerprint));
|
|
2315
|
+
const now = Date.now() / 1000;
|
|
2316
|
+
if (cached && now < cached.validatedAt + PEER_CERT_CACHE_TTL * 2) {
|
|
2317
|
+
return cached.certPem;
|
|
2318
|
+
}
|
|
2319
|
+
return null;
|
|
2320
|
+
}
|
|
2321
|
+
/** 解密单条 P2P 消息 */
|
|
2322
|
+
async _decryptSingleMessage(message) {
|
|
2323
|
+
const payload = message.payload;
|
|
2324
|
+
if (!isJsonObject(payload))
|
|
2325
|
+
return message;
|
|
2326
|
+
const payloadObj = payload;
|
|
2327
|
+
if (payloadObj.type !== 'e2ee.encrypted')
|
|
2328
|
+
return message;
|
|
2329
|
+
if (message.encrypted === false)
|
|
2330
|
+
return message;
|
|
2331
|
+
// 确保发送方证书已缓存到 keystore
|
|
2332
|
+
const fromAid = String(message.from ?? '');
|
|
2333
|
+
const senderCertFingerprint = String(payloadObj.sender_cert_fingerprint ?? payloadObj.aad?.sender_cert_fingerprint ?? '').trim().toLowerCase();
|
|
2334
|
+
if (fromAid) {
|
|
2335
|
+
const certReady = await this._ensureSenderCertCached(fromAid, senderCertFingerprint || undefined);
|
|
2336
|
+
if (!certReady) {
|
|
2337
|
+
_clientLog('warn', '无法获取发送方 %s 的证书,跳过解密', fromAid);
|
|
2338
|
+
throw new Error(`发送方证书不可用: from=${fromAid}, mid=${message.message_id}`);
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
// 密码学解密(E2EEManager.decryptMessage 内含本地防重放)
|
|
2342
|
+
const decrypted = this._e2ee.decryptMessage(message);
|
|
2343
|
+
this._schedulePrekeyReplenishIfConsumed(decrypted);
|
|
2344
|
+
// TS-015: 解密返回 null 表示失败(密文损坏/签名无效/重放等),
|
|
2345
|
+
// 不得回退到原始密文投递给应用层,应抛出错误触发 undecryptable 事件
|
|
2346
|
+
if (decrypted === null) {
|
|
2347
|
+
throw new Error(`E2EE 解密失败: from=${message.from}, mid=${message.message_id}`);
|
|
2348
|
+
}
|
|
2349
|
+
return decrypted;
|
|
2350
|
+
}
|
|
2351
|
+
/** 批量解密 P2P 消息(用于 message.pull) */
|
|
2352
|
+
async _decryptMessages(messages) {
|
|
2353
|
+
const seenInBatch = new Set();
|
|
2354
|
+
const result = [];
|
|
2355
|
+
for (const msg of messages) {
|
|
2356
|
+
const mid = String(msg.message_id ?? '');
|
|
2357
|
+
if (mid && seenInBatch.has(mid))
|
|
2358
|
+
continue;
|
|
2359
|
+
if (mid)
|
|
2360
|
+
seenInBatch.add(mid);
|
|
2361
|
+
const payload = msg.payload;
|
|
2362
|
+
if (isJsonObject(payload)
|
|
2363
|
+
&& payload.type === 'e2ee.encrypted'
|
|
2364
|
+
&& (msg.encrypted === true || !('encrypted' in msg))) {
|
|
2365
|
+
if (await this._tryHandleGroupKeyMessage(msg)) {
|
|
2366
|
+
continue;
|
|
2367
|
+
}
|
|
2368
|
+
const fromAid = String(msg.from ?? '');
|
|
2369
|
+
const senderCertFingerprint = String(payload.sender_cert_fingerprint ?? payload.aad?.sender_cert_fingerprint ?? '').trim().toLowerCase();
|
|
2370
|
+
if (fromAid) {
|
|
2371
|
+
const certReady = await this._ensureSenderCertCached(fromAid, senderCertFingerprint || undefined);
|
|
2372
|
+
if (!certReady) {
|
|
2373
|
+
_clientLog('warn', '无法获取发送方 %s 的证书,跳过解密', fromAid);
|
|
2374
|
+
continue;
|
|
2375
|
+
}
|
|
2376
|
+
}
|
|
2377
|
+
// pull 路径必须绕过本地 seen set,避免同一条消息先经 push 解密后再 pull 被误判为重放。
|
|
2378
|
+
const decrypted = this._e2ee._decryptMessage(msg);
|
|
2379
|
+
if (decrypted !== null) {
|
|
2380
|
+
result.push(decrypted);
|
|
2381
|
+
}
|
|
2382
|
+
else {
|
|
2383
|
+
// TS-015: 解密失败不回退到密文,跳过该消息并记录
|
|
2384
|
+
_clientLog('warn', 'pull 消息解密失败,跳过: from=%s mid=%s', msg.from, msg.message_id);
|
|
2385
|
+
}
|
|
2386
|
+
}
|
|
2387
|
+
else {
|
|
2388
|
+
result.push(msg);
|
|
2389
|
+
}
|
|
2390
|
+
}
|
|
2391
|
+
return result;
|
|
2392
|
+
}
|
|
2393
|
+
/** 解密单条群组消息。opts.skipReplay 用于 group.pull 场景跳过防重放。 */
|
|
2394
|
+
_enqueuePendingDecrypt(groupId, msg) {
|
|
2395
|
+
const ns = `group:${groupId}`;
|
|
2396
|
+
const queue = this._pendingDecryptMsgs.get(ns) ?? [];
|
|
2397
|
+
queue.push(msg);
|
|
2398
|
+
this._pendingDecryptMsgs.set(ns, queue.slice(-200));
|
|
2399
|
+
}
|
|
2400
|
+
async _retryPendingDecryptMsgs(groupId) {
|
|
2401
|
+
const ns = `group:${groupId}`;
|
|
2402
|
+
const queue = this._pendingDecryptMsgs.get(ns);
|
|
2403
|
+
if (!queue || queue.length === 0)
|
|
2404
|
+
return;
|
|
2405
|
+
this._pendingDecryptMsgs.set(ns, []);
|
|
2406
|
+
const stillPending = [];
|
|
2407
|
+
for (const msg of queue) {
|
|
2408
|
+
try {
|
|
2409
|
+
const decrypted = await this._decryptGroupMessage(msg);
|
|
2410
|
+
const payload = isJsonObject(msg.payload) ? msg.payload : null;
|
|
2411
|
+
if (payload?.type === 'e2ee.group_encrypted' && !decrypted.e2ee) {
|
|
2412
|
+
stillPending.push(msg);
|
|
2413
|
+
continue;
|
|
2414
|
+
}
|
|
2415
|
+
await this._dispatcher.publish('group.message_created', decrypted);
|
|
2416
|
+
}
|
|
2417
|
+
catch {
|
|
2418
|
+
stillPending.push(msg);
|
|
2419
|
+
}
|
|
2420
|
+
}
|
|
2421
|
+
const queuedDuringRetry = this._pendingDecryptMsgs.get(ns) ?? [];
|
|
2422
|
+
const mergedPending = [...stillPending, ...queuedDuringRetry].slice(-200);
|
|
2423
|
+
if (mergedPending.length)
|
|
2424
|
+
this._pendingDecryptMsgs.set(ns, mergedPending);
|
|
2425
|
+
else
|
|
2426
|
+
this._pendingDecryptMsgs.delete(ns);
|
|
2427
|
+
}
|
|
2428
|
+
_scheduleRetryPendingDecryptMsgs(groupId) {
|
|
2429
|
+
if (!groupId || !this._pendingDecryptMsgs.has(`group:${groupId}`))
|
|
2430
|
+
return;
|
|
2431
|
+
this._retryPendingDecryptMsgs(groupId).catch((exc) => _clientLog('warn', '群 %s pending 消息重试失败: %s', groupId, formatCaughtError(exc)));
|
|
2432
|
+
}
|
|
2433
|
+
async _recoverGroupEpochKey(groupId, epoch, senderAid = '', timeoutMs = 5000) {
|
|
2434
|
+
const existing = await this._groupE2ee.loadSecret(groupId, epoch);
|
|
2435
|
+
if (await this._groupEpochSecretReadyForRecovery(groupId, epoch, existing)) {
|
|
2436
|
+
this._scheduleRetryPendingDecryptMsgs(groupId);
|
|
2437
|
+
return true;
|
|
2438
|
+
}
|
|
2439
|
+
// inflight 去重:同 groupId:epoch 的并发恢复共享同一个 Promise
|
|
2440
|
+
const key = `${groupId}:${epoch}`;
|
|
2441
|
+
const inflight = this._groupEpochRecoveryInflight.get(key);
|
|
2442
|
+
if (inflight)
|
|
2443
|
+
return inflight;
|
|
2444
|
+
const promise = this._doRecoverGroupEpochKey(groupId, epoch, senderAid, timeoutMs)
|
|
2445
|
+
.finally(() => this._groupEpochRecoveryInflight.delete(key));
|
|
2446
|
+
this._groupEpochRecoveryInflight.set(key, promise);
|
|
2447
|
+
return promise;
|
|
2448
|
+
}
|
|
2449
|
+
async _doRecoverGroupEpochKey(groupId, epoch, senderAid, timeoutMs) {
|
|
2450
|
+
let epochResult = { epoch };
|
|
2451
|
+
try {
|
|
2452
|
+
const raw = await this.call('group.e2ee.get_epoch', { group_id: groupId });
|
|
2453
|
+
if (isJsonObject(raw))
|
|
2454
|
+
epochResult = { ...epochResult, ...raw };
|
|
2455
|
+
}
|
|
2456
|
+
catch {
|
|
2457
|
+
// 候选查询失败时仍使用 sender/local members 兜底。
|
|
2458
|
+
}
|
|
2459
|
+
if (senderAid) {
|
|
2460
|
+
const current = Array.isArray(epochResult.recovery_candidates) ? epochResult.recovery_candidates : [];
|
|
2461
|
+
epochResult.recovery_candidates = [senderAid, ...current];
|
|
2462
|
+
}
|
|
2463
|
+
await this._requestGroupKeyFromCandidates(groupId, epoch, epochResult);
|
|
2464
|
+
const deadline = Date.now() + timeoutMs;
|
|
2465
|
+
while (Date.now() < deadline) {
|
|
2466
|
+
await new Promise(resolve => setTimeout(resolve, 150));
|
|
2467
|
+
const secret = await this._groupE2ee.loadSecret(groupId, epoch);
|
|
2468
|
+
if (await this._groupEpochSecretReadyForRecovery(groupId, epoch, secret)) {
|
|
2469
|
+
this._scheduleRetryPendingDecryptMsgs(groupId);
|
|
2470
|
+
return true;
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
const secret = await this._groupE2ee.loadSecret(groupId, epoch);
|
|
2474
|
+
const ready = await this._groupEpochSecretReadyForRecovery(groupId, epoch, secret);
|
|
2475
|
+
if (ready)
|
|
2476
|
+
this._scheduleRetryPendingDecryptMsgs(groupId);
|
|
2477
|
+
return ready;
|
|
2478
|
+
}
|
|
2479
|
+
async _groupEpochSecretReadyForRecovery(groupId, epoch, secret) {
|
|
2480
|
+
if (!isJsonObject(secret))
|
|
2481
|
+
return false;
|
|
2482
|
+
const pendingRotationId = String(secret.pending_rotation_id ?? '').trim();
|
|
2483
|
+
if (!pendingRotationId)
|
|
2484
|
+
return true;
|
|
2485
|
+
return this._pendingGroupSecretStillCurrent(groupId, epoch, pendingRotationId);
|
|
2486
|
+
}
|
|
2487
|
+
async _pendingGroupSecretStillCurrent(groupId, epoch, pendingRotationId) {
|
|
2488
|
+
try {
|
|
2489
|
+
const epochResult = await this.call('group.e2ee.get_epoch', { group_id: groupId });
|
|
2490
|
+
if (!isJsonObject(epochResult))
|
|
2491
|
+
return false;
|
|
2492
|
+
const pending = isJsonObject(epochResult.pending_rotation) ? epochResult.pending_rotation : null;
|
|
2493
|
+
if (pending
|
|
2494
|
+
&& !pending.expired
|
|
2495
|
+
&& String(pending.rotation_id ?? '').trim() === pendingRotationId) {
|
|
2496
|
+
return true;
|
|
2497
|
+
}
|
|
2498
|
+
const committedRotation = isJsonObject(epochResult.committed_rotation) ? epochResult.committed_rotation : null;
|
|
2499
|
+
const committedTargetEpoch = Number(committedRotation?.target_epoch ?? 0);
|
|
2500
|
+
return Boolean(committedRotation
|
|
2501
|
+
&& Number.isFinite(committedTargetEpoch)
|
|
2502
|
+
&& committedTargetEpoch === epoch
|
|
2503
|
+
&& String(committedRotation.rotation_id ?? '').trim() === pendingRotationId);
|
|
2504
|
+
}
|
|
2505
|
+
catch {
|
|
2506
|
+
return false;
|
|
2507
|
+
}
|
|
2508
|
+
}
|
|
2509
|
+
async _decryptGroupMessage(message, opts) {
|
|
2510
|
+
const payload = message.payload;
|
|
2511
|
+
if (!isJsonObject(payload))
|
|
2512
|
+
return message;
|
|
2513
|
+
const payloadObj = payload;
|
|
2514
|
+
if (payloadObj.type !== 'e2ee.group_encrypted')
|
|
2515
|
+
return message;
|
|
2516
|
+
// 确保发送方证书已缓存(签名验证需要)
|
|
2517
|
+
const senderAid = String(message.from ?? message.sender_aid ?? '');
|
|
2518
|
+
if (senderAid) {
|
|
2519
|
+
const certOk = await this._ensureSenderCertCached(senderAid);
|
|
2520
|
+
if (!certOk) {
|
|
2521
|
+
_clientLog('warn', '群消息解密跳过:发送方 %s 证书不可用', senderAid);
|
|
2522
|
+
return message;
|
|
2523
|
+
}
|
|
2524
|
+
}
|
|
2525
|
+
// 先尝试直接解密
|
|
2526
|
+
const result = this._groupE2ee.decrypt(message, opts);
|
|
2527
|
+
if (result !== null && result.e2ee) {
|
|
2528
|
+
return result;
|
|
2529
|
+
}
|
|
2530
|
+
// replay guard 命中:decrypt 返回了原消息(非 null)但无 e2ee 字段
|
|
2531
|
+
// 不是解密失败,不应触发 recover
|
|
2532
|
+
if (result !== null) {
|
|
2533
|
+
return result;
|
|
2534
|
+
}
|
|
2535
|
+
// 真正的解密失败(result === null),尝试密钥恢复后重试
|
|
2536
|
+
const groupId = String(message.group_id ?? '');
|
|
2537
|
+
const sender = String(message.from ?? message.sender_aid ?? '');
|
|
2538
|
+
const epoch = Number(payloadObj.epoch ?? 0);
|
|
2539
|
+
if (epoch > 0 && groupId) {
|
|
2540
|
+
try {
|
|
2541
|
+
if (await this._recoverGroupEpochKey(groupId, epoch, sender, 5000)) {
|
|
2542
|
+
const retry = await this._groupE2ee.decrypt(message, opts);
|
|
2543
|
+
if (retry !== null && retry.e2ee)
|
|
2544
|
+
return retry;
|
|
2545
|
+
}
|
|
2546
|
+
}
|
|
2547
|
+
catch (exc) {
|
|
2548
|
+
_clientLog('debug', '群 %s epoch %s 同步恢复失败: %s', groupId, epoch, formatCaughtError(exc));
|
|
2549
|
+
}
|
|
2550
|
+
}
|
|
2551
|
+
return message;
|
|
2552
|
+
}
|
|
2553
|
+
/** 批量解密群组消息(用于 group.pull,跳过防重放) */
|
|
2554
|
+
async _decryptGroupMessages(messages) {
|
|
2555
|
+
const result = [];
|
|
2556
|
+
for (const msg of messages) {
|
|
2557
|
+
const decrypted = await this._decryptGroupMessage(msg);
|
|
2558
|
+
const payload = isJsonObject(msg.payload) ? msg.payload : null;
|
|
2559
|
+
const groupId = String(msg.group_id ?? '');
|
|
2560
|
+
if (payload?.type === 'e2ee.group_encrypted' && groupId && !decrypted.e2ee) {
|
|
2561
|
+
this._enqueuePendingDecrypt(groupId, msg);
|
|
2562
|
+
continue; // R3: 解密失败不入 result,不 publish 密文给应用层
|
|
2563
|
+
}
|
|
2564
|
+
result.push(decrypted);
|
|
2565
|
+
}
|
|
2566
|
+
return result;
|
|
2567
|
+
}
|
|
2568
|
+
// ── Group E2EE 编排 ───────────────────────────────────────
|
|
2569
|
+
_attachRotationId(info, rotationId) {
|
|
2570
|
+
if (!rotationId || !Array.isArray(info.distributions))
|
|
2571
|
+
return;
|
|
2572
|
+
for (const dist of info.distributions) {
|
|
2573
|
+
if (isJsonObject(dist) && isJsonObject(dist.payload)) {
|
|
2574
|
+
dist.payload.rotation_id = rotationId;
|
|
2575
|
+
}
|
|
2576
|
+
}
|
|
2577
|
+
}
|
|
2578
|
+
async _getGroupMemberAids(groupId) {
|
|
2579
|
+
const membersResult = await this.call('group.get_members', { group_id: groupId });
|
|
2580
|
+
const rawList = isJsonObject(membersResult)
|
|
2581
|
+
? (Array.isArray(membersResult.members) ? membersResult.members : membersResult.items)
|
|
2582
|
+
: [];
|
|
2583
|
+
if (!Array.isArray(rawList))
|
|
2584
|
+
return [];
|
|
2585
|
+
const aids = [];
|
|
2586
|
+
for (const item of rawList) {
|
|
2587
|
+
if (!isJsonObject(item))
|
|
2588
|
+
continue;
|
|
2589
|
+
const aid = String(item.aid ?? '').trim();
|
|
2590
|
+
if (aid)
|
|
2591
|
+
aids.push(aid);
|
|
2592
|
+
}
|
|
2593
|
+
return aids;
|
|
2594
|
+
}
|
|
2595
|
+
async _distributeGroupEpochKey(info, rotationId = '') {
|
|
2596
|
+
const sent = [];
|
|
2597
|
+
const failed = [];
|
|
2598
|
+
let lastHeartbeat = Date.now();
|
|
2599
|
+
const distributions = (Array.isArray(info.distributions) ? info.distributions : []);
|
|
2600
|
+
for (const dist of distributions) {
|
|
2601
|
+
if (!isJsonObject(dist) || !dist.to || !isJsonObject(dist.payload))
|
|
2602
|
+
continue;
|
|
2603
|
+
if (rotationId && Date.now() - lastHeartbeat >= 20_000) {
|
|
2604
|
+
if (await this._heartbeatGroupRotation(rotationId))
|
|
2605
|
+
lastHeartbeat = Date.now();
|
|
2606
|
+
}
|
|
2607
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
2608
|
+
try {
|
|
2609
|
+
await this.call('message.send', {
|
|
2610
|
+
to: dist.to,
|
|
2611
|
+
payload: dist.payload,
|
|
2612
|
+
encrypt: true,
|
|
2613
|
+
persist_required: true,
|
|
2614
|
+
});
|
|
2615
|
+
sent.push(String(dist.to));
|
|
2616
|
+
break;
|
|
2617
|
+
}
|
|
2618
|
+
catch (exc) {
|
|
2619
|
+
if (attempt < 2) {
|
|
2620
|
+
await new Promise(resolve => setTimeout(resolve, (attempt + 1) * 1000));
|
|
2621
|
+
}
|
|
2622
|
+
else {
|
|
2623
|
+
failed.push(String(dist.to));
|
|
2624
|
+
_clientLog('warn', 'epoch 密钥分发失败 (to=%s): %s', dist.to, formatCaughtError(exc));
|
|
2625
|
+
}
|
|
2626
|
+
}
|
|
2627
|
+
}
|
|
2628
|
+
}
|
|
2629
|
+
return { sent, failed };
|
|
2630
|
+
}
|
|
2631
|
+
async _heartbeatGroupRotation(rotationId) {
|
|
2632
|
+
if (!rotationId)
|
|
2633
|
+
return false;
|
|
2634
|
+
try {
|
|
2635
|
+
const result = await this.call('group.e2ee.heartbeat_rotation', {
|
|
2636
|
+
rotation_id: rotationId,
|
|
2637
|
+
lease_ms: GROUP_ROTATION_LEASE_MS,
|
|
2638
|
+
});
|
|
2639
|
+
return isJsonObject(result) && result.success === true;
|
|
2640
|
+
}
|
|
2641
|
+
catch (exc) {
|
|
2642
|
+
_clientLog('warn', '刷新 epoch rotation lease 失败: rotation=%s err=%s', rotationId, formatCaughtError(exc));
|
|
2643
|
+
return false;
|
|
2644
|
+
}
|
|
2645
|
+
}
|
|
2646
|
+
async _ackGroupRotationKey(rotationId, keyCommitment, deviceId) {
|
|
2647
|
+
if (!rotationId)
|
|
2648
|
+
return false;
|
|
2649
|
+
try {
|
|
2650
|
+
const result = await this.call('group.e2ee.ack_rotation_key', {
|
|
2651
|
+
rotation_id: rotationId,
|
|
2652
|
+
key_commitment: keyCommitment,
|
|
2653
|
+
device_id: deviceId ?? this._deviceId,
|
|
2654
|
+
});
|
|
2655
|
+
return isJsonObject(result) && result.success === true;
|
|
2656
|
+
}
|
|
2657
|
+
catch (exc) {
|
|
2658
|
+
_clientLog('warn', '提交 epoch key ack 失败: rotation=%s err=%s', rotationId, formatCaughtError(exc));
|
|
2659
|
+
return false;
|
|
2660
|
+
}
|
|
2661
|
+
}
|
|
2662
|
+
async _verifyActiveGroupRotationDistribution(payload) {
|
|
2663
|
+
const rotationId = String(payload.rotation_id ?? '').trim();
|
|
2664
|
+
const groupId = String(payload.group_id ?? '').trim();
|
|
2665
|
+
if (!groupId)
|
|
2666
|
+
return false;
|
|
2667
|
+
const epoch = Number(payload.epoch ?? 0);
|
|
2668
|
+
if (!Number.isFinite(epoch) || epoch <= 0)
|
|
2669
|
+
return false;
|
|
2670
|
+
const commitment = String(payload.commitment ?? '').trim();
|
|
2671
|
+
try {
|
|
2672
|
+
const epochResult = await this.call('group.e2ee.get_epoch', { group_id: groupId });
|
|
2673
|
+
if (!isJsonObject(epochResult))
|
|
2674
|
+
return false;
|
|
2675
|
+
const committedRotation = isJsonObject(epochResult.committed_rotation) ? epochResult.committed_rotation : null;
|
|
2676
|
+
const committedEpoch = Number(epochResult.committed_epoch ?? epochResult.epoch ?? 0);
|
|
2677
|
+
if (!rotationId) {
|
|
2678
|
+
if (Number.isFinite(epoch) && epoch > 0 && epoch <= committedEpoch) {
|
|
2679
|
+
if (committedRotation && Number(committedRotation.target_epoch ?? committedEpoch) === epoch) {
|
|
2680
|
+
const committedCommitment = String(committedRotation.key_commitment ?? '').trim();
|
|
2681
|
+
if (committedCommitment && commitment && committedCommitment !== commitment)
|
|
2682
|
+
return false;
|
|
2683
|
+
}
|
|
2684
|
+
return true;
|
|
2685
|
+
}
|
|
2686
|
+
_clientLog('info', '拒绝缺少 rotation_id 的未来 epoch key 分发: group=%s epoch=%s committed=%s', groupId, epoch, committedEpoch);
|
|
2687
|
+
return false;
|
|
2688
|
+
}
|
|
2689
|
+
const pending = isJsonObject(epochResult.pending_rotation) ? epochResult.pending_rotation : null;
|
|
2690
|
+
if (pending && !pending.expired) {
|
|
2691
|
+
const pendingCommitment = String(pending.key_commitment ?? '').trim();
|
|
2692
|
+
if (String(pending.rotation_id ?? '') === rotationId
|
|
2693
|
+
&& Number(pending.target_epoch ?? 0) === epoch
|
|
2694
|
+
&& (!pendingCommitment || pendingCommitment === commitment)) {
|
|
2695
|
+
return true;
|
|
2696
|
+
}
|
|
2697
|
+
}
|
|
2698
|
+
if (committedRotation && committedEpoch >= epoch) {
|
|
2699
|
+
const committedCommitment = String(committedRotation.key_commitment ?? '').trim();
|
|
2700
|
+
if (String(committedRotation.rotation_id ?? '') === rotationId
|
|
2701
|
+
&& (!committedCommitment || committedCommitment === commitment)) {
|
|
2702
|
+
return true;
|
|
2703
|
+
}
|
|
2704
|
+
}
|
|
2705
|
+
}
|
|
2706
|
+
catch (exc) {
|
|
2707
|
+
_clientLog('warn', '拒绝无法校验 active rotation 的 epoch key 分发: group=%s rotation=%s err=%s', groupId, rotationId, formatCaughtError(exc));
|
|
2708
|
+
return false;
|
|
2709
|
+
}
|
|
2710
|
+
_clientLog('info', '拒绝非 pending/committed 状态的 epoch key 分发: group=%s rotation=%s epoch=%s', groupId, rotationId, epoch);
|
|
2711
|
+
return false;
|
|
2712
|
+
}
|
|
2713
|
+
async _discardGroupDistributionIfStale(payload) {
|
|
2714
|
+
const rotationId = String(payload.rotation_id ?? '').trim();
|
|
2715
|
+
if (!rotationId)
|
|
2716
|
+
return;
|
|
2717
|
+
const groupId = String(payload.group_id ?? '').trim();
|
|
2718
|
+
const epoch = Number(payload.epoch ?? 0);
|
|
2719
|
+
if (!groupId || !Number.isFinite(epoch) || epoch <= 0)
|
|
2720
|
+
return;
|
|
2721
|
+
if (await this._verifyActiveGroupRotationDistribution(payload))
|
|
2722
|
+
return;
|
|
2723
|
+
try {
|
|
2724
|
+
this._groupE2ee.discardPendingSecret(groupId, epoch, rotationId);
|
|
2725
|
+
_clientLog('info', '丢弃 verify 后变为 stale 的 group epoch key: group=%s epoch=%s rotation=%s', groupId, epoch, rotationId);
|
|
2726
|
+
}
|
|
2727
|
+
catch (exc) {
|
|
2728
|
+
_clientLog('debug', '清理 stale group epoch key 失败: group=%s epoch=%s rotation=%s err=%s', groupId, epoch, rotationId, formatCaughtError(exc));
|
|
2729
|
+
}
|
|
2730
|
+
}
|
|
2731
|
+
async _verifyGroupKeyResponseEpoch(payload) {
|
|
2732
|
+
const groupId = String(payload.group_id ?? '').trim();
|
|
2733
|
+
if (!groupId)
|
|
2734
|
+
return false;
|
|
2735
|
+
const epoch = Number(payload.epoch ?? 0);
|
|
2736
|
+
if (!Number.isFinite(epoch) || epoch <= 0)
|
|
2737
|
+
return false;
|
|
2738
|
+
const commitment = String(payload.commitment ?? '').trim();
|
|
2739
|
+
try {
|
|
2740
|
+
const epochResult = await this.call('group.e2ee.get_epoch', { group_id: groupId });
|
|
2741
|
+
if (!isJsonObject(epochResult))
|
|
2742
|
+
return false;
|
|
2743
|
+
const committedEpoch = Number(epochResult.committed_epoch ?? epochResult.epoch ?? 0);
|
|
2744
|
+
if (epoch > committedEpoch) {
|
|
2745
|
+
_clientLog('info', '拒绝未提交 epoch 的 group key response: group=%s epoch=%s committed=%s', groupId, epoch, committedEpoch);
|
|
2746
|
+
return false;
|
|
2747
|
+
}
|
|
2748
|
+
const committedRotation = isJsonObject(epochResult.committed_rotation) ? epochResult.committed_rotation : null;
|
|
2749
|
+
if (committedRotation && Number(committedRotation.target_epoch ?? committedEpoch) === epoch) {
|
|
2750
|
+
const committedCommitment = String(committedRotation.key_commitment ?? '').trim();
|
|
2751
|
+
if (committedCommitment && commitment && committedCommitment !== commitment)
|
|
2752
|
+
return false;
|
|
2753
|
+
}
|
|
2754
|
+
return true;
|
|
2755
|
+
}
|
|
2756
|
+
catch (exc) {
|
|
2757
|
+
_clientLog('warn', '拒绝无法校验 committed epoch 的 group key response: group=%s epoch=%s err=%s', groupId, epoch, formatCaughtError(exc));
|
|
2758
|
+
return false;
|
|
2759
|
+
}
|
|
2760
|
+
}
|
|
2761
|
+
async _abortGroupRotation(rotationId, reason = '') {
|
|
2762
|
+
if (!rotationId)
|
|
2763
|
+
return false;
|
|
2764
|
+
try {
|
|
2765
|
+
const result = await this.call('group.e2ee.abort_rotation', {
|
|
2766
|
+
rotation_id: rotationId,
|
|
2767
|
+
reason: reason || 'client_abort',
|
|
2768
|
+
});
|
|
2769
|
+
return isJsonObject(result) && result.success === true;
|
|
2770
|
+
}
|
|
2771
|
+
catch (exc) {
|
|
2772
|
+
_clientLog('warn', '中止 epoch rotation 失败: rotation=%s err=%s', rotationId, formatCaughtError(exc));
|
|
2773
|
+
return false;
|
|
2774
|
+
}
|
|
2775
|
+
}
|
|
2776
|
+
_rotationExpectedMembersStale(rotation, memberAids) {
|
|
2777
|
+
const expected = Array.isArray(rotation.expected_members)
|
|
2778
|
+
? rotation.expected_members.map((item) => String(item ?? '').trim()).filter(Boolean).sort()
|
|
2779
|
+
: [];
|
|
2780
|
+
const current = memberAids.map((item) => String(item ?? '').trim()).filter(Boolean).sort();
|
|
2781
|
+
return expected.length > 0 && current.length > 0 && expected.join('\n') !== current.join('\n');
|
|
2782
|
+
}
|
|
2783
|
+
_rotationRetryDelayMs(pending) {
|
|
2784
|
+
let leaseExpiresAt = 0;
|
|
2785
|
+
if (pending && !pending.expired && ['', 'distributing'].includes(String(pending.status ?? ''))) {
|
|
2786
|
+
const parsed = Number(pending.lease_expires_at ?? 0);
|
|
2787
|
+
if (Number.isFinite(parsed))
|
|
2788
|
+
leaseExpiresAt = parsed;
|
|
2789
|
+
}
|
|
2790
|
+
const base = leaseExpiresAt
|
|
2791
|
+
? Math.max(1000, leaseExpiresAt - Date.now() + 1000)
|
|
2792
|
+
: 5000;
|
|
2793
|
+
return Math.min(base + Math.floor(Math.random() * 2000), GROUP_ROTATION_RETRY_MAX_DELAY_MS);
|
|
2794
|
+
}
|
|
2795
|
+
_scheduleGroupRotationRetry(groupId, opts) {
|
|
2796
|
+
if (this._closing || this._state !== 'connected')
|
|
2797
|
+
return;
|
|
2798
|
+
const retryKey = `${groupId}:${opts.triggerId || opts.reason}:${opts.expectedEpoch ?? '-'}`;
|
|
2799
|
+
if (this._groupEpochRotationRetryTimers.has(retryKey))
|
|
2800
|
+
return;
|
|
2801
|
+
const timer = setTimeout(() => {
|
|
2802
|
+
this._groupEpochRotationRetryTimers.delete(retryKey);
|
|
2803
|
+
if (this._closing || this._state !== 'connected')
|
|
2804
|
+
return;
|
|
2805
|
+
this._maybeLeadRotateGroupEpoch(groupId, opts.triggerId, opts.expectedEpoch)
|
|
2806
|
+
.catch((exc) => _clientLog('warn', 'group epoch rotation retry failed: %s', formatCaughtError(exc)));
|
|
2807
|
+
}, this._rotationRetryDelayMs(opts.pending));
|
|
2808
|
+
this._groupEpochRotationRetryTimers.set(retryKey, timer);
|
|
2809
|
+
this._unrefTimer(timer);
|
|
2810
|
+
}
|
|
2811
|
+
/** 建群后将本地 epoch 1 同步到服务端(服务端初始为 0),最多重试 3 次 */
|
|
2812
|
+
async _syncEpochToServer(groupId) {
|
|
2813
|
+
const started = Date.now();
|
|
2814
|
+
while (this._groupEpochRotationInflight.has(groupId)) {
|
|
2815
|
+
if (this._closing || this._state !== 'connected')
|
|
2816
|
+
return;
|
|
2817
|
+
if (Date.now() - started > 20000) {
|
|
2818
|
+
_clientLog('warn', 'group epoch create sync still in-flight; skip duplicate sync (group=%s)', groupId);
|
|
2819
|
+
return;
|
|
2820
|
+
}
|
|
2821
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
2822
|
+
}
|
|
2823
|
+
if (this._closing || this._state !== 'connected')
|
|
2824
|
+
return;
|
|
2825
|
+
this._groupEpochRotationInflight.add(groupId);
|
|
2826
|
+
try {
|
|
2827
|
+
const maxRetries = 3;
|
|
2828
|
+
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
2829
|
+
try {
|
|
2830
|
+
if (!this._aid)
|
|
2831
|
+
return;
|
|
2832
|
+
const secretData = this._groupE2ee.loadSecret(groupId, 1);
|
|
2833
|
+
if (!secretData)
|
|
2834
|
+
throw new StateError(`group ${groupId} epoch 1 secret missing`);
|
|
2835
|
+
const rotationId = `rot-${crypto.randomUUID().replace(/-/g, '')}`;
|
|
2836
|
+
const rotateParams = {
|
|
2837
|
+
group_id: groupId,
|
|
2838
|
+
base_epoch: 0,
|
|
2839
|
+
target_epoch: 1,
|
|
2840
|
+
rotation_id: rotationId,
|
|
2841
|
+
reason: 'create_group',
|
|
2842
|
+
key_commitment: secretData.commitment,
|
|
2843
|
+
expected_members: secretData.member_aids.length > 0 ? secretData.member_aids : [this._aid],
|
|
2844
|
+
required_acks: [this._aid],
|
|
2845
|
+
lease_ms: GROUP_ROTATION_LEASE_MS,
|
|
2846
|
+
};
|
|
2847
|
+
Object.assign(rotateParams, this._buildRotationSignature(groupId, 0, 1, rotateParams));
|
|
2848
|
+
const beginResult = await this.call('group.e2ee.begin_rotation', rotateParams);
|
|
2849
|
+
const rotation = isJsonObject(beginResult) && isJsonObject(beginResult.rotation) ? beginResult.rotation : null;
|
|
2850
|
+
if (!isJsonObject(beginResult) || beginResult.success !== true || !rotation) {
|
|
2851
|
+
_clientLog('warn', 'group epoch begin failed; stop key distribution (group=%s, returned=%s)', groupId, JSON.stringify(beginResult));
|
|
2852
|
+
return;
|
|
2853
|
+
}
|
|
2854
|
+
const activeRotationId = String(rotation.rotation_id ?? rotationId);
|
|
2855
|
+
if (!await this._ackGroupRotationKey(activeRotationId, secretData.commitment)) {
|
|
2856
|
+
_clientLog('warn', 'group epoch self ack failed (group=%s, rotation=%s)', groupId, activeRotationId);
|
|
2857
|
+
await this._abortGroupRotation(activeRotationId, 'self_ack_failed');
|
|
2858
|
+
return;
|
|
2859
|
+
}
|
|
2860
|
+
const commitResult = await this.call('group.e2ee.commit_rotation', { rotation_id: activeRotationId });
|
|
2861
|
+
if (isJsonObject(commitResult) && commitResult.success === true) {
|
|
2862
|
+
storeGroupSecret(this._keystore, this._aid, groupId, 1, secretData.secret, secretData.commitment, secretData.member_aids, secretData.epoch_chain);
|
|
2863
|
+
return;
|
|
2864
|
+
}
|
|
2865
|
+
_clientLog('warn', 'group epoch commit failed (group=%s, returned=%s)', groupId, JSON.stringify(commitResult));
|
|
2866
|
+
return;
|
|
2867
|
+
}
|
|
2868
|
+
catch (exc) {
|
|
2869
|
+
if (attempt < maxRetries) {
|
|
2870
|
+
const delay = 500 * Math.pow(2, attempt - 1);
|
|
2871
|
+
_clientLog('warn', '同步 epoch 到服务端失败 (group=%s, 第%d/%d次): %s, %dms后重试', groupId, attempt, maxRetries, formatCaughtError(exc), delay);
|
|
2872
|
+
await new Promise(r => setTimeout(r, delay));
|
|
2873
|
+
}
|
|
2874
|
+
else {
|
|
2875
|
+
_clientLog('error', '同步 epoch 到服务端最终失败 (group=%s, 已重试%d次): %s', groupId, maxRetries, formatCaughtError(exc));
|
|
2876
|
+
}
|
|
2877
|
+
}
|
|
2878
|
+
}
|
|
2879
|
+
}
|
|
2880
|
+
finally {
|
|
2881
|
+
this._groupEpochRotationInflight.delete(groupId);
|
|
2882
|
+
}
|
|
2883
|
+
}
|
|
2884
|
+
/**
|
|
2885
|
+
* 为指定群组轮换 epoch 并分发新密钥。
|
|
2886
|
+
* 使用服务端两阶段 rotation,避免服务端先提交但密钥未分发。
|
|
2887
|
+
*/
|
|
2888
|
+
async _rotateGroupEpoch(groupId, triggerId = '', expectedEpoch = null) {
|
|
2889
|
+
try {
|
|
2890
|
+
if (!this._aid)
|
|
2891
|
+
return;
|
|
2892
|
+
const memberAids = await this._getGroupMemberAids(groupId);
|
|
2893
|
+
if (triggerId && this._groupMembershipRotationDone.has(triggerId))
|
|
2894
|
+
return;
|
|
2895
|
+
const epochResult = await this.call('group.e2ee.get_epoch', { group_id: groupId });
|
|
2896
|
+
const serverEpoch = isJsonObject(epochResult) ? Number(epochResult.epoch ?? 0) : 0;
|
|
2897
|
+
const pendingRotation = isJsonObject(epochResult) && isJsonObject(epochResult.pending_rotation)
|
|
2898
|
+
? epochResult.pending_rotation
|
|
2899
|
+
: null;
|
|
2900
|
+
if (pendingRotation && !pendingRotation.expired) {
|
|
2901
|
+
const pendingRotationId = String(pendingRotation.rotation_id ?? '');
|
|
2902
|
+
const stalePending = (expectedEpoch !== null
|
|
2903
|
+
&& serverEpoch === expectedEpoch
|
|
2904
|
+
&& this._rotationExpectedMembersStale(pendingRotation, memberAids));
|
|
2905
|
+
if (stalePending && await this._abortGroupRotation(pendingRotationId, 'membership_changed_during_rotation')) {
|
|
2906
|
+
_clientLog('info', 'aborted stale pending group epoch rotation: group=%s rotation=%s', groupId, pendingRotationId || '-');
|
|
2907
|
+
}
|
|
2908
|
+
else {
|
|
2909
|
+
this._scheduleGroupRotationRetry(groupId, {
|
|
2910
|
+
reason: 'membership_changed',
|
|
2911
|
+
triggerId,
|
|
2912
|
+
expectedEpoch,
|
|
2913
|
+
pending: pendingRotation,
|
|
2914
|
+
});
|
|
2915
|
+
return;
|
|
2916
|
+
}
|
|
2917
|
+
}
|
|
2918
|
+
if (expectedEpoch !== null && serverEpoch !== expectedEpoch) {
|
|
2919
|
+
if (triggerId)
|
|
2920
|
+
this._groupMembershipRotationDone.add(triggerId);
|
|
2921
|
+
_clientLog('info', 'skip membership epoch rotation: group=%s expected_epoch=%d server_epoch=%d trigger=%s', groupId, expectedEpoch, serverEpoch, triggerId || '-');
|
|
2922
|
+
return;
|
|
2923
|
+
}
|
|
2924
|
+
const currentEpoch = expectedEpoch ?? serverEpoch;
|
|
2925
|
+
const targetEpoch = currentEpoch + 1;
|
|
2926
|
+
const rotationId = `rot-${crypto.randomUUID().replace(/-/g, '')}`;
|
|
2927
|
+
const info = this._groupE2ee.rotateEpochTo(groupId, targetEpoch, memberAids, { rotationId });
|
|
2928
|
+
this._attachRotationId(info, rotationId);
|
|
2929
|
+
const discardGeneratedPending = () => {
|
|
2930
|
+
try {
|
|
2931
|
+
this._groupE2ee.discardPendingSecret(groupId, targetEpoch, rotationId);
|
|
2932
|
+
}
|
|
2933
|
+
catch (cleanupExc) {
|
|
2934
|
+
_clientLog('debug', '清理本地 pending group key 失败: group=%s epoch=%s rotation=%s err=%s', groupId, targetEpoch, rotationId, formatCaughtError(cleanupExc));
|
|
2935
|
+
}
|
|
2936
|
+
};
|
|
2937
|
+
const rotateParams = {
|
|
2938
|
+
group_id: groupId,
|
|
2939
|
+
base_epoch: currentEpoch,
|
|
2940
|
+
target_epoch: targetEpoch,
|
|
2941
|
+
rotation_id: rotationId,
|
|
2942
|
+
reason: triggerId || expectedEpoch !== null ? 'membership_changed' : 'manual',
|
|
2943
|
+
key_commitment: String(info.commitment ?? ''),
|
|
2944
|
+
expected_members: memberAids,
|
|
2945
|
+
required_acks: [this._aid],
|
|
2946
|
+
lease_ms: GROUP_ROTATION_LEASE_MS,
|
|
2947
|
+
};
|
|
2948
|
+
Object.assign(rotateParams, this._buildRotationSignature(groupId, currentEpoch, targetEpoch, rotateParams));
|
|
2949
|
+
let rawBeginResult;
|
|
2950
|
+
try {
|
|
2951
|
+
rawBeginResult = await this.call('group.e2ee.begin_rotation', rotateParams);
|
|
2952
|
+
}
|
|
2953
|
+
catch (exc) {
|
|
2954
|
+
discardGeneratedPending();
|
|
2955
|
+
throw exc;
|
|
2956
|
+
}
|
|
2957
|
+
const beginResult = isJsonObject(rawBeginResult) ? rawBeginResult : null;
|
|
2958
|
+
const beginRotationRaw = beginResult ? beginResult.rotation : null;
|
|
2959
|
+
const rotation = isJsonObject(beginRotationRaw) ? beginRotationRaw : null;
|
|
2960
|
+
if (!beginResult || beginResult.success !== true || !rotation) {
|
|
2961
|
+
if (rotation && !rotation.expired) {
|
|
2962
|
+
if (this._rotationExpectedMembersStale(rotation, memberAids)
|
|
2963
|
+
&& await this._abortGroupRotation(String(rotation.rotation_id ?? ''), 'membership_changed_during_rotation')) {
|
|
2964
|
+
this._scheduleGroupRotationRetry(groupId, {
|
|
2965
|
+
reason: 'membership_changed',
|
|
2966
|
+
triggerId,
|
|
2967
|
+
expectedEpoch,
|
|
2968
|
+
pending: null,
|
|
2969
|
+
});
|
|
2970
|
+
}
|
|
2971
|
+
else {
|
|
2972
|
+
this._scheduleGroupRotationRetry(groupId, {
|
|
2973
|
+
reason: 'membership_changed',
|
|
2974
|
+
triggerId,
|
|
2975
|
+
expectedEpoch,
|
|
2976
|
+
pending: rotation,
|
|
2977
|
+
});
|
|
2978
|
+
}
|
|
2979
|
+
}
|
|
2980
|
+
else if (beginResult && beginResult.reason === 'expected_members_mismatch') {
|
|
2981
|
+
this._scheduleGroupRotationRetry(groupId, {
|
|
2982
|
+
reason: 'membership_changed',
|
|
2983
|
+
triggerId,
|
|
2984
|
+
expectedEpoch,
|
|
2985
|
+
pending: null,
|
|
2986
|
+
});
|
|
2987
|
+
}
|
|
2988
|
+
_clientLog('warn', 'group epoch begin failed; stop key distribution (group=%s, current_epoch=%d, returned=%s)', groupId, currentEpoch, JSON.stringify(beginResult));
|
|
2989
|
+
discardGeneratedPending();
|
|
2990
|
+
return;
|
|
2991
|
+
}
|
|
2992
|
+
const activeRotationId = String(rotation.rotation_id ?? rotationId);
|
|
2993
|
+
const distributeResult = await this._distributeGroupEpochKey(info, activeRotationId);
|
|
2994
|
+
if (distributeResult.failed.length > 0) {
|
|
2995
|
+
_clientLog('warn', 'group epoch key distribution incomplete; abort rotation before retry (group=%s rotation=%s failed=%s)', groupId, activeRotationId, distributeResult.failed.join(','));
|
|
2996
|
+
await this._abortGroupRotation(activeRotationId, 'distribution_failed');
|
|
2997
|
+
this._scheduleGroupRotationRetry(groupId, {
|
|
2998
|
+
reason: 'membership_changed',
|
|
2999
|
+
triggerId,
|
|
3000
|
+
expectedEpoch,
|
|
3001
|
+
pending: null,
|
|
3002
|
+
});
|
|
3003
|
+
discardGeneratedPending();
|
|
3004
|
+
return;
|
|
3005
|
+
}
|
|
3006
|
+
await this._heartbeatGroupRotation(activeRotationId);
|
|
3007
|
+
if (!await this._ackGroupRotationKey(activeRotationId, String(info.commitment ?? ''))) {
|
|
3008
|
+
_clientLog('warn', 'group epoch self ack failed; abort rotation before retry (group=%s rotation=%s)', groupId, activeRotationId);
|
|
3009
|
+
await this._abortGroupRotation(activeRotationId, 'self_ack_failed');
|
|
3010
|
+
this._scheduleGroupRotationRetry(groupId, {
|
|
3011
|
+
reason: 'membership_changed',
|
|
3012
|
+
triggerId,
|
|
3013
|
+
expectedEpoch,
|
|
3014
|
+
pending: null,
|
|
3015
|
+
});
|
|
3016
|
+
discardGeneratedPending();
|
|
3017
|
+
return;
|
|
3018
|
+
}
|
|
3019
|
+
const commitResult = await this.call('group.e2ee.commit_rotation', { rotation_id: activeRotationId });
|
|
3020
|
+
if (!isJsonObject(commitResult) || commitResult.success !== true) {
|
|
3021
|
+
_clientLog('warn', 'group epoch commit failed (group=%s, rotation=%s, returned=%s)', groupId, activeRotationId, JSON.stringify(commitResult));
|
|
3022
|
+
this._scheduleGroupRotationRetry(groupId, {
|
|
3023
|
+
reason: 'membership_changed',
|
|
3024
|
+
triggerId,
|
|
3025
|
+
expectedEpoch,
|
|
3026
|
+
pending: isJsonObject(commitResult) && isJsonObject(commitResult.rotation) ? commitResult.rotation : rotation,
|
|
3027
|
+
});
|
|
3028
|
+
const returnedRotation = isJsonObject(commitResult) && isJsonObject(commitResult.rotation) ? commitResult.rotation : null;
|
|
3029
|
+
if (!(returnedRotation
|
|
3030
|
+
&& String(returnedRotation.rotation_id ?? '') === activeRotationId
|
|
3031
|
+
&& String(returnedRotation.status ?? '') === 'distributing')) {
|
|
3032
|
+
discardGeneratedPending();
|
|
3033
|
+
}
|
|
3034
|
+
return;
|
|
3035
|
+
}
|
|
3036
|
+
const committedSecret = this._groupE2ee.loadSecret(groupId, targetEpoch);
|
|
3037
|
+
if (committedSecret && this._aid) {
|
|
3038
|
+
const committedRotation = isJsonObject(commitResult.rotation)
|
|
3039
|
+
? commitResult.rotation
|
|
3040
|
+
: { rotation_id: activeRotationId, key_commitment: String(info.commitment ?? '') };
|
|
3041
|
+
if (this._groupSecretMatchesCommittedRotation(committedSecret, committedRotation)) {
|
|
3042
|
+
storeGroupSecret(this._keystore, this._aid, groupId, targetEpoch, committedSecret.secret, committedSecret.commitment, committedSecret.member_aids.length > 0 ? committedSecret.member_aids : memberAids, committedSecret.epoch_chain);
|
|
3043
|
+
}
|
|
3044
|
+
else {
|
|
3045
|
+
_clientLog('warn', 'group epoch commit succeeded but local target key does not match committed rotation; keep pending blocked (group=%s rotation=%s epoch=%s)', groupId, activeRotationId, targetEpoch);
|
|
3046
|
+
}
|
|
3047
|
+
}
|
|
3048
|
+
if (triggerId) {
|
|
3049
|
+
this._groupMembershipRotationDone.add(triggerId);
|
|
3050
|
+
if (this._groupMembershipRotationDone.size > 2000) {
|
|
3051
|
+
this._groupMembershipRotationDone = new Set(Array.from(this._groupMembershipRotationDone).slice(-1000));
|
|
3052
|
+
}
|
|
3053
|
+
}
|
|
3054
|
+
}
|
|
3055
|
+
catch (exc) {
|
|
3056
|
+
this._logE2eeError('rotate_epoch', groupId, '', exc);
|
|
3057
|
+
}
|
|
3058
|
+
}
|
|
3059
|
+
/** 将当前 group_secret 通过 P2P E2EE 分发给新成员 */
|
|
3060
|
+
async _distributeKeyToNewMember(groupId, newMemberAid) {
|
|
3061
|
+
try {
|
|
3062
|
+
const secretData = this._groupE2ee.loadSecret(groupId);
|
|
3063
|
+
if (secretData === null)
|
|
3064
|
+
return;
|
|
3065
|
+
// 拉服务端最新成员列表
|
|
3066
|
+
const membersResult = await this.call('group.get_members', { group_id: groupId });
|
|
3067
|
+
const memberList = isJsonObject(membersResult) && Array.isArray(membersResult.members)
|
|
3068
|
+
? membersResult.members
|
|
3069
|
+
: [];
|
|
3070
|
+
const memberAids = memberList.map((m) => String(m.aid));
|
|
3071
|
+
// 用最新成员列表更新本地当前 epoch 的 member_aids/commitment
|
|
3072
|
+
const epoch = secretData.epoch;
|
|
3073
|
+
const commitment = computeMembershipCommitment(memberAids, epoch, groupId, secretData.secret);
|
|
3074
|
+
if (this._aid) {
|
|
3075
|
+
storeGroupSecret(this._keystore, this._aid, groupId, epoch, secretData.secret, commitment, memberAids);
|
|
3076
|
+
}
|
|
3077
|
+
// 构建并签名 manifest
|
|
3078
|
+
let manifest = buildMembershipManifest(groupId, epoch, epoch, memberAids, {
|
|
3079
|
+
added: [newMemberAid],
|
|
3080
|
+
removed: [],
|
|
3081
|
+
initiatorAid: this._aid ?? '',
|
|
3082
|
+
});
|
|
3083
|
+
const identity = this._identity;
|
|
3084
|
+
if (identity && identity.private_key_pem) {
|
|
3085
|
+
manifest = signMembershipManifest(manifest, String(identity.private_key_pem));
|
|
3086
|
+
}
|
|
3087
|
+
const distPayload = buildKeyDistribution(groupId, epoch, secretData.secret, memberAids, this._aid ?? '', manifest);
|
|
3088
|
+
// 重试 3 次,间隔递增(1s, 2s)
|
|
3089
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
3090
|
+
try {
|
|
3091
|
+
await this.call('message.send', {
|
|
3092
|
+
to: newMemberAid,
|
|
3093
|
+
payload: distPayload,
|
|
3094
|
+
encrypt: true,
|
|
3095
|
+
persist_required: true,
|
|
3096
|
+
});
|
|
3097
|
+
break; // 成功则跳出重试循环
|
|
3098
|
+
}
|
|
3099
|
+
catch (sendExc) {
|
|
3100
|
+
if (attempt < 2) {
|
|
3101
|
+
await new Promise(resolve => setTimeout(resolve, (attempt + 1) * 1000));
|
|
3102
|
+
}
|
|
3103
|
+
else {
|
|
3104
|
+
throw sendExc;
|
|
3105
|
+
}
|
|
3106
|
+
}
|
|
3107
|
+
}
|
|
3108
|
+
}
|
|
3109
|
+
catch (exc) {
|
|
3110
|
+
this._logE2eeError('distribute_key', groupId, newMemberAid, exc);
|
|
3111
|
+
}
|
|
3112
|
+
}
|
|
3113
|
+
/** 构建 epoch 轮换签名参数。失败时抛错,调用方需在 try/catch 中决定是否跳过轮换。 */
|
|
3114
|
+
_buildRotationSignature(groupId, currentEpoch, newEpoch = 0, source) {
|
|
3115
|
+
const identity = this._identity;
|
|
3116
|
+
if (!identity || !identity.private_key_pem) {
|
|
3117
|
+
throw new StateError('rotation signature requires local identity private key');
|
|
3118
|
+
}
|
|
3119
|
+
const aid = String(identity.aid ?? '');
|
|
3120
|
+
const ts = String(Math.floor(Date.now() / 1000));
|
|
3121
|
+
let signData;
|
|
3122
|
+
if (source) {
|
|
3123
|
+
const listField = (key) => {
|
|
3124
|
+
const raw = source[key];
|
|
3125
|
+
return Array.isArray(raw)
|
|
3126
|
+
? raw.map(item => String(item ?? '').trim()).filter(Boolean).sort()
|
|
3127
|
+
: [];
|
|
3128
|
+
};
|
|
3129
|
+
signData = Buffer.from(stableStringify({
|
|
3130
|
+
version: 'v2',
|
|
3131
|
+
group_id: groupId,
|
|
3132
|
+
base_epoch: Math.trunc(currentEpoch),
|
|
3133
|
+
target_epoch: Math.trunc(newEpoch),
|
|
3134
|
+
aid,
|
|
3135
|
+
rotation_timestamp: ts,
|
|
3136
|
+
rotation_id: String(source.rotation_id ?? source.new_rotation_id ?? ''),
|
|
3137
|
+
reason: String(source.reason ?? ''),
|
|
3138
|
+
key_commitment: String(source.key_commitment ?? ''),
|
|
3139
|
+
manifest_hash: String(source.manifest_hash ?? ''),
|
|
3140
|
+
epoch_chain: String(source.epoch_chain ?? ''),
|
|
3141
|
+
expected_members: listField('expected_members'),
|
|
3142
|
+
required_acks: listField('required_acks'),
|
|
3143
|
+
}), 'utf-8');
|
|
3144
|
+
}
|
|
3145
|
+
else {
|
|
3146
|
+
signData = Buffer.from(`${groupId}|${currentEpoch}|${newEpoch}|${aid}|${ts}`, 'utf-8');
|
|
3147
|
+
}
|
|
3148
|
+
const privateKey = crypto.createPrivateKey(String(identity.private_key_pem));
|
|
3149
|
+
const sig = crypto.sign('SHA256', signData, privateKey);
|
|
3150
|
+
const result = {
|
|
3151
|
+
rotation_signature: sig.toString('base64'),
|
|
3152
|
+
rotation_timestamp: ts,
|
|
3153
|
+
};
|
|
3154
|
+
if (source)
|
|
3155
|
+
result.rotation_sig_version = 'v2';
|
|
3156
|
+
return result;
|
|
3157
|
+
}
|
|
3158
|
+
/** 从 keystore 恢复 SeqTracker 状态 */
|
|
3159
|
+
_restoreSeqTrackerState() {
|
|
3160
|
+
if (!this._aid)
|
|
3161
|
+
return;
|
|
3162
|
+
try {
|
|
3163
|
+
// 优先从 seq_tracker 表按行读取
|
|
3164
|
+
const loadAll = this._keystore.loadAllSeqs;
|
|
3165
|
+
if (typeof loadAll === 'function') {
|
|
3166
|
+
const state = loadAll.call(this._keystore, this._aid, this._deviceId, this._slotId);
|
|
3167
|
+
if (state && Object.keys(state).length > 0) {
|
|
3168
|
+
this._seqTracker.restoreState(state);
|
|
3169
|
+
return;
|
|
3170
|
+
}
|
|
3171
|
+
}
|
|
3172
|
+
// fallback: 从旧 instance_state JSON blob 恢复
|
|
3173
|
+
const loader = this._keystore.loadInstanceState;
|
|
3174
|
+
if (typeof loader === 'function') {
|
|
3175
|
+
const instanceState = loader.call(this._keystore, this._aid, this._deviceId, this._slotId);
|
|
3176
|
+
if (instanceState && typeof instanceState.seq_tracker_state === 'object') {
|
|
3177
|
+
this._seqTracker.restoreState(instanceState.seq_tracker_state);
|
|
3178
|
+
}
|
|
3179
|
+
}
|
|
3180
|
+
}
|
|
3181
|
+
catch (exc) {
|
|
3182
|
+
_clientLog('warn', '恢复 SeqTracker 状态失败: %s', formatCaughtError(exc));
|
|
3183
|
+
// 通过内部 dispatcher 发布可观测事件,便于上层监控
|
|
3184
|
+
this._dispatcher.publish('seq_tracker.persist_error', {
|
|
3185
|
+
phase: 'restore',
|
|
3186
|
+
aid: this._aid,
|
|
3187
|
+
device_id: this._deviceId,
|
|
3188
|
+
slot_id: this._slotId,
|
|
3189
|
+
error: String(formatCaughtError(exc)),
|
|
3190
|
+
}).catch(() => { });
|
|
3191
|
+
}
|
|
3192
|
+
}
|
|
3193
|
+
_currentSeqTrackerContext() {
|
|
3194
|
+
if (!this._aid)
|
|
3195
|
+
return null;
|
|
3196
|
+
return JSON.stringify([this._aid, this._deviceId, this._slotId]);
|
|
3197
|
+
}
|
|
3198
|
+
_resetSeqTrackingState() {
|
|
3199
|
+
this._seqTracker = new SeqTracker();
|
|
3200
|
+
this._seqTrackerContext = null;
|
|
3201
|
+
this._gapFillDone.clear();
|
|
3202
|
+
this._pushedSeqs.clear();
|
|
3203
|
+
this._groupSynced.clear();
|
|
3204
|
+
this._p2pSynced = false;
|
|
3205
|
+
}
|
|
3206
|
+
_refreshSeqTrackerContext() {
|
|
3207
|
+
const nextContext = this._currentSeqTrackerContext();
|
|
3208
|
+
if (nextContext === this._seqTrackerContext)
|
|
3209
|
+
return;
|
|
3210
|
+
this._seqTracker = new SeqTracker();
|
|
3211
|
+
this._gapFillDone.clear();
|
|
3212
|
+
this._pushedSeqs.clear();
|
|
3213
|
+
this._groupSynced.clear();
|
|
3214
|
+
this._p2pSynced = false;
|
|
3215
|
+
this._seqTrackerContext = nextContext;
|
|
3216
|
+
}
|
|
3217
|
+
/** 将 SeqTracker 状态保存到 keystore */
|
|
3218
|
+
_saveSeqTrackerState() {
|
|
3219
|
+
if (!this._aid)
|
|
3220
|
+
return;
|
|
3221
|
+
const state = this._seqTracker.exportState();
|
|
3222
|
+
if (Object.keys(state).length === 0)
|
|
3223
|
+
return;
|
|
3224
|
+
try {
|
|
3225
|
+
// 优先按行写入 seq_tracker 表
|
|
3226
|
+
const saveFn = this._keystore.saveSeq;
|
|
3227
|
+
if (typeof saveFn === 'function') {
|
|
3228
|
+
for (const [ns, seq] of Object.entries(state)) {
|
|
3229
|
+
saveFn.call(this._keystore, this._aid, this._deviceId, this._slotId, ns, seq);
|
|
3230
|
+
}
|
|
3231
|
+
return;
|
|
3232
|
+
}
|
|
3233
|
+
// fallback: 旧版 updateInstanceState JSON blob
|
|
3234
|
+
const updater = this._keystore.updateInstanceState;
|
|
3235
|
+
if (typeof updater === 'function') {
|
|
3236
|
+
updater.call(this._keystore, this._aid, this._deviceId, this._slotId, (metadata) => {
|
|
3237
|
+
metadata.seq_tracker_state = state;
|
|
3238
|
+
return metadata;
|
|
3239
|
+
});
|
|
3240
|
+
}
|
|
3241
|
+
}
|
|
3242
|
+
catch (exc) {
|
|
3243
|
+
_clientLog('warn', '保存 SeqTracker 状态失败: %s', formatCaughtError(exc));
|
|
3244
|
+
// 通过内部 dispatcher 发布可观测事件,便于上层监控
|
|
3245
|
+
this._dispatcher.publish('seq_tracker.persist_error', {
|
|
3246
|
+
phase: 'save',
|
|
3247
|
+
aid: this._aid,
|
|
3248
|
+
device_id: this._deviceId,
|
|
3249
|
+
slot_id: this._slotId,
|
|
3250
|
+
error: String(formatCaughtError(exc)),
|
|
3251
|
+
}).catch(() => { });
|
|
3252
|
+
}
|
|
3253
|
+
}
|
|
3254
|
+
/** 记录 E2EE 自动编排错误 */
|
|
3255
|
+
_logE2eeError(stage, groupId, aid, exc) {
|
|
3256
|
+
try {
|
|
3257
|
+
this._dispatcher.publish('e2ee.orchestration_error', {
|
|
3258
|
+
stage, group_id: groupId, aid, error: String(exc),
|
|
3259
|
+
}).catch(() => { });
|
|
3260
|
+
}
|
|
3261
|
+
catch {
|
|
3262
|
+
// 日志本身不应阻断主流程
|
|
3263
|
+
}
|
|
3264
|
+
}
|
|
3265
|
+
// ── URL 辅助 ──────────────────────────────────────────────
|
|
3266
|
+
/** 跨域时将 Gateway URL 替换为 peer 所在域的 Gateway URL */
|
|
3267
|
+
static _resolvePeerGatewayUrl(localGatewayUrl, peerAid) {
|
|
3268
|
+
if (!peerAid.includes('.'))
|
|
3269
|
+
return localGatewayUrl;
|
|
3270
|
+
const dotIdx = peerAid.indexOf('.');
|
|
3271
|
+
const peerIssuer = peerAid.slice(dotIdx + 1);
|
|
3272
|
+
const m = localGatewayUrl.match(/gateway\.([^:/]+)/);
|
|
3273
|
+
if (!m)
|
|
3274
|
+
return localGatewayUrl;
|
|
3275
|
+
const localIssuer = m[1];
|
|
3276
|
+
if (localIssuer === peerIssuer)
|
|
3277
|
+
return localGatewayUrl;
|
|
3278
|
+
return localGatewayUrl.replace(`gateway.${localIssuer}`, `gateway.${peerIssuer}`);
|
|
3279
|
+
}
|
|
3280
|
+
/** 构建证书下载 URL */
|
|
3281
|
+
static _certCacheKey(aid, certFingerprint) {
|
|
3282
|
+
const normalized = String(certFingerprint ?? '').trim().toLowerCase();
|
|
3283
|
+
return normalized ? `${aid}#${normalized}` : aid;
|
|
3284
|
+
}
|
|
3285
|
+
static _buildCertUrl(gatewayUrl, aid, certFingerprint) {
|
|
3286
|
+
const parsed = new URL(gatewayUrl);
|
|
3287
|
+
const scheme = parsed.protocol === 'wss:' ? 'https:' : 'http:';
|
|
3288
|
+
const url = new URL(`${scheme}//${parsed.host}/pki/cert/${encodeURIComponent(aid)}`);
|
|
3289
|
+
const normalized = String(certFingerprint ?? '').trim().toLowerCase();
|
|
3290
|
+
if (normalized) {
|
|
3291
|
+
url.searchParams.set('cert_fingerprint', normalized);
|
|
3292
|
+
}
|
|
3293
|
+
return url.toString();
|
|
3294
|
+
}
|
|
3295
|
+
// ── 内部:连接 ────────────────────────────────────────────
|
|
3296
|
+
/** 执行一次连接流程 */
|
|
3297
|
+
async _connectOnce(params, allowReauth) {
|
|
3298
|
+
const gatewayUrl = this._resolveGateway(params);
|
|
3299
|
+
this._gatewayUrl = gatewayUrl;
|
|
3300
|
+
this._slotId = String(params.slot_id ?? '');
|
|
3301
|
+
this._connectDeliveryMode = { ...(params.delivery_mode ?? this._connectDeliveryMode) };
|
|
3302
|
+
const prevState = this._state;
|
|
3303
|
+
this._auth.setInstanceContext({ deviceId: this._deviceId, slotId: this._slotId });
|
|
3304
|
+
this._state = 'connecting';
|
|
3305
|
+
// 前置 restore:在 transport.connect 启动 reader 之前完成,
|
|
3306
|
+
// 避免 reader 把积压 push 交给空 tracker 的 handler,触发 S2 历史 gap 误补拉。
|
|
3307
|
+
this._refreshSeqTrackerContext();
|
|
3308
|
+
this._restoreSeqTrackerState();
|
|
3309
|
+
try {
|
|
3310
|
+
const challenge = await this._transport.connect(gatewayUrl);
|
|
3311
|
+
this._state = 'authenticating';
|
|
3312
|
+
if (allowReauth) {
|
|
3313
|
+
const authContext = await this._auth.connectSession(this._transport, challenge, gatewayUrl, {
|
|
3314
|
+
accessToken: String(params.access_token ?? ''),
|
|
3315
|
+
deviceId: this._deviceId,
|
|
3316
|
+
slotId: this._slotId,
|
|
3317
|
+
deliveryMode: this._connectDeliveryMode,
|
|
3318
|
+
});
|
|
3319
|
+
if (isJsonObject(authContext)) {
|
|
3320
|
+
const auth = authContext;
|
|
3321
|
+
const identity = auth.identity;
|
|
3322
|
+
if (identity && isJsonObject(identity)) {
|
|
3323
|
+
this._identity = identity;
|
|
3324
|
+
this._aid = String(identity.aid ?? this._aid ?? '');
|
|
3325
|
+
if (_debugLogger)
|
|
3326
|
+
_debugLogger.setAid(` [${this._aid}]`);
|
|
3327
|
+
if (this._sessionParams !== null) {
|
|
3328
|
+
this._sessionParams.access_token = String(auth.token ?? params.access_token ?? '');
|
|
3329
|
+
}
|
|
3330
|
+
}
|
|
3331
|
+
}
|
|
3332
|
+
}
|
|
3333
|
+
else {
|
|
3334
|
+
await this._auth.initializeWithToken(this._transport, challenge, String(params.access_token), {
|
|
3335
|
+
deviceId: this._deviceId,
|
|
3336
|
+
slotId: this._slotId,
|
|
3337
|
+
deliveryMode: this._connectDeliveryMode,
|
|
3338
|
+
});
|
|
3339
|
+
this._syncIdentityAfterConnect(String(params.access_token));
|
|
3340
|
+
}
|
|
3341
|
+
this._state = 'connected';
|
|
3342
|
+
await this._dispatcher.publish('connection.state', { state: this._state, gateway: gatewayUrl });
|
|
3343
|
+
// auth 阶段 aid 可能被 identity 覆盖(上方 this._aid = identity.aid);
|
|
3344
|
+
// 若 context 发生变化,重新 refresh + restore,保持 tracker 与真实身份一致。
|
|
3345
|
+
if (this._seqTrackerContext !== this._currentSeqTrackerContext()) {
|
|
3346
|
+
this._refreshSeqTrackerContext();
|
|
3347
|
+
this._restoreSeqTrackerState();
|
|
3348
|
+
}
|
|
3349
|
+
this._startBackgroundTasks();
|
|
3350
|
+
// 上线后自动上传 prekey
|
|
3351
|
+
try {
|
|
3352
|
+
await this._uploadPrekey();
|
|
3353
|
+
}
|
|
3354
|
+
catch (exc) {
|
|
3355
|
+
_clientLog('warn', 'prekey 上传失败: %s', formatCaughtError(exc));
|
|
3356
|
+
}
|
|
3357
|
+
}
|
|
3358
|
+
catch (err) {
|
|
3359
|
+
this._state = prevState === 'connected' ? 'disconnected' : 'idle';
|
|
3360
|
+
throw err;
|
|
3361
|
+
}
|
|
3362
|
+
}
|
|
3363
|
+
/** 从参数中解析 Gateway URL */
|
|
3364
|
+
_resolveGateway(params) {
|
|
3365
|
+
const topology = params.topology;
|
|
3366
|
+
if (isJsonObject(topology)) {
|
|
3367
|
+
const topo = topology;
|
|
3368
|
+
const mode = String(topo.mode ?? 'gateway');
|
|
3369
|
+
if (mode === 'peer') {
|
|
3370
|
+
throw new ValidationError('peer topology is not implemented in the TypeScript SDK');
|
|
3371
|
+
}
|
|
3372
|
+
if (mode === 'relay') {
|
|
3373
|
+
throw new ValidationError('relay topology is not implemented in the TypeScript SDK');
|
|
3374
|
+
}
|
|
3375
|
+
}
|
|
3376
|
+
const gateway = String(params.gateway ?? '');
|
|
3377
|
+
if (!gateway) {
|
|
3378
|
+
throw new StateError('missing gateway in connect params');
|
|
3379
|
+
}
|
|
3380
|
+
return gateway;
|
|
3381
|
+
}
|
|
3382
|
+
/** 连接后同步身份信息 */
|
|
3383
|
+
_syncIdentityAfterConnect(accessToken) {
|
|
3384
|
+
const identity = this._auth.loadIdentityOrNone(this._aid ?? undefined);
|
|
3385
|
+
if (identity === null) {
|
|
3386
|
+
this._identity = null;
|
|
3387
|
+
return;
|
|
3388
|
+
}
|
|
3389
|
+
identity.access_token = accessToken;
|
|
3390
|
+
this._identity = identity;
|
|
3391
|
+
this._aid = String(identity.aid ?? this._aid ?? '');
|
|
3392
|
+
if (_debugLogger)
|
|
3393
|
+
_debugLogger.setAid(` [${this._aid}]`);
|
|
3394
|
+
const persistIdentity = this._auth._persistIdentity;
|
|
3395
|
+
if (typeof persistIdentity === 'function') {
|
|
3396
|
+
persistIdentity.call(this._auth, identity);
|
|
3397
|
+
return;
|
|
3398
|
+
}
|
|
3399
|
+
this._keystore.saveIdentity(String(identity.aid), identity);
|
|
3400
|
+
}
|
|
3401
|
+
// ── 内部:参数处理 ────────────────────────────────────────
|
|
3402
|
+
/** 规范化连接参数 */
|
|
3403
|
+
_normalizeConnectParams(params) {
|
|
3404
|
+
const request = { ...params };
|
|
3405
|
+
const accessToken = String(request.access_token ?? '');
|
|
3406
|
+
if (!accessToken)
|
|
3407
|
+
throw new StateError('connect requires non-empty access_token');
|
|
3408
|
+
const gateway = String(request.gateway ?? this._gatewayUrl ?? '');
|
|
3409
|
+
if (!gateway)
|
|
3410
|
+
throw new StateError('connect requires non-empty gateway');
|
|
3411
|
+
request.access_token = accessToken;
|
|
3412
|
+
request.gateway = gateway;
|
|
3413
|
+
request.device_id = this._deviceId;
|
|
3414
|
+
request.slot_id = normalizeInstanceId(request.slot_id ?? this._slotId, 'slot_id', { allowEmpty: true });
|
|
3415
|
+
let deliveryModeRaw = request.delivery_mode;
|
|
3416
|
+
if (deliveryModeRaw == null) {
|
|
3417
|
+
deliveryModeRaw = { ...this._defaultConnectDeliveryMode };
|
|
3418
|
+
}
|
|
3419
|
+
else if (!isJsonObject(deliveryModeRaw)) {
|
|
3420
|
+
deliveryModeRaw = { mode: deliveryModeRaw };
|
|
3421
|
+
}
|
|
3422
|
+
else {
|
|
3423
|
+
deliveryModeRaw = { ...deliveryModeRaw };
|
|
3424
|
+
}
|
|
3425
|
+
if ('queue_routing' in request) {
|
|
3426
|
+
deliveryModeRaw.routing = request.queue_routing;
|
|
3427
|
+
}
|
|
3428
|
+
if ('affinity_ttl_ms' in request) {
|
|
3429
|
+
deliveryModeRaw.affinity_ttl_ms = request.affinity_ttl_ms;
|
|
3430
|
+
}
|
|
3431
|
+
request.delivery_mode = normalizeDeliveryModeConfig(deliveryModeRaw);
|
|
3432
|
+
if (request.topology != null && !isJsonObject(request.topology)) {
|
|
3433
|
+
throw new ValidationError('topology must be a dict');
|
|
3434
|
+
}
|
|
3435
|
+
if ('retry' in request && request.retry != null && !isJsonObject(request.retry)) {
|
|
3436
|
+
throw new ValidationError('retry must be a dict');
|
|
3437
|
+
}
|
|
3438
|
+
if ('timeouts' in request && request.timeouts != null && !isJsonObject(request.timeouts)) {
|
|
3439
|
+
throw new ValidationError('timeouts must be a dict');
|
|
3440
|
+
}
|
|
3441
|
+
return request;
|
|
3442
|
+
}
|
|
3443
|
+
/** 从参数构建会话选项 */
|
|
3444
|
+
_buildSessionOptions(params) {
|
|
3445
|
+
const options = {
|
|
3446
|
+
auto_reconnect: DEFAULT_SESSION_OPTIONS.auto_reconnect,
|
|
3447
|
+
heartbeat_interval: DEFAULT_SESSION_OPTIONS.heartbeat_interval,
|
|
3448
|
+
token_refresh_before: DEFAULT_SESSION_OPTIONS.token_refresh_before,
|
|
3449
|
+
retry: { ...DEFAULT_SESSION_OPTIONS.retry },
|
|
3450
|
+
timeouts: { ...DEFAULT_SESSION_OPTIONS.timeouts },
|
|
3451
|
+
};
|
|
3452
|
+
if ('auto_reconnect' in params)
|
|
3453
|
+
options.auto_reconnect = Boolean(params.auto_reconnect);
|
|
3454
|
+
if ('heartbeat_interval' in params)
|
|
3455
|
+
options.heartbeat_interval = Number(params.heartbeat_interval);
|
|
3456
|
+
if ('token_refresh_before' in params)
|
|
3457
|
+
options.token_refresh_before = Number(params.token_refresh_before);
|
|
3458
|
+
if ('retry' in params && isJsonObject(params.retry)) {
|
|
3459
|
+
Object.assign(options.retry, params.retry);
|
|
3460
|
+
}
|
|
3461
|
+
if ('timeouts' in params && isJsonObject(params.timeouts)) {
|
|
3462
|
+
Object.assign(options.timeouts, params.timeouts);
|
|
3463
|
+
}
|
|
3464
|
+
return options;
|
|
3465
|
+
}
|
|
3466
|
+
// ── 内部:后台任务 ────────────────────────────────────────
|
|
3467
|
+
/** 启动所有后台任务 */
|
|
3468
|
+
_startBackgroundTasks() {
|
|
3469
|
+
this._startHeartbeatTask();
|
|
3470
|
+
this._startTokenRefreshTask();
|
|
3471
|
+
this._startGroupEpochTasks();
|
|
3472
|
+
// 上线/重连后一次性补齐群消息和群事件
|
|
3473
|
+
this._syncAllGroupsOnce().catch(exc => _clientLog('warn', '后台补洞触发失败: %s', formatCaughtError(exc)));
|
|
3474
|
+
}
|
|
3475
|
+
/** 停止所有后台任务 */
|
|
3476
|
+
_stopBackgroundTasks() {
|
|
3477
|
+
if (this._heartbeatTimer !== null) {
|
|
3478
|
+
clearInterval(this._heartbeatTimer);
|
|
3479
|
+
this._heartbeatTimer = null;
|
|
3480
|
+
}
|
|
3481
|
+
if (this._tokenRefreshTimer !== null) {
|
|
3482
|
+
clearTimeout(this._tokenRefreshTimer);
|
|
3483
|
+
this._tokenRefreshTimer = null;
|
|
3484
|
+
}
|
|
3485
|
+
if (this._prekeyRefreshTimer !== null) {
|
|
3486
|
+
clearInterval(this._prekeyRefreshTimer);
|
|
3487
|
+
this._prekeyRefreshTimer = null;
|
|
3488
|
+
}
|
|
3489
|
+
if (this._groupEpochCleanupTimer !== null) {
|
|
3490
|
+
clearInterval(this._groupEpochCleanupTimer);
|
|
3491
|
+
this._groupEpochCleanupTimer = null;
|
|
3492
|
+
}
|
|
3493
|
+
if (this._groupEpochRotateTimer !== null) {
|
|
3494
|
+
clearInterval(this._groupEpochRotateTimer);
|
|
3495
|
+
this._groupEpochRotateTimer = null;
|
|
3496
|
+
}
|
|
3497
|
+
if (this._cacheCleanupTimer !== null) {
|
|
3498
|
+
clearInterval(this._cacheCleanupTimer);
|
|
3499
|
+
this._cacheCleanupTimer = null;
|
|
3500
|
+
}
|
|
3501
|
+
for (const timer of this._groupEpochRotationRetryTimers.values()) {
|
|
3502
|
+
clearTimeout(timer);
|
|
3503
|
+
}
|
|
3504
|
+
this._groupEpochRotationRetryTimers.clear();
|
|
3505
|
+
}
|
|
3506
|
+
/** 启动心跳任务 */
|
|
3507
|
+
_startHeartbeatTask() {
|
|
3508
|
+
if (this._heartbeatTimer !== null)
|
|
3509
|
+
return;
|
|
3510
|
+
const interval = Number(this._sessionOptions.heartbeat_interval ?? 30) * 1000;
|
|
3511
|
+
if (interval <= 0)
|
|
3512
|
+
return;
|
|
3513
|
+
// M25: 把连续失败阈值从 3 次收窄到 2 次。既能容忍一次网络抖动/GC 暂停,
|
|
3514
|
+
// 又把半开连接的检测延迟从 3 个心跳周期降到 2 个。
|
|
3515
|
+
// 真正的 socket 死亡由 ws.on('close') 立即触发 _handleTransportDisconnect,
|
|
3516
|
+
// 不依赖此心跳路径。
|
|
3517
|
+
let consecutiveFailures = 0;
|
|
3518
|
+
const maxFailures = 2;
|
|
3519
|
+
this._heartbeatTimer = setInterval(() => {
|
|
3520
|
+
if (this._closing || this._state !== 'connected')
|
|
3521
|
+
return;
|
|
3522
|
+
this._transport.call('meta.ping', {}).then(() => {
|
|
3523
|
+
consecutiveFailures = 0;
|
|
3524
|
+
}).catch((exc) => {
|
|
3525
|
+
consecutiveFailures++;
|
|
3526
|
+
_clientLog('warn', '心跳失败 (%s/%s): %s', consecutiveFailures, maxFailures, formatCaughtError(exc));
|
|
3527
|
+
this._dispatcher.publish('connection.error', { error: formatCaughtError(exc) }).catch(() => { });
|
|
3528
|
+
if (consecutiveFailures >= maxFailures) {
|
|
3529
|
+
_clientLog('warn', '连续 %s 次心跳失败,触发断线重连', maxFailures);
|
|
3530
|
+
this._handleTransportDisconnect(exc instanceof Error ? exc : new Error(String(exc)));
|
|
3531
|
+
}
|
|
3532
|
+
});
|
|
3533
|
+
}, interval);
|
|
3534
|
+
// 允许 Node.js 进程在只剩定时器时退出
|
|
3535
|
+
if (this._heartbeatTimer && typeof this._heartbeatTimer === 'object' && 'unref' in this._heartbeatTimer) {
|
|
3536
|
+
this._heartbeatTimer.unref();
|
|
3537
|
+
}
|
|
3538
|
+
}
|
|
3539
|
+
/** 启动 token 刷新任务 */
|
|
3540
|
+
_startTokenRefreshTask() {
|
|
3541
|
+
if (this._tokenRefreshTimer !== null)
|
|
3542
|
+
return;
|
|
3543
|
+
const lead = Number(this._sessionOptions.token_refresh_before ?? 60);
|
|
3544
|
+
const minimumSleep = 1000;
|
|
3545
|
+
const scheduleNext = () => {
|
|
3546
|
+
if (this._closing)
|
|
3547
|
+
return;
|
|
3548
|
+
if (this._state !== 'connected' || !this._gatewayUrl) {
|
|
3549
|
+
this._tokenRefreshTimer = setTimeout(scheduleNext, minimumSleep);
|
|
3550
|
+
this._unrefTimer(this._tokenRefreshTimer);
|
|
3551
|
+
return;
|
|
3552
|
+
}
|
|
3553
|
+
let identity = this._identity ?? this._auth.loadIdentityOrNone() ?? null;
|
|
3554
|
+
if (identity === null) {
|
|
3555
|
+
this._tokenRefreshTimer = setTimeout(scheduleNext, minimumSleep);
|
|
3556
|
+
this._unrefTimer(this._tokenRefreshTimer);
|
|
3557
|
+
return;
|
|
3558
|
+
}
|
|
3559
|
+
this._identity = identity;
|
|
3560
|
+
const expiresAt = this._auth.getAccessTokenExpiry(identity);
|
|
3561
|
+
if (expiresAt === null) {
|
|
3562
|
+
this._tokenRefreshTimer = setTimeout(scheduleNext, minimumSleep);
|
|
3563
|
+
this._unrefTimer(this._tokenRefreshTimer);
|
|
3564
|
+
return;
|
|
3565
|
+
}
|
|
3566
|
+
const delay = Math.max((expiresAt - lead - Date.now() / 1000) * 1000, minimumSleep);
|
|
3567
|
+
this._tokenRefreshTimer = setTimeout(async () => {
|
|
3568
|
+
if (this._closing || this._state !== 'connected' || !this._gatewayUrl) {
|
|
3569
|
+
scheduleNext();
|
|
3570
|
+
return;
|
|
3571
|
+
}
|
|
3572
|
+
try {
|
|
3573
|
+
identity = await this._auth.refreshCachedTokens(this._gatewayUrl, identity);
|
|
3574
|
+
this._identity = identity;
|
|
3575
|
+
if (this._sessionParams !== null && identity.access_token) {
|
|
3576
|
+
this._sessionParams.access_token = identity.access_token;
|
|
3577
|
+
}
|
|
3578
|
+
await this._dispatcher.publish('token.refreshed', {
|
|
3579
|
+
aid: identity.aid,
|
|
3580
|
+
expires_at: identity.access_token_expires_at,
|
|
3581
|
+
});
|
|
3582
|
+
this._tokenRefreshFailures = 0;
|
|
3583
|
+
}
|
|
3584
|
+
catch (exc) {
|
|
3585
|
+
if (exc instanceof AuthError) {
|
|
3586
|
+
this._tokenRefreshFailures++;
|
|
3587
|
+
if (this._tokenRefreshFailures >= 3) {
|
|
3588
|
+
_clientLog('warn', 'token 刷新连续失败 %d 次,停止刷新循环并触发重连', this._tokenRefreshFailures);
|
|
3589
|
+
await this._dispatcher.publish('token.refresh_exhausted', {
|
|
3590
|
+
aid: this._identity?.aid ?? null,
|
|
3591
|
+
consecutive_failures: this._tokenRefreshFailures,
|
|
3592
|
+
last_error: String(exc),
|
|
3593
|
+
});
|
|
3594
|
+
this._tokenRefreshFailures = 0;
|
|
3595
|
+
this._handleTransportDisconnect(new Error('token refresh exhausted, triggering reconnect'));
|
|
3596
|
+
return;
|
|
3597
|
+
}
|
|
3598
|
+
_clientLog('debug', 'token 刷新失败 (%d/3),下次重试: %s', this._tokenRefreshFailures, exc);
|
|
3599
|
+
}
|
|
3600
|
+
else {
|
|
3601
|
+
await this._dispatcher.publish('connection.error', { error: formatCaughtError(exc) });
|
|
3602
|
+
}
|
|
3603
|
+
}
|
|
3604
|
+
scheduleNext();
|
|
3605
|
+
}, delay);
|
|
3606
|
+
this._unrefTimer(this._tokenRefreshTimer);
|
|
3607
|
+
};
|
|
3608
|
+
scheduleNext();
|
|
3609
|
+
}
|
|
3610
|
+
/** 启动 prekey 刷新任务 */
|
|
3611
|
+
_startPrekeyRefreshTask() {
|
|
3612
|
+
return;
|
|
3613
|
+
}
|
|
3614
|
+
_extractConsumedPrekeyId(message) {
|
|
3615
|
+
if (!message?.e2ee)
|
|
3616
|
+
return '';
|
|
3617
|
+
if (message.e2ee.encryption_mode !== 'prekey_ecdh_v2')
|
|
3618
|
+
return '';
|
|
3619
|
+
return String(message.e2ee.prekey_id ?? '').trim();
|
|
3620
|
+
}
|
|
3621
|
+
_validateMessageRecipient(toAid) {
|
|
3622
|
+
if (isGroupServiceAid(toAid)) {
|
|
3623
|
+
throw new ValidationError('message.send receiver cannot be group.{issuer}; use group.send instead');
|
|
3624
|
+
}
|
|
3625
|
+
}
|
|
3626
|
+
_validateOutboundCall(method, params) {
|
|
3627
|
+
if (method === 'message.send') {
|
|
3628
|
+
this._validateMessageRecipient(params.to);
|
|
3629
|
+
if ('persist' in params) {
|
|
3630
|
+
throw new ValidationError("message.send no longer accepts 'persist'; configure delivery_mode during connect");
|
|
3631
|
+
}
|
|
3632
|
+
if ('delivery_mode' in params || 'queue_routing' in params || 'affinity_ttl_ms' in params) {
|
|
3633
|
+
throw new ValidationError('message.send does not accept delivery_mode; configure delivery_mode during connect');
|
|
3634
|
+
}
|
|
3635
|
+
}
|
|
3636
|
+
if (method === 'group.send') {
|
|
3637
|
+
if ('persist' in params) {
|
|
3638
|
+
throw new ValidationError("group.send does not accept 'persist'; group messages are always fanout");
|
|
3639
|
+
}
|
|
3640
|
+
if ('delivery_mode' in params || 'queue_routing' in params || 'affinity_ttl_ms' in params) {
|
|
3641
|
+
throw new ValidationError('group.send does not accept delivery_mode; group messages are always fanout');
|
|
3642
|
+
}
|
|
3643
|
+
}
|
|
3644
|
+
}
|
|
3645
|
+
_currentMessageDeliveryMode() {
|
|
3646
|
+
return { ...this._connectDeliveryMode };
|
|
3647
|
+
}
|
|
3648
|
+
_injectMessageCursorContext(method, params) {
|
|
3649
|
+
if (method !== 'message.pull' && method !== 'message.ack') {
|
|
3650
|
+
return;
|
|
3651
|
+
}
|
|
3652
|
+
if ('device_id' in params && String(params.device_id ?? '').trim() !== this._deviceId) {
|
|
3653
|
+
throw new ValidationError('message.pull/message.ack device_id must match the current client instance');
|
|
3654
|
+
}
|
|
3655
|
+
const slotId = normalizeInstanceId(params.slot_id ?? this._slotId, 'slot_id', { allowEmpty: true });
|
|
3656
|
+
if (slotId !== this._slotId) {
|
|
3657
|
+
throw new ValidationError('message.pull/message.ack slot_id must match the current client instance');
|
|
3658
|
+
}
|
|
3659
|
+
params.device_id = this._deviceId;
|
|
3660
|
+
params.slot_id = this._slotId;
|
|
3661
|
+
}
|
|
3662
|
+
_schedulePrekeyReplenishIfConsumed(message) {
|
|
3663
|
+
const prekeyId = this._extractConsumedPrekeyId(message);
|
|
3664
|
+
if (!prekeyId || this._state !== 'connected')
|
|
3665
|
+
return;
|
|
3666
|
+
if (this._prekeyReplenished.has(prekeyId))
|
|
3667
|
+
return;
|
|
3668
|
+
// 同一时刻只允许一个 put_prekey inflight
|
|
3669
|
+
if (this._prekeyReplenishInflight.size > 0)
|
|
3670
|
+
return;
|
|
3671
|
+
this._prekeyReplenishInflight.add(prekeyId);
|
|
3672
|
+
void (async () => {
|
|
3673
|
+
try {
|
|
3674
|
+
await this._uploadPrekey();
|
|
3675
|
+
this._prekeyReplenished.add(prekeyId);
|
|
3676
|
+
}
|
|
3677
|
+
catch (exc) {
|
|
3678
|
+
_clientLog('warn', '消费 prekey %s 后补充 current prekey 失败: %s', prekeyId, formatCaughtError(exc));
|
|
3679
|
+
}
|
|
3680
|
+
finally {
|
|
3681
|
+
this._prekeyReplenishInflight.delete(prekeyId);
|
|
3682
|
+
}
|
|
3683
|
+
})();
|
|
3684
|
+
}
|
|
3685
|
+
/** 启动群组 epoch 相关后台任务 */
|
|
3686
|
+
_startGroupEpochTasks() {
|
|
3687
|
+
// 群组 E2EE 是必备能力,始终执行 epoch 清理
|
|
3688
|
+
// 旧 epoch 清理(每小时检查一次)
|
|
3689
|
+
if (this._groupEpochCleanupTimer === null) {
|
|
3690
|
+
this._groupEpochCleanupTimer = setInterval(() => {
|
|
3691
|
+
if (this._closing || this._state !== 'connected' || !this._aid)
|
|
3692
|
+
return;
|
|
3693
|
+
try {
|
|
3694
|
+
const groupIds = typeof this._keystore.listGroupSecretIds === 'function'
|
|
3695
|
+
? this._keystore.listGroupSecretIds(this._aid)
|
|
3696
|
+
: [];
|
|
3697
|
+
const retention = this._configModel.oldEpochRetentionSeconds;
|
|
3698
|
+
for (const gid of groupIds) {
|
|
3699
|
+
this._groupE2ee.cleanup(gid, retention);
|
|
3700
|
+
}
|
|
3701
|
+
}
|
|
3702
|
+
catch (exc) {
|
|
3703
|
+
_clientLog('warn', 'epoch 清理失败: %s', formatCaughtError(exc));
|
|
3704
|
+
}
|
|
3705
|
+
}, 3600_000);
|
|
3706
|
+
this._unrefTimer(this._groupEpochCleanupTimer);
|
|
3707
|
+
}
|
|
3708
|
+
// 定时 epoch 轮换
|
|
3709
|
+
const rotateInterval = this._configModel.epochAutoRotateInterval;
|
|
3710
|
+
if (rotateInterval > 0 && this._groupEpochRotateTimer === null) {
|
|
3711
|
+
this._groupEpochRotateTimer = setInterval(() => {
|
|
3712
|
+
if (this._closing || this._state !== 'connected' || !this._aid)
|
|
3713
|
+
return;
|
|
3714
|
+
try {
|
|
3715
|
+
const groupIds = typeof this._keystore.listGroupSecretIds === 'function'
|
|
3716
|
+
? this._keystore.listGroupSecretIds(this._aid)
|
|
3717
|
+
: [];
|
|
3718
|
+
for (const gid of groupIds) {
|
|
3719
|
+
this._maybeLeadRotateGroupEpoch(gid).catch((exc) => _clientLog('warn', 'epoch 轮换失败: %s', formatCaughtError(exc)));
|
|
3720
|
+
}
|
|
3721
|
+
}
|
|
3722
|
+
catch (exc) {
|
|
3723
|
+
_clientLog('warn', 'epoch 轮换失败: %s', formatCaughtError(exc));
|
|
3724
|
+
}
|
|
3725
|
+
}, rotateInterval * 1000);
|
|
3726
|
+
this._unrefTimer(this._groupEpochRotateTimer);
|
|
3727
|
+
}
|
|
3728
|
+
// 内存缓存定时清理(每小时扫描过期条目)
|
|
3729
|
+
if (this._cacheCleanupTimer === null) {
|
|
3730
|
+
this._cacheCleanupTimer = setInterval(() => {
|
|
3731
|
+
const nowSec = Date.now() / 1000;
|
|
3732
|
+
// 证书缓存
|
|
3733
|
+
for (const [k, v] of this._certCache) {
|
|
3734
|
+
if (nowSec >= v.refreshAfter)
|
|
3735
|
+
this._certCache.delete(k);
|
|
3736
|
+
}
|
|
3737
|
+
// prekey 列表缓存
|
|
3738
|
+
for (const [k, v] of this._peerPrekeysCache) {
|
|
3739
|
+
if (nowSec >= v.expireAt)
|
|
3740
|
+
this._peerPrekeysCache.delete(k);
|
|
3741
|
+
}
|
|
3742
|
+
// 补洞去重:清理超过 5 分钟的旧条目(与 Python 对齐,按时间过期)
|
|
3743
|
+
const gapCutoffMs = Date.now() - 300_000;
|
|
3744
|
+
for (const [k, ts] of this._gapFillDone) {
|
|
3745
|
+
if (ts < gapCutoffMs)
|
|
3746
|
+
this._gapFillDone.delete(k);
|
|
3747
|
+
}
|
|
3748
|
+
// e2ee prekey 缓存
|
|
3749
|
+
this._e2ee.cleanExpiredCaches();
|
|
3750
|
+
// group e2ee replay guard 缓存
|
|
3751
|
+
this._groupE2ee.cleanExpiredCaches();
|
|
3752
|
+
// auth gateway 缓存
|
|
3753
|
+
this._auth.cleanExpiredCaches();
|
|
3754
|
+
}, 3600_000);
|
|
3755
|
+
this._unrefTimer(this._cacheCleanupTimer);
|
|
3756
|
+
}
|
|
3757
|
+
}
|
|
3758
|
+
/** 允许 Node.js 进程在只剩定时器时退出 */
|
|
3759
|
+
_unrefTimer(timer) {
|
|
3760
|
+
if (timer && typeof timer === 'object' && 'unref' in timer) {
|
|
3761
|
+
timer.unref();
|
|
3762
|
+
}
|
|
3763
|
+
}
|
|
3764
|
+
// ── 内部:断线重连 ────────────────────────────────────────
|
|
3765
|
+
/** 不重连 close code 集合:认证失败/权限错误/被踢等,重连无意义 */
|
|
3766
|
+
static _NO_RECONNECT_CODES = new Set([4001, 4003, 4008, 4009, 4010, 4011]);
|
|
3767
|
+
/** 处理服务端主动断开通知 event/gateway.disconnect */
|
|
3768
|
+
_onGatewayDisconnect(data) {
|
|
3769
|
+
const code = data?.code;
|
|
3770
|
+
const reason = data?.reason ?? '';
|
|
3771
|
+
_clientLog('warn', '服务端主动断开: code=%s, reason=%s', code, reason);
|
|
3772
|
+
this._serverKicked = true;
|
|
3773
|
+
}
|
|
3774
|
+
/** 传输层断线回调 */
|
|
3775
|
+
async _handleTransportDisconnect(error, closeCode) {
|
|
3776
|
+
if (this._closing || this._state === 'closed')
|
|
3777
|
+
return;
|
|
3778
|
+
// 已在重连中则跳过,避免心跳超时和 transport 断线回调重复触发
|
|
3779
|
+
if (this._reconnectActive)
|
|
3780
|
+
return;
|
|
3781
|
+
this._state = 'disconnected';
|
|
3782
|
+
this._stopBackgroundTasks();
|
|
3783
|
+
await this._dispatcher.publish('connection.state', { state: this._state, error });
|
|
3784
|
+
if (!this._sessionOptions.auto_reconnect)
|
|
3785
|
+
return;
|
|
3786
|
+
if (this._reconnectActive)
|
|
3787
|
+
return;
|
|
3788
|
+
// 不重连 close code(认证失败/权限错误/被踢等)或服务端通知断开:抑制重连
|
|
3789
|
+
if (this._serverKicked || (closeCode !== undefined && AUNClient._NO_RECONNECT_CODES.has(closeCode))) {
|
|
3790
|
+
this._state = 'terminal_failed';
|
|
3791
|
+
const reason = this._serverKicked ? 'server kicked' : `close code ${closeCode}`;
|
|
3792
|
+
_clientLog('warn', '抑制自动重连: %s', reason);
|
|
3793
|
+
await this._dispatcher.publish('connection.state', {
|
|
3794
|
+
state: this._state, error, reason,
|
|
3795
|
+
});
|
|
3796
|
+
return;
|
|
3797
|
+
}
|
|
3798
|
+
// 1000 = 正常关闭, 1006 = 网络异常断开(无 close frame),其他 code = 服务端主动关闭
|
|
3799
|
+
const serverInitiated = closeCode !== undefined && closeCode !== 1000 && closeCode !== 1006;
|
|
3800
|
+
this._startReconnect(serverInitiated);
|
|
3801
|
+
}
|
|
3802
|
+
/** 启动重连循环(默认无限重试 + 指数退避 + 固定上限抖动,仅在不可重试错误、close() 或 max_attempts 耗尽时终止) */
|
|
3803
|
+
_startReconnect(serverInitiated = false) {
|
|
3804
|
+
if (this._reconnectActive)
|
|
3805
|
+
return;
|
|
3806
|
+
this._reconnectActive = true;
|
|
3807
|
+
this._reconnectAbort = new AbortController();
|
|
3808
|
+
this._reconnectLoop(serverInitiated).catch((exc) => {
|
|
3809
|
+
_clientLog('warn', '重连循环异常: %s', formatCaughtError(exc));
|
|
3810
|
+
});
|
|
3811
|
+
}
|
|
3812
|
+
/** 重连循环(for 循环 + AbortController,与 JS/Python 对齐) */
|
|
3813
|
+
async _reconnectLoop(serverInitiated) {
|
|
3814
|
+
const retry = this._sessionOptions.retry;
|
|
3815
|
+
const maxBaseDelay = clampReconnectDelayMs(Number(retry.max_delay ?? 64.0) * 1000, RECONNECT_MAX_BASE_DELAY_MS);
|
|
3816
|
+
const maxAttemptsRaw = Number(retry.max_attempts ?? 0);
|
|
3817
|
+
const maxAttempts = Number.isFinite(maxAttemptsRaw) && maxAttemptsRaw > 0 ? Math.floor(maxAttemptsRaw) : 0;
|
|
3818
|
+
let delay = clampReconnectDelayMs(serverInitiated ? 16_000 : Number(retry.initial_delay ?? 1.0) * 1000, serverInitiated ? 16_000 : RECONNECT_MIN_BASE_DELAY_MS, maxBaseDelay);
|
|
3819
|
+
for (let attempt = 1; !this._reconnectAbort?.signal.aborted; attempt++) {
|
|
3820
|
+
if (this._closing)
|
|
3821
|
+
break;
|
|
3822
|
+
// max_attempts 检查在循环顶部,覆盖所有路径(含 health-fail)
|
|
3823
|
+
if (maxAttempts > 0 && attempt > maxAttempts) {
|
|
3824
|
+
this._state = 'terminal_failed';
|
|
3825
|
+
await this._dispatcher.publish('connection.state', {
|
|
3826
|
+
state: this._state,
|
|
3827
|
+
attempt: attempt - 1,
|
|
3828
|
+
reason: 'max_attempts_exhausted',
|
|
3829
|
+
});
|
|
3830
|
+
break;
|
|
3831
|
+
}
|
|
3832
|
+
this._state = 'reconnecting';
|
|
3833
|
+
await this._dispatcher.publish('connection.state', {
|
|
3834
|
+
state: this._state,
|
|
3835
|
+
attempt,
|
|
3836
|
+
});
|
|
3837
|
+
try {
|
|
3838
|
+
// 固定上限抖动:base=[1s, max_base],delay=base+rand(0..max_base)。
|
|
3839
|
+
await this._sleep(reconnectSleepDelayMs(delay, maxBaseDelay));
|
|
3840
|
+
if (this._reconnectAbort?.signal.aborted || this._closing)
|
|
3841
|
+
break;
|
|
3842
|
+
// 重连前先 GET /health 探测,不健康则跳过本轮
|
|
3843
|
+
if (this._gatewayUrl) {
|
|
3844
|
+
const healthy = await this._discovery.checkHealth(this._gatewayUrl, 5_000);
|
|
3845
|
+
if (!healthy) {
|
|
3846
|
+
delay = Math.min(delay * 2, maxBaseDelay);
|
|
3847
|
+
continue;
|
|
3848
|
+
}
|
|
3849
|
+
}
|
|
3850
|
+
await this._transport.close();
|
|
3851
|
+
if (this._sessionParams === null) {
|
|
3852
|
+
throw new StateError('missing connect params for reconnect');
|
|
3853
|
+
}
|
|
3854
|
+
await this._connectOnce(this._sessionParams, true);
|
|
3855
|
+
// 重连成功,退出循环
|
|
3856
|
+
this._reconnectActive = false;
|
|
3857
|
+
this._reconnectAbort = null;
|
|
3858
|
+
return;
|
|
3859
|
+
}
|
|
3860
|
+
catch (exc) {
|
|
3861
|
+
await this._dispatcher.publish('connection.error', {
|
|
3862
|
+
error: formatCaughtError(exc),
|
|
3863
|
+
attempt,
|
|
3864
|
+
});
|
|
3865
|
+
if (!AUNClient._shouldRetryReconnect(exc)) {
|
|
3866
|
+
this._state = 'terminal_failed';
|
|
3867
|
+
await this._dispatcher.publish('connection.state', {
|
|
3868
|
+
state: this._state,
|
|
3869
|
+
error: formatCaughtError(exc),
|
|
3870
|
+
attempt,
|
|
3871
|
+
});
|
|
3872
|
+
break;
|
|
3873
|
+
}
|
|
3874
|
+
delay = Math.min(delay * 2, maxBaseDelay);
|
|
3875
|
+
}
|
|
3876
|
+
}
|
|
3877
|
+
this._reconnectActive = false;
|
|
3878
|
+
this._reconnectAbort = null;
|
|
3879
|
+
}
|
|
3880
|
+
/** 可取消的 sleep */
|
|
3881
|
+
_sleep(ms) {
|
|
3882
|
+
return new Promise((resolve) => {
|
|
3883
|
+
const timer = setTimeout(resolve, ms);
|
|
3884
|
+
this._unrefTimer(timer);
|
|
3885
|
+
});
|
|
3886
|
+
}
|
|
3887
|
+
/** 停止重连 */
|
|
3888
|
+
_stopReconnect() {
|
|
3889
|
+
if (this._reconnectAbort) {
|
|
3890
|
+
this._reconnectAbort.abort();
|
|
3891
|
+
this._reconnectAbort = null;
|
|
3892
|
+
}
|
|
3893
|
+
this._reconnectActive = false;
|
|
3894
|
+
}
|
|
3895
|
+
/** 判断是否应重试重连 */
|
|
3896
|
+
static _shouldRetryReconnect(error) {
|
|
3897
|
+
if (error instanceof AuthError) {
|
|
3898
|
+
const message = String(error.message ?? '').toLowerCase();
|
|
3899
|
+
if (message.includes('aid_login1_failed') || message.includes('aid_login2_failed')) {
|
|
3900
|
+
return true;
|
|
3901
|
+
}
|
|
3902
|
+
return false;
|
|
3903
|
+
}
|
|
3904
|
+
if (error instanceof PermissionError
|
|
3905
|
+
|| error instanceof ValidationError || error instanceof StateError) {
|
|
3906
|
+
return false;
|
|
3907
|
+
}
|
|
3908
|
+
if (error instanceof ConnectionError)
|
|
3909
|
+
return true;
|
|
3910
|
+
if (error instanceof AUNError)
|
|
3911
|
+
return error.retryable;
|
|
3912
|
+
if (error instanceof TimeoutError)
|
|
3913
|
+
return true;
|
|
3914
|
+
// 其他网络错误默认重试
|
|
3915
|
+
return true;
|
|
3916
|
+
}
|
|
3917
|
+
}
|
|
3918
|
+
//# sourceMappingURL=client.js.map
|