@240xu/dsh-message-ops 0.10.7 → 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.7",
3
+ "version": "0.10.8",
4
4
  "description": "DSH web 插件:消息级回滚 / 删除 / 恢复(补 dsh 官方没有的部分)。分支与导出用官方内置能力。",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/client.js CHANGED
@@ -882,7 +882,7 @@ window.__ModuleLoader__.load({
882
882
  // 0.10.4 的 350/1400ms 延迟事实上起到了串行化作用,删除后重叠概率上升。
883
883
  const reqSeqRef = useRef(0)
884
884
  const sessRef = useRef(sessionId) // 真正的「切了会话」判据(R1 回归修复)
885
- const landedSeqRef = useRef(0) // 已成功落地的最大请求序号(R2:失败不回滚) // undefined = 尚未建立基线(见下方 effect)
885
+ const landedSeqRef = useRef(0) // 已成功落地的最大请求序号(R2:失败不回滚)
886
886
  const [open, setOpen] = useState(false)
887
887
  const [markers, setMarkers] = useState(null) // 活跃回撤标记(已恢复的自动消失)
888
888
  const [shadowCount, setShadowCount] = useState(0) // 标记 range 内被遮蔽消息数(标题口径)
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;
@@ -519,17 +527,32 @@ async function opsCommit(targetCtx, mode, sessionId, seq) {
519
527
  : `[消息回滚] 已回滚到 seq ${seq}(含)之后的 ${plan.shadowedSeqs.length} 个节点`;
520
528
  // 0.8.2:会话 store 命中时走引擎路径 —— 同样要先开合成 turn 窗口,
521
529
  // 否则 notice 落在已关闭的 turn/step 里,加载端拒绝整份历史。
522
- for (const pre of noticeWindowPreamble(win)) session.append(pre.kind, pre.data);
523
- const event = applySurfaceReplace(session, plan.startSeq, plan.endSeq, plan.shadowedSeqs, text, turnStep);
524
- // 必须闭合:否则引擎内存里 turn 16 永远开着 → isRunning 恒真 → 后续操作全被 409
525
- for (const post of noticeWindowPostamble(win)) session.append(post.kind, post.data);
526
- flushSessions(targetCtx, session);
527
- return {
528
- ok: true, mode, seq,
529
- syntheticTurn: win.synthetic === true,
530
- shadowedCount: plan.shadowedSeqs.length,
531
- eventSeq: event && event.seq != null ? event.seq : null,
532
- };
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
+ }
533
556
  } finally {
534
557
  acq.release();
535
558
  }
@@ -583,6 +606,9 @@ async function opsRestore(targetCtx, sessionId, restoreSeq, upToSeq, discard) {
583
606
  }
584
607
  const acq = await acquireSession(targetCtx, sessionId);
585
608
  if (acq !== null && acq.session !== undefined) {
609
+ // 0.10.8 孤儿护栏(与 opsCommit 同型):planRestore/进度校验本就在 preamble
610
+ // 之前完成;applyRestore 里的引擎 append 若抛(如 replay 坐标错开),
611
+ // preamble 已落——闭合合成 turn 再原样抛出,不留常开孤儿窗口。
586
612
  try {
587
613
  for (const pre of noticeWindowPreamble(win)) acq.session.append(pre.kind, pre.data);
588
614
  const result = applyRestore(acq.session, plan, {
@@ -590,6 +616,11 @@ async function opsRestore(targetCtx, sessionId, restoreSeq, upToSeq, discard) {
590
616
  });
591
617
  for (const post of noticeWindowPostamble(win)) acq.session.append(post.kind, post.data);
592
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;
593
624
  } finally {
594
625
  acq.release();
595
626
  }
@@ -763,7 +794,7 @@ export function apply(ctx) {
763
794
  path: "/api/message-ops/messages",
764
795
  handler: async (req, res) => {
765
796
  if (req.method !== "GET") return sendJson(res, 405, { ok: false, error: "method not allowed" });
766
- if (!fence(req, res)) return;
797
+ if (!(await fence(targetCtx, req, res))) return;
767
798
  try {
768
799
  const url = new URL(req.url, "http://localhost");
769
800
  return sendJson(res, 200, await opsList(targetCtx, url.searchParams.get("sessionId") || ""));
@@ -780,18 +811,24 @@ export function apply(ctx) {
780
811
  path: "/api/message-ops/text",
781
812
  handler: async (req, res) => {
782
813
  if (req.method !== "GET") return sendJson(res, 405, { ok: false, error: "method not allowed" });
783
- if (!fence(req, res)) return;
814
+ if (!(await fence(targetCtx, req, res))) return;
784
815
  try {
785
816
  const url = new URL(req.url, "http://localhost");
786
817
  const sessionId = url.searchParams.get("sessionId") || "";
787
818
  const seq = Number.parseInt(url.searchParams.get("seq") || "", 10);
788
819
  if (!isSessionId(sessionId)) throw new OpsError("invalid sessionId", 400);
789
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);
790
824
  const { logPath } = pickSessionDir(sessionId);
791
825
  const { events } = await readSessionFileAsync(logPath);
792
826
  const ev = events.find((e) => e && e.seq === seq);
793
827
  if (!ev) throw new OpsError("seq not found", 404);
794
- 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) });
795
832
  } catch (err) {
796
833
  return sendJson(res, err instanceof OpsError ? err.status : 500, { ok: false, error: String(err && err.message ? err.message : err) });
797
834
  }
@@ -801,7 +838,7 @@ export function apply(ctx) {
801
838
  // --- POST revert / delete:live-session surface replace ------------------
802
839
  const commitHandler = (mode) => async (req, res) => {
803
840
  if (req.method !== "POST") return sendJson(res, 405, { ok: false, error: "method not allowed" });
804
- if (!writeFence(req, res)) return;
841
+ if (!(await writeFence(targetCtx, req, res))) return;
805
842
  const body = await readFencedBody(req, res);
806
843
  if (body === undefined) return;
807
844
  if (!body || typeof body !== "object") return sendJson(res, 400, { ok: false, error: "invalid json" });
@@ -827,7 +864,7 @@ export function apply(ctx) {
827
864
  path: "/api/message-ops/restore",
828
865
  handler: async (req, res) => {
829
866
  if (req.method !== "POST") return sendJson(res, 405, { ok: false, error: "method not allowed" });
830
- if (!writeFence(req, res)) return;
867
+ if (!(await writeFence(targetCtx, req, res))) return;
831
868
  const body = await readFencedBody(req, res);
832
869
  if (body === undefined) return;
833
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
  // ---------------------------------------------------------------------------
@@ -20,15 +20,44 @@ const ZSTD_MAGIC = 0xfd2fb528;
20
20
  /** 魔数的字节形态(Buffer.indexOf 用;小端 0xfd2fb528 → 28 b5 2f fd)。 */
21
21
  const ZSTD_MAGIC_BYTES = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
22
22
 
23
- /** 从 message 事件提取首个非空 text 块(listMessages / ops-core 共用单点)。 */
24
- export function messageText(e) {
23
+ /** 带语义状态码的操作错误(单点:HTTP 直接映射 status,工具端转失败文本)。 */
24
+ export class OpsError extends Error {
25
+ constructor(message, status = 400) {
26
+ super(message);
27
+ this.status = status;
28
+ }
29
+ }
30
+
31
+ /** messageText 的「合格 text 段」选择口径(单点):type==='text' 且非空白。 */
32
+ function textSegments(e) {
25
33
  const msg = e && e.data && e.data.message;
26
34
  const content = msg && Array.isArray(msg.content) ? msg.content : (e && e.data && e.data.content);
27
- if (!Array.isArray(content)) return "";
35
+ if (!Array.isArray(content)) return [];
36
+ const out = [];
28
37
  for (const c of content) {
29
- if (c && c.type === "text" && typeof c.text === "string" && c.text.trim()) return c.text;
38
+ if (c && c.type === "text" && typeof c.text === "string" && c.text.trim()) out.push(c.text);
30
39
  }
31
- return "";
40
+ return out;
41
+ }
42
+
43
+ /** 从 message 事件提取首个非空 text 块(listMessages / ops-core 共用单点)。 */
44
+ export function messageText(e) {
45
+ const segs = textSegments(e);
46
+ return segs.length ? segs[0] : "";
47
+ }
48
+
49
+ /**
50
+ * message 事件的**全量** text(/text 路由用单点,别在路由里再造口径)。
51
+ *
52
+ * 宿主把长文本拆成多个 content 段(seq 6830 实测 = 321+7954+20 三段的
53
+ * compaction checkpoint),只取首段 = 摘要被拦腰截断。合并规则与 messageText
54
+ * **同一条口径**:段选择器共用 textSegments(非文本段按 messageText 的规则跳过),
55
+ * 差异只在聚合——全部合格段按 "\\n\\n" 接回(content 段是切块,接缝丢过换行,
56
+ * "\\n\\n" 恰好还原段落边界,也不会把「。」「#」硬粘成一行)。
57
+ */
58
+ export function messageTextFull(e) {
59
+ const segs = textSegments(e);
60
+ return segs.join("\n\n");
32
61
  }
33
62
 
34
63
  /** 与 DSH 宿主一致:帧带 checksum(ZSTD_c_checksumFlag=1)。 */
@@ -298,11 +327,25 @@ export function markCommitted(messages) {
298
327
  return messages;
299
328
  }
300
329
 
330
+ const MAX_SPAN = 1_000_000;
331
+
332
+ /**
333
+ * M1 护栏:超 span 上限直接抛(fail loud;与 session-search 同款常量与阈值,
334
+ * 对方仓库不碰、本仓库自行持有常量)。路由层 catch 把 OpsError.status 映射为
335
+ * 404——历史 0.10.x marker 的区间都是个位数,一百万量级只可能来自损坏行或
336
+ * 伪造 marker,不允许把它卡死事件循环。
337
+ */
301
338
  export function computeShadowed(events) {
302
339
  const shadowed = new Set();
303
340
  for (const e of events) {
304
341
  const range = readReplaceOp(e);
305
342
  if (!range) continue;
343
+ if (range.endSeq - range.startSeq > MAX_SPAN) {
344
+ throw new OpsError(
345
+ `surface replace span too large: [${range.startSeq}..${range.endSeq}] exceeds MAX_SPAN=${MAX_SPAN} — refusing to materialize (corrupt or hostile replace marker?)`,
346
+ 404,
347
+ );
348
+ }
306
349
  for (let s = range.startSeq; s <= range.endSeq; s++) shadowed.add(s);
307
350
  }
308
351
  return shadowed;