@240xu/dsh-message-ops 0.10.2 → 0.10.8

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@240xu/dsh-message-ops",
3
- "version": "0.10.2",
3
+ "version": "0.10.8",
4
4
  "description": "DSH web 插件:消息级回滚 / 删除 / 恢复(补 dsh 官方没有的部分)。分支与导出用官方内置能力。",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -42,7 +42,7 @@
42
42
  }
43
43
  },
44
44
  "scripts": {
45
- "test": "node --test \"test/*.test.js\""
45
+ "test": "node --check src/client.js && node --test \"test/*.test.js\""
46
46
  },
47
47
  "peerDependencies": {
48
48
  "@deepseek-ai/dsh-tools": "^0.1.0-rc.6 || ^0.2.0-rc.1"
package/src/client.js CHANGED
@@ -8,7 +8,7 @@ window.__ModuleLoader__.load({
8
8
  id: '@240xu/dsh-message-ops',
9
9
  factory: (require) => {
10
10
  const React = require('react')
11
- const { useCallback, useEffect, useState } = React
11
+ const { useCallback, useEffect, useRef, useState } = React
12
12
  const { Modal } = require('@deepseek-ai/dsh-client-ui-primitives')
13
13
 
14
14
  const SLOT = 'conversation.session.header.actions'
@@ -840,6 +840,29 @@ window.__ModuleLoader__.load({
840
840
  && m.restoreComplete !== true && m.committed !== true)
841
841
  }
842
842
 
843
+ /**
844
+ * activity 信号 → 是否重拉的**纯决策**(0.10.6 · 测试性改造)。
845
+ *
846
+ * 为什么抽出来:三轮测试审计的结论是「客户端 F1 的锁全是形状锁」——整个
847
+ * useEffect 可以被注释掉而 164 条测试全绿(审计 W4 实测)。根因是判定逻辑
848
+ * 埋在 hook 里,node --test 无法执行。抽成纯函数后可用 `new Function` 抽出来
849
+ * **行为测试**(client-perf-locks.test.js:161 已有同款手法,零新依赖)。
850
+ *
851
+ * 语义(三态,返回「推进后的基线」让调用方无脑赋值):
852
+ * next == null → 不动基线(宿主 store 还没就绪)
853
+ * prev == undefined → **建基线**。首帧渲染时 activityAt 常先是 null 再被
854
+ * 填充(或经 lastPromptAt 投影折入),把这次「null→值」
855
+ * 当成新活动会让开会话白拉一次(实测曾达 6 次 GET)
856
+ * next <= prev → 单调门,不动基线(refreshList 可能压低再抬高)
857
+ * next > prev → 真活动:重拉并推进基线
858
+ */
859
+ function activityTransition(prev, next) {
860
+ if (next == null) return { reload: false, baseline: prev }
861
+ if (prev === undefined) return { reload: false, baseline: next }
862
+ if (next <= prev) return { reload: false, baseline: prev }
863
+ return { reload: true, baseline: next }
864
+ }
865
+
843
866
  function RevertDock(props) {
844
867
  const { sessionId, useSessions, inputActions } = props
845
868
  if (sessionId) __currentSessionId = sessionId
@@ -849,6 +872,17 @@ window.__ModuleLoader__.load({
849
872
  const sessions = useSessions ? useSessions((s) => s) : undefined
850
873
  const summary = sessions && sessions.byId ? sessions.byId[sessionId] : undefined
851
874
  const running = summary ? summary.running === true : false
875
+ // F1 主路径:宿主 activity 信号(见下方 effect);null = 无 useSessions 或尚无活动
876
+ const activityAt = summary && typeof summary.updatedAt === 'number' ? summary.updatedAt : null
877
+ const loadRef = useRef(() => {})
878
+ const lastActivityRef = useRef(undefined)
879
+ // R2(审计):invalidateMessagesMemo() 只丢 memo 引用、**不取消在途 fetch**。
880
+ // 两个并发 load(mount + activity,或 CHANGED + activity)时慢的那个可能后落,
881
+ // setMarkers 会把已正确的 markers 覆盖回去 → dock 重新出现。
882
+ // 0.10.4 的 350/1400ms 延迟事实上起到了串行化作用,删除后重叠概率上升。
883
+ const reqSeqRef = useRef(0)
884
+ const sessRef = useRef(sessionId) // 真正的「切了会话」判据(R1 回归修复)
885
+ const landedSeqRef = useRef(0) // 已成功落地的最大请求序号(R2:失败不回滚)
852
886
  const [open, setOpen] = useState(false)
853
887
  const [markers, setMarkers] = useState(null) // 活跃回撤标记(已恢复的自动消失)
854
888
  const [shadowCount, setShadowCount] = useState(0) // 标记 range 内被遮蔽消息数(标题口径)
@@ -889,14 +923,29 @@ window.__ModuleLoader__.load({
889
923
  let alive = true
890
924
  const onChange = () => load()
891
925
  window.addEventListener(CHANGED_EVENT, onChange)
892
- const load = () => fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(sessionId))
926
+ const load = () => {
927
+ const reqSeq = ++reqSeqRef.current // 发起序号(防慢响应覆盖快响应)
928
+ // R1(复审实测):fetchMessagesJson 有 MSG_COALESCE_MS=1000 共用窗——
929
+ // 既有 scan 观察器在 T+200ms 已取到**落盘批窗(200ms)之前**的旧响应,
930
+ // 本路径若不先失效 memo,会原样复用它 → committed 仍是 false → 弹窗不清。
931
+ // emitChanged() 自己就是先 invalidate 再发事件,这里同款红线。
932
+ invalidateMessagesMemo()
933
+ return fetchMessagesJson('/api/message-ops/messages?sessionId=' + encodeURIComponent(sessionId))
893
934
  .then((data) => {
894
935
  if (!alive || !data || !data.ok) return
936
+ // R2:只有**最新发起且仍未被更新的请求**的结果才允许落地。
937
+ // 注意不能只看 reqSeq 是否等于当前发起序号 —— 后发请求若失败(fetchMessagesJson
938
+ // 对非 2xx / ok!==true 会 throw,被下面 catch 吞掉),它的序号已被占用,
939
+ // 先发那次**成功的**好响应就会被这里丢弃 → markers 停在旧值且无重试。
940
+ // 故另记一个「已落地序号」,失败不回滚它。
941
+ if (reqSeq !== reqSeqRef.current || reqSeq <= landedSeqRef.current) return
942
+ landedSeqRef.current = reqSeq
895
943
  const msgs = data.messages || []
896
- setMarkers(activeMarkers(msgs))
944
+ const act = activeMarkers(msgs)
945
+ setMarkers(act)
897
946
  // 0.5.2(P2):标题口径 = 标记 range 内 visible=false 的去重 seq 数
898
947
  const seen = new Set()
899
- for (const mk of activeMarkers(msgs)) {
948
+ for (const mk of act) {
900
949
  const start = mk.range && typeof mk.range.start === 'number' ? mk.range.start : mk.seq
901
950
  const end = mk.range && typeof mk.range.end === 'number' ? mk.range.end : start
902
951
  for (const m of msgs) {
@@ -906,10 +955,71 @@ window.__ModuleLoader__.load({
906
955
  setShadowCount(seen.size)
907
956
  })
908
957
  .catch(() => {})
958
+ }
959
+
960
+ // F1(复审后重做):宿主在 user/message(source.kind==='user') 时会
961
+ // `ctx.emit("api-session/activity", id, event.time)`
962
+ // ($B/dsh-api-session-controller/lib/index.js:2890-2896),客户端
963
+ // :3624 收到后抬高 summary.updatedAt(:3002 case "activity")——
964
+ // 这是与服务端 markCommitted **完全同判据**的一等信号。
965
+ //
966
+ // 第一版用 MutationObserver 盯 DOM 属性,复审判定为次优:
967
+ // - 判据靠近似(data-chat-flow-kind / 13:input-message 会命中注入行)
968
+ // - 多挂第三个 body-subtree 观察器
969
+ // - ready 门控在首拉失败时永久失效
970
+ // 本组件本就经 useSessions 读 summary(running 同源依赖),零新增依赖。
971
+ loadRef.current = load
909
972
  load()
910
- return () => { alive = false; window.removeEventListener(CHANGED_EVENT, onChange) }
973
+
974
+ return () => {
975
+ alive = false
976
+ loadRef.current = () => {}
977
+ window.removeEventListener(CHANGED_EVENT, onChange)
978
+ }
911
979
  }, [sessionId])
912
980
 
981
+ // F1 主路径:宿主 activity 信号抬高 updatedAt → 重拉。
982
+ // lastActivityRef 让 mount 那次(与初始值相等)不触发,避免开会话双请求。
983
+ //
984
+ // R2(复审推翻原「闪一下」定性,实为**弹窗可能一直不消失**):
985
+ // 宿主在 session.append 后**同步** emit api-session/activity
986
+ // ($B/dsh-api-session-controller/lib/index.js:2890-2896),而落盘是
987
+ // **异步批窗**($B/dsh-session/lib/index.js:1406 "hot path never blocks
988
+ // on I/O";persistence-jsonl:187 buffered/batchTimer)。
989
+ // 我们的 GET 读磁盘 + derivedCache 按 mtimeMs+size 失效(index.js:376),
990
+ // 拉取链 ≈30-150ms **几乎必然早于落盘** → 服务端 markCommitted 看不到
991
+ // 新 user 消息 → committed 仍是 false。
992
+ // 而 updatedAt 每条消息只跳变一次、scan 走 fetchRows 碰不到 markers、
993
+ // 宿主输入也不发 CHANGED_EVENT —— **没有第二次触发**,弹窗会一直留到
994
+ // 下一条消息或一次插件写操作。这正是用户原话的病灶。
995
+ // 故:有界重试,直到 dock 清空或重试耗尽(每条消息最多 3 次 GET)。
996
+ // R1(审计):原为 `= undefined`,但若切会话时 activityAt **不变**
997
+ // (同毫秒 createdAt / 都为 null 且新会话 summary 未进 store),
998
+ // 下游 effect 的依赖未变 → 不执行 → 基线永远停在 undefined →
999
+ // **用户切会话后的第一条消息撞上基线分支被吞,无任何 reload**(原 bug 上移一层)。
1000
+ // 重置到「当前」值:变了则基线=B(下游 B<=B 直接 return,不多拉);
1001
+ // 没变则基线=null,下次真实跳变 `x <= null` 为 false → 正常 load。
1002
+ // ⚠️ 必须**只有一个** effect。上一版拆成「重置 + 判定」两段、且重置段的依赖
1003
+ // 带上了 activityAt —— 同一次 commit 里 React 按声明顺序 flush,重置先把基线
1004
+ // 写成当前值,判定再拿到 T(B,B) → next <= prev → **活动信号被 100% 吃掉**,
1005
+ // F1 主路径彻底哑火(第四轮架构复审实跑抓出)。判据必须是「sessionId 真的
1006
+ // 变了」(sessRef),而不是「依赖数组里出现了 activityAt」。
1007
+ //
1008
+ // R1 原目标同样要达成:切会话时基线重置为**新会话当前值**(而非 undefined)——
1009
+ // 置 undefined 时若 activityAt 不变,下游不执行、基线永远 undefined,
1010
+ // 切会话后用户第一条消息撞上「建基线」分支被吞。
1011
+ useEffect(() => {
1012
+ if (sessRef.current !== sessionId) {
1013
+ sessRef.current = sessionId
1014
+ lastActivityRef.current = activityAt // 切会话:以新会话当前值为基线
1015
+ return
1016
+ }
1017
+ const step = activityTransition(lastActivityRef.current, activityAt)
1018
+ lastActivityRef.current = step.baseline
1019
+ if (step.reload) loadRef.current()
1020
+ }, [sessionId, activityAt])
1021
+
1022
+
913
1023
  // items 变化自动折叠(opencode createEffect 同款;必须在早退之前——Hooks 规则)
914
1024
  useEffect(() => { setOpen(false) }, [markers && markers.length, markers && markers[0] && markers[0].seq])
915
1025
  if (!markers || !markers.length) return null
@@ -1890,6 +2000,6 @@ window.__ModuleLoader__.load({
1890
2000
  installUserRevertInjector()
1891
2001
  }
1892
2002
 
1893
- return { apply, inject: ['slots'] }
2003
+ return { apply, inject: ['slots'], __test: { activityTransition } }
1894
2004
  },
1895
2005
  })
package/src/index.js CHANGED
@@ -8,11 +8,11 @@
8
8
 
9
9
  import { zstdCompressSync } from "node:zlib";
10
10
  import { open as openFile, truncate as truncateFile, stat as statFile } from "node:fs/promises";
11
- import { isSessionId, sessionIdVariants, findSessionDirs, readSessionFileAsync, listMessages, computeShadowed, messageText, turnBounds, markCommitted } from "./session-file.js";
11
+ import { isSessionId, sessionIdVariants, findSessionDirs, readSessionFileAsync, listMessages, computeShadowed, messageText, messageTextFull, turnBounds, markCommitted } from "./session-file.js";
12
12
  import { restoreNoticeText, planRevertFromEvents, planDeleteFromEvents, nextSeqFrom, buildMarkerEvent, buildRestoreNoticeEvent, buildReplayEvent, planNoticeWindow, noticeWindowPreamble, noticeWindowPostamble,
13
13
  OpsError, planRevert, planDelete, planRestore, applyRestore, applySurfaceReplace,
14
14
  restoreProgress, pendingRestoreTurns,
15
- isTrustedApiRequest, isJsonContentType,
15
+ isTrustedApiRequest, isJsonContentType, webAuthGate,
16
16
  } from "./ops-core.js";
17
17
 
18
18
  export const name = "dsh-message-ops";
@@ -42,18 +42,26 @@ async function readJsonBody(req) {
42
42
  catch { return null; }
43
43
  }
44
44
 
45
- /** 统一入口围栏:全部 /api/message-ops/* 路由先过这一层。 */
46
- function fence(req, res) {
45
+ /** 统一入口围栏:全部 /api/message-ops/* 路由先过这一层(三层信任 + 宿主 BrowserAuth cookie)。 */
46
+ async function fence(targetCtx, req, res) {
47
47
  if (!isTrustedApiRequest(req)) {
48
48
  sendJson(res, 403, { ok: false, error: "untrusted request origin (loopback Host + same-origin only)" });
49
49
  return false;
50
50
  }
51
+ // 0.10.8:宿主同条件 GET 被读全量(审计缺口)。宿主 /api admit = 三层围栏
52
+ // 之外还要 BrowserAuth cookie(无 cookie → 401);前端同源 fetch 自动带
53
+ // cookie,取数不受影响。secret 读不到 = 降级回旧围栏(webAuthGate 内部
54
+ // 告警一次),老宿主/测桩不破坏。
55
+ if (!(await webAuthGate(targetCtx, req))) {
56
+ sendJson(res, 401, { ok: false, error: "unauthorized (browser auth cookie required; reopen the URL printed by dsh web)" });
57
+ return false;
58
+ }
51
59
  return true;
52
60
  }
53
61
 
54
62
  /** 写操作围栏:入口信任 + Content-Type 必须 application/json(CSRF 纵深)。 */
55
- function writeFence(req, res) {
56
- if (!fence(req, res)) return false;
63
+ async function writeFence(targetCtx, req, res) {
64
+ if (!(await fence(targetCtx, req, res))) return false;
57
65
  if (!isJsonContentType(req)) {
58
66
  sendJson(res, 415, { ok: false, error: "content-type must be application/json" });
59
67
  return false;
@@ -155,6 +163,62 @@ async function acquireSession(ctx, sessionId) {
155
163
  }
156
164
 
157
165
  let __runningSource = null; // 诊断:最近一次 isRunning 的判定来源
166
+ /**
167
+ * 用**宿主内存日志**补算 marker's committed(0.10.5 · R2 的根治)。
168
+ *
169
+ * 问题:宿主在 session.append 后**同步** emit api-session/activity,而落盘是
170
+ * **异步批窗**($B/dsh-session/lib/index.js:1406 "hot path never blocks on I/O";
171
+ * persistence-jsonl:187 buffered/batchTimer,批窗 200ms)。opsList 读磁盘 +
172
+ * derivedCache 按 mtimeMs+size 失效(loadDerived:376),所以 activity 刚到时
173
+ * 几乎必然命中旧缓存 → markCommitted 看不到刚发出的 user 消息 → committed=false
174
+ * → dock 不清。客户端此前只能靠「延迟 350/1400ms 重拉」赌落盘已完成,
175
+ * 实测在 82% CPU 的 Android 上最坏 2×2.2s CPU + 2×248ms 卡顿,且 >1400ms 的
176
+ * 落盘没有第三次触发(残留缺口)。
177
+ *
178
+ * 根治:live Session 直接暴露内存事件日志 `this.log`
179
+ * ($B/dsh-session/lib/index.js:516),元素与磁盘事件**同构**
180
+ * (:1454-1459 `{type, seq, time, data, ...surfaceMetadata}`)→ 直接补算。
181
+ *
182
+ * 安全性(三重,都是构造上自洽的,不依赖隐式不变量):
183
+ * 1. **只叠加**:只有「live.log 里存在 seq > marker.seq 的真实用户输入」才置
184
+ * true;live.log 陈旧/读不到就什么都不做 → 自然退回 0.10.3 的磁盘语义。
185
+ * 2. **绝不动缓存**:调用点已对 baseMessages 做过每请求浅拷贝,这里只改副本。
186
+ * 3. **同判据**:`type==='user/message' && data.source.kind==='user'`,与
187
+ * markCommitted、与宿主 activity 事件三者一致(注入行/重放副本天然不算)。
188
+ */
189
+ function applyLiveCommitted(messages, live) {
190
+ // R4(审计):388 份语料里 360+ 无 marker。原先无条件扫完整个 live.log 才 return,
191
+ // 是请求路径上一个无界的同步 O(log.length) 扫描(最大实测 15178 事件),且不像
192
+ // buildDerived 那样有 framesPerYield 让出点。先判「有没有需要补算的 marker」。
193
+ let pending = null;
194
+ for (const m of messages) {
195
+ if (m.marker === true && typeof m.seq === "number" && m.committed !== true) {
196
+ (pending || (pending = [])).push(m);
197
+ }
198
+ }
199
+ if (!pending) return false;
200
+ const log = live && Array.isArray(live.log) ? live.log : null;
201
+ if (!log || log.length === 0) return false;
202
+ // 只要**最大的**真实用户输入 seq:判据是「存在 seq > marker.seq」,用 max 即可,
203
+ // 不必建数组 + sort(扫描本身已 O(log.length),别再叠 O(n log n))。
204
+ let maxUserSeq = -1;
205
+ for (const e of log) {
206
+ if (!e || typeof e.seq !== "number" || e.seq <= maxUserSeq) continue;
207
+ if (e.type !== "user/message") continue;
208
+ if (((e.data || {}).source || {}).kind !== "user") continue;
209
+ maxUserSeq = e.seq;
210
+ }
211
+ if (maxUserSeq < 0) return false;
212
+ // ⚠️ 遍历**全部** pending marker:审计实测「只补算第一个 + break」是存活突变,
213
+ // 而它对应一个真实 bug —— 用户连续回撤两次时第二个 marker 不被补算,
214
+ // 第二条 dock 行在发消息后不消失(正是用户原话的残留形态)。
215
+ let touched = 0;
216
+ for (const m of pending) {
217
+ if (maxUserSeq > m.seq) { m.committed = true; touched++; }
218
+ }
219
+ return touched > 0;
220
+ }
221
+
158
222
  function isRunning(ctx, sessionId) {
159
223
  // 0.5.4(实机三层根因第 3 层的最终修):与宿主**官方同源**——
160
224
  // dsh-api-session-controller/lib/index.js ApiSessionList.summaryFor():
@@ -401,6 +465,9 @@ async function opsList(targetCtx, sessionId) {
401
465
  // 并发请求之间零串扰(浅拷 5038 个小对象约 1~2ms)。
402
466
  const messages = baseMessages.map((m) => ({ ...m }));
403
467
  const live = resolveSession(targetCtx, sessionId);
468
+ // R2 根治:磁盘派生可能还停在落盘批窗之前,用 live.log 补算 committed。
469
+ // 必须在 messages 浅拷贝之后(绝不改写 derivedCache 里的对象)。
470
+ applyLiveCommitted(messages, live);
404
471
  const visibleNodes = live && live.surface && Array.isArray(live.surface.nodes) ? new Set(live.surface.nodes) : null;
405
472
  let visibleCount = 0;
406
473
  for (const m of messages) {
@@ -460,17 +527,32 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
460
527
  : `[消息回滚] 已回滚到 seq ${seq}(含)之后的 ${plan.shadowedSeqs.length} 个节点`;
461
528
  // 0.8.2:会话 store 命中时走引擎路径 —— 同样要先开合成 turn 窗口,
462
529
  // 否则 notice 落在已关闭的 turn/step 里,加载端拒绝整份历史。
463
- for (const pre of noticeWindowPreamble(win)) session.append(pre.kind, pre.data);
464
- const event = applySurfaceReplace(session, plan.startSeq, plan.endSeq, plan.shadowedSeqs, text, turnStep);
465
- // 必须闭合:否则引擎内存里 turn 16 永远开着 → isRunning 恒真 → 后续操作全被 409
466
- for (const post of noticeWindowPostamble(win)) session.append(post.kind, post.data);
467
- flushSessions(targetCtx, session);
468
- return {
469
- ok: true, mode, seq,
470
- syntheticTurn: win.synthetic === true,
471
- shadowedCount: plan.shadowedSeqs.length,
472
- eventSeq: event && event.seq != null ? event.seq : null,
473
- };
530
+ // 0.10.8 孤儿护栏:plan 校验(planRevert/planDelete 的 409 拒绝)本就在
531
+ // preamble **之前**执行;落 preamble 后残余的失败路径只剩引擎侧的
532
+ // replace/provenance/turn-step 校验(拼写探测双失败、surface TOCTOU 变化)。
533
+ // 捕一层把合成 turn 用 postamble **闭合**——失败时内存里不再留一个常开
534
+ // turn(0.8.2 注释锁定的「后半操作被 409 锁拒」形态),随后原样抛出,
535
+ // 由路由层按既有 OpsError 映射。append-only 引擎无「删除已落事件」能力,
536
+ // 闭合孤儿窗口是最小且可被动校验的整理。
537
+ try {
538
+ for (const pre of noticeWindowPreamble(win)) session.append(pre.kind, pre.data);
539
+ const event = applySurfaceReplace(session, plan.startSeq, plan.endSeq, plan.shadowedSeqs, text, turnStep);
540
+ // 必须闭合:否则引擎内存里 turn 16 永远开着 → isRunning 恒真 → 后续操作全被 409
541
+ for (const post of noticeWindowPostamble(win)) session.append(post.kind, post.data);
542
+ flushSessions(targetCtx, session);
543
+ return {
544
+ ok: true, mode, seq,
545
+ syntheticTurn: win.synthetic === true,
546
+ shadowedCount: plan.shadowedSeqs.length,
547
+ eventSeq: event && event.seq != null ? event.seq : null,
548
+ };
549
+ } catch (err) {
550
+ // 孤儿整理失败不再包一层也不会更糟(append 已失败态);原错误照抛。
551
+ for (const post of noticeWindowPostamble(win)) {
552
+ try { session.append(post.kind, post.data); } catch { /* postamble 被引擎拒:维持原错误上抛 */ }
553
+ }
554
+ throw err;
555
+ }
474
556
  } finally {
475
557
  acq.release();
476
558
  }
@@ -524,6 +606,9 @@ async function opsRestore(targetCtx, sessionId, restoreSeq, upToSeq, discard) {
524
606
  }
525
607
  const acq = await acquireSession(targetCtx, sessionId);
526
608
  if (acq !== null && acq.session !== undefined) {
609
+ // 0.10.8 孤儿护栏(与 opsCommit 同型):planRestore/进度校验本就在 preamble
610
+ // 之前完成;applyRestore 里的引擎 append 若抛(如 replay 坐标错开),
611
+ // preamble 已落——闭合合成 turn 再原样抛出,不留常开孤儿窗口。
527
612
  try {
528
613
  for (const pre of noticeWindowPreamble(win)) acq.session.append(pre.kind, pre.data);
529
614
  const result = applyRestore(acq.session, plan, {
@@ -531,6 +616,11 @@ async function opsRestore(targetCtx, sessionId, restoreSeq, upToSeq, discard) {
531
616
  });
532
617
  for (const post of noticeWindowPostamble(win)) acq.session.append(post.kind, post.data);
533
618
  return { ok: true, ...result, discarded: plan.discard === true, upToSeq: plan.upToSeq, restoredSourceSeqs: plan.replayable.map((i) => i.seq), range: { startSeq: plan.startSeq, endSeq: plan.endSeq } };
619
+ } catch (err) {
620
+ for (const post of noticeWindowPostamble(win)) {
621
+ try { acq.session.append(post.kind, post.data); } catch { /* postamble 被引擎拒:维持原错误上抛 */ }
622
+ }
623
+ throw err;
534
624
  } finally {
535
625
  acq.release();
536
626
  }
@@ -704,7 +794,7 @@ export function apply(ctx) {
704
794
  path: "/api/message-ops/messages",
705
795
  handler: async (req, res) => {
706
796
  if (req.method !== "GET") return sendJson(res, 405, { ok: false, error: "method not allowed" });
707
- if (!fence(req, res)) return;
797
+ if (!(await fence(targetCtx, req, res))) return;
708
798
  try {
709
799
  const url = new URL(req.url, "http://localhost");
710
800
  return sendJson(res, 200, await opsList(targetCtx, url.searchParams.get("sessionId") || ""));
@@ -721,18 +811,24 @@ export function apply(ctx) {
721
811
  path: "/api/message-ops/text",
722
812
  handler: async (req, res) => {
723
813
  if (req.method !== "GET") return sendJson(res, 405, { ok: false, error: "method not allowed" });
724
- if (!fence(req, res)) return;
814
+ if (!(await fence(targetCtx, req, res))) return;
725
815
  try {
726
816
  const url = new URL(req.url, "http://localhost");
727
817
  const sessionId = url.searchParams.get("sessionId") || "";
728
818
  const seq = Number.parseInt(url.searchParams.get("seq") || "", 10);
729
819
  if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
730
820
  if (!Number.isSafeInteger(seq) || seq < 0) throw new OpsError("invalid seq", 400);
821
+ // seq 0 在日志头里是结构事件区(permission/preset 等,实测恒非消息),
822
+ // messageText 恒空串;引用按钮不可能引用它,直接 404 而不是 200 {text:""}。
823
+ if (seq === 0) throw new OpsError("no quotable message at seq 0", 404);
731
824
  const { logPath } = pickSessionDir(sessionId);
732
825
  const { events } = await readSessionFileAsync(logPath);
733
826
  const ev = events.find((e) => e && e.seq === seq);
734
827
  if (!ev) throw new OpsError("seq not found", 404);
735
- return sendJson(res, 200, { ok: true, seq, text: messageText(ev) });
828
+ // 0.10.8:宿主会把长文本拆成多段 content(seq 6830 实测 321+7954+20),
829
+ // 只回首段 = 摘要拦腰截断。messageTextFull 与 messageText 同一条
830
+ // 「合格 text 段」口径,聚合改为全量拼接。
831
+ return sendJson(res, 200, { ok: true, seq, text: messageTextFull(ev) });
736
832
  } catch (err) {
737
833
  return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
738
834
  }
@@ -742,7 +838,7 @@ export function apply(ctx) {
742
838
  // --- POST revert / delete:live-session surface replace ------------------
743
839
  const commitHandler = (mode) => async (req, res) => {
744
840
  if (req.method !== "POST") return sendJson(res, 405, { ok: false, error: "method not allowed" });
745
- if (!writeFence(req, res)) return;
841
+ if (!(await writeFence(targetCtx, req, res))) return;
746
842
  const body = await readFencedBody(req, res);
747
843
  if (body === undefined) return;
748
844
  if (!body || typeof body !== "object") return sendJson(res, 400, { ok: false, error: "invalid json" });
@@ -768,7 +864,7 @@ export function apply(ctx) {
768
864
  path: "/api/message-ops/restore",
769
865
  handler: async (req, res) => {
770
866
  if (req.method !== "POST") return sendJson(res, 405, { ok: false, error: "method not allowed" });
771
- if (!writeFence(req, res)) return;
867
+ if (!(await writeFence(targetCtx, req, res))) return;
772
868
  const body = await readFencedBody(req, res);
773
869
  if (body === undefined) return;
774
870
  if (!body || typeof body !== "object") return sendJson(res, 400, { ok: false, error: "invalid json" });
package/src/ops-core.js CHANGED
@@ -1,4 +1,8 @@
1
- import { randomUUID } from "node:crypto";
1
+ import { randomUUID, createHash, createHmac, timingSafeEqual } from "node:crypto";
2
+
3
+ /** OpsError 单点在 session-file.js(computeShadowed 护栏也在那里抛它);此处转出保持既有导入面。 */
4
+ export { OpsError } from "./session-file.js";
5
+ import { OpsError } from "./session-file.js";
2
6
  /**
3
7
  * dsh-message-ops — 可复用操作核心(纯逻辑,无 HTTP、无 dsh-tools 依赖)。
4
8
  *
@@ -23,13 +27,7 @@ import { readReplaceOp, messageText, computeShadowed } from "./session-file.js";
23
27
  // 既有导入面兼容(ops-core 的 messageText 调用方不受影响)。
24
28
  export { messageText };
25
29
 
26
- /** 带语义状态码的操作错误(HTTP 直接映射,工具端转为失败文本)。 */
27
- export class OpsError extends Error {
28
- constructor(message, status = 400) {
29
- super(message);
30
- this.status = status;
31
- }
32
- }
30
+ /** 带语义状态码的操作错误(单点已迁至 session-file.js,此处仅转出)。 */
33
31
 
34
32
  /** planRevert:回撤语义 = 遮蔽 targetSeq 及其之后全部可见节点(连续到末尾)。 */
35
33
  export function planRevert(surface, targetSeq) {
@@ -513,6 +511,183 @@ export function isJsonContentType(req) {
513
511
  return ct.split(";")[0].trim().toLowerCase() === "application/json";
514
512
  }
515
513
 
514
+ // ---------------------------------------------------------------------------
515
+ // 0.10.8 · web 前端鉴权对齐(GET 也要过宿主的浏览器认证门)
516
+ // ---------------------------------------------------------------------------
517
+ // 宿主侧实况(全局 dsh 0.2.0-rc.2 的 dsh-client-connection/lib/index.js):
518
+ // admit(request)(:742-749)对每一条 /api 前缀请求(含 GET)都要求
519
+ // browserAuth 认证——根 token 只在 authorizeIndex 换 cookie:GET /<token>
520
+ // → 铸 HttpOnly+SameSite=Strict 的签名 cookie(名 = dsh-auth-<b64url(
521
+ // sha256(authority))>,载荷 v{1|2}.<b64url(json)>.<b64url(hmac-sha256)>
522
+ // secret 32 字节,存 credentials 记录 client-connection/browser-session)
523
+ // → 重定向 ./;此后每条 /api 都凭 cookie 过 admit,无 cookie → 401。
524
+ // 前端取数是同源 fetch(默认凭证)——cookie 自动随行,**全程没有
525
+ // Authorization 头,也没有 ?token= 打到 /api**。
526
+ // 插件路由此前只跑 isTrustedApiRequest(该围栏自述 "is not an auth layer"),
527
+ // 同机无凭证进程 GET 即可整卷消息/全文(宿主同条件 401——审计缺口)。
528
+ // 对齐修法(选型理由见报告):前端本来就带 cookie → 围栏里**校验同款
529
+ // cookie**;secret 经 credentials 服务的合法读法取(no-op modifyRecord,
530
+ // 勿写勿落盘);宿主无此服务 / 记录缺失或格式升级 → **降级回旧围栏语义**
531
+ // 并告警(UI 永不因新校验而被 401,老版本宿主下行为不变)。
532
+ // 非浏览器 GET(curl 等)从 200 变 401 = 与宿主对齐的有意行为变化。
533
+
534
+ const AUTH_RECORD_KEY = "client-connection/browser-session";
535
+ const AUTH_COOKIE_PREFIX = "dsh-auth-";
536
+ const AUTH_STORED_SECRET_VERSION = 1;
537
+ const AUTH_SECRET_BYTES = 32;
538
+
539
+ const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/u;
540
+
541
+ function encodeBase64Url(value) {
542
+ return Buffer.from(value).toString("base64").replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
543
+ }
544
+
545
+ function decodeBase64Url(value) {
546
+ if (!BASE64URL_PATTERN.test(value) || value.length % 4 === 1) return undefined;
547
+ const padding = "=".repeat((4 - (value.length % 4)) % 4);
548
+ const decoded = Buffer.from(value.replaceAll("-", "+").replaceAll("_", "/") + padding, "base64");
549
+ return encodeBase64Url(decoded) === value ? decoded : undefined;
550
+ }
551
+
552
+ /** 宿主 requestAudience 的口径:HTTP 用 url.host;TLS 用 url.origin。插件
553
+ * 读不到监听面协议,两种拼写都试(名字与载荷 authority 用**同一个**拼写
554
+ * 配对校验,跨拼写伪造照样被拒)。 */
555
+ function cookieAuthorityCandidates(hostHeader) {
556
+ try {
557
+ const url = new URL(`http://${hostHeader}`);
558
+ return [url.host, `https://${url.host}`];
559
+ } catch {
560
+ return [];
561
+ }
562
+ }
563
+
564
+ /** 宿主 cookieValue:按分号切段取**第一个**同名区的值(无解码语义)。 */
565
+ function cookieValue(rawCookie, name) {
566
+ if (typeof rawCookie !== "string") return undefined;
567
+ for (const segment of rawCookie.split(";")) {
568
+ const at = segment.indexOf("=");
569
+ if (at === -1 || segment.slice(0, at).trim() !== name) continue;
570
+ return segment.slice(at + 1).trim();
571
+ }
572
+ return undefined;
573
+ }
574
+
575
+ /** 宿主 decodeCookie 的镜像:三段结构 + HMAC + 载荷形状(v1 浏览器 peer / v2 带操作者 id)。 */
576
+ function decodeBrowserAuthCookie(value, secret) {
577
+ const parts = value.split(".");
578
+ const [version, body, encodedSignature] = parts;
579
+ if (parts.length !== 3 || (version !== "v1" && version !== "v2") || body === undefined || encodedSignature === undefined) return undefined;
580
+ const actualSignature = decodeBase64Url(encodedSignature);
581
+ if (actualSignature === undefined) return undefined;
582
+ const expectedSignature = createHmac("sha256", secret).update(body).digest();
583
+ if (actualSignature.length !== expectedSignature.length || !timingSafeEqual(actualSignature, expectedSignature)) return undefined;
584
+ const bodyBytes = decodeBase64Url(body);
585
+ if (bodyBytes === undefined) return undefined;
586
+ let decoded;
587
+ try { decoded = JSON.parse(bodyBytes.toString("utf8")); } catch { return undefined; }
588
+ if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) return undefined;
589
+ if (decoded.version !== 1 && decoded.version !== 2) return undefined;
590
+ if (version !== `v${decoded.version}`) return undefined;
591
+ if (typeof decoded.authority !== "string" || decoded.authority === "") return undefined;
592
+ if (typeof decoded.issuedAt !== "number" || !Number.isSafeInteger(decoded.issuedAt)) return undefined;
593
+ if (typeof decoded.expiresAt !== "number" || !Number.isSafeInteger(decoded.expiresAt)) return undefined;
594
+ const payload = { version: decoded.version, authority: decoded.authority, issuedAt: decoded.issuedAt, expiresAt: decoded.expiresAt };
595
+ if (decoded.version === 1) return payload;
596
+ if (typeof decoded.id !== "string" || decoded.id.length === 0) return undefined;
597
+ return { ...payload, id: decoded.id };
598
+ }
599
+
600
+ /**
601
+ * 校验请求是否携带**有效**的宿主浏览器认证 cookie。
602
+ * @returns 载荷(通过)或 undefined(未认证)。返回值只当布尔用。
603
+ */
604
+ export function browserAuthPayload(req, secret) {
605
+ if (secret == null) return undefined;
606
+ const host = headerOf(req && req.headers, "host");
607
+ if (host === undefined) return undefined;
608
+ const rawCookie = headerOf(req.headers, "cookie");
609
+ if (rawCookie === undefined) return undefined;
610
+ const now = Date.now();
611
+ for (const authority of cookieAuthorityCandidates(host)) {
612
+ const value = cookieValue(rawCookie, AUTH_COOKIE_PREFIX + encodeBase64Url(createHash("sha256").update(authority).digest()));
613
+ if (value === undefined) continue;
614
+ const payload = decodeBrowserAuthCookie(value, secret);
615
+ // payload.authority 与产生名字的同一个拼写配对(宿主同样的绑定语义)。
616
+ if (payload === undefined || payload.authority !== authority) continue;
617
+ // 宿主 authenticate(:555 附近) 的时效三条;expiresAt-issuedAt 的 maxAge
618
+ // 窗口不复制(host 可配 cookieMaxAgeDays,插件复制会误杀合法长龄 cookie)。
619
+ if (payload.issuedAt > now || payload.expiresAt <= now || payload.expiresAt <= payload.issuedAt) continue;
620
+ return payload;
621
+ }
622
+ return undefined;
623
+ }
624
+
625
+ /**
626
+ * 经 credentials 服务读宿主 BrowserAuth 签名 secret。**唯一读法**:
627
+ * no-op modifyRecord(mutate 返回 undefined = 记录未动、返回 current),
628
+ * 不落盘不经 argv。宿主无该成分 / 记录缺失 / 格式或长度不符 → null(降级)。
629
+ * @param {object|undefined} credentials ctx.get("credentials")
630
+ * @returns {Promise<Buffer|null>}
631
+ */
632
+ export async function loadBrowserAuthSecret(credentials) {
633
+ if (!credentials || typeof credentials.modifyRecord !== "function") return null;
634
+ let record;
635
+ try {
636
+ record = await credentials.modifyRecord(AUTH_RECORD_KEY, async () => undefined);
637
+ } catch {
638
+ return null;
639
+ }
640
+ if (record === undefined || record === null || typeof record !== "object" || record.kind !== "grant") return null;
641
+ const payload = record.payload;
642
+ if (!payload || typeof payload !== "object" || payload.version !== AUTH_STORED_SECRET_VERSION) return null;
643
+ if (typeof payload.secret !== "string") return null;
644
+ const secret = decodeBase64Url(payload.secret);
645
+ if (!secret || secret.length !== AUTH_SECRET_BYTES) return null;
646
+ return secret;
647
+ }
648
+
649
+ // 进程级 memo:secret 一次命中就终身持有(宿主 create 只在缺失时铸新记录,
650
+ // 正常进程内不会换代);探测失败 10s 内不重试,401 风暴不会打爆 credential 锁。
651
+ const WEB_AUTH_RETRY_MS = 10_000;
652
+ let __webAuthSecret = null;
653
+ let __webAuthProbeAt = 0;
654
+ let __webAuthWarned = false;
655
+
656
+ /** 测试钩子:直接注入/清除 secret,绕开 credentials 服务。 */
657
+ export function _setWebAuthSecret(secret) { __webAuthSecret = secret; }
658
+ export function _resetWebAuth() {
659
+ __webAuthSecret = null;
660
+ __webAuthProbeAt = 0;
661
+ __webAuthWarned = false;
662
+ }
663
+
664
+ /**
665
+ * 围栏的鉴权半段:取活跃 secret(含惰性探测与失败 memo)。
666
+ * secret 存在但请求未携有效 cookie → false(路由层回 401);
667
+ * secret 不可得(无 credentials / 记录缺失 / 老版本宿主)→ true = 降级回旧围栏。
668
+ * @param {object|undefined} ctx 插件 ctx(get("credentials"))
669
+ * @param {object} req http 请求
670
+ */
671
+ export async function webAuthGate(ctx, req) {
672
+ if (__webAuthSecret !== null) {
673
+ return browserAuthPayload(req, __webAuthSecret) !== undefined;
674
+ }
675
+ const now = Date.now();
676
+ if (now - __webAuthProbeAt < WEB_AUTH_RETRY_MS) return true; // 失败窗口内 = 降级
677
+ __webAuthProbeAt = now;
678
+ const credentials = ctx && typeof ctx.get === "function" ? ctx.get("credentials") : null;
679
+ __webAuthSecret = await loadBrowserAuthSecret(credentials);
680
+ if (__webAuthSecret === null && !__webAuthWarned) {
681
+ __webAuthWarned = true;
682
+ console.warn(
683
+ "[message-ops] BrowserAuth cookie 鉴权未启用(`client-connection/browser-session` 记录不可读)"
684
+ + "——GET 鉴权降级为旧的三层围栏语义;若这是 0.2.0+ 宿主,请检查该记录是否存在",
685
+ );
686
+ }
687
+ return __webAuthSecret === null ? true : browserAuthPayload(req, __webAuthSecret) !== undefined;
688
+ }
689
+
690
+
516
691
  // ---------------------------------------------------------------------------
517
692
  // 0.5.7 · 磁盘路径(lazy-view 会话不进对象层时的回退)
518
693
  // ---------------------------------------------------------------------------