jbc-dssi 1.1.155 → 1.1.158

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/index.js CHANGED
@@ -2305,6 +2305,7 @@ class BridgeConnection {
2305
2305
  if (got === this.opts.token) {
2306
2306
  this.authed = true;
2307
2307
  this.send(FRAME.READY, { authed: true });
2308
+ this.send(FRAME.VOICE_LIST, { voices: EDGE_VOICES });
2308
2309
  this.opts.log(`认证通过 App=${payload?.appVersion ?? '未知版本'}`);
2309
2310
  } else {
2310
2311
  // 长度和前几位足够定位问题:是少字符、多空格,还是完全另一个值
package/lib/edge-tts.js CHANGED
@@ -1,4 +1,8 @@
1
- import { MsEdgeTTS, OUTPUT_FORMAT } from 'msedge-tts';
1
+ import WebSocket from 'ws';
2
+ import { randomUUID } from 'node:crypto';
3
+ import SecMsGec from './sec-ms-gec.cjs';
4
+
5
+ const { hashSecMsGecV2 } = SecMsGec;
2
6
 
3
7
  export const EDGE_VOICES = [
4
8
  { id: 'zh-CN-XiaoxiaoNeural', name: '晓晓', gender: '女声', note: '温暖自然' },
@@ -9,7 +13,6 @@ export const EDGE_VOICES = [
9
13
  { id: 'zh-CN-XiaomengNeural', name: '晓梦', gender: '女声', note: '甜' },
10
14
  { id: 'zh-CN-XiaomoNeural', name: '晓墨', gender: '女声', note: '沉稳' },
11
15
  { id: 'zh-CN-XiaoruiNeural', name: '晓睿', gender: '女声', note: '成熟' },
12
- { id: 'zh-CN-XiaoshuangNeural', name: '晓双', gender: '女声', note: '童声' },
13
16
  { id: 'zh-CN-YunxiNeural', name: '云希', gender: '男声', note: '阳光' },
14
17
  { id: 'zh-CN-YunyangNeural', name: '云扬', gender: '男声', note: '专业播报' },
15
18
  { id: 'zh-CN-YunjianNeural', name: '云健', gender: '男声', note: '浑厚' },
@@ -21,62 +24,143 @@ export const EDGE_VOICES = [
21
24
 
22
25
  export const DEFAULT_EDGE_VOICE = 'zh-CN-XiaoxiaoNeural';
23
26
 
24
- const MP3 = OUTPUT_FORMAT.AUDIO_24KHZ_48KBITRATE_MONO_MP3;
27
+ const TOKEN = '6A5AA1D4EAFF4E9FB37E23D68491D6F4';
28
+ const BASE = 'wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1';
29
+ const OUTPUT = 'audio-24khz-48kbitrate-mono-mp3';
30
+ const VOICE_LANG = 'zh-CN';
25
31
 
26
32
  function voiceOf(id) {
27
33
  return EDGE_VOICES.some((v) => v.id === id) ? id : DEFAULT_EDGE_VOICE;
28
34
  }
29
35
 
36
+ function escapeXml(text) {
37
+ return String(text)
38
+ .replace(/&/g, '&')
39
+ .replace(/</g, '&lt;')
40
+ .replace(/>/g, '&gt;')
41
+ .replace(/"/g, '&quot;')
42
+ .replace(/'/g, '&apos;');
43
+ }
44
+
45
+ function stamp() {
46
+ return new Date().toISOString();
47
+ }
48
+
49
+ function ssml(text, voice) {
50
+ return `<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='${VOICE_LANG}'>` +
51
+ `<voice name='${voice}'><prosody rate='0%' pitch='0Hz' volume='0%'>${escapeXml(text)}</prosody></voice></speak>`;
52
+ }
53
+
54
+ function configMessage() {
55
+ const body = JSON.stringify({
56
+ context: {
57
+ synthesis: {
58
+ audio: {
59
+ metadataoptions: { sentenceBoundaryEnabled: false, wordBoundaryEnabled: false },
60
+ outputFormat: OUTPUT,
61
+ },
62
+ },
63
+ },
64
+ });
65
+ return `X-Timestamp:${stamp()}\r\nContent-Type:application/json; charset=utf-8\r\nPath:speech.config\r\n\r\n${body}`;
66
+ }
67
+
68
+ function ssmlMessage(text, voice, requestId) {
69
+ return `X-RequestId:${requestId}\r\nContent-Type:application/ssml+xml\r\nX-Timestamp:${stamp()}\r\nPath:ssml\r\n\r\n${ssml(text, voice)}`;
70
+ }
71
+
30
72
  export function createEdgeTts({ log }) {
31
73
  const sessions = new Map();
32
74
 
33
75
  async function synthesize({ id, text, voice, onChunk }) {
34
76
  const body = String(text ?? '');
35
77
  if (body.trim() === '') return { ok: false, message: '没有可朗读的文本' };
36
- const tts = new MsEdgeTTS({ connectionTimeoutMs: 10_000, synthesisTimeoutMs: 120_000 });
78
+ const requestId = randomUUID();
79
+ const ticks = Math.floor(Date.now() / 1000) + 11644473600;
80
+ const rounded = ticks - (ticks % 300);
81
+ let secMsGec = '';
82
+ try {
83
+ secMsGec = await hashSecMsGecV2(`${rounded * 10000000}${TOKEN}`);
84
+ } catch (err) {
85
+ log?.(`[edge-tts] GEC 计算失败: ${err?.message ?? err}`);
86
+ }
87
+ const url = `${BASE}?TrustedClientToken=${TOKEN}&Sec-MS-GEC=${secMsGec}&Sec-MS-GEC-Version=2-143.0.3650.96&ConnectionId=${requestId}`;
88
+ let ws;
37
89
  try {
38
- await tts.setMetadata(voiceOf(voice), MP3);
90
+ ws = new WebSocket(url, {
91
+ headers: {
92
+ Origin: 'chrome-extension://jdiccldimpdaibmpdkjnbmckianbfold',
93
+ Pragma: 'no-cache',
94
+ 'Cache-Control': 'no-cache',
95
+ 'User-Agent':
96
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36 Edg/143.0.0.0',
97
+ },
98
+ });
39
99
  } catch (err) {
40
- log?.(`[edge-tts] 元数据失败: ${err?.message ?? err}`);
41
- return { ok: false, message: '微软语音服务连接失败' };
100
+ return { ok: false, message: `语音服务连接失败:${err?.message ?? err}` };
42
101
  }
102
+
43
103
  return await new Promise((resolve) => {
104
+ let settled = false;
44
105
  let seq = 0;
45
106
  let bytes = 0;
46
- let settled = false;
47
- const { audioStream } = tts.toStream(body);
48
- sessions.set(id, { close: () => audioStream.destroy() });
49
- audioStream.on('data', (data) => {
50
- if (settled) return;
51
- const chunk = Buffer.from(data);
52
- bytes += chunk.length;
53
- onChunk?.({ id, seq: seq++, data: chunk.toString('base64'), codec: 'mp3' });
54
- });
55
- audioStream.on('close', () => {
107
+ const timer = setTimeout(() => finish({ ok: false, message: '语音合成超时' }), 120_000);
108
+
109
+ function finish(result) {
56
110
  if (settled) return;
57
111
  settled = true;
112
+ clearTimeout(timer);
58
113
  sessions.delete(id);
59
- resolve(bytes > 0 ? { ok: true, bytes } : { ok: false, message: '微软语音没有返回音频' });
114
+ try {
115
+ ws.close();
116
+ } catch {
117
+ /* 已关闭 */
118
+ }
119
+ resolve(result);
120
+ }
121
+
122
+ sessions.set(id, { close: () => finish({ ok: false, message: '已取消' }) });
123
+
124
+ ws.on('open', () => {
125
+ try {
126
+ ws.send(configMessage());
127
+ ws.send(ssmlMessage(body, voiceOf(voice), requestId));
128
+ } catch (err) {
129
+ finish({ ok: false, message: `语音发送失败:${err?.message ?? err}` });
130
+ }
60
131
  });
61
- audioStream.on('error', (err) => {
62
- if (settled) return;
63
- settled = true;
64
- sessions.delete(id);
65
- log?.(`[edge-tts] 合成失败: ${err?.message ?? err}`);
66
- resolve({ ok: false, message: '微软语音合成失败' });
132
+
133
+ ws.on('message', (data, isBinary) => {
134
+ if (!isBinary) {
135
+ const textFrame = data.toString('utf8');
136
+ if (textFrame.includes('Path:turn.end')) {
137
+ finish(bytes > 0 ? { ok: true, bytes } : { ok: false, message: '语音服务没有返回音频' });
138
+ }
139
+ return;
140
+ }
141
+ const buffer = Buffer.from(data);
142
+ const headerLength = buffer.readUInt16BE(0);
143
+ const header = buffer.subarray(2, 2 + headerLength).toString('utf8');
144
+ if (!header.includes('Path:audio')) return;
145
+ const audio = buffer.subarray(2 + headerLength);
146
+ if (audio.length === 0) return;
147
+ bytes += audio.length;
148
+ onChunk?.({ id, seq: seq++, data: audio.toString('base64'), codec: 'mp3' });
149
+ });
150
+
151
+ ws.on('error', (err) => {
152
+ log?.(`[edge-tts] 连接异常: ${err?.message ?? err}`);
153
+ finish({ ok: false, message: '微软语音连接失败' });
67
154
  });
155
+
156
+ ws.on('close', () => finish({ ok: false, message: '微软语音连接中断' }));
68
157
  });
69
158
  }
70
159
 
71
160
  function stop(id) {
72
161
  const session = sessions.get(id);
73
162
  if (!session) return;
74
- sessions.delete(id);
75
- try {
76
- session.close();
77
- } catch {
78
- /* 已关闭 */
79
- }
163
+ session.close();
80
164
  }
81
165
 
82
166
  function stopAll() {
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hashSecMsGecV2 = hashSecMsGecV2;
4
+ // Sec-MS-GEC v2 is "<CS64 checksum>-<SHA-256>" of Edge's copyright line followed by the v1 input.
5
+ // Worked out from the analysis in https://github.com/rany2/edge-tts/pull/492.
6
+ const EDGE_COPYRIGHT = "Copyright (C) Microsoft Corporation. All rights reserved.";
7
+ const SWAP_FIRST_WORD = { swappedWord: 0xEF0569FB, swappedSum: 0x76F50F34, swappedProduct: 0xC3EFEA97 };
8
+ const SWAP_SECOND_WORD = { swappedWord: 0xC31713DB, swappedSum: 0x1881CE3C, swappedProduct: 0x35BD1EC9 };
9
+ const MIX_FIRST_WORD = [0xCF98B111, 0x87085B9F, 0x12CEB96D, 0x257E1D83];
10
+ const MIX_SECOND_WORD = [0xA27416F5, 0xD38396FF, 0x7C932B89, 0xBFA49F69];
11
+ async function hashSecMsGecV2(ticksAndToken) {
12
+ const message = new TextEncoder().encode(EDGE_COPYRIGHT + ticksAndToken);
13
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", message));
14
+ return `${toUpperHex(cs64(message, digest))}-${toUpperHex(digest)}`;
15
+ }
16
+ function cs64(message, digest) {
17
+ const digestView = new DataView(digest.buffer, digest.byteOffset, digest.byteLength);
18
+ const firstKey = (digestView.getUint32(0, true) | 1) >>> 0;
19
+ const secondKey = (digestView.getUint32(4, true) | 1) >>> 0;
20
+ // The message is read as little-endian 32-bit word pairs, zero-padded to a whole pair.
21
+ const padded = new Uint8Array(Math.ceil(message.length / 8) * 8);
22
+ padded.set(message);
23
+ const words = new DataView(padded.buffer);
24
+ let swapSum = 0;
25
+ let lastSwap = 0;
26
+ let mix = 0;
27
+ let mixSum = 0;
28
+ for (let offset = 0; offset < padded.length; offset += 8) {
29
+ const firstWord = words.getUint32(offset, true);
30
+ const secondWord = words.getUint32(offset + 4, true);
31
+ const firstSwap = swapTerm(firstWord, firstKey, SWAP_FIRST_WORD);
32
+ lastSwap = swapTerm(secondWord, secondKey, SWAP_SECOND_WORD);
33
+ swapSum = (swapSum + firstSwap + lastSwap) >>> 0;
34
+ mix = swapAndMultiply(Math.imul(mix + firstWord, firstKey), MIX_FIRST_WORD);
35
+ mixSum = (mixSum + mix) >>> 0;
36
+ mix = swapAndMultiply(Math.imul(mix + secondWord, secondKey), MIX_SECOND_WORD);
37
+ mixSum = (mixSum + mix) >>> 0;
38
+ }
39
+ const checksum = new Uint8Array(8);
40
+ const checksumView = new DataView(checksum.buffer);
41
+ checksumView.setUint32(0, lastSwap ^ mix, true);
42
+ checksumView.setUint32(4, swapSum ^ mixSum, true);
43
+ return checksum;
44
+ }
45
+ function swapTerm(word, key, multipliers) {
46
+ const sum = Math.imul(word, key) + Math.imul(swapHalves(word), multipliers.swappedWord);
47
+ const product = Math.imul(swapHalves(sum), multipliers.swappedSum) >>> 0;
48
+ return (Math.imul(swapHalves(product), multipliers.swappedProduct) + product) >>> 0;
49
+ }
50
+ function swapAndMultiply(value, multipliers) {
51
+ for (const multiplier of multipliers) {
52
+ value = Math.imul(swapHalves(value), multiplier) >>> 0;
53
+ }
54
+ return value;
55
+ }
56
+ function swapHalves(value) {
57
+ return ((value << 16) | (value >>> 16)) >>> 0;
58
+ }
59
+ function toUpperHex(bytes) {
60
+ return Array.from(bytes, b => b.toString(16).padStart(2, "0")).join("").toUpperCase();
61
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jbc-dssi",
3
- "version": "1.1.155",
3
+ "version": "1.1.158",
4
4
  "type": "module",
5
5
  "description": "鲸聊 - 不只是手机遥控操作电脑,而是将电脑级的Agent能力装进手机",
6
6
  "keywords": [
@@ -52,7 +52,6 @@
52
52
  "prepack": "node scripts/build-vendor.mjs"
53
53
  },
54
54
  "dependencies": {
55
- "msedge-tts": "^2.1.1",
56
55
  "ws": "^8.18.0"
57
56
  }
58
57
  }