codexmate 0.1.29 → 0.1.31

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.
Files changed (72) hide show
  1. package/README.md +95 -4
  2. package/README.vi.md +95 -4
  3. package/README.zh.md +96 -4
  4. package/cli/config-bootstrap.js +25 -11
  5. package/cli/skills.js +33 -8
  6. package/cli.js +364 -42
  7. package/lib/cli-config-engine.js +260 -0
  8. package/lib/cli-utils.js +2 -1
  9. package/lib/cli-webhook.js +1 -1
  10. package/lib/handoff-mcp.js +282 -0
  11. package/lib/http-access-control.js +335 -0
  12. package/lib/thread-handoff.js +130 -0
  13. package/lib/web-startup-auth.js +49 -0
  14. package/lib/workflow-engine.js +92 -21
  15. package/lib/workflow-runner.js +261 -0
  16. package/package.json +6 -1
  17. package/web-ui/app.js +33 -4
  18. package/web-ui/logic.sessions.mjs +24 -0
  19. package/web-ui/modules/access-token.mjs +33 -0
  20. package/web-ui/modules/api.mjs +2 -1
  21. package/web-ui/modules/app.computed.dashboard.mjs +1 -1
  22. package/web-ui/modules/app.methods.codex-config.mjs +1 -1
  23. package/web-ui/modules/app.methods.index.mjs +2 -0
  24. package/web-ui/modules/app.methods.navigation.mjs +17 -3
  25. package/web-ui/modules/app.methods.prompts-editor.mjs +7 -0
  26. package/web-ui/modules/app.methods.providers.mjs +2 -2
  27. package/web-ui/modules/app.methods.runtime.mjs +3 -2
  28. package/web-ui/modules/app.methods.session-actions.mjs +3 -0
  29. package/web-ui/modules/app.methods.session-browser.mjs +11 -3
  30. package/web-ui/modules/app.methods.system-prompt.mjs +1 -8
  31. package/web-ui/modules/app.methods.workflows.mjs +41 -0
  32. package/web-ui/modules/i18n/locales/en.mjs +43 -2
  33. package/web-ui/modules/i18n/locales/ja.mjs +43 -2
  34. package/web-ui/modules/i18n/locales/vi.mjs +43 -2
  35. package/web-ui/modules/i18n/locales/zh-tw.mjs +43 -2
  36. package/web-ui/modules/i18n/locales/zh.mjs +43 -2
  37. package/web-ui/modules/i18n.mjs +16 -0
  38. package/web-ui/modules/sessions-filters-url.mjs +3 -0
  39. package/web-ui/modules/skills.computed.mjs +11 -0
  40. package/web-ui/modules/skills.methods.mjs +63 -12
  41. package/web-ui/modules/thread-handoff.mjs +142 -0
  42. package/web-ui/partials/index/layout-footer.html +1 -1
  43. package/web-ui/partials/index/layout-header.html +32 -12
  44. package/web-ui/partials/index/panel-config-claude.html +2 -0
  45. package/web-ui/partials/index/panel-config-codex.html +2 -0
  46. package/web-ui/partials/index/panel-config-kilocode.html +3 -1
  47. package/web-ui/partials/index/panel-config-openclaw.html +2 -0
  48. package/web-ui/partials/index/panel-config-opencode.html +3 -1
  49. package/web-ui/partials/index/panel-config-pi.html +2 -0
  50. package/web-ui/partials/index/panel-dashboard.html +59 -0
  51. package/web-ui/partials/index/panel-market.html +23 -5
  52. package/web-ui/partials/index/panel-prompts.html +28 -16
  53. package/web-ui/partials/index/panel-sessions.html +51 -70
  54. package/web-ui/partials/index/panel-trash.html +3 -0
  55. package/web-ui/partials/index/thread-handoff.html +59 -0
  56. package/web-ui/res/web-ui-render.precompiled.js +1020 -493
  57. package/web-ui/styles/controls-forms.css +9 -0
  58. package/web-ui/styles/dashboard.css +51 -0
  59. package/web-ui/styles/feedback.css +26 -0
  60. package/web-ui/styles/layout-shell.css +66 -2
  61. package/web-ui/styles/modals-core.css +87 -0
  62. package/web-ui/styles/navigation-panels.css +5 -11
  63. package/web-ui/styles/plugins-panel.css +62 -0
  64. package/web-ui/styles/prompts-editor.css +11 -4
  65. package/web-ui/styles/responsive.css +19 -10
  66. package/web-ui/styles/sessions-list.css +19 -1
  67. package/web-ui/styles/sessions-preview.css +224 -140
  68. package/web-ui/styles/sessions-toolbar-trash.css +2 -2
  69. package/web-ui/styles/settings-panel.css +1 -1
  70. package/web-ui/styles/skills-market.css +47 -0
  71. package/web-ui/styles/titles-cards.css +1 -1
  72. package/web-ui/styles/trash-panel.css +43 -6
@@ -0,0 +1,335 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const net = require('net');
5
+
6
+ const IPV4_BYTE_COUNT = 4;
7
+ const IPV6_BYTE_COUNT = 16;
8
+ const IPV4_PREFIX_MAX = 32;
9
+ const IPV6_PREFIX_MAX = 128;
10
+ const BITS_PER_BYTE = 8;
11
+ const AUTH_REALM = 'codexmate';
12
+ const SECURITY_HEADERS = Object.freeze({
13
+ 'X-Content-Type-Options': 'nosniff',
14
+ 'X-Frame-Options': 'DENY',
15
+ 'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' ws: wss:"
16
+ });
17
+
18
+ function parseIpv4Bytes(value) {
19
+ if (net.isIP(value) !== 4) {
20
+ return null;
21
+ }
22
+ return Buffer.from(value.split('.').map((part) => Number(part)));
23
+ }
24
+
25
+ function parseIpv6Words(value) {
26
+ if (net.isIP(value) !== 6) {
27
+ return null;
28
+ }
29
+ const halves = value.split('::');
30
+ if (halves.length > 2) {
31
+ return null;
32
+ }
33
+
34
+ const parseSide = (side) => {
35
+ if (!side) {
36
+ return [];
37
+ }
38
+ const words = [];
39
+ const tokens = side.split(':');
40
+ for (let index = 0; index < tokens.length; index += 1) {
41
+ const token = tokens[index];
42
+ if (token.includes('.')) {
43
+ if (index !== tokens.length - 1) {
44
+ return null;
45
+ }
46
+ const ipv4 = parseIpv4Bytes(token);
47
+ if (!ipv4) {
48
+ return null;
49
+ }
50
+ words.push(ipv4[0] * 256 + ipv4[1]);
51
+ words.push(ipv4[2] * 256 + ipv4[3]);
52
+ continue;
53
+ }
54
+ if (!/^[0-9a-f]{1,4}$/i.test(token)) {
55
+ return null;
56
+ }
57
+ words.push(parseInt(token, 16));
58
+ }
59
+ return words;
60
+ };
61
+
62
+ const left = parseSide(halves[0]);
63
+ const right = parseSide(halves[1] || '');
64
+ if (!left || !right) {
65
+ return null;
66
+ }
67
+
68
+ let words;
69
+ if (halves.length === 1) {
70
+ if (left.length !== 8) {
71
+ return null;
72
+ }
73
+ words = left;
74
+ } else {
75
+ const missing = 8 - left.length - right.length;
76
+ if (missing < 1) {
77
+ return null;
78
+ }
79
+ words = left.concat(new Array(missing).fill(0), right);
80
+ }
81
+
82
+ const bytes = Buffer.alloc(IPV6_BYTE_COUNT);
83
+ for (let index = 0; index < words.length; index += 1) {
84
+ bytes.writeUInt16BE(words[index], index * 2);
85
+ }
86
+ return bytes;
87
+ }
88
+
89
+ function parseIp(value) {
90
+ if (typeof value !== 'string') {
91
+ return null;
92
+ }
93
+ const address = value.trim();
94
+ const ipv4 = parseIpv4Bytes(address);
95
+ if (ipv4) {
96
+ return { version: 4, bytes: ipv4 };
97
+ }
98
+ const ipv6 = parseIpv6Words(address);
99
+ if (ipv6) {
100
+ return { version: 6, bytes: ipv6 };
101
+ }
102
+ return null;
103
+ }
104
+
105
+ function isIpv4Mapped(bytes) {
106
+ if (bytes.length !== IPV6_BYTE_COUNT) {
107
+ return false;
108
+ }
109
+ for (let index = 0; index < 10; index += 1) {
110
+ if (bytes[index] !== 0) {
111
+ return false;
112
+ }
113
+ }
114
+ return bytes[10] === 255 && bytes[11] === 255;
115
+ }
116
+
117
+ function normalizeIp(ip) {
118
+ if (ip && ip.version === 6 && isIpv4Mapped(ip.bytes)) {
119
+ return { version: 4, bytes: ip.bytes.slice(12, 16) };
120
+ }
121
+ return ip;
122
+ }
123
+
124
+ function parseCidr(value) {
125
+ if (typeof value !== 'string') {
126
+ return null;
127
+ }
128
+ const parts = value.trim().split('/');
129
+ if (parts.length > 2) {
130
+ return null;
131
+ }
132
+ const ip = parseIp(parts[0]);
133
+ if (!ip) {
134
+ return null;
135
+ }
136
+ let prefix = null;
137
+ if (parts.length === 2) {
138
+ if (!/^\d+$/.test(parts[1])) {
139
+ return null;
140
+ }
141
+ prefix = Number(parts[1]);
142
+ }
143
+ const maxPrefix = ip.version === 4 ? IPV4_PREFIX_MAX : IPV6_PREFIX_MAX;
144
+ if (prefix !== null && prefix > maxPrefix) {
145
+ return null;
146
+ }
147
+ if (ip.version === 6 && isIpv4Mapped(ip.bytes) && (prefix === null || prefix >= 96)) {
148
+ return {
149
+ version: 4,
150
+ bytes: ip.bytes.slice(12, 16),
151
+ prefix: prefix === null ? IPV4_PREFIX_MAX : prefix - 96
152
+ };
153
+ }
154
+ return {
155
+ version: ip.version,
156
+ bytes: ip.bytes,
157
+ prefix: prefix === null ? maxPrefix : prefix
158
+ };
159
+ }
160
+
161
+ function parseAllowedIps(value) {
162
+ let source = value;
163
+ if (source === undefined || source === null) {
164
+ source = [];
165
+ } else if (typeof source === 'string') {
166
+ source = source.split(',');
167
+ } else if (!Array.isArray(source)) {
168
+ throw new Error('parseAllowedIps: allowed IP list must be a string or an array');
169
+ }
170
+
171
+ const entries = [];
172
+ for (const item of source) {
173
+ if (typeof item !== 'string') {
174
+ throw new Error('parseAllowedIps: allowed IP entries must be strings');
175
+ }
176
+ for (const part of item.split(',')) {
177
+ const entry = part.trim();
178
+ if (!entry) {
179
+ continue;
180
+ }
181
+ if (!parseCidr(entry)) {
182
+ throw new Error(`parseAllowedIps: invalid CIDR entry "${entry}"`);
183
+ }
184
+ entries.push(entry);
185
+ }
186
+ }
187
+ return entries;
188
+ }
189
+
190
+ function bytesMatchPrefix(left, right, prefix) {
191
+ const fullBytes = Math.floor(prefix / BITS_PER_BYTE);
192
+ for (let index = 0; index < fullBytes; index += 1) {
193
+ if (left[index] !== right[index]) {
194
+ return false;
195
+ }
196
+ }
197
+ const remainingBits = prefix % BITS_PER_BYTE;
198
+ if (!remainingBits) {
199
+ return true;
200
+ }
201
+ const mask = (0xff << (BITS_PER_BYTE - remainingBits)) & 0xff;
202
+ return (left[fullBytes] & mask) === (right[fullBytes] & mask);
203
+ }
204
+
205
+ function compileAllowedIps(allowedIps) {
206
+ return parseAllowedIps(allowedIps).map((entry) => parseCidr(entry));
207
+ }
208
+
209
+ function isIpAllowed(ip, allowedIps) {
210
+ const candidate = normalizeIp(parseIp(ip));
211
+ if (!candidate) {
212
+ return false;
213
+ }
214
+ return compileAllowedIps(allowedIps).some((rule) => (
215
+ candidate.version === rule.version &&
216
+ bytesMatchPrefix(candidate.bytes, rule.bytes, rule.prefix)
217
+ ));
218
+ }
219
+
220
+ function sendJson(res, statusCode, payload, headers = {}) {
221
+ const body = JSON.stringify(payload);
222
+ res.writeHead(statusCode, {
223
+ ...SECURITY_HEADERS,
224
+ ...headers,
225
+ 'Content-Type': 'application/json; charset=utf-8',
226
+ 'Content-Length': Buffer.byteLength(body)
227
+ });
228
+ res.end(body);
229
+ }
230
+ function tokensMatch(provided, expected) {
231
+ const providedDigest = crypto.createHash('sha256').update(provided, 'utf8').digest();
232
+ const expectedDigest = crypto.createHash('sha256').update(expected, 'utf8').digest();
233
+ return crypto.timingSafeEqual(providedDigest, expectedDigest);
234
+ }
235
+ function isLoopbackAddress(value) {
236
+ const candidate = normalizeIp(parseIp(value));
237
+ if (!candidate) {
238
+ return false;
239
+ }
240
+ if (candidate.version === 4) {
241
+ return candidate.bytes[0] === 127;
242
+ }
243
+ return candidate.bytes.every((byte, index) => (index === 15 ? byte === 1 : byte === 0));
244
+ }
245
+
246
+
247
+ function getBearerToken(req) {
248
+ const headers = req && req.headers;
249
+ const authorization = headers && headers.authorization;
250
+ if (typeof authorization !== 'string') {
251
+ return null;
252
+ }
253
+ const match = /^Bearer[ \t]+(.+)$/i.exec(authorization.trim());
254
+ if (!match || /\s/.test(match[1])) {
255
+ return null;
256
+ }
257
+ return match[1];
258
+ }
259
+
260
+ function createHttpAccessControlMiddleware(options = {}) {
261
+ const requiresToken = typeof options.requiresToken === 'function'
262
+ ? options.requiresToken
263
+ : () => true;
264
+ const bypassLoopback = options.bypassLoopback === true;
265
+ const token = typeof options.token === 'string' ? options.token.trim() : '';
266
+ const allowedRules = compileAllowedIps(options.allowedIps);
267
+
268
+ return (req, res, next) => {
269
+ if (allowedRules.length > 0) {
270
+ const remoteAddress = req && req.socket && req.socket.remoteAddress;
271
+ const candidate = normalizeIp(parseIp(remoteAddress));
272
+ const allowed = candidate && allowedRules.some((rule) => (
273
+ candidate.version === rule.version &&
274
+ bytesMatchPrefix(candidate.bytes, rule.bytes, rule.prefix)
275
+ ));
276
+ if (!allowed) {
277
+ sendJson(res, 403, { error: 'Forbidden' });
278
+ return;
279
+ }
280
+ }
281
+
282
+ const remoteAddress = req && req.socket && req.socket.remoteAddress;
283
+ const loopbackPeer = bypassLoopback && isLoopbackAddress(remoteAddress);
284
+ if (token && !loopbackPeer && requiresToken(req)) {
285
+ const provided = getBearerToken(req);
286
+ if (!provided || !tokensMatch(provided, token)) {
287
+ sendJson(res, 401, { error: 'Unauthorized' }, {
288
+ 'WWW-Authenticate': `Bearer realm="${AUTH_REALM}"`
289
+ });
290
+ return;
291
+ }
292
+ }
293
+
294
+ next();
295
+ };
296
+ }
297
+
298
+ function isLoopbackHost(host) {
299
+ if (typeof host !== 'string') {
300
+ return false;
301
+ }
302
+ let value = host.trim().toLowerCase();
303
+ if (!value) {
304
+ return false;
305
+ }
306
+ if (value.startsWith('[') && value.endsWith(']')) {
307
+ value = value.slice(1, -1);
308
+ }
309
+ if (value === 'localhost' || value === 'localhost.') {
310
+ return true;
311
+ }
312
+ const ip = normalizeIp(parseIp(value));
313
+ if (!ip) {
314
+ return false;
315
+ }
316
+ if (ip.version === 4) {
317
+ return ip.bytes[0] === 127;
318
+ }
319
+ return ip.bytes.every((byte, index) => (index === 15 ? byte === 1 : byte === 0));
320
+ }
321
+
322
+ function assertExternalTokenConfigured(host, token) {
323
+ const normalizedToken = typeof token === 'string' ? token.trim() : '';
324
+ if (!isLoopbackHost(host) && !normalizedToken) {
325
+ throw new Error('对外监听必须设置 CODEXMATE_HTTP_TOKEN');
326
+ }
327
+ }
328
+
329
+ module.exports = {
330
+ createHttpAccessControlMiddleware,
331
+ parseAllowedIps,
332
+ isIpAllowed,
333
+ isLoopbackHost,
334
+ assertExternalTokenConfigured
335
+ };
@@ -0,0 +1,130 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+ const crypto = require('crypto');
5
+ const { deliver } = require('./handoff-mcp');
6
+
7
+ function threadDirectory(threadId, options = {}) {
8
+ if (typeof threadId !== 'string' || !threadId.trim()) throw new Error('缺少 threadId');
9
+ const key = crypto.createHash('sha256').update(threadId).digest('hex');
10
+ return path.join(options.root || path.join(os.homedir(), '.codexmate', 'threads'), key);
11
+ }
12
+
13
+ function appendEvent(threadId, event, options) {
14
+ const directory = threadDirectory(threadId, options);
15
+ fs.mkdirSync(directory, { recursive: true });
16
+ fs.appendFileSync(path.join(directory, 'handoffs.jsonl'), JSON.stringify({ ...event, eventAt: new Date().toISOString() }) + '\n', { mode: 0o600 });
17
+ }
18
+
19
+ function listHandoffs(threadId, options) {
20
+ const file = path.join(threadDirectory(threadId, options), 'handoffs.jsonl');
21
+ if (!fs.existsSync(file)) return [];
22
+ const records = new Map();
23
+ for (const line of fs.readFileSync(file, 'utf8').split('\n').filter(Boolean)) {
24
+ const event = JSON.parse(line);
25
+ records.set(event.id, { ...(records.get(event.id) || {}), ...event });
26
+ }
27
+ return Array.from(records.values()).reverse();
28
+ }
29
+
30
+ function requireRecord(params, options) {
31
+ const record = listHandoffs(params.threadId, options).find(item => item.id === params.handoffId);
32
+ if (!record) throw new Error('未找到交接记录');
33
+ return record;
34
+ }
35
+
36
+ function validateCard(card) {
37
+ if (!card || typeof card.goal !== 'string' || !card.goal.trim()) throw new Error('交接卡缺少 goal');
38
+ for (const field of ['completed', 'blockers', 'nextSteps', 'files']) {
39
+ if (!Array.isArray(card[field]) || card[field].some(value => typeof value !== 'string')) {
40
+ throw new Error(`交接卡 ${field} 必须为字符串数组`);
41
+ }
42
+ }
43
+ return Object.fromEntries(['goal', 'completed', 'blockers', 'nextSteps', 'files'].map(key => [key, card[key]]));
44
+ }
45
+
46
+ function resultMessage(record) {
47
+ if (record.route === 'mcp') return `已写入 MCP ${record.mcp.server};等待目标 Agent 读取确认。文件回退:${record.filePath}`;
48
+ return `已走文件级路径:${record.filePath};${record.reason || '已手动回退'}。尚未确认目标读取。`;
49
+ }
50
+
51
+ async function createHandoff(params, options = {}) {
52
+ const directory = threadDirectory(params.threadId, options);
53
+ if (typeof params.target !== 'string' || !params.target.trim()) throw new Error('缺少目标 Agent');
54
+ const card = validateCard(params.card);
55
+ const id = crypto.randomBytes(16).toString('hex');
56
+ const createdAt = new Date().toISOString();
57
+ const handoff = { id, threadId: params.threadId, target: params.target, createdAt, card,
58
+ acknowledgement: { command: `codexmate thread ack ${params.threadId} --handoff ${id} --agent ${params.target} --evidence <读取证据>`,
59
+ instruction: '目标 Agent 实际读取本卡后,使用原始 threadId、id、target 调用 thread ack;evidence 填写目标会话或检索记录标识。此确认为目标自报,非自动验证。' } };
60
+ fs.mkdirSync(directory, { recursive: true });
61
+ const filePath = path.join(directory, `${id}.json`);
62
+ fs.writeFileSync(filePath, JSON.stringify(handoff, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
63
+ let record = { id, threadId: params.threadId, target: params.target, createdAt, filePath,
64
+ route: 'file', status: 'file_ready', mcp: null, durationMs: 0, fallback: false,
65
+ reason: 'MCP 探测进行中;文件已就绪', readConfirmation: null, event: 'created' };
66
+ appendEvent(params.threadId, record, options);
67
+ const delivery = await deliver(handoff, { ...options, ...(params.cwd ? { cwd: path.resolve(params.cwd) } : {}) });
68
+ record = { ...record, route: delivery.ok ? 'mcp' : 'file',
69
+ status: delivery.ok ? 'awaiting_read' : 'file_ready', mcp: delivery.mcp,
70
+ durationMs: delivery.durationMs, writeDurationMs: delivery.writeDurationMs, discoveryWarnings: delivery.discoveryWarnings,
71
+ writeResult: delivery.ok ? 'written' : delivery.stage === 'tools/call' ? 'failed_or_unconfirmed' : 'not_attempted',
72
+ fallback: !delivery.ok, reason: delivery.reason, stage: delivery.stage, event: 'delivery' };
73
+ appendEvent(params.threadId, record, options);
74
+ return { record, message: resultMessage(record) };
75
+ }
76
+
77
+ function fallbackHandoff(params, options) {
78
+ const record = requireRecord(params, options);
79
+ const text = fs.readFileSync(record.filePath, 'utf8');
80
+ const updated = { id: record.id, route: 'file', fallback: true,
81
+ status: record.readConfirmation ? 'read_confirmed' : 'file_ready', event: 'manual_fallback',
82
+ reason: '用户选择文件级注入' };
83
+ appendEvent(params.threadId, updated, options);
84
+ return { record: { ...record, ...updated }, text, message: '已切换文件路径;请将交接卡注入目标 Agent,未据此确认读取。' };
85
+ }
86
+
87
+ function acknowledgeHandoff(params, options) {
88
+ const record = requireRecord(params, options);
89
+ if (params.agent !== record.target) throw new Error('确认 Agent 与目标不匹配');
90
+ if (typeof params.evidence !== 'string' || !params.evidence.trim()) throw new Error('读取确认需要会话或检索记录证据');
91
+ const updated = { id: record.id, status: 'read_confirmed', event: 'read_acknowledged',
92
+ readConfirmation: { agent: params.agent, evidence: params.evidence, at: new Date().toISOString(), source: 'target_reported' } };
93
+ appendEvent(params.threadId, updated, options);
94
+ return { record: { ...record, ...updated }, message: '已记录目标自报读取确认;证据已归档。' };
95
+ }
96
+
97
+ async function handleThreadAction(action, params, options) {
98
+ if (action === 'thread-handoff-list') return { records: listHandoffs(params.threadId, options) };
99
+ if (action === 'thread-handoff-create') return createHandoff(params, options);
100
+ if (action === 'thread-handoff-fallback') return fallbackHandoff(params, options);
101
+ if (action === 'thread-handoff-ack') return acknowledgeHandoff(params, options);
102
+ throw new Error('未知交接操作');
103
+ }
104
+
105
+ async function cmdThread(args) {
106
+ const [operation, threadId, ...flags] = args;
107
+ if (!operation || operation === '--help' || operation === '-h') {
108
+ console.log('用法:codexmate thread handoff <thread-id> --card <json-file> --target <agent>\n'
109
+ + ' codexmate thread list <thread-id>\n'
110
+ + ' codexmate thread fallback <thread-id> --handoff <id>\n'
111
+ + ' codexmate thread ack <thread-id> --handoff <id> --agent <agent> --evidence <读取证据>');
112
+ return;
113
+ }
114
+ const params = { threadId };
115
+ const names = { '--card': 'cardFile', '--target': 'target', '--handoff': 'handoffId', '--agent': 'agent', '--evidence': 'evidence' };
116
+ for (let i = 0; i < flags.length; i += 2) {
117
+ if (!names[flags[i]] || !flags[i + 1] || flags[i + 1].startsWith('--')) throw new Error('交接命令参数无效');
118
+ params[names[flags[i]]] = flags[i + 1];
119
+ }
120
+ const actions = { handoff: 'create', list: 'list', fallback: 'fallback', ack: 'ack' };
121
+ if (!actions[operation]) throw new Error('未知 thread 子命令');
122
+ if (operation === 'handoff') {
123
+ if (!params.cardFile) throw new Error('请用 --card 指定结构化交接卡 JSON 文件');
124
+ params.card = JSON.parse(fs.readFileSync(path.resolve(params.cardFile), 'utf8'));
125
+ }
126
+ const result = await handleThreadAction(`thread-handoff-${actions[operation]}`, params);
127
+ console.log(JSON.stringify(result, null, 2));
128
+ }
129
+
130
+ module.exports = { createHandoff, listHandoffs, fallbackHandoff, acknowledgeHandoff, handleThreadAction, cmdThread };
@@ -0,0 +1,49 @@
1
+ 'use strict';
2
+ const crypto = require('crypto');
3
+ const TOKEN_BYTES = 32;
4
+
5
+ function equalToken(actual, expected) {
6
+ const digest = value => crypto.createHash('sha256').update(value).digest();
7
+ return typeof actual === 'string' && crypto.timingSafeEqual(digest(actual), digest(expected));
8
+ }
9
+
10
+ function createStartupAuth(configuredToken = '') {
11
+ const token = configuredToken.trim() || crypto.randomBytes(TOKEN_BYTES).toString('hex');
12
+ function respond(res, status, body, headers = {}) {
13
+ res.writeHead(status, { 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer',
14
+ 'X-Content-Type-Options': 'nosniff', ...headers });
15
+ res.end(body);
16
+ }
17
+ function requestToken(req) {
18
+ const headers = req.headers || {};
19
+ const bearer = /^Bearer\s+(.+)$/i.exec(headers.authorization || '');
20
+ if (bearer) return bearer[1].trim();
21
+ try {
22
+ return new URL(req.url || '/', 'http://localhost').searchParams.get('token') || '';
23
+ } catch (_) {
24
+ return '';
25
+ }
26
+ }
27
+ function authorized(req) {
28
+ const provided = requestToken(req);
29
+ return !!provided && equalToken(provided, token);
30
+ }
31
+ function middleware(req, res, next) {
32
+ const pathname = String(req.url || '/').split('?')[0];
33
+ if (pathname.startsWith('/web-ui/') || pathname.startsWith('/res/') || pathname.startsWith('/bridge/')) { next(); return; }
34
+ const headers = req.headers || {};
35
+ if (headers['sec-fetch-site'] === 'cross-site') {
36
+ respond(res, 403, '跨站访问已拒绝');
37
+ return;
38
+ }
39
+ if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method) && headers.origin) {
40
+ const expectedOrigin = `http://${headers.host}`;
41
+ if (headers.origin !== expectedOrigin) { respond(res, 403, '请求来源不匹配'); return; }
42
+ }
43
+ if (authorized(req)) { next(); return; }
44
+ respond(res, 401, JSON.stringify({ error: 'Unauthorized' }), {
45
+ 'Content-Type': 'application/json; charset=utf-8', 'WWW-Authenticate': 'Bearer realm="codexmate"' });
46
+ }
47
+ return { token, middleware, authorized };
48
+ }
49
+ module.exports = { createStartupAuth };