dsh-plugin-starpost 0.3.1 → 0.4.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 +53 -40
- package/README.md +106 -92
- package/desktop.ps1 +4 -2
- package/docs/FFA-HUB-BOT-LOGIN.md +84 -84
- package/lib/core.mjs +40 -16
- package/package.json +18 -7
- package/src/index.mjs +51 -4
- package/src/local.mjs +15 -4
- package/src/panel.mjs +192 -0
- package/web/app.mjs +168 -0
- package/web/client.js +16 -0
- package/web/fields.mjs +49 -0
- package/web/index.html +6 -0
- package/web/style.css +3 -0
package/lib/core.mjs
CHANGED
|
@@ -1,3 +1,26 @@
|
|
|
1
|
+
// core/src/transport.ts
|
|
2
|
+
var STARPOST_IP = "https://8.148.13.225";
|
|
3
|
+
var HUB_IP = "https://8.148.13.225:8443";
|
|
4
|
+
var HUB_ISSUER = "https://ffahub.net";
|
|
5
|
+
function starpostIdentityOrigin(value) {
|
|
6
|
+
const origin = new URL(value).origin;
|
|
7
|
+
return origin === STARPOST_IP ? "https://starpost.com.cn" : origin;
|
|
8
|
+
}
|
|
9
|
+
function hubIdentityOrigin(value) {
|
|
10
|
+
const origin = new URL(value).origin;
|
|
11
|
+
return origin === HUB_IP ? HUB_ISSUER : origin;
|
|
12
|
+
}
|
|
13
|
+
function officialTransport(value) {
|
|
14
|
+
const url = new URL(String(value));
|
|
15
|
+
if (url.username || url.password) return url;
|
|
16
|
+
if (url.origin === "https://starpost.com.cn") url.hostname = "8.148.13.225";
|
|
17
|
+
else if (url.origin === HUB_ISSUER) {
|
|
18
|
+
url.hostname = "8.148.13.225";
|
|
19
|
+
url.port = "8443";
|
|
20
|
+
}
|
|
21
|
+
return url;
|
|
22
|
+
}
|
|
23
|
+
|
|
1
24
|
// core/src/world.ts
|
|
2
25
|
import { readFileSync as readFileSync3, writeFileSync as writeFileSync3, mkdirSync as mkdirSync3, existsSync as existsSync3, renameSync as renameSync3 } from "node:fs";
|
|
3
26
|
import { createHash as createHash3, randomBytes, randomUUID as randomUUID3 } from "node:crypto";
|
|
@@ -349,8 +372,8 @@ function normalizeBotId(value) {
|
|
|
349
372
|
var STARPOST_DEFAULTS = {
|
|
350
373
|
enabled: false,
|
|
351
374
|
receiveMode: "mixed",
|
|
352
|
-
serverUrl: "https://
|
|
353
|
-
hubUrl: "https://
|
|
375
|
+
serverUrl: "https://8.148.13.225",
|
|
376
|
+
hubUrl: "https://8.148.13.225:8443",
|
|
354
377
|
botId: "",
|
|
355
378
|
tokenSecret: "CORTICO_STARPOST_TOKEN",
|
|
356
379
|
emojiDir: "",
|
|
@@ -390,7 +413,7 @@ var STARPOST_CONFIG_GROUP = {
|
|
|
390
413
|
"worlds.starpost.speech.ttsProtocol": { type: "string", enum: ["openai", "json"], title: "TTS \u63A5\u53E3\u534F\u8BAE", description: "openai\uFF1APOST input/model/voice/response_format\uFF0C\u8FD4\u56DE\u97F3\u9891\uFF1Bjson\uFF1APOST text/model/voice\uFF0C\u8FD4\u56DE {audio}\u3002" },
|
|
391
414
|
"worlds.starpost.receiveMode": { type: "string", enum: ["active", "passive", "mixed"], title: "\u5185\u5BB9\u63A5\u6536\u6A21\u5F0F", description: "active \u65E5\u5E38\u5185\u5BB9\u53EA\u63D0\u9192\uFF0C\u6B63\u6587\u7531 bot \u4E3B\u52A8\u67E5\u770B\uFF1Bpassive \u5728\u7EBF\u804A\u5929\u5408\u6279\u6295\u9012\uFF1Bmixed \u4E24\u8005\u5747\u53EF\uFF08\u9ED8\u8BA4\uFF09\u3002\u4E3B\u52A8\u6A21\u5F0F\u7684\u5E7F\u573A\u3001\u52A8\u6001\u548C\u89C2\u6218\u66F4\u65B0\u53EA\u6C47\u603B\u6570\u91CF\u4E0E ID\uFF0C\u4E0D\u542B\u9884\u89C8\u3002\u6240\u6709\u6A21\u5F0F\u79BB\u7EBF\u79EF\u538B\u804A\u5929\u53EA\u63D0\u9192\uFF1B\u53C2\u8D5B\u6E38\u620F\u548C\u81EA\u5DF1\u7684\u624B\u673A/\u7F51\u9875\u7528\u6237\u6D88\u606F\u5B9E\u65F6\u6295\u9012\u3002\u4FEE\u6539\u540E\u91CD\u542F World\u3002" },
|
|
392
415
|
"worlds.starpost.serverUrl": { type: "string", title: "\u4E2D\u8F6C\u670D\u52A1\u5730\u5740", description: "\u5EFA\u8BAE\u4F7F\u7528 HTTPS\u3002\u4FEE\u6539\u540E\u91CD\u542F World\u3002" },
|
|
393
|
-
"worlds.starpost.hubUrl": { type: "string", title: "FFA hub \u8D26\u53F7\u4E2D\u5FC3", description: "\
|
|
416
|
+
"worlds.starpost.hubUrl": { type: "string", title: "FFA hub \u8D26\u53F7\u4E2D\u5FC3", description: "\u4E34\u65F6\u4F7F\u7528 https://8.148.13.225:8443\uFF0C\u4FDD\u7559\u539F Hub \u8EAB\u4EFD\uFF1B\u65E7\u5B98\u65B9\u57DF\u540D\u914D\u7F6E\u81EA\u52A8\u8D70 IP \u8FDE\u63A5\u3002\u7531\u4EBA\u7C7B\u53D1\u8D77\u6D4F\u89C8\u5668\u914D\u5BF9\uFF0C\u5DF2\u6709\u767B\u5F55\u4FDD\u7559\u3002\u4FEE\u6539\u540E\u91CD\u542F World\u3002" },
|
|
394
417
|
"worlds.starpost.botId": { type: "string", title: "\u65E7\u7248\u624B\u5DE5\u8D26\u53F7 ID\uFF08\u901A\u5E38\u7559\u7A7A\uFF09", description: "\u4EC5\u7528\u4E8E\u6700\u65E9\u671F\u624B\u5DE5\u914D\u7F6E\u3002\u91CD\u88C5\u6216\u8FC1\u79FB\u8BF7\u5728\u661F\u90AE\u521D\u59CB\u9875\u9009\u62E9\u201C\u6062\u590D\u5DF2\u6709\u8D26\u53F7\u201D\uFF0C\u586B\u5199\u539F ID \u5E76\u7C98\u8D34\u539F\u51ED\u636E\u6216\u9009\u62E9\u51ED\u636E\u6587\u4EF6\uFF1B\u4E0D\u9700\u8981\u5728\u8FD9\u91CC\u586B ID\u3002\u5DF2\u4FDD\u5B58\u7684\u51ED\u636E\u4F18\u5148\u3002" },
|
|
395
418
|
"worlds.starpost.tokenSecret": { type: "string", title: "\u65E7\u7248\u5BC6\u94A5\u73AF\u5883\u53D8\u91CF\u540D", description: "\u9ED8\u8BA4 CORTICO_STARPOST_TOKEN\uFF0C\u4EC5\u7528\u4E8E\u6700\u65E9\u671F\u624B\u5DE5\u8D26\u53F7\u7684 .env \u5BC6\u94A5\uFF1B\u8FD9\u91CC\u4E0D\u80FD\u586B\u5199\u51ED\u636E\u672C\u8EAB\u3002\u91CD\u88C5\u8BF7\u4F7F\u7528\u661F\u90AE\u9875\u9762\u7684\u201C\u6062\u590D\u5DF2\u6709\u8D26\u53F7\u201D\u3002" },
|
|
396
419
|
"worlds.starpost.emojiDir": { type: "string", title: "\u8868\u60C5\u5305\u6587\u4EF6\u5939", description: "\u7559\u7A7A\u4F7F\u7528\u6269\u5C55\u5185 emoji \u6587\u4EF6\u5939\uFF0C\u4E5F\u53EF\u81EA\u884C\u9009\u62E9\u56FE\u7247\u76EE\u5F55\u3002\u6536\u5230\u7684\u804A\u5929\u8868\u60C5\u5305\u81EA\u52A8\u6536\u96C6\u5230\u6B64\u76EE\u5F55\uFF0C\u661F\u90AE\u72EC\u7ACB\u4FDD\u5B58\u6807\u7B7E\u548C\u5907\u6CE8\u3002" },
|
|
@@ -443,7 +466,7 @@ var HubAuth = class {
|
|
|
443
466
|
renameSync(tmp, file);
|
|
444
467
|
}
|
|
445
468
|
pin(value) {
|
|
446
|
-
if (value.server !== hubOrigin(this.server()) || value.issuer !== hubOrigin(this.issuer())) throw Error("Hub \u8D26\u53F7\u5DF2\u7ED1\u5B9A\u5176\u4ED6\u670D\u52A1\u5730\u5740\uFF0C\u8BF7\u6062\u590D\u539F\u5730\u5740\u6216\u4F7F\u7528\u72EC\u7ACB\u7684\u6570\u636E\u76EE\u5F55");
|
|
469
|
+
if (starpostIdentityOrigin(hubOrigin(value.server)) !== starpostIdentityOrigin(hubOrigin(this.server())) || hubIdentityOrigin(hubOrigin(value.issuer)) !== hubIdentityOrigin(hubOrigin(this.issuer()))) throw Error("Hub \u8D26\u53F7\u5DF2\u7ED1\u5B9A\u5176\u4ED6\u670D\u52A1\u5730\u5740\uFF0C\u8BF7\u6062\u590D\u539F\u5730\u5740\u6216\u4F7F\u7528\u72EC\u7ACB\u7684\u6570\u636E\u76EE\u5F55");
|
|
447
470
|
}
|
|
448
471
|
session() {
|
|
449
472
|
if (!existsSync(this.file)) return null;
|
|
@@ -463,11 +486,11 @@ var HubAuth = class {
|
|
|
463
486
|
return {
|
|
464
487
|
mode: s2 ? "hub" : "legacy",
|
|
465
488
|
...s2 ? { botId: s2.botId, subject: s2.subject, installationId: s2.installationId, expiresAt: s2.expiresAt, expired: s2.expiresAt <= Date.now() } : {},
|
|
466
|
-
...p ? { pending: { shortCode: p.shortCode, verificationUri: p.verificationUri, expiresAt: p.expiresAt, approved: Boolean(p.approved) } } : {}
|
|
489
|
+
...p ? { pending: { shortCode: p.shortCode, verificationUri: officialTransport(p.verificationUri).href, expiresAt: p.expiresAt, approved: Boolean(p.approved) } } : {}
|
|
467
490
|
};
|
|
468
491
|
}
|
|
469
492
|
async request(base, path, body) {
|
|
470
|
-
const r = await this.post(new URL(path, base), body);
|
|
493
|
+
const r = await this.post(officialTransport(new URL(path, base)), body);
|
|
471
494
|
if (r.status !== 200 || !r.body?.ok) throw Error(r.body?.message ?? r.body?.error ?? "FFA hub \u8BA4\u8BC1\u670D\u52A1\u6682\u4E0D\u53EF\u7528");
|
|
472
495
|
return r.body.result;
|
|
473
496
|
}
|
|
@@ -477,20 +500,20 @@ var HubAuth = class {
|
|
|
477
500
|
this.busy = true;
|
|
478
501
|
const revision = ++this.revision;
|
|
479
502
|
try {
|
|
480
|
-
const issuer = hubOrigin(this.issuer()), server = hubOrigin(this.server());
|
|
503
|
+
const issuer = hubIdentityOrigin(hubOrigin(this.issuer())), server = hubOrigin(this.server());
|
|
481
504
|
const info = await this.request(server, "/hub/info", {});
|
|
482
505
|
if (info.issuer !== issuer || info.service !== "starpost") throw Error("\u661F\u90AE\u670D\u52A1\u5668\u914D\u7F6E\u7684 Hub \u4E0E\u672C\u673A\u4E0D\u4E00\u81F4");
|
|
483
506
|
const { privateKey, publicKey } = generateKeyPairSync("ed25519");
|
|
484
507
|
const installationId = randomUUID(), deviceId = randomUUID();
|
|
485
508
|
const start = await this.request(issuer, "/v1/pairings", { service: "starpost", label, deviceId, installationId, publicKey: publicKey.export({ format: "jwk" }) });
|
|
486
509
|
const uri = new URL(start.verificationUri);
|
|
487
|
-
if (uri.origin
|
|
510
|
+
if (![issuer, officialTransport(issuer).origin].includes(uri.origin) || uri.pathname !== "/" || uri.username || uri.password || uri.searchParams.get("pair") !== start.pairingId) throw Error("Hub \u8FD4\u56DE\u7684\u914D\u5BF9\u5730\u5740\u4E0D\u5408\u6CD5");
|
|
488
511
|
const header = Buffer.from(JSON.stringify({ alg: "EdDSA" })).toString("base64url");
|
|
489
512
|
const payload = Buffer.from(JSON.stringify({ pairingId: start.pairingId, challenge: start.challenge, installationId, service: "starpost" })).toString("base64url");
|
|
490
513
|
const unsigned = `${header}.${payload}`, signature = sign(null, Buffer.from(unsigned), privateKey).toString("base64url");
|
|
491
514
|
await this.request(issuer, "/v1/pairings/prove", { pairingId: start.pairingId, pollingSecret: start.pollingSecret, signature: `${unsigned}.${signature}` });
|
|
492
515
|
if (revision !== this.revision) throw Error("\u914D\u5BF9\u5DF2\u53D6\u6D88");
|
|
493
|
-
this.save(this.pendingFile, { version: 1, issuer, server, installationId, deviceId, pairingId: start.pairingId, pollingSecret: start.pollingSecret, shortCode: start.shortCode, verificationUri: uri.href, expectedBotId, expiresAt: Date.now() + 3e5 });
|
|
516
|
+
this.save(this.pendingFile, { version: 1, issuer, server, installationId, deviceId, pairingId: start.pairingId, pollingSecret: start.pollingSecret, shortCode: start.shortCode, verificationUri: officialTransport(uri).href, expectedBotId, expiresAt: Date.now() + 3e5 });
|
|
494
517
|
return this.status();
|
|
495
518
|
} finally {
|
|
496
519
|
this.busy = false;
|
|
@@ -1081,7 +1104,7 @@ var StarpostWorld = class {
|
|
|
1081
1104
|
this.identityFile = join4(dataDir, "starpost-identity.json");
|
|
1082
1105
|
this.credentialFile = join4(dataDir, "starpost-credential.json");
|
|
1083
1106
|
this.releaseNoticeFile = join4(dataDir, "starpost-release-notice.json");
|
|
1084
|
-
this.hub = new HubAuth(dataDir, () => this.serverBase().origin, () => this.cfg.hubUrl ||
|
|
1107
|
+
this.hub = new HubAuth(dataDir, () => this.serverBase().origin, () => this.cfg.hubUrl || HUB_IP, postJson);
|
|
1085
1108
|
}
|
|
1086
1109
|
id = "starpost";
|
|
1087
1110
|
host = null;
|
|
@@ -1184,7 +1207,7 @@ var StarpostWorld = class {
|
|
|
1184
1207
|
this.credentialClaimed = true;
|
|
1185
1208
|
}
|
|
1186
1209
|
serverBase() {
|
|
1187
|
-
const base =
|
|
1210
|
+
const base = officialTransport(this.cfg.serverUrl);
|
|
1188
1211
|
if (!(base.protocol === "https:" || base.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(base.hostname)) || base.username || base.password || base.search || base.hash) throw new Error("\u661F\u90AE\u670D\u52A1\u5730\u5740\u987B\u4F7F\u7528 HTTPS\uFF1B\u672C\u673A\u56DE\u73AF\u5730\u5740\u53EF\u7528 HTTP");
|
|
1189
1212
|
return base;
|
|
1190
1213
|
}
|
|
@@ -1838,7 +1861,7 @@ var StarpostWorld = class {
|
|
|
1838
1861
|
webUi() {
|
|
1839
1862
|
const identity = this.activeIdentity();
|
|
1840
1863
|
const hub = this.hub.session();
|
|
1841
|
-
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 ${hub.issuer} \u7BA1\u7406\u3002` : identity ? `\u7ED1\u5B9A bot \u4F7F\u7528\u7684 ID\uFF1A${identity.botId}\u3000\u51ED\u636E\uFF1A${identity.token}\u3000\u8BF7\u52FF\u8F6C\u53D1\u51ED\u636E\u3002` : "\u6CE8\u518C\u540E\u5728\u6B64\u663E\u793A\u7ED1\u5B9A bot \u6240\u9700\u7684 ID \u4E0E\u51ED\u636E\u3002") + " \u5B98\u7F51\uFF1Ahttps://
|
|
1864
|
+
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 ? `\u7ED1\u5B9A bot \u4F7F\u7528\u7684 ID\uFF1A${identity.botId}\u3000\u51ED\u636E\uFF1A${identity.token}\u3000\u8BF7\u52FF\u8F6C\u53D1\u51ED\u636E\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" } };
|
|
1842
1865
|
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) => {
|
|
1843
1866
|
if (panel !== "viewer") throw new Error("\u672A\u77E5\u9762\u677F");
|
|
1844
1867
|
if (method === "hubStatus") return this.hub.status();
|
|
@@ -1863,7 +1886,7 @@ var StarpostWorld = class {
|
|
|
1863
1886
|
}
|
|
1864
1887
|
if (method === "mobileLoginInfo") {
|
|
1865
1888
|
const current = this.activeIdentity();
|
|
1866
|
-
return { botId: current?.botId ?? "", credential: this.hub.session() ? "" : current?.token ?? "", authMode: this.hub.session() ? "hub" : "legacy", hubUrl: this.cfg.hubUrl ||
|
|
1889
|
+
return { botId: current?.botId ?? "", credential: this.hub.session() ? "" : current?.token ?? "", authMode: this.hub.session() ? "hub" : "legacy", hubUrl: officialTransport(this.cfg.hubUrl || HUB_IP).origin, apkUrl: "https://8.148.13.225/downloads/starpost-android-1.15.1.apk" };
|
|
1867
1890
|
}
|
|
1868
1891
|
if (method === "teenControl") {
|
|
1869
1892
|
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");
|
|
@@ -2246,7 +2269,7 @@ ${active ? "\u4E3B\u52A8\u67E5\u770B\u6A21\u5F0F\uFF1A\u8FD9\u91CC\u53EA\u63D0\u
|
|
|
2246
2269
|
${data.text || ""}${voiceText ? "\n[\u8BED\u97F3\u8F6C\u5199\uFF0C\u5916\u90E8\u5185\u5BB9] " + voiceText : ""}${messageInfo.sticker ? `
|
|
2247
2270
|
[\u8868\u60C5\u5305:${messageInfo.sticker}]` : ""}
|
|
2248
2271
|
[\u6D88\u606F\u8BB0\u5F55] ${JSON.stringify({ id: data.id, ...data.senderTitle ? { senderTitle: data.senderTitle } : {}, quote: data.quote, forward: data.forward, recalled: data.recalled })}
|
|
2249
|
-
[\u661F\u90AE\u56DE\u590D\u5165\u53E3] \u6B64\u6D88\u606F\u6765\u81EA\
|
|
2272
|
+
[\u661F\u90AE\u56DE\u590D\u5165\u53E3] \u6B64\u6D88\u606F\u6765\u81EA\u661F\u90AE\u4E13\u5C5E bot \u9891\u9053\uFF08\u53EF\u4ECE\u661F\u90AE\u6216 CooDock \u53D1\u9001\uFF0C\u6765\u6E90\u89C1\u4E0A\u6587\uFF09\u3002\u56DE\u590D\u4F7F\u7528 starpost_use\uFF1Afamily="mobile"\uFF0Caction="send"\uFF0CargsJson \u4E3A\u5305\u542B text \u7684 JSON \u5B57\u7B26\u4E32\uFF1B\u65E0\u9700 target\uFF0C\u4E0D\u4F7F\u7528\u666E\u901A send/private\u3002\u666E\u901A\u6587\u672C\u8F93\u51FA\u4E0D\u4F1A\u53D1\u9001\u5230\u8BE5\u9891\u9053\u3002`;
|
|
2250
2273
|
const gameChat = ["game.public", "game.wolf", "game.outside"].includes(event.type) && data?.kind === "chat";
|
|
2251
2274
|
const message = event.type === "message" || gameChat;
|
|
2252
2275
|
if (ownerMessage) await this.flushNotifications("piggyback", true);
|
|
@@ -2300,10 +2323,11 @@ ${data.text || ""}${voiceText ? "\n[\u8BED\u97F3\u8F6C\u5199\uFF0C\u5916\u90E8\u
|
|
|
2300
2323
|
};
|
|
2301
2324
|
|
|
2302
2325
|
// <stdin>
|
|
2303
|
-
var relayVersion = "0.
|
|
2326
|
+
var relayVersion = "0.35.1";
|
|
2304
2327
|
export {
|
|
2305
2328
|
STARPOST_DEFAULTS,
|
|
2306
2329
|
STARPOST_TOOL_DECLS,
|
|
2307
2330
|
StarpostWorld,
|
|
2308
|
-
relayVersion
|
|
2331
|
+
relayVersion,
|
|
2332
|
+
starpostIdentityOrigin
|
|
2309
2333
|
};
|
package/package.json
CHANGED
|
@@ -1,14 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-plugin-starpost",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "星邮的 DeepSeek Harness bot
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "星邮的 DeepSeek Harness bot 客户端,提供本机 Web 配置、FFA Hub 配对、消息收发和折叠社交工具",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "./src/index.mjs",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./src/index.mjs",
|
|
10
|
+
"./client": "./web/client.js",
|
|
11
|
+
"./package.json": "./package.json",
|
|
12
|
+
"./*": "./*"
|
|
13
|
+
},
|
|
8
14
|
"bin": {
|
|
9
15
|
"starpost-dsh": "./src/account.mjs"
|
|
10
16
|
},
|
|
11
17
|
"dsh": {
|
|
18
|
+
"client": {
|
|
19
|
+
"platform": "web",
|
|
20
|
+
"inject": ["@deepseek-ai/dsh-client-ui-settings"]
|
|
21
|
+
},
|
|
12
22
|
"bundle": {
|
|
13
23
|
"patch": "./cordis.patch.yml"
|
|
14
24
|
}
|
|
@@ -19,6 +29,7 @@
|
|
|
19
29
|
},
|
|
20
30
|
"files": [
|
|
21
31
|
"src/*.mjs",
|
|
32
|
+
"web",
|
|
22
33
|
"lib",
|
|
23
34
|
"cordis.patch.yml",
|
|
24
35
|
"desktop.ps1",
|
|
@@ -35,12 +46,12 @@
|
|
|
35
46
|
},
|
|
36
47
|
"repository": {
|
|
37
48
|
"type": "git",
|
|
38
|
-
"url": "git+https://github.com/
|
|
49
|
+
"url": "git+https://github.com/insomnic-Evan/dsh-plugin-starpost.git"
|
|
39
50
|
},
|
|
40
51
|
"author": "hth768",
|
|
41
|
-
"homepage": "https://github.com/
|
|
52
|
+
"homepage": "https://github.com/insomnic-Evan/dsh-plugin-starpost#readme",
|
|
42
53
|
"bugs": {
|
|
43
|
-
"url": "https://github.com/
|
|
54
|
+
"url": "https://github.com/insomnic-Evan/dsh-plugin-starpost/issues"
|
|
44
55
|
},
|
|
45
56
|
"keywords": [
|
|
46
57
|
"deepseek-harness",
|
|
@@ -49,13 +60,13 @@
|
|
|
49
60
|
"bot",
|
|
50
61
|
"chat"
|
|
51
62
|
],
|
|
52
|
-
"starpostCoreVersion": "0.
|
|
63
|
+
"starpostCoreVersion": "0.35.1",
|
|
53
64
|
"devDependencies": {
|
|
54
65
|
"@deepseek-ai/dsh-agent-loop": "0.2.2-rc.1",
|
|
55
66
|
"@deepseek-ai/dsh-agent-loop-testkit": "0.2.2-rc.1",
|
|
56
67
|
"@deepseek-ai/dsh-llm": "0.2.2-rc.1",
|
|
57
68
|
"@deepseek-ai/dsh-tools": "0.2.2-rc.1",
|
|
58
|
-
"cortico-world-starpost": "0.
|
|
69
|
+
"cortico-world-starpost": "0.35.1",
|
|
59
70
|
"esbuild": "0.25.12"
|
|
60
71
|
},
|
|
61
72
|
"dependencies": {
|
package/src/index.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto';
|
|
|
3
3
|
import { readFileSync } from 'node:fs';
|
|
4
4
|
import { clientHome, clientVersions, loadSettings, makeWorld, options, lock } from './local.mjs';
|
|
5
5
|
import { Config, registerNotificationSettings } from './settings.mjs';
|
|
6
|
+
import { makePanel, panelHandler, panelPath } from './panel.mjs';
|
|
6
7
|
export { Config } from './settings.mjs';
|
|
7
8
|
import { STARPOST_TOOL_DECLS } from '../lib/core.mjs';
|
|
8
9
|
|
|
@@ -25,7 +26,7 @@ export function apply(ctx, entry = {}) {
|
|
|
25
26
|
attachments = scoped.attachments;
|
|
26
27
|
scoped.effect(() => () => { attachments = undefined; }, 'starpost.attachments');
|
|
27
28
|
});
|
|
28
|
-
let current, disposed = false, retired = Promise.resolve();
|
|
29
|
+
let current, disposed = false, retired = Promise.resolve(), offlineWork = Promise.resolve();
|
|
29
30
|
const declaration = STARPOST_TOOL_DECLS[0];
|
|
30
31
|
function attach(agent) {
|
|
31
32
|
if (disposed || !settings.sessionId || agent.id !== settings.sessionId || current?.agent === agent) return;
|
|
@@ -70,14 +71,14 @@ export function apply(ctx, entry = {}) {
|
|
|
70
71
|
}
|
|
71
72
|
}
|
|
72
73
|
};
|
|
73
|
-
client.ready = retired.then(async () => {
|
|
74
|
+
client.ready = Promise.all([retired,offlineWork]).then(async () => {
|
|
74
75
|
live();
|
|
75
76
|
client.unlock = lock(dir);
|
|
76
77
|
const effectiveSettings = { ...settings, ...notificationConfig() };
|
|
77
78
|
client.settings = options(effectiveSettings, dir);
|
|
78
79
|
client.world = makeWorld(dir,effectiveSettings);
|
|
79
80
|
const status = await client.world.webUi().invoke('viewer','status',[]);
|
|
80
|
-
if (!status.registered) throw Error('
|
|
81
|
+
if (!status.registered) throw Error('请在星邮设置页登录账号,或使用 starpost-dsh hub-login 配对。');
|
|
81
82
|
live();
|
|
82
83
|
client.tool = client.world.tools()[0];
|
|
83
84
|
agent.inject(notice(readFileSync(new URL('../lib/ENV_PROMPT.md',import.meta.url),'utf8')));
|
|
@@ -99,6 +100,52 @@ export function apply(ctx, entry = {}) {
|
|
|
99
100
|
});
|
|
100
101
|
return retired;
|
|
101
102
|
}
|
|
103
|
+
const optional = {};
|
|
104
|
+
for (const name of ['settings','sessionPersistence','sessionTitle','sessions']) {
|
|
105
|
+
ctx.inject([name], scoped => {
|
|
106
|
+
optional[name] = scoped[name];
|
|
107
|
+
scoped.effect(() => () => { delete optional[name]; }, 'starpost.panel.'+name);
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
ctx.inject(['webServer'], scoped => {
|
|
111
|
+
const starting = options({...settings,...notificationConfig()},dir);
|
|
112
|
+
const run = makePanel({
|
|
113
|
+
dir, entry:Config(entry), nativeSettings:()=>optional.settings,
|
|
114
|
+
runtime:()=>({sessionId:settings.sessionId, cfg:current?.settings ?? starting,
|
|
115
|
+
ready:Boolean(current?.tool && !current.error), error:current?.error?.message || ''}),
|
|
116
|
+
async sessions() {
|
|
117
|
+
const rows = new Map();
|
|
118
|
+
for (const s of await optional.sessionPersistence?.list() ?? []) {
|
|
119
|
+
if (s.origin !== 'subagent') rows.set(s.id,{id:s.id,title:s.title || s.agentPreset || ''});
|
|
120
|
+
}
|
|
121
|
+
for (const s of optional.sessions?.list() ?? []) {
|
|
122
|
+
if (s.meta?.origin === 'subagent') continue;
|
|
123
|
+
const title = optional.sessionTitle?.get(s)?.title;
|
|
124
|
+
rows.set(s.id,{id:s.id,title:title || rows.get(s.id)?.title || ''});
|
|
125
|
+
}
|
|
126
|
+
for (const agent of ctx.agents.list()) if (!rows.has(agent.id)) rows.set(agent.id,{id:agent.id,title:''});
|
|
127
|
+
return [...rows.values()];
|
|
128
|
+
},
|
|
129
|
+
async withWorld(task) {
|
|
130
|
+
let client, stopping;
|
|
131
|
+
do {
|
|
132
|
+
stopping=retired; client=current;
|
|
133
|
+
await Promise.all([stopping,client?.ready]);
|
|
134
|
+
} while (client!==current || stopping!==retired);
|
|
135
|
+
if (disposed) throw Error('星邮已停止');
|
|
136
|
+
if (client && client===current && client.unlock) {
|
|
137
|
+
const operation=Promise.resolve().then(()=>task(client.world));
|
|
138
|
+
client.work.add(operation);
|
|
139
|
+
try { return await operation; } finally { client.work.delete(operation); }
|
|
140
|
+
}
|
|
141
|
+
const release=lock(dir);
|
|
142
|
+
const operation=Promise.resolve().then(()=>task(makeWorld(dir,loadSettings(dir)))).finally(release);
|
|
143
|
+
offlineWork=operation.catch(()=>{});
|
|
144
|
+
return operation;
|
|
145
|
+
},
|
|
146
|
+
});
|
|
147
|
+
scoped.effect(()=>scoped.webServer.register({kind:'prefix',path:panelPath,handler:panelHandler(run)}),'starpost.panel.route');
|
|
148
|
+
});
|
|
102
149
|
const off = ctx.tools.register({
|
|
103
150
|
name:declaration.name,
|
|
104
151
|
description:declaration.description+' 用 client/status 查看当前 DSH 会话 ID 与绑定状态。',
|
|
@@ -133,6 +180,6 @@ export function apply(ctx, entry = {}) {
|
|
|
133
180
|
});
|
|
134
181
|
ctx.on('agent/created',({agent})=>attach(agent));
|
|
135
182
|
ctx.on('agent/disposed',({agent})=>detach(agent));
|
|
136
|
-
ctx.effect(() => async () => { disposed = true; off(); await detach(current?.agent); }, 'starpost.client');
|
|
183
|
+
ctx.effect(() => async () => { disposed = true; off(); await Promise.all([detach(current?.agent),offlineWork]); }, 'starpost.client');
|
|
137
184
|
for (const agent of ctx.agents.list()) attach(agent);
|
|
138
185
|
}
|
package/src/local.mjs
CHANGED
|
@@ -3,7 +3,8 @@ import { homedir } from 'node:os';
|
|
|
3
3
|
import { resolve, join } from 'node:path';
|
|
4
4
|
import { DatabaseSync } from 'node:sqlite';
|
|
5
5
|
import { randomUUID } from 'node:crypto';
|
|
6
|
-
import {
|
|
6
|
+
import { sections, readKey, setKey, check } from '../web/fields.mjs';
|
|
7
|
+
import { StarpostWorld, STARPOST_DEFAULTS, relayVersion, starpostIdentityOrigin } from '../lib/core.mjs';
|
|
7
8
|
|
|
8
9
|
export const clientVersions = Object.freeze({
|
|
9
10
|
pluginVersion: JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version,
|
|
@@ -39,11 +40,19 @@ export function options(settings, dir) {
|
|
|
39
40
|
cfg.serverUrl = url.origin;
|
|
40
41
|
cfg.hubUrl = settings.hubUrl ?? cfg.hubUrl;
|
|
41
42
|
const pin = join(dir, 'server-origin');
|
|
42
|
-
if (existsSync(pin) && readFileSync(pin, 'utf8') !== url.origin) throw Error('账号数据已绑定其他服务器,请为新服务器选择独立的数据目录');
|
|
43
|
+
if (existsSync(pin) && starpostIdentityOrigin(readFileSync(pin, 'utf8').trim()) !== starpostIdentityOrigin(url.origin)) throw Error('账号数据已绑定其他服务器,请为新服务器选择独立的数据目录');
|
|
43
44
|
cfg.receiveMode = settings.receiveMode ?? cfg.receiveMode;
|
|
44
45
|
if (!['active','mixed','passive'].includes(cfg.receiveMode)) throw Error('接收模式须为 active、mixed 或 passive');
|
|
45
46
|
cfg.notifications = notificationOptions(settings);
|
|
46
47
|
cfg.emojiDir = resolve(dir, settings.emojiDir || 'emoji');
|
|
48
|
+
for (const group of [sections.limits, sections.media]) {
|
|
49
|
+
for (const field of group.fields.filter(field => field.key.includes('.'))) {
|
|
50
|
+
const value = readKey(settings, field.key);
|
|
51
|
+
if (value === undefined) continue;
|
|
52
|
+
if (!check(field, value)) throw Error(field.label+' 设置无效');
|
|
53
|
+
setKey(cfg, field.key, value);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
47
56
|
if(settings.speech!==undefined){
|
|
48
57
|
if(!settings.speech||typeof settings.speech!=='object'||Array.isArray(settings.speech))throw Error('speech 须为配置对象');
|
|
49
58
|
for(const [key,value]of Object.entries(settings.speech)){
|
|
@@ -65,8 +74,10 @@ export function validateSettings(dir, settings) {
|
|
|
65
74
|
options(settings, dir);
|
|
66
75
|
if (typeof settings.sessionId !== 'string' || !settings.sessionId.trim() || settings.sessionId.length > 512 || /[\x00-\x1f\x7f]/.test(settings.sessionId)) throw Error('请指定有效的 DSH 会话 ID');
|
|
67
76
|
}
|
|
68
|
-
export function saveSettings(dir, settings) {
|
|
69
|
-
|
|
77
|
+
export function saveSettings(dir, settings, { allowUnbound = false } = {}) {
|
|
78
|
+
if (allowUnbound && settings.sessionId === undefined) options(settings, dir);
|
|
79
|
+
else validateSettings(dir,settings);
|
|
80
|
+
mkdirSync(dir,{recursive:true,mode:0o700});
|
|
70
81
|
const tmp = join(dir, randomUUID()+'.tmp');
|
|
71
82
|
writeFileSync(tmp, JSON.stringify(settings,null,2)+'\n', {mode:0o600});
|
|
72
83
|
renameSync(tmp,join(dir,'client.json'));
|
package/src/panel.mjs
ADDED
|
@@ -0,0 +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
|
+
}
|