diff --git a/src/gateway/pty-guard.ts b/src/gateway/pty-guard.ts new file mode 100644 index 0000000..2d0d8bb --- /dev/null +++ b/src/gateway/pty-guard.ts @@ -0,0 +1,26 @@ +// PTY(웹 터미널) 접근 판단 — /ws 소켓의 pty_* 메시지에 적용(2026-09-29). +// 예전엔 로그인하지 않은 연결도 pty_spawn 으로 서버 셸을 열 수 있었다(인증이 켜져 있어도 user=null 인 채 통과). +// 이제 (1) 로그인한 관리자만, (2) 브라우저 Origin 이 요청 Host 와 같을 때만 허용한다 — 다른 사이트가 로그인된 +// 브라우저로 소켓을 여는 것(CSWSH)도 막는다. +export interface PtyAccessInput { + user: { username?: string; role?: string } | null | undefined; + origin?: string | string[]; + host?: string | string[]; + /** 리버스 프록시(NPM 등)가 Host 를 바꿔 전달하는 경우를 위해 X-Forwarded-Host 도 비교 대상에 넣는다. */ + forwardedHost?: string | string[]; +} + +export function ptyAccessDecision(input: PtyAccessInput): { allowed: true } | { allowed: false; reason: string } { + const u = input.user; + if (!u || !u.username) return { allowed: false, reason: '로그인이 필요합니다.' }; + if (u.role !== 'admin') return { allowed: false, reason: '터미널은 관리자만 사용할 수 있습니다.' }; + const origin = String(Array.isArray(input.origin) ? input.origin[0] : (input.origin || '')); + const host = String(Array.isArray(input.host) ? input.host[0] : (input.host || '')); + if (!origin || !host) return { allowed: false, reason: 'Origin 헤더가 없습니다.' }; + const fwd = String(Array.isArray(input.forwardedHost) ? input.forwardedHost[0] : (input.forwardedHost || '')).split(',')[0].trim(); + try { + const oh = new URL(origin).host; + if (oh !== host && !(fwd && oh === fwd)) return { allowed: false, reason: '다른 사이트에서 연 연결입니다(Origin 불일치).' }; + } catch { return { allowed: false, reason: 'Origin 형식이 잘못되었습니다.' }; } + return { allowed: true }; +} diff --git a/src/gateway/routes/routes-claude-fs.ts b/src/gateway/routes/routes-claude-fs.ts new file mode 100644 index 0000000..cd3bee7 --- /dev/null +++ b/src/gateway/routes/routes-claude-fs.ts @@ -0,0 +1,162 @@ +import express from 'express'; +import fs from 'fs'; +import path from 'path'; +import { getConfig, getUserWorkspace } from '../../config/config'; + +// 클로드 앱 "서버 모드" 파일 API (2026-09-29). /api/code/*(고정 code/ 폴더)와 달리 작업 루트를 고를 수 있다. +// - 관리자(role=admin): 서버 어디든 루트로 지정 가능 — 단 아래 차단 규칙(시스템 디렉토리·비밀 파일)은 항상 적용. +// - 일반 사용자: 자기 워크스페이스 안만(점(.)으로 시작하는 하위 경로 제외). +// - root 를 비우면 예전처럼 사용자 워크스페이스의 code/ 폴더. +// 쓰기·읽기 모두 realpath 로 심볼릭 링크 탈출을 막고, 목록·읽기·쓰기 전부 같은 차단 규칙을 거친다. +// (셸 실행은 여기 없다 — 파일 읽기/쓰기/목록만.) + +const IGNORE_DIRS = new Set(['node_modules', '.git', 'dist', 'build', '__pycache__', 'venv', '.venv', '.next', 'target', '.cache', 'out']); +const MAX_LIST = 5000; +const MAX_READ = 2 * 1024 * 1024; +const MAX_WRITE = 10 * 1024 * 1024; +const DENY_ROOT_PREFIXES = ['/etc', '/proc', '/sys', '/dev', '/boot', '/root', '/run', '/usr', '/bin', '/sbin', '/lib', '/lib32', '/lib64', '/var/lib', '/var/log', '/snap']; +const SECRET_SEGMENT = /^\.(ssh|gnupg|aws|kube|docker|config|claude)$/i; +const SECRET_FILE = /^(\.env(\..*)?|\.git-credentials|\.netrc|authorized_keys|id_(rsa|dsa|ecdsa|ed25519)(\.pub)?|.*\.(pem|key|p12|pfx)|\.npmrc|\.pgpass|.*credentials.*|.*secret.*|.*_api_key\.txt|.*-key\.txt|.*token.*\.txt)$/i; + +function within(base: string, target: string): boolean { + return target === base || target.startsWith(base.endsWith(path.sep) ? base : base + path.sep); +} + +// 존재하는 가장 가까운 조상의 realpath + 나머지 — 아직 없는 파일 경로에도 심볼릭 링크 검사를 하기 위함. +function realResolve(p: string): string { + let cur = path.resolve(p); + const rest: string[] = []; + while (!fs.existsSync(cur)) { + const parent = path.dirname(cur); + if (parent === cur) break; + rest.unshift(path.basename(cur)); + cur = parent; + } + let real = cur; + try { real = fs.realpathSync(cur); } catch { /* keep */ } + return path.join(real, ...rest); +} + +export function isSecretOrSystemPath(abs: string, configDir: string): string | null { + const p = path.resolve(abs); + for (const d of DENY_ROOT_PREFIXES) if (within(d, p)) return '시스템 경로는 열 수 없습니다.'; + if (p === path.sep) return '루트(/)는 열 수 없습니다.'; + const cfg = path.resolve(configDir); + if (within(cfg, p)) { + // .smallclaw 안은 설정·키·vault·세션이 있어서 막고, 사용자/공용 워크스페이스만 허용한다. + const rel = path.relative(cfg, p).split(path.sep); + const ok = (rel[0] === 'users' && rel[2] === 'workspace') || rel[0] === 'workspace'; + if (!ok) return '.smallclaw 설정·키·세션 영역은 열 수 없습니다(사용자 워크스페이스만 가능).'; + } + const segs = p.split(path.sep).filter(Boolean); + if (segs.some(s => SECRET_SEGMENT.test(s))) return '비밀 설정 폴더(.ssh, .gnupg 등)는 열 수 없습니다.'; + if (SECRET_FILE.test(segs[segs.length - 1] || '')) return '비밀 키·토큰 파일은 열 수 없습니다.'; + return null; +} + +export function registerClaudeFsRoutes(app: express.Application): void { + function ctx(req: express.Request) { + const user = (req as any).user; + if (!user?.username) throw Object.assign(new Error('Unauthorized'), { status: 401 }); + const workspace = getUserWorkspace(user.username); + const configDir = getConfig().getConfigDir(); + const codeSub = (getConfig().getConfig() as any)?.workspace?.codeDir || 'code'; + return { user, admin: user.role === 'admin', workspace, configDir, codeDir: path.join(workspace, codeSub) }; + } + + // root 문자열 → 검증된 절대 경로(실제 존재하는 디렉토리). + function resolveRoot(req: express.Request, rootParam: string) { + const c = ctx(req); + const raw = String(rootParam || '').trim(); + let root: string; + if (!raw) { fs.mkdirSync(c.codeDir, { recursive: true }); root = c.codeDir; } + else root = path.isAbsolute(raw) ? path.resolve(raw) : path.resolve(c.workspace, raw); + let real: string; + try { real = fs.realpathSync(root); } catch { throw Object.assign(new Error(`폴더를 찾을 수 없습니다: ${root}`), { status: 404 }); } + if (!fs.statSync(real).isDirectory()) throw Object.assign(new Error('폴더가 아닙니다.'), { status: 400 }); + const blocked = isSecretOrSystemPath(real, c.configDir); + if (blocked) throw Object.assign(new Error(blocked), { status: 403 }); + if (!c.admin) { + const ws = fs.realpathSync(c.workspace); + if (!within(ws, real)) throw Object.assign(new Error('일반 사용자는 자기 워크스페이스 안만 열 수 있습니다.'), { status: 403 }); + if (path.relative(ws, real).split(path.sep).some(s => s.startsWith('.'))) throw Object.assign(new Error('점(.)으로 시작하는 폴더는 열 수 없습니다.'), { status: 403 }); + } + return { ...c, root: real }; + } + + function resolveTarget(root: string, name: string, configDir: string, admin: boolean): string { + const target = path.resolve(root, name); + if (!within(root, target)) throw Object.assign(new Error('Access denied'), { status: 403 }); + const real = realResolve(target); + if (!within(root, real)) throw Object.assign(new Error('Access denied (링크가 작업 폴더 밖을 가리킵니다)'), { status: 403 }); + const blocked = isSecretOrSystemPath(real, configDir); + if (blocked) throw Object.assign(new Error(blocked), { status: 403 }); + if (!admin && path.relative(root, real).split(path.sep).some(s => s.startsWith('.'))) throw Object.assign(new Error('점(.)으로 시작하는 경로는 열 수 없습니다.'), { status: 403 }); + return target; + } + + const fail = (res: express.Response, e: any) => res.status(e?.status || 500).json({ success: false, error: String(e?.message || e) }); + + // 작업 루트 정보 — 화면에 실제 경로를 보여주고 관리자 여부를 알려준다. + app.get('/api/claude-fs/info', (req, res) => { + try { + const r = resolveRoot(req, String(req.query.root || '')); + res.json({ success: true, root: r.root, admin: r.admin, defaultRoot: r.codeDir, workspace: r.workspace }); + } catch (e: any) { fail(res, e); } + }); + + app.get('/api/claude-fs/files', (req, res) => { + try { + const r = resolveRoot(req, String(req.query.root || '')); + const out: string[] = []; + let truncated = false; + const walk = (dir: string, base: string, depth: number) => { + if (depth > 12 || truncated) return; + let ents: fs.Dirent[]; + try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; } + for (const ent of ents) { + if (truncated) return; + if (ent.name.startsWith('.') || IGNORE_DIRS.has(ent.name)) continue; + if (ent.isSymbolicLink()) continue; + const rel = base ? `${base}/${ent.name}` : ent.name; + const abs = path.join(dir, ent.name); + if (isSecretOrSystemPath(abs, r.configDir)) continue; + if (ent.isDirectory()) walk(abs, rel, depth + 1); + else if (ent.isFile()) { if (out.length >= MAX_LIST) { truncated = true; return; } out.push(rel); } + } + }; + walk(r.root, '', 0); + res.json({ success: true, root: r.root, files: out, truncated }); + } catch (e: any) { fail(res, e); } + }); + + app.get('/api/claude-fs/file', (req, res) => { + try { + const name = String(req.query.name || ''); + if (!name) { res.status(400).json({ success: false, error: 'name required' }); return; } + const r = resolveRoot(req, String(req.query.root || '')); + const target = resolveTarget(r.root, name, r.configDir, r.admin); + if (!fs.existsSync(target) || !fs.statSync(target).isFile()) { res.status(404).json({ success: false, error: 'Not found' }); return; } + const st = fs.statSync(target); + if (st.size > MAX_READ) { res.status(413).json({ success: false, error: `파일이 너무 큽니다(${(st.size / 1024 / 1024).toFixed(1)}MB > 2MB)` }); return; } + res.json({ success: true, content: fs.readFileSync(target, 'utf-8'), path: name }); + } catch (e: any) { fail(res, e); } + }); + + app.post('/api/claude-fs/save', (req, res) => { + try { + const { filename, content, root: rootParam } = req.body || {}; + if (!filename || typeof filename !== 'string') { res.status(400).json({ success: false, error: 'filename required' }); return; } + const text = typeof content === 'string' ? content : ''; + if (Buffer.byteLength(text, 'utf-8') > MAX_WRITE) { res.status(413).json({ success: false, error: '내용이 너무 큽니다(>10MB)' }); return; } + const r = resolveRoot(req, String(rootParam || '')); + const target = resolveTarget(r.root, filename, r.configDir, r.admin); + fs.mkdirSync(path.dirname(target), { recursive: true }); + // mkdir 이후 다시 검사 — 방금 만든 상위 경로가 링크를 통해 밖으로 나가지 않는지. + resolveTarget(r.root, filename, r.configDir, r.admin); + fs.writeFileSync(target, text, 'utf-8'); + console.log(`[claude-fs] ${r.user.username}${r.admin ? '(admin)' : ''} write ${target} (${Buffer.byteLength(text, 'utf-8')}B)`); + res.json({ success: true, path: path.relative(r.root, target).split(path.sep).join('/'), size: Buffer.byteLength(text, 'utf-8') }); + } catch (e: any) { fail(res, e); } + }); +} diff --git a/src/gateway/server.ts b/src/gateway/server.ts index 171ef81..9bd8371 100644 --- a/src/gateway/server.ts +++ b/src/gateway/server.ts @@ -58,6 +58,8 @@ import { registerKakaoRoutes } from './routes/routes-kakao'; 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 { registerTaskRoutes } from './routes/routes-tasks'; import { registerAgentRoutes } from './routes/routes-agents'; import { registerChannelsRoutes } from './routes/routes-channels'; @@ -2699,6 +2701,19 @@ app.use('/vendor', express.static(path.join(webUiPath, 'vendor'), { })); // AudioMass — pure JS audio editor, no COOP/COEP needed +// 서버에 설치된 D2Coding(고정폭 한글 코딩 글꼴)을 원격 브라우저에도 그대로 내려준다(2026-09-29) — 콘솔이 서버 화면과 +// 같은 글꼴로 보이게. 허용 목록의 파일만(경로 조작 불가). 글꼴은 SIL OFL 이라 재배포 가능, 저장소에는 넣지 않는다. +const SERVER_FONTS: Record = { + 'D2Coding-Regular.ttf': '/usr/share/fonts/truetype/nanum/D2Coding-Ver1.3.2-20180524-ligature.ttf', + 'D2Coding-Bold.ttf': '/usr/share/fonts/truetype/nanum/D2CodingBold-Ver1.3.2-20180524-ligature.ttf', +}; +app.get('/fonts-srv/:name', (req, res) => { + const f = SERVER_FONTS[String(req.params.name)]; + if (!f || !fs.existsSync(f)) { res.status(404).end(); return; } + res.set('Cache-Control', 'public, max-age=604800'); + res.type('font/ttf'); + res.sendFile(f); +}); app.use('/audiomass', express.static(path.join(webUiPath, 'audiomass'), { setHeaders: (res) => { res.setHeader('Cache-Control', 'no-cache'); } })); @@ -4551,6 +4566,7 @@ registerSkillsRoutes(app, { setOrchestrationEnabled, }); registerCodeRoutes(app); +registerClaudeFsRoutes(app); registerTaskRoutes(app, cronScheduler); registerAgentRoutes(app, resolvePromptPath); registerChannelsRoutes(app, { @@ -4730,10 +4746,20 @@ wss.on('connection', (ws: WebSocket, req: http.IncomingMessage) => { const ptySessions = new Map(); // shellId → node-pty process const ptyImport = import('node-pty').catch(() => null); + // 터미널(pty_*)은 로그인한 관리자 + 같은 Origin 의 연결만 — 아니면 어떤 pty 메시지도 처리하지 않는다. + const ptyAccess = ptyAccessDecision({ user, origin: req.headers.origin, host: req.headers.host, forwardedHost: req.headers['x-forwarded-host'] }); + let ptyDeniedLogged = false; + ws.on('message', async (d) => { let msg: any; try { msg = JSON.parse(d.toString('utf8')); } catch { return; } + if (typeof msg?.type === 'string' && msg.type.startsWith('pty_') && !ptyAccess.allowed) { + if (!ptyDeniedLogged) { ptyDeniedLogged = true; console.warn(`[pty] denied ${msg.type} user=${user?.username || 'anonymous'} origin=${req.headers.origin || '-'}: ${ptyAccess.reason}`); } + try { ws.send(JSON.stringify({ type: 'pty_error', shellId: msg.shellId, error: ptyAccess.reason })); } catch {} + return; + } + if (msg.type === 'pty_spawn') { const shellId = msg.shellId; if (!shellId || typeof shellId !== 'string') return; @@ -4751,6 +4777,7 @@ wss.on('connection', (ws: WebSocket, req: http.IncomingMessage) => { env: { ...process.env, TERM: 'xterm-256color' } as any, }); ptySessions.set(shellId, proc); + console.log(`[pty] open user=${user?.username} shell=${shellId} pid=${proc.pid}`); proc.onData((data: string) => { try { ws.send(JSON.stringify({ type: 'pty_output', shellId, data })); } catch {} }); diff --git a/tests/claude-fs.test.ts b/tests/claude-fs.test.ts new file mode 100644 index 0000000..9c213e9 --- /dev/null +++ b/tests/claude-fs.test.ts @@ -0,0 +1,129 @@ +// 클로드 앱 서버 모드 파일 API(routes-claude-fs.ts) — 관리자/일반 사용자 범위, 차단 규칙, 심볼릭 링크 탈출. +import { test, describe, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import http from 'http'; +import express from 'express'; +import { registerClaudeFsRoutes, isSecretOrSystemPath } from '../src/gateway/routes/routes-claude-fs'; +import { getConfig, getUserWorkspace } from '../src/config/config'; + +const CFG = getConfig().getConfigDir(); + +describe('isSecretOrSystemPath — 차단 규칙', () => { + test('시스템 경로/루트 차단', () => { + for (const p of ['/', '/etc', '/etc/passwd', '/proc/1', '/root', '/usr/bin', '/var/lib/x']) assert.ok(isSecretOrSystemPath(p, CFG), p); + }); + test('.smallclaw 설정·키·vault·세션 차단, 워크스페이스는 허용', () => { + for (const rel of ['config.json', 'vault/vault.enc', 'active-sessions.json', 'claude-key.txt', 'users/papa/profile.json', 'logs/gateway.log']) + assert.ok(isSecretOrSystemPath(path.join(CFG, rel), CFG), rel); + for (const rel of ['users/papa/workspace', 'users/papa/workspace/workshop/robot/a.txt', 'workspace/x']) + assert.equal(isSecretOrSystemPath(path.join(CFG, rel), CFG), null, rel); + }); + test('비밀 파일·폴더 차단', () => { + for (const p of ['/home/u/.ssh/id_rsa', '/srv/app/.env', '/srv/app/.env.production', '/x/server.pem', '/x/my_api_key.txt', '/home/u/.claude/settings.json', '/x/credentials.json']) + assert.ok(isSecretOrSystemPath(p, CFG), p); + }); + test('일반 프로젝트 파일은 허용', () => { + for (const p of ['/srv/homeclaw/src/tools/stl-cad.ts', '/tmp/work/readme.md']) assert.equal(isSecretOrSystemPath(p, CFG), null, p); + }); +}); + +describe('HTTP — 관리자/일반 사용자', () => { + let server: http.Server; let base = ''; + let role: 'admin' | 'user' = 'admin'; let username = 'zz_claude_fs_test'; + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'claude-fs-')); + const ws = getUserWorkspace('zz_claude_fs_test'); + const call = async (method: string, url: string, body?: any) => { + const r = await fetch(base + url, { method, headers: { 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined }); + return { status: r.status, json: await r.json().catch(() => ({})) as any }; + }; + + before(async () => { + fs.mkdirSync(path.join(tmp, 'proj', 'sub'), { recursive: true }); + fs.writeFileSync(path.join(tmp, 'proj', 'a.txt'), 'hello'); + fs.writeFileSync(path.join(tmp, 'proj', 'sub', 'b.md'), 'x'); + fs.writeFileSync(path.join(tmp, 'proj', '.env'), 'SECRET=1'); + fs.writeFileSync(path.join(tmp, 'outside.txt'), 'outside'); + fs.symlinkSync(path.join(tmp, 'outside.txt'), path.join(tmp, 'proj', 'link.txt')); + fs.mkdirSync(path.join(ws, 'workshop', 'robot'), { recursive: true }); + fs.writeFileSync(path.join(ws, 'workshop', 'robot', 'n.txt'), 'note'); + const app = express(); app.use(express.json()); + app.use((req, _res, next) => { (req as any).user = { username, role, workspace: ws }; next(); }); + registerClaudeFsRoutes(app); + await new Promise(r => { server = app.listen(0, '127.0.0.1', () => r()); }); + base = `http://127.0.0.1:${(server.address() as any).port}`; + }); + after(() => { + server.close(); + fs.rmSync(tmp, { recursive: true, force: true }); + fs.rmSync(path.join(CFG, 'users', 'zz_claude_fs_test'), { recursive: true, force: true }); + }); + + test('관리자: 임의 절대경로 루트 — 목록/읽기/쓰기', async () => { + role = 'admin'; + const root = encodeURIComponent(path.join(tmp, 'proj')); + const list = await call('GET', `/api/claude-fs/files?root=${root}`); + assert.equal(list.status, 200); + assert.deepEqual(list.json.files.sort(), ['a.txt', 'sub/b.md']); // .env·링크는 목록에서 빠짐 + assert.equal((await call('GET', `/api/claude-fs/file?root=${root}&name=a.txt`)).json.content, 'hello'); + const w = await call('POST', '/api/claude-fs/save', { root: path.join(tmp, 'proj'), filename: 'new/dir/c.txt', content: 'zzz' }); + assert.ok(w.json.success); + assert.equal(fs.readFileSync(path.join(tmp, 'proj', 'new', 'dir', 'c.txt'), 'utf8'), 'zzz'); + }); + test('관리자도: 시스템·.smallclaw 설정 루트는 403', async () => { + role = 'admin'; + for (const r of ['/etc', '/', CFG]) assert.equal((await call('GET', `/api/claude-fs/files?root=${encodeURIComponent(r)}`)).status, 403, r); + }); + test('관리자도: .env 읽기/쓰기 403, 경로 탈출(..) 403, 링크 탈출 403', async () => { + role = 'admin'; + const root = path.join(tmp, 'proj'); const q = encodeURIComponent(root); + assert.equal((await call('GET', `/api/claude-fs/file?root=${q}&name=.env`)).status, 403); + assert.equal((await call('POST', '/api/claude-fs/save', { root, filename: '.env', content: 'x' })).status, 403); + assert.equal((await call('GET', `/api/claude-fs/file?root=${q}&name=${encodeURIComponent('../outside.txt')}`)).status, 403); + assert.equal((await call('GET', `/api/claude-fs/file?root=${q}&name=link.txt`)).status, 403); + assert.equal((await call('POST', '/api/claude-fs/save', { root, filename: 'link.txt', content: 'overwrite' })).status, 403); + assert.equal(fs.readFileSync(path.join(tmp, 'outside.txt'), 'utf8'), 'outside', '링크로 밖 파일이 바뀜'); + }); + test('일반 사용자: 자기 워크스페이스 상대경로는 OK, 밖 절대경로는 403', async () => { + role = 'user'; + const ok = await call('GET', `/api/claude-fs/files?root=${encodeURIComponent('workshop/robot')}`); + assert.equal(ok.status, 200); assert.deepEqual(ok.json.files, ['n.txt']); + assert.equal((await call('GET', `/api/claude-fs/files?root=${encodeURIComponent(path.join(tmp, 'proj'))}`)).status, 403); + assert.equal((await call('GET', `/api/claude-fs/files?root=${encodeURIComponent('/srv/homeclaw/src')}`)).status, 403); + assert.equal((await call('GET', `/api/claude-fs/files?root=${encodeURIComponent('../..')}`)).status, 403); + }); + test('root 비우면 code/ 폴더(기본)', async () => { + role = 'user'; + const info = await call('GET', '/api/claude-fs/info'); + assert.equal(info.status, 200); + assert.ok(info.json.root.endsWith(path.join('workspace', 'code'))); + }); +}); + +import { ptyAccessDecision } from '../src/gateway/pty-guard'; +describe('ptyAccessDecision — 웹 터미널 접근', () => { + const admin = { username: 'papa', role: 'admin' }; const host = 'localhost:18789'; + test('로그인한 관리자 + 같은 Origin → 허용', () => { + assert.equal(ptyAccessDecision({ user: admin, origin: 'http://localhost:18789', host }).allowed, true); + assert.equal(ptyAccessDecision({ user: admin, origin: 'https://claw.example.com', host: 'claw.example.com' }).allowed, true); + }); + test('비로그인(user=null) 거부', () => { + assert.equal(ptyAccessDecision({ user: null, origin: 'http://localhost:18789', host }).allowed, false); + assert.equal(ptyAccessDecision({ user: undefined, origin: 'http://localhost:18789', host }).allowed, false); + }); + test('일반 사용자 거부', () => { + assert.equal(ptyAccessDecision({ user: { username: 'apple', role: 'user' }, origin: 'http://localhost:18789', host }).allowed, false); + }); + test('Origin 없음/다른 사이트/형식 오류 거부', () => { + assert.equal(ptyAccessDecision({ user: admin, host }).allowed, false); + assert.equal(ptyAccessDecision({ user: admin, origin: 'https://evil.example', host }).allowed, false); + assert.equal(ptyAccessDecision({ user: admin, origin: 'not a url', host }).allowed, false); + assert.equal(ptyAccessDecision({ user: admin, origin: 'http://localhost:18789' }).allowed, false); + }); +}); +test('프록시가 Host 를 바꿔도 X-Forwarded-Host 가 Origin 과 같으면 허용', () => { + assert.equal(ptyAccessDecision({ user: { username: 'papa', role: 'admin' }, origin: 'https://claw.example.com', host: '192.168.0.5:18789', forwardedHost: 'claw.example.com' }).allowed, true); + assert.equal(ptyAccessDecision({ user: { username: 'papa', role: 'admin' }, origin: 'https://evil.example', host: '192.168.0.5:18789', forwardedHost: 'claw.example.com' }).allowed, false); +});