cortico-world-memory-core 0.24.0 → 0.26.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 +46 -0
- package/ENV_PROMPT.md +2 -2
- package/package.json +2 -2
- package/src/config.ts +63 -4
- package/src/definition.ts +54 -53
- package/src/recall.ts +114 -8
- package/src/site.ts +435 -435
- package/src/store.ts +11 -0
- package/src/tools.ts +22 -2
- package/src/world.ts +206 -11
- package/webui/app.js +7 -1
- package/webui/next.css +21 -13
package/src/site.ts
CHANGED
|
@@ -1,435 +1,435 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 记忆地图的本地站点:一个只绑 127.0.0.1 的小 HTTP 服务。
|
|
3
|
-
*
|
|
4
|
-
* 六条约束(改的时候别破坏):
|
|
5
|
-
* 1) **只绑 127.0.0.1** —— 站点不对局域网露面;
|
|
6
|
-
* 2) **只认 127.0.0.1 / localhost 这两个 Host** —— 别人把域名解析到本机(DNS 重绑定)也进不来;
|
|
7
|
-
* 3) **写接口必须带页面注入的一次性令牌** —— 别的网页能打 localhost,但拿不到这个令牌;
|
|
8
|
-
* 4) 端口被占就 +1 重试,起不来不算致命,只少一个链接;
|
|
9
|
-
* 5) 写操作走**插件内存里的同一份 store**,不直接改文件 ——
|
|
10
|
-
* 否则宿主下一次 save() 会用内存状态把文件覆盖回去;
|
|
11
|
-
* 6) 读文件接口只允许在已扫描的目录内,防目录穿越。
|
|
12
|
-
*/
|
|
13
|
-
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
|
|
14
|
-
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
15
|
-
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
16
|
-
import { extname, join, normalize, resolve, sep } from 'node:path';
|
|
17
|
-
import type { Card, CoreState, PlanItem, RawEntry } from './store.ts';
|
|
18
|
-
import type { DocFile } from './workspace.ts';
|
|
19
|
-
|
|
20
|
-
const MIME: Record<string, string> = {
|
|
21
|
-
'.html': 'text/html; charset=utf-8',
|
|
22
|
-
'.js': 'text/javascript; charset=utf-8',
|
|
23
|
-
'.css': 'text/css; charset=utf-8',
|
|
24
|
-
'.json': 'application/json; charset=utf-8',
|
|
25
|
-
'.svg': 'image/svg+xml',
|
|
26
|
-
'.png': 'image/png',
|
|
27
|
-
'.woff2': 'font/woff2',
|
|
28
|
-
'.ico': 'image/x-icon',
|
|
29
|
-
};
|
|
30
|
-
|
|
31
|
-
const MAX_PORT_TRIES = 10;
|
|
32
|
-
const MAX_BODY = 512 * 1024;
|
|
33
|
-
/** 导入的是整包备份,比日常请求大得多。 */
|
|
34
|
-
const MAX_IMPORT = 32 * 1024 * 1024;
|
|
35
|
-
|
|
36
|
-
export interface Snapshot {
|
|
37
|
-
now: string;
|
|
38
|
-
cards: readonly Card[];
|
|
39
|
-
turns: readonly RawEntry[];
|
|
40
|
-
plans: readonly PlanItem[];
|
|
41
|
-
state: CoreState;
|
|
42
|
-
proactive: { enabled: boolean; count: number; cap: number; dueAt: string | null; lastTalkAt: string | null };
|
|
43
|
-
stats: {
|
|
44
|
-
total: number;
|
|
45
|
-
retired: number;
|
|
46
|
-
byKind: Record<string, number>;
|
|
47
|
-
openPromises: number;
|
|
48
|
-
overdue: number;
|
|
49
|
-
todayNew: number;
|
|
50
|
-
weekNew: number;
|
|
51
|
-
avgWeight: number;
|
|
52
|
-
tags: Array<{ tag: string; n: number }>;
|
|
53
|
-
byDay: Array<{ day: string; n: number }>;
|
|
54
|
-
scopes: Array<{ scope: string; n: number }>;
|
|
55
|
-
};
|
|
56
|
-
docs: { enabled: boolean; count: number; dirs: string[] };
|
|
57
|
-
archive: { days: number; bytes: number; oldest: string; retention: number };
|
|
58
|
-
site: { port: number; origin: string };
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
export interface MaintenanceReport {
|
|
62
|
-
dupes: Array<{ score: number; ids: string[] }>;
|
|
63
|
-
stale: string[];
|
|
64
|
-
junk: string[];
|
|
65
|
-
retired: string[];
|
|
66
|
-
/** 承诺:没写截止时间的提醒管线管不到;overdue 是已过期还没做的。 */
|
|
67
|
-
promises: { noDue: string[]; overdue: string[] };
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
export interface HealthReport {
|
|
71
|
-
generatedAt: string;
|
|
72
|
-
cards: { total: number; active: number; retired: number; dead: number };
|
|
73
|
-
recall: { calls: number; cardsTouched: number; primed: number };
|
|
74
|
-
perDay: Array<{ day: string; n: number }>;
|
|
75
|
-
promises: { open: number; overdue: number; noDue: number; repeating: number };
|
|
76
|
-
raw: { lines: number; archivedDays: number; archivedLines: number };
|
|
77
|
-
backup: { count: number; latest: string | null; dir: string };
|
|
78
|
-
/** 冷层:沉下去多少、还能再沉多少、门槛多少天。 */
|
|
79
|
-
chill: { cold: number; eligible: number; afterDays: number };
|
|
80
|
-
deadIds: string[];
|
|
81
|
-
coldIds: string[];
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
export interface ImportReport {
|
|
85
|
-
cards: { added: number; skipped: number };
|
|
86
|
-
turns: { added: number; skipped: number };
|
|
87
|
-
plans: { added: number; skipped: number };
|
|
88
|
-
state: { watermark: number };
|
|
89
|
-
warnings: string[];
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
export interface SiteHooks {
|
|
93
|
-
snapshot(): Snapshot;
|
|
94
|
-
docs(): readonly DocFile[];
|
|
95
|
-
docRoots(): string[];
|
|
96
|
-
createCard(input: Record<string, unknown>): Card;
|
|
97
|
-
updateCard(id: string, patch: Record<string, unknown>): Card | undefined;
|
|
98
|
-
deleteCard(id: string): boolean;
|
|
99
|
-
retireCard(id: string): boolean;
|
|
100
|
-
restoreCard(id: string): boolean;
|
|
101
|
-
lineage(id: string): { card: Card | null; supersedes: Card[]; replacedBy: Card | null };
|
|
102
|
-
maintenance(): MaintenanceReport;
|
|
103
|
-
mergeCards(keepId: string, dropIds: string[]): { kept: Card | null; merged: number };
|
|
104
|
-
purgeCards(ids: string[]): number;
|
|
105
|
-
health(): HealthReport;
|
|
106
|
-
importData(payload: Record<string, unknown>): ImportReport;
|
|
107
|
-
/** 在按天归档的旧原文里搜(页面上的「含归档」开关)。 */
|
|
108
|
-
archiveSearch(q: string, days: number, limit: number): RawEntry[];
|
|
109
|
-
/** 删掉一条原文(热数据或归档)。 */
|
|
110
|
-
deleteTurn(cursor: number): boolean;
|
|
111
|
-
/** 把记忆沉到冷层 / 从冷层捞回来。 */
|
|
112
|
-
chillCards(ids: string[]): number;
|
|
113
|
-
warmCards(ids: string[]): number;
|
|
114
|
-
patchState(input: Record<string, unknown>): CoreState;
|
|
115
|
-
planAction(input: Record<string, unknown>): unknown;
|
|
116
|
-
exportAll(fmt: string): { body: string; mime: string; filename: string };
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
export class MemorySite {
|
|
120
|
-
private server: Server | null = null;
|
|
121
|
-
private port: number | null = null;
|
|
122
|
-
private readonly basePort: number;
|
|
123
|
-
private readonly webDir: string;
|
|
124
|
-
/** 进程级一次性令牌:只有这个站点发出的页面才知道,别的网页拿不到。 */
|
|
125
|
-
private readonly token = randomBytes(18).toString('base64url');
|
|
126
|
-
|
|
127
|
-
constructor(private readonly hooks: SiteHooks, webDir: string, port: number) {
|
|
128
|
-
this.webDir = resolve(webDir);
|
|
129
|
-
this.basePort = Number(port) || 7801;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
get origin(): string | null {
|
|
133
|
-
return this.port ? `http://127.0.0.1:${this.port}` : null;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
async start(): Promise<string | null> {
|
|
137
|
-
if (this.server) return this.origin;
|
|
138
|
-
for (let i = 0; i < MAX_PORT_TRIES; i += 1) {
|
|
139
|
-
const port = this.basePort + i;
|
|
140
|
-
if (await this.tryListen(port)) {
|
|
141
|
-
this.port = port;
|
|
142
|
-
return this.origin;
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
return null;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
private tryListen(port: number): Promise<boolean> {
|
|
149
|
-
return new Promise((res) => {
|
|
150
|
-
const server = createServer((req, rsp) => {
|
|
151
|
-
this.handle(req, rsp).catch((error: unknown) => {
|
|
152
|
-
this.json(rsp, 500, { error: error instanceof Error ? error.message : String(error) });
|
|
153
|
-
});
|
|
154
|
-
});
|
|
155
|
-
server.once('error', () => {
|
|
156
|
-
try {
|
|
157
|
-
server.close();
|
|
158
|
-
} catch {
|
|
159
|
-
// 已经关了
|
|
160
|
-
}
|
|
161
|
-
res(false);
|
|
162
|
-
});
|
|
163
|
-
server.listen(port, '127.0.0.1', () => {
|
|
164
|
-
server.removeAllListeners('error');
|
|
165
|
-
server.on('error', () => {
|
|
166
|
-
// 运行期错误不该让进程挂掉
|
|
167
|
-
});
|
|
168
|
-
this.server = server;
|
|
169
|
-
res(true);
|
|
170
|
-
});
|
|
171
|
-
});
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
async stop(): Promise<void> {
|
|
175
|
-
const s = this.server;
|
|
176
|
-
this.server = null;
|
|
177
|
-
this.port = null;
|
|
178
|
-
if (!s) return;
|
|
179
|
-
await new Promise<void>((res) => s.close(() => res()));
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
// ---- 路由 ----
|
|
183
|
-
|
|
184
|
-
private async handle(req: IncomingMessage, rsp: ServerResponse): Promise<void> {
|
|
185
|
-
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
186
|
-
const path = url.pathname;
|
|
187
|
-
|
|
188
|
-
// 只认本机这两个 Host:域名解析到 127.0.0.1(DNS 重绑定)会在这一步被挡掉
|
|
189
|
-
if (!this.hostOk(req)) return this.json(rsp, 403, { error: '只能通过 127.0.0.1 或 localhost 打开' });
|
|
190
|
-
|
|
191
|
-
if (path.startsWith('/api/')) return this.api(req, rsp, url, path);
|
|
192
|
-
|
|
193
|
-
// 原页面和新版页面共用同一个本地站点与令牌,方便并排对比。
|
|
194
|
-
if (path === '/next' || path === '/next/') {
|
|
195
|
-
if (req.method !== 'GET' && req.method !== 'HEAD') return this.text(rsp, 405, 'method not allowed');
|
|
196
|
-
return this.sendFile(rsp, 'next.html');
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
// 无域名、无认证:只服务本机,禁止被 iframe 之外的地方引用
|
|
200
|
-
if (req.method !== 'GET' && req.method !== 'HEAD') return this.text(rsp, 405, 'method not allowed');
|
|
201
|
-
const file = path === '/' ? 'index.html' : path.replace(/^\/+/, '');
|
|
202
|
-
return this.sendFile(rsp, file);
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
private hostOk(req: IncomingMessage): boolean {
|
|
206
|
-
const host = String(req.headers.host ?? '').toLowerCase();
|
|
207
|
-
const port = this.port ?? this.basePort;
|
|
208
|
-
return host === `127.0.0.1:${port}` || host === `localhost:${port}`;
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
/** 定长比较,别用 === 给出计时侧信道。 */
|
|
212
|
-
private tokenOk(req: IncomingMessage): boolean {
|
|
213
|
-
const got = String(req.headers['x-mcore-token'] ?? '');
|
|
214
|
-
if (got.length !== this.token.length) return false;
|
|
215
|
-
try {
|
|
216
|
-
return timingSafeEqual(Buffer.from(got), Buffer.from(this.token));
|
|
217
|
-
} catch {
|
|
218
|
-
return false;
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
private async api(req: IncomingMessage, rsp: ServerResponse, url: URL, path: string): Promise<void> {
|
|
223
|
-
// GET/HEAD 是只读,随便看(跨站也读不到内容,因为没有 CORS 头);
|
|
224
|
-
// 其余方法一律要令牌——跨站页面能打到这里,但发不出这个头。
|
|
225
|
-
if (req.method !== 'GET' && req.method !== 'HEAD' && !this.tokenOk(req)) {
|
|
226
|
-
return this.json(rsp, 403, { error: '写操作需要页面上带过来的一次性令牌,刷新一下页面' });
|
|
227
|
-
}
|
|
228
|
-
if (path === '/api/snapshot' && req.method === 'GET') {
|
|
229
|
-
return this.json(rsp, 200, this.hooks.snapshot());
|
|
230
|
-
}
|
|
231
|
-
if (path === '/api/docs' && req.method === 'GET') {
|
|
232
|
-
return this.json(rsp, 200, {
|
|
233
|
-
roots: this.hooks.docRoots(),
|
|
234
|
-
files: this.hooks.docs().map(({ text, ...rest }) => ({ ...rest, chars: text.length })),
|
|
235
|
-
});
|
|
236
|
-
}
|
|
237
|
-
if (path === '/api/doc' && req.method === 'GET') {
|
|
238
|
-
const target = url.searchParams.get('path') ?? '';
|
|
239
|
-
return this.sendDoc(rsp, target);
|
|
240
|
-
}
|
|
241
|
-
if (path === '/api/export' && req.method === 'GET') {
|
|
242
|
-
const fmt = url.searchParams.get('fmt') === 'md' ? 'md' : 'json';
|
|
243
|
-
const out = this.hooks.exportAll(fmt);
|
|
244
|
-
rsp.writeHead(200, {
|
|
245
|
-
'content-type': `${out.mime}; charset=utf-8`,
|
|
246
|
-
'content-disposition': `attachment; filename="${out.filename}"`,
|
|
247
|
-
'cache-control': 'no-store',
|
|
248
|
-
});
|
|
249
|
-
return rsp.end(out.body);
|
|
250
|
-
}
|
|
251
|
-
if (path === '/api/cards' && req.method === 'POST') {
|
|
252
|
-
const body = await this.body(req);
|
|
253
|
-
const card = this.hooks.createCard(body);
|
|
254
|
-
return this.json(rsp, 201, card);
|
|
255
|
-
}
|
|
256
|
-
if (path === '/api/maintenance' && req.method === 'GET') {
|
|
257
|
-
return this.json(rsp, 200, this.hooks.maintenance());
|
|
258
|
-
}
|
|
259
|
-
if (path === '/api/merge' && req.method === 'POST') {
|
|
260
|
-
const body = await this.body(req);
|
|
261
|
-
const keep = String(body.keep ?? '');
|
|
262
|
-
const drop = Array.isArray(body.drop) ? (body.drop as unknown[]).map((x) => String(x)) : [];
|
|
263
|
-
if (!keep) return this.json(rsp, 400, { error: '缺少要保留的那条' });
|
|
264
|
-
return this.json(rsp, 200, this.hooks.mergeCards(keep, drop));
|
|
265
|
-
}
|
|
266
|
-
if (path === '/api/purge' && req.method === 'POST') {
|
|
267
|
-
const body = await this.body(req);
|
|
268
|
-
const ids = Array.isArray(body.ids) ? (body.ids as unknown[]).map((x) => String(x)) : [];
|
|
269
|
-
return this.json(rsp, 200, { removed: this.hooks.purgeCards(ids) });
|
|
270
|
-
}
|
|
271
|
-
if (path === '/api/chill' || path === '/api/warm') {
|
|
272
|
-
if (req.method !== 'POST') return this.text(rsp, 405, 'method not allowed');
|
|
273
|
-
const body = await this.body(req);
|
|
274
|
-
const ids = Array.isArray(body.ids) ? (body.ids as unknown[]).map((x) => String(x)) : [];
|
|
275
|
-
// 不带 ids 就是「全部符合条件的」:冷层一键沉、一键回暖
|
|
276
|
-
const n = path === '/api/chill' ? this.hooks.chillCards(ids) : this.hooks.warmCards(ids);
|
|
277
|
-
return this.json(rsp, 200, { changed: n });
|
|
278
|
-
}
|
|
279
|
-
if (path === '/api/health' && req.method === 'GET') {
|
|
280
|
-
return this.json(rsp, 200, this.hooks.health());
|
|
281
|
-
}
|
|
282
|
-
if (path === '/api/archive' && req.method === 'GET') {
|
|
283
|
-
const q = (url.searchParams.get('q') ?? '').trim();
|
|
284
|
-
const days = Number(url.searchParams.get('days') ?? 90) || 90;
|
|
285
|
-
const limit = Number(url.searchParams.get('limit') ?? 40) || 40;
|
|
286
|
-
return this.json(rsp, 200, q ? this.hooks.archiveSearch(q, days, limit) : []);
|
|
287
|
-
}
|
|
288
|
-
const turnMatch = /^\/api\/turns\/(\d{1,12})$/.exec(path);
|
|
289
|
-
if (turnMatch && req.method === 'DELETE') {
|
|
290
|
-
return this.json(rsp, 200, { removed: this.hooks.deleteTurn(Number(turnMatch[1])) });
|
|
291
|
-
}
|
|
292
|
-
if (path === '/api/import' && req.method === 'POST') {
|
|
293
|
-
let body: Record<string, unknown>;
|
|
294
|
-
try {
|
|
295
|
-
body = await this.body(req, MAX_IMPORT);
|
|
296
|
-
} catch (err) {
|
|
297
|
-
return this.json(rsp, 400, { error: err instanceof Error ? err.message : '读不了请求体' });
|
|
298
|
-
}
|
|
299
|
-
try {
|
|
300
|
-
return this.json(rsp, 200, this.hooks.importData(body));
|
|
301
|
-
} catch (err) {
|
|
302
|
-
return this.json(rsp, 400, { error: err instanceof Error ? err.message : '导入失败' });
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
const actionMatch = /^\/api\/cards\/([\w-]{1,60})\/(retire|restore|lineage)$/.exec(path);
|
|
306
|
-
if (actionMatch) {
|
|
307
|
-
const [, id, action] = actionMatch;
|
|
308
|
-
if (action === 'lineage' && req.method === 'GET') {
|
|
309
|
-
return this.json(rsp, 200, this.hooks.lineage(id));
|
|
310
|
-
}
|
|
311
|
-
if (req.method === 'POST') {
|
|
312
|
-
if (action === 'retire') return this.hooks.retireCard(id) ? this.json(rsp, 200, { ok: true }) : this.json(rsp, 404, { error: '没有这条记忆' });
|
|
313
|
-
if (action === 'restore') return this.hooks.restoreCard(id) ? this.json(rsp, 200, { ok: true }) : this.json(rsp, 404, { error: '没有这条记忆' });
|
|
314
|
-
}
|
|
315
|
-
return this.json(rsp, 405, { error: 'method not allowed' });
|
|
316
|
-
}
|
|
317
|
-
const cardMatch = /^\/api\/cards\/([\w-]{1,60})$/.exec(path);
|
|
318
|
-
if (cardMatch) {
|
|
319
|
-
const id = cardMatch[1];
|
|
320
|
-
if (req.method === 'PATCH' || req.method === 'PUT') {
|
|
321
|
-
const body = await this.body(req);
|
|
322
|
-
const card = this.hooks.updateCard(id, body);
|
|
323
|
-
return card ? this.json(rsp, 200, card) : this.json(rsp, 404, { error: '没有这条记忆' });
|
|
324
|
-
}
|
|
325
|
-
if (req.method === 'DELETE') {
|
|
326
|
-
return this.hooks.deleteCard(id) ? this.json(rsp, 200, { ok: true }) : this.json(rsp, 404, { error: '没有这条记忆' });
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
if (path === '/api/state' && req.method === 'POST') {
|
|
330
|
-
const body = await this.body(req);
|
|
331
|
-
return this.json(rsp, 200, this.hooks.patchState(body));
|
|
332
|
-
}
|
|
333
|
-
if (path === '/api/plans' && req.method === 'POST') {
|
|
334
|
-
const body = await this.body(req);
|
|
335
|
-
return this.json(rsp, 200, this.hooks.planAction(body));
|
|
336
|
-
}
|
|
337
|
-
return this.json(rsp, 404, { error: `未知接口 ${path}` });
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
private sendDoc(rsp: ServerResponse, rawPath: string): void {
|
|
341
|
-
let target: string;
|
|
342
|
-
try {
|
|
343
|
-
target = normalize(decodeURIComponent(rawPath));
|
|
344
|
-
} catch {
|
|
345
|
-
return this.text(rsp, 400, 'bad path');
|
|
346
|
-
}
|
|
347
|
-
const roots = this.hooks.docRoots();
|
|
348
|
-
const abs = resolve(target);
|
|
349
|
-
const allowed = roots.some((root) => {
|
|
350
|
-
const base = resolve(root);
|
|
351
|
-
const prefix = base.endsWith(sep) ? base : base + sep;
|
|
352
|
-
return abs.toLowerCase() === base.toLowerCase() || abs.toLowerCase().startsWith(prefix.toLowerCase());
|
|
353
|
-
});
|
|
354
|
-
if (!allowed) return this.json(rsp, 403, { error: '只能读配置里允许的目录' });
|
|
355
|
-
if (!existsSync(target)) return this.json(rsp, 404, { error: '文件不在了' });
|
|
356
|
-
const file = this.hooks.docs().find((d) => resolve(d.path) === resolve(target));
|
|
357
|
-
if (!file) return this.json(rsp, 404, { error: '文件不在扫描结果里(可能太大或后缀不符)' });
|
|
358
|
-
return this.json(rsp, 200, { path: file.path, name: file.name, rel: file.rel, mtimeMs: file.mtimeMs, text: file.text });
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
// ---- 静态文件 ----
|
|
362
|
-
|
|
363
|
-
private sendFile(rsp: ServerResponse, rel: string): void {
|
|
364
|
-
const safe = normalize(rel).replace(/^([.][.][\\/])+/, '');
|
|
365
|
-
const full = join(this.webDir, safe);
|
|
366
|
-
if (!full.startsWith(this.webDir + sep) && full !== this.webDir) return this.text(rsp, 403, 'forbidden');
|
|
367
|
-
if (!existsSync(full)) return this.text(rsp, 404, 'not found');
|
|
368
|
-
try {
|
|
369
|
-
if (!statSync(full).isFile()) return this.text(rsp, 404, 'not found');
|
|
370
|
-
const body = readFileSync(full);
|
|
371
|
-
const type = MIME[extname(full).toLowerCase()] ?? 'application/octet-stream';
|
|
372
|
-
// 首页注入一次性令牌:app.js 把它放进每个写请求的头里。
|
|
373
|
-
// 这份 HTML 不进缓存,否则进程重启后旧令牌会让所有写操作 403。
|
|
374
|
-
if (safe === 'index.html' || safe === 'next.html') {
|
|
375
|
-
const html = body
|
|
376
|
-
.toString('utf8')
|
|
377
|
-
.replace('<head>', `<head>\n<meta name="mcore-token" content="${this.token}">`);
|
|
378
|
-
rsp.writeHead(200, {
|
|
379
|
-
'content-type': type,
|
|
380
|
-
'cache-control': 'no-store',
|
|
381
|
-
'x-content-type-options': 'nosniff',
|
|
382
|
-
});
|
|
383
|
-
return rsp.end(html);
|
|
384
|
-
}
|
|
385
|
-
rsp.writeHead(200, {
|
|
386
|
-
'content-type': type,
|
|
387
|
-
'cache-control': 'no-cache',
|
|
388
|
-
'x-content-type-options': 'nosniff',
|
|
389
|
-
});
|
|
390
|
-
rsp.end(body);
|
|
391
|
-
} catch {
|
|
392
|
-
this.text(rsp, 500, 'read failed');
|
|
393
|
-
}
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
private readBody(req: IncomingMessage, limit = MAX_BODY): Promise<string> {
|
|
397
|
-
return new Promise((res, rej) => {
|
|
398
|
-
let size = 0;
|
|
399
|
-
const chunks: Buffer[] = [];
|
|
400
|
-
req.on('data', (chunk: Buffer) => {
|
|
401
|
-
size += chunk.length;
|
|
402
|
-
if (size > limit) {
|
|
403
|
-
rej(new Error('请求体太大'));
|
|
404
|
-
req.destroy();
|
|
405
|
-
return;
|
|
406
|
-
}
|
|
407
|
-
chunks.push(chunk);
|
|
408
|
-
});
|
|
409
|
-
req.on('end', () => res(Buffer.concat(chunks).toString('utf8')));
|
|
410
|
-
req.on('error', rej);
|
|
411
|
-
});
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
private async body(req: IncomingMessage, limit = MAX_BODY): Promise<Record<string, unknown>> {
|
|
415
|
-
const raw = await this.readBody(req, limit);
|
|
416
|
-
if (!raw.trim()) return {};
|
|
417
|
-
try {
|
|
418
|
-
const parsed = JSON.parse(raw) as unknown;
|
|
419
|
-
return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};
|
|
420
|
-
} catch {
|
|
421
|
-
throw new Error('请求体不是合法 JSON');
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
private json(rsp: ServerResponse, code: number, payload: unknown): void {
|
|
426
|
-
const body = JSON.stringify(payload);
|
|
427
|
-
rsp.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
428
|
-
rsp.end(body);
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
private text(rsp: ServerResponse, code: number, msg: string): void {
|
|
432
|
-
rsp.writeHead(code, { 'content-type': 'text/plain; charset=utf-8' });
|
|
433
|
-
rsp.end(msg);
|
|
434
|
-
}
|
|
435
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* 记忆地图的本地站点:一个只绑 127.0.0.1 的小 HTTP 服务。
|
|
3
|
+
*
|
|
4
|
+
* 六条约束(改的时候别破坏):
|
|
5
|
+
* 1) **只绑 127.0.0.1** —— 站点不对局域网露面;
|
|
6
|
+
* 2) **只认 127.0.0.1 / localhost 这两个 Host** —— 别人把域名解析到本机(DNS 重绑定)也进不来;
|
|
7
|
+
* 3) **写接口必须带页面注入的一次性令牌** —— 别的网页能打 localhost,但拿不到这个令牌;
|
|
8
|
+
* 4) 端口被占就 +1 重试,起不来不算致命,只少一个链接;
|
|
9
|
+
* 5) 写操作走**插件内存里的同一份 store**,不直接改文件 ——
|
|
10
|
+
* 否则宿主下一次 save() 会用内存状态把文件覆盖回去;
|
|
11
|
+
* 6) 读文件接口只允许在已扫描的目录内,防目录穿越。
|
|
12
|
+
*/
|
|
13
|
+
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
|
|
14
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
15
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
16
|
+
import { extname, join, normalize, resolve, sep } from 'node:path';
|
|
17
|
+
import type { Card, CoreState, PlanItem, RawEntry } from './store.ts';
|
|
18
|
+
import type { DocFile } from './workspace.ts';
|
|
19
|
+
|
|
20
|
+
const MIME: Record<string, string> = {
|
|
21
|
+
'.html': 'text/html; charset=utf-8',
|
|
22
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
23
|
+
'.css': 'text/css; charset=utf-8',
|
|
24
|
+
'.json': 'application/json; charset=utf-8',
|
|
25
|
+
'.svg': 'image/svg+xml',
|
|
26
|
+
'.png': 'image/png',
|
|
27
|
+
'.woff2': 'font/woff2',
|
|
28
|
+
'.ico': 'image/x-icon',
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const MAX_PORT_TRIES = 10;
|
|
32
|
+
const MAX_BODY = 512 * 1024;
|
|
33
|
+
/** 导入的是整包备份,比日常请求大得多。 */
|
|
34
|
+
const MAX_IMPORT = 32 * 1024 * 1024;
|
|
35
|
+
|
|
36
|
+
export interface Snapshot {
|
|
37
|
+
now: string;
|
|
38
|
+
cards: readonly Card[];
|
|
39
|
+
turns: readonly RawEntry[];
|
|
40
|
+
plans: readonly PlanItem[];
|
|
41
|
+
state: CoreState;
|
|
42
|
+
proactive: { enabled: boolean; count: number; cap: number; dueAt: string | null; lastTalkAt: string | null };
|
|
43
|
+
stats: {
|
|
44
|
+
total: number;
|
|
45
|
+
retired: number;
|
|
46
|
+
byKind: Record<string, number>;
|
|
47
|
+
openPromises: number;
|
|
48
|
+
overdue: number;
|
|
49
|
+
todayNew: number;
|
|
50
|
+
weekNew: number;
|
|
51
|
+
avgWeight: number;
|
|
52
|
+
tags: Array<{ tag: string; n: number }>;
|
|
53
|
+
byDay: Array<{ day: string; n: number }>;
|
|
54
|
+
scopes: Array<{ scope: string; n: number }>;
|
|
55
|
+
};
|
|
56
|
+
docs: { enabled: boolean; count: number; dirs: string[] };
|
|
57
|
+
archive: { days: number; bytes: number; oldest: string; retention: number };
|
|
58
|
+
site: { port: number; origin: string };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface MaintenanceReport {
|
|
62
|
+
dupes: Array<{ score: number; ids: string[] }>;
|
|
63
|
+
stale: string[];
|
|
64
|
+
junk: string[];
|
|
65
|
+
retired: string[];
|
|
66
|
+
/** 承诺:没写截止时间的提醒管线管不到;overdue 是已过期还没做的。 */
|
|
67
|
+
promises: { noDue: string[]; overdue: string[] };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface HealthReport {
|
|
71
|
+
generatedAt: string;
|
|
72
|
+
cards: { total: number; active: number; retired: number; dead: number };
|
|
73
|
+
recall: { calls: number; cardsTouched: number; primed: number };
|
|
74
|
+
perDay: Array<{ day: string; n: number }>;
|
|
75
|
+
promises: { open: number; overdue: number; noDue: number; repeating: number; repeatMin?: number; dueList?: Array<{ id: string; text: string; dueAt: string; lateMin: number; remindCount: number }> };
|
|
76
|
+
raw: { lines: number; archivedDays: number; archivedLines: number };
|
|
77
|
+
backup: { count: number; latest: string | null; dir: string };
|
|
78
|
+
/** 冷层:沉下去多少、还能再沉多少、门槛多少天。 */
|
|
79
|
+
chill: { cold: number; eligible: number; afterDays: number };
|
|
80
|
+
deadIds: string[];
|
|
81
|
+
coldIds: string[];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface ImportReport {
|
|
85
|
+
cards: { added: number; skipped: number };
|
|
86
|
+
turns: { added: number; skipped: number };
|
|
87
|
+
plans: { added: number; skipped: number };
|
|
88
|
+
state: { watermark: number };
|
|
89
|
+
warnings: string[];
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface SiteHooks {
|
|
93
|
+
snapshot(): Snapshot;
|
|
94
|
+
docs(): readonly DocFile[];
|
|
95
|
+
docRoots(): string[];
|
|
96
|
+
createCard(input: Record<string, unknown>): Card;
|
|
97
|
+
updateCard(id: string, patch: Record<string, unknown>): Card | undefined;
|
|
98
|
+
deleteCard(id: string): boolean;
|
|
99
|
+
retireCard(id: string): boolean;
|
|
100
|
+
restoreCard(id: string): boolean;
|
|
101
|
+
lineage(id: string): { card: Card | null; supersedes: Card[]; replacedBy: Card | null };
|
|
102
|
+
maintenance(): MaintenanceReport;
|
|
103
|
+
mergeCards(keepId: string, dropIds: string[]): { kept: Card | null; merged: number };
|
|
104
|
+
purgeCards(ids: string[]): number;
|
|
105
|
+
health(): HealthReport;
|
|
106
|
+
importData(payload: Record<string, unknown>): ImportReport;
|
|
107
|
+
/** 在按天归档的旧原文里搜(页面上的「含归档」开关)。 */
|
|
108
|
+
archiveSearch(q: string, days: number, limit: number): RawEntry[];
|
|
109
|
+
/** 删掉一条原文(热数据或归档)。 */
|
|
110
|
+
deleteTurn(cursor: number): boolean;
|
|
111
|
+
/** 把记忆沉到冷层 / 从冷层捞回来。 */
|
|
112
|
+
chillCards(ids: string[]): number;
|
|
113
|
+
warmCards(ids: string[]): number;
|
|
114
|
+
patchState(input: Record<string, unknown>): CoreState;
|
|
115
|
+
planAction(input: Record<string, unknown>): unknown;
|
|
116
|
+
exportAll(fmt: string): { body: string; mime: string; filename: string };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export class MemorySite {
|
|
120
|
+
private server: Server | null = null;
|
|
121
|
+
private port: number | null = null;
|
|
122
|
+
private readonly basePort: number;
|
|
123
|
+
private readonly webDir: string;
|
|
124
|
+
/** 进程级一次性令牌:只有这个站点发出的页面才知道,别的网页拿不到。 */
|
|
125
|
+
private readonly token = randomBytes(18).toString('base64url');
|
|
126
|
+
|
|
127
|
+
constructor(private readonly hooks: SiteHooks, webDir: string, port: number) {
|
|
128
|
+
this.webDir = resolve(webDir);
|
|
129
|
+
this.basePort = Number(port) || 7801;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
get origin(): string | null {
|
|
133
|
+
return this.port ? `http://127.0.0.1:${this.port}` : null;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async start(): Promise<string | null> {
|
|
137
|
+
if (this.server) return this.origin;
|
|
138
|
+
for (let i = 0; i < MAX_PORT_TRIES; i += 1) {
|
|
139
|
+
const port = this.basePort + i;
|
|
140
|
+
if (await this.tryListen(port)) {
|
|
141
|
+
this.port = port;
|
|
142
|
+
return this.origin;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
private tryListen(port: number): Promise<boolean> {
|
|
149
|
+
return new Promise((res) => {
|
|
150
|
+
const server = createServer((req, rsp) => {
|
|
151
|
+
this.handle(req, rsp).catch((error: unknown) => {
|
|
152
|
+
this.json(rsp, 500, { error: error instanceof Error ? error.message : String(error) });
|
|
153
|
+
});
|
|
154
|
+
});
|
|
155
|
+
server.once('error', () => {
|
|
156
|
+
try {
|
|
157
|
+
server.close();
|
|
158
|
+
} catch {
|
|
159
|
+
// 已经关了
|
|
160
|
+
}
|
|
161
|
+
res(false);
|
|
162
|
+
});
|
|
163
|
+
server.listen(port, '127.0.0.1', () => {
|
|
164
|
+
server.removeAllListeners('error');
|
|
165
|
+
server.on('error', () => {
|
|
166
|
+
// 运行期错误不该让进程挂掉
|
|
167
|
+
});
|
|
168
|
+
this.server = server;
|
|
169
|
+
res(true);
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async stop(): Promise<void> {
|
|
175
|
+
const s = this.server;
|
|
176
|
+
this.server = null;
|
|
177
|
+
this.port = null;
|
|
178
|
+
if (!s) return;
|
|
179
|
+
await new Promise<void>((res) => s.close(() => res()));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// ---- 路由 ----
|
|
183
|
+
|
|
184
|
+
private async handle(req: IncomingMessage, rsp: ServerResponse): Promise<void> {
|
|
185
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
186
|
+
const path = url.pathname;
|
|
187
|
+
|
|
188
|
+
// 只认本机这两个 Host:域名解析到 127.0.0.1(DNS 重绑定)会在这一步被挡掉
|
|
189
|
+
if (!this.hostOk(req)) return this.json(rsp, 403, { error: '只能通过 127.0.0.1 或 localhost 打开' });
|
|
190
|
+
|
|
191
|
+
if (path.startsWith('/api/')) return this.api(req, rsp, url, path);
|
|
192
|
+
|
|
193
|
+
// 原页面和新版页面共用同一个本地站点与令牌,方便并排对比。
|
|
194
|
+
if (path === '/next' || path === '/next/') {
|
|
195
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return this.text(rsp, 405, 'method not allowed');
|
|
196
|
+
return this.sendFile(rsp, 'next.html');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// 无域名、无认证:只服务本机,禁止被 iframe 之外的地方引用
|
|
200
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return this.text(rsp, 405, 'method not allowed');
|
|
201
|
+
const file = path === '/' ? 'index.html' : path.replace(/^\/+/, '');
|
|
202
|
+
return this.sendFile(rsp, file);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
private hostOk(req: IncomingMessage): boolean {
|
|
206
|
+
const host = String(req.headers.host ?? '').toLowerCase();
|
|
207
|
+
const port = this.port ?? this.basePort;
|
|
208
|
+
return host === `127.0.0.1:${port}` || host === `localhost:${port}`;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** 定长比较,别用 === 给出计时侧信道。 */
|
|
212
|
+
private tokenOk(req: IncomingMessage): boolean {
|
|
213
|
+
const got = String(req.headers['x-mcore-token'] ?? '');
|
|
214
|
+
if (got.length !== this.token.length) return false;
|
|
215
|
+
try {
|
|
216
|
+
return timingSafeEqual(Buffer.from(got), Buffer.from(this.token));
|
|
217
|
+
} catch {
|
|
218
|
+
return false;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
private async api(req: IncomingMessage, rsp: ServerResponse, url: URL, path: string): Promise<void> {
|
|
223
|
+
// GET/HEAD 是只读,随便看(跨站也读不到内容,因为没有 CORS 头);
|
|
224
|
+
// 其余方法一律要令牌——跨站页面能打到这里,但发不出这个头。
|
|
225
|
+
if (req.method !== 'GET' && req.method !== 'HEAD' && !this.tokenOk(req)) {
|
|
226
|
+
return this.json(rsp, 403, { error: '写操作需要页面上带过来的一次性令牌,刷新一下页面' });
|
|
227
|
+
}
|
|
228
|
+
if (path === '/api/snapshot' && req.method === 'GET') {
|
|
229
|
+
return this.json(rsp, 200, this.hooks.snapshot());
|
|
230
|
+
}
|
|
231
|
+
if (path === '/api/docs' && req.method === 'GET') {
|
|
232
|
+
return this.json(rsp, 200, {
|
|
233
|
+
roots: this.hooks.docRoots(),
|
|
234
|
+
files: this.hooks.docs().map(({ text, ...rest }) => ({ ...rest, chars: text.length })),
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
if (path === '/api/doc' && req.method === 'GET') {
|
|
238
|
+
const target = url.searchParams.get('path') ?? '';
|
|
239
|
+
return this.sendDoc(rsp, target);
|
|
240
|
+
}
|
|
241
|
+
if (path === '/api/export' && req.method === 'GET') {
|
|
242
|
+
const fmt = url.searchParams.get('fmt') === 'md' ? 'md' : 'json';
|
|
243
|
+
const out = this.hooks.exportAll(fmt);
|
|
244
|
+
rsp.writeHead(200, {
|
|
245
|
+
'content-type': `${out.mime}; charset=utf-8`,
|
|
246
|
+
'content-disposition': `attachment; filename="${out.filename}"`,
|
|
247
|
+
'cache-control': 'no-store',
|
|
248
|
+
});
|
|
249
|
+
return rsp.end(out.body);
|
|
250
|
+
}
|
|
251
|
+
if (path === '/api/cards' && req.method === 'POST') {
|
|
252
|
+
const body = await this.body(req);
|
|
253
|
+
const card = this.hooks.createCard(body);
|
|
254
|
+
return this.json(rsp, 201, card);
|
|
255
|
+
}
|
|
256
|
+
if (path === '/api/maintenance' && req.method === 'GET') {
|
|
257
|
+
return this.json(rsp, 200, this.hooks.maintenance());
|
|
258
|
+
}
|
|
259
|
+
if (path === '/api/merge' && req.method === 'POST') {
|
|
260
|
+
const body = await this.body(req);
|
|
261
|
+
const keep = String(body.keep ?? '');
|
|
262
|
+
const drop = Array.isArray(body.drop) ? (body.drop as unknown[]).map((x) => String(x)) : [];
|
|
263
|
+
if (!keep) return this.json(rsp, 400, { error: '缺少要保留的那条' });
|
|
264
|
+
return this.json(rsp, 200, this.hooks.mergeCards(keep, drop));
|
|
265
|
+
}
|
|
266
|
+
if (path === '/api/purge' && req.method === 'POST') {
|
|
267
|
+
const body = await this.body(req);
|
|
268
|
+
const ids = Array.isArray(body.ids) ? (body.ids as unknown[]).map((x) => String(x)) : [];
|
|
269
|
+
return this.json(rsp, 200, { removed: this.hooks.purgeCards(ids) });
|
|
270
|
+
}
|
|
271
|
+
if (path === '/api/chill' || path === '/api/warm') {
|
|
272
|
+
if (req.method !== 'POST') return this.text(rsp, 405, 'method not allowed');
|
|
273
|
+
const body = await this.body(req);
|
|
274
|
+
const ids = Array.isArray(body.ids) ? (body.ids as unknown[]).map((x) => String(x)) : [];
|
|
275
|
+
// 不带 ids 就是「全部符合条件的」:冷层一键沉、一键回暖
|
|
276
|
+
const n = path === '/api/chill' ? this.hooks.chillCards(ids) : this.hooks.warmCards(ids);
|
|
277
|
+
return this.json(rsp, 200, { changed: n });
|
|
278
|
+
}
|
|
279
|
+
if (path === '/api/health' && req.method === 'GET') {
|
|
280
|
+
return this.json(rsp, 200, this.hooks.health());
|
|
281
|
+
}
|
|
282
|
+
if (path === '/api/archive' && req.method === 'GET') {
|
|
283
|
+
const q = (url.searchParams.get('q') ?? '').trim();
|
|
284
|
+
const days = Number(url.searchParams.get('days') ?? 90) || 90;
|
|
285
|
+
const limit = Number(url.searchParams.get('limit') ?? 40) || 40;
|
|
286
|
+
return this.json(rsp, 200, q ? this.hooks.archiveSearch(q, days, limit) : []);
|
|
287
|
+
}
|
|
288
|
+
const turnMatch = /^\/api\/turns\/(\d{1,12})$/.exec(path);
|
|
289
|
+
if (turnMatch && req.method === 'DELETE') {
|
|
290
|
+
return this.json(rsp, 200, { removed: this.hooks.deleteTurn(Number(turnMatch[1])) });
|
|
291
|
+
}
|
|
292
|
+
if (path === '/api/import' && req.method === 'POST') {
|
|
293
|
+
let body: Record<string, unknown>;
|
|
294
|
+
try {
|
|
295
|
+
body = await this.body(req, MAX_IMPORT);
|
|
296
|
+
} catch (err) {
|
|
297
|
+
return this.json(rsp, 400, { error: err instanceof Error ? err.message : '读不了请求体' });
|
|
298
|
+
}
|
|
299
|
+
try {
|
|
300
|
+
return this.json(rsp, 200, this.hooks.importData(body));
|
|
301
|
+
} catch (err) {
|
|
302
|
+
return this.json(rsp, 400, { error: err instanceof Error ? err.message : '导入失败' });
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
const actionMatch = /^\/api\/cards\/([\w-]{1,60})\/(retire|restore|lineage)$/.exec(path);
|
|
306
|
+
if (actionMatch) {
|
|
307
|
+
const [, id, action] = actionMatch;
|
|
308
|
+
if (action === 'lineage' && req.method === 'GET') {
|
|
309
|
+
return this.json(rsp, 200, this.hooks.lineage(id));
|
|
310
|
+
}
|
|
311
|
+
if (req.method === 'POST') {
|
|
312
|
+
if (action === 'retire') return this.hooks.retireCard(id) ? this.json(rsp, 200, { ok: true }) : this.json(rsp, 404, { error: '没有这条记忆' });
|
|
313
|
+
if (action === 'restore') return this.hooks.restoreCard(id) ? this.json(rsp, 200, { ok: true }) : this.json(rsp, 404, { error: '没有这条记忆' });
|
|
314
|
+
}
|
|
315
|
+
return this.json(rsp, 405, { error: 'method not allowed' });
|
|
316
|
+
}
|
|
317
|
+
const cardMatch = /^\/api\/cards\/([\w-]{1,60})$/.exec(path);
|
|
318
|
+
if (cardMatch) {
|
|
319
|
+
const id = cardMatch[1];
|
|
320
|
+
if (req.method === 'PATCH' || req.method === 'PUT') {
|
|
321
|
+
const body = await this.body(req);
|
|
322
|
+
const card = this.hooks.updateCard(id, body);
|
|
323
|
+
return card ? this.json(rsp, 200, card) : this.json(rsp, 404, { error: '没有这条记忆' });
|
|
324
|
+
}
|
|
325
|
+
if (req.method === 'DELETE') {
|
|
326
|
+
return this.hooks.deleteCard(id) ? this.json(rsp, 200, { ok: true }) : this.json(rsp, 404, { error: '没有这条记忆' });
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
if (path === '/api/state' && req.method === 'POST') {
|
|
330
|
+
const body = await this.body(req);
|
|
331
|
+
return this.json(rsp, 200, this.hooks.patchState(body));
|
|
332
|
+
}
|
|
333
|
+
if (path === '/api/plans' && req.method === 'POST') {
|
|
334
|
+
const body = await this.body(req);
|
|
335
|
+
return this.json(rsp, 200, this.hooks.planAction(body));
|
|
336
|
+
}
|
|
337
|
+
return this.json(rsp, 404, { error: `未知接口 ${path}` });
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
private sendDoc(rsp: ServerResponse, rawPath: string): void {
|
|
341
|
+
let target: string;
|
|
342
|
+
try {
|
|
343
|
+
target = normalize(decodeURIComponent(rawPath));
|
|
344
|
+
} catch {
|
|
345
|
+
return this.text(rsp, 400, 'bad path');
|
|
346
|
+
}
|
|
347
|
+
const roots = this.hooks.docRoots();
|
|
348
|
+
const abs = resolve(target);
|
|
349
|
+
const allowed = roots.some((root) => {
|
|
350
|
+
const base = resolve(root);
|
|
351
|
+
const prefix = base.endsWith(sep) ? base : base + sep;
|
|
352
|
+
return abs.toLowerCase() === base.toLowerCase() || abs.toLowerCase().startsWith(prefix.toLowerCase());
|
|
353
|
+
});
|
|
354
|
+
if (!allowed) return this.json(rsp, 403, { error: '只能读配置里允许的目录' });
|
|
355
|
+
if (!existsSync(target)) return this.json(rsp, 404, { error: '文件不在了' });
|
|
356
|
+
const file = this.hooks.docs().find((d) => resolve(d.path) === resolve(target));
|
|
357
|
+
if (!file) return this.json(rsp, 404, { error: '文件不在扫描结果里(可能太大或后缀不符)' });
|
|
358
|
+
return this.json(rsp, 200, { path: file.path, name: file.name, rel: file.rel, mtimeMs: file.mtimeMs, text: file.text });
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// ---- 静态文件 ----
|
|
362
|
+
|
|
363
|
+
private sendFile(rsp: ServerResponse, rel: string): void {
|
|
364
|
+
const safe = normalize(rel).replace(/^([.][.][\\/])+/, '');
|
|
365
|
+
const full = join(this.webDir, safe);
|
|
366
|
+
if (!full.startsWith(this.webDir + sep) && full !== this.webDir) return this.text(rsp, 403, 'forbidden');
|
|
367
|
+
if (!existsSync(full)) return this.text(rsp, 404, 'not found');
|
|
368
|
+
try {
|
|
369
|
+
if (!statSync(full).isFile()) return this.text(rsp, 404, 'not found');
|
|
370
|
+
const body = readFileSync(full);
|
|
371
|
+
const type = MIME[extname(full).toLowerCase()] ?? 'application/octet-stream';
|
|
372
|
+
// 首页注入一次性令牌:app.js 把它放进每个写请求的头里。
|
|
373
|
+
// 这份 HTML 不进缓存,否则进程重启后旧令牌会让所有写操作 403。
|
|
374
|
+
if (safe === 'index.html' || safe === 'next.html') {
|
|
375
|
+
const html = body
|
|
376
|
+
.toString('utf8')
|
|
377
|
+
.replace('<head>', `<head>\n<meta name="mcore-token" content="${this.token}">`);
|
|
378
|
+
rsp.writeHead(200, {
|
|
379
|
+
'content-type': type,
|
|
380
|
+
'cache-control': 'no-store',
|
|
381
|
+
'x-content-type-options': 'nosniff',
|
|
382
|
+
});
|
|
383
|
+
return rsp.end(html);
|
|
384
|
+
}
|
|
385
|
+
rsp.writeHead(200, {
|
|
386
|
+
'content-type': type,
|
|
387
|
+
'cache-control': 'no-cache',
|
|
388
|
+
'x-content-type-options': 'nosniff',
|
|
389
|
+
});
|
|
390
|
+
rsp.end(body);
|
|
391
|
+
} catch {
|
|
392
|
+
this.text(rsp, 500, 'read failed');
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
private readBody(req: IncomingMessage, limit = MAX_BODY): Promise<string> {
|
|
397
|
+
return new Promise((res, rej) => {
|
|
398
|
+
let size = 0;
|
|
399
|
+
const chunks: Buffer[] = [];
|
|
400
|
+
req.on('data', (chunk: Buffer) => {
|
|
401
|
+
size += chunk.length;
|
|
402
|
+
if (size > limit) {
|
|
403
|
+
rej(new Error('请求体太大'));
|
|
404
|
+
req.destroy();
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
chunks.push(chunk);
|
|
408
|
+
});
|
|
409
|
+
req.on('end', () => res(Buffer.concat(chunks).toString('utf8')));
|
|
410
|
+
req.on('error', rej);
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
private async body(req: IncomingMessage, limit = MAX_BODY): Promise<Record<string, unknown>> {
|
|
415
|
+
const raw = await this.readBody(req, limit);
|
|
416
|
+
if (!raw.trim()) return {};
|
|
417
|
+
try {
|
|
418
|
+
const parsed = JSON.parse(raw) as unknown;
|
|
419
|
+
return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};
|
|
420
|
+
} catch {
|
|
421
|
+
throw new Error('请求体不是合法 JSON');
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
private json(rsp: ServerResponse, code: number, payload: unknown): void {
|
|
426
|
+
const body = JSON.stringify(payload);
|
|
427
|
+
rsp.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
428
|
+
rsp.end(body);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
private text(rsp: ServerResponse, code: number, msg: string): void {
|
|
432
|
+
rsp.writeHead(code, { 'content-type': 'text/plain; charset=utf-8' });
|
|
433
|
+
rsp.end(msg);
|
|
434
|
+
}
|
|
435
|
+
}
|