cortico-world-memory-core 0.4.3 → 0.4.4

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 CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.4
4
+
5
+ 站点安全修复。来源是仓库 issue #1(Phantivia,扩展市场审查):写接口没有鉴权,任意网页可跨站写卡。**方向完全正确**,我按他给的两条建议都做了,并且先复现了四个事实:`text/plain` 跨站 POST 能写进去、伪造 `Host` 能拿到 200、`OPTIONS` 是 404、响应里没有 CORS 头。
6
+
7
+ - **写接口加一次性令牌**:`MemorySite` 启动时生成 `randomBytes(18)`,首页 HTML 注入 `<meta name="mcore-token">`,`app.js` 把它放进所有写请求的 `x-mcore-token` 头。校验用 `timingSafeEqual`。其他网页能打 localhost,但拿不到这个头。
8
+ - **Host 白名单**:只认 `127.0.0.1:<port>` 和 `localhost:<port>`,其他 Host 一律 403——包括首页。这条专门挡 DNS 重绑定:光有令牌挡不住重绑定(攻击者能读到带令牌的首页),光有 Host 白名单也挡不住用户浏览器里的普通 CSRF。
9
+ - **首页 `no-store`**:令牌每次启动都换,页面缓存住旧令牌会让所有写操作 403。
10
+ - **只读接口保持无令牌**:`/api/snapshot`、`/api/export` 等跨站读不到响应体(没有 CORS 头),导出链接也要能直接下载。
11
+ - **新增 `tools/test-site-auth.ts`**:10 项,覆盖令牌注入、伪造 Host、无令牌/错令牌/正确令牌、`localhost` 放行、导出仍可下载。
12
+
13
+ 顺带一提:`Content-Type` 那条建议(只接受 `application/json`)我没单独做。因为写了「必须带令牌」之后它已经没有增量——没有令牌时,无论什么 Content-Type 都进不来。
14
+
3
15
  ## 0.4.3
4
16
 
5
17
  隐私和手滑这两件事,都是之前列出来一直没做的。
package/README.md CHANGED
@@ -65,12 +65,16 @@ pnpm add cortico-world-memory-core
65
65
 
66
66
  导出与导入:`⋯` 菜单里能导出 Markdown / JSON。JSON 是整包(卡片 + 原文 + 日程 + 状态),可以原样 `POST /api/import` 导回来——**只加不覆盖**,同 id 或同类型同文本会跳过,所以重复导同一个文件是安全的。水位只往前推,不会被旧备份倒回去。
67
67
 
68
- 四条实现约束(改的时候别破坏):
68
+ 六条实现约束(改的时候别破坏):
69
69
 
70
- 1. 只绑 `127.0.0.1` —— 站点没有身份认证,不能对局域网露面;
71
- 2. 端口被占自动 +1,起不来只少一个链接,不影响 World 挂载;
72
- 3. 写操作走插件内存里的同一个 store,不直接改文件,否则宿主下一次 `save()` 会把文件覆盖回去;
73
- 4. `/api/doc` 只允许读配置里列出的目录。
70
+ 1. 只绑 `127.0.0.1` —— 不对局域网露面;
71
+ 2. 只认 `127.0.0.1` / `localhost` 这两个 Host —— 别的域名解析到本机(DNS 重绑定)连首页都拿不到;
72
+ 3. 写接口必须带首页注入的一次性令牌(`x-mcore-token`)—— 任何网页都能打 localhost,但发不出这个头;令牌每次启动重新生成,旧页面写失败会提示刷新;
73
+ 4. 端口被占自动 +1,起不来只少一个链接,不影响 World 挂载;
74
+ 5. 写操作走插件内存里的同一个 store,不直接改文件,否则宿主下一次 `save()` 会把文件覆盖回去;
75
+ 6. `/api/doc` 只允许读配置里列出的目录。
76
+
77
+ 只读接口(`/api/snapshot`、`/api/export`、`/api/health` 等)不校验令牌:跨站拿不到响应体(没有 CORS 头),导出链接也要能直接下载。真正值钱的是「写」和「读到内容」这两件事,前者靠令牌,后者靠 Host 白名单。
74
78
 
75
79
  ## 省 token 的四条硬约束
76
80
 
@@ -139,6 +143,12 @@ node --experimental-transform-types tools/test-capture.ts
139
143
  # World 层:用假宿主真启动一次,跑写、查、closes 取代
140
144
  node --experimental-transform-types tools/test-world.ts
141
145
 
146
+ # 站点鉴权:令牌注入、伪造 Host、无令牌/错令牌、导出仍可下载
147
+ node --experimental-transform-types tools/test-site-auth.ts
148
+
149
+ # 前端静态自检:DOM id、S 属性、前后端接口对账
150
+ node --experimental-transform-types tools/audit-webui.ts
151
+
142
152
  # 改了工具或提示词之后,重新生成市场详情页读的自描述
143
153
  node --experimental-transform-types tools/build-describe.ts
144
154
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cortico-world-memory-core",
3
- "version": "0.4.3",
3
+ "version": "0.4.4",
4
4
  "type": "module",
5
5
  "description": "Cortico World 长期记忆:一张卡片表 + 4 个工具 + 一段静态提示词,附状态、日程、主动开口与本地记忆地图。\n\nQQ 交流群:745879632",
6
6
  "keywords": [
package/src/site.ts CHANGED
@@ -1,14 +1,17 @@
1
1
  /**
2
2
  * 记忆地图的本地站点:一个只绑 127.0.0.1 的小 HTTP 服务。
3
3
  *
4
- * 四条约束(和参考实现一致,改的时候别破坏):
5
- * 1) **只绑 127.0.0.1** —— 站点没有身份认证,记忆不能对局域网露面;
6
- * 2) **端口被占就 +1 重试**,起不来不算致命,只少一个链接;
7
- * 3) 写操作走**插件内存里的同一份 store**,不直接改文件 ——
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**,不直接改文件 ——
8
10
  * 否则宿主下一次 save() 会用内存状态把文件覆盖回去;
9
- * 4) 读文件接口只允许在已扫描的目录内,防目录穿越。
11
+ * 6) 读文件接口只允许在已扫描的目录内,防目录穿越。
10
12
  */
11
13
  import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
14
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
12
15
  import { existsSync, readFileSync, statSync } from 'node:fs';
13
16
  import { extname, join, normalize, resolve, sep } from 'node:path';
14
17
  import type { Card, CoreState, PlanItem, RawEntry } from './store.ts';
@@ -112,6 +115,8 @@ export class MemorySite {
112
115
  private port: number | null = null;
113
116
  private readonly basePort: number;
114
117
  private readonly webDir: string;
118
+ /** 进程级一次性令牌:只有这个站点发出的页面才知道,别的网页拿不到。 */
119
+ private readonly token = randomBytes(18).toString('base64url');
115
120
 
116
121
  constructor(private readonly hooks: SiteHooks, webDir: string, port: number) {
117
122
  this.webDir = resolve(webDir);
@@ -174,6 +179,9 @@ export class MemorySite {
174
179
  const url = new URL(req.url ?? '/', 'http://127.0.0.1');
175
180
  const path = url.pathname;
176
181
 
182
+ // 只认本机这两个 Host:域名解析到 127.0.0.1(DNS 重绑定)会在这一步被挡掉
183
+ if (!this.hostOk(req)) return this.json(rsp, 403, { error: '只能通过 127.0.0.1 或 localhost 打开' });
184
+
177
185
  if (path.startsWith('/api/')) return this.api(req, rsp, url, path);
178
186
 
179
187
  // 无域名、无认证:只服务本机,禁止被 iframe 之外的地方引用
@@ -182,7 +190,29 @@ export class MemorySite {
182
190
  return this.sendFile(rsp, file);
183
191
  }
184
192
 
193
+ private hostOk(req: IncomingMessage): boolean {
194
+ const host = String(req.headers.host ?? '').toLowerCase();
195
+ const port = this.port ?? this.basePort;
196
+ return host === `127.0.0.1:${port}` || host === `localhost:${port}`;
197
+ }
198
+
199
+ /** 定长比较,别用 === 给出计时侧信道。 */
200
+ private tokenOk(req: IncomingMessage): boolean {
201
+ const got = String(req.headers['x-mcore-token'] ?? '');
202
+ if (got.length !== this.token.length) return false;
203
+ try {
204
+ return timingSafeEqual(Buffer.from(got), Buffer.from(this.token));
205
+ } catch {
206
+ return false;
207
+ }
208
+ }
209
+
185
210
  private async api(req: IncomingMessage, rsp: ServerResponse, url: URL, path: string): Promise<void> {
211
+ // GET/HEAD 是只读,随便看(跨站也读不到内容,因为没有 CORS 头);
212
+ // 其余方法一律要令牌——跨站页面能打到这里,但发不出这个头。
213
+ if (req.method !== 'GET' && req.method !== 'HEAD' && !this.tokenOk(req)) {
214
+ return this.json(rsp, 403, { error: '写操作需要页面上带过来的一次性令牌,刷新一下页面' });
215
+ }
186
216
  if (path === '/api/snapshot' && req.method === 'GET') {
187
217
  return this.json(rsp, 200, this.hooks.snapshot());
188
218
  }
@@ -318,8 +348,22 @@ export class MemorySite {
318
348
  try {
319
349
  if (!statSync(full).isFile()) return this.text(rsp, 404, 'not found');
320
350
  const body = readFileSync(full);
351
+ const type = MIME[extname(full).toLowerCase()] ?? 'application/octet-stream';
352
+ // 首页注入一次性令牌:app.js 把它放进每个写请求的头里。
353
+ // 这份 HTML 不进缓存,否则进程重启后旧令牌会让所有写操作 403。
354
+ if (safe === 'index.html') {
355
+ const html = body
356
+ .toString('utf8')
357
+ .replace('<head>', `<head>\n<meta name="mcore-token" content="${this.token}">`);
358
+ rsp.writeHead(200, {
359
+ 'content-type': type,
360
+ 'cache-control': 'no-store',
361
+ 'x-content-type-options': 'nosniff',
362
+ });
363
+ return rsp.end(html);
364
+ }
321
365
  rsp.writeHead(200, {
322
- 'content-type': MIME[extname(full).toLowerCase()] ?? 'application/octet-stream',
366
+ 'content-type': type,
323
367
  'cache-control': 'no-cache',
324
368
  'x-content-type-options': 'nosniff',
325
369
  });
package/webui/app.js CHANGED
@@ -201,9 +201,17 @@ async function purgeWithUndo(ids) {
201
201
  return removed;
202
202
  }
203
203
 
204
- async function api(path, init = {}) { const res = await fetch(path, {
204
+ // 服务端把一次性令牌写进首页的 meta,写接口靠它认「这是自己发的页面」
205
+ const TOKEN = document.querySelector('meta[name="mcore-token"]')?.content ?? '';
206
+
207
+ async function api(path, init = {}) {
208
+ const res = await fetch(path, {
205
209
  ...init,
206
- headers: { 'content-type': 'application/json', ...(init.headers ?? {}) },
210
+ headers: {
211
+ 'content-type': 'application/json',
212
+ ...(TOKEN ? { 'x-mcore-token': TOKEN } : {}),
213
+ ...(init.headers ?? {}),
214
+ },
207
215
  });
208
216
  if (!res.ok) {
209
217
  let msg = `${res.status}`;