dsh-plugin-starpost 0.5.0 → 0.5.1
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 +4 -0
- package/README.md +4 -0
- package/lib/core.mjs +14 -3
- package/package.json +77 -77
- package/src/panel.mjs +193 -192
- package/web/app.mjs +181 -168
package/CHANGELOG.md
CHANGED
package/README.md
CHANGED
package/lib/core.mjs
CHANGED
|
@@ -1880,7 +1880,7 @@ var StarpostWorld = class {
|
|
|
1880
1880
|
webUi() {
|
|
1881
1881
|
const identity = this.activeIdentity();
|
|
1882
1882
|
const hub = this.hub.session();
|
|
1883
|
-
const config = { ...STARPOST_CONFIG_GROUP, schema: { ...STARPOST_CONFIG_GROUP.schema, description: (hub ? `FFA hub \u5DF2\u767B\u5F55\uFF0C\u661F\u90AE ID\uFF1A${hub.botId}\u3002\u6388\u6743\u3001\u7BA1\u7406\u5458\u4E0E\u4E3B\u8FD0\u884C\u7AEF\u8BF7\u5230 ${officialTransport(hub.issuer).origin} \u7BA1\u7406\u3002` : identity ? `\
|
|
1883
|
+
const config = { ...STARPOST_CONFIG_GROUP, schema: { ...STARPOST_CONFIG_GROUP.schema, description: (hub ? `FFA hub \u5DF2\u767B\u5F55\uFF0C\u661F\u90AE ID\uFF1A${hub.botId}\u3002\u6388\u6743\u3001\u7BA1\u7406\u5458\u4E0E\u4E3B\u8FD0\u884C\u7AEF\u8BF7\u5230 ${officialTransport(hub.issuer).origin} \u7BA1\u7406\u3002` : identity ? `\u661F\u90AE ID\uFF1A${identity.botId}\u3002\u70B9\u51FB\u661F\u90AE\u9996\u9875\u7684\u300C\u7ED1\u5B9A\u51ED\u636E\u300D\u53EF\u67E5\u770B\u5E76\u590D\u5236\u3002` : "\u6CE8\u518C\u540E\u5728\u6B64\u663E\u793A\u7ED1\u5B9A bot \u6240\u9700\u7684 ID \u4E0E\u51ED\u636E\u3002") + " \u5B98\u7F51\uFF1Ahttps://8.148.13.225 \u3002\u5DF2\u6709\u8D26\u53F7\u4FDD\u6301\u539F\u767B\u5F55\uFF1B\u4EBA\u7C7B\u53EF\u5728\u661F\u90AE\u9875\u9762\u9009\u62E9 FFA hub \u6D4F\u89C8\u5668\u914D\u5BF9\u3002" } };
|
|
1884
1884
|
return { label: "\u661F\u90AE", lamps: [{ label: "\u4E2D\u8F6C\u670D\u52A1", state: this.connected ? "online" : this.lastError ? "error" : "loading", hint: this.lastError || (this.connected ? "\u5DF2\u8FDE\u63A5" : "\u7B49\u5F85\u9996\u6B21\u8FDE\u63A5") }], config: [config], panels: [{ id: "viewer", title: "\u661F\u90AE", description: "\u9996\u6B21\u6CE8\u518C\u8D26\u53F7\uFF1B\u6CE8\u518C\u540E\u6309\u597D\u53CB\u6216\u7FA4\u804A\u67E5\u770B\u53EA\u8BFB\u804A\u5929\u8BB0\u5F55\u53CA\u52A8\u6001\u3002" }], invoke: async (panel, method, args) => {
|
|
1885
1885
|
if (panel !== "viewer") throw new Error("\u672A\u77E5\u9762\u677F");
|
|
1886
1886
|
if (method === "hubStatus") return this.hub.status();
|
|
@@ -1905,9 +1905,20 @@ var StarpostWorld = class {
|
|
|
1905
1905
|
recoveryHint: normalizeBotId(this.cfg.botId) ? "\u65E7\u7248\u624B\u5DE5\u8D26\u53F7\u7F3A\u5C11 .env \u5BC6\u94A5\u3002\u91CD\u88C5\u7528\u6237\u8BF7\u5728\u4E0B\u65B9\u4F7F\u7528\u539F ID \u548C\u539F\u51ED\u636E\u6062\u590D\u8D26\u53F7\u3002" : "\u65E7\u7248\u624B\u5DE5\u8D26\u53F7 ID \u683C\u5F0F\u65E0\u6548\u3002Bot ID \u5E94\u4E3A\u4E0D\u5C0F\u4E8E 10001 \u7684 5\u201312 \u4F4D\u6570\u5B57\uFF1B\u91CD\u88C5\u7528\u6237\u8BF7\u5728\u4E0B\u65B9\u6062\u590D\u5DF2\u6709\u8D26\u53F7\u3002"
|
|
1906
1906
|
} : {} };
|
|
1907
1907
|
}
|
|
1908
|
+
if (method === "bindingCredential") {
|
|
1909
|
+
const current = this.activeIdentity();
|
|
1910
|
+
if (!current) throw new Error("\u8BF7\u5148\u767B\u5F55\u661F\u90AE");
|
|
1911
|
+
if (!this.hub.session()) return { botId: current.botId, credential: current.token };
|
|
1912
|
+
const headers = await this.authHeaders();
|
|
1913
|
+
const response = await postJson(new URL("/hub/session", this.serverBase()), { bindingOperation: "issue" }, headers);
|
|
1914
|
+
const body = response.body;
|
|
1915
|
+
if (!body.ok || body.result?.botId !== current.botId || this.activeIdentity()?.botId !== current.botId || !this.hub.session())
|
|
1916
|
+
throw new Error(body.error ?? "\u83B7\u53D6\u7ED1\u5B9A\u7801\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u9762\u677F");
|
|
1917
|
+
return body.result;
|
|
1918
|
+
}
|
|
1908
1919
|
if (method === "mobileLoginInfo") {
|
|
1909
1920
|
const current = this.activeIdentity();
|
|
1910
|
-
return { botId: current?.botId ?? "", credential:
|
|
1921
|
+
return { botId: current?.botId ?? "", credential: "", authMode: this.hub.session() ? "hub" : "legacy", hubUrl: officialTransport(this.cfg.hubUrl || HUB_IP).origin, apkUrl: "https://8.137.59.209/downloads/ffa/apps/starpost/android/1.18.1/starpost-android.apk" };
|
|
1911
1922
|
}
|
|
1912
1923
|
if (method === "teenControl") {
|
|
1913
1924
|
if (this.hub.session()) throw new Error("Hub \u6A21\u5F0F\u7684\u7BA1\u7406\u5458\u8BBE\u7F6E\u8BF7\u524D\u5F80 FFA hub \u8D26\u53F7\u4E2D\u5FC3");
|
|
@@ -2349,7 +2360,7 @@ ${data.text || ""}${voiceText ? "\n[\u8BED\u97F3\u8F6C\u5199\uFF0C\u5916\u90E8\u
|
|
|
2349
2360
|
};
|
|
2350
2361
|
|
|
2351
2362
|
// <stdin>
|
|
2352
|
-
var relayVersion = "0.36.
|
|
2363
|
+
var relayVersion = "0.36.1";
|
|
2353
2364
|
export {
|
|
2354
2365
|
STARPOST_DEFAULTS,
|
|
2355
2366
|
STARPOST_TOOL_DECLS,
|
package/package.json
CHANGED
|
@@ -1,77 +1,77 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "dsh-plugin-starpost",
|
|
3
|
-
"version": "0.5.
|
|
4
|
-
"description": "星邮的 DeepSeek Harness bot 客户端,提供本机 Web 配置、FFA Hub 配对、消息收发和折叠社交工具",
|
|
5
|
-
"license": "MIT",
|
|
6
|
-
"type": "module",
|
|
7
|
-
"main": "./src/index.mjs",
|
|
8
|
-
"exports": {
|
|
9
|
-
".": "./src/index.mjs",
|
|
10
|
-
"./client": "./web/client.js",
|
|
11
|
-
"./package.json": "./package.json",
|
|
12
|
-
"./*": "./*"
|
|
13
|
-
},
|
|
14
|
-
"bin": {
|
|
15
|
-
"starpost-dsh": "./src/account.mjs"
|
|
16
|
-
},
|
|
17
|
-
"dsh": {
|
|
18
|
-
"client": {
|
|
19
|
-
"platform": "web",
|
|
20
|
-
"inject": [
|
|
21
|
-
"@deepseek-ai/dsh-client-ui-settings"
|
|
22
|
-
]
|
|
23
|
-
},
|
|
24
|
-
"bundle": {
|
|
25
|
-
"patch": "./cordis.patch.yml"
|
|
26
|
-
}
|
|
27
|
-
},
|
|
28
|
-
"engines": {
|
|
29
|
-
"node": ">=22.16.0",
|
|
30
|
-
"dsh": "^0.1.1-rc.2 || ^0.2.2-rc.1"
|
|
31
|
-
},
|
|
32
|
-
"files": [
|
|
33
|
-
"src/*.mjs",
|
|
34
|
-
"web",
|
|
35
|
-
"lib",
|
|
36
|
-
"cordis.patch.yml",
|
|
37
|
-
"desktop.ps1",
|
|
38
|
-
"README.md",
|
|
39
|
-
"LICENSE",
|
|
40
|
-
"CHANGELOG.md",
|
|
41
|
-
"docs"
|
|
42
|
-
],
|
|
43
|
-
"scripts": {
|
|
44
|
-
"build": "node build.mjs",
|
|
45
|
-
"prepack": "npm run build",
|
|
46
|
-
"test": "node --test tests/*.test.mjs",
|
|
47
|
-
"pretest": "npm run build"
|
|
48
|
-
},
|
|
49
|
-
"repository": {
|
|
50
|
-
"type": "git",
|
|
51
|
-
"url": "git+https://github.com/insomnic-Evan/dsh-plugin-starpost.git"
|
|
52
|
-
},
|
|
53
|
-
"author": "hth768",
|
|
54
|
-
"homepage": "https://github.com/insomnic-Evan/dsh-plugin-starpost#readme",
|
|
55
|
-
"bugs": {
|
|
56
|
-
"url": "https://github.com/insomnic-Evan/dsh-plugin-starpost/issues"
|
|
57
|
-
},
|
|
58
|
-
"keywords": [
|
|
59
|
-
"deepseek-harness",
|
|
60
|
-
"dsh-plugin",
|
|
61
|
-
"starpost",
|
|
62
|
-
"bot",
|
|
63
|
-
"chat"
|
|
64
|
-
],
|
|
65
|
-
"starpostCoreVersion": "0.36.
|
|
66
|
-
"devDependencies": {
|
|
67
|
-
"@deepseek-ai/dsh-agent-loop": "0.2.2-rc.1",
|
|
68
|
-
"@deepseek-ai/dsh-agent-loop-testkit": "0.2.2-rc.1",
|
|
69
|
-
"@deepseek-ai/dsh-llm": "0.2.2-rc.1",
|
|
70
|
-
"@deepseek-ai/dsh-tools": "0.2.2-rc.1",
|
|
71
|
-
"cortico-world-starpost": "0.36.
|
|
72
|
-
"esbuild": "0.25.12"
|
|
73
|
-
},
|
|
74
|
-
"dependencies": {
|
|
75
|
-
"@deepseek-ai/schemastery": "3.19.0"
|
|
76
|
-
}
|
|
77
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "dsh-plugin-starpost",
|
|
3
|
+
"version": "0.5.1",
|
|
4
|
+
"description": "星邮的 DeepSeek Harness bot 客户端,提供本机 Web 配置、FFA Hub 配对、消息收发和折叠社交工具",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./src/index.mjs",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./src/index.mjs",
|
|
10
|
+
"./client": "./web/client.js",
|
|
11
|
+
"./package.json": "./package.json",
|
|
12
|
+
"./*": "./*"
|
|
13
|
+
},
|
|
14
|
+
"bin": {
|
|
15
|
+
"starpost-dsh": "./src/account.mjs"
|
|
16
|
+
},
|
|
17
|
+
"dsh": {
|
|
18
|
+
"client": {
|
|
19
|
+
"platform": "web",
|
|
20
|
+
"inject": [
|
|
21
|
+
"@deepseek-ai/dsh-client-ui-settings"
|
|
22
|
+
]
|
|
23
|
+
},
|
|
24
|
+
"bundle": {
|
|
25
|
+
"patch": "./cordis.patch.yml"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"engines": {
|
|
29
|
+
"node": ">=22.16.0",
|
|
30
|
+
"dsh": "^0.1.1-rc.2 || ^0.2.2-rc.1"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"src/*.mjs",
|
|
34
|
+
"web",
|
|
35
|
+
"lib",
|
|
36
|
+
"cordis.patch.yml",
|
|
37
|
+
"desktop.ps1",
|
|
38
|
+
"README.md",
|
|
39
|
+
"LICENSE",
|
|
40
|
+
"CHANGELOG.md",
|
|
41
|
+
"docs"
|
|
42
|
+
],
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "node build.mjs",
|
|
45
|
+
"prepack": "npm run build",
|
|
46
|
+
"test": "node --test tests/*.test.mjs",
|
|
47
|
+
"pretest": "npm run build"
|
|
48
|
+
},
|
|
49
|
+
"repository": {
|
|
50
|
+
"type": "git",
|
|
51
|
+
"url": "git+https://github.com/insomnic-Evan/dsh-plugin-starpost.git"
|
|
52
|
+
},
|
|
53
|
+
"author": "hth768",
|
|
54
|
+
"homepage": "https://github.com/insomnic-Evan/dsh-plugin-starpost#readme",
|
|
55
|
+
"bugs": {
|
|
56
|
+
"url": "https://github.com/insomnic-Evan/dsh-plugin-starpost/issues"
|
|
57
|
+
},
|
|
58
|
+
"keywords": [
|
|
59
|
+
"deepseek-harness",
|
|
60
|
+
"dsh-plugin",
|
|
61
|
+
"starpost",
|
|
62
|
+
"bot",
|
|
63
|
+
"chat"
|
|
64
|
+
],
|
|
65
|
+
"starpostCoreVersion": "0.36.1",
|
|
66
|
+
"devDependencies": {
|
|
67
|
+
"@deepseek-ai/dsh-agent-loop": "0.2.2-rc.1",
|
|
68
|
+
"@deepseek-ai/dsh-agent-loop-testkit": "0.2.2-rc.1",
|
|
69
|
+
"@deepseek-ai/dsh-llm": "0.2.2-rc.1",
|
|
70
|
+
"@deepseek-ai/dsh-tools": "0.2.2-rc.1",
|
|
71
|
+
"cortico-world-starpost": "0.36.1",
|
|
72
|
+
"esbuild": "0.25.12"
|
|
73
|
+
},
|
|
74
|
+
"dependencies": {
|
|
75
|
+
"@deepseek-ai/schemastery": "3.19.0"
|
|
76
|
+
}
|
|
77
|
+
}
|
package/src/panel.mjs
CHANGED
|
@@ -1,192 +1,193 @@
|
|
|
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==='
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
if (
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
if (before.pending)
|
|
131
|
-
await invoke('viewer',
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
if (
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
queue
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
res.
|
|
158
|
-
res.setHeader('
|
|
159
|
-
res.setHeader('
|
|
160
|
-
res.setHeader('
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
[
|
|
165
|
-
|
|
166
|
-
const
|
|
167
|
-
|
|
168
|
-
if (
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
const
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
if (
|
|
179
|
-
if (
|
|
180
|
-
if (req.
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
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 (!['bindingCredential','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==='bindingCredential') return invoke('viewer','bindingCredential',[]);
|
|
116
|
+
if (action==='profile') {
|
|
117
|
+
if (!before.botId) throw error('请先登录星邮');
|
|
118
|
+
const result=await invoke('viewer','profileRead',[before.botId,'basic']);
|
|
119
|
+
return {nickname:String(result.nickname ?? '').slice(0,120)};
|
|
120
|
+
}
|
|
121
|
+
if (action==='hubCancel') { await invoke('viewer',action,[]); return {}; }
|
|
122
|
+
const settings=loadSettings(dir);
|
|
123
|
+
if (!settings.sessionId) throw error('请先选择并保存 DSH 会话');
|
|
124
|
+
if (action==='hubFinish') {
|
|
125
|
+
const result=await invoke('viewer',action,[]);
|
|
126
|
+
return {status:result.status};
|
|
127
|
+
}
|
|
128
|
+
pinServer(dir,settings);
|
|
129
|
+
if (action==='hubBegin') {
|
|
130
|
+
if (before.pending && before.pending.expiresAt>Date.now()) throw error('已有配对等待确认,可继续或取消。');
|
|
131
|
+
if (before.pending) await invoke('viewer','hubCancel',[]);
|
|
132
|
+
await invoke('viewer',action,['星邮 DSH · '+settings.sessionId.slice(0,50)]);
|
|
133
|
+
} else {
|
|
134
|
+
if (before.registered) throw error('本机已有星邮账号');
|
|
135
|
+
if (action==='register') {
|
|
136
|
+
if (body.confirm!==true) throw error('请确认注册新账号');
|
|
137
|
+
await invoke('viewer','register',[]);
|
|
138
|
+
} else {
|
|
139
|
+
const data=body.credential;
|
|
140
|
+
if (!data || typeof data.botId!=='string' || typeof data.token!=='string') throw error('请选择包含 botId 和 token 的星邮凭据文件');
|
|
141
|
+
await invoke('viewer','login',[data.botId,JSON.stringify({version:data.version,botId:data.botId,token:data.token})]);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return {};
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
let queue=Promise.resolve();
|
|
148
|
+
return async (action,body={}) => {
|
|
149
|
+
const task=queue.then(()=>perform(action,body));
|
|
150
|
+
queue=task.catch(()=>{});
|
|
151
|
+
return task;
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function panelHandler(run) {
|
|
156
|
+
return async (req,res) => {
|
|
157
|
+
const json=(code,obj)=>{res.writeHead(code,{'content-type':'application/json; charset=utf-8'}); res.end(JSON.stringify(obj));};
|
|
158
|
+
res.setHeader('Cache-Control','no-store');
|
|
159
|
+
res.setHeader('X-Content-Type-Options','nosniff');
|
|
160
|
+
res.setHeader('Referrer-Policy','no-referrer');
|
|
161
|
+
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'");
|
|
162
|
+
try {
|
|
163
|
+
if (!['127.0.0.1','::1','::ffff:127.0.0.1'].includes(req.socket.remoteAddress) ||
|
|
164
|
+
!/^(localhost|127\.0\.0\.1|\[::1\])(:[0-9]{1,5})?$/i.test(req.headers.host || '') ||
|
|
165
|
+
['forwarded','x-forwarded-for','x-forwarded-host'].some(key=>req.headers[key])) throw error('请在运行 DSH 的本机打开设置',403);
|
|
166
|
+
const origin=(req.socket.encrypted?'https://':'http://')+req.headers.host;
|
|
167
|
+
const pathname=new URL(req.url,origin).pathname;
|
|
168
|
+
if (pathname===panelPath) {res.writeHead(302,{location:panelPath+'/'});return res.end();}
|
|
169
|
+
if (!pathname.startsWith(panelPath+'/')) throw error('页面不存在',404);
|
|
170
|
+
const name=pathname.slice(panelPath.length+1);
|
|
171
|
+
if (req.method==='GET' && assets.has(name)) {
|
|
172
|
+
const [file,type]=assets.get(name);
|
|
173
|
+
const bytes=readFileSync(new URL('../web/'+file,import.meta.url));
|
|
174
|
+
res.writeHead(200,{'content-type':type+'; charset=utf-8'});return res.end(bytes);
|
|
175
|
+
}
|
|
176
|
+
if (!/^api\/[a-zA-Z]+$/.test(name)) throw error('页面不存在',404);
|
|
177
|
+
const action=name.slice(4);
|
|
178
|
+
if (req.headers['x-starpost-panel']!=='1' || (req.headers.origin && req.headers.origin!==origin)) throw error('请求来源无效',403);
|
|
179
|
+
if (action==='state' && req.method==='GET') return json(200,await run(action));
|
|
180
|
+
if (req.method!=='POST' || action==='state') throw error('请求方法无效',405);
|
|
181
|
+
if (req.headers.origin!==origin || !/^application\/json(?:;|$)/i.test(req.headers['content-type'] || '')) throw error('请求来源或格式无效',403);
|
|
182
|
+
let size=0;const chunks=[];
|
|
183
|
+
for await (const chunk of req) { size+=chunk.length;if(size>16384)throw error('请求过大',413);chunks.push(chunk); }
|
|
184
|
+
let body;
|
|
185
|
+
try {body=JSON.parse(Buffer.concat(chunks).toString('utf8'));} catch {throw error('无效的 JSON');}
|
|
186
|
+
if (!body || typeof body!=='object' || Array.isArray(body)) throw error('请求格式无效');
|
|
187
|
+
return json(200,await run(action,body));
|
|
188
|
+
} catch (cause) {
|
|
189
|
+
const msg=String(cause.message || '操作失败').replace(/\b[A-Za-z0-9_+./=-]{48,}\b/g,'[已隐藏]').slice(0,350);
|
|
190
|
+
return json(Number.isInteger(cause.status) && cause.status>=400 && cause.status<=599 ? cause.status : 400,{error:msg});
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
}
|
package/web/app.mjs
CHANGED
|
@@ -1,168 +1,181 @@
|
|
|
1
|
-
import {sections} from './fields.mjs';
|
|
2
|
-
const $ = id=>document.getElementById(id);
|
|
3
|
-
function el(tag,text,cls) {
|
|
4
|
-
const node=document.createElement(tag);
|
|
5
|
-
if(text!==undefined) node.textContent=text;
|
|
6
|
-
if(cls) node.className=cls;
|
|
7
|
-
return node;
|
|
8
|
-
}
|
|
9
|
-
const labels={account:'账号与会话',...Object.fromEntries(Object.entries(sections).map(([id,s])=>[id,s.title])),connection:'服务连接'};
|
|
10
|
-
const icons={account:'M20 21v-2a7 7 0 0 0-14 0v2 M17 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0',notify:'M3 5h18v13H9l-5 4v-4H3z M7 9h10 M7 13h6',limits:'M3 6h18 M3 12h18 M3 18h18 M9 3v6 M16 9v6 M8 15v6',media:'M3 4h18v16H3z M4 17l6-6 4 4 3-3 4 4 M15 8h2',speech:'M9 4a3 3 0 0 1 6 0v7a3 3 0 0 1-6 0z M5 11a7 7 0 0 0 14 0 M12 18v3 M8 21h8'};
|
|
11
|
-
let tab='account',state,nickname='',profileId='',dirty=false,busy=false;
|
|
12
|
-
icons.connection='M9 15l6-6 M8 13l-2 2a3 3 0 0 0 4 4l3-3 M11 8l3-3a3 3 0 0 1 5 4l-3 3';
|
|
13
|
-
function say(text,failed=false){$('notice').textContent=text;$('notice').className=failed?'error':'';}
|
|
14
|
-
async function api(action,body) {
|
|
15
|
-
const headers={'X-Starpost-Panel':'1'};
|
|
16
|
-
const opts={headers,cache:'no-store',credentials:'same-origin'};
|
|
17
|
-
if(body!==undefined){headers['Content-Type']='application/json';opts.method='POST';opts.body=JSON.stringify(body);}
|
|
18
|
-
const res=await fetch('./api/'+action,opts);
|
|
19
|
-
const json=await res.json();
|
|
20
|
-
if(!res.ok)throw Error(json.error || '请求失败');
|
|
21
|
-
return json;
|
|
22
|
-
}
|
|
23
|
-
function btn(label,handler,primary=false) {
|
|
24
|
-
const b=el('button',label,primary?'primary':'');b.type='button';b.addEventListener('click',handler);return b;
|
|
25
|
-
}
|
|
26
|
-
function group(cls='actions'){return el('div',undefined,cls);}
|
|
27
|
-
function card(title,cls='') {
|
|
28
|
-
const c=el('section',undefined,'card '+cls);
|
|
29
|
-
if(title)c.append(el('h2',title));
|
|
30
|
-
return c;
|
|
31
|
-
}
|
|
32
|
-
function field(label,input) {
|
|
33
|
-
const f=el('label',undefined,'field');f.append(el('span',label),input);return f;
|
|
34
|
-
}
|
|
35
|
-
function setBusy(value){busy=value;$('page').inert=value;$('tabs').inert=value;$('reload').disabled=value;}
|
|
36
|
-
async function action(fn) {
|
|
37
|
-
if(busy)return;
|
|
38
|
-
setBusy(true);
|
|
39
|
-
try {await fn();} catch(e){say(e.message,true);} finally {setBusy(false);}
|
|
40
|
-
}
|
|
41
|
-
function resetAllowed(){return !dirty || window.confirm('放弃本页尚未保存的修改?');}
|
|
42
|
-
const baseline=()=>state.pendingRestart?'有设置待生效,重启 DSH 后将使用已保存的配置。':'已读取本机配置。';
|
|
43
|
-
async function refresh(message) {
|
|
44
|
-
const next=await api('state');
|
|
45
|
-
if(next.account.botId!==state?.account.botId)nickname='';
|
|
46
|
-
state=next;dirty=false;render();say(message || baseline());
|
|
47
|
-
if(state.account.botId && profileId!==state.account.botId){
|
|
48
|
-
const id=state.account.botId;profileId=id;
|
|
49
|
-
api('profile',{}).then(result=>{
|
|
50
|
-
if(state.account.botId!==id)return;
|
|
51
|
-
nickname=result.nickname;
|
|
52
|
-
const title=$('accountName');if(title && nickname)title.textContent=nickname;
|
|
53
|
-
}).catch(()=>{ /* The retry button remains available when the relay is offline. */ });
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
async function save(data) {
|
|
57
|
-
await api('save',{...data,revision:state.revision});
|
|
58
|
-
await refresh('已保存。');
|
|
59
|
-
say('已保存。'+(state.pendingRestart?'重启 DSH 后生效。':''));
|
|
60
|
-
}
|
|
61
|
-
function edit(){dirty=true;say('有尚未保存的修改。');}
|
|
62
|
-
window.addEventListener('beforeunload',e=>{if(dirty){e.preventDefault();e.returnValue='';}});
|
|
63
|
-
for(const [id,title] of Object.entries(labels)){
|
|
64
|
-
const b=btn(title,()=>{if(!state || id===tab || !resetAllowed())return;tab=id;dirty=false;render();say(baseline());});
|
|
65
|
-
const svg=document.createElementNS('http://www.w3.org/2000/svg','svg'),p=document.createElementNS(svg.namespaceURI,'path');
|
|
66
|
-
svg.setAttribute('viewBox','0 0 24 24');svg.setAttribute('fill','none');svg.setAttribute('stroke','currentColor');svg.setAttribute('stroke-width','1.8');svg.setAttribute('aria-hidden','true');p.setAttribute('d',icons[id]);svg.append(p);b.prepend(svg);b.dataset.tab=id;$('tabs').append(b);
|
|
67
|
-
}
|
|
68
|
-
$('reload').onclick=()=>action(async()=>{if(resetAllowed())await refresh();});
|
|
69
|
-
function display(f,v){return f.choices?.find(x=>x[0]===v)?.[1] ?? (f.type==='checkbox'?(v?'开启':'关闭'):String(f.scale?v/f.scale:v || '默认'));}
|
|
70
|
-
function accountPage() {
|
|
71
|
-
const {account:a}=state, hero=card(a.registered?(nickname || '已登录的 bot'):'尚未登录星邮','hero');
|
|
72
|
-
hero.querySelector('h2').id='accountName';
|
|
73
|
-
const status=el('p',a.registered?'星邮 ID '+a.botId+' · '+(a.mode==='hub'?'FFA Hub 配对':'本机凭据登录'):'选择 DSH 会话后,使用 FFA Hub 在浏览器中配对。');hero.append(status);
|
|
74
|
-
hero.append(el('div',state.ready?'已连接到 DSH 会话':a.expired?'Hub 授权已到期':state.runtimeSession?'等待会话就绪':'尚未启用接收','badge'));
|
|
75
|
-
if(state.runtimeError)hero.append(el('p',state.runtimeError,'aux'));
|
|
76
|
-
if(a.registered)hero.append(btn('读取 bot 昵称',()=>action(async()=>{nickname=(await api('profile',{})).nickname;hero.querySelector('h2').textContent=nickname || '已登录的 bot';say(nickname?'已读取昵称。':'该 bot 尚未设置昵称。');})));
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
if(
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
if(
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
1
|
+
import {sections} from './fields.mjs';
|
|
2
|
+
const $ = id=>document.getElementById(id);
|
|
3
|
+
function el(tag,text,cls) {
|
|
4
|
+
const node=document.createElement(tag);
|
|
5
|
+
if(text!==undefined) node.textContent=text;
|
|
6
|
+
if(cls) node.className=cls;
|
|
7
|
+
return node;
|
|
8
|
+
}
|
|
9
|
+
const labels={account:'账号与会话',...Object.fromEntries(Object.entries(sections).map(([id,s])=>[id,s.title])),connection:'服务连接'};
|
|
10
|
+
const icons={account:'M20 21v-2a7 7 0 0 0-14 0v2 M17 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0',notify:'M3 5h18v13H9l-5 4v-4H3z M7 9h10 M7 13h6',limits:'M3 6h18 M3 12h18 M3 18h18 M9 3v6 M16 9v6 M8 15v6',media:'M3 4h18v16H3z M4 17l6-6 4 4 3-3 4 4 M15 8h2',speech:'M9 4a3 3 0 0 1 6 0v7a3 3 0 0 1-6 0z M5 11a7 7 0 0 0 14 0 M12 18v3 M8 21h8'};
|
|
11
|
+
let tab='account',state,nickname='',profileId='',dirty=false,busy=false;
|
|
12
|
+
icons.connection='M9 15l6-6 M8 13l-2 2a3 3 0 0 0 4 4l3-3 M11 8l3-3a3 3 0 0 1 5 4l-3 3';
|
|
13
|
+
function say(text,failed=false){$('notice').textContent=text;$('notice').className=failed?'error':'';}
|
|
14
|
+
async function api(action,body) {
|
|
15
|
+
const headers={'X-Starpost-Panel':'1'};
|
|
16
|
+
const opts={headers,cache:'no-store',credentials:'same-origin'};
|
|
17
|
+
if(body!==undefined){headers['Content-Type']='application/json';opts.method='POST';opts.body=JSON.stringify(body);}
|
|
18
|
+
const res=await fetch('./api/'+action,opts);
|
|
19
|
+
const json=await res.json();
|
|
20
|
+
if(!res.ok)throw Error(json.error || '请求失败');
|
|
21
|
+
return json;
|
|
22
|
+
}
|
|
23
|
+
function btn(label,handler,primary=false) {
|
|
24
|
+
const b=el('button',label,primary?'primary':'');b.type='button';b.addEventListener('click',handler);return b;
|
|
25
|
+
}
|
|
26
|
+
function group(cls='actions'){return el('div',undefined,cls);}
|
|
27
|
+
function card(title,cls='') {
|
|
28
|
+
const c=el('section',undefined,'card '+cls);
|
|
29
|
+
if(title)c.append(el('h2',title));
|
|
30
|
+
return c;
|
|
31
|
+
}
|
|
32
|
+
function field(label,input) {
|
|
33
|
+
const f=el('label',undefined,'field');f.append(el('span',label),input);return f;
|
|
34
|
+
}
|
|
35
|
+
function setBusy(value){busy=value;$('page').inert=value;$('tabs').inert=value;$('reload').disabled=value;}
|
|
36
|
+
async function action(fn) {
|
|
37
|
+
if(busy)return;
|
|
38
|
+
setBusy(true);
|
|
39
|
+
try {await fn();} catch(e){say(e.message,true);} finally {setBusy(false);}
|
|
40
|
+
}
|
|
41
|
+
function resetAllowed(){return !dirty || window.confirm('放弃本页尚未保存的修改?');}
|
|
42
|
+
const baseline=()=>state.pendingRestart?'有设置待生效,重启 DSH 后将使用已保存的配置。':'已读取本机配置。';
|
|
43
|
+
async function refresh(message) {
|
|
44
|
+
const next=await api('state');
|
|
45
|
+
if(next.account.botId!==state?.account.botId)nickname='';
|
|
46
|
+
state=next;dirty=false;render();say(message || baseline());
|
|
47
|
+
if(state.account.botId && profileId!==state.account.botId){
|
|
48
|
+
const id=state.account.botId;profileId=id;
|
|
49
|
+
api('profile',{}).then(result=>{
|
|
50
|
+
if(state.account.botId!==id)return;
|
|
51
|
+
nickname=result.nickname;
|
|
52
|
+
const title=$('accountName');if(title && nickname)title.textContent=nickname;
|
|
53
|
+
}).catch(()=>{ /* The retry button remains available when the relay is offline. */ });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
async function save(data) {
|
|
57
|
+
await api('save',{...data,revision:state.revision});
|
|
58
|
+
await refresh('已保存。');
|
|
59
|
+
say('已保存。'+(state.pendingRestart?'重启 DSH 后生效。':''));
|
|
60
|
+
}
|
|
61
|
+
function edit(){dirty=true;say('有尚未保存的修改。');}
|
|
62
|
+
window.addEventListener('beforeunload',e=>{if(dirty){e.preventDefault();e.returnValue='';}});
|
|
63
|
+
for(const [id,title] of Object.entries(labels)){
|
|
64
|
+
const b=btn(title,()=>{if(!state || id===tab || !resetAllowed())return;tab=id;dirty=false;render();say(baseline());});
|
|
65
|
+
const svg=document.createElementNS('http://www.w3.org/2000/svg','svg'),p=document.createElementNS(svg.namespaceURI,'path');
|
|
66
|
+
svg.setAttribute('viewBox','0 0 24 24');svg.setAttribute('fill','none');svg.setAttribute('stroke','currentColor');svg.setAttribute('stroke-width','1.8');svg.setAttribute('aria-hidden','true');p.setAttribute('d',icons[id]);svg.append(p);b.prepend(svg);b.dataset.tab=id;$('tabs').append(b);
|
|
67
|
+
}
|
|
68
|
+
$('reload').onclick=()=>action(async()=>{if(resetAllowed())await refresh();});
|
|
69
|
+
function display(f,v){return f.choices?.find(x=>x[0]===v)?.[1] ?? (f.type==='checkbox'?(v?'开启':'关闭'):String(f.scale?v/f.scale:v || '默认'));}
|
|
70
|
+
function accountPage() {
|
|
71
|
+
const {account:a}=state, hero=card(a.registered?(nickname || '已登录的 bot'):'尚未登录星邮','hero');
|
|
72
|
+
hero.querySelector('h2').id='accountName';
|
|
73
|
+
const status=el('p',a.registered?'星邮 ID '+a.botId+' · '+(a.mode==='hub'?'FFA Hub 配对':'本机凭据登录'):'选择 DSH 会话后,使用 FFA Hub 在浏览器中配对。');hero.append(status);
|
|
74
|
+
hero.append(el('div',state.ready?'已连接到 DSH 会话':a.expired?'Hub 授权已到期':state.runtimeSession?'等待会话就绪':'尚未启用接收','badge'));
|
|
75
|
+
if(state.runtimeError)hero.append(el('p',state.runtimeError,'aux'));
|
|
76
|
+
if(a.registered)hero.append(btn('读取 bot 昵称',()=>action(async()=>{nickname=(await api('profile',{})).nickname;hero.querySelector('h2').textContent=nickname || '已登录的 bot';say(nickname?'已读取昵称。':'该 bot 尚未设置昵称。');})));
|
|
77
|
+
if(a.registered){
|
|
78
|
+
const output=el('output');let shown=0;
|
|
79
|
+
hero.append(btn('绑定凭据 · 显示并复制',()=>action(async()=>{
|
|
80
|
+
const value=await api('bindingCredential',{});
|
|
81
|
+
if(!hero.isConnected || state.account.botId!==value.botId)return;
|
|
82
|
+
output.textContent=value.credential;
|
|
83
|
+
const generation=++shown;
|
|
84
|
+
setTimeout(()=>{if(shown===generation)output.textContent='';},60_000);
|
|
85
|
+
let message='已复制';
|
|
86
|
+
try {await navigator.clipboard.writeText(value.credential);} catch {message='请手动复制显示的凭据';}
|
|
87
|
+
say(message+(value.expiresAt?' · 十分钟内有效,仅可使用一次':' · 原星邮账号凭据'));
|
|
88
|
+
}),true),output);
|
|
89
|
+
}
|
|
90
|
+
const bind=card('DSH 会话'), select=el('select');
|
|
91
|
+
select.append(new Option('选择一个会话',''));
|
|
92
|
+
for(const s of state.sessions)select.append(new Option(s.title?s.title+' · '+s.id:s.id,s.id));
|
|
93
|
+
select.value=state.sessionId;select.onchange=edit;
|
|
94
|
+
bind.append(field('用于收发消息的会话',select));
|
|
95
|
+
if(!state.sessions.length)bind.append(el('p','请先在 DSH 中创建一个会话,然后点击重新载入。'));
|
|
96
|
+
const controls=group(), saveSession=btn('保存会话',()=>action(async()=>{if(!select.value)throw Error('请选择 DSH 会话');await save({section:'account',sessionId:select.value});}),true);
|
|
97
|
+
controls.append(saveSession);bind.append(controls);
|
|
98
|
+
if(state.runtimeSession)bind.append(el('p','本次启动使用的会话 · '+state.runtimeSession,'aux'));
|
|
99
|
+
const auth=card('FFA Hub 登录'), pending=a.pending;
|
|
100
|
+
function command(op,body={},ok='操作完成。'){
|
|
101
|
+
return ()=>action(async()=>{
|
|
102
|
+
if(dirty)throw Error('请先保存会话,或重新载入以放弃改动。');
|
|
103
|
+
const result=await api(op,body);
|
|
104
|
+
const messages={pending:'浏览器授权尚未完成。',awaiting_primary:'请管理员在 Hub 指定本安装为主运行端,再检查授权。',connected:'Hub 配对成功。'};
|
|
105
|
+
await refresh((messages[result.status] || ok)+(result.status==='connected' || op==='login' || op==='register'?' 重启 DSH 后启用收发。':''));
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
if(pending){
|
|
109
|
+
const expired=Date.now()>=pending.expiresAt;
|
|
110
|
+
auth.append(el('p',expired?'本次配对已过期,请重新开始。':'在 Hub 中选择要连接的 bot,并核对配对码。'));
|
|
111
|
+
if(!expired){
|
|
112
|
+
auth.append(el('div',pending.shortCode,'code'));
|
|
113
|
+
const uri=new URL(pending.verificationUri);
|
|
114
|
+
if(uri.protocol==='https:' || (uri.protocol==='http:' && ['127.0.0.1','localhost','[::1]'].includes(uri.hostname))){
|
|
115
|
+
const link=el('a','打开 FFA Hub ↗','action primary');link.href=uri.href;link.target='_blank';link.rel='noopener noreferrer';auth.append(link);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const buttons=group();
|
|
119
|
+
buttons.append(expired?btn('重新配对',command('hubBegin',{},'已生成新的配对码。')):btn('检查授权并完成登录',command('hubFinish')),btn('取消配对',command('hubCancel',{},'已取消配对。')));auth.append(buttons);
|
|
120
|
+
} else {
|
|
121
|
+
auth.append(btn(a.mode==='hub'?'重新配对':'开始浏览器配对',command('hubBegin',{},'配对码已生成,请打开 FFA Hub。'),true));
|
|
122
|
+
}
|
|
123
|
+
const nodes=[hero,bind,auth];
|
|
124
|
+
if(!a.registered){
|
|
125
|
+
const box=el('details',undefined,'card');box.append(el('summary','使用原星邮凭据或注册新 bot'));
|
|
126
|
+
const file=el('input');file.type='file';file.accept='.json,application/json';
|
|
127
|
+
const controls=group();
|
|
128
|
+
controls.append(btn('恢复已有账号',()=>action(async()=>{
|
|
129
|
+
if(dirty || !state.sessionId)throw Error('请先保存 DSH 会话');
|
|
130
|
+
const chosen=file.files[0];if(!chosen || chosen.size>8192)throw Error('请选择星邮凭据 JSON 文件(最大 8 KB)');
|
|
131
|
+
let data;try{data=JSON.parse((await chosen.text()).replace(/^\uFEFF/,''));}catch{throw Error('凭据文件格式无效');}
|
|
132
|
+
await api('login',{credential:data});file.value='';await refresh('账号已恢复,重启 DSH 后启用收发。');
|
|
133
|
+
})),btn('注册新 bot',()=>{if(confirm('为此安装创建一个新的星邮 bot 账号?'))command('register',{confirm:true},'已注册新 bot。')();}));
|
|
134
|
+
box.append(field('本机星邮凭据文件',file),controls);nodes.push(box);
|
|
135
|
+
}
|
|
136
|
+
return nodes;
|
|
137
|
+
}
|
|
138
|
+
function settingsPage(){
|
|
139
|
+
const section=sections[tab], box=card();
|
|
140
|
+
box.append(el('p',section.hint));
|
|
141
|
+
const form=el('form'),grid=group('grid'),inputs=new Map();
|
|
142
|
+
for(const f of section.fields){
|
|
143
|
+
let input;
|
|
144
|
+
if(f.type==='select'){input=el('select');for(const [v,l] of f.choices)input.append(new Option(l,v));}
|
|
145
|
+
else {input=el('input');input.type=f.type;if(f.type==='number'){input.min=f.min/f.scale;input.max=f.max/f.scale;input.step=f.step==='any'?'any':1/f.scale;input.required=true;}else if(f.type==='text')input.maxLength=2048;}
|
|
146
|
+
const saved=state.saved[f.key];if(f.type==='checkbox')input.checked=saved;else input.value=f.scale?saved/f.scale:saved;
|
|
147
|
+
input.name=f.key;input.oninput=edit;const label=field(f.label,input);
|
|
148
|
+
if(f.hint)label.append(el('small',f.hint));
|
|
149
|
+
if(state.masked.includes(f.key))label.append(el('small','已隐藏原地址。填写新地址可替换原值。'));
|
|
150
|
+
if(state.active[f.key]!==saved)label.append(el('small','本次启动 · '+display(f,state.active[f.key]),'pending'));
|
|
151
|
+
inputs.set(f,input);grid.append(label);
|
|
152
|
+
}
|
|
153
|
+
const foot=group('formFoot'),submit=el('button','保存设置','primary');submit.type='submit';
|
|
154
|
+
foot.append(submit,el('span','修改后重启 DSH 生效','aux'));form.append(grid,foot);
|
|
155
|
+
form.onsubmit=e=>{e.preventDefault();action(async()=>{
|
|
156
|
+
const values={};for(const [f,input] of inputs){let v=input.value;if(f.type==='number'){v=Number(v)*f.scale;if(f.step!=='any')v=Math.round(v);}if(f.type==='checkbox')v=input.checked;if(v!==state.saved[f.key])values[f.key]=v;}
|
|
157
|
+
if(!Object.keys(values).length){dirty=false;say('设置没有改动。');return;}
|
|
158
|
+
await save({section:tab,values});
|
|
159
|
+
});};
|
|
160
|
+
box.append(form);return [box];
|
|
161
|
+
}
|
|
162
|
+
function connectionPage() {
|
|
163
|
+
const c=state.connection,box=card('中转与身份认证'),form=el('form'),grid=group('grid'),inputs={};
|
|
164
|
+
box.append(el('p',c.locked?'当前账号数据已绑定以下服务。':'官方地址已预填。使用自建服务时,请在注册或配对前保存地址。'));
|
|
165
|
+
for(const [key,label] of [['serverUrl','星邮中转服务'],['hubUrl','FFA Hub 账号中心']]){
|
|
166
|
+
const input=el('input');input.type='url';input.required=true;input.value=c[key];input.readOnly=c.locked;input.oninput=edit;
|
|
167
|
+
inputs[key]=input;grid.append(field(label,input));
|
|
168
|
+
}
|
|
169
|
+
form.append(grid);
|
|
170
|
+
if(!c.locked){
|
|
171
|
+
const foot=group('formFoot'),b=el('button','保存服务地址','primary');b.type='submit';foot.append(b);form.append(foot);
|
|
172
|
+
}
|
|
173
|
+
form.onsubmit=e=>{e.preventDefault();action(()=>save({section:'connection',serverUrl:inputs.serverUrl.value,hubUrl:inputs.hubUrl.value}));};
|
|
174
|
+
box.append(form);return [box];
|
|
175
|
+
}
|
|
176
|
+
function render(){
|
|
177
|
+
for(const b of $('tabs').children){if(b.dataset.tab===tab)b.setAttribute('aria-current','page');else b.removeAttribute('aria-current');}
|
|
178
|
+
$('version').textContent='v'+state.pluginVersion;$('title').textContent=labels[tab];
|
|
179
|
+
$('page').replaceChildren(...(tab==='account'?accountPage():tab==='connection'?connectionPage():settingsPage()));
|
|
180
|
+
}
|
|
181
|
+
action(()=>refresh());
|