pygmalion 0.1.4 → 0.1.6

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/src/web-server.js CHANGED
@@ -1,506 +1,506 @@
1
- /**
2
- * Pygmalion 管理网页(插件内置独立 HTTP 服务,修 D1/D3/D4)。
3
- *
4
- * 安全设计:
5
- * - 密码 scrypt 哈希 + 随机 salt(persona.hashPassword/verifyPassword);
6
- * - 登录会话 = 内存 token + httpOnly cookie(SameSite=Lax),不落 localStorage;
7
- * - 登录失败限流:同一 qq+IP 15 分钟内失败 5 次 → 锁定 15 分钟;
8
- * - CSRF:非 GET 请求必须带自定义头 x-pygmalion-csrf: 1(跨站表单/图片发不了);
9
- * - 监听默认 127.0.0.1(仅本机),公网部署配 0.0.0.0 + HTTPS 反向代理(见 docs/DEPLOY.md);
10
- * - 业务接口一律要求登录,且只返回「我」的数据(角色私有:owner=accountId)。
11
- *
12
- * 接口:
13
- * POST /api/session/register { qqNumber, password, displayName? }
14
- * POST /api/session/login { qqNumber, password }
15
- * POST /api/session/logout
16
- * GET /api/status → ok/dataRoot
17
- * GET /api/me → account + roles 列表(含绑定/机器人/脚本状态)
18
- * PUT /api/me { displayName?, currentPassword?, newPassword? }
19
- * POST /api/me/roles { persona 字段 } → 新建角色(自动归我)
20
- * GET /api/me/roles/<roleId> → 完整角色(persona/model/proactive/binding/bot/脚本状态)
21
- * PUT /api/me/roles/<roleId> { persona?, model?, proactive? }
22
- * DELETE /api/me/roles/<roleId> → 级联删除该角色的机器人
23
- * PUT /api/me/roles/<roleId>/bot { qqAppId, qqSecret?, sandbox?, withinChatWindowMs?, streaming? }
24
- * DELETE /api/me/roles/<roleId>/bot
25
- * POST /api/me/roles/<roleId>/reset-binding
26
- * GET /api/me/roles/<roleId>/life → 脚本监管:manifest + logs + backups + running 清单
27
- * GET /api/me/roles/<roleId>/life/log/<name> → 某次运行日志全文
28
- * GET /api/me/roles/<roleId>/life/script/<name> → 脚本源码
29
- * POST /api/me/roles/<roleId>/life/stop → 终止一个运行中脚本(body: { runId })
30
- */
31
- import { createServer } from 'node:http';
32
- import { readFile, readdir } from 'node:fs/promises';
33
- import { existsSync } from 'node:fs';
34
- import { join, extname } from 'node:path';
35
- import { fileURLToPath } from 'node:url';
36
- import path from 'node:path';
37
- import { listLifeScripts, listRunningLifeScripts, stopLifeScript, recoverLifeScripts, pruneDeadLifeScripts } from './agent-life.js';
38
- import { roleUsesCustomProvider } from './llm-provider.js';
39
-
40
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
41
- const PUBLIC_DIR = join(__dirname, 'web-public');
42
- const COOKIE_NAME = 'pygmalion_sid';
43
- const BODY_LIMIT = 1 * 1024 * 1024;
44
- const LOGIN_MAX_FAILS = 5;
45
- const LOGIN_LOCK_MS = 15 * 60 * 1000;
46
- const MIME = {
47
- '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
48
- '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml',
49
- '.png': 'image/png', '.ico': 'image/x-icon',
50
- };
51
-
52
- export function createWebServer(deps) {
53
- const { persona, log } = deps;
54
- // 自定义 LLM provider 注册服务(index.js 注入;缺省时保存模型不注册,功能照旧)。
55
- const llmProviders = deps.llmProviders;
56
- const host = deps.web?.host ?? '127.0.0.1';
57
- const port = (deps.web?.port === undefined || deps.web?.port === null || deps.web?.port === '')
58
- ? 4180 : Number(deps.web?.port);
59
- // botApi:{ list, upsertForRole, removeForRole, recordForRole, statusOf }(BotManager)。
60
- // 独立运行(无宿主)时读接口空转、写接口报不可用。
61
- const botApi = deps.botApi ?? {
62
- list: () => [], recordForRole: () => null, statusOf: () => ({ state: 'missing', detail: '' }),
63
- upsertForRole: async () => { throw new Error('bot 管理不可用(无 BotManager)'); },
64
- removeForRole: async () => {},
65
- };
66
- let server = null;
67
- let started = null;
68
-
69
- /** ip|qq → { fails, lockUntil },内存限流(重启清零,可接受)。 */
70
- const rate = new Map();
71
- function rateKey(ip, qq) { return `${ip}|${qq}`; }
72
- function isLocked(ip, qq) {
73
- const r = rate.get(rateKey(ip, qq));
74
- return r?.lockUntil && r.lockUntil > Date.now() ? r.lockUntil : 0;
75
- }
76
- function failLogin(ip, qq) {
77
- const k = rateKey(ip, qq);
78
- const r = rate.get(k) || { fails: 0, lockUntil: 0 };
79
- r.fails += 1;
80
- if (r.fails >= LOGIN_MAX_FAILS) { r.fails = 0; r.lockUntil = Date.now() + LOGIN_LOCK_MS; }
81
- rate.set(k, r);
82
- }
83
- function okLogin(ip, qq) { rate.delete(rateKey(ip, qq)); }
84
-
85
- function cookieOf(req) {
86
- const h = req.headers.cookie;
87
- if (typeof h !== 'string') return undefined;
88
- for (const part of h.split(';')) {
89
- const [k, ...v] = part.trim().split('=');
90
- if (k === COOKIE_NAME) return v.join('=');
91
- }
92
- return undefined;
93
- }
94
- function setCookie(res, token) {
95
- res.setHeader('set-cookie',
96
- `${COOKIE_NAME}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${Math.floor(persona.SESSION_TTL_MS / 1000)}`);
97
- }
98
- function clearCookie(res) {
99
- res.setHeader('set-cookie', `${COOKIE_NAME}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`);
100
- }
101
- function clientIp(req) {
102
- const f = req.headers['x-forwarded-for'];
103
- return typeof f === 'string' ? f.split(',')[0].trim() : (req.socket.remoteAddress || '?');
104
- }
105
-
106
- function sendJson(res, status, body) {
107
- res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
108
- res.end(JSON.stringify(body, null, 2));
109
- }
110
- function readBody(req) {
111
- return new Promise((resolve, reject) => {
112
- const chunks = []; let size = 0;
113
- req.on('data', (c) => {
114
- size += c.length;
115
- if (size > BODY_LIMIT) { reject(new Error('body too large')); req.destroy(); return; }
116
- chunks.push(c);
117
- });
118
- req.on('end', () => {
119
- try { resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}); }
120
- catch { reject(new Error('invalid json')); }
121
- });
122
- req.on('error', reject);
123
- });
124
- }
125
- /** CSRF 校验:非 GET 的 /api 请求必须带自定义头。 */
126
- function csrfOk(req) {
127
- if (req.method === 'GET') return true;
128
- return req.headers['x-pygmalion-csrf'] === '1';
129
- }
130
- async function serveStatic(pathname, res) {
131
- const safe = pathname === '/' ? 'index.html' : pathname.slice(1).replace(/\.\./g, '');
132
- const file = join(PUBLIC_DIR, safe);
133
- if (!file.startsWith(PUBLIC_DIR) || !existsSync(file)) {
134
- res.writeHead(404, { 'content-type': 'text/html; charset=utf-8' });
135
- res.end('Not Found');
136
- return;
137
- }
138
- const ext = extname(file).toLowerCase();
139
- const mime = MIME[ext] || 'application/octet-stream';
140
- res.writeHead(200, { 'content-type': `${mime}; charset=utf-8`, 'cache-control': 'no-store' });
141
- res.end(await readFile(file));
142
- }
143
-
144
- /** 角色是否归 me(私有)。 */
145
- function ownedBy(role, me) {
146
- return role?.persona?.owner === me;
147
- }
148
- /** 该角色的机器人配置摘要(botId/roleId 为内部标识,不在界面展示)。 */
149
- function roleBot(roleId) {
150
- const bot = botApi.recordForRole(roleId);
151
- if (!bot) return { configured: false };
152
- return {
153
- configured: true,
154
- botId: bot.botId,
155
- qqAppId: bot.qqAppId,
156
- sandbox: bot.sandbox,
157
- withinChatWindowMs: bot.withinChatWindowMs,
158
- streaming: bot.streaming,
159
- httpApiPath: bot.httpApiPath,
160
- httpApiToken: bot.httpApiToken,
161
- enabled: bot.enabled,
162
- httpApiUnavailable: bot.httpApiUnavailable,
163
- status: bot.status,
164
- };
165
- }
166
- async function publicRole(role) {
167
- // 先恢复 dsh 重启前的运行表,runningCount 才准确。
168
- await recoverLifeScripts(role.workspace);
169
- await pruneDeadLifeScripts(role.workspace);
170
- return {
171
- roleId: role.roleId,
172
- persona: role.persona,
173
- model: role.model,
174
- proactive: role.proactive,
175
- binding: role.binding,
176
- bot: roleBot(role.roleId),
177
- life: {
178
- hasScript: (await listLifeScripts(role.workspace)).length > 0,
179
- runningCount: listRunningLifeScripts(role.workspace).length,
180
- },
181
- };
182
- }
183
- async function lifeStatus(roleId) {
184
- const role = await persona.loadRole(roleId);
185
- if (!role) return null;
186
- await recoverLifeScripts(role.workspace);
187
- await pruneDeadLifeScripts(role.workspace);
188
- const lifeDir = join(role.workspace, 'life');
189
- const manifest = await readFile(join(lifeDir, '.manifest.json'), 'utf8').then(JSON.parse).catch(() => ({}));
190
- const logs = await readdir(join(lifeDir, '.logs')).then((a) => a.sort().reverse()).catch(() => []);
191
- const backups = await readdir(join(lifeDir, '.backup')).then((a) => a.sort().reverse()).catch(() => []);
192
- return { manifest, logs: logs.slice(0, 50), backups: backups.slice(0, 50), running: listRunningLifeScripts(role.workspace) };
193
- }
194
- /** 安全化角色 id 参数(防路径穿越)。 */
195
- function roleParam(raw) {
196
- const rid = String(raw ?? '');
197
- return /^[A-Za-z0-9._-]+$/.test(rid) ? rid : null;
198
- }
199
- function logFileNameParam(raw) {
200
- const n = String(raw ?? '');
201
- return /^[\w.-]+\.log$/.test(n) && n !== '..' && !n.includes('/') && !n.includes('\\') ? n : null;
202
- }
203
- function scriptFileNameParam(raw) {
204
- const n = String(raw ?? '');
205
- // 排除法:允许中文等任意文件名,只禁路径分隔与 Windows 非法字符(防穿越)
206
- return /^[^/\\\x00-\x1f<>:"|?*]+\.(mjs|js|py|ts)$/.test(n) ? n : null;
207
- }
208
-
209
- async function requireAccount(req, res) {
210
- const token = cookieOf(req);
211
- const session = token ? persona.getSession(token) : null;
212
- if (!session) { sendJson(res, 401, { ok: false, error: '未登录或会话失效' }); return null; }
213
- const account = await persona.loadAccount(session.accountId);
214
- if (!account) { sendJson(res, 401, { ok: false, error: '账号不存在' }); return null; }
215
- return account;
216
- }
217
-
218
- function normalizePersona(b) {
219
- const p = (b?.persona && typeof b.persona === 'object') ? b.persona : b ?? {};
220
- const schedule = {};
221
- if (p.schedule && typeof p.schedule === 'object')
222
- for (const [k, v] of Object.entries(p.schedule)) if (String(v).trim()) schedule[String(k).trim()] = String(v).trim();
223
- return {
224
- name: String(p.name ?? '').trim() || undefined,
225
- age: String(p.age ?? '').trim() || undefined,
226
- avatarHint: String(p.avatarHint ?? '').trim() || undefined,
227
- personality: String(p.personality ?? '').trim() || undefined,
228
- backstory: String(p.backstory ?? '').trim() || undefined,
229
- speakingStyle: String(p.speakingStyle ?? '').trim() || undefined,
230
- relationship: String(p.relationship ?? '').trim() || undefined,
231
- schedule,
232
- };
233
- }
234
-
235
- /**
236
- * 应用 model/proactive patch 并同步自定义 provider(POST 新建与 PUT 编辑共用)。
237
- * model 保存时去掉空值键(清空的字段等同不配置);provider 留空由 providerRoute
238
- * 自动按 apiUrl 派生。返回聚合后的最新 role。
239
- */
240
- async function applyModelProactive(rid, patch) {
241
- if (patch.model !== undefined) {
242
- await persona.saveRoleField(rid, 'model', Object.fromEntries(Object.entries(patch.model ?? {}).filter(([, v]) => String(v ?? '').trim())));
243
- }
244
- if (patch.proactive !== undefined) {
245
- await persona.saveRoleField(rid, 'proactive', { ...persona.DEFAULT_PROACTIVE, ...patch.proactive });
246
- }
247
- const updated = await persona.loadRole(rid);
248
- await persona.syncRoleMemory(updated);
249
- if (llmProviders) {
250
- try {
251
- if (roleUsesCustomProvider(updated)) await llmProviders.register(updated);
252
- else await llmProviders.unregister(updated);
253
- } catch (e) { log?.warn?.('pygmalion: 同步自定义 provider %s 失败 %o', rid, e); }
254
- }
255
- return updated;
256
- }
257
-
258
- const handler = async (req, res) => {
259
- const url = new URL(req.url ?? '/', `http://${host}`);
260
- const pathname = url.pathname;
261
- try {
262
- // 静态页(无需登录;页面本身不含敏感数据)——/api/ 一律走 API 分发,
263
- // 防 API 路径以 .mjs/.js/.css 等静态后缀结尾时被这里误拦(如 /life/script/x.mjs)。
264
- if (req.method === 'GET' && !pathname.startsWith('/api/') && (pathname === '/' || /\.(html|mjs|js|css|json|svg|png|ico)$/.test(pathname) || pathname.startsWith('/public'))) {
265
- await serveStatic(pathname, res);
266
- return;
267
- }
268
- if (!csrfOk(req)) { sendJson(res, 403, { ok: false, error: 'CSRF 校验失败' }); return; }
269
-
270
- if (pathname === '/api/status' && req.method === 'GET') {
271
- sendJson(res, 200, { ok: true, dataRoot: persona.dataRoot() });
272
- return;
273
- }
274
-
275
- // ---- 会话(无需登录)----
276
- if (pathname === '/api/session/register' && req.method === 'POST') {
277
- const b = await readBody(req);
278
- const qq = String(b.qqNumber ?? '').trim(), password = String(b.password ?? '');
279
- if (!/^\d{5,}$/.test(qq)) { sendJson(res, 400, { ok: false, error: 'QQ 号应为至少 5 位数字' }); return; }
280
- if (password.length < 6) { sendJson(res, 400, { ok: false, error: '密码至少 6 位' }); return; }
281
- if (await persona.loadAccount(qq)) { sendJson(res, 409, { ok: false, error: '该 QQ 已注册' }); return; }
282
- await persona.createAccount({ qqNumber: qq, password, displayName: String(b.displayName ?? '').trim() || undefined });
283
- const token = persona.createSession(qq);
284
- setCookie(res, token);
285
- sendJson(res, 200, { ok: true, account: publicMe(await persona.loadAccount(qq)) });
286
- return;
287
- }
288
- if (pathname === '/api/session/login' && req.method === 'POST') {
289
- const b = await readBody(req);
290
- const qq = String(b.qqNumber ?? '').trim(), password = String(b.password ?? '');
291
- const ip = clientIp(req);
292
- const lock = isLocked(ip, qq);
293
- if (lock) { sendJson(res, 429, { ok: false, error: `登录失败次数过多,请 ${Math.ceil((lock - Date.now()) / 60000)} 分钟后重试` }); return; }
294
- const account = await persona.authenticate(qq, password);
295
- if (!account) {
296
- failLogin(ip, qq);
297
- sendJson(res, 401, { ok: false, error: 'QQ 号或密码错误' });
298
- return;
299
- }
300
- okLogin(ip, qq);
301
- const token = persona.createSession(qq);
302
- setCookie(res, token);
303
- sendJson(res, 200, { ok: true, account: publicMe(account) });
304
- return;
305
- }
306
- if (pathname === '/api/session/logout' && req.method === 'POST') {
307
- const token = cookieOf(req);
308
- if (token) persona.destroySession(token);
309
- clearCookie(res);
310
- sendJson(res, 200, { ok: true });
311
- return;
312
- }
313
-
314
- // ---- 业务(需登录)----
315
- const me = await requireAccount(req, res);
316
- if (!me) return;
317
-
318
- function publicMe(a) {
319
- return {
320
- qqNumber: a.qqNumber,
321
- displayName: a.displayName ?? '',
322
- roleIds: a.roleIds ?? [],
323
- };
324
- }
325
-
326
- if (pathname === '/api/me' && req.method === 'GET') {
327
- const roles = [];
328
- for (const rid of me.roleIds ?? []) {
329
- const role = await persona.loadRole(rid);
330
- if (role) roles.push(await publicRole(role));
331
- }
332
- sendJson(res, 200, { ok: true, account: publicMe(me), roles });
333
- return;
334
- }
335
- if (pathname === '/api/me' && req.method === 'PUT') {
336
- const b = await readBody(req);
337
- const next = { ...me };
338
- if (b.displayName !== undefined) next.displayName = String(b.displayName).trim();
339
- if (b.newPassword !== undefined) {
340
- if (String(b.newPassword).length < 6) { sendJson(res, 400, { ok: false, error: '新密码至少 6 位' }); return; }
341
- if (!persona.verifyPassword(String(b.currentPassword ?? ''), { hash: me.passwordHash, salt: me.salt })) {
342
- sendJson(res, 403, { ok: false, error: '当前密码不正确' }); return;
343
- }
344
- const { hash, salt } = persona.hashPassword(String(b.newPassword));
345
- next.passwordHash = hash; next.salt = salt;
346
- }
347
- await persona.saveAccount(next);
348
- sendJson(res, 200, { ok: true, account: publicMe(next) });
349
- return;
350
- }
351
-
352
- // ---- 我的角色 ----
353
- if (pathname === '/api/me/roles' && req.method === 'POST') {
354
- const b = await readBody(req);
355
- const personaFields = normalizePersona(b);
356
- if (!personaFields.name) { sendJson(res, 400, { ok: false, error: '请填写角色名' }); return; }
357
- const roleId = await persona.createRole({ accountId: me.qqNumber, persona: personaFields });
358
- // 首次保存同样落 model/proactive(修:新建角色一次保存即生效,而非只有再编辑才存)。
359
- const role = await applyModelProactive(roleId, b ?? {});
360
- sendJson(res, 200, { ok: true, roleId, role: await publicRole(role) });
361
- return;
362
- }
363
-
364
- const pm = /^\/api\/me\/roles\/([^/]+)$/.exec(pathname);
365
- if (pm) {
366
- const rid = roleParam(pm[1]);
367
- if (!rid) { sendJson(res, 400, { ok: false, error: '角色 ID 非法' }); return; }
368
- const role = await persona.loadRole(rid);
369
- if (!role || !ownedBy(role, me.qqNumber)) { sendJson(res, 404, { ok: false, error: '角色不存在' }); return; }
370
- if (req.method === 'GET') { sendJson(res, 200, { ok: true, role: await publicRole(role) }); return; }
371
- if (req.method === 'PUT') {
372
- const b = await readBody(req);
373
- const patch = b ?? {};
374
- if (patch.persona !== undefined) {
375
- const p = normalizePersona({ persona: patch.persona });
376
- p.owner = me.qqNumber;
377
- await persona.saveRoleField(rid, 'persona', p);
378
- }
379
- const updated = await applyModelProactive(rid, patch);
380
- sendJson(res, 200, { ok: true, role: await publicRole(updated) });
381
- return;
382
- }
383
- if (req.method === 'DELETE') {
384
- if (llmProviders) {
385
- try { await llmProviders.unregister(role); } catch (e) { log?.warn?.('pygmalion: 注销自定义 provider %s 失败 %o', rid, e); }
386
- }
387
- await botApi.removeForRole(rid);
388
- await persona.deleteRole(rid);
389
- sendJson(res, 200, { ok: true, deleted: rid });
390
- return;
391
- }
392
- sendJson(res, 405, { ok: false, error: 'method not allowed' });
393
- return;
394
- }
395
-
396
- // 我的角色的 QQ 机器人(凭据仅角色 owner 可配;qqSecret 不回传,空留=保持原值)。
397
- const pBot = /^\/api\/me\/roles\/([^/]+)\/bot$/.exec(pathname);
398
- if (pBot) {
399
- const rid = roleParam(pBot[1]);
400
- if (!rid) { sendJson(res, 400, { ok: false, error: '角色 ID 非法' }); return; }
401
- const role = await persona.loadRole(rid);
402
- if (!role || !ownedBy(role, me.qqNumber)) { sendJson(res, 404, { ok: false, error: '角色不存在' }); return; }
403
- if (req.method === 'PUT') {
404
- const b = await readBody(req);
405
- try {
406
- await botApi.upsertForRole(rid, { ...(b ?? {}), owner: me.qqNumber });
407
- sendJson(res, 200, { ok: true, bot: roleBot(rid) });
408
- } catch (e) {
409
- sendJson(res, 400, { ok: false, error: String(e?.message ?? e) });
410
- }
411
- return;
412
- }
413
- if (req.method === 'DELETE') {
414
- await botApi.removeForRole(rid);
415
- sendJson(res, 200, { ok: true });
416
- return;
417
- }
418
- sendJson(res, 405, { ok: false, error: 'method not allowed' });
419
- return;
420
- }
421
-
422
- const pReset = /^\/api\/me\/roles\/([^/]+)\/reset-binding$/.exec(pathname);
423
- if (pReset && req.method === 'POST') {
424
- const rid = roleParam(pReset[1]);
425
- if (!rid) { sendJson(res, 400, { ok: false, error: '角色 ID 非法' }); return; }
426
- const role = await persona.loadRole(rid);
427
- if (!role || !ownedBy(role, me.qqNumber)) { sendJson(res, 404, { ok: false, error: '角色不存在' }); return; }
428
- const updated = await persona.resetRoleBinding(rid);
429
- sendJson(res, 200, { ok: true, role: await publicRole(updated) });
430
- return;
431
- }
432
-
433
- const pLifeStop = /^\/api\/me\/roles\/([^/]+)\/life\/stop$/.exec(pathname);
434
- if (pLifeStop && req.method === 'POST') {
435
- const rid = roleParam(pLifeStop[1]);
436
- if (!rid) { sendJson(res, 400, { ok: false, error: '角色 ID 非法' }); return; }
437
- const role = await persona.loadRole(rid);
438
- if (!role || !ownedBy(role, me.qqNumber)) { sendJson(res, 404, { ok: false, error: '角色不存在' }); return; }
439
- const b = await readBody(req);
440
- const runId = String(b?.runId ?? '').trim();
441
- if (!runId) { sendJson(res, 400, { ok: false, error: '缺少 runId' }); return; }
442
- sendJson(res, 200, await stopLifeScript(runId));
443
- return;
444
- }
445
-
446
- const pLife = /^\/api\/me\/roles\/([^/]+)\/life(?:\/(script|log)\/([^/]+))?$/.exec(pathname);
447
- if (pLife) {
448
- const rid = roleParam(pLife[1]);
449
- if (!rid) { sendJson(res, 400, { ok: false, error: '角色 ID 非法' }); return; }
450
- const role = await persona.loadRole(rid);
451
- if (!role || !ownedBy(role, me.qqNumber)) { sendJson(res, 404, { ok: false, error: '角色不存在' }); return; }
452
- if (req.method !== 'GET') { sendJson(res, 405, { ok: false, error: 'method not allowed' }); return; }
453
- if (pLife[2]) {
454
- // pathname 保留百分号编码;解码后交由白名单校验(含中文脚本名,%2e%2e 还原成穿越路径会被拒)
455
- let rawName = '';
456
- try { rawName = decodeURIComponent(pLife[3]); } catch { /* 非法 % 序列 → 校验拒绝 */ }
457
- const name = pLife[2] === 'log' ? logFileNameParam(rawName) : scriptFileNameParam(rawName);
458
- if (!name) { sendJson(res, 400, { ok: false, error: pLife[2] === 'log' ? '日志名非法' : '脚本名非法' }); return; }
459
- const file = pLife[2] === 'log'
460
- ? join(role.workspace, 'life', '.logs', name)
461
- : join(role.workspace, 'life', name);
462
- const base = pLife[2] === 'log'
463
- ? join(role.workspace, 'life', '.logs')
464
- : join(role.workspace, 'life');
465
- if (!file.startsWith(base)) { sendJson(res, 400, { ok: false, error: '路径非法' }); return; }
466
- const text = await readFile(file, 'utf8').catch(() => null);
467
- if (text === null) { sendJson(res, 404, { ok: false, error: pLife[2] === 'log' ? '日志不存在' : '脚本不存在' }); return; }
468
- res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
469
- res.end(text);
470
- return;
471
- }
472
- sendJson(res, 200, { ok: true, ...(await lifeStatus(rid)) });
473
- return;
474
- }
475
-
476
- sendJson(res, 404, { ok: false, error: `not found: ${pathname}` });
477
- } catch (e) {
478
- log?.error?.('web-server error: %o', e);
479
- if (!res.headersSent) sendJson(res, 500, { ok: false, error: String(e?.message ?? e) });
480
- }
481
- };
482
-
483
- return {
484
- async start() {
485
- if (server) return started;
486
- server = createServer(handler);
487
- await new Promise((resolve, reject) => {
488
- server.once('error', reject);
489
- server.listen(port, host, () => resolve());
490
- });
491
- const addr = server.address();
492
- const actualPort = addr && typeof addr === 'object' ? addr.port : port;
493
- started = { host, port: actualPort };
494
- log?.info?.('pygmalion web 管理网页已启动: http://%s:%d', host, actualPort);
495
- return started;
496
- },
497
- async stop() {
498
- if (!server) return;
499
- const s = server; server = null;
500
- await new Promise((resolve) => s.close(() => resolve()));
501
- },
502
- };
503
- }
504
-
505
- // 便捷导出:独立运行入口(调试用,正常由插件 index.js 挂载)
506
- export const webServerDefault = createWebServer;
1
+ /**
2
+ * Pygmalion 管理网页(插件内置独立 HTTP 服务,修 D1/D3/D4)。
3
+ *
4
+ * 安全设计:
5
+ * - 密码 scrypt 哈希 + 随机 salt(persona.hashPassword/verifyPassword);
6
+ * - 登录会话 = 内存 token + httpOnly cookie(SameSite=Lax),不落 localStorage;
7
+ * - 登录失败限流:同一 qq+IP 15 分钟内失败 5 次 → 锁定 15 分钟;
8
+ * - CSRF:非 GET 请求必须带自定义头 x-pygmalion-csrf: 1(跨站表单/图片发不了);
9
+ * - 监听默认 127.0.0.1(仅本机),公网部署配 0.0.0.0 + HTTPS 反向代理(见 docs/DEPLOY.md);
10
+ * - 业务接口一律要求登录,且只返回「我」的数据(角色私有:owner=accountId)。
11
+ *
12
+ * 接口:
13
+ * POST /api/session/register { qqNumber, password, displayName? }
14
+ * POST /api/session/login { qqNumber, password }
15
+ * POST /api/session/logout
16
+ * GET /api/status → ok/dataRoot
17
+ * GET /api/me → account + roles 列表(含绑定/机器人/脚本状态)
18
+ * PUT /api/me { displayName?, currentPassword?, newPassword? }
19
+ * POST /api/me/roles { persona 字段 } → 新建角色(自动归我)
20
+ * GET /api/me/roles/<roleId> → 完整角色(persona/model/proactive/binding/bot/脚本状态)
21
+ * PUT /api/me/roles/<roleId> { persona?, model?, proactive? }
22
+ * DELETE /api/me/roles/<roleId> → 级联删除该角色的机器人
23
+ * PUT /api/me/roles/<roleId>/bot { qqAppId, qqSecret?, sandbox?, withinChatWindowMs?, streaming? }
24
+ * DELETE /api/me/roles/<roleId>/bot
25
+ * POST /api/me/roles/<roleId>/reset-binding
26
+ * GET /api/me/roles/<roleId>/life → 脚本监管:manifest + logs + backups + running 清单
27
+ * GET /api/me/roles/<roleId>/life/log/<name> → 某次运行日志全文
28
+ * GET /api/me/roles/<roleId>/life/script/<name> → 脚本源码
29
+ * POST /api/me/roles/<roleId>/life/stop → 终止一个运行中脚本(body: { runId })
30
+ */
31
+ import { createServer } from 'node:http';
32
+ import { readFile, readdir } from 'node:fs/promises';
33
+ import { existsSync } from 'node:fs';
34
+ import { join, extname } from 'node:path';
35
+ import { fileURLToPath } from 'node:url';
36
+ import path from 'node:path';
37
+ import { listLifeScripts, listRunningLifeScripts, stopLifeScript, recoverLifeScripts, pruneDeadLifeScripts } from './agent-life.js';
38
+ import { roleUsesCustomProvider } from './llm-provider.js';
39
+
40
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
41
+ const PUBLIC_DIR = join(__dirname, 'web-public');
42
+ const COOKIE_NAME = 'pygmalion_sid';
43
+ const BODY_LIMIT = 1 * 1024 * 1024;
44
+ const LOGIN_MAX_FAILS = 5;
45
+ const LOGIN_LOCK_MS = 15 * 60 * 1000;
46
+ const MIME = {
47
+ '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
48
+ '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml',
49
+ '.png': 'image/png', '.ico': 'image/x-icon',
50
+ };
51
+
52
+ export function createWebServer(deps) {
53
+ const { persona, log } = deps;
54
+ // 自定义 LLM provider 注册服务(index.js 注入;缺省时保存模型不注册,功能照旧)。
55
+ const llmProviders = deps.llmProviders;
56
+ const host = deps.web?.host ?? '127.0.0.1';
57
+ const port = (deps.web?.port === undefined || deps.web?.port === null || deps.web?.port === '')
58
+ ? 4180 : Number(deps.web?.port);
59
+ // botApi:{ list, upsertForRole, removeForRole, recordForRole, statusOf }(BotManager)。
60
+ // 独立运行(无宿主)时读接口空转、写接口报不可用。
61
+ const botApi = deps.botApi ?? {
62
+ list: () => [], recordForRole: () => null, statusOf: () => ({ state: 'missing', detail: '' }),
63
+ upsertForRole: async () => { throw new Error('bot 管理不可用(无 BotManager)'); },
64
+ removeForRole: async () => {},
65
+ };
66
+ let server = null;
67
+ let started = null;
68
+
69
+ /** ip|qq → { fails, lockUntil },内存限流(重启清零,可接受)。 */
70
+ const rate = new Map();
71
+ function rateKey(ip, qq) { return `${ip}|${qq}`; }
72
+ function isLocked(ip, qq) {
73
+ const r = rate.get(rateKey(ip, qq));
74
+ return r?.lockUntil && r.lockUntil > Date.now() ? r.lockUntil : 0;
75
+ }
76
+ function failLogin(ip, qq) {
77
+ const k = rateKey(ip, qq);
78
+ const r = rate.get(k) || { fails: 0, lockUntil: 0 };
79
+ r.fails += 1;
80
+ if (r.fails >= LOGIN_MAX_FAILS) { r.fails = 0; r.lockUntil = Date.now() + LOGIN_LOCK_MS; }
81
+ rate.set(k, r);
82
+ }
83
+ function okLogin(ip, qq) { rate.delete(rateKey(ip, qq)); }
84
+
85
+ function cookieOf(req) {
86
+ const h = req.headers.cookie;
87
+ if (typeof h !== 'string') return undefined;
88
+ for (const part of h.split(';')) {
89
+ const [k, ...v] = part.trim().split('=');
90
+ if (k === COOKIE_NAME) return v.join('=');
91
+ }
92
+ return undefined;
93
+ }
94
+ function setCookie(res, token) {
95
+ res.setHeader('set-cookie',
96
+ `${COOKIE_NAME}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${Math.floor(persona.SESSION_TTL_MS / 1000)}`);
97
+ }
98
+ function clearCookie(res) {
99
+ res.setHeader('set-cookie', `${COOKIE_NAME}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`);
100
+ }
101
+ function clientIp(req) {
102
+ const f = req.headers['x-forwarded-for'];
103
+ return typeof f === 'string' ? f.split(',')[0].trim() : (req.socket.remoteAddress || '?');
104
+ }
105
+
106
+ function sendJson(res, status, body) {
107
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
108
+ res.end(JSON.stringify(body, null, 2));
109
+ }
110
+ function readBody(req) {
111
+ return new Promise((resolve, reject) => {
112
+ const chunks = []; let size = 0;
113
+ req.on('data', (c) => {
114
+ size += c.length;
115
+ if (size > BODY_LIMIT) { reject(new Error('body too large')); req.destroy(); return; }
116
+ chunks.push(c);
117
+ });
118
+ req.on('end', () => {
119
+ try { resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}); }
120
+ catch { reject(new Error('invalid json')); }
121
+ });
122
+ req.on('error', reject);
123
+ });
124
+ }
125
+ /** CSRF 校验:非 GET 的 /api 请求必须带自定义头。 */
126
+ function csrfOk(req) {
127
+ if (req.method === 'GET') return true;
128
+ return req.headers['x-pygmalion-csrf'] === '1';
129
+ }
130
+ async function serveStatic(pathname, res) {
131
+ const safe = pathname === '/' ? 'index.html' : pathname.slice(1).replace(/\.\./g, '');
132
+ const file = join(PUBLIC_DIR, safe);
133
+ if (!file.startsWith(PUBLIC_DIR) || !existsSync(file)) {
134
+ res.writeHead(404, { 'content-type': 'text/html; charset=utf-8' });
135
+ res.end('Not Found');
136
+ return;
137
+ }
138
+ const ext = extname(file).toLowerCase();
139
+ const mime = MIME[ext] || 'application/octet-stream';
140
+ res.writeHead(200, { 'content-type': `${mime}; charset=utf-8`, 'cache-control': 'no-store' });
141
+ res.end(await readFile(file));
142
+ }
143
+
144
+ /** 角色是否归 me(私有)。 */
145
+ function ownedBy(role, me) {
146
+ return role?.persona?.owner === me;
147
+ }
148
+ /** 该角色的机器人配置摘要(botId/roleId 为内部标识,不在界面展示)。 */
149
+ function roleBot(roleId) {
150
+ const bot = botApi.recordForRole(roleId);
151
+ if (!bot) return { configured: false };
152
+ return {
153
+ configured: true,
154
+ botId: bot.botId,
155
+ qqAppId: bot.qqAppId,
156
+ sandbox: bot.sandbox,
157
+ withinChatWindowMs: bot.withinChatWindowMs,
158
+ streaming: bot.streaming,
159
+ httpApiPath: bot.httpApiPath,
160
+ httpApiToken: bot.httpApiToken,
161
+ enabled: bot.enabled,
162
+ httpApiUnavailable: bot.httpApiUnavailable,
163
+ status: bot.status,
164
+ };
165
+ }
166
+ async function publicRole(role) {
167
+ // 先恢复 dsh 重启前的运行表,runningCount 才准确。
168
+ await recoverLifeScripts(role.workspace);
169
+ await pruneDeadLifeScripts(role.workspace);
170
+ return {
171
+ roleId: role.roleId,
172
+ persona: role.persona,
173
+ model: role.model,
174
+ proactive: role.proactive,
175
+ binding: role.binding,
176
+ bot: roleBot(role.roleId),
177
+ life: {
178
+ hasScript: (await listLifeScripts(role.workspace)).length > 0,
179
+ runningCount: listRunningLifeScripts(role.workspace).length,
180
+ },
181
+ };
182
+ }
183
+ async function lifeStatus(roleId) {
184
+ const role = await persona.loadRole(roleId);
185
+ if (!role) return null;
186
+ await recoverLifeScripts(role.workspace);
187
+ await pruneDeadLifeScripts(role.workspace);
188
+ const lifeDir = join(role.workspace, 'life');
189
+ const manifest = await readFile(join(lifeDir, '.manifest.json'), 'utf8').then(JSON.parse).catch(() => ({}));
190
+ const logs = await readdir(join(lifeDir, '.logs')).then((a) => a.sort().reverse()).catch(() => []);
191
+ const backups = await readdir(join(lifeDir, '.backup')).then((a) => a.sort().reverse()).catch(() => []);
192
+ return { manifest, logs: logs.slice(0, 50), backups: backups.slice(0, 50), running: listRunningLifeScripts(role.workspace) };
193
+ }
194
+ /** 安全化角色 id 参数(防路径穿越)。 */
195
+ function roleParam(raw) {
196
+ const rid = String(raw ?? '');
197
+ return /^[A-Za-z0-9._-]+$/.test(rid) ? rid : null;
198
+ }
199
+ function logFileNameParam(raw) {
200
+ const n = String(raw ?? '');
201
+ return /^[\w.-]+\.log$/.test(n) && n !== '..' && !n.includes('/') && !n.includes('\\') ? n : null;
202
+ }
203
+ function scriptFileNameParam(raw) {
204
+ const n = String(raw ?? '');
205
+ // 排除法:允许中文等任意文件名,只禁路径分隔与 Windows 非法字符(防穿越)
206
+ return /^[^/\\\x00-\x1f<>:"|?*]+\.(mjs|js|py|ts)$/.test(n) ? n : null;
207
+ }
208
+
209
+ async function requireAccount(req, res) {
210
+ const token = cookieOf(req);
211
+ const session = token ? persona.getSession(token) : null;
212
+ if (!session) { sendJson(res, 401, { ok: false, error: '未登录或会话失效' }); return null; }
213
+ const account = await persona.loadAccount(session.accountId);
214
+ if (!account) { sendJson(res, 401, { ok: false, error: '账号不存在' }); return null; }
215
+ return account;
216
+ }
217
+
218
+ function normalizePersona(b) {
219
+ const p = (b?.persona && typeof b.persona === 'object') ? b.persona : b ?? {};
220
+ const schedule = {};
221
+ if (p.schedule && typeof p.schedule === 'object')
222
+ for (const [k, v] of Object.entries(p.schedule)) if (String(v).trim()) schedule[String(k).trim()] = String(v).trim();
223
+ return {
224
+ name: String(p.name ?? '').trim() || undefined,
225
+ age: String(p.age ?? '').trim() || undefined,
226
+ avatarHint: String(p.avatarHint ?? '').trim() || undefined,
227
+ personality: String(p.personality ?? '').trim() || undefined,
228
+ backstory: String(p.backstory ?? '').trim() || undefined,
229
+ speakingStyle: String(p.speakingStyle ?? '').trim() || undefined,
230
+ relationship: String(p.relationship ?? '').trim() || undefined,
231
+ schedule,
232
+ };
233
+ }
234
+
235
+ /**
236
+ * 应用 model/proactive patch 并同步自定义 provider(POST 新建与 PUT 编辑共用)。
237
+ * model 保存时去掉空值键(清空的字段等同不配置);provider 留空由 providerRoute
238
+ * 自动按 apiUrl 派生。返回聚合后的最新 role。
239
+ */
240
+ async function applyModelProactive(rid, patch) {
241
+ if (patch.model !== undefined) {
242
+ await persona.saveRoleField(rid, 'model', Object.fromEntries(Object.entries(patch.model ?? {}).filter(([, v]) => String(v ?? '').trim())));
243
+ }
244
+ if (patch.proactive !== undefined) {
245
+ await persona.saveRoleField(rid, 'proactive', { ...persona.DEFAULT_PROACTIVE, ...patch.proactive });
246
+ }
247
+ const updated = await persona.loadRole(rid);
248
+ await persona.syncRoleMemory(updated);
249
+ if (llmProviders) {
250
+ try {
251
+ if (roleUsesCustomProvider(updated)) await llmProviders.register(updated);
252
+ else await llmProviders.unregister(updated);
253
+ } catch (e) { log?.warn?.('pygmalion: 同步自定义 provider %s 失败 %o', rid, e); }
254
+ }
255
+ return updated;
256
+ }
257
+
258
+ const handler = async (req, res) => {
259
+ const url = new URL(req.url ?? '/', `http://${host}`);
260
+ const pathname = url.pathname;
261
+ try {
262
+ // 静态页(无需登录;页面本身不含敏感数据)——/api/ 一律走 API 分发,
263
+ // 防 API 路径以 .mjs/.js/.css 等静态后缀结尾时被这里误拦(如 /life/script/x.mjs)。
264
+ if (req.method === 'GET' && !pathname.startsWith('/api/') && (pathname === '/' || /\.(html|mjs|js|css|json|svg|png|ico)$/.test(pathname) || pathname.startsWith('/public'))) {
265
+ await serveStatic(pathname, res);
266
+ return;
267
+ }
268
+ if (!csrfOk(req)) { sendJson(res, 403, { ok: false, error: 'CSRF 校验失败' }); return; }
269
+
270
+ if (pathname === '/api/status' && req.method === 'GET') {
271
+ sendJson(res, 200, { ok: true, dataRoot: persona.dataRoot() });
272
+ return;
273
+ }
274
+
275
+ // ---- 会话(无需登录)----
276
+ if (pathname === '/api/session/register' && req.method === 'POST') {
277
+ const b = await readBody(req);
278
+ const qq = String(b.qqNumber ?? '').trim(), password = String(b.password ?? '');
279
+ if (!/^\d{5,}$/.test(qq)) { sendJson(res, 400, { ok: false, error: 'QQ 号应为至少 5 位数字' }); return; }
280
+ if (password.length < 6) { sendJson(res, 400, { ok: false, error: '密码至少 6 位' }); return; }
281
+ if (await persona.loadAccount(qq)) { sendJson(res, 409, { ok: false, error: '该 QQ 已注册' }); return; }
282
+ await persona.createAccount({ qqNumber: qq, password, displayName: String(b.displayName ?? '').trim() || undefined });
283
+ const token = persona.createSession(qq);
284
+ setCookie(res, token);
285
+ sendJson(res, 200, { ok: true, account: publicMe(await persona.loadAccount(qq)) });
286
+ return;
287
+ }
288
+ if (pathname === '/api/session/login' && req.method === 'POST') {
289
+ const b = await readBody(req);
290
+ const qq = String(b.qqNumber ?? '').trim(), password = String(b.password ?? '');
291
+ const ip = clientIp(req);
292
+ const lock = isLocked(ip, qq);
293
+ if (lock) { sendJson(res, 429, { ok: false, error: `登录失败次数过多,请 ${Math.ceil((lock - Date.now()) / 60000)} 分钟后重试` }); return; }
294
+ const account = await persona.authenticate(qq, password);
295
+ if (!account) {
296
+ failLogin(ip, qq);
297
+ sendJson(res, 401, { ok: false, error: 'QQ 号或密码错误' });
298
+ return;
299
+ }
300
+ okLogin(ip, qq);
301
+ const token = persona.createSession(qq);
302
+ setCookie(res, token);
303
+ sendJson(res, 200, { ok: true, account: publicMe(account) });
304
+ return;
305
+ }
306
+ if (pathname === '/api/session/logout' && req.method === 'POST') {
307
+ const token = cookieOf(req);
308
+ if (token) persona.destroySession(token);
309
+ clearCookie(res);
310
+ sendJson(res, 200, { ok: true });
311
+ return;
312
+ }
313
+
314
+ // ---- 业务(需登录)----
315
+ const me = await requireAccount(req, res);
316
+ if (!me) return;
317
+
318
+ function publicMe(a) {
319
+ return {
320
+ qqNumber: a.qqNumber,
321
+ displayName: a.displayName ?? '',
322
+ roleIds: a.roleIds ?? [],
323
+ };
324
+ }
325
+
326
+ if (pathname === '/api/me' && req.method === 'GET') {
327
+ const roles = [];
328
+ for (const rid of me.roleIds ?? []) {
329
+ const role = await persona.loadRole(rid);
330
+ if (role) roles.push(await publicRole(role));
331
+ }
332
+ sendJson(res, 200, { ok: true, account: publicMe(me), roles });
333
+ return;
334
+ }
335
+ if (pathname === '/api/me' && req.method === 'PUT') {
336
+ const b = await readBody(req);
337
+ const next = { ...me };
338
+ if (b.displayName !== undefined) next.displayName = String(b.displayName).trim();
339
+ if (b.newPassword !== undefined) {
340
+ if (String(b.newPassword).length < 6) { sendJson(res, 400, { ok: false, error: '新密码至少 6 位' }); return; }
341
+ if (!persona.verifyPassword(String(b.currentPassword ?? ''), { hash: me.passwordHash, salt: me.salt })) {
342
+ sendJson(res, 403, { ok: false, error: '当前密码不正确' }); return;
343
+ }
344
+ const { hash, salt } = persona.hashPassword(String(b.newPassword));
345
+ next.passwordHash = hash; next.salt = salt;
346
+ }
347
+ await persona.saveAccount(next);
348
+ sendJson(res, 200, { ok: true, account: publicMe(next) });
349
+ return;
350
+ }
351
+
352
+ // ---- 我的角色 ----
353
+ if (pathname === '/api/me/roles' && req.method === 'POST') {
354
+ const b = await readBody(req);
355
+ const personaFields = normalizePersona(b);
356
+ if (!personaFields.name) { sendJson(res, 400, { ok: false, error: '请填写角色名' }); return; }
357
+ const roleId = await persona.createRole({ accountId: me.qqNumber, persona: personaFields });
358
+ // 首次保存同样落 model/proactive(修:新建角色一次保存即生效,而非只有再编辑才存)。
359
+ const role = await applyModelProactive(roleId, b ?? {});
360
+ sendJson(res, 200, { ok: true, roleId, role: await publicRole(role) });
361
+ return;
362
+ }
363
+
364
+ const pm = /^\/api\/me\/roles\/([^/]+)$/.exec(pathname);
365
+ if (pm) {
366
+ const rid = roleParam(pm[1]);
367
+ if (!rid) { sendJson(res, 400, { ok: false, error: '角色 ID 非法' }); return; }
368
+ const role = await persona.loadRole(rid);
369
+ if (!role || !ownedBy(role, me.qqNumber)) { sendJson(res, 404, { ok: false, error: '角色不存在' }); return; }
370
+ if (req.method === 'GET') { sendJson(res, 200, { ok: true, role: await publicRole(role) }); return; }
371
+ if (req.method === 'PUT') {
372
+ const b = await readBody(req);
373
+ const patch = b ?? {};
374
+ if (patch.persona !== undefined) {
375
+ const p = normalizePersona({ persona: patch.persona });
376
+ p.owner = me.qqNumber;
377
+ await persona.saveRoleField(rid, 'persona', p);
378
+ }
379
+ const updated = await applyModelProactive(rid, patch);
380
+ sendJson(res, 200, { ok: true, role: await publicRole(updated) });
381
+ return;
382
+ }
383
+ if (req.method === 'DELETE') {
384
+ if (llmProviders) {
385
+ try { await llmProviders.unregister(role); } catch (e) { log?.warn?.('pygmalion: 注销自定义 provider %s 失败 %o', rid, e); }
386
+ }
387
+ await botApi.removeForRole(rid);
388
+ await persona.deleteRole(rid);
389
+ sendJson(res, 200, { ok: true, deleted: rid });
390
+ return;
391
+ }
392
+ sendJson(res, 405, { ok: false, error: 'method not allowed' });
393
+ return;
394
+ }
395
+
396
+ // 我的角色的 QQ 机器人(凭据仅角色 owner 可配;qqSecret 不回传,空留=保持原值)。
397
+ const pBot = /^\/api\/me\/roles\/([^/]+)\/bot$/.exec(pathname);
398
+ if (pBot) {
399
+ const rid = roleParam(pBot[1]);
400
+ if (!rid) { sendJson(res, 400, { ok: false, error: '角色 ID 非法' }); return; }
401
+ const role = await persona.loadRole(rid);
402
+ if (!role || !ownedBy(role, me.qqNumber)) { sendJson(res, 404, { ok: false, error: '角色不存在' }); return; }
403
+ if (req.method === 'PUT') {
404
+ const b = await readBody(req);
405
+ try {
406
+ await botApi.upsertForRole(rid, { ...(b ?? {}), owner: me.qqNumber });
407
+ sendJson(res, 200, { ok: true, bot: roleBot(rid) });
408
+ } catch (e) {
409
+ sendJson(res, 400, { ok: false, error: String(e?.message ?? e) });
410
+ }
411
+ return;
412
+ }
413
+ if (req.method === 'DELETE') {
414
+ await botApi.removeForRole(rid);
415
+ sendJson(res, 200, { ok: true });
416
+ return;
417
+ }
418
+ sendJson(res, 405, { ok: false, error: 'method not allowed' });
419
+ return;
420
+ }
421
+
422
+ const pReset = /^\/api\/me\/roles\/([^/]+)\/reset-binding$/.exec(pathname);
423
+ if (pReset && req.method === 'POST') {
424
+ const rid = roleParam(pReset[1]);
425
+ if (!rid) { sendJson(res, 400, { ok: false, error: '角色 ID 非法' }); return; }
426
+ const role = await persona.loadRole(rid);
427
+ if (!role || !ownedBy(role, me.qqNumber)) { sendJson(res, 404, { ok: false, error: '角色不存在' }); return; }
428
+ const updated = await persona.resetRoleBinding(rid);
429
+ sendJson(res, 200, { ok: true, role: await publicRole(updated) });
430
+ return;
431
+ }
432
+
433
+ const pLifeStop = /^\/api\/me\/roles\/([^/]+)\/life\/stop$/.exec(pathname);
434
+ if (pLifeStop && req.method === 'POST') {
435
+ const rid = roleParam(pLifeStop[1]);
436
+ if (!rid) { sendJson(res, 400, { ok: false, error: '角色 ID 非法' }); return; }
437
+ const role = await persona.loadRole(rid);
438
+ if (!role || !ownedBy(role, me.qqNumber)) { sendJson(res, 404, { ok: false, error: '角色不存在' }); return; }
439
+ const b = await readBody(req);
440
+ const runId = String(b?.runId ?? '').trim();
441
+ if (!runId) { sendJson(res, 400, { ok: false, error: '缺少 runId' }); return; }
442
+ sendJson(res, 200, await stopLifeScript(runId));
443
+ return;
444
+ }
445
+
446
+ const pLife = /^\/api\/me\/roles\/([^/]+)\/life(?:\/(script|log)\/([^/]+))?$/.exec(pathname);
447
+ if (pLife) {
448
+ const rid = roleParam(pLife[1]);
449
+ if (!rid) { sendJson(res, 400, { ok: false, error: '角色 ID 非法' }); return; }
450
+ const role = await persona.loadRole(rid);
451
+ if (!role || !ownedBy(role, me.qqNumber)) { sendJson(res, 404, { ok: false, error: '角色不存在' }); return; }
452
+ if (req.method !== 'GET') { sendJson(res, 405, { ok: false, error: 'method not allowed' }); return; }
453
+ if (pLife[2]) {
454
+ // pathname 保留百分号编码;解码后交由白名单校验(含中文脚本名,%2e%2e 还原成穿越路径会被拒)
455
+ let rawName = '';
456
+ try { rawName = decodeURIComponent(pLife[3]); } catch { /* 非法 % 序列 → 校验拒绝 */ }
457
+ const name = pLife[2] === 'log' ? logFileNameParam(rawName) : scriptFileNameParam(rawName);
458
+ if (!name) { sendJson(res, 400, { ok: false, error: pLife[2] === 'log' ? '日志名非法' : '脚本名非法' }); return; }
459
+ const file = pLife[2] === 'log'
460
+ ? join(role.workspace, 'life', '.logs', name)
461
+ : join(role.workspace, 'life', name);
462
+ const base = pLife[2] === 'log'
463
+ ? join(role.workspace, 'life', '.logs')
464
+ : join(role.workspace, 'life');
465
+ if (!file.startsWith(base)) { sendJson(res, 400, { ok: false, error: '路径非法' }); return; }
466
+ const text = await readFile(file, 'utf8').catch(() => null);
467
+ if (text === null) { sendJson(res, 404, { ok: false, error: pLife[2] === 'log' ? '日志不存在' : '脚本不存在' }); return; }
468
+ res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
469
+ res.end(text);
470
+ return;
471
+ }
472
+ sendJson(res, 200, { ok: true, ...(await lifeStatus(rid)) });
473
+ return;
474
+ }
475
+
476
+ sendJson(res, 404, { ok: false, error: `not found: ${pathname}` });
477
+ } catch (e) {
478
+ log?.error?.('web-server error: %o', e);
479
+ if (!res.headersSent) sendJson(res, 500, { ok: false, error: String(e?.message ?? e) });
480
+ }
481
+ };
482
+
483
+ return {
484
+ async start() {
485
+ if (server) return started;
486
+ server = createServer(handler);
487
+ await new Promise((resolve, reject) => {
488
+ server.once('error', reject);
489
+ server.listen(port, host, () => resolve());
490
+ });
491
+ const addr = server.address();
492
+ const actualPort = addr && typeof addr === 'object' ? addr.port : port;
493
+ started = { host, port: actualPort };
494
+ log?.info?.('pygmalion web 管理网页已启动: http://%s:%d', host, actualPort);
495
+ return started;
496
+ },
497
+ async stop() {
498
+ if (!server) return;
499
+ const s = server; server = null;
500
+ await new Promise((resolve) => s.close(() => resolve()));
501
+ },
502
+ };
503
+ }
504
+
505
+ // 便捷导出:独立运行入口(调试用,正常由插件 index.js 挂载)
506
+ export const webServerDefault = createWebServer;