feat(workshop): 💻 콘솔 탭 — 프로젝트 폴더에서 Claude Code(claude)·셸을 웹 터미널로. pty_spawn에 workshopProjectId(서버가 경로 해석, 탈출 거부)·autorun 허용목록(claude만) 추가, 기존 관리자+Origin 가드 그대로

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5.5 committed 2026-10-02 14:14:54 +09:00
1 parent ffc32d0321
commit 068bc92e33
7 files changed
+203 -3

No files matched your search

+20
View File
@@ -24,3 +24,23 @@ export function ptyAccessDecision(input: PtyAccessInput): { allowed: true } | {
} catch { return { allowed: false, reason: 'Origin 형식이 잘못되었습니다.' }; }
return { allowed: true };
}
// 작업실 콘솔(2026-10-02): pty_spawn 이 workshopProjectId 를 주면 그 프로젝트 폴더(workspace/workshop/<id>)에서 시작한다.
// 클라이언트가 임의 경로를 보내지 않게 서버가 id로부터 경로를 만들고, id는 영숫자·밑줄·하이픈만 허용하며 결과가
// 반드시 workspace/workshop 아래인지 다시 확인한다. 폴더가 없으면 null(호출자가 기본 경로로 폴백).
import path from 'path';
import fs from 'fs';
export function resolveWorkshopCwd(workspace: string | undefined, projectId: unknown): string | null {
if (!workspace || typeof projectId !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(projectId)) return null;
const root = path.resolve(workspace, 'workshop');
const dir = path.resolve(root, projectId);
if (dir !== path.join(root, projectId) || !dir.startsWith(root + path.sep)) return null;
try { return fs.statSync(dir).isDirectory() ? dir : null; } catch { return null; }
}
// pty_spawn 에서 자동 실행을 허용하는 명령 — 허용 목록에 있는 것만(임의 명령 주입 방지).
export function allowedAutorun(v: unknown): string | null {
return v === 'claude' ? 'claude' : null;
}
+8 -3
View File
@@ -60,7 +60,7 @@ import { registerScheduleRoutes } from './routes/routes-schedules';
import { registerSkillsRoutes } from './routes/routes-skills';
import { registerCodeRoutes } from './routes/routes-code';
import { registerClaudeFsRoutes } from './routes/routes-claude-fs';
import { ptyAccessDecision } from './pty-guard';
import { ptyAccessDecision, resolveWorkshopCwd, allowedAutorun } from './pty-guard';
import { registerTaskRoutes } from './routes/routes-tasks';
import { registerAgentRoutes } from './routes/routes-agents';
import { registerChannelsRoutes } from './routes/routes-channels';
@@ -4760,15 +4760,20 @@ wss.on('connection', (ws: WebSocket, req: http.IncomingMessage) => {
const ptyModule = await ptyImport;
if (!ptyModule) { ws.send(JSON.stringify({ type: 'pty_error', shellId, error: 'node-pty not available' })); return; }
const pty = (ptyModule as any).default || ptyModule;
// 작업실 콘솔: workshopProjectId 가 있으면 서버가 그 프로젝트 폴더를 해석해 시작 위치로 쓴다(클라이언트 경로 불신).
const wsCwd = resolveWorkshopCwd(user?.workspace, msg.workshopProjectId);
const proc = pty.spawn(process.env.SHELL || '/bin/bash', [], {
name: 'xterm-256color',
cols: msg.cols || 120,
rows: msg.rows || 30,
cwd: msg.cwd || user?.workspace || process.cwd(),
cwd: wsCwd || msg.cwd || user?.workspace || process.cwd(),
env: { ...process.env, TERM: 'xterm-256color' } as any,
});
ptySessions.set(shellId, proc);
console.log(`[pty] open user=${user?.username} shell=${shellId} pid=${proc.pid}`);
console.log(`[pty] open user=${user?.username} shell=${shellId} pid=${proc.pid}${wsCwd ? ` workshop=${msg.workshopProjectId}` : ''}`);
// 허용 목록의 명령만 셸이 뜬 직후 입력해 준다(claude 가 끝나면 셸로 돌아온다).
const auto = allowedAutorun(msg.autorun);
if (auto) setTimeout(() => { try { proc.write(auto + '\r'); } catch {} }, 500);
proc.onData((data: string) => {
try { ws.send(JSON.stringify({ type: 'pty_output', shellId, data })); } catch {}
});
+46
View File
@@ -0,0 +1,46 @@
/**
* 작업실 콘솔 — pty_spawn 시작 폴더 해석(resolveWorkshopCwd)과 자동 실행 허용 목록(allowedAutorun)
* 클라이언트가 보낸 projectId로 서버가 경로를 만들고, 경로 탈출·임의 명령은 거부해야 한다.
*/
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { resolveWorkshopCwd, allowedAutorun } from '../src/gateway/pty-guard';
describe('resolveWorkshopCwd', () => {
const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'wscwd-'));
fs.mkdirSync(path.join(ws, 'workshop', 'proj_abc'), { recursive: true });
fs.writeFileSync(path.join(ws, 'workshop', 'a_file'), 'x');
test('있는 프로젝트 폴더는 그 절대 경로를 돌려준다', () => {
assert.equal(resolveWorkshopCwd(ws, 'proj_abc'), path.join(ws, 'workshop', 'proj_abc'));
});
test('없는 폴더·파일은 null (호출자가 기본 경로로 폴백)', () => {
assert.equal(resolveWorkshopCwd(ws, 'proj_none'), null);
assert.equal(resolveWorkshopCwd(ws, 'a_file'), null);
});
test('경로 탈출 시도는 모두 거부한다', () => {
for (const bad of ['..', '../..', '../../etc', 'proj_abc/../..', '/etc', 'proj_abc/x', '', '.', 'a b', 'x\0y']) {
assert.equal(resolveWorkshopCwd(ws, bad), null, JSON.stringify(bad));
}
});
test('문자열이 아니거나 workspace가 없으면 null', () => {
assert.equal(resolveWorkshopCwd(ws, undefined), null);
assert.equal(resolveWorkshopCwd(ws, 123), null);
assert.equal(resolveWorkshopCwd(ws, { a: 1 }), null);
assert.equal(resolveWorkshopCwd(undefined, 'proj_abc'), null);
});
});
describe('allowedAutorun', () => {
test('claude만 허용한다', () => {
assert.equal(allowedAutorun('claude'), 'claude');
});
test('그 밖의 명령·주입 시도는 모두 null', () => {
for (const bad of ['rm -rf /', 'claude; id', 'claude && ls', 'bash', '', undefined, 1, ['claude']]) {
assert.equal(allowedAutorun(bad), null, JSON.stringify(bad));
}
});
});
+7
View File
@@ -299,3 +299,10 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
.rb-cam-ctl label{display:flex;align-items:center;gap:6px;cursor:pointer;}
.rb-cam-btns{display:flex;gap:6px;flex-wrap:wrap;}
.rb-msg .rb-cam-shot{display:block;max-width:140px;border-radius:6px;margin-bottom:4px;}
/* 콘솔 탭(2026-10-02) */
.rb-console-bar{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:6px;}
.rb-console-proj{font-size:12px;color:var(--text);font-weight:600;margin-right:4px;}
.rb-console-status{font-size:11px;color:var(--muted);margin-left:4px;}
.rb-console-warn{font-size:11px;color:#f59e0b;margin-bottom:6px;}
#console-term{height:min(62vh,640px);min-height:320px;background:#0d1117;border:1px solid var(--line);border-radius:8px;padding:6px;overflow:hidden;}
+12
View File
@@ -59,6 +59,7 @@
<button class="rb-tab-btn" data-tab="files" onclick="switchTab('files')">파일</button>
<button class="rb-tab-btn" data-tab="overview" onclick="switchTab('overview')">개요</button>
<button class="rb-tab-btn" data-tab="notes" onclick="switchTab('notes')">메모</button>
<button class="rb-tab-btn" data-tab="console" onclick="switchTab('console')" title="이 프로젝트 폴더에서 Claude Code·셸 실행(관리자 전용)">💻 콘솔</button>
</div>
<div class="rb-body">
@@ -140,6 +141,17 @@
<textarea class="rb-notes" id="overview-textarea" placeholder="프로젝트 개요 — 무엇을 만드는지/목표/구성. 채팅에서 '개요 써줘'로도 쓸 수 있다." oninput="onOverviewChange()"></textarea>
</div>
<div class="rb-pane" id="pane-console">
<div class="rb-console-bar">
<span id="console-proj" class="rb-console-proj"></span>
<button class="hdr-btn" onclick="consoleStart('claude')">▶ claude 시작</button>
<button class="hdr-btn" onclick="consoleStart('shell')">🐚 셸</button>
<button class="hdr-btn" onclick="consoleStop()">■ 종료</button>
<span id="console-status" class="rb-console-status"></span>
</div>
<div class="rb-console-warn">⚠ 서버 전체에 접근하는 터미널입니다(관리자 로그인 + 같은 주소에서만 열림). Claude Code의 권한 확인 질문에는 신중히 답하세요.</div>
<div id="console-term"></div>
</div>
<div class="rb-pane" id="pane-notes">
<textarea class="rb-notes" id="notes-textarea" placeholder="자유 메모..." oninput="onNotesChange()"></textarea>
</div>
+106
View File
@@ -0,0 +1,106 @@
// 작업실 콘솔 탭(2026-10-02) — 프로젝트 폴더에서 Claude Code(`claude`)나 셸을 웹 터미널로 쓴다.
// 서버의 기존 PTY 웹소켓(/ws, pty_*)을 그대로 쓰며, 서버가 workshopProjectId로 시작 폴더를 정하고(경로를 클라이언트가 못 정함)
// autorun은 'claude'만 허용한다. 터미널은 로그인한 관리자 + 같은 Origin만(pty-guard.ts) — 아니면 pty_error가 온다.
// classic script — 작업실 전역(currentProject, authH …)을 공유한다. 처음 콘솔 탭을 열 때만 로드된다(switchTab → withLazyModule).
let consoleWs = null, consoleTerm = null, consoleFit = null;
let consoleShellId = null, consoleProjId = null, consoleOpen = false;
function consoleLoadScript(src) {
return new Promise((resolve, reject) => {
if ([...document.scripts].some(s => s.src.endsWith(src))) return resolve();
const s = document.createElement('script'); s.src = src; s.onload = resolve; s.onerror = () => reject(new Error(src + ' 로드 실패'));
document.head.appendChild(s);
});
}
async function consoleEnsureXterm() {
if (!document.getElementById('xterm-css')) {
const l = document.createElement('link'); l.id = 'xterm-css'; l.rel = 'stylesheet'; l.href = '/vendor/xterm.css'; document.head.appendChild(l);
}
if (typeof Terminal === 'undefined') await consoleLoadScript('/vendor/xterm.js');
if (typeof FitAddon === 'undefined') await consoleLoadScript('/vendor/addon-fit.js');
}
function consoleStatus(text, color) {
const el = document.getElementById('console-status');
if (el) { el.textContent = text; el.style.color = color || 'var(--muted)'; }
}
function consoleCookie(name) {
const m = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
return m ? decodeURIComponent(m[1]) : '';
}
function consoleWsConnect() {
return new Promise((resolve, reject) => {
if (consoleWs && consoleWs.readyState === WebSocket.OPEN) return resolve();
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
let url = `${proto}//${location.host}/ws`;
let token = ''; try { token = sessionStorage.getItem('smallclaw_token') || ''; } catch {}
token = token || consoleCookie('smallclaw_session');
if (token) url += `?token=${encodeURIComponent(token)}`;
const ws = new WebSocket(url);
ws.onopen = () => { consoleWs = ws; resolve(); };
ws.onerror = () => reject(new Error('웹소켓 연결 실패'));
ws.onclose = () => { if (consoleWs === ws) { consoleWs = null; if (consoleShellId) { consoleShellId = null; consoleStatus('연결이 끊어짐', '#ef4444'); } } };
ws.onmessage = ev => {
let m; try { m = JSON.parse(ev.data); } catch { return; }
if (!m.type || !m.type.startsWith('pty_') || m.shellId !== consoleShellId) return;
if (m.type === 'pty_output') consoleTerm.write(m.data);
else if (m.type === 'pty_exit') { consoleTerm.write('\r\n\x1b[90m[종료됨]\x1b[0m\r\n'); consoleShellId = null; consoleStatus('종료됨'); }
else if (m.type === 'pty_error') { consoleTerm.write('\r\n\x1b[31m터미널 오류: ' + (m.error || '?') + '\x1b[0m\r\n'); consoleShellId = null; consoleStatus('오류', '#ef4444'); }
};
});
}
function consoleSend(obj) { if (consoleWs && consoleWs.readyState === WebSocket.OPEN) consoleWs.send(JSON.stringify(obj)); }
// 콘솔 탭이 열릴 때(switchTab). 터미널 요소만 만들고 세션은 사용자가 시작 버튼을 눌러야 시작한다(실수로 claude가 뜨지 않게).
async function openConsole() {
consoleOpen = true;
const proj = currentProject();
document.getElementById('console-proj').textContent = proj ? '📁 ' + proj.name : '프로젝트 없음';
await consoleEnsureXterm();
if (!consoleTerm) {
consoleTerm = new Terminal({ fontSize: 13, cursorBlink: true, convertEol: false, scrollback: 5000,
fontFamily: "'D2Coding','IBM Plex Mono',monospace", theme: { background: '#0d1117' } });
consoleFit = new FitAddon.FitAddon();
consoleTerm.loadAddon(consoleFit);
consoleTerm.open(document.getElementById('console-term'));
consoleTerm.onData(d => { if (consoleShellId) consoleSend({ type: 'pty_input', shellId: consoleShellId, data: d }); });
consoleTerm.onResize(({ cols, rows }) => { if (consoleShellId) consoleSend({ type: 'pty_resize', shellId: consoleShellId, cols, rows }); });
window.addEventListener('resize', () => { if (consoleOpen) consoleRefit(); });
consoleTerm.write('\x1b[90m▶ claude 시작을 누르면 이 프로젝트 폴더에서 Claude Code가 실행됩니다.\x1b[0m\r\n');
}
consoleOnProjectChange(true);
setTimeout(consoleRefit, 50);
consoleTerm.focus();
}
function closeConsoleTab() { consoleOpen = false; } // 세션은 유지(탭만 숨김) — 다시 열면 이어서 쓴다
function consoleRefit() { try { if (consoleFit) consoleFit.fit(); } catch {} }
async function consoleStart(mode) {
const proj = currentProject();
if (!proj) { consoleStatus('프로젝트를 먼저 고르세요', '#ef4444'); return; }
await openConsole();
consoleStop(true);
try { await consoleWsConnect(); } catch (e) { consoleStatus(e.message, '#ef4444'); return; }
consoleProjId = proj.id;
consoleShellId = 'wsc_' + Date.now().toString(36);
consoleTerm.reset();
consoleRefit();
consoleSend({ type: 'pty_spawn', shellId: consoleShellId, cols: consoleTerm.cols, rows: consoleTerm.rows,
workshopProjectId: proj.id, ...(mode === 'claude' ? { autorun: 'claude' } : {}) });
consoleStatus((mode === 'claude' ? 'Claude Code' : '셸') + ' 실행 중 — ' + proj.name, '#22c55e');
consoleTerm.focus();
}
function consoleStop(silent) {
if (consoleShellId) { consoleSend({ type: 'pty_kill', shellId: consoleShellId }); consoleShellId = null; }
if (!silent) consoleStatus('종료됨');
}
// 프로젝트를 바꾸면 실행 중인 세션은 이전 프로젝트 폴더 기준이라 혼동되므로 종료하고 안내한다.
function consoleOnProjectChange(fromOpen) {
const proj = currentProject();
const lbl = document.getElementById('console-proj');
if (lbl) lbl.textContent = proj ? '📁 ' + proj.name : '프로젝트 없음';
if (consoleShellId && proj && consoleProjId && proj.id !== consoleProjId) {
consoleStop(true);
if (consoleTerm) consoleTerm.write('\r\n\x1b[33m[프로젝트가 바뀌어 세션을 종료했습니다 — 다시 시작하세요]\x1b[0m\r\n');
consoleStatus('프로젝트가 바뀌어 종료됨');
}
}
+4
View File
@@ -182,6 +182,7 @@ function switchProject(id){
syncLocalToProject();
workshopData.activeProjectId=id;
loadLocalFromProject();
if(typeof consoleOnProjectChange==='function')consoleOnProjectChange();
clearStlSelection();
refreshAllPanes();
scheduleSave();
@@ -472,6 +473,9 @@ function switchTab(tab){
else if(typeof stopEquipTimers==='function')stopEquipTimers();
if(tab==='files')loadFiles();
if(tab==='assembly')refreshAssemblyPane(true);
// 콘솔 탭(지연 로딩 workshop-console.js): 열 때 터미널 준비, 나갈 때는 세션을 유지한 채 숨김
if(tab==='console')withLazyModule('console','pane-console',()=>openConsole());
else if(typeof closeConsoleTab==='function')closeConsoleTab();
}
// ── 지연 로딩 모듈(2026-09-25) ────────────────────────────────────────────────