feat(workshop): 파일 탭에서 G-code를 누르면 슬라이서 미리보기 모드로 열림(?gcode=) — 툴패스·시간·필라멘트·서포트 표시, 저장본을 K2에 업로드·출력 시작, ⬇ 원본 다운로드 링크. 경로는 작업실 프로젝트 안 .gcode만(../·심볼릭 링크 탈출 거부)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5.5 committed 2026-09-30 13:27:02 +09:00
1 parent a0884881e1
commit a426c6aee6
4 files changed
+137 -9

No files matched your search

+47 -3
View File
@@ -81,6 +81,33 @@ export function saveGcodeToProject(
return { ok: true, relPath: `출력/${fileName}`, name: fileName };
}
/**
* 작업실 프로젝트 안의 .gcode 파일 경로 검증(2026-09-30). 파일 탭에서 G-code를 눌러 슬라이서로 미리보기·
* K2 업로드를 할 때 쓴다. 워크스페이스 기준 상대경로 "workshop/<프로젝트id>/.../x.gcode" 형태만 허용하고,
* 그 프로젝트 폴더 밖(../, 심볼릭 링크 탈출)으로 나가는 경로는 거부한다.
*/
export function resolveProjectGcode(workspacePath: string, relPath: string): string {
const rel = String(relPath || '').replace(/\\/g, '/');
const segs = rel.split('/');
if (!/^workshop\/[A-Za-z0-9_-]+\/.+\.gcode$/i.test(rel) || segs.some((seg) => seg === '' || seg === '.' || seg === '..' || seg.includes('\0'))) {
throw new Error('작업실 프로젝트의 .gcode 파일만 열 수 있습니다.');
}
const base = path.join(workspacePath, 'workshop');
const abs = path.resolve(workspacePath, rel);
if (!isPathInsideDir(base, abs)) throw new Error('경로가 작업실 폴더 밖입니다.');
if (fs.existsSync(abs)) {
const real = fs.realpathSync(abs);
if (!isPathInsideDir(fs.realpathSync(base), real)) throw new Error('경로가 작업실 폴더 밖입니다.');
}
return abs;
}
/** K2(Moonraker)에 올릴 파일명 — 한글·공백 등은 _로 바꾼다(안전한 ASCII 이름). */
export function moonrakerGcodeName(baseName: string): string {
const stem = String(baseName || 'model').replace(/\.gcode$/i, '').replace(/[^A-Za-z0-9._-]+/g, '_').replace(/_+/g, '_').replace(/^[._-]+|[._-]+$/g, '');
return `${stem || 'model'}.gcode`;
}
export function registerK2Routes(app: Express): void {
// Moonraker 상태(print_stats/virtual_sdcard)를 대시보드 위젯용으로 요약해서 반환 —
// 브라우저가 K2 LAN IP를 직접 못 치니(HTTPS 페이지에서 mixed-content) 서버가 대신 조회.
@@ -346,10 +373,14 @@ export function registerK2Routes(app: Express): void {
app.post('/api/k2/upload', express.json(), async (req: Request, res: Response) => {
const user = (req as any).user;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
const filename = String(req.body?.filename || '').trim();
if (!filename) return res.status(400).json({ error: 'filename이 필요합니다.' });
const filenameArg = String(req.body?.filename || '').trim();
const pathArg = String(req.body?.path || '').trim();
if (!filenameArg && !pathArg) return res.status(400).json({ error: 'filename 또는 path가 필요합니다.' });
try {
const p = gcodePath(getUserWorkspace(user.username), filename);
// path: 작업실 프로젝트 안의 gcode(파일 탭 → 슬라이서 미리보기). filename: 슬라이싱 직후 임시 결과.
const workspace = getUserWorkspace(user.username);
const p = pathArg ? resolveProjectGcode(workspace, pathArg) : gcodePath(workspace, filenameArg);
const filename = pathArg ? moonrakerGcodeName(path.basename(p)) : filenameArg;
if (!fs.existsSync(p)) return res.status(404).json({ error: 'gcode 파일이 없습니다.' });
const up = await uploadToMoonraker(p, filename);
if (!up.ok) return res.status(502).json({ error: up.detail });
@@ -359,6 +390,19 @@ export function registerK2Routes(app: Express): void {
}
});
// 작업실 프로젝트 안의 gcode를 미리보기용으로 스트리밍(파일 탭에서 G-code 클릭 → 슬라이서 미리보기 모드).
app.get('/api/k2/gcode-file', (req: Request, res: Response) => {
const user = (req as any).user;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
try {
const p = resolveProjectGcode(getUserWorkspace(user.username), String(req.query.path || ''));
if (!fs.existsSync(p)) return res.status(404).json({ error: 'gcode 파일이 없습니다.' });
res.type('text/plain').sendFile(p, { dotfiles: 'allow' });
} catch (e: any) {
res.status(400).json({ error: String(e?.message || e) });
}
});
// 슬라이싱 결과 gcode를 브라우저로 스트리밍 — Cura 스타일 툴패스 미리보기용.
app.get('/api/k2/gcode/:filename', (req: Request, res: Response) => {
const user = (req as any).user;
+33
View File
@@ -97,3 +97,36 @@ describe('ensureOutputFolder — 출력/ 폴더가 파일 탭에 보이게 항
assert.equal(fs.readFileSync(path.join(d, 'keep.gcode'), 'utf8'), 'x');
});
});
import { resolveProjectGcode, moonrakerGcodeName } from '../src/gateway/routes/routes-k2';
describe('resolveProjectGcode — 파일 탭 G-code 미리보기·업로드 경로 검증', () => {
const w = fs.mkdtempSync(path.join(os.tmpdir(), 'k2proj-'));
fs.mkdirSync(path.join(w, 'workshop', 'proj_a', '출력'), { recursive: true });
fs.mkdirSync(path.join(w, 'secret'), { recursive: true });
fs.writeFileSync(path.join(w, 'workshop', 'proj_a', '출력', 'x.gcode'), 'G1');
fs.writeFileSync(path.join(w, 'secret', 'leak.gcode'), 'SECRET');
test('프로젝트 안의 gcode는 절대경로로 돌려준다', () => {
assert.equal(resolveProjectGcode(w, 'workshop/proj_a/출력/x.gcode'), path.join(w, 'workshop', 'proj_a', '출력', 'x.gcode'));
});
test('.gcode가 아니거나 작업실 밖이거나 ../ 가 섞인 경로는 거부한다', () => {
for (const bad of ['workshop/proj_a/출력/x.txt', 'secret/leak.gcode', 'workshop/proj_a/../../secret/leak.gcode', '/etc/passwd.gcode', 'workshop//x.gcode', 'workshop/proj_a/./x.gcode', '', 'workshop/proj a/x.gcode']) {
assert.throws(() => resolveProjectGcode(w, bad), undefined, bad);
}
});
test('심볼릭 링크로 작업실 밖 파일을 가리키면 거부한다', () => {
fs.symlinkSync(path.join(w, 'secret', 'leak.gcode'), path.join(w, 'workshop', 'proj_a', '출력', 'link.gcode'));
assert.throws(() => resolveProjectGcode(w, 'workshop/proj_a/출력/link.gcode'), /작업실 폴더 밖/);
});
});
describe('moonrakerGcodeName', () => {
test('한글·공백은 _로, 확장자는 .gcode로 정리한다', () => {
assert.equal(moonrakerGcodeName('body_a_외3_2026-09-30_1318.gcode'), 'body_a_3_2026-09-30_1318.gcode');
assert.equal(moonrakerGcodeName('집진 커버.gcode'), 'model.gcode');
assert.equal(moonrakerGcodeName('plate.v2.gcode'), 'plate.v2.gcode');
});
});
+18 -4
View File
@@ -114,7 +114,8 @@ function stlThumbFail(img){
}
function renderFileCard(file){
const isStl=STL_RE.test(file.name);
const icon=isStl?'🔧':(FILE_ICONS[file.category]||FILE_ICONS.other);
const isGcode=/\.gcode$/i.test(file.name);
const icon=isStl?'🔧':(isGcode?'🖨️':(FILE_ICONS[file.category]||FILE_ICONS.other));
const proj=currentProject();
// STL은 서버가 OpenSCAD로 렌더한 썸네일(캐시)을 쓴다 — ASCII STL/큰 파일/렌더 실패는 404라
// onerror로 기존 🔧 아이콘으로 되돌아간다.
@@ -124,21 +125,25 @@ function renderFileCard(file){
? `<img class="stl-thumb" src="/api/workshop/thumb?projectId=${encodeURIComponent(proj.id)}&relPath=${encodeURIComponent(file.relPath)}&v=${encodeURIComponent(file.mtime||'')}" alt="" loading="lazy" onerror="stlThumbFail(this)">`
: `<span class="rb-file-icon">${icon}</span>`;
// STL은 새탭 다운로드 대신 Three.js CAD 편집기 팝업으로 연다(작업실↔K2 CAD 플러그인 연동).
const openAttrs=isStl?`href="javascript:void(0)" onclick="openCadEditorForFile('${escJs(file.relPath)}')"`:`href="${escAttr(file.url)}" target="_blank" rel="noopener"`;
// G-code는 텍스트로 열어 봐야 알아볼 수 없다 — 슬라이서 미리보기 모드로 연다(툴패스·시간·K2 업로드). 원본은 ⬇ 링크로.
const openAttrs=isStl?`href="javascript:void(0)" onclick="openCadEditorForFile('${escJs(file.relPath)}')"`
:isGcode?`href="javascript:void(0)" onclick="openSlicerForGcode('${escJs(file.relPath)}')"`
:`href="${escAttr(file.url)}" target="_blank" rel="noopener"`;
// STL만 슬라이서로 보낼 다중선택 체크박스(09-22) — 여러 부품 STL을 한 판에 얹어 같이 슬라이싱.
const checked=stlSelection.has(file.relPath);
const selBox=isStl?`<input type="checkbox" class="rb-file-stl-sel" title="슬라이서로 보내기 선택" ${checked?'checked':''} onclick="event.stopPropagation()" onchange="toggleStlSelect('${escJs(file.relPath)}',this.checked)">`:'';
// STL 전용 도면 버튼(09-25) — OpenSCAD 3면도(외곽 치수선) 새 탭 생성.
const dlLink=isGcode?`<a class="rb-file-draw" href="${escAttr(file.url)}" download="${escAttr(file.name)}" onclick="event.stopPropagation()" title="G-code 원본 다운로드">⬇</a>`:'';
const drawBtn=isStl?`<button class="rb-file-draw" onclick="openDrawingForFile('${escJs(file.relPath)}')" title="3면도 도면 생성">📐</button>`:'';
return `<div class="rb-file-card${checked?' stl-selected':''}" data-rel="${escAttr(file.relPath)}">
${selBox}
<button class="rb-file-del" onclick="deleteFile('${escJs(file.relPath)}')" title="삭제">✕</button>
${drawBtn}
${drawBtn}${dlLink}
<a ${openAttrs}>
<div class="rb-file-thumb">${thumb}</div>
<div class="rb-file-info">
<div class="rb-file-name" title="${escAttr(file.name)}">${escAttr(file.name)}</div>
<div class="rb-file-size">${fmtFileSize(file.size)}${isStl?' · CAD 편집기에서 열기':''}</div>
<div class="rb-file-size">${fmtFileSize(file.size)}${isStl?' · CAD 편집기에서 열기':''}${isGcode?' · 슬라이서에서 미리보기':''}</div>
</div>
</a>
</div>`;
@@ -217,6 +222,15 @@ function toggleFolderStl(key){
}
}
// 저장된 G-code를 슬라이서 미리보기 모드로 연다(?gcode=). 경로는 워크스페이스 기준(workshop/<id>/...).
function openSlicerForGcode(relPath){
const p=workshopFilePath(relPath);
if(!p)return;
const w=1320,h=860;
const left=Math.max(0,(screen.width-w)/2), top=Math.max(0,(screen.height-h)/2);
window.open('/html/slicer-app.html?gcode='+encodeURIComponent(p),'k2-slicer',`width=${w},height=${h},left=${left},top=${top},menubar=no,toolbar=no,location=no,status=no`);
}
function openSlicerForSelected(){
if(!stlSelection.size)return;
const paths=[...stlSelection].map(workshopFilePath).filter(Boolean);
+39 -2
View File
@@ -142,6 +142,7 @@
let layerObjects = []; // THREE.LineSegments per layer
let layerZs = []; // Z(mm) per layer
let curGcodeFile = null;
let curGcodePath = null; // 작업실 프로젝트의 저장된 gcode(미리보기 모드) — 업로드는 filename 대신 이 경로로
let profBaseValues = {};
let profLoaded = false;
let singleLayerMode = false;
@@ -895,6 +896,7 @@
const d = await r.json();
if (!r.ok || !d.success) throw new Error(d.error || ('HTTP ' + r.status));
curGcodeFile = d.gcodeFilename;
curGcodePath = null; // 새로 슬라이싱했으니 저장본 미리보기 문맥은 끝
// 4) gcode 받아서 툴패스 렌더.
const gr = await fetch('/api/k2/gcode/' + encodeURIComponent(curGcodeFile), { headers: authH() });
@@ -921,12 +923,15 @@
}
async function uploadGcode() {
if (!curGcodeFile) return;
if (!curGcodeFile && !curGcodePath) return;
setErr('');
try {
const r = await fetch('/api/k2/upload', { method: 'POST', headers: { 'Content-Type': 'application/json', ...authH() }, body: JSON.stringify({ filename: curGcodeFile }) });
// 미리보기 모드(저장된 gcode)는 경로로, 방금 슬라이싱한 결과는 임시 파일명으로 올린다.
const body = curGcodePath ? { path: curGcodePath } : { filename: curGcodeFile };
const r = await fetch('/api/k2/upload', { method: 'POST', headers: { 'Content-Type': 'application/json', ...authH() }, body: JSON.stringify(body) });
const d = await r.json();
if (!r.ok || !d.success) throw new Error(d.error || ('HTTP ' + r.status));
curGcodeFile = d.filename; // K2에 올라간 이름 — 출력 시작이 이 이름을 쓴다
setInfo(prevInfoWithUploaded());
barEl.querySelector('#sv-print-btn').disabled = false;
} catch (e) { setErr('업로드 실패: ' + e.message); }
@@ -1194,7 +1199,39 @@
loadedModelNames = paths.map((p) => (p.split('/').pop() || p).replace(/\.(stl|3mf)$/i, ''));
}
// ?gcode=<workshop/.../x.gcode> — 저장해 둔 G-code를 다시 열어 툴패스·시간을 보고 K2로 보낸다(2026-09-30).
// 슬라이싱은 하지 않는다: 헤더(시간·필라멘트·서포트)는 gcode 주석에서 읽는다.
async function loadGcodePreview(gpath) {
setErr(''); setInfo(`📂 G-code 불러오는 중… ${escHtmlSv(gpath.split('/').pop() || gpath)}`);
try {
const r = await fetch('/api/k2/gcode-file?path=' + encodeURIComponent(gpath), { headers: authH() });
if (!r.ok) { const d = await r.json().catch(() => ({})); throw new Error(d.error || ('HTTP ' + r.status)); }
const text = await r.text();
const layers = parseGcodeToolpath(text);
if (!layers.length) throw new Error('툴패스를 읽지 못했습니다(G-code가 비었거나 형식이 다릅니다).');
renderToolpath(layers);
setLayerCount(layers.length);
fitCameraToPlate();
curGcodePath = gpath;
curGcodeFile = null;
const time = (/; estimated printing time \(normal mode\) = (.+)/.exec(text) || [])[1];
const fil = (/; filament used \[mm\] = ([\d.]+)/.exec(text) || [])[1];
const sup = (/; support_material = (\d)/.exec(text) || [])[1];
const name = gpath.split('/').pop() || gpath;
setInfo(
`📄 저장된 G-code: <b>${escHtmlSv(name)}</b><br>` +
`예상 시간 <b>${time ? escHtmlSv(time.trim()) : '—'}</b> · 필라멘트 <b>${fil ? Number(fil).toFixed(0) + 'mm' : '—'}</b> · <b>${layers.length}</b>층` +
(sup === '1' ? ' · 서포트 포함' : sup === '0' ? ' · 서포트 없음' : '') + '<br>' +
`<button class="sv-btn green" id="sv-upload-btn" onclick="window.__slicerUpload()">📤 K2 업로드</button> ` +
`<button class="sv-btn" id="sv-print-btn" onclick="window.__slicerPrint()" disabled>🖨️ 출력 시작</button>`
);
} catch (e) { setErr('G-code 불러오기 실패: ' + e.message); setInfo(''); }
}
function escHtmlSv(s) { return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c])); }
async function loadFromUrlParams() {
const gcodeParam = new URLSearchParams(location.search).get('gcode');
if (gcodeParam) { await loadGcodePreview(gcodeParam); return; }
const loadParam = new URLSearchParams(location.search).get('load');
if (!loadParam) return;
let paths;