cortico-world-memory-core 0.4.2 → 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,26 @@
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
+
15
+ ## 0.4.3
16
+
17
+ 隐私和手滑这两件事,都是之前列出来一直没做的。
18
+
19
+ - **原文来源脱敏**:`turns.jsonl` 里的 `sender` 原来存的是 `private:1940008084` 这种明文账号,目录一同步到网盘或备份就跟着泄露。现在只留后 4 位(`private:…8084`)。三道都做了:写入时脱敏、读取时再脱一次(老文件即使没改也不会露)、启动时把 `archive/` 下的旧文件抹一遍(`state.senderScrubbedAt` 记时间,只做一次)。
20
+ - **原文单条删除**:`DELETE /api/turns/:cursor`,热数据和归档都支持;删的是本地这一行,不影响对方那边,删完不会因为水位回退被重新录回来。页面上鼠标移到某一行,右上角出现「×」。
21
+ - **修掉 `load()` 里 `if (!quiet) render(); else render();`** 的冗余分支。
22
+ - **新增 `tools/audit-webui.ts`**:静态检查三件事——`$('#id')` 引用的元素在 HTML 里是否存在、`S.xxx` 读取的属性是否在 `S` 上定义、前端调的 `/api/*` 在后端是否有对应路由。0.4.2 里那个「搜索框从 0.1.0 起就抛异常」的 bug,正属于这套检查能提前抓到的类型。
23
+
3
24
  ## 0.4.2
4
25
 
5
26
  按「第一批」做的三件事,其中第一件顺带挖出一个从 0.1.0 就带着的 bug。
package/README.md CHANGED
@@ -53,7 +53,7 @@ pnpm add cortico-world-memory-core
53
53
  | 图谱 | 力导向图:节点大小=权重、颜色=类型、连线=共同标签或同一天;滚轮缩放、拖动、双击适应 |
54
54
  | 时间线 | 按天分组,带权重条与截止时间 |
55
55
  | 列表 | 可排序表格(类型 / 内容 / 权重 / 来源 / 标签 / 记于 / 使用次数),权重带微条 |
56
- | 原文 | 最近 7 天的对话原文,搜索高亮;勾「含归档」能连 `archive/` 里更早的句子一起搜,命中按天分组列在下面 |
56
+ | 原文 | 最近 7 天的对话原文,搜索高亮;勾「含归档」能连 `archive/` 里更早的句子一起搜,命中按天分组列在下面;鼠标移到某行可以单条删除 |
57
57
  | 文件 | 工作区里被检索的 md / txt(只读) |
58
58
  | 维护 | 重复 / 疑似作废 / 垃圾 / **承诺** / 回收站;承诺页能补截止时间、标记做完;彻底的删除会先列出要删的东西,10 秒内可撤销 |
59
59
  | 体检 | 在用 / 从没被召回 / 召回次数 / 原文规模、近 14 天新增、承诺与备份状态;从没被召回的卡能一键退休 |
@@ -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
 
@@ -107,7 +111,7 @@ pnpm add cortico-world-memory-core
107
111
  data/memory-core/
108
112
  ├─ cards.jsonl 卡片(一行一张,可以直接看)
109
113
  ├─ backups/ 每天第一笔写入前自动存的副本(cards-YYYY-MM-DD.jsonl,留 7 份)
110
- ├─ turns.jsonl 对方最近的对话原文(按 captureSenders 过滤)
114
+ ├─ turns.jsonl 对方最近的对话原文(sender 只留后 4 位,不留完整账号)
111
115
  ├─ archive/ 过期的原文按天归档(YYYY-MM-DD.jsonl),可搜可删
112
116
  ├─ plans.json 今天的日程
113
117
  ├─ state.json 精力/心情/活动/位置/主动计数
@@ -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.2",
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';
@@ -100,6 +103,8 @@ export interface SiteHooks {
100
103
  importData(payload: Record<string, unknown>): ImportReport;
101
104
  /** 在按天归档的旧原文里搜(页面上的「含归档」开关)。 */
102
105
  archiveSearch(q: string, days: number, limit: number): RawEntry[];
106
+ /** 删掉一条原文(热数据或归档)。 */
107
+ deleteTurn(cursor: number): boolean;
103
108
  patchState(input: Record<string, unknown>): CoreState;
104
109
  planAction(input: Record<string, unknown>): unknown;
105
110
  exportAll(fmt: string): { body: string; mime: string; filename: string };
@@ -110,6 +115,8 @@ export class MemorySite {
110
115
  private port: number | null = null;
111
116
  private readonly basePort: number;
112
117
  private readonly webDir: string;
118
+ /** 进程级一次性令牌:只有这个站点发出的页面才知道,别的网页拿不到。 */
119
+ private readonly token = randomBytes(18).toString('base64url');
113
120
 
114
121
  constructor(private readonly hooks: SiteHooks, webDir: string, port: number) {
115
122
  this.webDir = resolve(webDir);
@@ -172,6 +179,9 @@ export class MemorySite {
172
179
  const url = new URL(req.url ?? '/', 'http://127.0.0.1');
173
180
  const path = url.pathname;
174
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
+
175
185
  if (path.startsWith('/api/')) return this.api(req, rsp, url, path);
176
186
 
177
187
  // 无域名、无认证:只服务本机,禁止被 iframe 之外的地方引用
@@ -180,7 +190,29 @@ export class MemorySite {
180
190
  return this.sendFile(rsp, file);
181
191
  }
182
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
+
183
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
+ }
184
216
  if (path === '/api/snapshot' && req.method === 'GET') {
185
217
  return this.json(rsp, 200, this.hooks.snapshot());
186
218
  }
@@ -233,6 +265,10 @@ export class MemorySite {
233
265
  const limit = Number(url.searchParams.get('limit') ?? 40) || 40;
234
266
  return this.json(rsp, 200, q ? this.hooks.archiveSearch(q, days, limit) : []);
235
267
  }
268
+ const turnMatch = /^\/api\/turns\/(\d{1,12})$/.exec(path);
269
+ if (turnMatch && req.method === 'DELETE') {
270
+ return this.json(rsp, 200, { removed: this.hooks.deleteTurn(Number(turnMatch[1])) });
271
+ }
236
272
  if (path === '/api/import' && req.method === 'POST') {
237
273
  let body: Record<string, unknown>;
238
274
  try {
@@ -312,8 +348,22 @@ export class MemorySite {
312
348
  try {
313
349
  if (!statSync(full).isFile()) return this.text(rsp, 404, 'not found');
314
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
+ }
315
365
  rsp.writeHead(200, {
316
- 'content-type': MIME[extname(full).toLowerCase()] ?? 'application/octet-stream',
366
+ 'content-type': type,
317
367
  'cache-control': 'no-cache',
318
368
  'x-content-type-options': 'nosniff',
319
369
  });
package/src/store.ts CHANGED
@@ -84,6 +84,8 @@ export interface CoreState {
84
84
  backfillFrom?: number;
85
85
  backfillTo?: number;
86
86
  };
87
+ /** 归档里的账号号码抹过一次之后记下时间,不再重复扫。 */
88
+ senderScrubbedAt?: string;
87
89
  }
88
90
 
89
91
  export function ensureDir(dir: string): void {
@@ -145,6 +147,14 @@ function clamp01(n: number): number {
145
147
  return Number.isFinite(n) ? Math.min(1, Math.max(0, n)) : 0.5;
146
148
  }
147
149
 
150
+ /**
151
+ * 原文的来源里带平台账号(`private:1940008084`),原样落盘就是明文号码,
152
+ * 目录一同步到网盘或备份就跟着泄露。只留后 4 位——够区分是谁,不够认出是谁。
153
+ */
154
+ export function maskSender(sender: string): string {
155
+ return String(sender ?? '').replace(/\d{5,}/g, (digits) => `…${digits.slice(-4)}`);
156
+ }
157
+
148
158
  export class CardStore {
149
159
  private cards: Card[] = [];
150
160
  private readonly file: string;
@@ -709,6 +719,8 @@ export class RawLog {
709
719
  if (!e || typeof e.text !== 'string') continue;
710
720
  const at = Date.parse(e.ts);
711
721
  if (!Number.isFinite(at)) continue;
722
+ // 读的时候就脱敏:即便文件里还留着老格式,界面和快照也不会露号码
723
+ e.sender = maskSender(e.sender);
712
724
  (at >= cutoff ? kept : expired).push(e);
713
725
  } catch {
714
726
  // 跳过坏行
@@ -809,6 +821,77 @@ export class RawLog {
809
821
  return { days: files.length, bytes, oldest: files[0]?.day ?? '' };
810
822
  }
811
823
 
824
+ /** 删掉一条原文:热数据从内存表里摘掉重写;在归档里就改写那天对应的文件。 */
825
+ remove(cursor: number): boolean {
826
+ const id = Number(cursor);
827
+ if (!Number.isFinite(id)) return false;
828
+ const at = this.entries.findIndex((e) => e.cursor === id);
829
+ if (at >= 0) {
830
+ this.entries.splice(at, 1);
831
+ this.rewrite();
832
+ return true;
833
+ }
834
+ for (const { file } of this.archiveFiles()) {
835
+ try {
836
+ const lines = readFileSync(file, 'utf8').split('\n');
837
+ let hit = -1;
838
+ for (let i = 0; i < lines.length; i += 1) {
839
+ if (!lines[i].trim()) continue;
840
+ try {
841
+ if ((JSON.parse(lines[i]) as RawEntry).cursor === id) {
842
+ hit = i;
843
+ break;
844
+ }
845
+ } catch {
846
+ // 坏行跳过
847
+ }
848
+ }
849
+ if (hit < 0) continue;
850
+ lines.splice(hit, 1);
851
+ const kept = lines.filter((line) => line.trim());
852
+ if (!kept.length) {
853
+ // 那天只有这一条,删完就把空文件收掉,免得归档里留个 0 行的日期
854
+ unlinkSync(file);
855
+ } else {
856
+ writeAtomic(file, `${kept.join('\n')}\n`);
857
+ }
858
+ return true;
859
+ } catch {
860
+ // 读不了就试下一个文件
861
+ }
862
+ }
863
+ return false;
864
+ }
865
+
866
+ /** 热数据里的旧格式已经由 load() 的 rewrite 抹掉了,这里只处理 archive/ 下的文件。 */
867
+ scrubArchiveSenders(): number {
868
+ let changed = 0;
869
+ for (const { file } of this.archiveFiles()) {
870
+ try {
871
+ const lines = readFileSync(file, 'utf8').split('\n');
872
+ let dirty = false;
873
+ const out = lines.map((line) => {
874
+ if (!line.trim()) return line;
875
+ try {
876
+ const e = JSON.parse(line) as RawEntry;
877
+ const masked = maskSender(e.sender);
878
+ if (masked === e.sender) return line;
879
+ e.sender = masked;
880
+ dirty = true;
881
+ changed += 1;
882
+ return JSON.stringify(e);
883
+ } catch {
884
+ return line;
885
+ }
886
+ });
887
+ if (dirty) writeAtomic(file, out.join('\n'));
888
+ } catch {
889
+ // 读不了就跳过
890
+ }
891
+ }
892
+ return changed;
893
+ }
894
+
812
895
  /** 归档总行数。健康面板按需调用,不进热路径。 */
813
896
  archiveLines(): number {
814
897
  let n = 0;
@@ -835,7 +918,10 @@ export class RawLog {
835
918
  if (!line.trim()) continue;
836
919
  try {
837
920
  const e = JSON.parse(line) as RawEntry;
838
- if (e && typeof e.text === 'string') out.push(e);
921
+ if (e && typeof e.text === 'string') {
922
+ e.sender = maskSender(e.sender);
923
+ out.push(e);
924
+ }
839
925
  } catch {
840
926
  // 跳过坏行
841
927
  }
@@ -878,7 +964,10 @@ export class RawLog {
878
964
  if (!items.length) return 0;
879
965
  // 回放时一次几千行,用 Set 判重,别拿 some() 平方级扫
880
966
  const have = new Set(this.entries.map((e) => e.cursor));
881
- const fresh = items.filter((item) => !have.has(item.cursor));
967
+ const fresh = items
968
+ .filter((item) => !have.has(item.cursor))
969
+ // 落盘前统一脱敏:不管调用方传的是原始 key 还是已脱敏的,这里都兜一道
970
+ .map((item) => ({ ...item, sender: maskSender(item.sender) }));
882
971
  if (!fresh.length) return 0;
883
972
  this.entries.push(...fresh);
884
973
  const cutoff = Date.now() - this.retentionDays * 86_400_000;
package/src/world.ts CHANGED
@@ -20,6 +20,7 @@ import {
20
20
  CardStore,
21
21
  RawLog,
22
22
  ensureDir,
23
+ maskSender,
23
24
  readJson,
24
25
  writeJson,
25
26
  type CardKind,
@@ -266,6 +267,19 @@ export class MemoryCoreWorld implements World {
266
267
  this.stopped = false;
267
268
  ensureDir(this.dataDir);
268
269
  this.importOnce();
270
+ // 归档里可能还留着老格式的明文账号,抹一次就够(热数据在 load 时已经抹了)
271
+ if (!this.state.senderScrubbedAt) {
272
+ const scrubbed = this.raw.scrubArchiveSenders();
273
+ this.state.senderScrubbedAt = new Date().toISOString();
274
+ this.save(true);
275
+ if (scrubbed) {
276
+ try {
277
+ host.log?.info?.(`[memory-core] 归档里 ${scrubbed} 条来源已脱敏`);
278
+ } catch {
279
+ // 日志失败不影响挂载
280
+ }
281
+ }
282
+ }
269
283
  try {
270
284
  host.log?.info?.('[memory-core] 启动', {
271
285
  dataDir: this.dataDir,
@@ -463,6 +477,7 @@ export class MemoryCoreWorld implements World {
463
477
  const cap = Math.min(50, Math.max(1, Number(limit) || 40));
464
478
  return rankRaw(this.raw.readArchive(span, 20000), query, cap);
465
479
  },
480
+ deleteTurn: (cursor: number) => this.raw.remove(cursor),
466
481
  mergeCards: (keepId: string, dropIds: string[]) => this.store.merge(keepId, dropIds),
467
482
  purgeCards: (ids: string[]) => this.store.purge(ids),
468
483
  patchState: (input: Record<string, unknown>) => {
@@ -596,7 +611,7 @@ export class MemoryCoreWorld implements World {
596
611
  entries.push({
597
612
  cursor,
598
613
  ts: typeof t.ts === 'string' && t.ts ? t.ts : new Date().toISOString(),
599
- sender: String(t.sender ?? 'import').slice(0, 40),
614
+ sender: maskSender(String(t.sender ?? 'import')).slice(0, 40),
600
615
  text: t.text.slice(0, 200),
601
616
  });
602
617
  }
@@ -981,7 +996,7 @@ export class MemoryCoreWorld implements World {
981
996
  if (/^\[(表情包|CQ:|图片)/.test(text)) continue;
982
997
  if (/^[\p{P}\p{S}\s]+$/u.test(text)) continue;
983
998
  if (/^\[[^\]]{0,12}\]$/.test(text.trim())) continue;
984
- items.push({ cursor: e.cursor, ts: e.ts, sender: key.slice(0, 40), text });
999
+ items.push({ cursor: e.cursor, ts: e.ts, sender: maskSender(key).slice(0, 40), text });
985
1000
  }
986
1001
  // 按窗口边界推进,不按「最后一个匹配到的 cursor」:窗口里可能一条 external 都没有
987
1002
  from = to;
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}`;
@@ -270,8 +278,7 @@ async function load({ quiet = false } = {}) {
270
278
  try {
271
279
  const snap = await api('/api/snapshot');
272
280
  S.snap = snap;
273
- if (!quiet) render();
274
- else render();
281
+ render();
275
282
  } catch (err) {
276
283
  toast(`读不到数据:${err.message}`, true);
277
284
  }
@@ -1170,6 +1177,7 @@ function turnRow(t) {
1170
1177
  return `<div class="turn">
1171
1178
  <div><time>${fmtTime(t.ts).slice(6)}</time><div class="who">${esc(shortSender(t.sender))}</div></div>
1172
1179
  <div class="msg">${highlight(t.text.slice(0, 600), S.query)}</div>
1180
+ <button class="turn-del" data-cursor="${t.cursor}" title="删掉这条原文" aria-label="删掉这条原文">×</button>
1173
1181
  </div>`;
1174
1182
  }
1175
1183
 
@@ -1951,6 +1959,25 @@ $('#view-timeline').addEventListener('click', (event) => {
1951
1959
  selectCard(item.dataset.id);
1952
1960
  });
1953
1961
 
1962
+ // 原文单条删除:按钮随行渲染,用事件委托,重绘后不用重新绑定
1963
+ $('#view-turns').addEventListener('click', async (event) => {
1964
+ const btn = event.target.closest('.turn-del');
1965
+ if (!btn) return;
1966
+ const cursor = Number(btn.dataset.cursor);
1967
+ if (!Number.isFinite(cursor)) return;
1968
+ if (!confirm('删掉这条原文?只删本地这一行,对方那边不受影响。删了补不回来。')) return;
1969
+ try {
1970
+ const res = await api(`/api/turns/${cursor}`, { method: 'DELETE', body: '{}' });
1971
+ if (!res?.removed) return toast('没找到这条', true);
1972
+ S.archiveQ = '';
1973
+ S.archive = null;
1974
+ await load();
1975
+ toast('已删掉');
1976
+ } catch (err) {
1977
+ toast(`删除失败:${err.message}`, true);
1978
+ }
1979
+ });
1980
+
1954
1981
  $('#view-table').addEventListener('click', (event) => {
1955
1982
  const th = event.target.closest('th[data-sort]');
1956
1983
  if (th) {
package/webui/style.css CHANGED
@@ -719,3 +719,18 @@ kbd {
719
719
  font-size: 11px; color: var(--warn);
720
720
  }
721
721
  .archive-head span { color: var(--ink-dim); }
722
+
723
+ /* ── 原文单条删除 ───────────────────────────────────── */
724
+ .turn { position: relative; padding-right: 22px; }
725
+ .turn-del {
726
+ position: absolute; right: 4px; top: 6px;
727
+ width: 20px; height: 20px; padding: 0;
728
+ display: grid; place-items: center;
729
+ border: 1px solid transparent; border-radius: 6px;
730
+ background: transparent; color: var(--ink-dim);
731
+ font-size: 14px; line-height: 1; cursor: pointer;
732
+ opacity: 0; transition: opacity .12s ease;
733
+ }
734
+ .turn:hover .turn-del, .turn-del:focus-visible { opacity: 1; }
735
+ .turn-del:hover { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 45%, transparent); background: var(--paper); }
736
+ @media (hover: none) { .turn-del { opacity: .55; } }