dsh-plugin-starpost 0.4.1 → 0.5.0
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/CHANGELOG.md +6 -2
- package/LICENSE +21 -21
- package/README.md +2 -0
- package/cordis.patch.yml +3 -3
- package/docs/voice.md +81 -81
- package/lib/ENV_PROMPT.md +9 -9
- package/lib/core.mjs +35 -1
- package/package.json +3 -3
- package/src/account.mjs +47 -47
- package/src/index.mjs +185 -185
- package/src/local.mjs +100 -100
- package/src/panel.mjs +192 -192
- package/src/settings.mjs +22 -22
- package/web/app.mjs +168 -168
- package/web/client.js +16 -16
- package/web/fields.mjs +49 -49
- package/web/index.html +6 -6
- package/web/style.css +3 -3
package/src/panel.mjs
CHANGED
|
@@ -1,192 +1,192 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto';
|
|
2
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
-
import { isAbsolute, join } from 'node:path';
|
|
4
|
-
import { clientVersions, loadSettings, options, pinServer, saveSettings } from './local.mjs';
|
|
5
|
-
import { settingsNamespace } from './settings.mjs';
|
|
6
|
-
import { sections, check, readKey, setKey } from '../web/fields.mjs';
|
|
7
|
-
|
|
8
|
-
export const panelPath = '/starpost/settings';
|
|
9
|
-
const assets = new Map([
|
|
10
|
-
['', ['index.html','text/html']], ['index.html',['index.html','text/html']],
|
|
11
|
-
['app.mjs',['app.mjs','text/javascript']], ['fields.mjs',['fields.mjs','text/javascript']], ['style.css',['style.css','text/css']]
|
|
12
|
-
]);
|
|
13
|
-
const error = (message, status = 400) => Object.assign(new Error(message), {status});
|
|
14
|
-
function project(cfg) {
|
|
15
|
-
const flat = {...cfg, ...cfg.notifications};
|
|
16
|
-
return Object.fromEntries(Object.values(sections).flatMap(section => section.fields.map(f => [f.key,readKey(flat,f.key)])));
|
|
17
|
-
}
|
|
18
|
-
const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
19
|
-
function loopback(host) { return ['127.0.0.1','localhost','[::1]'].includes(host); }
|
|
20
|
-
function serviceOrigin(value) {
|
|
21
|
-
let url;
|
|
22
|
-
try { url=new URL(value); } catch { throw error('服务地址无效'); }
|
|
23
|
-
if (!(url.protocol==='https:' || url.protocol==='http:' && loopback(url.hostname)) ||
|
|
24
|
-
url.username || url.password || url.search || url.hash || url.pathname!=='/') throw error('请输入 HTTPS 服务根地址,本机测试可使用 HTTP 回环地址');
|
|
25
|
-
return url.origin;
|
|
26
|
-
}
|
|
27
|
-
function hasPrivateUrlParts(url) {
|
|
28
|
-
return Boolean(url.username || url.password || url.hash || [...url.searchParams.keys()].some(key=>/token|secret|password|signature|api.?key|authorization|credential|^key$|^sig$/i.test(key)));
|
|
29
|
-
}
|
|
30
|
-
function forDisplay(values) {
|
|
31
|
-
const clean={...values}, masked=[];
|
|
32
|
-
for (const key of Object.keys(clean).filter(key=>key.endsWith('Url') && clean[key])) {
|
|
33
|
-
try { if (!hasPrivateUrlParts(new URL(clean[key]))) continue; } catch {}
|
|
34
|
-
masked.push(key); clean[key]='';
|
|
35
|
-
}
|
|
36
|
-
return {values:clean, masked};
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export function makePanel({dir, sessions, runtime, nativeSettings, withWorld, entry = {}}) {
|
|
40
|
-
async function config() {
|
|
41
|
-
const file = loadSettings(dir), service = nativeSettings();
|
|
42
|
-
const descriptor = service && (await service.describe()).find(d => d.ns === settingsNamespace);
|
|
43
|
-
const resolved=options({...file,...entry,...descriptor?.user},dir);
|
|
44
|
-
const saved=project(resolved);
|
|
45
|
-
return {file, descriptor, service, saved, resolved, revision:digest([file, saved, descriptor?.revision ?? null])};
|
|
46
|
-
}
|
|
47
|
-
async function account(world) {
|
|
48
|
-
const invoke = world.webUi().invoke;
|
|
49
|
-
const [identity,hub] = await Promise.all([invoke('viewer','status',[]), invoke('viewer','hubStatus',[])]);
|
|
50
|
-
const pending = hub.pending;
|
|
51
|
-
return {botId:identity.botId, registered:identity.registered, mode:hub.mode, expired:Boolean(hub.expired),
|
|
52
|
-
pending:pending ? {shortCode:pending.shortCode,verificationUri:pending.verificationUri,expiresAt:pending.expiresAt} : null};
|
|
53
|
-
}
|
|
54
|
-
async function state() {
|
|
55
|
-
const cfg = await config(), running = runtime(), choices = await sessions();
|
|
56
|
-
const sessionId = cfg.file.sessionId || '';
|
|
57
|
-
if (sessionId && !choices.some(s=>s.id===sessionId)) choices.push({id:sessionId,title:'已保存的会话'});
|
|
58
|
-
const active = project(running.cfg);
|
|
59
|
-
const identity=await withWorld(account);
|
|
60
|
-
const display=forDisplay(cfg.saved);
|
|
61
|
-
const connection={serverUrl:cfg.resolved.serverUrl,hubUrl:serviceOrigin(cfg.resolved.hubUrl),
|
|
62
|
-
locked:identity.registered || Boolean(identity.pending) || existsSync(join(dir,'server-origin'))};
|
|
63
|
-
return { ...clientVersions, sessions:choices, sessionId, runtimeSession:running.sessionId || '',
|
|
64
|
-
ready:running.ready, runtimeError:running.error, account:identity, connection,
|
|
65
|
-
saved:display.values, masked:display.masked, active:forDisplay(active).values, revision:cfg.revision, native:Boolean(cfg.descriptor),
|
|
66
|
-
pendingRestart:sessionId !== (running.sessionId || '') || Object.keys(active).some(key=>active[key] !== cfg.saved[key]) ||
|
|
67
|
-
running.cfg.serverUrl!==cfg.resolved.serverUrl || running.cfg.hubUrl!==cfg.resolved.hubUrl };
|
|
68
|
-
}
|
|
69
|
-
async function perform(action, body) {
|
|
70
|
-
if (action==='state') return state();
|
|
71
|
-
if (action==='save') {
|
|
72
|
-
// Share the runtime/CLI data-directory lock for the full read–validate–write.
|
|
73
|
-
return withWorld(async world => {
|
|
74
|
-
const cfg = await config();
|
|
75
|
-
if (body.revision !== cfg.revision) throw error('设置已在其他页面修改,请重新载入后再保存。',409);
|
|
76
|
-
if (body.section==='account') {
|
|
77
|
-
const list = await sessions();
|
|
78
|
-
if (!list.some(s=>s.id===body.sessionId) && (!cfg.file.sessionId || cfg.file.sessionId !== body.sessionId)) throw error('请选择当前 DSH 中的会话');
|
|
79
|
-
saveSettings(dir,{...cfg.file,sessionId:body.sessionId});
|
|
80
|
-
return {};
|
|
81
|
-
}
|
|
82
|
-
if (body.section==='connection') {
|
|
83
|
-
const id=await account(world);
|
|
84
|
-
if (id.registered || id.pending || existsSync(join(dir,'server-origin'))) throw error('该数据目录已绑定服务');
|
|
85
|
-
saveSettings(dir,{...cfg.file,serverUrl:serviceOrigin(body.serverUrl),hubUrl:serviceOrigin(body.hubUrl)},{allowUnbound:true});
|
|
86
|
-
return {};
|
|
87
|
-
}
|
|
88
|
-
if (!Object.hasOwn(sections,body.section) || !body.values || typeof body.values!=='object' || Array.isArray(body.values)) throw error('设置栏目无效');
|
|
89
|
-
const fields=sections[body.section].fields, changes=Object.entries(body.values);
|
|
90
|
-
if (!changes.length) return {};
|
|
91
|
-
for (const [key,value] of changes) {
|
|
92
|
-
const field=fields.find(f=>f.key===key);
|
|
93
|
-
if (!field || !check(field,value)) throw error((field?.label ?? '配置项')+' 的值无效');
|
|
94
|
-
if (key.endsWith('Url') && value) {
|
|
95
|
-
let url;
|
|
96
|
-
try { url = new URL(value); } catch { throw error(field.label+' 地址无效'); }
|
|
97
|
-
if (!(url.protocol==='https:' || url.protocol==='http:' && loopback(url.hostname)) || hasPrivateUrlParts(url)) throw error(field.label+' 请使用 HTTPS 或本机 HTTP 地址,密钥请通过环境变量提供');
|
|
98
|
-
}
|
|
99
|
-
if (['speech.ffmpegPath','speech.silkPath'].includes(key) && value && !isAbsolute(value)) throw error(field.label+' 请填写绝对路径');
|
|
100
|
-
setKey(cfg.file,key,value);
|
|
101
|
-
}
|
|
102
|
-
options(cfg.file,dir);
|
|
103
|
-
if (body.section==='notify' && cfg.descriptor) {
|
|
104
|
-
await cfg.service.update(settingsNamespace,body.values,cfg.descriptor.revision);
|
|
105
|
-
} else {
|
|
106
|
-
if (body.section==='notify' && changes.some(([key])=>Object.hasOwn(entry,key))) throw error('该项由 DSH 启动配置覆盖,请在宿主设置中修改。');
|
|
107
|
-
saveSettings(dir,cfg.file,{allowUnbound:true});
|
|
108
|
-
}
|
|
109
|
-
return {};
|
|
110
|
-
});
|
|
111
|
-
}
|
|
112
|
-
if (!['profile','hubBegin','hubFinish','hubCancel','register','login'].includes(action)) throw error('接口不存在',404);
|
|
113
|
-
return withWorld(async world => {
|
|
114
|
-
const invoke=world.webUi().invoke, before=await account(world);
|
|
115
|
-
if (action==='profile') {
|
|
116
|
-
if (!before.botId) throw error('请先登录星邮');
|
|
117
|
-
const result=await invoke('viewer','profileRead',[before.botId,'basic']);
|
|
118
|
-
return {nickname:String(result.nickname ?? '').slice(0,120)};
|
|
119
|
-
}
|
|
120
|
-
if (action==='hubCancel') { await invoke('viewer',action,[]); return {}; }
|
|
121
|
-
const settings=loadSettings(dir);
|
|
122
|
-
if (!settings.sessionId) throw error('请先选择并保存 DSH 会话');
|
|
123
|
-
if (action==='hubFinish') {
|
|
124
|
-
const result=await invoke('viewer',action,[]);
|
|
125
|
-
return {status:result.status};
|
|
126
|
-
}
|
|
127
|
-
pinServer(dir,settings);
|
|
128
|
-
if (action==='hubBegin') {
|
|
129
|
-
if (before.pending && before.pending.expiresAt>Date.now()) throw error('已有配对等待确认,可继续或取消。');
|
|
130
|
-
if (before.pending) await invoke('viewer','hubCancel',[]);
|
|
131
|
-
await invoke('viewer',action,['星邮 DSH · '+settings.sessionId.slice(0,50)]);
|
|
132
|
-
} else {
|
|
133
|
-
if (before.registered) throw error('本机已有星邮账号');
|
|
134
|
-
if (action==='register') {
|
|
135
|
-
if (body.confirm!==true) throw error('请确认注册新账号');
|
|
136
|
-
await invoke('viewer','register',[]);
|
|
137
|
-
} else {
|
|
138
|
-
const data=body.credential;
|
|
139
|
-
if (!data || typeof data.botId!=='string' || typeof data.token!=='string') throw error('请选择包含 botId 和 token 的星邮凭据文件');
|
|
140
|
-
await invoke('viewer','login',[data.botId,JSON.stringify({version:data.version,botId:data.botId,token:data.token})]);
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
return {};
|
|
144
|
-
});
|
|
145
|
-
}
|
|
146
|
-
let queue=Promise.resolve();
|
|
147
|
-
return async (action,body={}) => {
|
|
148
|
-
const task=queue.then(()=>perform(action,body));
|
|
149
|
-
queue=task.catch(()=>{});
|
|
150
|
-
return task;
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
export function panelHandler(run) {
|
|
155
|
-
return async (req,res) => {
|
|
156
|
-
const json=(code,obj)=>{res.writeHead(code,{'content-type':'application/json; charset=utf-8'}); res.end(JSON.stringify(obj));};
|
|
157
|
-
res.setHeader('Cache-Control','no-store');
|
|
158
|
-
res.setHeader('X-Content-Type-Options','nosniff');
|
|
159
|
-
res.setHeader('Referrer-Policy','no-referrer');
|
|
160
|
-
res.setHeader('Content-Security-Policy',"default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; frame-ancestors 'self'; base-uri 'none'; form-action 'none'");
|
|
161
|
-
try {
|
|
162
|
-
if (!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(req.socket.remoteAddress) ||
|
|
163
|
-
!/^(localhost|127\.0\.0\.1|\[::1\])(:[0-9]{1,5})?$/i.test(req.headers.host || '') ||
|
|
164
|
-
['forwarded','x-forwarded-for','x-forwarded-host'].some(key=>req.headers[key])) throw error('请在运行 DSH 的本机打开设置',403);
|
|
165
|
-
const origin=(req.socket.encrypted?'https://':'http://')+req.headers.host;
|
|
166
|
-
const pathname=new URL(req.url,origin).pathname;
|
|
167
|
-
if (pathname===panelPath) {res.writeHead(302,{location:panelPath+'/'});return res.end();}
|
|
168
|
-
if (!pathname.startsWith(panelPath+'/')) throw error('页面不存在',404);
|
|
169
|
-
const name=pathname.slice(panelPath.length+1);
|
|
170
|
-
if (req.method==='GET' && assets.has(name)) {
|
|
171
|
-
const [file,type]=assets.get(name);
|
|
172
|
-
const bytes=readFileSync(new URL('../web/'+file,import.meta.url));
|
|
173
|
-
res.writeHead(200,{'content-type':type+'; charset=utf-8'});return res.end(bytes);
|
|
174
|
-
}
|
|
175
|
-
if (!/^api\/[a-zA-Z]+$/.test(name)) throw error('页面不存在',404);
|
|
176
|
-
const action=name.slice(4);
|
|
177
|
-
if (req.headers['x-starpost-panel']!=='1' || (req.headers.origin && req.headers.origin!==origin)) throw error('请求来源无效',403);
|
|
178
|
-
if (action==='state' && req.method==='GET') return json(200,await run(action));
|
|
179
|
-
if (req.method!=='POST' || action==='state') throw error('请求方法无效',405);
|
|
180
|
-
if (req.headers.origin!==origin || !/^application\/json(?:;|$)/i.test(req.headers['content-type'] || '')) throw error('请求来源或格式无效',403);
|
|
181
|
-
let size=0;const chunks=[];
|
|
182
|
-
for await (const chunk of req) { size+=chunk.length;if(size>16384)throw error('请求过大',413);chunks.push(chunk); }
|
|
183
|
-
let body;
|
|
184
|
-
try {body=JSON.parse(Buffer.concat(chunks).toString('utf8'));} catch {throw error('无效的 JSON');}
|
|
185
|
-
if (!body || typeof body!=='object' || Array.isArray(body)) throw error('请求格式无效');
|
|
186
|
-
return json(200,await run(action,body));
|
|
187
|
-
} catch (cause) {
|
|
188
|
-
const msg=String(cause.message || '操作失败').replace(/\b[A-Za-z0-9_+./=-]{48,}\b/g,'[已隐藏]').slice(0,350);
|
|
189
|
-
return json(Number.isInteger(cause.status) && cause.status>=400 && cause.status<=599 ? cause.status : 400,{error:msg});
|
|
190
|
-
}
|
|
191
|
-
};
|
|
192
|
-
}
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { isAbsolute, join } from 'node:path';
|
|
4
|
+
import { clientVersions, loadSettings, options, pinServer, saveSettings } from './local.mjs';
|
|
5
|
+
import { settingsNamespace } from './settings.mjs';
|
|
6
|
+
import { sections, check, readKey, setKey } from '../web/fields.mjs';
|
|
7
|
+
|
|
8
|
+
export const panelPath = '/starpost/settings';
|
|
9
|
+
const assets = new Map([
|
|
10
|
+
['', ['index.html','text/html']], ['index.html',['index.html','text/html']],
|
|
11
|
+
['app.mjs',['app.mjs','text/javascript']], ['fields.mjs',['fields.mjs','text/javascript']], ['style.css',['style.css','text/css']]
|
|
12
|
+
]);
|
|
13
|
+
const error = (message, status = 400) => Object.assign(new Error(message), {status});
|
|
14
|
+
function project(cfg) {
|
|
15
|
+
const flat = {...cfg, ...cfg.notifications};
|
|
16
|
+
return Object.fromEntries(Object.values(sections).flatMap(section => section.fields.map(f => [f.key,readKey(flat,f.key)])));
|
|
17
|
+
}
|
|
18
|
+
const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
19
|
+
function loopback(host) { return ['127.0.0.1','localhost','[::1]'].includes(host); }
|
|
20
|
+
function serviceOrigin(value) {
|
|
21
|
+
let url;
|
|
22
|
+
try { url=new URL(value); } catch { throw error('服务地址无效'); }
|
|
23
|
+
if (!(url.protocol==='https:' || url.protocol==='http:' && loopback(url.hostname)) ||
|
|
24
|
+
url.username || url.password || url.search || url.hash || url.pathname!=='/') throw error('请输入 HTTPS 服务根地址,本机测试可使用 HTTP 回环地址');
|
|
25
|
+
return url.origin;
|
|
26
|
+
}
|
|
27
|
+
function hasPrivateUrlParts(url) {
|
|
28
|
+
return Boolean(url.username || url.password || url.hash || [...url.searchParams.keys()].some(key=>/token|secret|password|signature|api.?key|authorization|credential|^key$|^sig$/i.test(key)));
|
|
29
|
+
}
|
|
30
|
+
function forDisplay(values) {
|
|
31
|
+
const clean={...values}, masked=[];
|
|
32
|
+
for (const key of Object.keys(clean).filter(key=>key.endsWith('Url') && clean[key])) {
|
|
33
|
+
try { if (!hasPrivateUrlParts(new URL(clean[key]))) continue; } catch {}
|
|
34
|
+
masked.push(key); clean[key]='';
|
|
35
|
+
}
|
|
36
|
+
return {values:clean, masked};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function makePanel({dir, sessions, runtime, nativeSettings, withWorld, entry = {}}) {
|
|
40
|
+
async function config() {
|
|
41
|
+
const file = loadSettings(dir), service = nativeSettings();
|
|
42
|
+
const descriptor = service && (await service.describe()).find(d => d.ns === settingsNamespace);
|
|
43
|
+
const resolved=options({...file,...entry,...descriptor?.user},dir);
|
|
44
|
+
const saved=project(resolved);
|
|
45
|
+
return {file, descriptor, service, saved, resolved, revision:digest([file, saved, descriptor?.revision ?? null])};
|
|
46
|
+
}
|
|
47
|
+
async function account(world) {
|
|
48
|
+
const invoke = world.webUi().invoke;
|
|
49
|
+
const [identity,hub] = await Promise.all([invoke('viewer','status',[]), invoke('viewer','hubStatus',[])]);
|
|
50
|
+
const pending = hub.pending;
|
|
51
|
+
return {botId:identity.botId, registered:identity.registered, mode:hub.mode, expired:Boolean(hub.expired),
|
|
52
|
+
pending:pending ? {shortCode:pending.shortCode,verificationUri:pending.verificationUri,expiresAt:pending.expiresAt} : null};
|
|
53
|
+
}
|
|
54
|
+
async function state() {
|
|
55
|
+
const cfg = await config(), running = runtime(), choices = await sessions();
|
|
56
|
+
const sessionId = cfg.file.sessionId || '';
|
|
57
|
+
if (sessionId && !choices.some(s=>s.id===sessionId)) choices.push({id:sessionId,title:'已保存的会话'});
|
|
58
|
+
const active = project(running.cfg);
|
|
59
|
+
const identity=await withWorld(account);
|
|
60
|
+
const display=forDisplay(cfg.saved);
|
|
61
|
+
const connection={serverUrl:cfg.resolved.serverUrl,hubUrl:serviceOrigin(cfg.resolved.hubUrl),
|
|
62
|
+
locked:identity.registered || Boolean(identity.pending) || existsSync(join(dir,'server-origin'))};
|
|
63
|
+
return { ...clientVersions, sessions:choices, sessionId, runtimeSession:running.sessionId || '',
|
|
64
|
+
ready:running.ready, runtimeError:running.error, account:identity, connection,
|
|
65
|
+
saved:display.values, masked:display.masked, active:forDisplay(active).values, revision:cfg.revision, native:Boolean(cfg.descriptor),
|
|
66
|
+
pendingRestart:sessionId !== (running.sessionId || '') || Object.keys(active).some(key=>active[key] !== cfg.saved[key]) ||
|
|
67
|
+
running.cfg.serverUrl!==cfg.resolved.serverUrl || running.cfg.hubUrl!==cfg.resolved.hubUrl };
|
|
68
|
+
}
|
|
69
|
+
async function perform(action, body) {
|
|
70
|
+
if (action==='state') return state();
|
|
71
|
+
if (action==='save') {
|
|
72
|
+
// Share the runtime/CLI data-directory lock for the full read–validate–write.
|
|
73
|
+
return withWorld(async world => {
|
|
74
|
+
const cfg = await config();
|
|
75
|
+
if (body.revision !== cfg.revision) throw error('设置已在其他页面修改,请重新载入后再保存。',409);
|
|
76
|
+
if (body.section==='account') {
|
|
77
|
+
const list = await sessions();
|
|
78
|
+
if (!list.some(s=>s.id===body.sessionId) && (!cfg.file.sessionId || cfg.file.sessionId !== body.sessionId)) throw error('请选择当前 DSH 中的会话');
|
|
79
|
+
saveSettings(dir,{...cfg.file,sessionId:body.sessionId});
|
|
80
|
+
return {};
|
|
81
|
+
}
|
|
82
|
+
if (body.section==='connection') {
|
|
83
|
+
const id=await account(world);
|
|
84
|
+
if (id.registered || id.pending || existsSync(join(dir,'server-origin'))) throw error('该数据目录已绑定服务');
|
|
85
|
+
saveSettings(dir,{...cfg.file,serverUrl:serviceOrigin(body.serverUrl),hubUrl:serviceOrigin(body.hubUrl)},{allowUnbound:true});
|
|
86
|
+
return {};
|
|
87
|
+
}
|
|
88
|
+
if (!Object.hasOwn(sections,body.section) || !body.values || typeof body.values!=='object' || Array.isArray(body.values)) throw error('设置栏目无效');
|
|
89
|
+
const fields=sections[body.section].fields, changes=Object.entries(body.values);
|
|
90
|
+
if (!changes.length) return {};
|
|
91
|
+
for (const [key,value] of changes) {
|
|
92
|
+
const field=fields.find(f=>f.key===key);
|
|
93
|
+
if (!field || !check(field,value)) throw error((field?.label ?? '配置项')+' 的值无效');
|
|
94
|
+
if (key.endsWith('Url') && value) {
|
|
95
|
+
let url;
|
|
96
|
+
try { url = new URL(value); } catch { throw error(field.label+' 地址无效'); }
|
|
97
|
+
if (!(url.protocol==='https:' || url.protocol==='http:' && loopback(url.hostname)) || hasPrivateUrlParts(url)) throw error(field.label+' 请使用 HTTPS 或本机 HTTP 地址,密钥请通过环境变量提供');
|
|
98
|
+
}
|
|
99
|
+
if (['speech.ffmpegPath','speech.silkPath'].includes(key) && value && !isAbsolute(value)) throw error(field.label+' 请填写绝对路径');
|
|
100
|
+
setKey(cfg.file,key,value);
|
|
101
|
+
}
|
|
102
|
+
options(cfg.file,dir);
|
|
103
|
+
if (body.section==='notify' && cfg.descriptor) {
|
|
104
|
+
await cfg.service.update(settingsNamespace,body.values,cfg.descriptor.revision);
|
|
105
|
+
} else {
|
|
106
|
+
if (body.section==='notify' && changes.some(([key])=>Object.hasOwn(entry,key))) throw error('该项由 DSH 启动配置覆盖,请在宿主设置中修改。');
|
|
107
|
+
saveSettings(dir,cfg.file,{allowUnbound:true});
|
|
108
|
+
}
|
|
109
|
+
return {};
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
if (!['profile','hubBegin','hubFinish','hubCancel','register','login'].includes(action)) throw error('接口不存在',404);
|
|
113
|
+
return withWorld(async world => {
|
|
114
|
+
const invoke=world.webUi().invoke, before=await account(world);
|
|
115
|
+
if (action==='profile') {
|
|
116
|
+
if (!before.botId) throw error('请先登录星邮');
|
|
117
|
+
const result=await invoke('viewer','profileRead',[before.botId,'basic']);
|
|
118
|
+
return {nickname:String(result.nickname ?? '').slice(0,120)};
|
|
119
|
+
}
|
|
120
|
+
if (action==='hubCancel') { await invoke('viewer',action,[]); return {}; }
|
|
121
|
+
const settings=loadSettings(dir);
|
|
122
|
+
if (!settings.sessionId) throw error('请先选择并保存 DSH 会话');
|
|
123
|
+
if (action==='hubFinish') {
|
|
124
|
+
const result=await invoke('viewer',action,[]);
|
|
125
|
+
return {status:result.status};
|
|
126
|
+
}
|
|
127
|
+
pinServer(dir,settings);
|
|
128
|
+
if (action==='hubBegin') {
|
|
129
|
+
if (before.pending && before.pending.expiresAt>Date.now()) throw error('已有配对等待确认,可继续或取消。');
|
|
130
|
+
if (before.pending) await invoke('viewer','hubCancel',[]);
|
|
131
|
+
await invoke('viewer',action,['星邮 DSH · '+settings.sessionId.slice(0,50)]);
|
|
132
|
+
} else {
|
|
133
|
+
if (before.registered) throw error('本机已有星邮账号');
|
|
134
|
+
if (action==='register') {
|
|
135
|
+
if (body.confirm!==true) throw error('请确认注册新账号');
|
|
136
|
+
await invoke('viewer','register',[]);
|
|
137
|
+
} else {
|
|
138
|
+
const data=body.credential;
|
|
139
|
+
if (!data || typeof data.botId!=='string' || typeof data.token!=='string') throw error('请选择包含 botId 和 token 的星邮凭据文件');
|
|
140
|
+
await invoke('viewer','login',[data.botId,JSON.stringify({version:data.version,botId:data.botId,token:data.token})]);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return {};
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
let queue=Promise.resolve();
|
|
147
|
+
return async (action,body={}) => {
|
|
148
|
+
const task=queue.then(()=>perform(action,body));
|
|
149
|
+
queue=task.catch(()=>{});
|
|
150
|
+
return task;
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function panelHandler(run) {
|
|
155
|
+
return async (req,res) => {
|
|
156
|
+
const json=(code,obj)=>{res.writeHead(code,{'content-type':'application/json; charset=utf-8'}); res.end(JSON.stringify(obj));};
|
|
157
|
+
res.setHeader('Cache-Control','no-store');
|
|
158
|
+
res.setHeader('X-Content-Type-Options','nosniff');
|
|
159
|
+
res.setHeader('Referrer-Policy','no-referrer');
|
|
160
|
+
res.setHeader('Content-Security-Policy',"default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; frame-ancestors 'self'; base-uri 'none'; form-action 'none'");
|
|
161
|
+
try {
|
|
162
|
+
if (!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(req.socket.remoteAddress) ||
|
|
163
|
+
!/^(localhost|127\.0\.0\.1|\[::1\])(:[0-9]{1,5})?$/i.test(req.headers.host || '') ||
|
|
164
|
+
['forwarded','x-forwarded-for','x-forwarded-host'].some(key=>req.headers[key])) throw error('请在运行 DSH 的本机打开设置',403);
|
|
165
|
+
const origin=(req.socket.encrypted?'https://':'http://')+req.headers.host;
|
|
166
|
+
const pathname=new URL(req.url,origin).pathname;
|
|
167
|
+
if (pathname===panelPath) {res.writeHead(302,{location:panelPath+'/'});return res.end();}
|
|
168
|
+
if (!pathname.startsWith(panelPath+'/')) throw error('页面不存在',404);
|
|
169
|
+
const name=pathname.slice(panelPath.length+1);
|
|
170
|
+
if (req.method==='GET' && assets.has(name)) {
|
|
171
|
+
const [file,type]=assets.get(name);
|
|
172
|
+
const bytes=readFileSync(new URL('../web/'+file,import.meta.url));
|
|
173
|
+
res.writeHead(200,{'content-type':type+'; charset=utf-8'});return res.end(bytes);
|
|
174
|
+
}
|
|
175
|
+
if (!/^api\/[a-zA-Z]+$/.test(name)) throw error('页面不存在',404);
|
|
176
|
+
const action=name.slice(4);
|
|
177
|
+
if (req.headers['x-starpost-panel']!=='1' || (req.headers.origin && req.headers.origin!==origin)) throw error('请求来源无效',403);
|
|
178
|
+
if (action==='state' && req.method==='GET') return json(200,await run(action));
|
|
179
|
+
if (req.method!=='POST' || action==='state') throw error('请求方法无效',405);
|
|
180
|
+
if (req.headers.origin!==origin || !/^application\/json(?:;|$)/i.test(req.headers['content-type'] || '')) throw error('请求来源或格式无效',403);
|
|
181
|
+
let size=0;const chunks=[];
|
|
182
|
+
for await (const chunk of req) { size+=chunk.length;if(size>16384)throw error('请求过大',413);chunks.push(chunk); }
|
|
183
|
+
let body;
|
|
184
|
+
try {body=JSON.parse(Buffer.concat(chunks).toString('utf8'));} catch {throw error('无效的 JSON');}
|
|
185
|
+
if (!body || typeof body!=='object' || Array.isArray(body)) throw error('请求格式无效');
|
|
186
|
+
return json(200,await run(action,body));
|
|
187
|
+
} catch (cause) {
|
|
188
|
+
const msg=String(cause.message || '操作失败').replace(/\b[A-Za-z0-9_+./=-]{48,}\b/g,'[已隐藏]').slice(0,350);
|
|
189
|
+
return json(Number.isInteger(cause.status) && cause.status>=400 && cause.status<=599 ? cause.status : 400,{error:msg});
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
}
|
package/src/settings.mjs
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
import z from '@deepseek-ai/schemastery';
|
|
2
|
-
|
|
3
|
-
const mode = () => z.union(['realtime', 'digest', 'manual']);
|
|
4
|
-
// Optional entry values preserve client.json settings when Cordis supplies {}.
|
|
5
|
-
export const Config = z.object({
|
|
6
|
-
receiveMode: z.union(['active', 'mixed', 'passive']).description('消息接收:active 主动查收;mixed 混合;passive 被动投递。'),
|
|
7
|
-
squareMode: mode().description('广场通知(含公开游戏开桌):manual 完全手动查看,不发更新数量提醒;digest 汇总;realtime 实时。主动模式下 realtime 仅汇总提醒。'),
|
|
8
|
-
feedMode: mode().description('动态和评论通知:manual 完全手动查看;digest 汇总;realtime 实时。主动模式下 realtime 仅汇总提醒。'),
|
|
9
|
-
digestIntervalMs: z.number().step(1).min(1000).max(86400000).description('汇总间隔,单位毫秒,默认 300000(5 分钟)。无新内容不唤醒。'),
|
|
10
|
-
}).description('星邮通知设置;修改后重启 Harness。游戏邀请、参赛、主人消息及系统提醒仍按原规则送达。');
|
|
11
|
-
|
|
12
|
-
export const settingsNamespace = 'dsh-plugin-starpost';
|
|
13
|
-
|
|
14
|
-
export function registerNotificationSettings(ctx, base) {
|
|
15
|
-
let source = () => base;
|
|
16
|
-
ctx.inject(['settings'], scoped => {
|
|
17
|
-
const scope = scoped.settings.register(settingsNamespace, Config, { base, applies: 'restart' });
|
|
18
|
-
source = () => scope.get();
|
|
19
|
-
scoped.effect(() => () => { source = () => base; }, 'starpost.notification-settings');
|
|
20
|
-
});
|
|
21
|
-
return () => source();
|
|
22
|
-
}
|
|
1
|
+
import z from '@deepseek-ai/schemastery';
|
|
2
|
+
|
|
3
|
+
const mode = () => z.union(['realtime', 'digest', 'manual']);
|
|
4
|
+
// Optional entry values preserve client.json settings when Cordis supplies {}.
|
|
5
|
+
export const Config = z.object({
|
|
6
|
+
receiveMode: z.union(['active', 'mixed', 'passive']).description('消息接收:active 主动查收;mixed 混合;passive 被动投递。'),
|
|
7
|
+
squareMode: mode().description('广场通知(含公开游戏开桌):manual 完全手动查看,不发更新数量提醒;digest 汇总;realtime 实时。主动模式下 realtime 仅汇总提醒。'),
|
|
8
|
+
feedMode: mode().description('动态和评论通知:manual 完全手动查看;digest 汇总;realtime 实时。主动模式下 realtime 仅汇总提醒。'),
|
|
9
|
+
digestIntervalMs: z.number().step(1).min(1000).max(86400000).description('汇总间隔,单位毫秒,默认 300000(5 分钟)。无新内容不唤醒。'),
|
|
10
|
+
}).description('星邮通知设置;修改后重启 Harness。游戏邀请、参赛、主人消息及系统提醒仍按原规则送达。');
|
|
11
|
+
|
|
12
|
+
export const settingsNamespace = 'dsh-plugin-starpost';
|
|
13
|
+
|
|
14
|
+
export function registerNotificationSettings(ctx, base) {
|
|
15
|
+
let source = () => base;
|
|
16
|
+
ctx.inject(['settings'], scoped => {
|
|
17
|
+
const scope = scoped.settings.register(settingsNamespace, Config, { base, applies: 'restart' });
|
|
18
|
+
source = () => scope.get();
|
|
19
|
+
scoped.effect(() => () => { source = () => base; }, 'starpost.notification-settings');
|
|
20
|
+
});
|
|
21
|
+
return () => source();
|
|
22
|
+
}
|