dsh-watch-together 0.2.5 → 0.2.7

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.
@@ -38,19 +38,49 @@ export async function startChatServer({
38
38
 
39
39
  // 扩展从**网页的源**发请求,属于跨域;而且是从公网页面访问本地地址,
40
40
  // Chrome 的 Private Network Access 还要求预检里看到 allow-private-network。
41
- // 我们只暴露"上报位置"和"读位置",没有敏感信息,所以直接放开。
42
- const cors = {
43
- 'access-control-allow-origin': '*',
44
- 'access-control-allow-methods': 'GET, POST, OPTIONS',
45
- 'access-control-allow-headers': 'content-type',
46
- 'access-control-allow-private-network': 'true',
47
- 'cache-control': 'no-store',
48
- };
41
+ //
42
+ // **不能直接放开成 `*`**:否则用户随便打开一个网页,它就能向本机 9377 写假台词、
43
+ // 伪造播放位置。只放行扩展来源和同端口的本机页面;没有 Origin 的请求(CLI、Python
44
+ // 悬浮窗、curl)保持可用 —— 浏览器发起的跨域请求一定会带 Origin。
45
+ const EXTENSION_SCHEMES = new Set(['chrome-extension:', 'moz-extension:', 'safari-web-extension:']);
46
+ function isAllowedOrigin(origin, port) {
47
+ if (!origin) return true;
48
+ try {
49
+ const u = new URL(origin);
50
+ if (EXTENSION_SCHEMES.has(u.protocol)) return true;
51
+ if (u.protocol !== 'http:') return false;
52
+ const host = u.hostname;
53
+ if (host !== '127.0.0.1' && host !== 'localhost' && host !== '[::1]') return false;
54
+ const p = Number(u.port || 80);
55
+ return Number.isInteger(p) && p === Number(port);
56
+ } catch {
57
+ return false;
58
+ }
59
+ }
60
+ function corsFor(origin) {
61
+ return {
62
+ 'access-control-allow-origin': origin || '*',
63
+ 'access-control-allow-methods': 'GET, POST, OPTIONS',
64
+ 'access-control-allow-headers': 'content-type',
65
+ 'access-control-allow-private-network': 'true',
66
+ 'cache-control': 'no-store',
67
+ };
68
+ }
49
69
 
50
70
  const server = createServer(async (req, res) => {
51
71
  let u;
52
72
  try { u = new URL(req.url, 'http://127.0.0.1'); } catch { res.writeHead(400); res.end(); return; }
53
73
 
74
+ const port = server.address()?.port ?? listenPort;
75
+ const origin = typeof req.headers.origin === 'string' && req.headers.origin
76
+ ? req.headers.origin : null;
77
+ if (!isAllowedOrigin(origin, port)) {
78
+ res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' });
79
+ res.end('origin not allowed');
80
+ return;
81
+ }
82
+ const cors = corsFor(origin);
83
+
54
84
  // 扩展直接 fetch(不经过 service worker)时会有这一趟预检
55
85
  if (req.method === 'OPTIONS') {
56
86
  res.writeHead(204, cors);
@@ -107,8 +137,16 @@ export async function startChatServer({
107
137
  if (u.pathname === '/api/messages') {
108
138
  const since = Math.max(0, Number(u.searchParams.get('since')) || 0);
109
139
  const all = readChat(env);
110
- res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
111
- res.end(JSON.stringify({ total: all.length, msgs: all.slice(since) }));
140
+ // 页面按"已读条数"轮询。chat.jsonl 被清空/重写后文件会比 since 短,
141
+ // 这时 slice(since) 永远是空的 —— 页面从此再也看不到新消息。让页面知道
142
+ // 该重置游标,而不是让它永远卡在旧条数上。
143
+ const reset = since > all.length;
144
+ res.writeHead(200, { ...cors, 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
145
+ res.end(JSON.stringify({
146
+ total: all.length,
147
+ msgs: reset ? all : all.slice(since),
148
+ ...(reset ? { reset: true } : {}),
149
+ }));
112
150
  return;
113
151
  }
114
152
  if (u.pathname === '/api/say' && req.method === 'POST') {
@@ -128,7 +166,7 @@ export async function startChatServer({
128
166
  } catch { /* 坏请求就算了 */ }
129
167
  // ok:false 让页面能把话回填进输入框 —— 之前一律 ok:true,
130
168
  // 服务端没写进去用户也不知道,字就丢了
131
- res.writeHead(200, { 'content-type': 'application/json' });
169
+ res.writeHead(200, { ...cors, 'content-type': 'application/json' });
132
170
  res.end(JSON.stringify({ ok }));
133
171
  });
134
172
  return;
package/src/chat-view.js CHANGED
@@ -56,6 +56,9 @@ input:focus{border-color:#4a7ab5}
56
56
  var n=0;
57
57
  function poll(){
58
58
  fetch(BASE+"/api/messages?since="+n+"&t="+Date.now()).then(function(r){return r.json();}).then(function(j){
59
+ // chat.jsonl 被清空/重写过:游标比文件长,服务端会回 reset。清屏重放,
60
+ // 否则页面会一直用旧条数 slice,新消息永远不出现。
61
+ if(j.reset){log.innerHTML="";n=0;}
59
62
  for(var k=0;k<j.msgs.length;k++)add(j.msgs[k]);
60
63
  n=j.total;setTimeout(poll,600);
61
64
  }).catch(function(){setTimeout(poll,1500);});
package/src/index.js CHANGED
@@ -102,10 +102,18 @@ async function registerAll(ctx) {
102
102
  // 声音适配器(可选):只通过 tts 接口挂,不 import voice.js。
103
103
  // 这里也保留启动时挂载,这样第一次只调 `say`(还没开窗)也有声音。
104
104
  try {
105
- const v = await getTtsPort().attachConfigured?.({ log: (m) => ctx?.logger?.info?.(m) });
105
+ const tts = getTtsPort();
106
+ const v = await tts.attachConfigured?.({ log: (m) => ctx?.logger?.info?.(m) });
106
107
  if (v && !v.ok && v.reason !== 'not-configured') {
107
108
  ctx?.logger?.warn?.(`[dsh-watch-together] voice adapter not loaded: ${v.reason}`);
108
109
  }
110
+ // 适配器订阅了 speech bus;插件卸载必须退订,否则 speechSubscribers()
111
+ // 会一直 > 0,重载后循环误以为"有人会念",模型就再也不会被叫醒。
112
+ if (v?.ok && typeof tts.detachConfigured === 'function') {
113
+ disposers.push(() => {
114
+ try { void tts.detachConfigured(); } catch { /* 卸载失败不能影响其他 disposer */ }
115
+ });
116
+ }
109
117
  } catch (e) {
110
118
  ctx?.logger?.warn?.(`[dsh-watch-together] voice adapter crashed: ${e?.message ?? e}`);
111
119
  }
@@ -118,6 +118,8 @@ export function readVoiceSettings(env = process.env) {
118
118
  exists: raw.exists,
119
119
  error: raw.error,
120
120
  adapter: typeof raw.data.adapter === 'string' ? raw.data.adapter : '',
121
+ envOverrides: ['DSH_VOICE_ADAPTER']
122
+ .filter((k) => env[k] !== undefined && env[k] !== ''),
121
123
  };
122
124
  }
123
125
 
@@ -115,11 +115,12 @@ function floatingWindow() {
115
115
 
116
116
  function voice(env) {
117
117
  const cfg = readVoiceSettings(env);
118
- if (!cfg.adapter) return { ok: false, detail: '未配置(可选;只影响念台词)' };
119
- if (/^[a-zA-Z]:[\\/]|^\\\\|^\.{1,2}[\\/]|^\//.test(cfg.adapter)) {
120
- return { ok: existsSync(cfg.adapter), detail: existsSync(cfg.adapter) ? cfg.adapter : '文件不存在:' + cfg.adapter };
118
+ const adapter = String(env.DSH_VOICE_ADAPTER || '').trim() || cfg.adapter;
119
+ if (!adapter) return { ok: false, detail: '未配置(可选;只影响念台词)' };
120
+ if (/^[a-zA-Z]:[\\/]|^\\\\|^\.{1,2}[\\/]|^\//.test(adapter)) {
121
+ return { ok: existsSync(adapter), detail: existsSync(adapter) ? adapter : '文件不存在:' + adapter };
121
122
  }
122
- return { ok: true, detail: cfg.adapter + '(包名,挂载时才能校验)' };
123
+ return { ok: true, detail: adapter + '(包名,挂载时才能校验)' };
123
124
  }
124
125
 
125
126
  /** @returns {Promise<Array<{id:string,label:string,ok:boolean,detail:string}>>} */
@@ -16,6 +16,7 @@ export const TTS_INTERFACE_VERSION = 1;
16
16
  * speechSubscribers: Function,
17
17
  * lastSpeech: Function,
18
18
  * attachConfiguredVoice?: Function,
19
+ * detachAdapters?: Function,
19
20
  * attachedAdapters?: Function,
20
21
  * configuredVoiceAdapter?: Function,
21
22
  * }} bus
@@ -23,7 +24,7 @@ export const TTS_INTERFACE_VERSION = 1;
23
24
  export function createTtsInterface(bus = {}) {
24
25
  const {
25
26
  onSpeech, emitSpeech, emitSpoken, speechSubscribers, lastSpeech,
26
- attachConfiguredVoice, attachedAdapters, configuredVoiceAdapter,
27
+ attachConfiguredVoice, detachAdapters, attachedAdapters, configuredVoiceAdapter,
27
28
  } = bus;
28
29
  for (const [name, fn] of Object.entries({ onSpeech, emitSpeech, speechSubscribers, lastSpeech })) {
29
30
  if (typeof fn !== 'function') throw new TypeError(`tts: ${name}() is required`);
@@ -53,6 +54,7 @@ export function createTtsInterface(bus = {}) {
53
54
  return lastSpeech();
54
55
  },
55
56
  attachConfigured: typeof attachConfiguredVoice === 'function' ? attachConfiguredVoice : null,
57
+ detachConfigured: typeof detachAdapters === 'function' ? detachAdapters : null,
56
58
  attached: typeof attachedAdapters === 'function' ? attachedAdapters : () => [],
57
59
  configured: typeof configuredVoiceAdapter === 'function' ? configuredVoiceAdapter : () => null,
58
60
  });