dsh-mobile-plugin 0.5.138 → 0.5.140
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/config/agent-presets/standard/skills/dsh-mobile-kb/references/pairing.md +2 -2
- package/lib/impl.js +8 -5
- package/lib/mobile/permissions.js +10 -0
- package/lib/mobile/session-step.js +17 -11
- package/lib/mobile/voice/frames.js +198 -0
- package/lib/mobile/voice/gateway.js +746 -0
- package/lib/mobile/voice/lang.js +347 -0
- package/lib/mobile/voice/lexicon-store.js +189 -0
- package/lib/mobile/voice/lexicon.js +508 -0
- package/lib/mobile/voice/panel-api.js +88 -0
- package/lib/mobile/voice/postprocess.js +551 -0
- package/lib/mobile/voice/protocol.js +306 -0
- package/lib/mobile/voice/providers/cn/aliyun.js +401 -0
- package/lib/mobile/voice/providers/cn/tencent.js +402 -0
- package/lib/mobile/voice/providers/cn/volc.js +328 -0
- package/lib/mobile/voice/providers/cn/xfyun.js +290 -0
- package/lib/mobile/voice/providers/host.js +190 -0
- package/lib/mobile/voice/providers/intl/_common.js +346 -0
- package/lib/mobile/voice/providers/intl/assemblyai.js +353 -0
- package/lib/mobile/voice/providers/intl/azure.js +444 -0
- package/lib/mobile/voice/providers/intl/deepgram.js +366 -0
- package/lib/mobile/voice/providers/intl/openai.js +389 -0
- package/lib/mobile/voice/providers/intl/speechmatics.js +405 -0
- package/lib/mobile/voice/providers/local/ondevice.js +129 -0
- package/lib/mobile/voice/providers/registry.js +277 -0
- package/lib/mobile/voice/routes.js +278 -0
- package/lib/mobile/voice/runtime.js +84 -0
- package/lib/mobile/voice/settings.js +206 -0
- package/lib/mobile/voice/stream.js +415 -0
- package/lib/mobile/voice/voice-provider.js +268 -0
- package/lib/panel/index.html +17 -17
- package/lib/routes/control-plane.js +19 -0
- package/lib/routes/mobile-api.js +33 -1
- package/lib/sidecar-facade-worker.cjs +1 -1
- package/lib/zeronews/runner.cjs +7 -4
- package/lib/zeronews/wiring.cjs +36 -43
- package/package.json +14 -15
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// 2026-11-28:语音 provider 选择、各家配置与每日用量的电脑侧落盘(密钥只在这里)。
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 语音网关的配置存储:**只在电脑侧**。
|
|
6
|
+
*
|
|
7
|
+
* 落点跟插件其它本机偏好一致:`<DSH_HOME>/storages/mobile-plugin/voice-settings.json`,
|
|
8
|
+
* 权限 0600、写临时文件再 rename(与 `relay.json` / 过程播报同一个写法)。手机永远拿不到
|
|
9
|
+
* 这里的原文:能力接口只回 provider 名单,面板配置接口对 secret 字段只回 `set: true/false`。
|
|
10
|
+
*
|
|
11
|
+
* 为什么单独一份、不塞进 `relay.json`:那份是「远程连接」的状态机,有严格的 schema 与
|
|
12
|
+
* 一小撮会重配隧道的订阅者;语音配置写进去等于让每次填个 key 都触发隧道重配,还会让
|
|
13
|
+
* 两个功能共用一条写路径互相牵连。
|
|
14
|
+
*
|
|
15
|
+
* 文件形状(v1,往后只许加字段、不许改含义):
|
|
16
|
+
*
|
|
17
|
+
* ```json
|
|
18
|
+
* {
|
|
19
|
+
* "version": 1,
|
|
20
|
+
* "enabled": true,
|
|
21
|
+
* "default": "host",
|
|
22
|
+
* "providers": { "volc": { "apiKey": "…" } },
|
|
23
|
+
* "usage": { "day": "2026-11-28", "seconds": 0, "requests": 0 }
|
|
24
|
+
* }
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
const fs = require('node:fs');
|
|
29
|
+
const path = require('node:path');
|
|
30
|
+
|
|
31
|
+
const { dshHome } = require('../../shared/paths.js');
|
|
32
|
+
|
|
33
|
+
function isPlainObject(value) {
|
|
34
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const SETTINGS_VERSION = 1;
|
|
38
|
+
/** 每日额度:按音频秒数算,另加一条请求数上限(防小段请求刷爆上游次数)。可用环境变量调。 */
|
|
39
|
+
const DEFAULT_DAILY_SECONDS = Number(process.env.DSH_MOBILE_VOICE_DAILY_SECONDS) || 3600;
|
|
40
|
+
const DEFAULT_DAILY_REQUESTS = Number(process.env.DSH_MOBILE_VOICE_DAILY_REQUESTS) || 500;
|
|
41
|
+
/** 单个配置值的长度上限:key / endpoint 都远小于它,挡的是往配置里灌正文。 */
|
|
42
|
+
const MAX_CONFIG_VALUE_CHARS = 4096;
|
|
43
|
+
|
|
44
|
+
function defaultFile() {
|
|
45
|
+
return path.join(dshHome(), 'storages', 'mobile-plugin', 'voice-settings.json');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 本地日期键(按用户所在时区算一天,跨天清零)。 */
|
|
49
|
+
function dayKey(now) {
|
|
50
|
+
const date = now instanceof Date ? now : new Date();
|
|
51
|
+
const year = date.getFullYear();
|
|
52
|
+
const month = String(date.getMonth() + 1).padStart(2, '0');
|
|
53
|
+
const day = String(date.getDate()).padStart(2, '0');
|
|
54
|
+
return `${year}-${month}-${day}`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 缺省状态:默认 `host`(宿主装了语音包就零配置可用),开关开,用量清零。 */
|
|
58
|
+
function defaultState() {
|
|
59
|
+
return { version: SETTINGS_VERSION, enabled: true, default: 'host', providers: {}, usage: { day: '', seconds: 0, requests: 0 } };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 把盘上读到的任意形状收敛成可用状态;脏值就地丢弃,不报错(与 relay.json 同口径)。 */
|
|
63
|
+
function normalizeState(raw, now) {
|
|
64
|
+
const base = defaultState();
|
|
65
|
+
if (!isPlainObject(raw)) return base;
|
|
66
|
+
if (typeof raw.enabled === 'boolean') base.enabled = raw.enabled;
|
|
67
|
+
if (typeof raw.default === 'string' && raw.default.trim()) base.default = raw.default.trim();
|
|
68
|
+
if (isPlainObject(raw.providers)) {
|
|
69
|
+
for (const [id, config] of Object.entries(raw.providers)) {
|
|
70
|
+
// id 的合法性由 settings 调用方(面板)保证;这里只收对象形状,避免脏文件把后续读取带崩。
|
|
71
|
+
if (!/^[a-z][a-z0-9-]{0,31}$/.test(id) || !isPlainObject(config)) continue;
|
|
72
|
+
const clean = {};
|
|
73
|
+
for (const [key, value] of Object.entries(config)) {
|
|
74
|
+
if (typeof value === 'string') clean[key] = value.slice(0, MAX_CONFIG_VALUE_CHARS);
|
|
75
|
+
else if (typeof value === 'number' && Number.isFinite(value)) clean[key] = value;
|
|
76
|
+
else if (typeof value === 'boolean') clean[key] = value;
|
|
77
|
+
}
|
|
78
|
+
base.providers[id] = clean;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const usage = isPlainObject(raw.usage) ? raw.usage : null;
|
|
82
|
+
const today = dayKey(now);
|
|
83
|
+
if (usage && usage.day === today) {
|
|
84
|
+
base.usage = {
|
|
85
|
+
day: today,
|
|
86
|
+
seconds: Number.isFinite(usage.seconds) && usage.seconds > 0 ? Math.floor(usage.seconds) : 0,
|
|
87
|
+
requests: Number.isFinite(usage.requests) && usage.requests > 0 ? Math.floor(usage.requests) : 0,
|
|
88
|
+
};
|
|
89
|
+
} else {
|
|
90
|
+
base.usage = { day: today, seconds: 0, requests: 0 };
|
|
91
|
+
}
|
|
92
|
+
return base;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* 建一个配置存储。
|
|
97
|
+
*
|
|
98
|
+
* @param {{ file?: string, now?: () => Date }} [options] `file` 只给测试指到临时目录;
|
|
99
|
+
* `now` 让「跨天」可在测试里构造。
|
|
100
|
+
*/
|
|
101
|
+
function createVoiceSettingsStore(options = {}) {
|
|
102
|
+
const file = typeof options.file === 'string' && options.file ? options.file : defaultFile();
|
|
103
|
+
const now = typeof options.now === 'function' ? options.now : () => new Date();
|
|
104
|
+
let cached = null;
|
|
105
|
+
|
|
106
|
+
/** 读状态。每次调用会顺带做跨天清零(用量过了零点就归零,但**不写盘**)。 */
|
|
107
|
+
function read() {
|
|
108
|
+
if (!cached) {
|
|
109
|
+
let raw = null;
|
|
110
|
+
try {
|
|
111
|
+
raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
112
|
+
} catch { /* 没文件 / 读坏都从缺省开始,用户第一次打开面板不该看到报错 */ }
|
|
113
|
+
cached = normalizeState(raw, now());
|
|
114
|
+
}
|
|
115
|
+
// 跨天:用量归零但不落盘 —— 落盘要等真的用了一次,别让「只是打开面板」写一次盘。
|
|
116
|
+
const today = dayKey(now());
|
|
117
|
+
if (cached.usage.day !== today) cached.usage = { day: today, seconds: 0, requests: 0 };
|
|
118
|
+
return cached;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** 落盘:0600(里面有 key),先写 tmp 再 rename,避免半截文件。 */
|
|
122
|
+
function save() {
|
|
123
|
+
const state = read();
|
|
124
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
125
|
+
const tmp = `${file}.tmp`;
|
|
126
|
+
fs.writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
|
|
127
|
+
fs.renameSync(tmp, file);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return {
|
|
131
|
+
file,
|
|
132
|
+
/** 完整状态(内部用,含密钥;**不要**把它直接交给面板 / 手机)。 */
|
|
133
|
+
read,
|
|
134
|
+
enabled() {
|
|
135
|
+
return read().enabled === true;
|
|
136
|
+
},
|
|
137
|
+
/** 总开关:关掉后两个入口都回 `voice-disabled`。 */
|
|
138
|
+
setEnabled(enabled) {
|
|
139
|
+
read().enabled = enabled === true;
|
|
140
|
+
save();
|
|
141
|
+
return read().enabled;
|
|
142
|
+
},
|
|
143
|
+
defaultProvider() {
|
|
144
|
+
return read().default;
|
|
145
|
+
},
|
|
146
|
+
setDefault(id) {
|
|
147
|
+
read().default = typeof id === 'string' ? id.trim().slice(0, 64) : '';
|
|
148
|
+
save();
|
|
149
|
+
return read().default;
|
|
150
|
+
},
|
|
151
|
+
/** 某家 provider 的配置(含密钥,只给适配器 / 面板回显逻辑用,别原样回包)。 */
|
|
152
|
+
configFor(id) {
|
|
153
|
+
if (typeof id !== 'string' || !id) return {};
|
|
154
|
+
const config = read().providers[id];
|
|
155
|
+
return isPlainObject(config) ? config : {};
|
|
156
|
+
},
|
|
157
|
+
/** 合并写入某家的配置;值是 `undefined` 表示不动,空串表示清掉该字段。 */
|
|
158
|
+
setConfig(id, patch) {
|
|
159
|
+
if (typeof id !== 'string' || !/^[a-z][a-z0-9-]{0,31}$/.test(id)) return {};
|
|
160
|
+
const state = read();
|
|
161
|
+
const next = { ...(isPlainObject(state.providers[id]) ? state.providers[id] : {}) };
|
|
162
|
+
for (const [key, value] of Object.entries(isPlainObject(patch) ? patch : {})) {
|
|
163
|
+
if (value === undefined) continue;
|
|
164
|
+
if (value === '') { delete next[key]; continue; }
|
|
165
|
+
if (typeof value === 'string') next[key] = value.slice(0, MAX_CONFIG_VALUE_CHARS);
|
|
166
|
+
else if (typeof value === 'number' && Number.isFinite(value)) next[key] = value;
|
|
167
|
+
else if (typeof value === 'boolean') next[key] = value;
|
|
168
|
+
}
|
|
169
|
+
state.providers[id] = next;
|
|
170
|
+
save();
|
|
171
|
+
return next;
|
|
172
|
+
},
|
|
173
|
+
usage() {
|
|
174
|
+
return { ...read().usage };
|
|
175
|
+
},
|
|
176
|
+
limits() {
|
|
177
|
+
return {
|
|
178
|
+
dailySeconds: DEFAULT_DAILY_SECONDS,
|
|
179
|
+
dailyRequests: DEFAULT_DAILY_REQUESTS,
|
|
180
|
+
};
|
|
181
|
+
},
|
|
182
|
+
/**
|
|
183
|
+
* 记一次成功识别。
|
|
184
|
+
*
|
|
185
|
+
* 只记成功的那一次:失败的请求不该吃掉用户额度(上游失败还扣钱是第二重伤害)。
|
|
186
|
+
* 写盘失败不抛:记录用量失败不该让一次已经成功的识别变成报错。
|
|
187
|
+
*/
|
|
188
|
+
noteUsage({ seconds = 0, requests = 1 } = {}) {
|
|
189
|
+
const state = read();
|
|
190
|
+
state.usage.seconds += Math.max(0, Math.floor(Number(seconds) || 0));
|
|
191
|
+
state.usage.requests += Math.max(0, Math.floor(Number(requests) || 0));
|
|
192
|
+
try { save(); } catch { /* 用量记账失败不影响识别结果 */ }
|
|
193
|
+
return { ...state.usage };
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
module.exports = {
|
|
199
|
+
createVoiceSettingsStore,
|
|
200
|
+
defaultFile,
|
|
201
|
+
dayKey,
|
|
202
|
+
defaultState,
|
|
203
|
+
normalizeState,
|
|
204
|
+
DEFAULT_DAILY_SECONDS,
|
|
205
|
+
DEFAULT_DAILY_REQUESTS,
|
|
206
|
+
};
|
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
// 2026-11-28:语音流式入口(WebSocket 升级路由)——一条连接一个流会话,鉴权与 mux 同源。
|
|
2
|
+
// 2026-11-28:升级处理器改为接收装配层显式传入的 ctx(第四参数),运行时记的 ctx 只作兜底。
|
|
3
|
+
// 2026-11-28:`start.enc === "v2"` 的连接逐帧封 / 解(字节口径全在 `./frames.js`),没声明就照旧收明文。
|
|
4
|
+
'use strict';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* `/api/mobile/v1/voice/stream` 的 WebSocket 服务。
|
|
8
|
+
*
|
|
9
|
+
* 为什么不进 mux:mux 只承载 JSON 文本帧(见 `mobile/mux.js` 文件头),而语音每 100 ms 就是
|
|
10
|
+
* 一包二进制 PCM;塞进文本通道要 base64(体积 +33%)、还会和对话请求抢同一条流。所以单开
|
|
11
|
+
* 一条升级路由,鉴权照 mux 的做法在**握手之前**做完:
|
|
12
|
+
*
|
|
13
|
+
* - 凭据、吊销、过期、权限位的判定全部复用 `mobile/auth.js` 与 `mobile/permissions.js`;
|
|
14
|
+
* - 拒绝时还在 HTTP 阶段,能干净地回 401/403 再关 socket,而不是给对端一条立断的 WS;
|
|
15
|
+
* - 连上之后所有权归这条连接:**一条连接最多一个在飞的流会话**,断开 / 取消统一释放,
|
|
16
|
+
* 不挂模块级单例(否则两个人同时说话会互相串音频)。
|
|
17
|
+
*
|
|
18
|
+
* 帧契约见 `docs/voice-input-contract.md` §2。provider 不支持流式时网关内部降级,这里
|
|
19
|
+
* 只是把 `ready.streaming=false` 如实告诉客户端、继续收 PCM、到 stop 才发 final。
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const { WebSocketServer } = require('ws');
|
|
23
|
+
|
|
24
|
+
const protocol = require('./protocol.js');
|
|
25
|
+
const frames = require('./frames.js');
|
|
26
|
+
const { authOutcome } = require('../auth.js');
|
|
27
|
+
const { hasPermission, resolvePermission } = require('../permissions.js');
|
|
28
|
+
const { voiceGatewayFor } = require('./runtime.js');
|
|
29
|
+
|
|
30
|
+
const { CLIENT_FRAMES, SERVER_FRAMES, VOICE_ERRORS, voiceError } = protocol;
|
|
31
|
+
|
|
32
|
+
/** 单条连接同时只会有一个流会话;留两格是为了「cancel 之后立刻 start 新的」不被误伤。 */
|
|
33
|
+
const MAX_SESSIONS_PER_CONNECTION = 2;
|
|
34
|
+
/** 整台电脑同时最多几条语音流:够几个用户各说各的,又不至于把内存吃穿。 */
|
|
35
|
+
const MAX_CONCURRENT_SESSIONS = 16;
|
|
36
|
+
const HEARTBEAT_INTERVAL_MS = 15_000;
|
|
37
|
+
const PONG_TIMEOUT_MS = 45_000;
|
|
38
|
+
/** 单帧上限:100 ms 是 3200 字节,这里留足余量;加密帧只多出 seq + nonce + tag 那点固定开销。 */
|
|
39
|
+
const WS_MAX_PAYLOAD = protocol.MAX_AUDIO_FRAME_BYTES + protocol.FRAME_SEQ_BYTES + frames.FRAME_OVERHEAD;
|
|
40
|
+
/** 会话超时余量:到 provider 上限之后再多给几秒,让「最后一句 final」有机会回来。 */
|
|
41
|
+
const TIMEOUT_GRACE_MS = 5_000;
|
|
42
|
+
|
|
43
|
+
function safeJson(text) {
|
|
44
|
+
try { return JSON.parse(text); } catch { return null; }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 握手拒绝:还是 HTTP 阶段,能回一句状态码再关,不用等差一个 WS close 帧。 */
|
|
48
|
+
function reject(socket, status, reason) {
|
|
49
|
+
const line = status === 401 ? '401 Unauthorized' : status === 403 ? '403 Forbidden' : '429 Too Many Requests';
|
|
50
|
+
try { socket.write(`HTTP/1.1 ${line}\r\nconnection: close\r\ncontent-length: 0\r\nx-dsh-voice-reject: ${reason}\r\n\r\n`); } catch { /* 已断 */ }
|
|
51
|
+
try { socket.destroy(); } catch { /* 已关 */ }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 建流式服务。返回 `handleUpgrade(req, socket, head)`,由路由注册器挂到宿主 webServer。
|
|
56
|
+
*
|
|
57
|
+
* @param {{ log?: Function }} [options]
|
|
58
|
+
*/
|
|
59
|
+
function createVoiceStreamService(options = {}) {
|
|
60
|
+
const log = typeof options.log === 'function' ? options.log : () => {};
|
|
61
|
+
const wss = new WebSocketServer({ noServer: true, maxPayload: WS_MAX_PAYLOAD });
|
|
62
|
+
let activeSessions = 0;
|
|
63
|
+
let connections = 0;
|
|
64
|
+
/** 当前活着的连接(含它属于哪台设备),设备吊销时按设备号断掉。 */
|
|
65
|
+
const liveConnections = new Set();
|
|
66
|
+
|
|
67
|
+
/** 逐路由权限:与 guarded 同一个判定口径(这里没有信封,但凭据与权限位一样查)。 */
|
|
68
|
+
function authorize(req) {
|
|
69
|
+
let outcome;
|
|
70
|
+
try {
|
|
71
|
+
outcome = authOutcome(req);
|
|
72
|
+
} catch {
|
|
73
|
+
return { ok: false, status: 401, reason: 'unauthorized' };
|
|
74
|
+
}
|
|
75
|
+
if (!outcome.ok) return { ok: false, status: 401, reason: outcome.reason || 'unauthorized' };
|
|
76
|
+
if (outcome.record) req.__dshRecord = outcome.record;
|
|
77
|
+
const need = resolvePermission('/api/mobile/v1/voice/stream', 'GET');
|
|
78
|
+
if (need === 'unknown') return { ok: false, status: 403, reason: 'permission-unclassified' };
|
|
79
|
+
if (need && !hasPermission(req.__dshRecord, need)) return { ok: false, status: 403, reason: 'permission-denied' };
|
|
80
|
+
return { ok: true };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* 升级处理器:宿主按 `(req, socket, head)` 调,**拿不到插件 ctx**。
|
|
85
|
+
*
|
|
86
|
+
* 流式会话要问宿主(host 适配器的 `ctx.speechToText`),所以装配层(`lib/routes/mobile-api.js`)
|
|
87
|
+
* 在挂 `/voice/stream` 时把当前这一代 ctx 作为第四参数递进来;只有本机调试 / 测试这类没传
|
|
88
|
+
* ctx 的调用方才退回 `runtime.js` 记下的值(App 开麦前必先调 `/voice/capabilities`,正常
|
|
89
|
+
* 时序下一定有值)。一条连接从 start 到 final 问的是同一代宿主。
|
|
90
|
+
*/
|
|
91
|
+
function handleUpgrade(req, socket, head, ctx) {
|
|
92
|
+
const verdict = authorize(req);
|
|
93
|
+
if (verdict.ok !== true) {
|
|
94
|
+
reject(socket, verdict.status, verdict.reason);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
if (connections >= MAX_CONCURRENT_SESSIONS * 2) {
|
|
98
|
+
reject(socket, 429, 'too-many-connections');
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
wss.handleUpgrade(req, socket, head, (ws) => open(ws, req, ctx));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function open(ws, req, ctx) {
|
|
105
|
+
connections += 1;
|
|
106
|
+
/** 这条连接属于哪台设备:吊销凭据时要能就地断开(见 dropDevice)。 */
|
|
107
|
+
const owner = {
|
|
108
|
+
deviceId: String((req && req.__dshRecord && req.__dshRecord.deviceId) || ''),
|
|
109
|
+
instanceId: String((req && req.__dshRecord && req.__dshRecord.instanceId) || ''),
|
|
110
|
+
close: null,
|
|
111
|
+
};
|
|
112
|
+
liveConnections.add(owner);
|
|
113
|
+
/** 本连接的流会话表:id → 会话句柄。断开时逐条 cancel(会话归连接所有)。 */
|
|
114
|
+
const sessions = new Map();
|
|
115
|
+
/** 已声明加密的流:id → `frames.createVoiceCipher` 的封 / 解状态(一条流一份序号)。 */
|
|
116
|
+
const ciphers = new Map();
|
|
117
|
+
/** 这条连接一旦声明过 `enc`,之后的 start 必须继续声明,不能退回明文。 */
|
|
118
|
+
let encDeviceKey = '';
|
|
119
|
+
let closed = false;
|
|
120
|
+
/** 二进制音频没有 id:一条连接同一时刻只认一条「当前流」,到 stop/cancel/final 才换。 */
|
|
121
|
+
let currentId = null;
|
|
122
|
+
let lastPong = Date.now();
|
|
123
|
+
let heartbeat = null;
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* 下行帧:属于加密流的帧按那条流的下行密钥封,其余原样 JSON。
|
|
127
|
+
*
|
|
128
|
+
* 封不了的(加密会话里却没有对应流 id 的帧)直接丢:宁可少一帧,也不能把明文塞进一条
|
|
129
|
+
* 已经声明加密的连接 —— 那正是「加密被降级」的样子。
|
|
130
|
+
*/
|
|
131
|
+
const send = (frame) => {
|
|
132
|
+
if (closed || ws.readyState !== 1 /* OPEN */) return;
|
|
133
|
+
const key = typeof frame.id === 'string' || typeof frame.id === 'number' ? String(frame.id) : '';
|
|
134
|
+
const cipher = key ? ciphers.get(key) : null;
|
|
135
|
+
let text;
|
|
136
|
+
if (cipher) {
|
|
137
|
+
try { text = cipher.sealDownFrame(frame); } catch { return; }
|
|
138
|
+
} else if (encDeviceKey) {
|
|
139
|
+
return;
|
|
140
|
+
} else {
|
|
141
|
+
text = JSON.stringify(frame);
|
|
142
|
+
}
|
|
143
|
+
try { ws.send(text); } catch { /* 对端已断 */ }
|
|
144
|
+
};
|
|
145
|
+
const sendError = (id, error) => {
|
|
146
|
+
const payload = protocol.errorPayload(error);
|
|
147
|
+
send({ t: SERVER_FRAMES.ERROR, id: id ?? null, code: payload.code, message: payload.message });
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
const dropSession = (id, { quiet = false } = {}) => {
|
|
151
|
+
const entry = sessions.get(id);
|
|
152
|
+
if (!entry) return;
|
|
153
|
+
sessions.delete(id);
|
|
154
|
+
clearTimeout(entry.timer);
|
|
155
|
+
activeSessions = Math.max(0, activeSessions - 1);
|
|
156
|
+
if (!quiet) {
|
|
157
|
+
try { entry.session.cancel(); } catch { /* ignore */ }
|
|
158
|
+
}
|
|
159
|
+
return entry;
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
/** 开一条流会话:provider 与限额由网关判,这里只做帧层的事情。 */
|
|
163
|
+
const startSession = (frame) => {
|
|
164
|
+
const id = frame && (typeof frame.id === 'string' || typeof frame.id === 'number') ? frame.id : null;
|
|
165
|
+
if (id === null) { sendError(null, voiceError(VOICE_ERRORS.FAILED, 'start 帧缺 id')); return; }
|
|
166
|
+
|
|
167
|
+
// ── 加密声明 ──
|
|
168
|
+
// App 只在能力表声明了 `features.streamE2ee` 时才发 `enc`。声明了就整条流都封:这条
|
|
169
|
+
// 连接上后续的 start 也必须继续声明,否则一次「没声明」就等于给这条连接留了明文口。
|
|
170
|
+
// 没声明 `enc` 的一律走老帧(本机调试、老 App、守卫都在用),明文不是线上降级口。
|
|
171
|
+
let cipher = null;
|
|
172
|
+
if (frame.enc === frames.ENC_VERSION) {
|
|
173
|
+
const deviceKey = req && req.__dshRecord && typeof req.__dshRecord.deviceKey === 'string'
|
|
174
|
+
? req.__dshRecord.deviceKey
|
|
175
|
+
: '';
|
|
176
|
+
if (!deviceKey) {
|
|
177
|
+
// 老凭据里没有设备密钥:明说一句再断开,App 会退回整段识别,别让它对着一条永远
|
|
178
|
+
// 解不开的流干等。
|
|
179
|
+
sendError(id, voiceError(VOICE_ERRORS.FAILED, '这台电脑上没有这条设备凭据的密钥,没法加密这条语音流'));
|
|
180
|
+
try { ws.close(1008, 'voice encryption unavailable'); } catch { /* 已断 */ }
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
try {
|
|
184
|
+
cipher = frames.createVoiceCipher({ deviceKey, streamId: String(id) });
|
|
185
|
+
} catch {
|
|
186
|
+
sendError(id, voiceError(VOICE_ERRORS.FAILED, '加密这条语音流失败'));
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
ciphers.set(String(id), cipher);
|
|
190
|
+
encDeviceKey = deviceKey;
|
|
191
|
+
} else if (encDeviceKey) {
|
|
192
|
+
sendError(id, voiceError(VOICE_ERRORS.INVALID_AUDIO, '这条连接已经声明加密,start 必须继续声明 enc'));
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
/** start 失败:撤掉刚建好的加密状态,免得后面拿它封一条并不存在的流。 */
|
|
196
|
+
const abortStart = (error) => {
|
|
197
|
+
if (cipher) ciphers.delete(String(id));
|
|
198
|
+
sendError(id, error);
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
if (sessions.has(id)) { abortStart(voiceError(VOICE_ERRORS.FAILED, '这个 id 的流已经开始了')); return; }
|
|
202
|
+
if (sessions.size >= MAX_SESSIONS_PER_CONNECTION) { abortStart(voiceError(VOICE_ERRORS.RATE_LIMITED, '这条连接上同时只能有一条语音流')); return; }
|
|
203
|
+
if (activeSessions >= MAX_CONCURRENT_SESSIONS) { abortStart(voiceError(VOICE_ERRORS.RATE_LIMITED, '这台电脑同时在识别的语音流太多了')); return; }
|
|
204
|
+
// 格式必须与协议口径一致:客户端报了别的值就直接拒,省得后面算时长 / 降级时全都错。
|
|
205
|
+
const format = frame.format && typeof frame.format === 'object' ? frame.format : {};
|
|
206
|
+
const rate = Number(format.rate || protocol.SAMPLE_RATE);
|
|
207
|
+
const bits = Number(format.bits || protocol.BITS_PER_SAMPLE);
|
|
208
|
+
const channels = Number(format.channels || protocol.CHANNELS);
|
|
209
|
+
if (rate !== protocol.SAMPLE_RATE || bits !== protocol.BITS_PER_SAMPLE || channels !== protocol.CHANNELS) {
|
|
210
|
+
abortStart(voiceError(VOICE_ERRORS.INVALID_AUDIO, `音频格式必须是 ${protocol.SAMPLE_RATE} Hz / ${protocol.BITS_PER_SAMPLE}-bit / 单声道`));
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
let gateway;
|
|
215
|
+
try {
|
|
216
|
+
gateway = voiceGatewayFor(ctx);
|
|
217
|
+
} catch (error) {
|
|
218
|
+
abortStart(protocol.voiceError(VOICE_ERRORS.FAILED, error && error.message ? error.message : '语音服务没起来'));
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
let session;
|
|
223
|
+
try {
|
|
224
|
+
session = gateway.openStream({
|
|
225
|
+
providerId: typeof frame.provider === 'string' ? frame.provider : undefined,
|
|
226
|
+
lang: typeof frame.lang === 'string' ? frame.lang : 'auto',
|
|
227
|
+
hints: frame.hints && typeof frame.hints === 'object' ? frame.hints : {},
|
|
228
|
+
onReady: (info) => send({ t: SERVER_FRAMES.READY, id, provider: info.provider, streaming: info.streaming === true }),
|
|
229
|
+
onPartial: (text) => send({ t: SERVER_FRAMES.PARTIAL, id, text }),
|
|
230
|
+
onFinal: (result) => {
|
|
231
|
+
const entry = sessions.get(id);
|
|
232
|
+
if (closed || !entry || entry.session !== session) return;
|
|
233
|
+
clearTimeout(entry.timer);
|
|
234
|
+
sessions.delete(id);
|
|
235
|
+
if (currentId === id) currentId = null;
|
|
236
|
+
activeSessions = Math.max(0, activeSessions - 1);
|
|
237
|
+
send({
|
|
238
|
+
t: SERVER_FRAMES.FINAL,
|
|
239
|
+
id,
|
|
240
|
+
text: result.text,
|
|
241
|
+
...(result.lang ? { lang: result.lang } : {}),
|
|
242
|
+
provider: result.provider,
|
|
243
|
+
durationMs: result.durationMs,
|
|
244
|
+
corrected: result.corrected === true,
|
|
245
|
+
});
|
|
246
|
+
// final 必须先封再撤密钥:反过来的话最后一帧就是明文,客户端整帧丢,终稿没了。
|
|
247
|
+
ciphers.delete(String(id));
|
|
248
|
+
},
|
|
249
|
+
onError: (error) => {
|
|
250
|
+
if (closed || sessions.get(id)?.session !== session) return;
|
|
251
|
+
// 取消后的 voice-failed 是收尾信号,不对客户端报错。
|
|
252
|
+
if (error && error.cancelled === true) return;
|
|
253
|
+
sendError(id, error);
|
|
254
|
+
ciphers.delete(String(id));
|
|
255
|
+
if (currentId === id) currentId = null;
|
|
256
|
+
dropSession(id, { quiet: true });
|
|
257
|
+
},
|
|
258
|
+
});
|
|
259
|
+
} catch (error) {
|
|
260
|
+
abortStart(error);
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const entry = { session, timer: null };
|
|
265
|
+
sessions.set(id, entry);
|
|
266
|
+
currentId = id;
|
|
267
|
+
activeSessions += 1;
|
|
268
|
+
// 兜底超时:网关按收到的 PCM 判时长,但如果客户端一直不发也不 stop,连接会永远挂着。
|
|
269
|
+
entry.timer = setTimeout(() => {
|
|
270
|
+
if (closed || sessions.get(id) !== entry) return;
|
|
271
|
+
sendError(id, voiceError(VOICE_ERRORS.TOO_LONG, `音频超过上限(${session.limits.maxSeconds} 秒)`));
|
|
272
|
+
ciphers.delete(String(id));
|
|
273
|
+
dropSession(id);
|
|
274
|
+
}, session.limits.maxSeconds * 1000 + TIMEOUT_GRACE_MS);
|
|
275
|
+
entry.timer.unref?.();
|
|
276
|
+
};
|
|
277
|
+
const onFrame = (frame) => {
|
|
278
|
+
switch (frame.t) {
|
|
279
|
+
case CLIENT_FRAMES.START:
|
|
280
|
+
startSession(frame);
|
|
281
|
+
break;
|
|
282
|
+
case CLIENT_FRAMES.STOP: {
|
|
283
|
+
const id = frame.id;
|
|
284
|
+
const entry = sessions.get(id);
|
|
285
|
+
if (!entry) return;
|
|
286
|
+
// finish 之后由网关的 onFinal / onError 收尾;这里不动表,避免 final 被当成孤儿会话。
|
|
287
|
+
void entry.session.finish();
|
|
288
|
+
break;
|
|
289
|
+
}
|
|
290
|
+
case CLIENT_FRAMES.CANCEL: {
|
|
291
|
+
const entry = sessions.get(frame.id);
|
|
292
|
+
if (!entry) return;
|
|
293
|
+
clearTimeout(entry.timer);
|
|
294
|
+
try { entry.session.cancel(); } catch { /* ignore */ }
|
|
295
|
+
sessions.delete(frame.id);
|
|
296
|
+
ciphers.delete(String(frame.id));
|
|
297
|
+
if (currentId === frame.id) currentId = null;
|
|
298
|
+
activeSessions = Math.max(0, activeSessions - 1);
|
|
299
|
+
break;
|
|
300
|
+
}
|
|
301
|
+
default:
|
|
302
|
+
break; // 未知帧忽略(前向兼容)
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
const cleanup = () => {
|
|
307
|
+
if (closed) return;
|
|
308
|
+
closed = true;
|
|
309
|
+
clearInterval(heartbeat);
|
|
310
|
+
for (const [, entry] of sessions) {
|
|
311
|
+
clearTimeout(entry.timer);
|
|
312
|
+
activeSessions = Math.max(0, activeSessions - 1);
|
|
313
|
+
try { entry.session.cancel(); } catch { /* ignore */ }
|
|
314
|
+
}
|
|
315
|
+
sessions.clear();
|
|
316
|
+
ciphers.clear();
|
|
317
|
+
connections = Math.max(0, connections - 1);
|
|
318
|
+
liveConnections.delete(owner);
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
// 吊销凭据时就地断开这条连接:会话跟着 cleanup 一起取消。
|
|
322
|
+
owner.close = (reason) => {
|
|
323
|
+
cleanup();
|
|
324
|
+
try { ws.close(1000, reason || 'device revoked'); } catch { try { ws.terminate(); } catch { /* 已关 */ } }
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
heartbeat = setInterval(() => {
|
|
328
|
+
if (closed) return;
|
|
329
|
+
if (ws.readyState !== 1 || Date.now() - lastPong >= PONG_TIMEOUT_MS) {
|
|
330
|
+
cleanup();
|
|
331
|
+
try { ws.terminate(); } catch { /* 已关 */ }
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
try { ws.ping(); } catch {
|
|
335
|
+
cleanup();
|
|
336
|
+
try { ws.terminate(); } catch { /* 已关 */ }
|
|
337
|
+
}
|
|
338
|
+
}, HEARTBEAT_INTERVAL_MS);
|
|
339
|
+
heartbeat.unref?.();
|
|
340
|
+
ws.on('pong', () => { lastPong = Date.now(); });
|
|
341
|
+
|
|
342
|
+
ws.on('message', (data, isBinary) => {
|
|
343
|
+
if (closed) return;
|
|
344
|
+
const bytes = Buffer.isBuffer(data) ? data : Buffer.from(data);
|
|
345
|
+
if (isBinary) {
|
|
346
|
+
// 二进制帧只放音频;当前没有进行中的会话就丢掉(可能是 cancel 之后在途的一包)。
|
|
347
|
+
if (currentId === null) return;
|
|
348
|
+
const entry = sessions.get(currentId);
|
|
349
|
+
if (!entry) { currentId = null; return; }
|
|
350
|
+
// 加密流的解封与序号校验都跟着这条流走(每条流一个计数器,见 frames.js)。
|
|
351
|
+
const cipher = ciphers.get(String(currentId));
|
|
352
|
+
if (cipher) {
|
|
353
|
+
const opened = cipher.openUpAudio(bytes);
|
|
354
|
+
if (!opened.ok) { sendError(currentId, protocol.voiceError(opened.code, opened.message)); return; }
|
|
355
|
+
entry.session.push(opened.pcm, opened.seq);
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
const parsed = protocol.parseAudioFrame(bytes);
|
|
359
|
+
if (!parsed.ok) {
|
|
360
|
+
sendError(null, protocol.voiceError(parsed.code, parsed.message));
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
entry.session.push(parsed.pcm, parsed.seq);
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
const text = bytes.toString('utf8');
|
|
367
|
+
// 加密会话里只认封好的控制帧:明文控制帧等于「把加密会话拖回明文」,直接拒。
|
|
368
|
+
const cipher = currentId === null ? null : ciphers.get(String(currentId));
|
|
369
|
+
let frame;
|
|
370
|
+
if (cipher) {
|
|
371
|
+
const opened = cipher.openUpControl(text);
|
|
372
|
+
if (!opened.ok) { sendError(currentId, protocol.voiceError(opened.code, opened.message)); return; }
|
|
373
|
+
frame = opened.frame;
|
|
374
|
+
} else {
|
|
375
|
+
frame = safeJson(text);
|
|
376
|
+
}
|
|
377
|
+
if (!frame || typeof frame !== 'object') { log('语音流:收到坏 JSON 帧'); return; }
|
|
378
|
+
try { onFrame(frame); } catch (error) { sendError(frame.id ?? null, error); }
|
|
379
|
+
});
|
|
380
|
+
ws.on('close', cleanup);
|
|
381
|
+
ws.on('error', cleanup);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** 断开某台设备的全部语音流;返回断掉的连接数。 */
|
|
385
|
+
function dropDevice(deviceId, instanceId) {
|
|
386
|
+
let dropped = 0;
|
|
387
|
+
for (const owner of liveConnections) {
|
|
388
|
+
if (deviceId && owner.deviceId !== deviceId) continue;
|
|
389
|
+
if (instanceId && owner.instanceId && owner.instanceId !== instanceId) continue;
|
|
390
|
+
if (!owner.close) continue;
|
|
391
|
+
owner.close('device revoked');
|
|
392
|
+
dropped += 1;
|
|
393
|
+
}
|
|
394
|
+
return dropped;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** 断开全部语音流(换身份 / 全量清理);返回断掉的连接数。 */
|
|
398
|
+
function dropAll(instanceId) {
|
|
399
|
+
return dropDevice('', instanceId);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
return {
|
|
403
|
+
handleUpgrade,
|
|
404
|
+
dropDevice,
|
|
405
|
+
dropAll,
|
|
406
|
+
MAX_CONCURRENT_SESSIONS,
|
|
407
|
+
MAX_SESSIONS_PER_CONNECTION,
|
|
408
|
+
WS_MAX_PAYLOAD,
|
|
409
|
+
/** 当前连接数(测试与诊断用)。 */
|
|
410
|
+
connectionCount: () => connections,
|
|
411
|
+
activeSessionCount: () => activeSessions,
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
module.exports = { createVoiceStreamService, WS_MAX_PAYLOAD, MAX_CONCURRENT_SESSIONS };
|