Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

refactor(mcps): 抽出确认 token 编解码供多个工具复用

Yecheng Fu273c0a9c36bf
diff --git a/packages/lizi-mcps/src/__tests__/_confirmation_token.test.ts b/packages/lizi-mcps/src/__tests__/_confirmation_token.test.ts
new file mode 100644
index 0000000000..f188d2124e
--- /dev/null
+++ b/packages/lizi-mcps/src/__tests__/_confirmation_token.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ decodeConfirmationToken,
+ encodeConfirmationToken,
+} from "../xdt-helper/_confirmation_token.js";
+
+describe("confirmation token", () => {
+ it("round-trips a payload when validation succeeds", () => {
+ const payload = { v: 1, changes: ["session-1"] };
+ const token = encodeConfirmationToken(payload);
+
+ expect(
+ decodeConfirmationToken(token, (value): value is typeof payload => {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ "v" in value &&
+ value.v === 1 &&
+ "changes" in value &&
+ Array.isArray(value.changes)
+ );
+ }),
+ ).toEqual(payload);
+ });
+
+ it("returns null when the signature is tampered with", () => {
+ const token = encodeConfirmationToken({ v: 1 });
+ const tampered = `${token.slice(0, -1)}${token.endsWith("0") ? "1" : "0"}`;
+
+ expect(
+ decodeConfirmationToken(
+ tampered,
+ (_value): _value is { v: number } => true,
+ ),
+ ).toBeNull();
+ });
+
+ it("returns null when validation rejects the payload", () => {
+ const token = encodeConfirmationToken({ v: 1 });
+
+ expect(
+ decodeConfirmationToken(token, (_value): _value is { v: 2 } => false),
+ ).toBeNull();
+ });
+});
diff --git a/packages/lizi-mcps/src/xdt-helper/_confirmation_token.ts b/packages/lizi-mcps/src/xdt-helper/_confirmation_token.ts
new file mode 100644
index 0000000000..690dcfe976
--- /dev/null
+++ b/packages/lizi-mcps/src/xdt-helper/_confirmation_token.ts
@@ -0,0 +1,45 @@
+/**
+ * xdt-helper/_confirmation_token.ts —— dry-run → 确认 两段式写操作共用的 token 编解码。
+ *
+ * 需要用户核对后才能落库的批量写(rename_sessions / delete_sessions)先返回预览与
+ * 一枚 HMAC 签名的 token,真正写入时必须回传同一批变更对应的 token。密钥进程内随机,
+ * token 不跨进程、不落盘,只用于防止模型跳过预览直接写。
+ */
+
+import { createHmac, randomBytes } from "node:crypto";
+
+const CONFIRMATION_TOKEN_SECRET = randomBytes(32);
+
+function sign(encoded: string): string {
+ return createHmac("sha256", CONFIRMATION_TOKEN_SECRET)
+ .update(encoded)
+ .digest("hex")
+ .slice(0, 24);
+}
+
+export function encodeConfirmationToken(payload: unknown): string {
+ const encoded = Buffer.from(JSON.stringify(payload), "utf8").toString(
+ "base64url",
+ );
+ return `v1.${encoded}.${sign(encoded)}`;
+}
+
+/**
+ * 解码并校验签名;`validate` 负责结构校验,任一步失败返回 null。
+ */
+export function decodeConfirmationToken<T>(
+ token: string,
+ validate: (payload: unknown) => payload is T,
+): T | null {
+ const [version, encoded, digest] = token.split(".");
+ if (version !== "v1" || !encoded || !digest) return null;
+ if (digest !== sign(encoded)) return null;
+ try {
+ const payload: unknown = JSON.parse(
+ Buffer.from(encoded, "base64url").toString("utf8"),
+ );
+ return validate(payload) ? payload : null;
+ } catch {
+ return null;
+ }
+}
diff --git a/packages/lizi-mcps/src/xdt-helper/rename_sessions.ts b/packages/lizi-mcps/src/xdt-helper/rename_sessions.ts
index fe21f2d531..9c2b78f152 100644
--- a/packages/lizi-mcps/src/xdt-helper/rename_sessions.ts
+++ b/packages/lizi-mcps/src/xdt-helper/rename_sessions.ts
@@ -1,16 +1,14 @@
import { BRAND_NAME } from '@cindy/maker-shared/branding';
-import { createHmac, randomBytes } from 'node:crypto';
-
import { z } from 'zod';
import type { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';
import type { ControlResult } from '../lizi_xdtHelperMcpServer.js';
import type { LiziMcpSessionContext } from '../types.js';
+import { decodeConfirmationToken, encodeConfirmationToken } from './_confirmation_token.js';
import { errorPayload, okPayload } from './_payload.js';
const MAX_RENAME_BATCH_SIZE = 20;
const TITLE_MAX_LENGTH = 120;
-const CONFIRMATION_TOKEN_SECRET = randomBytes(32);
export interface RenameSessionChange {
sessionId: string;
@@ -108,44 +106,23 @@ function createConfirmationPayload(
};
}
-function encodeConfirmationToken(payload: RenameSessionsConfirmationPayload): string {
- const encoded = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');
- const digest = createHmac('sha256', CONFIRMATION_TOKEN_SECRET)
- .update(encoded)
- .digest('hex')
- .slice(0, 24);
- return `v1.${encoded}.${digest}`;
-}
-
-function decodeConfirmationToken(token: string): RenameSessionsConfirmationPayload | null {
- const [version, encoded, digest] = token.split('.');
- if (version !== 'v1' || !encoded || !digest) return null;
- const expectedDigest = createHmac('sha256', CONFIRMATION_TOKEN_SECRET)
- .update(encoded)
- .digest('hex')
- .slice(0, 24);
- if (digest !== expectedDigest) return null;
-
- try {
- const payload = JSON.parse(
- Buffer.from(encoded, 'base64url').toString('utf8'),
- ) as RenameSessionsConfirmationPayload;
- if (payload.v !== 1 || !Array.isArray(payload.changes)) return null;
- for (const change of payload.changes) {
- if (
- typeof change?.sessionId !== 'string' ||
- typeof change.title !== 'string' ||
- (change.expectedCurrentTitle !== null && typeof change.expectedCurrentTitle !== 'string') ||
- (change.expectedUpdatedAt !== null && typeof change.expectedUpdatedAt !== 'string') ||
- (change.approvedCurrentTitle !== null && typeof change.approvedCurrentTitle !== 'string')
- ) {
- return null;
- }
+function isRenameConfirmationPayload(
+ payload: unknown,
+): payload is RenameSessionsConfirmationPayload {
+ const p = payload as Partial<RenameSessionsConfirmationPayload> | null;
+ if (!p || p.v !== 1 || !Array.isArray(p.changes)) return false;
+ for (const change of p.changes) {
+ if (
+ typeof change?.sessionId !== 'string' ||
+ typeof change.title !== 'string' ||
+ (change.expectedCurrentTitle !== null && typeof change.expectedCurrentTitle !== 'string') ||
+ (change.expectedUpdatedAt !== null && typeof change.expectedUpdatedAt !== 'string') ||
+ (change.approvedCurrentTitle !== null && typeof change.approvedCurrentTitle !== 'string')
+ ) {
+ return false;
}
- return payload;
- } catch {
- return null;
}
+ return true;
}
function matchesConfirmationPayload(
@@ -213,7 +190,9 @@ export function registerRenameSessionsTool(
}
const confirmationPayload =
- !dry_run && confirmation_token ? decodeConfirmationToken(confirmation_token) : null;
+ !dry_run && confirmation_token
+ ? decodeConfirmationToken(confirmation_token, isRenameConfirmationPayload)
+ : null;
if (
!dry_run &&
(!confirmationPayload || !matchesConfirmationPayload(normalized, confirmationPayload))