cladogram 0.6.0-beta.2 → 0.6.0-beta.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.
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Safe workspace source code reader, symbol resolver & Git diff inspector
3
+ * for Clado's Right-Side Live Code & Git Diff Drawer.
4
+ */
5
+
6
+ import { execFileSync } from 'node:child_process';
7
+ import { existsSync, lstatSync, readdirSync, readFileSync } from 'node:fs';
8
+ import { extname, join, relative, resolve, sep } from 'node:path';
9
+ import { DocumentError } from '../workspace/documents.js';
10
+
11
+ const MAX_CODE_BYTES = 256 * 1024;
12
+ const SKIP_DIRS = new Set(['node_modules', '.git', '.clado', 'dist', 'build', '.next', 'coverage', '.cache', 'target', 'vendor']);
13
+ const LANG_BY_EXT = {
14
+ '.js': 'javascript', '.mjs': 'javascript', '.cjs': 'javascript', '.jsx': 'jsx',
15
+ '.ts': 'typescript', '.tsx': 'tsx', '.py': 'python', '.go': 'go', '.rs': 'rust',
16
+ '.java': 'java', '.kt': 'kotlin', '.rb': 'ruby', '.php': 'php', '.cs': 'csharp',
17
+ '.c': 'c', '.cpp': 'cpp', '.h': 'c', '.hpp': 'cpp', '.css': 'css', '.scss': 'scss',
18
+ '.html': 'html', '.json': 'json', '.yaml': 'yaml', '.yml': 'yaml', '.xml': 'xml',
19
+ '.sql': 'sql', '.sh': 'bash', '.md': 'markdown', '.mdc': 'markdown', '.vue': 'vue',
20
+ };
21
+
22
+ export function safeWorkspaceSourcePath(workspaceRoot, relPath) {
23
+ const clean = String(relPath || '').trim().replace(/^\/+/, '');
24
+ if (!clean || clean.includes('\0') || clean.includes('..') || clean.startsWith('.git/') || clean === '.git') {
25
+ throw new DocumentError('文件路径超出工作区安全范围。', 403);
26
+ }
27
+ const base = resolve(workspaceRoot);
28
+ const full = resolve(base, clean);
29
+ if (full !== base && !full.startsWith(base + sep)) {
30
+ throw new DocumentError('文件路径超出工作区安全范围。', 403);
31
+ }
32
+ return { full, rel: relative(base, full).split('\\').join('/') };
33
+ }
34
+
35
+ function isLikelyBinary(buf) {
36
+ const sample = buf.subarray(0, Math.min(buf.length, 4096));
37
+ for (let i = 0; i < sample.length; i++) {
38
+ if (sample[i] === 0) return true;
39
+ }
40
+ return false;
41
+ }
42
+
43
+ export function readWorkspaceCodeFile(workspaceRoot, relPath) {
44
+ const { full, rel } = safeWorkspaceSourcePath(workspaceRoot, relPath);
45
+ if (!existsSync(full)) throw new DocumentError('找不到文件:' + rel, 404);
46
+ const stat = lstatSync(full);
47
+ if (!stat.isFile()) throw new DocumentError('目标不是普通文件:' + rel, 400);
48
+ if (stat.size > MAX_CODE_BYTES) throw new DocumentError('源码文件超过 256 KB 预览限制。', 413);
49
+ const buf = readFileSync(full);
50
+ if (isLikelyBinary(buf)) throw new DocumentError('不支持预览二进制文件。', 415);
51
+ const content = buf.toString('utf8');
52
+ const lines = content.split(/\r?\n/);
53
+ const ext = extname(rel).toLowerCase();
54
+ return {
55
+ path: rel,
56
+ content,
57
+ totalLines: lines.length,
58
+ language: LANG_BY_EXT[ext] || ext.replace(/^\./, '') || 'text',
59
+ };
60
+ }
61
+
62
+ export function readFileGitState(workspaceRoot, relPath) {
63
+ const { full, rel } = safeWorkspaceSourcePath(workspaceRoot, relPath);
64
+ let headContent = null;
65
+ let gitDiff = '';
66
+ let tracked = false;
67
+ try {
68
+ headContent = execFileSync('git', ['show', `HEAD:${rel}`], {
69
+ cwd: workspaceRoot,
70
+ encoding: 'utf8',
71
+ maxBuffer: MAX_CODE_BYTES * 2,
72
+ stdio: ['ignore', 'pipe', 'ignore'],
73
+ });
74
+ tracked = true;
75
+ } catch {
76
+ headContent = null;
77
+ }
78
+ try {
79
+ gitDiff = execFileSync('git', ['diff', 'HEAD', '--', rel], {
80
+ cwd: workspaceRoot,
81
+ encoding: 'utf8',
82
+ maxBuffer: MAX_CODE_BYTES * 2,
83
+ stdio: ['ignore', 'pipe', 'ignore'],
84
+ });
85
+ } catch {
86
+ gitDiff = '';
87
+ }
88
+ const currentContent = existsSync(full) && lstatSync(full).isFile() && lstatSync(full).size <= MAX_CODE_BYTES
89
+ ? readFileSync(full, 'utf8')
90
+ : null;
91
+ return {
92
+ path: rel,
93
+ tracked,
94
+ headContent,
95
+ currentContent,
96
+ gitDiff,
97
+ changed: headContent !== null && currentContent !== null ? headContent !== currentContent : (!tracked && currentContent !== null),
98
+ };
99
+ }
100
+
101
+ export function resolveSymbolInWorkspace(workspaceRoot, symbolQuery) {
102
+ const raw = String(symbolQuery || '').trim();
103
+ if (!raw) throw new DocumentError('缺少符号或文件路径参数。', 400);
104
+
105
+ // Direct relative path check first
106
+ const strippedLine = raw.replace(/:(\d+)$/, '');
107
+ const explicitLine = Number(raw.match(/:(\d+)$/)?.[1] || 0);
108
+ try {
109
+ const { full, rel } = safeWorkspaceSourcePath(workspaceRoot, strippedLine);
110
+ if (existsSync(full) && lstatSync(full).isFile()) {
111
+ const fileData = readWorkspaceCodeFile(workspaceRoot, rel);
112
+ return { ...fileData, matchedLine: explicitLine || 1 };
113
+ }
114
+ } catch {}
115
+
116
+ // Parse ClassName#methodName or ClassName.methodName or filename
117
+ const [rawClass, rawMethod] = raw.split(/[#.]/);
118
+ const className = String(rawClass || '').replace(/\(.*\)$/, '').trim();
119
+ const methodName = String(rawMethod || '').replace(/\(.*\)$/, '').trim();
120
+ if (!className) throw new DocumentError('无法解析符号:' + raw, 404);
121
+
122
+ const candidates = [];
123
+ const walk = (dir, depth = 0) => {
124
+ if (depth > 6 || candidates.length >= 250) return;
125
+ let entries;
126
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
127
+ for (const ent of entries) {
128
+ if (ent.name.startsWith('.') && ent.name !== '.env.example') continue;
129
+ if (ent.isDirectory()) {
130
+ if (!SKIP_DIRS.has(ent.name)) walk(join(dir, ent.name), depth + 1);
131
+ } else if (ent.isFile()) {
132
+ const ext = extname(ent.name).toLowerCase();
133
+ if (!(ext in LANG_BY_EXT) || ext === '.md' || ext === '.mdc') continue;
134
+ const full = join(dir, ent.name);
135
+ const rel = relative(workspaceRoot, full).split('\\').join('/');
136
+ const stem = ent.name.slice(0, ent.name.length - ext.length);
137
+ const exactFile = stem.toLowerCase() === className.toLowerCase()
138
+ || ent.name.toLowerCase() === raw.toLowerCase()
139
+ || stem.replace(/[-_]/g, '').toLowerCase() === className.replace(/[-_]/g, '').toLowerCase();
140
+ candidates.push({ full, rel, score: exactFile ? 10 : (rel.toLowerCase().includes(className.toLowerCase()) ? 5 : 1) });
141
+ }
142
+ }
143
+ };
144
+ walk(workspaceRoot);
145
+ candidates.sort((a, b) => b.score - a.score);
146
+
147
+ const classRegex = new RegExp(`\\b${className.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
148
+ const methodRegex = methodName
149
+ ? new RegExp(`\\b${methodName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`)
150
+ : null;
151
+
152
+ for (const cand of candidates.slice(0, 80)) {
153
+ try {
154
+ const stat = lstatSync(cand.full);
155
+ if (stat.size > MAX_CODE_BYTES) continue;
156
+ const text = readFileSync(cand.full, 'utf8');
157
+ if (cand.score < 10 && !classRegex.test(text)) continue;
158
+ const lines = text.split(/\r?\n/);
159
+ let matchedLine = 1;
160
+ if (methodRegex) {
161
+ const mIdx = lines.findIndex(l => methodRegex.test(l));
162
+ if (mIdx >= 0) matchedLine = mIdx + 1;
163
+ else {
164
+ const cIdx = lines.findIndex(l => classRegex.test(l));
165
+ if (cIdx >= 0) matchedLine = cIdx + 1;
166
+ }
167
+ } else {
168
+ const cIdx = lines.findIndex(l => classRegex.test(l));
169
+ if (cIdx >= 0) matchedLine = cIdx + 1;
170
+ }
171
+ const ext = extname(cand.rel).toLowerCase();
172
+ return {
173
+ path: cand.rel,
174
+ content: text,
175
+ totalLines: lines.length,
176
+ language: LANG_BY_EXT[ext] || ext.replace(/^\./, '') || 'text',
177
+ matchedLine,
178
+ };
179
+ } catch {}
180
+ }
181
+
182
+ throw new DocumentError(`在工作区源码中未找到匹配「${raw}」的文件。`, 404);
183
+ }
package/src/server/mcp.js CHANGED
@@ -65,8 +65,8 @@ function createServer(invoke, invokeCapability) {
65
65
  catch (error) { return await failure(error, args); }
66
66
  });
67
67
  };
68
- register('clado_workspace', '初始化、查看工作区、列出子工作区、搜索或校验。用户说“我选的卡片”时用selection,按点选顺序读取标题路径、正文、后代和版本。selectionStatus为empty或stale时请用户选中或重新选择。inspect返回工作区版本和目录;workspaces列出当前服务范围内的子工作区;init准备工作区。', {
69
- action: z.enum(['init','inspect','search','validate','selection','workspaces']), query: z.string().optional(), includeContent: z.boolean().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(100).optional()
68
+ register('clado_workspace', '初始化、查看工作区、列出子工作区、读取画布拓扑树(graph)、搜索或校验。用户说“我选的卡片”时用selection,按点选顺序读取标题路径、正文、后代和版本。selectionStatus为empty或stale时请用户选中或重新选择。graph返回类似DOM树的卡片列布局、跨卡连线、语义Tag、孤立卡与断链快照。inspect返回工作区版本和目录;workspaces列出当前服务范围内的子工作区;init准备工作区。', {
69
+ action: z.enum(['init','inspect','search','validate','selection','workspaces','graph']), file: z.string().optional(), query: z.string().optional(), includeContent: z.boolean().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(100).optional()
70
70
  });
71
71
  register('clado_templates', '管理模板:scope默认project,设user操作用户库。read默认只返回prompt;编辑时view:source读完整MDC,view:full才返回metadata/source/starter/prompt全部内容。按当前项目、逐层上级、用户库查找,返回来源目录。create传templateId及source,或baseTemplateId(可选name/purpose)复制为新模板;update传完整source。模板头包含id/name/version/purpose/hard_constraints/soft_constraints/organization。pull复制到当前项目,默认逐层查找上级项目再查用户库,可用from:ancestor或from:user指定;push同步到用户库。不同内容默认拒绝覆盖,确认后overwrite:true。项目写入需expectedWorkspaceVersion,用户写入需expectedUserTemplateVersion,push需两者;均可dryRun。修改模板不影响已有文档头部。', {
72
72
  action: z.enum(['list','read','create','update','delete','pull','push']), scope: z.enum(['project','user']).optional(),
@@ -75,8 +75,8 @@ function createServer(invoke, invokeCapability) {
75
75
  view: z.enum(['prompt','source','full']).optional().describe('read默认prompt,编辑规则用source,只有需要全部字段时才用full。'),
76
76
  expectedWorkspaceVersion: version, expectedUserTemplateVersion: z.string().optional().describe('读取返回的userTemplateVersion;用户库写入及push必填。'), dryRun: z.boolean().optional()
77
77
  });
78
- register('clado_documents', '文档list/read/create/copy/update/rename/delete。read默认full,按需view:nodes/source/summary。create用file(.md或.mdc)/title/templateId,source只传正文。copy用file/newFile保留规则头和正文并重定位副本引用。create/copy检查目标尚不存在,可省略版本。update传完整source,可用metadata替换头;rename用newFile维护引用;delete被引用默认拒绝,unlink才断开。update/rename/delete使用expectedFileVersion或expectedWorkspaceVersion;results返回最终位置。', {
79
- action: z.enum(['list','read','create','copy','update','rename','delete']), view: z.enum(['full','nodes','source','summary']).optional(), file: z.string().optional(), query: z.string().optional(), title: z.string().optional(), templateId: z.string().optional(), source: text().optional(), metadata: z.record(z.string(), z.unknown()).optional(), newFile: z.string().optional(), unlink: z.boolean().optional(), expectedFileVersion, expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
78
+ register('clado_documents', '文档list/read/create/copy/update/rename/delete。read默认full,按需view:nodes/source/summary/graph(graph返回卡片列布局、跨卡连线、语义Tag、孤立卡与断链拓扑树)。create用file(.md或.mdc)/title/templateId,source只传正文。copy用file/newFile保留规则头和正文并重定位副本引用。create/copy检查目标尚不存在,可省略版本。update传完整source,可用metadata替换头;rename用newFile维护引用;delete被引用默认拒绝,unlink才断开。update/rename/delete使用expectedFileVersion或expectedWorkspaceVersion;results返回最终位置。', {
79
+ action: z.enum(['list','read','create','copy','update','rename','delete']), view: z.enum(['full','nodes','source','summary','graph']).optional(), file: z.string().optional(), query: z.string().optional(), title: z.string().optional(), templateId: z.string().optional(), source: text().optional(), metadata: z.record(z.string(), z.unknown()).optional(), newFile: z.string().optional(), unlink: z.boolean().optional(), expectedFileVersion, expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
80
80
  });
81
81
  register('clado_nodes', '节点read/query/create/insert/update/rename/move/delete。file必填,node用标题数组。read返回nodeVersion、行号、同级index和段落编号。create在同级末尾新增可省略版本;指定index需文件版本。insert追加/置顶或按唯一anchor插入、update用position:{mode:replace,anchor:原文}时可省略版本。按段落编号或整段覆盖用expectedNodeVersion、expectedFileVersion或expectedWorkspaceVersion,均保留孩子。rename/move维护引用;delete有孩子需recursive。results返回最终位置。', {
82
82
  action: z.enum(['read','query','create','insert','update','rename','move','delete']), ...Object.fromEntries(['file','node','parent','title','content','index','position','recursive','unlink','targetFile'].map(key => [key, nodeFields[key]])), relation: z.enum(['parent','children','ancestors','descendants','siblings','upstream','downstream']).optional(), depth: z.number().int().min(1).max(100).optional(), includeContent: z.boolean().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(100).optional(), expectedFileVersion, expectedNodeVersion, expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
@@ -1,11 +1,14 @@
1
1
  import { createServer } from 'node:http';
2
- import { createHash, randomUUID } from 'node:crypto';
2
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
3
3
  import { readFileSync, statSync, existsSync, mkdirSync } from 'node:fs';
4
4
  import { dirname, resolve, basename, join, relative, sep, isAbsolute } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { renderHtml } from '../html/page.js';
7
7
  import { pluginMarkup, workspacePluginAssets } from '../html/plugin-assets.js';
8
8
  import { scanDirectory, workspacePath, readDocument, DocumentError } from '../workspace/documents.js';
9
+ import { paragraphs } from '../workspace/content.js';
10
+ import { findNode, treeOf } from '../workspace/tree.js';
11
+ import { blockMedia, mediaPointFits } from '../core/media-links.js';
9
12
  import { contextFor, discoverWorkspaces, initialize } from '../workspace/storage.js';
10
13
  import { deleteCanvasObject, listCanvasObjects, readCanvasObject, saveCanvasObject } from '../workspace/objects.js';
11
14
  import { createWorkspaceService } from '../workspace/service.js';
@@ -25,10 +28,80 @@ import {
25
28
  renameCanvasDocument,
26
29
  resolveWorkspaceSelection,
27
30
  } from './workspace-hub.js';
31
+ import { readFileGitState, readWorkspaceCodeFile, resolveSymbolInWorkspace } from './code-inspect.js';
28
32
  import { z } from 'zod/v4';
29
33
  const assets = join(dirname(fileURLToPath(import.meta.url)), 'assets');
30
- const resourceTypes = {png:'image/png',jpg:'image/jpeg',jpeg:'image/jpeg',gif:'image/gif',webp:'image/webp',svg:'image/svg+xml',pdf:'application/pdf',txt:'text/plain',csv:'text/csv',json:'application/json'};
34
+ const resourceTypes = {
35
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml',
36
+ pdf: 'application/pdf', txt: 'text/plain', csv: 'text/csv', json: 'application/json',
37
+ mp4: 'video/mp4', webm: 'video/webm', mov: 'video/quicktime', ogv: 'video/ogg',
38
+ mp3: 'audio/mpeg', wav: 'audio/wav', m4a: 'audio/mp4', ogg: 'audio/ogg', flac: 'audio/flac',
39
+ };
31
40
  const types = { html: 'text/html', css: 'text/css', js: 'text/javascript', json: 'application/json', md: 'text/markdown' };
41
+ const REMOTE_COOKIE = 'clado_remote_token';
42
+
43
+ function isTrustedOrigin(req, remote = false) {
44
+ const origin = req.headers.origin;
45
+ if (!origin) return true;
46
+ const host = String(req.headers.host || '').trim();
47
+ if (!host) return false;
48
+ if (origin === 'http://' + host) return true;
49
+ if (!remote) return false;
50
+ const forwardedHost = String(req.headers['x-forwarded-host'] || '').split(',')[0].trim();
51
+ const allowed = new Set([host]);
52
+ if (forwardedHost) allowed.add(forwardedHost);
53
+ for (const h of allowed) {
54
+ if (h && (origin === 'http://' + h || origin === 'https://' + h)) return true;
55
+ }
56
+ return false;
57
+ }
58
+
59
+ function hasTrustedSameOrigin(req, remote = false) {
60
+ return Boolean(req.headers.origin) && isTrustedOrigin(req, remote);
61
+ }
62
+
63
+ function readCookie(req, name) {
64
+ const raw = String(req.headers.cookie || '');
65
+ if (!raw) return '';
66
+ for (const part of raw.split(';')) {
67
+ const idx = part.indexOf('=');
68
+ if (idx < 0) continue;
69
+ if (part.slice(0, idx).trim() === name) {
70
+ try { return decodeURIComponent(part.slice(idx + 1).trim()); } catch { return part.slice(idx + 1).trim(); }
71
+ }
72
+ }
73
+ return '';
74
+ }
75
+
76
+ function safeTokenMatch(candidate, expected) {
77
+ if (!candidate || !expected) return false;
78
+ const a = Buffer.from(String(candidate));
79
+ const b = Buffer.from(String(expected));
80
+ return a.length === b.length && timingSafeEqual(a, b);
81
+ }
82
+
83
+ function renderRemoteUnlockPage(errorMsg = '') {
84
+ const errHtml = errorMsg ? `<p class="err">${String(errorMsg).replace(/[<>&"]/g, '')}</p>` : '';
85
+ return `<!doctype html>
86
+ <html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
87
+ <title>Clado 远程调试验证</title>
88
+ <style>
89
+ *{box-sizing:border-box}body{margin:0;min-height:100dvh;display:grid;place-items:center;padding:20px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC",sans-serif;background:radial-gradient(circle at 20% 20%,#e0f2fe 0%,#f8fafc 45%,#eef2ff 100%);color:#0f172a}
90
+ .card{width:min(380px,100%);padding:26px 24px;border-radius:22px;background:rgba(255,255,255,.82);backdrop-filter:blur(22px);border:1px solid rgba(148,163,184,.32);box-shadow:0 24px 48px -20px rgba(15,23,42,.22)}
91
+ h1{margin:0 0 6px;font-size:18px;font-weight:650}p{margin:0 0 16px;font-size:13px;line-height:1.55;color:#475569}
92
+ .err{color:#be123c;background:rgba(244,63,94,.1);padding:8px 10px;border-radius:10px;margin-bottom:12px}
93
+ input{width:100%;padding:10px 12px;border-radius:12px;border:1px solid rgba(148,163,184,.45);font:inherit;font-size:14px;outline:none;margin-bottom:12px}
94
+ input:focus{border-color:#0284c7}button{width:100%;padding:10px 14px;border:0;border-radius:12px;background:#0f172a;color:#fff;font:inherit;font-size:14px;font-weight:600;cursor:pointer}
95
+ </style></head><body>
96
+ <form class="card" method="GET" action="/">
97
+ <h1>Clado 远程调试验证</h1>
98
+ <p>当前工作台运行在安全远程模式,请输入终端打印的访问口令(Token)继续。</p>
99
+ ${errHtml}
100
+ <input name="token" type="password" placeholder="粘贴访问口令…" autocomplete="off" required autofocus>
101
+ <button type="submit">进入空间画布</button>
102
+ </form></body></html>`;
103
+ }
104
+
32
105
  const viewSelection = z.object({
33
106
  tab: z.uuid(), file: z.string().min(1), version: z.string().regex(/^[a-f0-9]{64}$/),
34
107
  nodes: z.array(z.array(z.string().min(1)).min(1).max(6)).max(200),
@@ -36,6 +109,8 @@ const viewSelection = z.object({
36
109
  }).strict();
37
110
  export function createWorkspaceHandler(directory, options = {}) {
38
111
  const root = resolve(directory);
112
+ const remote = Boolean(options.remote);
113
+ const remoteToken = remote && options.remoteToken ? String(options.remoteToken) : '';
39
114
  const assetNames = new Set(['library.html','library.css','library.js','library-canvas.js']);
40
115
  if (options.capabilities) assetNames.add('library-plugin-bridge.js');
41
116
  if (options.plugins || options.experimentalPlugins) for (const name of ['library-plugins.js', 'library-plugins.css', 'clado-plugin-sdk.js']) assetNames.add(name);
@@ -50,13 +125,43 @@ export function createWorkspaceHandler(directory, options = {}) {
50
125
  const pluginFile = workspacePluginAssets.get(url.pathname);
51
126
  if (!url.pathname.startsWith('/library/') && !assetNames.has(route) && !pluginFile && !(options.entrypoint && route === '')) return false;
52
127
  try {
53
- const host = req.headers.host;
54
- if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host || '')) throw new DocumentError('只接受本机预览请求。',403);
128
+ const host = String(req.headers.host || '').trim();
129
+ if (remote) {
130
+ if (!host || /[\s/@]/.test(host)) throw new DocumentError('请求主机头不合法。', 403);
131
+ } else if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) {
132
+ throw new DocumentError('只接受本机预览请求。', 403);
133
+ }
134
+ if (remoteToken) {
135
+ const queryToken = url.searchParams.get('token') || '';
136
+ const authHeader = String(req.headers.authorization || '');
137
+ const bearerToken = authHeader.startsWith('Bearer ') ? authHeader.slice(7).trim() : '';
138
+ const cookieToken = readCookie(req, REMOTE_COOKIE);
139
+ if (queryToken && safeTokenMatch(queryToken, remoteToken) && req.method === 'GET') {
140
+ const isHttps = String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim() === 'https';
141
+ const cleanUrl = new URL(url.pathname + url.search, 'http://clado.local');
142
+ cleanUrl.searchParams.delete('token');
143
+ const dest = cleanUrl.pathname + (cleanUrl.search || '');
144
+ const cookie = `${REMOTE_COOKIE}=${encodeURIComponent(remoteToken)}; Path=/; HttpOnly; SameSite=Lax${isHttps ? '; Secure' : ''}`;
145
+ res.writeHead(302, { 'set-cookie': cookie, location: dest, 'cache-control': 'no-store' });
146
+ res.end();
147
+ return true;
148
+ }
149
+ const authed = safeTokenMatch(cookieToken, remoteToken)
150
+ || safeTokenMatch(bearerToken, remoteToken)
151
+ || safeTokenMatch(queryToken, remoteToken);
152
+ if (!authed) {
153
+ if (req.method === 'GET' && String(req.headers.accept || '').includes('text/html')) {
154
+ send(res, 401, types.html, renderRemoteUnlockPage(queryToken ? '口令不正确,请重新输入。' : ''));
155
+ return true;
156
+ }
157
+ throw new DocumentError('需要远程访问口令(token)。', 401);
158
+ }
159
+ }
55
160
  const pluginsEnabled = !!(options.plugins || options.experimentalPlugins);
56
161
  const pluginAsset = pluginsEnabled && url.pathname.startsWith('/library/plugin-assets/');
57
- if (req.headers.origin && req.headers.origin !== 'http://' + host && !(pluginAsset && req.headers.origin === 'null')) throw new DocumentError('来源不匹配。',403);
162
+ if (req.headers.origin && !isTrustedOrigin(req, remote) && !(pluginAsset && req.headers.origin === 'null')) throw new DocumentError('来源不匹配。',403);
58
163
  if (url.pathname === '/library/selection' && options.publishSelection && req.method === 'POST') {
59
- if (req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') throw new DocumentError('选区只接受同源页面请求。', 403);
164
+ if (!hasTrustedSameOrigin(req, remote) || req.headers['content-type'] !== 'application/json') throw new DocumentError('选区只接受同源页面请求。', 403);
60
165
  const target = resolveTarget(url);
61
166
  const chunks = []; let size = 0;
62
167
  for await (const chunk of req) {
@@ -97,7 +202,7 @@ export function createWorkspaceHandler(directory, options = {}) {
97
202
  if (!target.settings) throw new DocumentError('没有这个预览入口;文档操作请使用 /mcp。',404);
98
203
  const id = url.searchParams.get('id');
99
204
  if (req.method === 'GET') { json(res, 200, target.settings.read(id)); return true; }
100
- if (req.method !== 'POST' || req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') {
205
+ if (req.method !== 'POST' || !hasTrustedSameOrigin(req, remote) || req.headers['content-type'] !== 'application/json') {
101
206
  throw new DocumentError('插件设置只接受同源页面写入。', 403);
102
207
  }
103
208
  const chunks = []; let size = 0;
@@ -112,12 +217,12 @@ export function createWorkspaceHandler(directory, options = {}) {
112
217
  }
113
218
  if (options.installPlugin && url.pathname === '/library/install-plugin') {
114
219
  if (req.method === 'DELETE' && options.removePlugin) {
115
- if (req.headers.origin !== 'http://' + host) throw new DocumentError('卸载插件需要在工作区页面操作。', 403);
220
+ if (!hasTrustedSameOrigin(req, remote)) throw new DocumentError('卸载插件需要在工作区页面操作。', 403);
116
221
  const target = resolveTarget(url);
117
222
  json(res, 200, options.removePlugin(target.workspace, url.searchParams.get('id')));
118
223
  return true;
119
224
  }
120
- if (req.method !== 'POST' || req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') {
225
+ if (req.method !== 'POST' || !hasTrustedSameOrigin(req, remote) || req.headers['content-type'] !== 'application/json') {
121
226
  throw new DocumentError('插件安装需要在工作区页面操作。', 403);
122
227
  }
123
228
  const target = resolveTarget(url);
@@ -137,7 +242,7 @@ export function createWorkspaceHandler(directory, options = {}) {
137
242
  return true;
138
243
  }
139
244
  if (req.method === 'POST' && options.installCatalog) {
140
- if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
245
+ if (!hasTrustedSameOrigin(req, remote) || req.headers['content-type']?.split(';')[0] !== 'application/json') {
141
246
  throw new DocumentError('插件市场安装只接受同源页面请求。', 403);
142
247
  }
143
248
  const chunks = []; let size = 0;
@@ -167,7 +272,7 @@ export function createWorkspaceHandler(directory, options = {}) {
167
272
  return true;
168
273
  }
169
274
  if (req.method === 'POST') {
170
- if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
275
+ if (!hasTrustedSameOrigin(req, remote) || req.headers['content-type']?.split(';')[0] !== 'application/json') {
171
276
  throw new DocumentError('画布组件操作只接受同源页面请求。', 403);
172
277
  }
173
278
  const chunks = []; let size = 0;
@@ -194,7 +299,7 @@ export function createWorkspaceHandler(directory, options = {}) {
194
299
  return true;
195
300
  }
196
301
  if (req.method === 'POST') {
197
- if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
302
+ if (!hasTrustedSameOrigin(req, remote) || req.headers['content-type']?.split(';')[0] !== 'application/json') {
198
303
  throw new DocumentError('工作区切换只接受同源页面请求。', 403);
199
304
  }
200
305
  const chunks = []; let size = 0;
@@ -232,7 +337,7 @@ export function createWorkspaceHandler(directory, options = {}) {
232
337
  const target = resolveTarget(url);
233
338
  options.capabilities.connect(view.data, res, target.workspace, target.workspaceId); return true;
234
339
  }
235
- if (req.method !== 'POST' || req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') {
340
+ if (req.method !== 'POST' || !hasTrustedSameOrigin(req, remote) || req.headers['content-type'] !== 'application/json') {
236
341
  throw new DocumentError('插件通信只接受同源页面请求。', 403);
237
342
  }
238
343
  const captureId = url.searchParams.get('captureId');
@@ -251,6 +356,21 @@ export function createWorkspaceHandler(directory, options = {}) {
251
356
  json(res, 200, await options.capabilities.receive(view.data, message));
252
357
  return true;
253
358
  }
359
+ if (options.linkNode && url.pathname === '/library/link') {
360
+ if (req.method !== 'POST' || !hasTrustedSameOrigin(req, remote) || req.headers['content-type']?.split(';')[0] !== 'application/json') {
361
+ throw new DocumentError('画布连线只接受同源页面 POST 请求。', 403);
362
+ }
363
+ const chunks = []; let size = 0;
364
+ for await (const chunk of req) {
365
+ size += chunk.length;
366
+ if (size > 65536) throw new DocumentError('连线参数过大。', 413);
367
+ chunks.push(chunk);
368
+ }
369
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
370
+ const target = resolveTarget(url);
371
+ json(res, 200, await options.linkNode(target, body));
372
+ return true;
373
+ }
254
374
  if (req.method !== 'GET' && req.method !== 'HEAD') throw new DocumentError('不支持这个请求方法。',405);
255
375
  if (url.pathname === '/library/workspaces.json') {
256
376
  const workspaces = options.listWorkspaces
@@ -258,6 +378,30 @@ export function createWorkspaceHandler(directory, options = {}) {
258
378
  : [{ id: '', name: basename(root), workspace: root, documentRoot: root, documents: scanDirectory(root).documents.length }];
259
379
  json(res, 200, { scope: options.scopeName ? (typeof options.scopeName === 'function' ? options.scopeName() : options.scopeName) : basename(root), workspaces }); return true;
260
380
  }
381
+ if (url.pathname === '/library/code-file') {
382
+ const target = resolveTarget(url);
383
+ const relPath = url.searchParams.get('path');
384
+ const symbol = url.searchParams.get('symbol');
385
+ const data = relPath
386
+ ? readWorkspaceCodeFile(target.workspace, relPath)
387
+ : resolveSymbolInWorkspace(target.workspace, symbol);
388
+ let git = null;
389
+ try { git = readFileGitState(target.workspace, data.path); } catch {}
390
+ json(res, 200, {
391
+ ...data,
392
+ gitDiff: git?.gitDiff || '',
393
+ headContent: git?.headContent ?? null,
394
+ changed: Boolean(git?.changed),
395
+ });
396
+ return true;
397
+ }
398
+ if (url.pathname === '/library/git-diff') {
399
+ const target = resolveTarget(url);
400
+ const relPath = url.searchParams.get('path');
401
+ if (!relPath) throw new DocumentError('缺少 path 参数。', 400);
402
+ json(res, 200, readFileGitState(target.workspace, relPath));
403
+ return true;
404
+ }
261
405
  if (pluginsEnabled && url.pathname === '/library/plugins.json') {
262
406
  const target = resolveTarget(url);
263
407
  const values = target.settings?.values() || {};
@@ -302,11 +446,15 @@ export function createWorkspaceHandler(directory, options = {}) {
302
446
  const path=workspacePath(target.root,name,false,true);
303
447
  res.writeHead(200,{'content-type':type,'x-content-type-options':'nosniff','content-security-policy':"default-src 'none'; sandbox",'cache-control':'no-store'});res.end(readFileSync(path));return true;
304
448
  }
305
- if (!['/library/source.mdc','/library/canvas'].includes(url.pathname)) throw new DocumentError('没有这个预览入口;文档操作请使用 /mcp。',404);
449
+ if (!['/library/source.mdc','/library/canvas','/library/doc.json'].includes(url.pathname)) throw new DocumentError('没有这个预览入口;文档操作请使用 /mcp。',404);
306
450
  const target = resolveTarget(url);
307
451
  const file = workspacePath(target.root,name), item = readDocument(file);
308
452
  if (url.pathname === '/library/source.mdc') { send(res,200,types.md,item.source); return true; }
309
453
  if (item.diagnostics.some(d=>d.severity==='error')) throw new DocumentError('文档暂时无法解析。',422,item.diagnostics);
454
+ if (url.pathname === '/library/doc.json') {
455
+ json(res, 200, { file: name, version: item.version, doc: item.doc, diagnostics: item.diagnostics });
456
+ return true;
457
+ }
310
458
  const mode = ['cards','mindmap','doc'].includes(url.searchParams.get('mode')) ? url.searchParams.get('mode') : (options.mode || 'cards');
311
459
  let html = (options.render || renderHtml)(item.doc,item.diagnostics,{file:name,title:item.doc.title,mode,theme:['light','dark'].includes(url.searchParams.get('theme')) ? url.searchParams.get('theme') : options.theme || 'light',library:true,workspaceChrome:url.searchParams.get('chrome') === 'workspace'});
312
460
  const bodyEnd = html.lastIndexOf('</body>');
@@ -317,7 +465,12 @@ export function createWorkspaceHandler(directory, options = {}) {
317
465
  }
318
466
  };
319
467
  }
320
- export async function startWorkspace(input, { port = 4317, mode = 'cards', theme = 'light', entry, project = false, hubMode = false, experimentalPlugins = false, agent: agentName = 'pi' } = {}) {
468
+ export async function startWorkspace(input, { port = 4317, host = '', remote = false, token = '', noToken = false, mode = 'cards', theme = 'light', entry, project = false, hubMode = false, experimentalPlugins = false, agent: agentName = 'pi' } = {}) {
469
+ const isRemote = Boolean(remote);
470
+ const remoteToken = isRemote && !noToken
471
+ ? (String(token || '').trim() || randomBytes(12).toString('hex'))
472
+ : '';
473
+ const listenHost = String(host || '').trim() || (isRemote ? '0.0.0.0' : '127.0.0.1');
321
474
  const path = resolve(input);
322
475
  if (!existsSync(path) && !/\.mdc?$/i.test(path)) mkdirSync(path, { recursive: true });
323
476
  if (statSync(path).isFile() && !/\.mdc?$/i.test(path)) throw new DocumentError('serve 文件需要 .mdc 或 .md 扩展名。');
@@ -408,6 +561,7 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
408
561
  mcpUrl: liveMcpUrl,
409
562
  workspaceService: mcpService,
410
563
  events,
564
+ remote: isRemote,
411
565
  resolveRuntimeInfo: targetWorkspace => {
412
566
  const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
413
567
  return {
@@ -553,8 +707,100 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
553
707
  return { ok: true, ...removed };
554
708
  },
555
709
  };
710
+ async function linkNode(target, body = {}) {
711
+ const file = String(body.file || '').trim();
712
+ const rawNode = Array.isArray(body.node) && body.node.length ? body.node : body.sourceNode;
713
+ const node = Array.isArray(rawNode) && rawNode.length ? rawNode.map(String) : null;
714
+ if (!file || !node) throw new DocumentError('缺少源画布文件或源节点路径。', 400);
715
+ const targetNode = Array.isArray(body.targetNode) && body.targetNode.length ? body.targetNode.map(String) : undefined;
716
+ const targetFile = body.targetFile ? String(body.targetFile).trim() : undefined;
717
+ const rawTag = body.targetTag || body.targetTagId || '';
718
+ const targetTag = rawTag ? String(rawTag).trim().replace(/^#/, '') : '';
719
+ const anchor = typeof body.anchor === 'string' && body.anchor.trim() ? body.anchor.trim() : '';
720
+ let sourcePoint = body.sourcePoint && typeof body.sourcePoint === 'object' ? { ...body.sourcePoint } : undefined;
721
+ let targetPoint = body.targetPoint && typeof body.targetPoint === 'object' ? { ...body.targetPoint } : undefined;
722
+ const rawLabel = String(body.label || anchor || targetTag || targetNode?.at(-1) || '').replace(/[\r\n\[\]]/g, '').trim();
723
+ const label = rawLabel || '关联';
724
+ const docSummary = await mcpService('clado_documents', { workspace: target.workspace, action: 'read', file, view: 'summary' });
725
+ const expectedFileVersion = docSummary?.version;
726
+
727
+ // 自动把前端传入的「第 N 个代码块/表格/Mermaid」映射为节点正文中的真实段落序号,并规范 Mermaid nodeId 字段
728
+ const resolveMediaPoint = (nodePath, pt) => {
729
+ if (!pt || !nodePath) return pt;
730
+ const next = { ...pt };
731
+ if (next.kind === 'mermaid' && next.node && !next.nodeId) {
732
+ next.nodeId = next.node;
733
+ delete next.node;
734
+ }
735
+ if (next.kind === 'line') return next;
736
+ try {
737
+ const full = workspacePath(target.root, file);
738
+ const tree = treeOf(readFileSync(full, 'utf8'), file);
739
+ const rec = findNode(tree, nodePath);
740
+ if (!rec?.node?.content) return next;
741
+ const blocks = paragraphs(rec.node.content);
742
+ const direct = blocks[(next.paragraph || 1) - 1];
743
+ if (direct && mediaPointFits(blockMedia(direct.text), next)) return next;
744
+ const sameKind = blocks.filter(b => blockMedia(b.text)?.kind === next.kind);
745
+ const byKindIdx = sameKind[(next.paragraph || 1) - 1];
746
+ if (byKindIdx && mediaPointFits(blockMedia(byKindIdx.text), next)) {
747
+ return { ...next, paragraph: byKindIdx.index };
748
+ }
749
+ const firstFit = sameKind.find(b => mediaPointFits(blockMedia(b.text), next));
750
+ if (firstFit) return { ...next, paragraph: firstFit.index };
751
+ } catch {}
752
+ return next;
753
+ };
754
+ if (sourcePoint) sourcePoint = resolveMediaPoint(node, sourcePoint);
755
+ if (targetPoint && targetNode) targetPoint = resolveMediaPoint(targetNode, targetPoint);
756
+
757
+ // Direct Tag link in prose (no media sourcePoint): write clean [label](#tagId)
758
+ if (targetTag && !sourcePoint && !targetPoint) {
759
+ const tagLink = `[${label}](#${targetTag})`;
760
+ if (anchor) {
761
+ const res = await mcpService('clado_nodes', {
762
+ workspace: target.workspace,
763
+ action: 'update',
764
+ file,
765
+ node,
766
+ content: tagLink,
767
+ position: { mode: 'replace', anchor },
768
+ expectedFileVersion,
769
+ });
770
+ events.emit(target.workspace, 'doc.updated', { file, action: 'link', nodes: [node], label: '已连接到 #' + targetTag });
771
+ return { ok: true, file, mode: 'tag-replace', ...res };
772
+ }
773
+ const res = await mcpService('clado_nodes', {
774
+ workspace: target.workspace,
775
+ action: 'insert',
776
+ file,
777
+ node,
778
+ content: tagLink,
779
+ expectedFileVersion,
780
+ });
781
+ events.emit(target.workspace, 'doc.updated', { file, action: 'link', nodes: [node], label: '已连接到 #' + targetTag });
782
+ return { ok: true, file, mode: 'tag-append', ...res };
783
+ }
784
+
785
+ if (!targetNode && !targetFile) throw new DocumentError('缺少目标卡片、小节或语义 Tag。', 400);
786
+ const res = await mcpService('clado_links', {
787
+ workspace: target.workspace,
788
+ action: 'connect',
789
+ file,
790
+ node,
791
+ ...(targetFile ? { targetFile } : {}),
792
+ ...(targetNode ? { targetNode } : {}),
793
+ label,
794
+ ...(sourcePoint ? { sourcePoint } : (anchor ? { position: { mode: 'replace', anchor } } : {})),
795
+ ...(targetPoint ? { targetPoint } : {}),
796
+ ...(expectedFileVersion ? { expectedFileVersion } : {}),
797
+ });
798
+ events.emit(target.workspace, 'doc.updated', { file, action: 'link', nodes: [node, ...(targetNode ? [targetNode] : [])], label: '已建立新连线' });
799
+ return { ok: true, file, mode: sourcePoint ? 'media-point' : (anchor ? 'anchor-replace' : 'card-link'), ...res };
800
+ }
556
801
  const handle = createWorkspaceHandler(root,{
557
- entrypoint:true,mode,theme,entry:entryFile,publishSelection,events,
802
+ entrypoint:true,mode,theme,entry:entryFile,publishSelection,events,linkNode,
803
+ remote:isRemote,remoteToken,
558
804
  plugins:rootRuntime.plugins,experimentalPlugins,servePluginAsset,
559
805
  agent,agentProfile:agentName,capabilities,settings:rootRuntime.settings,installPlugin,removePlugin,readPluginRegistry,installCatalog,canvasObjects,workspaceHub,
560
806
  mcpUrl:liveMcpUrl,
@@ -571,8 +817,9 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
571
817
  });
572
818
  if (agent) server.on('close', agent.close);
573
819
  server.on('close', events.close);
574
- await new Promise((resolve,reject) => { server.once('error',reject); server.listen(port,'127.0.0.1',resolve); });
820
+ await new Promise((resolve,reject) => { server.once('error',reject); server.listen(port,listenHost,resolve); });
575
821
  const file = entryFile ? '?file='+encodeURIComponent(entryFile) : '';
576
- const origin = 'http://127.0.0.1:'+server.address().port;
577
- return {server,url:origin+'/'+file,mcpUrl:origin+'/mcp',workspace,root,pluginWarnings:rootRuntime.plugins?.warnings || [],stopAgent:agent?.close,stopCapabilities:capabilities.close,stopEvents:events.close};
822
+ const actualPort = server.address().port;
823
+ const origin = 'http://127.0.0.1:'+actualPort;
824
+ return {server,url:origin+'/'+file,mcpUrl:origin+'/mcp',workspace,root,remote:isRemote,remoteToken,listenHost,pluginWarnings:rootRuntime.plugins?.warnings || [],stopAgent:agent?.close,stopCapabilities:capabilities.close,stopEvents:events.close};
578
825
  }