triflux 3.2.0-dev.12 → 3.2.0-dev.13

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/hub/bridge.mjs CHANGED
@@ -12,6 +12,16 @@ import { parseArgs as nodeParseArgs } from 'node:util';
12
12
  import { randomUUID } from 'node:crypto';
13
13
 
14
14
  const HUB_PID_FILE = join(homedir(), '.claude', 'cache', 'tfx-hub', 'hub.pid');
15
+ const HUB_TOKEN_FILE = join(homedir(), '.claude', '.tfx-hub-token');
16
+
17
+ // Hub 인증 토큰 읽기 (파일 없으면 null → 하위 호환)
18
+ function readHubToken() {
19
+ try {
20
+ return readFileSync(HUB_TOKEN_FILE, 'utf8').trim();
21
+ } catch {
22
+ return null;
23
+ }
24
+ }
15
25
 
16
26
  export function getHubUrl() {
17
27
  if (process.env.TFX_HUB_URL) return process.env.TFX_HUB_URL.replace(/\/mcp$/, '');
@@ -46,9 +56,15 @@ export async function post(path, body, timeoutMs = 5000) {
46
56
  const timer = setTimeout(() => controller.abort(), timeoutMs);
47
57
 
48
58
  try {
59
+ const headers = { 'Content-Type': 'application/json' };
60
+ const token = readHubToken();
61
+ if (token) {
62
+ headers['Authorization'] = `Bearer ${token}`;
63
+ }
64
+
49
65
  const res = await fetch(`${getHubUrl()}${path}`, {
50
66
  method: 'POST',
51
- headers: { 'Content-Type': 'application/json' },
67
+ headers,
52
68
  body: JSON.stringify(body),
53
69
  signal: controller.signal,
54
70
  });
@@ -316,7 +332,7 @@ async function cmdTeamInfo(args) {
316
332
  }
317
333
  // Hub 미실행 fallback — nativeProxy 직접 호출
318
334
  const { teamInfo } = await import('./team/nativeProxy.mjs');
319
- console.log(JSON.stringify(teamInfo(body)));
335
+ console.log(JSON.stringify(await teamInfo(body)));
320
336
  }
321
337
 
322
338
  async function cmdTeamTaskList(args) {
@@ -334,7 +350,7 @@ async function cmdTeamTaskList(args) {
334
350
  }
335
351
  // Hub 미실행 fallback — nativeProxy 직접 호출
336
352
  const { teamTaskList } = await import('./team/nativeProxy.mjs');
337
- console.log(JSON.stringify(teamTaskList(body)));
353
+ console.log(JSON.stringify(await teamTaskList(body)));
338
354
  }
339
355
 
340
356
  async function cmdTeamTaskUpdate(args) {
@@ -360,7 +376,7 @@ async function cmdTeamTaskUpdate(args) {
360
376
  }
361
377
  // Hub 미실행 fallback — nativeProxy 직접 호출
362
378
  const { teamTaskUpdate } = await import('./team/nativeProxy.mjs');
363
- console.log(JSON.stringify(teamTaskUpdate(body)));
379
+ console.log(JSON.stringify(await teamTaskUpdate(body)));
364
380
  }
365
381
 
366
382
  async function cmdTeamSendMessage(args) {
@@ -379,7 +395,7 @@ async function cmdTeamSendMessage(args) {
379
395
  }
380
396
  // Hub 미실행 fallback — nativeProxy 직접 호출
381
397
  const { teamSendMessage } = await import('./team/nativeProxy.mjs');
382
- console.log(JSON.stringify(teamSendMessage(body)));
398
+ console.log(JSON.stringify(await teamSendMessage(body)));
383
399
  }
384
400
 
385
401
  function getHubDbPath() {
package/hub/server.mjs CHANGED
@@ -52,6 +52,14 @@ async function parseBody(req) {
52
52
 
53
53
  const PID_DIR = join(homedir(), '.claude', 'cache', 'tfx-hub');
54
54
  const PID_FILE = join(PID_DIR, 'hub.pid');
55
+ const TOKEN_FILE = join(homedir(), '.claude', '.tfx-hub-token');
56
+
57
+ // localhost 계열 Origin만 허용
58
+ const ALLOWED_ORIGIN_RE = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/;
59
+
60
+ function isAllowedOrigin(origin) {
61
+ return origin && ALLOWED_ORIGIN_RE.test(origin);
62
+ }
55
63
 
56
64
  /**
57
65
  * tfx-hub 시작
@@ -66,6 +74,11 @@ export async function startHub({ port = 27888, dbPath, host = '127.0.0.1', sessi
66
74
  dbPath = join(PID_DIR, 'state.db');
67
75
  }
68
76
 
77
+ // 인증 토큰 생성 (환경변수 우선, 없으면 자동 생성)
78
+ const HUB_TOKEN = process.env.TFX_HUB_TOKEN || randomUUID();
79
+ mkdirSync(join(homedir(), '.claude'), { recursive: true });
80
+ writeFileSync(TOKEN_FILE, HUB_TOKEN, { mode: 0o600 });
81
+
69
82
  const store = createStore(dbPath);
70
83
  const router = createRouter(store);
71
84
  const pipe = createPipeServer({ router, store, sessionId });
@@ -109,12 +122,16 @@ export async function startHub({ port = 27888, dbPath, host = '127.0.0.1', sessi
109
122
  }
110
123
 
111
124
  const httpServer = createHttpServer(async (req, res) => {
112
- res.setHeader('Access-Control-Allow-Origin', '*');
113
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
114
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type, mcp-session-id, Last-Event-ID');
125
+ // CORS: localhost 계열 Origin 허용
126
+ const origin = req.headers['origin'];
127
+ if (isAllowedOrigin(origin)) {
128
+ res.setHeader('Access-Control-Allow-Origin', origin);
129
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
130
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, mcp-session-id, Last-Event-ID');
131
+ }
115
132
 
116
133
  if (req.method === 'OPTIONS') {
117
- res.writeHead(204);
134
+ res.writeHead(isAllowedOrigin(origin) ? 204 : 403);
118
135
  return res.end();
119
136
  }
120
137
 
@@ -141,6 +158,14 @@ export async function startHub({ port = 27888, dbPath, host = '127.0.0.1', sessi
141
158
  if (req.url.startsWith('/bridge')) {
142
159
  res.setHeader('Content-Type', 'application/json');
143
160
 
161
+ // Bearer 토큰 인증
162
+ const authHeader = req.headers['authorization'] || '';
163
+ const bearerToken = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : '';
164
+ if (bearerToken !== HUB_TOKEN) {
165
+ res.writeHead(401);
166
+ return res.end(JSON.stringify({ ok: false, error: 'Unauthorized' }));
167
+ }
168
+
144
169
  if (req.method !== 'POST' && req.method !== 'DELETE') {
145
170
  res.writeHead(405);
146
171
  return res.end(JSON.stringify({ ok: false, error: 'Method Not Allowed' }));
@@ -223,13 +248,13 @@ export async function startHub({ port = 27888, dbPath, host = '127.0.0.1', sessi
223
248
  if (req.method === 'POST') {
224
249
  let teamResult = null;
225
250
  if (path === '/bridge/team/info' || path === '/bridge/team-info') {
226
- teamResult = teamInfo(body);
251
+ teamResult = await teamInfo(body);
227
252
  } else if (path === '/bridge/team/task-list' || path === '/bridge/team-task-list') {
228
- teamResult = teamTaskList(body);
253
+ teamResult = await teamTaskList(body);
229
254
  } else if (path === '/bridge/team/task-update' || path === '/bridge/team-task-update') {
230
- teamResult = teamTaskUpdate(body);
255
+ teamResult = await teamTaskUpdate(body);
231
256
  } else if (path === '/bridge/team/send-message' || path === '/bridge/team-send-message') {
232
- teamResult = teamSendMessage(body);
257
+ teamResult = await teamSendMessage(body);
233
258
  }
234
259
 
235
260
  if (teamResult) {
@@ -452,6 +477,7 @@ export async function startHub({ port = 27888, dbPath, host = '127.0.0.1', sessi
452
477
  await pipe.stop();
453
478
  store.close();
454
479
  try { unlinkSync(PID_FILE); } catch {}
480
+ try { unlinkSync(TOKEN_FILE); } catch {}
455
481
  await new Promise((resolveClose) => httpServer.close(resolveClose));
456
482
  };
457
483
 
@@ -4,8 +4,6 @@
4
4
  import {
5
5
  existsSync,
6
6
  mkdirSync,
7
- readdirSync,
8
- readFileSync,
9
7
  renameSync,
10
8
  statSync,
11
9
  unlinkSync,
@@ -13,6 +11,7 @@ import {
13
11
  openSync,
14
12
  closeSync,
15
13
  } from 'node:fs';
14
+ import { readdir, stat, readFile } from 'node:fs/promises';
16
15
  import { basename, dirname, join } from 'node:path';
17
16
  import { homedir } from 'node:os';
18
17
  import { randomUUID } from 'node:crypto';
@@ -25,6 +24,7 @@ const TASKS_ROOT = join(CLAUDE_HOME, 'tasks');
25
24
  // ── 인메모리 캐시 (디렉토리 mtime 기반 무효화) ──
26
25
  const _dirCache = new Map(); // tasksDir → { mtimeMs, files: string[] }
27
26
  const _taskIdIndex = new Map(); // taskId → filePath
27
+ const _taskContentCache = new Map(); // filePath → { mtimeMs, data }
28
28
 
29
29
  function _invalidateCache(tasksDir) {
30
30
  _dirCache.delete(tasksDir);
@@ -40,9 +40,9 @@ function validateTeamName(teamName) {
40
40
  }
41
41
  }
42
42
 
43
- function readJsonSafe(path) {
43
+ async function readJsonSafe(path) {
44
44
  try {
45
- return JSON.parse(readFileSync(path, 'utf8'));
45
+ return JSON.parse(await readFile(path, 'utf8'));
46
46
  } catch {
47
47
  return null;
48
48
  }
@@ -66,12 +66,11 @@ function atomicWriteJson(path, value) {
66
66
  }
67
67
  }
68
68
 
69
- function sleepMs(ms) {
70
- // busy-wait를 피하고 Atomics.wait로 동기 대기 (CPU 점유 최소화)
71
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
69
+ async function sleepMs(ms) {
70
+ return new Promise((r) => setTimeout(r, ms));
72
71
  }
73
72
 
74
- function withFileLock(lockPath, fn, retries = 20, delayMs = 25) {
73
+ async function withFileLock(lockPath, fn, retries = 20, delayMs = 25) {
75
74
  let fd = null;
76
75
  for (let i = 0; i < retries; i += 1) {
77
76
  try {
@@ -79,12 +78,12 @@ function withFileLock(lockPath, fn, retries = 20, delayMs = 25) {
79
78
  break;
80
79
  } catch (e) {
81
80
  if (e?.code !== 'EEXIST' || i === retries - 1) throw e;
82
- sleepMs(delayMs);
81
+ await sleepMs(delayMs);
83
82
  }
84
83
  }
85
84
 
86
85
  try {
87
- return fn();
86
+ return await fn();
88
87
  } finally {
89
88
  try { if (fd != null) closeSync(fd); } catch {}
90
89
  try { unlinkSync(lockPath); } catch {}
@@ -99,13 +98,13 @@ function getLeadSessionId(config) {
99
98
  || null;
100
99
  }
101
100
 
102
- export function resolveTeamPaths(teamName) {
101
+ export async function resolveTeamPaths(teamName) {
103
102
  validateTeamName(teamName);
104
103
 
105
104
  const teamDir = join(TEAMS_ROOT, teamName);
106
105
  const configPath = join(teamDir, 'config.json');
107
106
  const inboxesDir = join(teamDir, 'inboxes');
108
- const config = readJsonSafe(configPath);
107
+ const config = await readJsonSafe(configPath);
109
108
  const leadSessionId = getLeadSessionId(config);
110
109
 
111
110
  const byTeam = join(TASKS_ROOT, teamName);
@@ -131,19 +130,20 @@ export function resolveTeamPaths(teamName) {
131
130
  };
132
131
  }
133
132
 
134
- function collectTaskFiles(tasksDir) {
133
+ async function collectTaskFiles(tasksDir) {
135
134
  if (!existsSync(tasksDir)) return [];
136
135
 
137
136
  // 디렉토리 mtime 기반 캐시 — O(N) I/O를 반복 호출 시 O(1)로 축소
138
137
  let dirMtime;
139
- try { dirMtime = statSync(tasksDir).mtimeMs; } catch { return []; }
138
+ try { dirMtime = (await stat(tasksDir)).mtimeMs; } catch { return []; }
140
139
 
141
140
  const cached = _dirCache.get(tasksDir);
142
141
  if (cached && cached.mtimeMs === dirMtime) {
143
142
  return cached.files;
144
143
  }
145
144
 
146
- const files = readdirSync(tasksDir)
145
+ const entries = await readdir(tasksDir);
146
+ const files = entries
147
147
  .filter((name) => name.endsWith('.json'))
148
148
  .filter((name) => !name.endsWith('.lock'))
149
149
  .filter((name) => name !== '.highwatermark')
@@ -153,7 +153,7 @@ function collectTaskFiles(tasksDir) {
153
153
  return files;
154
154
  }
155
155
 
156
- function locateTaskFile(tasksDir, taskId) {
156
+ async function locateTaskFile(tasksDir, taskId) {
157
157
  const direct = join(tasksDir, `${taskId}.json`);
158
158
  if (existsSync(direct)) return direct;
159
159
 
@@ -162,13 +162,13 @@ function locateTaskFile(tasksDir, taskId) {
162
162
  if (indexed && existsSync(indexed)) return indexed;
163
163
 
164
164
  // 캐시된 collectTaskFiles로 풀 스캔
165
- const files = collectTaskFiles(tasksDir);
165
+ const files = await collectTaskFiles(tasksDir);
166
166
  for (const file of files) {
167
167
  if (basename(file, '.json') === taskId) {
168
168
  _taskIdIndex.set(taskId, file);
169
169
  return file;
170
170
  }
171
- const json = readJsonSafe(file);
171
+ const json = await readJsonSafe(file);
172
172
  if (json && String(json.id || '') === taskId) {
173
173
  _taskIdIndex.set(taskId, file);
174
174
  return file;
@@ -181,7 +181,7 @@ function isObject(v) {
181
181
  return !!v && typeof v === 'object' && !Array.isArray(v);
182
182
  }
183
183
 
184
- export function teamInfo(args = {}) {
184
+ export async function teamInfo(args = {}) {
185
185
  const { team_name, include_members = true, include_paths = true } = args;
186
186
  try {
187
187
  validateTeamName(team_name);
@@ -189,7 +189,7 @@ export function teamInfo(args = {}) {
189
189
  return err('INVALID_TEAM_NAME', 'team_name 형식이 올바르지 않습니다');
190
190
  }
191
191
 
192
- const paths = resolveTeamPaths(team_name);
192
+ const paths = await resolveTeamPaths(team_name);
193
193
  if (!existsSync(paths.team_dir)) {
194
194
  return err('TEAM_NOT_FOUND', `팀 디렉토리가 없습니다: ${paths.team_dir}`);
195
195
  }
@@ -224,7 +224,7 @@ export function teamInfo(args = {}) {
224
224
  };
225
225
  }
226
226
 
227
- export function teamTaskList(args = {}) {
227
+ export async function teamTaskList(args = {}) {
228
228
  const {
229
229
  team_name,
230
230
  owner,
@@ -239,7 +239,7 @@ export function teamTaskList(args = {}) {
239
239
  return err('INVALID_TEAM_NAME', 'team_name 형식이 올바르지 않습니다');
240
240
  }
241
241
 
242
- const paths = resolveTeamPaths(team_name);
242
+ const paths = await resolveTeamPaths(team_name);
243
243
  if (paths.tasks_dir_resolution === 'not_found') {
244
244
  return err('TASKS_DIR_NOT_FOUND', `task 디렉토리를 찾지 못했습니다: ${team_name}`);
245
245
  }
@@ -249,8 +249,22 @@ export function teamTaskList(args = {}) {
249
249
  let parseWarnings = 0;
250
250
 
251
251
  const tasks = [];
252
- for (const file of collectTaskFiles(paths.tasks_dir)) {
253
- const json = readJsonSafe(file);
252
+ for (const file of await collectTaskFiles(paths.tasks_dir)) {
253
+ // mtime 기반 task 콘텐츠 캐시 — 변경 없으면 파일 읽기 생략
254
+ let fileMtime = Date.now();
255
+ try { fileMtime = (await stat(file)).mtimeMs; } catch {}
256
+
257
+ const contentCached = _taskContentCache.get(file);
258
+ let json;
259
+ if (contentCached && contentCached.mtimeMs === fileMtime) {
260
+ json = contentCached.data;
261
+ } else {
262
+ json = await readJsonSafe(file);
263
+ if (json && isObject(json)) {
264
+ _taskContentCache.set(file, { mtimeMs: fileMtime, data: json });
265
+ }
266
+ }
267
+
254
268
  if (!json || !isObject(json)) {
255
269
  parseWarnings += 1;
256
270
  continue;
@@ -260,13 +274,10 @@ export function teamTaskList(args = {}) {
260
274
  if (owner && String(json.owner || '') !== String(owner)) continue;
261
275
  if (statusSet.size > 0 && !statusSet.has(String(json.status || ''))) continue;
262
276
 
263
- let mtime = Date.now();
264
- try { mtime = statSync(file).mtimeMs; } catch {}
265
-
266
277
  tasks.push({
267
278
  ...json,
268
279
  task_file: file,
269
- mtime_ms: mtime,
280
+ mtime_ms: fileMtime,
270
281
  });
271
282
  }
272
283
 
@@ -288,7 +299,7 @@ export function teamTaskList(args = {}) {
288
299
  // status 화이트리스트 (Claude Code API 호환)
289
300
  const VALID_STATUSES = new Set(['pending', 'in_progress', 'completed', 'deleted']);
290
301
 
291
- export function teamTaskUpdate(args = {}) {
302
+ export async function teamTaskUpdate(args = {}) {
292
303
  // "failed" → "completed" + metadata.result 자동 매핑
293
304
  if (String(args.status || '') === 'failed') {
294
305
  args = {
@@ -326,12 +337,12 @@ export function teamTaskUpdate(args = {}) {
326
337
  return err('INVALID_TASK_ID', 'task_id가 필요합니다');
327
338
  }
328
339
 
329
- const paths = resolveTeamPaths(team_name);
340
+ const paths = await resolveTeamPaths(team_name);
330
341
  if (paths.tasks_dir_resolution === 'not_found') {
331
342
  return err('TASKS_DIR_NOT_FOUND', `task 디렉토리를 찾지 못했습니다: ${team_name}`);
332
343
  }
333
344
 
334
- const taskFile = locateTaskFile(paths.tasks_dir, String(task_id));
345
+ const taskFile = await locateTaskFile(paths.tasks_dir, String(task_id));
335
346
  if (!taskFile) {
336
347
  return err('TASK_NOT_FOUND', `task를 찾지 못했습니다: ${task_id}`);
337
348
  }
@@ -339,14 +350,14 @@ export function teamTaskUpdate(args = {}) {
339
350
  const lockFile = `${taskFile}.lock`;
340
351
 
341
352
  try {
342
- return withFileLock(lockFile, () => {
343
- const before = readJsonSafe(taskFile);
353
+ return await withFileLock(lockFile, async () => {
354
+ const before = await readJsonSafe(taskFile);
344
355
  if (!before || !isObject(before)) {
345
356
  return err('INVALID_TASK_FILE', `task 파일 파싱 실패: ${taskFile}`);
346
357
  }
347
358
 
348
359
  let beforeMtime = Date.now();
349
- try { beforeMtime = statSync(taskFile).mtimeMs; } catch {}
360
+ try { beforeMtime = (await stat(taskFile)).mtimeMs; } catch {}
350
361
 
351
362
  if (if_match_mtime_ms != null && Number(if_match_mtime_ms) !== Number(beforeMtime)) {
352
363
  return err('MTIME_CONFLICT', 'if_match_mtime_ms가 일치하지 않습니다', {
@@ -427,6 +438,8 @@ export function teamTaskUpdate(args = {}) {
427
438
  if (updated) {
428
439
  atomicWriteJson(taskFile, after);
429
440
  _invalidateCache(dirname(taskFile));
441
+ // 콘텐츠 캐시 무효화
442
+ _taskContentCache.delete(taskFile);
430
443
  }
431
444
 
432
445
  let afterMtime = beforeMtime;
@@ -453,7 +466,7 @@ function sanitizeRecipientName(v) {
453
466
  return String(v || 'team-lead').replace(/[\\/:*?"<>|]/g, '_');
454
467
  }
455
468
 
456
- export function teamSendMessage(args = {}) {
469
+ export async function teamSendMessage(args = {}) {
457
470
  const {
458
471
  team_name,
459
472
  from,
@@ -472,7 +485,7 @@ export function teamSendMessage(args = {}) {
472
485
  if (!String(from || '').trim()) return err('INVALID_FROM', 'from이 필요합니다');
473
486
  if (!String(text || '').trim()) return err('INVALID_TEXT', 'text가 필요합니다');
474
487
 
475
- const paths = resolveTeamPaths(team_name);
488
+ const paths = await resolveTeamPaths(team_name);
476
489
  if (!existsSync(paths.team_dir)) {
477
490
  return err('TEAM_NOT_FOUND', `팀 디렉토리가 없습니다: ${paths.team_dir}`);
478
491
  }
@@ -483,8 +496,8 @@ export function teamSendMessage(args = {}) {
483
496
  let message;
484
497
 
485
498
  try {
486
- const unreadCount = withFileLock(lockFile, () => {
487
- const queue = readJsonSafe(inboxFile);
499
+ const unreadCount = await withFileLock(lockFile, async () => {
500
+ const queue = await readJsonSafe(inboxFile);
488
501
  const list = Array.isArray(queue) ? queue : [];
489
502
 
490
503
  message = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "triflux",
3
- "version": "3.2.0-dev.12",
3
+ "version": "3.2.0-dev.13",
4
4
  "description": "CLI-first multi-model orchestrator for Claude Code — route tasks to Codex, Gemini, and Claude",
5
5
  "type": "module",
6
6
  "bin": {