v4.3.19-25: 탐정 앱 자체 WOPI 호스트로 NextCloud 없이 Collabora 직결

기존 col.applecherry.net Collabora 서버를 재사용하되, NextCloud(WebDAV
업로드/가져오기 왕복) 없이 홈클로 게이트웨이가 직접 WOPI 호스트 역할
수행 (CheckFileInfo/GetFile/PutFile). hwp는 사건 폴더 안에서 odt로
1회 변환 후 그 자리에서 바로 편집 — 타이핑하는 대로 사건 폴더에 즉시
저장되어 별도 "가져오기" 버튼이 필요 없어짐(dtFetchFromNextcloud 제거).
config.json에 collabora.baseUrl/publicUrl 추가. Express 5의
res.sendFile 이슈(이미 known) 재발 → createReadStream으로 우회.

실기기(col.applecherry.net + 실제 사건 고소장.odt)로 전체 라운드트립
검증 완료.

부수: 사이드바 사건목록이 빠른조사/법률질문 버튼 늘어나며 눌리는 문제
— 잘 안쓰는 버튼 정리(19개→11개)로 완화 + .dt-cases min-height 안전장치.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5 committed 2026-07-28 14:18:18 +09:00
1 parent e180c3978e
commit 3bff465c08
5 files changed
+135 -32

No files matched your search

+5 -1
View File
@@ -371,5 +371,9 @@
},
"writer": {
"providers": {}
},
"collabora": {
"baseUrl": "https://col.applecherry.net",
"publicUrl": "https://ai.applecherry.net"
}
}
}
+116 -1
View File
@@ -1,10 +1,33 @@
import express from 'express';
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import { execFile } from 'child_process';
import archiver from 'archiver';
import { getUserWorkspace } from '../../config/config';
import { getUserWorkspace, getConfig } from '../../config/config';
import { openInNextcloudEditor, fetchFromNextcloudEditor, odtBufferToPdf } from './nextcloud-webdav';
// ─── Collabora WOPI host (local, no NextCloud) ────────────────────────────────
// Reuses the existing col.applecherry.net Collabora server directly — our own
// gateway plays WOPI host instead of NextCloud's richdocuments app, so edits
// save straight into the case folder with no upload/download round trip.
// Tokens are short-lived, in-memory, generated fresh each time the editor is
// opened (see collabora-open below) — never persisted, no signing needed.
interface WopiTokenEntry {
username: string;
absPath: string;
expiresAt: number;
}
const wopiTokens = new Map<string, WopiTokenEntry>();
const WOPI_TOKEN_TTL_MS = 8 * 60 * 60 * 1000; // 8h — generous for a long editing session
function wopiCleanupExpired(): void {
const now = Date.now();
for (const [token, entry] of wopiTokens) {
if (entry.expiresAt < now) wopiTokens.delete(token);
}
}
// ─── Per-user Detective Cases ─────────────────────────────────────────────────
// Stored at <user-workspace>/.smallclaw/detective-cases.json
@@ -99,6 +122,98 @@ export function registerDetectiveRoutes(
CONFIG_DIR_PATH: string,
): void {
// Opens a case file in Collabora directly — no NextCloud in the loop.
// .hwp is converted to .odt once (saved alongside the original in the case
// folder, same naming convention the old NextCloud flow used) since
// Collabora has no HWP filter; .odt opens as-is. A fresh WOPI token is
// minted and the browser is redirected straight into Collabora's editor,
// which then calls back into the routes below using that token.
app.get('/api/detective/collabora-open', async (req, res) => {
const session = getSessionUser(req);
if (!session) return res.status(401).send('Unauthorized');
const caseId = String(req.query.caseId || '');
const relPath = String(req.query.relPath || '');
const segments = relPath.split('/').filter(Boolean);
if (!/^[a-zA-Z0-9_-]+$/.test(caseId) || !segments.length || segments.some(s => s === '..' || s === '.')) {
return res.status(400).send('invalid');
}
const dir = detectiveFilesDir(session.username, caseId);
const srcPath = path.join(dir, ...segments);
if (!isPathInsideDir(dir, srcPath) || !fs.existsSync(srcPath)) return res.status(404).send('File not found');
const collaboraCfg = (getConfig().getConfig() as any).collabora || {};
if (!collaboraCfg.baseUrl || !collaboraCfg.publicUrl) {
return res.status(500).send('Collabora is not configured (collabora.baseUrl/publicUrl)');
}
try {
let editPath = srcPath;
if (/\.hwp$/i.test(srcPath)) {
const outDir = path.dirname(srcPath);
const base = path.basename(srcPath, path.extname(srcPath));
const odtPath = path.join(outDir, `${base}.odt`);
// Reuse an already-converted .odt if one exists from a prior open — don't
// clobber edits already saved into it just because the .hwp is still there.
if (!fs.existsSync(odtPath)) {
await new Promise<void>((resolve, reject) => {
execFile('soffice', ['--headless', '--convert-to', 'odt', '--outdir', outDir, srcPath], { timeout: 60_000 }, (err) => {
if (err) reject(err); else resolve();
});
});
if (!fs.existsSync(odtPath)) throw new Error('hwp → odt 변환 결과물이 없습니다');
}
editPath = odtPath;
}
wopiCleanupExpired();
const token = crypto.randomBytes(32).toString('hex');
wopiTokens.set(token, { username: session.username, absPath: editPath, expiresAt: Date.now() + WOPI_TOKEN_TTL_MS });
const wopiSrc = `${collaboraCfg.publicUrl.replace(/\/+$/, '')}/api/detective/wopi/files/${token}`;
const editorUrl = `${collaboraCfg.baseUrl.replace(/\/+$/, '')}/browser/dist/cool.html?WOPISrc=${encodeURIComponent(wopiSrc)}&access_token=${token}`;
res.redirect(editorUrl);
} catch (e: any) {
res.status(502).send('Collabora open failed: ' + String(e?.message || e));
}
});
// ── WOPI callbacks — Collabora calls these directly (no session cookie,
// the token itself is the auth) ────────────────────────────────────────────
app.get('/api/detective/wopi/files/:token', (req, res) => {
const entry = wopiTokens.get(req.params.token);
if (!entry || entry.expiresAt < Date.now()) return res.status(404).json({ error: 'Unknown or expired token' });
if (!fs.existsSync(entry.absPath)) return res.status(404).json({ error: 'File not found' });
const stat = fs.statSync(entry.absPath);
res.json({
BaseFileName: path.basename(entry.absPath),
Size: stat.size,
UserId: entry.username,
OwnerId: entry.username,
UserCanWrite: true,
UserFriendlyName: entry.username,
});
});
app.get('/api/detective/wopi/files/:token/contents', (req, res) => {
const entry = wopiTokens.get(req.params.token);
if (!entry || entry.expiresAt < Date.now()) return res.status(404).end();
if (!fs.existsSync(entry.absPath)) return res.status(404).end();
// res.sendFile has known reliability issues on Express 5 with some paths
// (see /api/files/{*filePath} in server.ts) — stream it directly instead.
const stream = fs.createReadStream(entry.absPath);
stream.on('error', () => { if (!res.headersSent) res.status(500).end(); });
stream.pipe(res);
});
app.post('/api/detective/wopi/files/:token/contents', express.raw({ type: '*/*', limit: '200mb' }), (req, res) => {
const entry = wopiTokens.get(req.params.token);
if (!entry || entry.expiresAt < Date.now()) return res.status(404).json({ error: 'Unknown or expired token' });
try {
fs.writeFileSync(entry.absPath, req.body);
res.json({ LastModifiedTime: new Date().toISOString() });
} catch (e: any) {
res.status(500).json({ error: String(e?.message || e) });
}
});
app.get('/api/detective/cases', (req, res) => {
const session = getSessionUser(req);
if (!session) return res.status(401).json({ error: 'Unauthorized' });
+2
View File
@@ -2604,6 +2604,8 @@ app.use((req, _res, next) => {
if (req.path === '/api/kakao/webhook') return next();
// 카카오 이미지 전송용 임시 공개 링크 — 카카오 서버가 직접 fetch (토큰 자체가 인증)
if (req.path.startsWith('/api/kakao/img/')) return next();
// Collabora Online이 WOPI 콜백으로 직접 호출 — 세션 쿠키가 없으므로 access_token 자체가 인증
if (req.path.startsWith('/api/detective/wopi/')) return next();
const token = extractAuthToken(req);
const session = token ? activeSessions.get(token) : undefined;
+9
View File
@@ -398,6 +398,15 @@ export interface SmallClawConfig {
username?: string;
appPassword?: string;
};
collabora?: {
// Existing col.applecherry.net Collabora server — reused directly via our
// own WOPI host below, no NextCloud in the loop.
baseUrl?: string;
// This gateway's own public URL, used to build the WOPISrc Collabora calls
// back into (must match what's allowlisted on the Collabora side via
// --o:storage.wopi.host).
publicUrl?: string;
};
weather?: {
api_key?: string;
};
+3 -30
View File
@@ -34,7 +34,7 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
.dt-search::placeholder{color:var(--muted);}
.dt-sort-bar{display:flex;align-items:center;padding:0 8px 4px;gap:4px;flex-shrink:0;}
.dt-sort-sel{flex:1;background:var(--panel-2);border:1px solid var(--line);border-radius:5px;padding:2px 5px;font-size:10px;color:var(--muted);font-family:inherit;}
.dt-cases{flex:1;overflow-y:auto;padding:4px;}
.dt-cases{flex:1;overflow-y:auto;padding:4px;min-height:120px;}
.dt-cases::-webkit-scrollbar{width:3px;}
.dt-cases::-webkit-scrollbar-thumb{background:var(--line);border-radius:3px;}
.dt-case-item{padding:7px 10px;border-radius:7px;border:1px solid transparent;cursor:pointer;margin-bottom:2px;transition:.12s;position:relative;}
@@ -287,11 +287,8 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
<div class="dt-quick-sec">빠른 조사</div>
<div class="dt-quick">
<button class="dt-qbtn" onclick="sendQuick('인물 조사 방법론을 알려주세요. 공개 정보를 활용해 특정 인물의 이력, 소속, 활동을 파악하는 단계별 절차가 궁금합니다.')">👤 인물 조사 방법</button>
<button class="dt-qbtn" onclick="sendQuick('기업 실사(Due Diligence) 체크리스트를 알려주세요. 계약 전 상대 회사의 신뢰성과 재무 건전성을 확인하는 방법이 궁금합니다.')">🏢 기업 실사 체크리스트</button>
<button class="dt-qbtn" onclick="sendQuick('온라인 사기 피해를 입었습니다. 증거 수집 방법과 신고 절차를 알려주세요.')">🚨 온라인 사기 대응</button>
<button class="dt-qbtn" onclick="sendQuick('SNS·인터넷에서 허위 정보나 루머가 퍼지고 있습니다. 출처 추적과 대응 방법을 알려주세요.')">📱 허위정보 추적</button>
<button class="dt-qbtn" onclick="sendQuick('디지털 발자국(Digital Footprint) 조사 방법을 알려주세요. SNS, 이메일, 도메인, IP 기반 공개 정보 추적 절차를 설명해 주세요.')">🌐 디지털 발자국 추적</button>
<button class="dt-qbtn" onclick="sendQuick('부동산 사기 유형과 사기 여부를 판별하는 방법을 알려주세요. 등기부등본 확인, 임대인 신원 확인, 이중계약 체크 방법도 포함해 주세요.')">🏠 부동산 사기 체크</button>
<button class="dt-qbtn" onclick="sendQuick('현재 사건의 단서와 증거를 바탕으로 가설을 세우고 조사 방향을 잡아주세요.',true)">🗂 현재 사건 분석 요청</button>
<button class="dt-qbtn" onclick="promptIPTrack()">🌐 IP 추적</button>
</div>
@@ -299,12 +296,7 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
<div class="dt-sb-divider"></div>
<div class="dt-quick-sec">⚖️ 법률 질문</div>
<div class="dt-quick">
<button class="dt-qbtn" onclick="sendQuick('사기죄(형법 제347조) 성립 요건을 알려주세요. 판례 기준으로 기망행위·재산상 이익·인과관계 각각 어떻게 판단하는지 설명해 주세요. 관련 대법원 판례도 찾아주세요.')">📌 사기죄 성립 요건</button>
<button class="dt-qbtn" onclick="sendQuick('민사소송과 형사고소의 차이점을 알려주세요. 같은 피해에 대해 동시에 진행할 수 있는지, 어떤 경우에 어느 쪽이 유리한지도 설명해 주세요.')">⚖️ 민사 vs 형사 선택</button>
<button class="dt-qbtn" onclick="sendQuick('내용증명 작성 방법과 법적 효력을 알려주세요. 어떤 상황에서 보내야 하고, 보낸 후 상대방이 무시하면 어떻게 대응해야 하는지도 알려주세요.')">📮 내용증명 작성·효력</button>
<button class="dt-qbtn" onclick="sendQuick('명예훼손죄와 모욕죄의 차이를 알려주세요. 온라인(SNS, 카카오톡 단체방 등)에서 발생한 경우 성립 요건과 처벌 수위, 증거 수집 방법도 알려주세요. 관련 판례를 찾아주세요.')">🗣 명예훼손·모욕죄</button>
<button class="dt-qbtn" onclick="sendQuick('계약 해지·위약금 관련 법률을 알려주세요. 상대방이 계약을 이행하지 않을 때 해지 통보 방법, 위약금 청구 절차, 관련 민법 조항과 판례를 설명해 주세요.')">📝 계약 해지·위약금</button>
<button class="dt-qbtn" onclick="sendQuick('임금 체불 피해를 받았습니다. 근로기준법상 임금 체불의 법적 정의, 고소 절차, 체당금 신청 방법, 사업주 처벌 수위를 알려주세요. 관련 법령도 찾아주세요.')">💼 임금 체불 대응</button>
<button class="dt-qbtn" onclick="sendQuick('법률 관련 질문이 있습니다. 상황을 말씀드릴 테니 관련 법령·판례를 조사해서 답변해 주세요.')">⚖️ 법률 질문하기</button>
<button class="dt-qbtn" onclick="sendQuick('현재 사건에 적용 가능한 법령과 판례를 조사해서 법적 대응 방향을 제시해주세요.',true)">🔍 현재 사건 법률 검토</button>
</div>
@@ -1268,24 +1260,6 @@ async function dtQuickAddToTimeline(relPath,btn){
showSaveIndicator(s.date?`날짜 인식: ${s.date} — 아래에서 확인 후 추가하세요`:'날짜를 찾지 못했습니다 — 아래에서 직접 입력 후 추가하세요');
}
async function dtFetchFromNextcloud(relPath,btn){
if(!currentCaseId)return;
if(btn){btn.disabled=true;btn.textContent='⏳';}
try{
const url='/api/detective/nextcloud-fetch?caseId='+encodeURIComponent(currentCaseId)+'&relPath='+encodeURIComponent(relPath);
const r=await fetch(url,{headers:authH()});
const d=await r.json();
if(!r.ok||!d.success)throw new Error(d.error||'가져오기 실패');
const names=(d.files||[]).map(f=>f.name).join(', ');
showSaveIndicator(`NextCloud에서 최신본을 가져왔습니다: ${names}`);
loadFiles();
}catch(e){
alert('NextCloud에서 가져오기 실패: '+e.message);
}finally{
if(btn){btn.disabled=false;btn.textContent='⬇️';}
}
}
// ── Files ─────────────────────────────────────────────────────────────────────
function fmtFileSize(n){
if(n<1024)return n+'B';
@@ -1361,8 +1335,7 @@ function renderFileRow(f,name){
${nameHtml}
<span style="font-size:10px;color:var(--muted);flex-shrink:0">${fmtFileSize(f.size)}</span>
${isPdf?`<a href="/pdf-editor-open?caseId=${encodeURIComponent(currentCaseId)}" target="_blank" class="dt-cl-del" style="opacity:.7" title="PDF 편집기를 새 창에서 엽니다. 이 파일은 자동으로 열리지 않으니(외부 편집기 한계), 편집기의 업로드 버튼에서 이 파일을 직접 선택하세요. 수정 후 다운로드하면 사건 폴더에 자동 저장됩니다.">✏️</a>`:''}
${isCloudEditable?`<a href="/api/detective/nextcloud-open?caseId=${encodeURIComponent(currentCaseId)}&relPath=${encodeURIComponent(f.relPath)}" target="_blank" class="dt-cl-del" style="opacity:.7" title="NextCloud(Collabora)에서 바로 편집합니다. 새 창이 열리면 그 문서에 즉시 편집 가능하고, 입력하는 대로 자동 저장됩니다(다운로드 불필요).">🌐</a>
<button class="dt-cl-del" onclick="dtFetchFromNextcloud('${escJsAttr(f.relPath)}',this)" title="NextCloud에서 편집 중인(또는 편집 완료한) 최신본을 사건 폴더로 가져옵니다(odt+PDF).">⬇️</button>`:''}
${isCloudEditable?`<a href="/api/detective/collabora-open?caseId=${encodeURIComponent(currentCaseId)}&relPath=${encodeURIComponent(f.relPath)}" target="_blank" class="dt-cl-del" style="opacity:.7" title="Collabora에서 바로 편집합니다. 새 창이 열리면 그 문서에 즉시 편집 가능하고, 입력하는 대로 사건 폴더에 자동 저장됩니다(다운로드/가져오기 불필요).">🌐</a>`:''}
${(f.category==='photo'||isText)?`<button class="dt-cl-del" onclick="dtQuickAddToTimeline('${escJsAttr(f.relPath)}',this)" title="날짜 인식 (타임라인 탭에서 확인 후 추가)">🕐+</button>
<button class="dt-cl-del" onclick="dtManualDateSuggest('${escJsAttr(f.relPath)}',this)" title="날짜 인식">📅</button>`:''}
<a href="${escAttr(f.url)}" download="${escAttr(f.name)}" class="dt-cl-del" title="기기에 다운로드">💾</a>