feat(packs): per-domain resource packs stored on Nextcloud, served at /pack/<domain>.zip

- api: /api/packs upload/list/delete (zip + pack.mcmeta check, SHA1), files go to
  Nextcloud WebDAV; public GET /pack/<domain>.zip streams from Nextcloud
- nginx: unlimited body for /api/packs/, separate :81 server that only serves /pack/
- frontend: 리소스팩 page with upload progress and server.properties snippet
- compose: NEXTCLOUD_* env from .env, 8081:81 mapping

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 15:46:05 +09:00
parent 7362b45846
commit 5474dc2fca
12 changed files with 444 additions and 2 deletions

1
.gitignore vendored
View File

@@ -4,6 +4,7 @@ data/logs.db
data/logs.db-wal
data/logs.db-shm
data/restart.signal
data/packs.json
# 노드/파이썬 빌드 산출물
node_modules/

View File

@@ -14,6 +14,7 @@
- 설정 파일(`data/config.json`) 변경을 프록시가 자동 감지해 hot reload (재시작 불필요)
- 모든 연결 시도(허용 / 차단 / 에러)를 SQLite 에 기록
- 웹 대시보드 (NPM 스타일): 도메인 관리, 실시간 로그, 통계 카드, 백엔드/포트 설정
- **도메인별 리소스팩**: 대시보드에서 zip 업로드 → Nextcloud(share.tkrmagid.kr) 에 저장 → `https://mc.tkrmagid.kr/pack/<도메인>.zip` 로 공개. MC 서버 `server.properties` 에 붙여 넣을 URL/SHA1 을 보여준다
## 네트워크 구조
@@ -75,6 +76,7 @@ mc-filter-proxy 컨테이너 (25565)
| `api` | 8000 (내부) | FastAPI, 설정/로그/통계 REST API |
| `frontend` | 3000 (내부) | React + Vite SPA |
| `nginx` | 8080 (외부) | 대시보드 리버스 프록시 |
| `nginx` | 8081 (외부) | 리소스팩 공개 다운로드 (`/pack/` 만) |
`data/` 디렉터리는 모든 서비스가 공유 볼륨으로 마운트해 `config.json`, `logs.db` 를 공용합니다.
@@ -92,6 +94,10 @@ mc-filter-proxy 컨테이너 (25565)
| DELETE | `/api/logs?from_ts&to_ts` | 접속 로그 삭제 (범위 미지정 시 전체) |
| GET | `/api/status` | 프록시 상태 + 통계 |
| POST | `/api/proxy/restart` | config 파일 touch (프록시 재로드 트리거) |
| GET | `/api/packs` | 도메인별 리소스팩 목록 (URL, SHA1) |
| PUT | `/api/packs/{domain}` | 리소스팩 업로드 (multipart `file`, 크기 제한 없음) |
| DELETE | `/api/packs/{domain}` | 리소스팩 삭제 |
| GET | `/pack/{domain}.zip` | 공개 다운로드 (nginx 81 포트에서만 노출) |
## Hot reload 동작
@@ -102,6 +108,20 @@ mc-filter-proxy 컨테이너 (25565)
> **리스닝 포트 변경:** `proxy.listen_port` 는 docker-compose 의 `ports` 매핑과 짝이라 대시보드에서 편집할 수 없습니다. 바꾸려면 `data/config.json` 과 `docker-compose.yml` 의 `25565:25565` 매핑을 함께 수정한 뒤 `docker compose up -d --force-recreate proxy` 하세요.
## 리소스팩
- 팩 파일은 Nextcloud 의 `NEXTCLOUD_DIR/<도메인>.zip` 에 저장되고, 메타데이터(SHA1, 크기, 업로드 시각)는 `data/packs.json` 에 남는다.
- 클라이언트 다운로드는 API 가 Nextcloud 에서 받아 그대로 중계한다. (Nextcloud 공유 링크는 http 로 리다이렉트를 줘서 MC 클라이언트가 못 따라간다.)
- nginx 의 81 포트(compose `8081:81`)는 `/pack/` 만 응답하고 나머지는 404 다. 외부 리버스 프록시(NPMplus)에서는 `mc.tkrmagid.kr/pack/` 만 이 포트로 연결한다. 대시보드 포트는 계속 외부 비공개.
- Nextcloud 계정은 compose 폴더의 `.env` 에 둔다:
```
NEXTCLOUD_USER=<계정>
NEXTCLOUD_PASSWORD=<앱 비밀번호>
```
- 팩을 교체하면 SHA1 이 바뀌므로 MC 서버의 `resource-pack-sha1` 을 고치고 서버를 재시작해야 한다.
## 보안 권장
- **대시보드 포트(8080)는 외부 포트포워딩 금지.** Proxmox 내부망 / VPN / SSH 터널을 통해서만 접근하세요.
@@ -179,6 +199,11 @@ npm run dev # http://localhost:3000, /api 는 8000 으로 자동 프록시
|-------------------|--------------------|-------------------|
| `MC_CONFIG_PATH` | `/data/config.json`| proxy, api |
| `MC_LOG_DB` | `/data/logs.db` | proxy, api |
| `MC_PACKS_PATH` | `/data/packs.json` | api |
| `NEXTCLOUD_URL` | `http://192.168.10.10:8080` | api |
| `NEXTCLOUD_USER` / `NEXTCLOUD_PASSWORD` | (없음) | api |
| `NEXTCLOUD_DIR` | `/claude/mc_domain_proxy/packs` | api |
| `PACK_PUBLIC_BASE`| `https://mc.tkrmagid.kr/pack` | api |
## 라이선스

View File

@@ -1,6 +1,6 @@
"""MC Domain Filter 관리 API.
FastAPI 로 설정/도메인/로그/상태 4개 라우터를 노출한다. 인증은 없으니
FastAPI 로 설정/도메인/로그/상태/리소스팩 라우터를 노출한다. 인증은 없으니
공개 네트워크에 직접 노출하지 말 것 (nginx + basic auth 권장).
"""
from __future__ import annotations
@@ -11,6 +11,7 @@ from fastapi.middleware.cors import CORSMiddleware
from routes import config as config_routes
from routes import domains as domain_routes
from routes import logs as log_routes
from routes import packs as pack_routes
from routes import status as status_routes
app = FastAPI(title="MC Domain Filter API", version="0.1.0")
@@ -26,6 +27,8 @@ app.include_router(config_routes.router, prefix="/api", tags=["config"])
app.include_router(domain_routes.router, prefix="/api", tags=["domains"])
app.include_router(log_routes.router, prefix="/api", tags=["logs"])
app.include_router(status_routes.router, prefix="/api", tags=["status"])
app.include_router(pack_routes.router, prefix="/api", tags=["packs"])
app.include_router(pack_routes.public_router, tags=["packs"])
@app.get("/health")

View File

@@ -1,3 +1,5 @@
fastapi==0.115.0
uvicorn[standard]==0.30.6
pydantic==2.9.2
httpx==0.27.2
python-multipart==0.0.12

201
api/routes/packs.py Normal file
View File

@@ -0,0 +1,201 @@
"""도메인별 리소스팩: Nextcloud(share.tkrmagid.kr) 에 저장하고 공개 경로로 내려준다.
- 업로드/삭제/목록은 대시보드용 /api/packs (인증 없음, 내부망 전용)
- 클라이언트 다운로드는 /pack/<domain>.zip (외부 공개). Nextcloud 에서 받아 그대로 스트리밍한다.
Nextcloud 공유 링크의 /download 는 http:// 로 303 리다이렉트를 주는데,
MC 클라이언트(HttpURLConnection)는 https→http 리다이렉트를 따라가지 않아서 직접 중계한다.
"""
from __future__ import annotations
import hashlib
import json
import os
import shutil
import tempfile
import threading
import time
import zipfile
from pathlib import Path
from urllib.parse import quote
import httpx
from fastapi import APIRouter, HTTPException, Response, UploadFile
from fastapi.responses import StreamingResponse
from config_io import load_config
router = APIRouter() # /api 아래
public_router = APIRouter() # /pack 공개 다운로드
PACKS_PATH = Path(os.environ.get("MC_PACKS_PATH", "/data/packs.json"))
NC_URL = os.environ.get("NEXTCLOUD_URL", "http://192.168.10.10:8080").rstrip("/")
NC_USER = os.environ.get("NEXTCLOUD_USER", "")
NC_PASSWORD = os.environ.get("NEXTCLOUD_PASSWORD", "")
NC_DIR = os.environ.get("NEXTCLOUD_DIR", "/claude/mc_domain_proxy/packs").strip("/")
PUBLIC_BASE = os.environ.get("PACK_PUBLIC_BASE", "https://mc.tkrmagid.kr/pack").rstrip("/")
_lock = threading.Lock()
def _load_packs() -> dict:
if not PACKS_PATH.exists():
return {}
with PACKS_PATH.open("r", encoding="utf-8") as f:
return json.load(f)
def _save_packs(packs: dict) -> None:
PACKS_PATH.parent.mkdir(parents=True, exist_ok=True)
tmp = PACKS_PATH.with_suffix(".json.tmp")
with tmp.open("w", encoding="utf-8") as f:
json.dump(packs, f, ensure_ascii=False, indent=2)
os.replace(tmp, PACKS_PATH)
def _dav_url(*parts: str) -> str:
path = "/".join(quote(p, safe="") for p in [*NC_DIR.split("/"), *parts] if p)
return f"{NC_URL}/remote.php/dav/files/{quote(NC_USER, safe='')}/{path}"
def _client(timeout: float | None = 30.0) -> httpx.Client:
return httpx.Client(auth=(NC_USER, NC_PASSWORD), timeout=timeout)
def _require_storage() -> None:
if not NC_USER or not NC_PASSWORD:
raise HTTPException(
status_code=503,
detail="Nextcloud 계정이 설정되지 않았습니다 (NEXTCLOUD_USER / NEXTCLOUD_PASSWORD).",
)
def _ensure_dir(client: httpx.Client) -> None:
# NC_DIR 의 각 단계를 순서대로 MKCOL (이미 있으면 405)
parts = NC_DIR.split("/")
for i in range(1, len(parts) + 1):
url = f"{NC_URL}/remote.php/dav/files/{quote(NC_USER, safe='')}/" + "/".join(
quote(p, safe="") for p in parts[:i]
)
r = client.request("MKCOL", url)
if r.status_code not in (201, 405):
raise HTTPException(status_code=502, detail=f"Nextcloud 폴더 생성 실패: {r.status_code}")
def _domain_names() -> set[str]:
return {d["domain"].lower() for d in load_config().get("allowed_domains", [])}
def _pack_url(domain: str) -> str:
return f"{PUBLIC_BASE}/{quote(domain, safe='')}.zip"
@router.get("/packs")
def list_packs() -> dict:
packs = _load_packs()
items = []
for d in load_config().get("allowed_domains", []):
name = d["domain"].lower()
meta = packs.get(name)
items.append({
"domain": name,
"pack": {**meta, "url": _pack_url(name)} if meta else None,
})
return {"storage_configured": bool(NC_USER and NC_PASSWORD), "packs": items}
@router.put("/packs/{domain}")
def upload_pack(domain: str, file: UploadFile) -> dict:
_require_storage()
name = domain.strip().lower()
if name not in _domain_names():
raise HTTPException(status_code=404, detail="domain not found")
with tempfile.NamedTemporaryFile(suffix=".zip") as tmp:
sha1 = hashlib.sha1()
size = 0
while chunk := file.file.read(1024 * 1024):
sha1.update(chunk)
size += len(chunk)
tmp.write(chunk)
tmp.flush()
try:
with zipfile.ZipFile(tmp.name) as zf:
has_meta = "pack.mcmeta" in zf.namelist()
except zipfile.BadZipFile:
raise HTTPException(status_code=400, detail="zip 파일이 아닙니다.")
if not has_meta:
raise HTTPException(
status_code=400,
detail="zip 최상위에 pack.mcmeta 가 없습니다. 폴더째 압축하지 말고 폴더 안의 내용물을 압축해 주세요.",
)
with _client(timeout=None) as client:
_ensure_dir(client)
tmp.seek(0)
r = client.put(
_dav_url(f"{name}.zip"),
content=iter(lambda: tmp.read(1024 * 1024), b""),
headers={"Content-Length": str(size)},
)
if r.status_code not in (201, 204):
raise HTTPException(status_code=502, detail=f"Nextcloud 업로드 실패: {r.status_code}")
meta = {
"sha1": sha1.hexdigest(),
"size": size,
"original_name": file.filename or f"{name}.zip",
"uploaded_at": time.time(),
}
with _lock:
packs = _load_packs()
packs[name] = meta
_save_packs(packs)
return {"domain": name, "pack": {**meta, "url": _pack_url(name)}}
@router.delete("/packs/{domain}", status_code=204)
def delete_pack(domain: str) -> Response:
_require_storage()
name = domain.strip().lower()
with _lock:
packs = _load_packs()
if name not in packs:
raise HTTPException(status_code=404, detail="pack not found")
with _client() as client:
r = client.delete(_dav_url(f"{name}.zip"))
if r.status_code not in (204, 404):
raise HTTPException(status_code=502, detail=f"Nextcloud 삭제 실패: {r.status_code}")
packs.pop(name)
_save_packs(packs)
return Response(status_code=204)
@public_router.get("/pack/{filename}")
def download_pack(filename: str) -> StreamingResponse:
if not filename.endswith(".zip"):
raise HTTPException(status_code=404)
name = filename[: -len(".zip")].lower()
if name not in _load_packs() or not NC_USER:
raise HTTPException(status_code=404)
client = _client(timeout=httpx.Timeout(30.0, read=None))
upstream = client.send(client.build_request(
"GET", _dav_url(f"{name}.zip"), headers={"Accept-Encoding": "identity"}
), stream=True)
if upstream.status_code != 200:
upstream.close()
client.close()
raise HTTPException(status_code=404 if upstream.status_code == 404 else 502)
def body():
try:
yield from upstream.iter_bytes(1024 * 1024)
finally:
upstream.close()
client.close()
headers = {"Content-Disposition": f'attachment; filename="{name}.zip"'}
if "content-length" in upstream.headers:
headers["Content-Length"] = upstream.headers["content-length"]
return StreamingResponse(body(), media_type="application/zip", headers=headers)

View File

@@ -15,6 +15,13 @@ services:
container_name: mc-filter-api
expose:
- "8000"
environment:
# 리소스팩 저장소 (share.tkrmagid.kr). 비밀번호는 같은 폴더의 .env 에 둔다.
NEXTCLOUD_URL: ${NEXTCLOUD_URL:-http://192.168.10.10:8080}
NEXTCLOUD_USER: ${NEXTCLOUD_USER:-}
NEXTCLOUD_PASSWORD: ${NEXTCLOUD_PASSWORD:-}
NEXTCLOUD_DIR: ${NEXTCLOUD_DIR:-/claude/mc_domain_proxy/packs}
PACK_PUBLIC_BASE: ${PACK_PUBLIC_BASE:-https://mc.tkrmagid.kr/pack}
volumes:
- ./data:/data
restart: unless-stopped
@@ -35,6 +42,7 @@ services:
container_name: mc-filter-nginx
ports:
- "8080:80" # 대시보드 접근 포트 (외부 포트포워딩 금지 권장)
- "8081:81" # 리소스팩 공개 다운로드 전용 (/pack/ 만 응답)
depends_on:
- api
- frontend

View File

@@ -2,6 +2,7 @@ import { NavLink, Route, Routes } from 'react-router-dom'
import Dashboard from './pages/Dashboard.jsx'
import Domains from './pages/Domains.jsx'
import Logs from './pages/Logs.jsx'
import Packs from './pages/Packs.jsx'
import Settings from './pages/Settings.jsx'
export default function App() {
@@ -14,6 +15,7 @@ export default function App() {
<nav>
<NavLink to="/" end>대시보드</NavLink>
<NavLink to="/domains">허용 도메인</NavLink>
<NavLink to="/packs">리소스팩</NavLink>
<NavLink to="/logs">접속 로그</NavLink>
<NavLink to="/settings">설정</NavLink>
</nav>
@@ -23,6 +25,7 @@ export default function App() {
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/domains" element={<Domains />} />
<Route path="/packs" element={<Packs />} />
<Route path="/logs" element={<Logs />} />
<Route path="/settings" element={<Settings />} />
</Routes>

View File

@@ -38,5 +38,8 @@ export const api = {
).toString()
return req('/logs' + (q ? `?${q}` : ''), { method: 'DELETE' })
},
packs: () => req('/packs'),
deletePack: (name) =>
req(`/packs/${encodeURIComponent(name)}`, { method: 'DELETE' }),
restart: () => req('/proxy/restart', { method: 'POST' }),
}

View File

@@ -0,0 +1,147 @@
import { useEffect, useState } from 'react'
import { api } from '../api.js'
function fmtSize(n) {
if (n >= 1024 * 1024) return `${(n / 1024 / 1024).toFixed(1)} MB`
if (n >= 1024) return `${(n / 1024).toFixed(1)} KB`
return `${n} B`
}
function propsSnippet(pack) {
return [
`resource-pack=${pack.url}`,
`resource-pack-sha1=${pack.sha1}`,
'require-resource-pack=true',
].join('\n')
}
// fetch 는 업로드 진행률을 못 주므로 XHR 사용
function uploadPack(domain, file, onProgress) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open('PUT', `/api/packs/${encodeURIComponent(domain)}`)
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) onProgress(Math.round((e.loaded / e.total) * 100))
}
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) return resolve(JSON.parse(xhr.responseText))
let detail = xhr.responseText
try { detail = JSON.parse(xhr.responseText).detail ?? detail } catch { /* 원문 사용 */ }
reject(new Error(`${xhr.status}: ${detail}`))
}
xhr.onerror = () => reject(new Error('업로드 중 네트워크 오류'))
const form = new FormData()
form.append('file', file)
xhr.send(form)
})
}
export default function Packs() {
const [data, setData] = useState(null)
const [error, setError] = useState(null)
const [progress, setProgress] = useState({}) // domain -> %
const [copied, setCopied] = useState(null)
async function load() {
try {
setData(await api.packs())
setError(null)
} catch (e) {
setError(e.message)
}
}
useEffect(() => { load() }, [])
async function onFile(domain, e) {
const file = e.target.files?.[0]
e.target.value = ''
if (!file) return
setProgress((p) => ({ ...p, [domain]: 0 }))
try {
await uploadPack(domain, file, (pct) => setProgress((p) => ({ ...p, [domain]: pct })))
await load()
} catch (err) {
setError(err.message)
} finally {
setProgress((p) => { const n = { ...p }; delete n[domain]; return n })
}
}
async function remove(domain) {
if (!confirm(`${domain} 의 리소스팩을 삭제할까요?`)) return
try {
await api.deletePack(domain)
await load()
} catch (e) { setError(e.message) }
}
async function copy(domain, text) {
await navigator.clipboard.writeText(text)
setCopied(domain)
setTimeout(() => setCopied(null), 1500)
}
return (
<div>
<h1>리소스팩</h1>
{error && <div className="error">{error}</div>}
{data && !data.storage_configured && (
<div className="error">
Nextcloud 계정이 설정되지 않아 업로드할 수 없습니다. 서버의 .env 에 NEXTCLOUD_USER / NEXTCLOUD_PASSWORD 를 넣어 주세요.
</div>
)}
<p className="muted">
팩은 share.tkrmagid.kr 에 저장되고 아래 URL 로 공개됩니다. 해당 도메인이 연결된 MC 서버의
server.properties 에 설정 줄을 붙여 넣고 서버를 재시작하세요. 팩을 바꾸면 SHA1 이 바뀌므로
다시 붙여 넣어야 합니다.
</p>
{data && data.packs.length === 0 && (
<div className="card muted">등록된 도메인이 없습니다. 허용 도메인 페이지에서 먼저 추가하세요.</div>
)}
{data?.packs.map(({ domain, pack }) => {
const busy = domain in progress
return (
<section className="card" key={domain}>
<h2><code>{domain}</code></h2>
{pack ? (
<>
<div className="muted">
{pack.original_name} · {fmtSize(pack.size)} ·{' '}
{new Date(pack.uploaded_at * 1000).toLocaleString()}
</div>
<textarea readOnly rows={3} value={propsSnippet(pack)} style={{ maxWidth: '100%', fontFamily: 'ui-monospace, Consolas, monospace' }} />
</>
) : (
<div className="muted">리소스팩 없음</div>
)}
<div className="actions">
<label>
<input
type="file"
accept=".zip,application/zip"
disabled={busy || !data.storage_configured}
onChange={(e) => onFile(domain, e)}
style={{ display: 'none' }}
/>
<span className={`btn${busy || !data.storage_configured ? ' disabled' : ''}`}>
{busy ? `업로드 중… ${progress[domain]}%` : pack ? '교체 업로드' : '업로드'}
</span>
</label>
{pack && (
<>
<button className="ghost" onClick={() => copy(domain, propsSnippet(pack))}>
{copied === domain ? '복사됨' : '설정 복사'}
</button>
<button className="danger" onClick={() => remove(domain)} disabled={busy}>삭제</button>
</>
)}
</div>
</section>
)
})}
</div>
)
}

View File

@@ -156,6 +156,18 @@ button.ghost {
}
button.ghost:hover { background: var(--panel-2); filter: none; }
button.mt { margin-top: 12px; }
/* 파일 선택 label 을 버튼처럼 */
.btn {
display: inline-block;
background: var(--accent);
color: white;
padding: 8px 14px;
border-radius: 6px;
cursor: pointer;
font-weight: 500;
font-size: 14px;
}
.btn.disabled { opacity: 0.6; cursor: not-allowed; }
input:disabled { opacity: 0.7; cursor: not-allowed; }
input,

View File

@@ -3,4 +3,4 @@
# 502 가 나는 경우가 있어 image 안에 직접 포함시킨다.)
FROM nginx:alpine
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
EXPOSE 80 81

View File

@@ -23,6 +23,21 @@ http {
proxy_set_header X-Forwarded-Proto $scheme;
}
# 리소스팩 업로드: 크기 제한 없음 (Nextcloud 로 넘어가므로)
# 정규식으로 둔다: prefix "/api/packs/" 면 nginx 가 GET /api/packs 를 301 로 돌려버린다
location ~ ^/api/packs/ {
client_max_body_size 0;
proxy_request_buffering off;
proxy_read_timeout 600s;
proxy_send_timeout 600s;
proxy_pass http://mc_api;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location = /health {
proxy_pass http://mc_api;
}
@@ -38,4 +53,26 @@ http {
proxy_set_header X-Forwarded-Proto $scheme;
}
}
# 리소스팩 공개 다운로드 전용 (외부 mc.tkrmagid.kr/pack/ 이 이 포트로 연결됨).
# 대시보드/API 와 포트를 분리해서, 외부에서는 /pack/ 말고는 아무것도 닿지 않게 한다.
server {
listen 81;
server_name _;
location /pack/ {
limit_except GET HEAD { deny all; }
proxy_buffering off;
proxy_read_timeout 600s;
proxy_pass http://mc_api;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location / {
return 404;
}
}
}