Compare commits

...

62 Commits

Author SHA1 Message Date
868bee7931 perf(rp): 사진 다운로드 병렬화로 속도 개선
한 장씩 순차+딜레이(0.8s)로 느리던 사진 다운로드를 워커 풀(동시 4~8, CPU 기반)로
병렬화. 장간 고정 딜레이 제거, 음악 단계 후 쿨다운 4s→1s 로 축소. 429 는 기존
지수 백오프 재시도(images.ts)가 흡수하고, 첫 하드 실패 시 새 작업 배정을 멈춘 뒤
워커가 드레인되면 그 오류를 던진다(이어받기·취소 동작 유지). 0.4.9→0.4.10.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-20 13:54:53 +09:00
f85e0439b8 feat(server): JDK 탐색 우선순위 재정의 (.mc_custom → 환경변수 → Program Files)
요청 사양대로 탐색 순서 변경:
  ① .mc_custom/jdk(설치기 자동설치 위치)가 있으면 먼저 사용(권장이면 match, 아니면 경고)
  ② 환경변수(JAVA_HOME/JDK_HOME)가 권장 버전이면 사용
  ③ 기본 폴더 C:\Program Files\Java 에 권장 버전 있으면 사용
  ④ 없으면 환경변수 자바(없으면 Program Files 자바)로 폴백 + "권장과 다름" 경고
소스별 후보 수집 헬퍼(mcCustom/env/programFiles) 분리. 문서도 갱신. 0.4.8→0.4.9.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-17 18:35:40 +09:00
812cabd405 fix(server): 권장 JDK 상세 릴리스명 XSS escape + 문서 갱신
- 편집기 "자세히 보기" 에서 Adoptium release_name 을 escape 없이 innerHTML 에
  넣던 부분을 escHtml 처리(외부 API 값 → 관리 페이지 XSS 방지).
- docs/installer.md 의 JDK 탐색 순서/자동 설치 경로를 실제 코드(C:\Program Files\Java
  → 환경변수 → .mc_custom\jdk, 불일치 경고)와 일치하도록 갱신.

exe 산출물은 변경 없음(사이트/문서 수정) → 재빌드/재릴리스 없음.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-17 14:47:49 +09:00
fefa2dcdd2 feat(server): 권장 JDK 목록을 Adoptium 에서 동적으로 + 자세히 보기(스냅샷)
- 하드코딩 [8,11,17,21,25] 대신 Adoptium(Temurin) API 에서 실제 배포 버전을 가져와
  편집기 드롭다운을 채운다. 브라우저 CORS 차단이라 서버가 프록시:
  GET /op/jdk-versions (메이저 목록), GET /op/jdk-versions/:major (GA/EA 릴리스명).
  6h 캐시 + 네트워크 실패 시 정적 폴백.
- 편집기: 기본은 LTS(25/21/17/11/8)만 표시, "자세히 보기" 체크 시 비-LTS 메이저까지
  펼치고 선택 메이저의 GA/EA 스냅샷 릴리스명을 함께 보여준다.
- normalizeRecommendedJdk 를 고정 목록 대신 8~99 범위로 완화(동적 메이저 허용).
- 버전 0.4.7→0.4.8.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-17 14:43:55 +09:00
9d9b5183b8 feat(server): 권장 JDK 탐색을 PF/환경변수 중심으로 + 불일치 경고 + .mc_custom/jdk 설치
- JDK 탐색을 C:\Program Files\Java → 환경변수(JAVA_HOME/JDK_HOME) → 설치기
  자동설치 위치 순으로 훑어 권장 버전을 우선 선택. 권장이 없으면 가장 높은 버전을
  대신 고르되 match=false 로 표시.
- 권장과 다른 버전을 찾거나 직접 선택하면 "권장과 달라 정상 실행이 안 될 수 있음"
  경고를 띄우고, 동의(확인) 시에만 진행(무조건 차단 대신 경고+동의).
- 자동 설치 경로를 %APPDATA%/jdk → .mc_custom/jdk 로 변경(파일제거기가 함께 정리).
  Adoptium zip 의 중첩 jdk-* 폴더까지 탐색하도록 resolveJdkHome 보강.
- 버전 0.4.6→0.4.7.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-17 12:13:33 +09:00
a1d8435b71 feat(server): 사이트에서 권장 JDK 선택 + 설치기 권장 JDK 우선 탐색
- pack 에 recommendedJdk 추가(shared/types, store 정규화, 기본 25, 허용목록
  [8,11,17,21,25]). 사이트 편집기에 JDK 버전 드롭다운 추가(직접 입력 X).
- 설치기 JDK 탐색 순서 변경: ① 권장 JDK 자동설치 위치(temurin-<권장>) 우선 →
  ② 없으면 컴퓨터 JDK(JAVA_HOME/Program Files, 권장 버전 이상만 인정).
- 자동 설치/버전 검증도 pack 의 권장 버전을 사용(하드코딩 25 제거).
- 렌더러에 권장 JDK 표시, 관련 안내/문서 갱신. 버전 0.4.5→0.4.6.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-17 08:59:41 +09:00
a6118039a3 fix(server): 직접 선택한 JDK 도 Java 25+ 검증 후 진행
자동 탐색은 Java 25 미만을 걸렀지만, 사용자가 직접 입력/폴더선택한 JDK 는
버전 검증 없이 다음 단계로 넘어가 run.bat 이 낡은 자바로 패치될 수 있었다.
그러면 서버가 여전히 UnsupportedClassVersionError 로 뜨지 않는다.

- jdk:verify IPC 추가(java -version 으로 메이저 버전 확인) + preload 노출.
- JDK 단계 "다음" 에서 선택 경로를 검증해 Java 25 미만이거나 버전을 못 읽으면
  진행을 막고 안내. 자동 설치/자동 탐색 경로도 이 게이트를 통과.
- 버전 0.4.4→0.4.5.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-17 00:45:06 +09:00
48e0421135 fix(rp): 사진 다운로드 HTTP 429(속도제한) 내성 강화
증상: 리소스팩 설치기 사진 다운로드에서 "N번 사진 다운로드 실패: HTTP 429" 로
설치가 중단됨. 원인: 음악(yt-dlp) 단계가 유튜브를 많이 두드려 IP 가 일시
throttle 되고, 사진 단계는 순차이긴 하나 요청 간 간격이 없어 i.ytimg.com 429 를
유발/회복하지 못하고 첫 장부터 실패.

- 음악 단계 직후 사진 단계 시작 전 쿨다운(4s).
- 사진 요청 사이 간격(0.8s+jitter)으로 429 유발 억제.
- 재시도 5→6회, 재시도마다 로그/진행률로 대기 상태 표시(멈춘 것처럼 보이지 않게).
- 최종 실패가 429면 "잠시 뒤 다시 시도하면 이어받는다"는 안내 추가.
- 버전 0.4.3→0.4.4.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-17 00:29:23 +09:00
cf29270102 fix(server): Java 25 번들 + run.bat 이 설치기 JDK 를 쓰도록 수정
증상: 서버 실행 시 UnsupportedClassVersionError (class 69.0=Java 25 서버를
Java 17 로 실행). 원인: (1) 자동 설치 JDK 가 21 로 최신 MC(Java 25)에 부족,
(2) server:install 이 jdkPath 를 무시해 run.bat 이 시스템 PATH 의 낡은 java 사용.

- 번들 JDK 21→25(Adoptium Temurin 25). BUNDLED_JDK_MAJOR 상수로 일원화.
- jdk:detect 가 `java -version` 으로 메이저 버전을 확인해 25 미만은 "없음" 처리
  → 낡은 JAVA_HOME/시스템 자바에 걸리지 않고 자동 설치(25)로 유도.
- server:install 이 run.bat 의 `java` 실행 토큰을 설치기 JDK 의 java 로 치환.
  자동설치 JDK 는 %APPDATA% 전개형 경로라 한글 사용자명에도 안전, latin1
  라운드트립으로 기존 주석 바이트 보존.
- 안내 문구/문서(Java 25), 버전 0.4.2→0.4.3.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-17 00:11:50 +09:00
10362e204a fix(installer): 약관 본문 로드 실패 시 동의 차단 + 다시 시도
로드 실패 경로에서 markReadable()로 체크박스가 활성화돼, 약관을 못 본 채로
동의할 수 있던 문제 수정. termLoaded 플래그를 두어 본문이 정상 로드된 뒤에만
동의 체크를 허용하고, 실패 시에는 체크/다음을 막고 "다시 시도" 버튼만 노출.
installer / installer-rp 동일 적용. 버전 0.4.1 → 0.4.2.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-16 00:09:51 +09:00
3f553f958d feat(installer): 약관을 한 건씩 페이지로 — 개별 동의 + 상단 스크롤 + 끝까지 읽기 강제
- "위 모든 약관에 동의합니다" 통합 체크(탭 방식)를 약관별 페이지 흐름으로 변경.
  각 약관마다 "해당 약관에 동의합니다" 체크박스, [다음] 이면 다음 약관 페이지로.
- 다음 약관을 보여줄 때 화면(pageHost)을 맨 위로 스크롤해 처음부터 읽게 함.
- 본문을 끝까지 내려 읽어야 동의 체크가 활성화(짧아서 스크롤 불필요하면 즉시 허용).
  뒤로/앞으로 이동 시 이전 동의 상태 유지.
- installer / installer-rp 양쪽 적용, 로케일 키(agreeThis/readToBottom/stepLabel) 추가.
- 버전 0.4.0 → 0.4.1.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-15 23:54:10 +09:00
996a7cc03e feat(installer): v0.4.0 — 파일제거기, 커스텀 폴더명, 포트포워딩 개편, 이름/개발자용 표기
- 음악퀴즈 파일제거 도구 신규 추가: 동의 → 휴지통/완전삭제 선택 → 커스텀 폴더
  (현재값 + 기본 .mc_custom) 전체, 데스크톱 바로가기, gameDir 가 해당 폴더인
  마인크래프트 런처 프로필 정리.
- MC_CUSTOM_DIR .env 로 커스텀 게임 폴더 이름 유동화(.mc_custom 기본). 렌더러
  사전에도 실제 폴더명 반영.
- 간편포트포워딩: 실행 중 UPnP 매핑 유지, 창 닫힘/종료 시 자동 제거(activePort 추적).
- 개발자용 빌드는 창/헤더 제목 앞에 (개발자용) 표기, exe 이름에도 반영.
- exe 이름 변경: 음악퀴즈 간편설치기 / 음악퀴즈 리소스팩설치기 / 간편포트포워딩.
- README 및 .env 템플릿 갱신, 버전 0.3.23 → 0.4.0.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-15 23:21:46 +09:00
00aa47ed17 feat(installer): record EULA acceptance timestamp in eula.txt
Write an ISO 8601 "# EULA accepted at: <time>" comment when the user
accepts the EULA, so the agreement time is captured alongside eula=true.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-15 22:29:07 +09:00
9c2a92c101 docs: align account section with account.local.json + scrypt reality
The 계정 section still described account.json as the account store and
scrypt hashing as future work; both are now implemented. Point it at the
gitignored account.local.json (0600) seed/scrypt flow, consistent with the
migration section below.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-12 01:06:05 +09:00
662c3c7b23 docs+comment: pin account.json untrack-after-redeploy TODO
추적 해제는 코드 작업이 아니라 사용자의 1회 재배포에 게이트된 운영 절차이므로,
잊히지 않도록 명시적 TODO 를 코드(paths.ts) + 운영 문서(admin-site.md)에 고정.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-11 13:31:50 +09:00
face70b3e9 security: env-gate trust proxy, 0600 account file, seed+template for account.json untrack
리뷰 지적 추가 반영(서버 전용).
- trust proxy 를 항상 켜던 것을 TRUST_PROXY=true 일 때만 켜도록 변경. 직접 노출
  시 X-Forwarded-For 조작으로 로그인 rate limit 을 우회하던 문제 차단(프록시 뒤면
  TRUST_PROXY=true 설정).
- account.local.json 을 0o600(소유자 전용)으로 저장.
- 서버 시작 시 account.local.json 이 없으면 account.json 에서 시드(0o600). 이렇게
  하면 재배포 직후(로그인 전에도) 로컬 계정 파일이 항상 존재해, 이후 account.json
  을 안전하게 추적 해제할 수 있다.
- account.example.json 템플릿 추가.

account.json 자체의 git 추적 해제는 서버가 한 번 재배포되어 account.local.json 이
생성된 뒤 후속 커밋에서 처리(그 전에 지우면 pull 시 삭제되어 로그인이 막힘).

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-07-11 13:27:32 +09:00
651c63faa6 security: revert auto-upgrade failure logging (keep silent per request)
사용자 요청으로 평문→해시 자동 업그레이드 저장 실패 시 console.error 로그를
원래대로 조용한 catch 로 되돌림. 나머지 보안 개선(로그인 rate-limit,
account.local.json 분리, secure 쿠키 옵션)은 유지.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-07-11 13:23:17 +09:00
f392842d7f security: login rate-limit, gitignored account store, secure cookie opt, upgrade-fail log
리뷰 지적 4건 반영(서버 전용, exe 영향 없음).
- 로그인 IP 기준 실패 제한(15분 창 10회 → 15분 차단). 브루트포스 + scrypt CPU
  남용 방지. 인메모리, 무한 성장 가드 포함.
- 운영 계정을 gitignore 된 account.local.json 으로 이전. readAccounts 는 local
  우선, 없으면 추적되는 account.json 을 시드로 읽음. writeAccounts 는 local 에만
  기록 → 첫 로그인 자동 해시 업그레이드부터는 추적 평문 파일을 더 쓰지 않음.
  (account.json 을 git rm --cached 하면 서버 pull 시 삭제되는 위험이 있어 추적 자체는
  건드리지 않고, 실질 사용 파일만 분리.)
- 세션 쿠키 secure 를 SESSION_COOKIE_SECURE=true 로 켤 수 있게(HTTPS 배포용).
- 평문→해시 자동 업그레이드 저장 실패를 조용히 무시하지 않고 console.error 로 기록.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-07-11 12:31:34 +09:00
00344084c7 security: hash operator passwords (scrypt) + persistent session secret
- 운영자 로그인 비밀번호를 평문 비교(===)에서 Node 내장 scrypt 해시 + 상수시간
  비교(verifyPassword)로 전환. 새 파일 src/server/password.ts. 기존 account.json
  의 평문 비밀번호는 그대로 검증되며, 로그인 성공 시 scrypt 해시로 자동 업그레이드
  후 저장(writeAccounts 추가). 외부 의존성 없음.
- 세션 시크릿을 하드코딩 폴백('...dev-secret') 대신, 환경변수 우선 → 없으면
  .session-secret 파일에 영구 랜덤값 생성/보관하도록 변경(세션 위조 방지, 재시작
  후에도 세션 유지). .session-secret 은 .gitignore 에 추가.

서버(사이트) 전용 변경이라 설치기 exe 는 영향 없음(재빌드 불필요).

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-07-11 12:24:42 +09:00
704d58d3ac optimize: crash guard, yt-dlp url validation, dead-key cleanup
전체 코드 재검토 기반의 안전한 개선 1차 배치.
- 메인 설치기에 전역 uncaughtException/unhandledRejection 가드 추가. nat-upnp
  (detectExternalIpUpnp)의 비동기 소켓 오류로 앱이 조용히 종료되던 잠재 크래시
  방지(포트포워딩 도구 v0.3.18 과 동일 대비).
- 서버: fetchVideoMeta/fetchPlaylistEntries 에 http(s) URL 검증 추가(운영자 입력이
  yt-dlp 플래그로 오인되는 인자 주입 차단). /file/mods/:folder/index.json 의 async
  throw → next(error) 로 위임(unhandledRejection 방지). index 라우트 pack 정의
  병렬 로드.
- 죽은 i18n 키 정리: installer 로케일의 UPnP/run.bat 관련 19개 + pf 로케일 2개
  제거(코드에서 미참조 확인). 크래시 가드용 log.internalError, youtube.invalidUrl 추가.
v0.3.23.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-07-11 12:10:55 +09:00
2212195b3c installer: add big 'close Minecraft & launcher' notice after pack select
퀴즈팩 선택(step1) 직후, 약관 동의 진입 전에 "마인크래프트와 마인크래프트 런처를
종료한 뒤 진행해주세요"를 큰 글씨의 강조 카드(빨강 테두리 + 매우 중요 배지)로
표시하는 페이지 추가(renderCloseNotice). 이전/다음 버튼 제공. v0.3.22.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-07-11 11:23:33 +09:00
2fa1173b8e installer: stop injecting UPnP auto-open into run.bat (check-only)
리뷰 반영. 포트포워딩 페이지를 check-only 로 바꾼 것과 정합성을 맞춰, 서버 설치
시 run.bat 에 UPnP 자동 등록/해제를 주입하던 로직(injectUpnpToRunBat)을 제거.
이제 설치기는 포트를 직접 열지 않고, 사용자가 수동 포워딩 후 페이지에서 확인만
한다. v0.3.21.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-07-11 00:50:37 +09:00
7b532d6520 feat: per-pack public flag + developer installer variants
manifest.json 의 각 pack 에 public(boolean) 을 추가하고, 대상(audience)별로
설치기를 구분한다.
- ManifestEntry.public 추가. 미지정=공개(하위호환). store 가 upsert/rename 시
  기존 public 보존, 신규 pack 은 public=true 기본. setPackPublic() 추가.
- 사이트 pack 편집기에 "공개" 체크박스 추가(체크=일반, 해제=개발자용). 저장 시
  manifest 엔트리 public 갱신, 편집기 진입 시 현재 값 표시.
- shared/audience.ts: 빌드의 musicQuizAudience(package.json)로 대상 판별.
  일반 설치기=public!==false 만, 개발자용=public===false 만 노출.
- 간편/리소스팩 설치기 packs 로드에서 audience 필터 적용.
- 개발자용 빌드 구성(electron-builder-dev.yml, electron-builder-rp-dev.yml)과
  dist:win:dev / dist:win:rp:dev 스크립트 추가(artifact: *-Dev-*). v0.3.20.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-07-11 00:32:06 +09:00
f0e07e06d6 installer: port page = check-only (no auto-open), big open/notOpen message
요청 반영: 간편설치기 포트포워딩 페이지가 포트를 직접 열지 않고 "열려 있는지"만
확인한다.
- server:portForward 를 UPnP 자동 개방/재점검 없이 외부 도달 점검만 하도록 변경,
  결과를 open/notOpen 으로 반환(PortForwardResult status 타입도 변경).
- 열려 있으면 외부 접속 주소를 크게, 안 열려 있으면 "직접 포트포워딩 해주세요"
  를 크게 표시.
- 페이지 체크에서만 쓰이던 openPortViaUpnp/removeUpnpMapping 제거(고아 코드).
- 참고: 서버 기동 시 run.bat 의 UPnP 자동 개방 주입(injectUpnpToRunBat)은 이번엔
  유지. v0.3.19.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-07-11 00:12:55 +09:00
281dbb644b installer-pf: prevent app from dying on nat-upnp async errors
라우터가 UPnP 를 거부(ECONNREFUSED)하는 환경에서 nat-upnp 가 콜백 밖에서
비동기 소켓 오류를 내면 Electron 메인이 종료돼 창이 갑자기 닫히는("오류나면서
끝남") 현상이 생길 수 있다. v0.3.17 에서 CGNAT 판별용으로 externalIp() 를 항상
호출하게 되면서 이 경로가 새로 노출됨. process 전역 uncaughtException/
unhandledRejection 가드로 잡아 로그만 남기고 앱은 계속 살려 둔다(각 UPnP 호출은
타임아웃으로 진행되므로 멈추지 않음). v0.3.18.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-07-05 22:32:20 +09:00
005c7bf44c installer-pf: accurate CGNAT detection via router WAN vs public IP
리뷰 지적 반영. 기존엔 HTTP 공인 egress IP 만 100.64/10 검사라, 전형적 CGNAT
(egress 는 ISP 공인, 라우터 WAN 만 100.64)을 놓치고 "CGNAT 아님"처럼 오진 가능.
- 라우터 WAN(IGD 외부) IP 를 UPnP 로 조회해 HTTP 공인 IP 와 비교.
- cgnat 를 3-state(yes/no/unknown)로: WAN 이 사설/CGNAT 이거나 공인 IP 와 다르면
  yes, 같으면 no, WAN 못 읽으면 unknown.
- unknown 이면 "외부 IP만으론 CGNAT 확정/배제 불가, 라우터 WAN 확인" 안내.
- WAN 조회 타임아웃 8s→6s. v0.3.17.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-07-05 21:26:13 +09:00
05a5dcedc0 installer-pf: guide manual forwarding + detect CGNAT on failure
포트포워딩 도구가 실패/확인불가일 때 다음 조치를 바로 안내하도록 보강.
- 이 PC LAN IPv4 자동 감지 → "외부 TCP {port} → {localIp}:{port} 수동 포워딩 +
  Windows 방화벽 인바운드 허용" 안내.
- 외부 IP 가 CGNAT(100.64/10) 대역이면 경고(공유기 포워딩만으론 불가).
- UPnP 가 ECONNREFUSED/타임아웃이면 "라우터 UPnP 거부/미지원" 로그 힌트.
실제 사용자 로그(라우터 UPnP ECONNREFUSED, 공인 IP, ifconfig false)에 기반한
개선. v0.3.16.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-07-05 21:13:19 +09:00
86883f56e4 add standalone port-forwarding tool (마인크래프트 간편 포트포워딩)
포트포워딩만 단독으로 수행하는 세 번째 Electron 앱 추가.
- 포트 입력(기본 25565) → UPnP 개방 시도 → 외부에서 닿는지 점검(ifconfig.co
  + 임시 리스너) → 외부 접속 주소/성공·실패·확인불가 안내. '포트 닫기'로 매핑 제거.
- 점검 로직은 메인 설치기의 v0.3.14 오탐 수정(ifconfig 실패→확인불가)을 반영해
  자체 포함. sharp 미사용이라 빌드에서 제외(exe 약 73MB).
- 신규: src/installer-pf/{main,preload}.ts, installer-pf/{index.html,renderer.js},
  locales/installer-pf/ko-kr.json, tsconfig.installer-pf.json, electron-builder-pf.yml.
- package.json 에 installer:pf / dist:win:pf 스크립트, i18n 컴포넌트 유니온에
  'installer-pf' 추가. v0.3.15.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-06-24 21:43:06 +09:00
f554559be9 installer: stop treating ifconfig.co failure as 'port closed'
포트 1차 점검(probePortFromOutside) 오탐 수정.
- 임시 리스너에 인바운드가 안 왔다는 이유만으로 false(닫힘) 단정하던 로직 제거.
  ifconfig.co 가 타임아웃/레이트리밋으로 실패하면 외부에서 연결 시도 자체가
  없었던 것이라 '리스너 미도달'은 무의미하고, 인바운드 수신 주체가 마크 서버가
  아니라 설치기 프로세스라 Windows 방화벽이 설치기만 막아도 미도달이 된다.
  외부 판정이 없으면 reachable=null(확인 불가)로 남겨 UPnP 시도/안내로 넘긴다.
- ifconfig.co 일시 실패 대비 1회 재시도 추가(fetchIfconfigCoPortOnce + 래퍼).
v0.3.14.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-06-24 21:24:12 +09:00
8c0226d3f9 installer: fix UPnP PowerShell parse error (^| -> | inside quotes)
run.bat 의 UPnP 등록/해제 PowerShell 명령에서 파이프를 cmd식 ^| 로
이스케이프했는데, 이 파이프는 powershell -Command "..." 의 큰따옴표 안이라
cmd 가 이미 리터럴로 넘긴다. 그래서 PowerShell 이 ^ 를 "예기치 않은 토큰"
으로 파싱 실패(서버는 정상 기동하나 콘솔에 에러 출력, UPnP 매핑도 실패).
^| -> | 로 교정. for/f 의 2^>nul(=cmd 레벨 리다이렉트)은 그대로 유지. v0.3.13.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-06-24 17:09:39 +09:00
674b9e7c87 installers: add intro notice (main) and finish notice (rp)
- 메인 설치기: 첫 페이지로 "마인크래프트 런처를 끄고 시작해주세요" 안내(renderIntro)
  추가 후 다음 버튼으로 step1 진입.
- 리소스팩 설치기: 완료(step3) 페이지 문구를 "사용자 동의하에 리소스팩이
  설치되었습니다." + "리소스팩은 직접 적용해주세요." 로 변경.
v0.3.12.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-06-23 23:02:38 +09:00
4a76c09f3a installer: brighten agreement text (white→pure white, gray→white)
약관 본문(.agreementBody) 글자색을 더 진하게: 제목/굵은글씨/목록은 순백(#fff),
회색이던 문단(.page p 상속)은 이전 흰색 톤(#e6edf3)으로 올림. 두 설치기가
공유하는 installer/styles.css 변경. v0.3.11.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-06-23 22:54:51 +09:00
48aec4e144 site: add video field and set volume default 0.5 in datapack SNBT
곡 SNBT 출력을 {volume:0.5, title, author, alias, description, video} 형식으로
변경(요청). video = MusicListEntry.url(유튜브 영상 주소). volume 기본값을
1.0 → 0.5 로 변경. 헤더 안내 주석도 새 형식에 맞춤.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-06-14 01:39:55 +09:00
21eadb3b20 site: reorder datapack SNBT fields to volume-first
데이터팩 songs.mcfunction 의 곡 SNBT 출력 순서를
{volume, title, author, alias, description} 로 변경(요청). volume 기본값은
1.0 유지. SNBT 는 키 순서 무관이라 데이터팩 파싱에는 영향 없음.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-06-14 01:35:59 +09:00
fa5da6d052 installer-rp: fix ffmpeg 404 by using rolling 'latest' tag URL
BtbN/FFmpeg-Builds 다운로드를 releases/latest/download/ (GitHub 최신 릴리스
자동 포인터)에서 releases/download/latest/ (항상 최신 자산이 붙은 롤링 latest
태그)로 변경. 전자는 갓 생성된 autobuild-<날짜> 릴리스로 리다이렉트되는데
자산이 아직/없으면 HTTP 404 로 ffmpeg 설치가 실패한다. v0.3.10.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-06-07 23:54:18 +09:00
f6df5f936c installer-rp: retry image download on HTTP 429/5xx with backoff
i.ytimg.com 썸네일 서버가 연속 요청을 속도제한(HTTP 429)하면 사진
다운로드가 즉시 실패해 전체 설치가 중단됐다. 일시적 상태코드
(408/425/429/5xx)와 네트워크 오류를 Retry-After 우선 + 지수 백오프(jitter)로
최대 5회 재시도하도록 fetchBuffer 를 보강. v0.3.9.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-06-07 23:36:30 +09:00
dfb7acba2f installer: use 128x128 launcher profile icon (correct spec)
마인크래프트 런처 사용자 지정 설치 아이콘 규격은 128x128 PNG 고정이다
(minecraft.wiki/w/Launcher). 64x64/256x256 등 규격과 다른 크기는 런처가
무시하고 기본 아이콘(화로)으로 폴백한다. ICON_SIZE 를 128 로 맞춰 음악
아이콘이 실제로 표시되게 한다. v0.3.8.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-06-07 23:04:34 +09:00
f4c9504c1a installer: shrink launcher profile icon to 64x64 data URL
256x256(~44KB base64) 아이콘은 일부 마인크래프트 런처에서 렌더링되지 않고
기본 아이콘(화로)으로 폴백한다. 프로필 아이콘은 작은 타일로 표시되므로
sharp 로 64x64(~8KB base64) 로 다운스케일해 안정적으로 표시되게 한다.
exe 아이콘(build/icon.*)은 256x256 그대로 유지. v0.3.7.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-06-07 22:54:48 +09:00
60a52a9bec installer-rp: delete partial artifacts on failure; bump to 0.3.6
Resume previously skipped any track/cover whose file merely existed, so a
partially written NN.ogg or cover_NN.png from a failed download/convert
could be mistaken for a finished file on the next attempt. Now the
failure path removes the expected output before bailing, so only fully
completed artifacts are skipped on resume.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-06-05 16:30:45 +09:00
fe0d2f75e3 installer-rp: add resume-on-retry and discard-on-quit for failed installs
On install failure the temp folder is now preserved instead of wiped, so
already-downloaded songs/images are skipped on the next attempt. The
error screen offers 재시도 (resume from the failed item) and 처음으로
(discard the partial download and restart). Closing the program without
retrying still wipes the partial download via window-all-closed, and an
explicit cancel also clears it.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-06-05 16:23:34 +09:00
399f4af808 installer-rp: defer yt-dlp/ffmpeg reinstall until all music workers finish
Avoid the Windows file-lock race where one worker deletes/overwrites
yt-dlp.exe/ffmpeg.exe while sibling workers still run those processes.
Now pass 1 downloads all tracks and collects failures without any
mid-flight refresh; after Promise.all (no live child processes), the
binaries are force-reinstalled once and only the failed tracks retry.

Co-Authored-By: Claude Opus 4 <noreply@anthropic.com>
2026-06-05 16:18:12 +09:00
d5f88e0e76 yt-dlp/ffmpeg: reinstall latest on failure, retry once
오래된 yt-dlp/ffmpeg 가 유튜브 변경을 못 따라가 다운로드가 실패할 때
최신 버전으로 강제 재설치 후 한 번 더 시도한다.

- server youtube.ts: ensureYtDlp(force) 추가(캐시·zipapp 삭제 후 최신 재다운로드).
  fetchVideoMeta/fetchPlaylistEntries 를 runYtDlp 로 묶어 1차 실패 시
  강제 재설치 후 재시도.
- installer ytdlp.ts/ffmpeg.ts: ensure*Exe(log, force) 추가.
- installer main.ts: 음악 워커가 곡 다운로드 실패 시 전역 1회 강제 재설치
  (refreshBinariesOnce) 후 해당 곡을 1회 재시도.
2026-06-05 16:08:26 +09:00
d9ba2b0f35 installer-rp: decode data: URL images instead of crashing
사진 URL 에 data: URI 가 들어오면 http/https 만 처리하는 다운로더가
'Protocol "data:" not supported' 로 설치 전체를 중단시키던 문제 수정.
data: URL 은 이미지 바이트를 직접 품고 있으므로 base64/percent-encoding
을 디코드해 Buffer 로 바로 반환한다. 잘못된 형식은 명확한 메시지로 거절.
2026-06-05 15:58:22 +09:00
3baf84cfd1 op: emit painting_variant author/title as plain strings
이미지 zip 의 cover_NN.json 이 title/author 를 {text:...} 객체로 내보내
일부 환경에서 인식되지 않던 문제. 요청 형식대로 author:"musicquiz",
title:"cover_NN" 평문 문자열로 바꿔 asset_id/width/height 뒤에 배치한다.
2026-06-05 15:51:59 +09:00
d22c6f17a3 store: rename file/list JSON when pack key changes
renamePack 가 manifest 정의와 약관 폴더는 새 키로 옮기면서 정작 음악·사진
목록(file/list/<key>.json)은 옛 키 파일에 남겨, 이름 변경 후 목록이 비어
보이던 버그 수정. 약관 폴더와 동일하게 fsp.rename 으로 옮기고 옛 파일이
없으면(ENOENT) 무시한다.
2026-06-05 01:57:30 +09:00
0629aa54aa datapack: emit volume:1.0 default on every SNBT entry
운영자가 곡별로 /playsound 음량을 빠르게 조정할 수 있도록
launcher 가 생성하는 모든 SNBT 항목에 volume:1.0 기본값을 항상 넣는다.
주석의 예시도 volume:1.0 으로 통일.
2026-05-28 00:37:37 +09:00
201043e289 datapack: include description in SNBT entry output
entrySnbt() now emits {title, author, alias, description} so the
mcfunction export carries the operator-entered song description
into the data modify storage command. Multiline descriptions are
flattened via newline/tab escapes inside the SNBT string literal
(escapeSnbtString extended to handle \r, \n, \t alongside the
existing backslash + quote escapes) so each `data modify` stays a
single line.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-28 00:28:37 +09:00
acd3dd995d list-editor: preserve aliases + description across URL edit
The url-edit modal's save handler was rebuilding state.music[idx]
from scratch using only meta-lookup fields, silently dropping aliases
and (newly added) description. Carry them over from prev so editing
a track's URL no longer wipes operator-entered metadata.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-27 20:48:55 +09:00
b4160aefc1 list-editor: add per-track description button + modal
Each music list row now shows a 설명 button immediately to the left of
the 별칭 button. Click opens a modal with a multi-line textarea; on
close the value is persisted into MusicListEntry.description and saved
to the same pack list JSON. The button gets a hasDesc visual indicator
when filled. Description is stored but intentionally not consumed by
datapack export or alias matching — purely informational metadata.

- types.ts: add description: string to MusicListEntry
- store.ts: normalize entry.description via sanitizeStr (defaults to '')
- listEditor.ejs: new #descModal alongside aliasModal
- listEditor.js: render descBtn left of aliasBtn, attach handlers,
  also set description: '' on playlist-fetched entries
- styles.css: extend trackRow grid to 6 cols, reuse aliasBtn styling
  for descBtn, add descTextarea sizing
- locale (ko-kr): descBtn / descModalTitle / descBack / descPlaceholder
  / descHint

Backwards-compatible: existing list JSON files without description
field normalize to ''.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-27 20:44:24 +09:00
1ac13a03ff server-youtube: fast-path reuse for cached zipapp
ensureYtDlp() and prepareYtDlp() now check the on-disk yt-dlp_zipapp
before re-running the native-fail -> network-download path. On Linux
servers where the native binary always fails verification (glibc/musl/
arch mismatch), every previous request was re-downloading both the
native (~33MB) and the zipapp (~3MB). With the fast path, after the
first successful zipapp install all subsequent requests short-circuit
to the cached zipapp.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 16:39:10 +09:00
542f759585 chore: remove stray 0-byte garbage file from repo root
Accidentally tracked by the previous commit's git add -A. Untracked
artifact from shell-command mangling in an earlier smoke test, not
part of any feature.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 16:35:30 +09:00
3248d096e4 server-youtube: add POSIX zipapp fallback when native bundled binary won't run
If the native yt-dlp_linux/yt-dlp_macos binary fails to execute (glibc
mismatch, musl libc, wrong arch) AND no system yt-dlp is on PATH, fall
back to downloading the universal Python zipapp ('yt-dlp', ~3MB) and
running it via shebang. Requires python3 on PATH, which is standard on
modern Linux servers. Also: rewrite stale Windows-flavored install-path
comments to reflect actual cross-platform behavior.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 16:35:11 +09:00
8c9dc88e8b server-youtube: strip Zone.Identifier ADS on Windows after download
NTFS marks files downloaded over HTTP with a Zone.Identifier alternate
data stream, which SmartScreen/Attachment Manager can use to block
execution of yt-dlp.exe. Remove the ADS best-effort after each
download to reduce one likely cause of "execution verification failed"
in the user-reported failure.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 16:29:27 +09:00
b769f453a3 server-youtube: diagnostic detail + PATH fallback when bundled yt-dlp won't run
probeVersion() now captures stderr/exit-code/signal/spawn-error instead of
returning a bare boolean, and ensureYtDlp() tries the bundled binary first,
falls back to `yt-dlp(.exe)` on PATH if the bundled one won't execute (AV
block, missing libc symbol, broken download), and only then re-downloads.
The final user-facing error includes the per-attempt diagnostics so we can
actually see WHY verification failed instead of the opaque
"yt-dlp 다운로드는 됐지만 실행 검증에 실패했습니다." message.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 16:24:54 +09:00
5c13648f63 rp-pack: fail-fast on base track/painting collision (was: silent skip)
Reviewer correctly flagged that the previous skip-on-collision
behavior silently drops new quiz tracks when the base resourcepack
already has the same track_NN key. That makes the install LOOK
successful but breaks the quiz at runtime (datapack references the
missing track).

The new behavior throws a clear error explaining which key collided
and what the user must do (remove the conflicting base entry, or
use a different base). The base assets are still preserved (we
never overwrite); we just refuse to build a broken pack.

Removed the now-unused skip-summary log keys.
2026-05-23 17:26:41 +09:00
9efd4a696a rp-pack: never overwrite base resourcepack sounds/paintings (v0.3.5)
If the base resourcepack already has audio files under
assets/musicquiz/sounds/ or entries in assets/musicquiz/sounds.json,
the build now PRESERVES them and skips any new track that would
collide. Same policy for painting textures: existing cover_*.png
in the base are not overwritten by new ones.

Per-track collision is logged so the user can see exactly what was
preserved and what was skipped. Summary counts (added / skipped)
are also logged.

Requested by 사금향: "기존에 있는걸 삭제하거나 이상하게 엎어쓰지
말것" — preserve base assets unconditionally.
2026-05-23 17:18:46 +09:00
c580a50fd4 installer: escape agreement tab labels (XSS hardening)
RP installer already escapes k.tab; main installer was injecting it raw.
Add escapeHtml helper and apply to tab id/label so admin-supplied
agreement labels can't break the HTML.
2026-05-20 10:29:06 +09:00
38df72e4f6 terms: phrase agreement-list failure as install failure (per request)
User asked for "약관 표시 실패시 설치 실패로 처리". The block-on-failure path
is already in place; this just sharpens the message so users see "설치를
진행할 수 없습니다" rather than a soft retry prompt.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-20 10:22:02 +09:00
6447b1cb78 terms: block install on terms list fetch failure (retry UI)
Reviewer caught that v0.3.4 was bypassing the agreement step entirely on
network/server errors, letting users install without ever seeing terms.
Now only the explicit empty-list response (terms:[]) skips the step.
Network errors, 404s, and IPC failures render an error page with Back/Retry
buttons; no next button is exposed.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-20 10:20:49 +09:00
9ba5dc6b7b terms: per-term installer visibility toggles + universal delete (v0.3.4)
- _meta.json: customLabels -> terms.{label,showInInstaller,showInInstallerRp}
- Drop builtin protection; any term kind can be deleted/added/toggled
- New public route /manifest/terms/<pack>/index.json for installer term lists
- Installers fetch terms:list dynamically; skip agreement step if list empty
- Term editor: 2 visibility checkboxes (설치기 / 리소스팩 설치기), multi-select
- Migration from old schema preserves custom labels (default: visible in both)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-20 10:14:42 +09:00
05dc9d7166 terms: seed-on-fetch + rename/delete sync (v0.3.3)
- public route `/manifest/terms/:packKey/:fileName` 가 sendFile 전에
  `ensurePackTermsDir(packKey)` 를 호출하도록 수정. 관리자가 사이트 약관
  페이지를 한 번도 열지 않은 fresh 배포에서도 설치기가 정상적으로 약관을
  받을 수 있다. `loadPackDefinition` 으로 실제 pack 만 허용해 임의 키로
  빈 폴더가 생성되는 것을 차단.
- `renamePack`: pack JSON 이름이 바뀌면 `manifest/terms/<oldKey>/` 도
  `<newKey>/` 로 함께 rename.
- `deletePackKeys`: pack 삭제 시 약관 폴더도 `fs.rm` 으로 정리 — 동일 key
  재생성 시 옛 약관 부활 방지.
- `ensurePackTermsDir` export.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-20 01:39:28 +09:00
25977d894b terms: per-pack storage + import from another pack (v0.3.2)
- store.ts: 약관을 manifest/terms/<packKey>/ 폴더별로 저장. 첫 접근 시
  legacy 전역 .md 파일을 시드로 자동 복사한다.
- importTerms() 추가: 다른 음악퀴즈의 .md + _meta.json 을 현재 pack 으로
  복사한다. 동일 kind 는 source 값으로 덮어쓴다.
- /op/agreement 라우트를 세 단계로 분리:
  · /op/agreement → 음악퀴즈 카드 선택 페이지
  · /op/agreement/:packName → 해당 pack 의 약관 목록 + 추가 + 불러오기
  · /op/agreement/:packName/:kind → 에디터
- 공개 라우트도 /manifest/terms/:packKey/:fileName 으로 변경.
- 설치기 main.ts: state.selectedKey 를 약관 URL 에 포함하도록 수정 (메인 +
  rp 양쪽). pack 미선택 상태에서는 에러 반환.
- termsEditor.js: PACK_KEY 를 받아 저장 URL 에 포함.
- 다른 음악퀴즈 후보 select + 확인 모달 + locale 추가.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-20 01:29:04 +09:00
63 changed files with 4614 additions and 916 deletions

View File

@@ -31,6 +31,14 @@ SITE_BASE_URL=https://mq.example.com
# 특별히 다른 경로를 쓰고 싶을 때만 아래를 풀어서 우선 적용시키세요.
# MANIFEST_URL=https://mq.example.com/manifest.json
# ----- 커스텀 게임 폴더 이름 -----
# 음악퀴즈 전용 게임/캐시 폴더의 이름. %APPDATA% 바로 아래에 이 이름으로 생성됩니다.
# 비워두면 기본값 `.mc_custom` 을 사용합니다. 경로 구분자(/ \)와 `..` 는 무시됩니다.
# 설치기·리소스팩설치기·파일제거기가 모두 이 값을 공유하므로, 값을 바꾸면
# 세 exe 를 같은 값으로 다시 빌드해야 서로 같은 폴더를 가리킵니다.
# MC_CUSTOM_DIR=.mc_custom
# ----- 리소스팩 설치기 -----
# yt-dlp 동시 다운로드 수(1~8). 비워두면 CPU 코어 수로 자동 결정.

View File

@@ -27,6 +27,12 @@ SITE_BASE_URL=http://127.0.0.1:3000
# 특별히 다른 경로를 쓰고 싶을 때만 아래를 풀어서 우선 적용시키세요.
# MANIFEST_URL=http://127.0.0.1:3000/manifest.json
# ----- 커스텀 게임 폴더 이름 -----
# 음악퀴즈 전용 게임/캐시 폴더의 이름. %APPDATA% 바로 아래에 이 이름으로 생성됩니다.
# 비워두면 기본값 `.mc_custom` 을 사용합니다. 경로 구분자(/ \)와 `..` 는 무시됩니다.
# MC_CUSTOM_DIR=.mc_custom
# ----- 리소스팩 설치기 -----
# yt-dlp 동시 다운로드 수(1~8). 비워두면 CPU 코어 수로 자동 결정.

4
.gitignore vendored
View File

@@ -7,3 +7,7 @@ conversations/
.env
.env.local
.env.*.local
# 세션 서명용 자동 생성 시크릿. 절대 커밋 금지.
.session-secret
# 운영 계정(해시 비밀번호) 파일. 추적되는 account.json 대신 이 파일을 사용. 커밋 금지.
account.local.json

View File

@@ -5,6 +5,8 @@
- **관리 사이트** — 음악퀴즈 정보(JSON)와 음악·사진 목록, 데이터팩 출력을 한 곳에서 운영.
- **음악퀴즈 간편설치기 (`.exe`)** — `manifest.json` 기반으로 사용자가 마인크래프트 본체·서버·모드를 자동 설치.
- **리소스팩 간편설치기 (`.exe`)** — 음악퀴즈 음악·표지를 yt-dlp 로 받아 painting variant 텍스처 리소스팩으로 패키징.
- **간편포트포워딩 (`.exe`)** — 원하는 포트를 입력해 UPnP 로 개방. 프로그램을 켜 두는 동안만 열려 있고 창을 닫으면 자동으로 닫힙니다.
- **음악퀴즈 파일제거 (`.exe`)** — 설치기들이 만든 게임 폴더·캐시와 런처 프로필을 휴지통 이동 또는 완전 삭제로 한 번에 정리.
---
@@ -15,7 +17,9 @@
| `src/server/` | 음악퀴즈 관리 웹사이트 (Express + EJS) | `bun start` 또는 `npm start` |
| `src/installer/` | 음악퀴즈 간편설치기 (Electron) | `npm run installer` |
| `src/installer-rp/` | 리소스팩 간편설치기 (Electron) | `npm run installer:rp` |
| `src/shared/` | 두 설치기와 서버가 공유하는 타입·스토어 | — |
| `src/installer-pf/` | 간편포트포워딩 도구 (Electron) | `npm run installer:pf` |
| `src/installer-uninstall/` | 음악퀴즈 파일제거 도구 (Electron) | `npm run installer:uninstall` |
| `src/shared/` | 설치기들과 서버가 공유하는 타입·스토어 | — |
| `views/` | EJS 템플릿 (관리 사이트) | — |
| `manifest/` | 음악퀴즈별 정의 JSON | — |
| `file/list/` | 음악퀴즈별 음악·사진 목록 JSON | — |
@@ -43,6 +47,8 @@
이렇게 분리해 두면 사용자가 평소 쓰던 마인크래프트와 음악퀴즈 설정이 섞이지 않고, 음악퀴즈만 삭제해도 본체에는 영향이 없습니다.
> **폴더 이름 바꾸기.** 기본값은 `.mc_custom` 이지만 `.env` / `.env.build` 의 `MC_CUSTOM_DIR` 로 다른 이름을 지정할 수 있습니다. 설치기·리소스팩설치기·파일제거기가 모두 이 값을 공유하므로, 값을 바꾸면 세 exe 를 같은 값으로 다시 빌드해야 서로 같은 폴더를 가리킵니다. (경로 구분자 `/ \` 와 `..` 는 무시되어 항상 `%APPDATA%` 바로 아래 단일 폴더가 됩니다.)
---
## 빠른 시작
@@ -65,8 +71,17 @@ npm run installer
# 3) 리소스팩 간편설치기를 Electron 으로 실행해 보기
npm run installer:rp
# 4) 음악퀴즈 간편설치기 윈도우 .exe 빌드
npm run dist:win
# 4) 간편포트포워딩 / 파일제거 도구 실행해 보기
npm run installer:pf
npm run installer:uninstall
# 5) 윈도우 .exe 빌드 (개별)
npm run dist:win # 음악퀴즈 간편설치기
npm run dist:win:rp # 음악퀴즈 리소스팩설치기
npm run dist:win:pf # 간편포트포워딩
npm run dist:win:uninstall # 음악퀴즈 파일제거
npm run dist:win:dev # (개발자용) 음악퀴즈 간편설치기
npm run dist:win:rp:dev # (개발자용) 음악퀴즈 리소스팩설치기
```
리소스팩 설치기는 `yt-dlp` 가 필요합니다. 자동 다운로드되지만, 막혀 있는 환경이라면 [`docs/yt-dlp-setup.md`](docs/yt-dlp-setup.md) 참고.
@@ -155,9 +170,13 @@ minecraft_launcher/
│ ├─ server/ Express + EJS 관리 사이트
│ ├─ installer/ 음악퀴즈 간편설치기 (Electron 메인 + preload)
│ ├─ installer-rp/ 리소스팩 간편설치기 (Electron 메인 + 음악/이미지 파이프라인)
│ ├─ installer-pf/ 간편포트포워딩 도구 (Electron 메인 + preload)
│ ├─ installer-uninstall/ 음악퀴즈 파일제거 도구 (Electron 메인 + preload)
│ └─ shared/ 공용 타입, 매니페스트 스토어, mojang/upnp 유틸
├─ installer/ 음악퀴즈 설치기 렌더러(HTML/CSS/JS)
├─ installer-rp/ 리소스팩 설치기 렌더러(HTML/CSS/JS)
├─ installer-pf/ 간편포트포워딩 렌더러(HTML/JS)
├─ installer-uninstall/ 파일제거 렌더러(HTML/JS)
├─ views/ 관리 사이트 EJS 템플릿
├─ public/ 관리 사이트 정적 파일(styles.css 등)
├─ manifest/ 음악퀴즈 JSON 정의 (운영자가 편집)
@@ -172,18 +191,24 @@ minecraft_launcher/
├─ manifest.json 사이트 루트 매니페스트 (자동 관리)
├─ account.json 관리자 계정 (절대 외부 노출 금지)
├─ package.json
└─ tsconfig.{,server,installer,installer-rp}.json
└─ tsconfig.{,server,installer,installer-rp,installer-pf,installer-uninstall}.json
```
---
## 빌드 산출물 / 배포
| 산출물 | 빌드 명령 | 비고 |
| 산출물(파일명) | 빌드 명령 | 비고 |
| --- | --- | --- |
| 관리 사이트 (Node 실행) | `npm start` | systemd 등으로 띄우기. 외부 도메인이 manifest 의 base URL 이 됩니다. |
| 음악퀴즈 간편설치기 `.exe` | `npm run dist:win` | `electron-builder.yml` 설정 사용. |
| 리소스팩 간편설치기 `.exe` | `tsconfig.installer-rp.json` 빌드 후 `electron-builder` 수동 패키징 | |
| `음악퀴즈 간편설치기-<버전>.exe` | `npm run dist:win` | `electron-builder.yml`. |
| `음악퀴즈 리소스팩설치기-<버전>.exe` | `npm run dist:win:rp` | `electron-builder-rp.yml`. |
| `간편포트포워딩-<버전>.exe` | `npm run dist:win:pf` | `electron-builder-pf.yml`. |
| `음악퀴즈 파일제거-<버전>.exe` | `npm run dist:win:uninstall` | `electron-builder-uninstall.yml`. |
| `(개발자용) 음악퀴즈 간편설치기-<버전>.exe` | `npm run dist:win:dev` | 비공개(public=false) 팩만 노출. 제목 앞에 `(개발자용)` 표시. |
| `(개발자용) 음악퀴즈 리소스팩설치기-<버전>.exe` | `npm run dist:win:rp:dev` | 상동. |
빌드 결과물은 `release/` 폴더에 생성됩니다(포터블 exe).
---

3
account.example.json Normal file
View File

@@ -0,0 +1,3 @@
[
{ "id": "admin", "password": "여기에-비밀번호를-넣으세요" }
]

View File

@@ -50,7 +50,9 @@ npm start # 기본 포트 3000.
## 계정
`account.json` 에 정의합니다(루트 디렉터리). **외부 HTTP 로 절대 노출되지 않도록 라우팅에서 제외돼 있습니다.**
운영 계정은 **gitignore 된 `account.local.json`**(루트 디렉터리, 0600, scrypt 해시)에 저장됩니다. 추적되는 `account.json` 은 서버에 `account.local.json` 이 없을 때만 읽는 **시드 소스**로, 서버 시작 시 자동으로 `account.local.json`(0600) 으로 복사됩니다. 두 파일 모두 **외부 HTTP 로 절대 노출되지 않도록 라우팅에서 제외돼 있습니다.**
시드 포맷(`account.json`):
```json
[
@@ -58,7 +60,7 @@ npm start # 기본 포트 3000.
]
```
> 운영 환경에서는 평문 비밀번호 대신 해시를 쓰도록 추후 보강할 여지가 있습니다.
평문 비밀번호로 시드해도 로그인 성공 시 자동으로 scrypt 해시(`scrypt$<salt>$<hash>`)로 업그레이드되어 `account.local.json` 에만 저장됩니다. 자세한 마이그레이션 절차는 아래 "운영 계정 파일 마이그레이션" 을 참고하세요.
## 대시보드 (`/op/dashboard`)
@@ -138,4 +140,14 @@ say [musicquiz] 데이터팩 초기화
- `account.json` 은 라우팅에서 차단되어 있으나, 디스크 권한도 운영자만 접근 가능하게 두는 것이 안전합니다.
- 관리자 비밀번호는 충분히 강하게 설정.
### 운영 계정 파일 마이그레이션 (미완결 — 재배포 게이트)
운영 계정은 이제 gitignore 된 `account.local.json`(0o600, scrypt 해시)에만 저장됩니다. 추적되는 `account.json` 은 서버에 `account.local.json` 이 없을 때만 읽는 **시드 소스**로 남겨 둔 상태입니다. 남은 위생 작업이 하나 있습니다:
1. **[운영] 최신 main 재배포** → 서버가 `account.local.json`(0o600) 을 자동 생성하는지 확인.
2. **[운영] 비밀번호 로테이션** — git 히스토리에 평문 비밀번호가 남아 있어 추적 해제로는 지워지지 않으므로, 이것이 실질적 최우선 보안 조치입니다.
3. **[후속 커밋] `account.json` 추적 해제** — 위 1번(서버에 `account.local.json` 존재) 확인 **후에만** `git rm --cached account.json` 를 별도 커밋으로 진행. 같은 커밋에서 하면 시드 소스가 사라져 로그인이 막힙니다.
> 코드 상 앵커: `src/shared/paths.ts` 의 `TODO(untrack-after-redeploy)` 주석.
- 모든 `/op/*` 라우트는 세션 기반 인증 미들웨어를 거칩니다. 세션 만료 시 자동으로 로그인 페이지로 리다이렉트.

View File

@@ -28,9 +28,16 @@
### 3-2. JDK 확인
- 환경변수(`JAVA_HOME`, `JDK_HOME`) → 자동 설치 위치(`%APPDATA%\jdk\temurin-21`) → `C:\Program Files\Java` 순으로 자동 탐색.
- **자동 설치** 버튼을 누르면 Adoptium Temurin 21 LTS Windows x64 zip 을 받아 `%APPDATA%\jdk\temurin-21\` 에 풀어 사용합니다.
- 각 음악퀴즈(pack)는 사이트 편집기에서 **권장 JDK 버전**(예: Java 25)을 지정합니다. 편집기 목록은 Adoptium(Temurin)에서 실제 배포되는 버전을 불러오며, "자세히 보기"로 비-LTS·스냅샷까지 확인할 수 있습니다. 설치기는 이 권장 버전을 기준으로 동작합니다.
- 탐색 순서:
1. **설치기 자동 설치 위치 `%APPDATA%\.mc_custom\jdk`**(구버전 `%APPDATA%\jdk` 호환)에 JDK 가 있으면 **가장 먼저 사용**합니다(권장 버전이면 그대로, 혹시 다른 버전이면 경고).
2. 없으면 **환경변수(`JAVA_HOME` / `JDK_HOME`)** 의 JDK 가 **권장 버전이면** 사용합니다.
3. 그래도 없으면 **기본 폴더 `C:\Program Files\Java`** 에서 **권장 버전**을 찾아 사용합니다.
4. 권장 버전을 어디서도 못 찾으면 **환경변수 자바(없으면 Program Files 자바)로 폴백**하고, "권장 버전과 달라 서버가 정상 실행되지 않을 수 있다"는 **경고**를 띄웁니다.
- 직접 선택/입력한 경로도 "다음" 에서 검증해, 권장과 다르면 경고 후 동의(확인) 시에만 진행합니다(무조건 차단이 아니라 경고+동의). 아무 JDK 도 없으면 자동 설치로 유도합니다.
- **자동 설치** 버튼을 누르면 Adoptium Temurin(권장 버전) Windows x64 zip 을 받아 **`%APPDATA%\.mc_custom\jdk\temurin-<권장>\`** 에 풀어 사용합니다. (`.mc_custom` 안에 두므로 "음악퀴즈 파일제거" 도구로 한 번에 정리됩니다. `MC_CUSTOM_DIR` 로 폴더명을 바꾼 경우 그 폴더 아래 `jdk`.)
- 설치 중 같은 버튼이 "설치 취소" 로 바뀌고, 누르면 다운로드를 즉시 중단하고 부분 파일을 정리합니다.
- 서버 zip 의 `run.bat` 이 시스템 PATH 의 `java` 를 그대로 쓰면 낡은 자바로 실행돼 실패할 수 있어, 설치기가 준비/선택한 JDK 의 `java` 를 쓰도록 `run.bat` 을 자동으로 수정합니다(자동 설치 JDK 는 `%APPDATA%` 전개형 경로라 한글 사용자명에도 안전).
### 3-3. 서버 다운로드 및 설치

35
electron-builder-dev.yml Normal file
View File

@@ -0,0 +1,35 @@
appId: kr.tkrmagid.musicquiz.installer.dev
productName: MusicQuizInstaller
# 개발자용 빌드: manifest 의 public===false 인 pack 만 노출한다.
# musicQuizAudience 를 package.json 에 박아 런타임에서 대상(audience)을 판별.
extraMetadata:
main: dist/installer/main.js
musicQuizAudience: developer
directories:
output: release
buildResources: build
files:
- dist/installer/**
- dist/shared/**
- installer/**
- build/icon.*
- package.json
- "!node_modules/@img/sharp-linux-*"
- "!node_modules/@img/sharp-linuxmusl-*"
- "!node_modules/@img/sharp-libvips-linux-*"
- "!node_modules/@img/sharp-libvips-linuxmusl-*"
extraResources:
- from: .
to: .
filter:
- .env.build
- from: locales
to: locales
filter:
- "**/*"
win:
target: portable
artifactName: (개발자용) 음악퀴즈 간편설치기-${version}.${ext}
icon: build/icon.ico
portable:
artifactName: (개발자용) 음악퀴즈 간편설치기-${version}.${ext}

33
electron-builder-pf.yml Normal file
View File

@@ -0,0 +1,33 @@
appId: kr.tkrmagid.musicquiz.portforward
productName: 마인크래프트 간편 포트포워딩
# 루트 package.json 의 "main" 은 메인 설치기를 가리키므로, 패키지된 앱이
# 포트포워딩 도구를 진입점으로 쓰도록 빌드 시 main 을 덮어쓴다.
extraMetadata:
main: dist/installer-pf/main.js
directories:
output: release
buildResources: build
files:
- dist/installer-pf/**
- dist/shared/**
- installer-pf/**
# pf 의 index.html 은 메인 설치기와 동일한 styles.css 를 공유함
# (`<link href="../installer/styles.css">`). 그 한 파일만 명시적으로 포함.
- installer/styles.css
- build/icon.*
- package.json
# 이 도구는 sharp(이미지 처리)를 쓰지 않으므로 통째로 제외해 exe 크기를 줄인다.
- "!node_modules/sharp/**"
- "!node_modules/@img/**"
# i18n 사전(locales/installer-pf/ko-kr.json)을 런타임에서 읽도록 함께 배포.
extraResources:
- from: locales
to: locales
filter:
- "**/*"
win:
target: portable
artifactName: 간편포트포워딩-${version}.${ext}
icon: build/icon.ico
portable:
artifactName: 간편포트포워딩-${version}.${ext}

View File

@@ -0,0 +1,35 @@
appId: kr.tkrmagid.musicquiz.installer-rp.dev
productName: MusicQuizResourcepackInstaller
# 개발자용 리소스팩 설치기: manifest 의 public===false 인 pack 만 노출.
extraMetadata:
main: dist/installer-rp/main.js
musicQuizAudience: developer
directories:
output: release
buildResources: build
files:
- dist/installer-rp/**
- dist/shared/**
- installer-rp/**
- installer/styles.css
- build/icon.*
- package.json
- "!node_modules/@img/sharp-linux-*"
- "!node_modules/@img/sharp-linuxmusl-*"
- "!node_modules/@img/sharp-libvips-linux-*"
- "!node_modules/@img/sharp-libvips-linuxmusl-*"
extraResources:
- from: .
to: .
filter:
- .env.build
- from: locales
to: locales
filter:
- "**/*"
win:
target: portable
artifactName: (개발자용) 음악퀴즈 리소스팩설치기-${version}.${ext}
icon: build/icon.ico
portable:
artifactName: (개발자용) 음악퀴즈 리소스팩설치기-${version}.${ext}

View File

@@ -35,7 +35,7 @@ extraResources:
- "**/*"
win:
target: portable
artifactName: ${productName}-${version}-Portable.${ext}
artifactName: 음악퀴즈 리소스팩설치기-${version}.${ext}
icon: build/icon.ico
portable:
artifactName: ${productName}-${version}-Portable.${ext}
artifactName: 음악퀴즈 리소스팩설치기-${version}.${ext}

View File

@@ -0,0 +1,38 @@
appId: kr.tkrmagid.musicquiz.uninstall
productName: 음악퀴즈 파일제거
# 루트 package.json 의 "main" 은 메인 설치기를 가리키므로, 패키지된 앱이
# 파일제거 도구를 진입점으로 쓰도록 빌드 시 main 을 덮어쓴다.
extraMetadata:
main: dist/installer-uninstall/main.js
directories:
output: release
buildResources: build
files:
- dist/installer-uninstall/**
- dist/shared/**
- installer-uninstall/**
# index.html 은 메인 설치기와 동일한 styles.css 를 공유함
# (`<link href="../installer/styles.css">`). 그 한 파일만 명시적으로 포함.
- installer/styles.css
- build/icon.*
- package.json
# 이 도구는 sharp(이미지 처리)를 쓰지 않으므로 통째로 제외해 exe 크기를 줄인다.
- "!node_modules/sharp/**"
- "!node_modules/@img/**"
# MC_CUSTOM_DIR 을 커스텀으로 빌드했다면 파일제거기도 같은 폴더를 가리켜야 하므로
# `.env.build` 를 함께 배포한다. i18n 사전(locales/installer-uninstall/ko-kr.json)도 함께.
extraResources:
- from: .
to: .
filter:
- .env.build
- from: locales
to: locales
filter:
- "**/*"
win:
target: portable
artifactName: 음악퀴즈 파일제거-${version}.${ext}
icon: build/icon.ico
portable:
artifactName: 음악퀴즈 파일제거-${version}.${ext}

View File

@@ -32,7 +32,7 @@ extraResources:
- "**/*"
win:
target: portable
artifactName: ${productName}-${version}-Portable.${ext}
artifactName: 음악퀴즈 간편설치기-${version}.${ext}
icon: build/icon.ico
portable:
artifactName: ${productName}-${version}-Portable.${ext}
artifactName: 음악퀴즈 간편설치기-${version}.${ext}

22
installer-pf/index.html Normal file
View File

@@ -0,0 +1,22 @@
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8" />
<title>마인크래프트 간편 포트포워딩</title>
<link rel="stylesheet" href="../installer/styles.css" />
</head>
<body>
<header class="appHeader">
<h1>마인크래프트 간편 포트포워딩</h1>
</header>
<main id="pageHost"></main>
<aside class="logViewer" id="logViewer" hidden>
<header><h2>로그</h2><button type="button" id="logToggle">접기</button></header>
<pre id="logBody"></pre>
</aside>
<script src="./renderer.js"></script>
</body>
</html>

172
installer-pf/renderer.js Normal file
View File

@@ -0,0 +1,172 @@
'use strict'
const api = window.pfTool
let I18N = {}
function tt(key, params) {
var parts = String(key).split('.')
var cur = I18N
for (var i = 0; i < parts.length; i++) {
if (cur && typeof cur === 'object' && parts[i] in cur) {
cur = cur[parts[i]]
} else {
return key
}
}
if (typeof cur !== 'string') return key
if (!params) return cur
return cur.replace(/\{\{\s*(\w+)\s*\}\}/g, function (_m, name) {
return name in params ? String(params[name]) : '{{' + name + '}}'
})
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, function (c) {
return c === '&' ? '&amp;' : c === '<' ? '&lt;' : c === '>' ? '&gt;' : c === '"' ? '&quot;' : '&#39;'
})
}
const pageHost = document.getElementById('pageHost')
const logViewer = document.getElementById('logViewer')
const logBody = document.getElementById('logBody')
const logToggle = document.getElementById('logToggle')
logToggle.addEventListener('click', function () {
logViewer.classList.toggle('collapsed')
if (logViewer.classList.contains('collapsed')) {
logViewer.style.height = '36px'
logToggle.textContent = tt('logViewer.expand')
} else {
logViewer.style.height = ''
logToggle.textContent = tt('logViewer.collapse')
}
})
api.onLog(function (line) {
logViewer.hidden = false
logBody.textContent += line + '\n'
logBody.scrollTop = logBody.scrollHeight
})
function applyStaticI18n() {
document.title = tt('app.title')
var h1 = document.querySelector('.appHeader h1')
if (h1) h1.textContent = tt('app.title')
var logH2 = logViewer.querySelector('header h2')
if (logH2) logH2.textContent = tt('logViewer.heading')
logToggle.textContent = tt('logViewer.collapse')
}
function renderMain() {
pageHost.innerHTML =
'<section class="page">' +
' <h2>' + escapeHtml(tt('main.heading')) + '</h2>' +
' <p class="formMessage">' + escapeHtml(tt('main.intro')) + '</p>' +
' <div class="fieldset">' +
' <label for="port">' + escapeHtml(tt('main.portLabel')) + '</label>' +
' <input type="text" id="port" inputmode="numeric" value="25565" />' +
' </div>' +
' <div class="actionRow">' +
' <button class="primaryBtn" id="openBtn">' + escapeHtml(tt('main.openBtn')) + '</button>' +
' <button class="secondaryBtn" id="closeBtn">' + escapeHtml(tt('main.closeBtn')) + '</button>' +
' <button class="secondaryBtn" id="quitBtn">' + escapeHtml(tt('main.quitBtn')) + '</button>' +
' </div>' +
' <div id="result"></div>' +
'</section>'
var portEl = document.getElementById('port')
var openBtn = document.getElementById('openBtn')
var closeBtn = document.getElementById('closeBtn')
var quitBtn = document.getElementById('quitBtn')
var resultEl = document.getElementById('result')
function parsePort() {
var n = parseInt(String(portEl.value).replace(/[^0-9]/g, ''), 10)
if (!isFinite(n) || n <= 0 || n >= 65536) return 25565
return n
}
function setBusy(busy) {
openBtn.disabled = busy
closeBtn.disabled = busy
portEl.disabled = busy
}
function showResult(outcome) {
var addr = (outcome.externalIp || tt('main.ipUnknown')) +
(outcome.port === 25565 ? '' : (':' + outcome.port))
var cls, badge, msg
if (outcome.reachable === true) {
cls = 'ok'; badge = tt('verdict.success')
msg = tt('main.successMsg', { addr: addr }) +
(outcome.preForwarded ? ' ' + tt('main.alreadyOpen') : '')
} else if (outcome.reachable === false) {
cls = 'fail'; badge = tt('verdict.fail')
msg = tt('main.failMsg')
} else {
cls = 'warn'; badge = tt('verdict.unknown')
msg = tt('main.unknownMsg')
}
// 실패/확인불가일 때 다음 조치 안내: CGNAT 경고 + 수동 포워딩 방법.
var extra = ''
if (outcome.reachable !== true) {
if (outcome.cgnat === 'yes') {
extra += '<p class="formMessage error" style="margin-top:8px;">' +
escapeHtml(tt('main.cgnatWarn', { public: outcome.externalIp || '?', wan: outcome.wanIp || '?' })) + '</p>'
} else if (outcome.cgnat === 'unknown') {
extra += '<p class="formMessage" style="margin-top:8px;">' +
escapeHtml(tt('main.cgnatUnknown', { ip: outcome.externalIp || '?' })) + '</p>'
}
var manual = outcome.localIp
? tt('main.manualForward', { port: outcome.port, localIp: outcome.localIp })
: tt('main.manualForwardNoIp', { port: outcome.port })
extra += '<p class="formMessage" style="margin-top:8px;">' + escapeHtml(manual) + '</p>'
}
resultEl.innerHTML =
'<div class="progressCard ' + (cls === 'ok' ? 'done' : cls === 'fail' ? 'error' : 'running') + '" style="margin-top:14px;">' +
' <div class="cardTop"><span class="statusBadge ' + cls + '">' + escapeHtml(badge) + '</span> ' +
' <span class="label">' + escapeHtml(addr) + '</span></div>' +
' <p class="formMessage" style="margin-top:8px;">' + escapeHtml(msg) + '</p>' +
extra +
' <p class="formMessage"><small>' + escapeHtml(tt('main.detailLabel', { detail: outcome.detail || '' })) + '</small></p>' +
'</div>'
}
openBtn.addEventListener('click', function () {
var port = parsePort()
portEl.value = String(port)
setBusy(true)
resultEl.innerHTML = '<p class="formMessage" style="margin-top:14px;">' + escapeHtml(tt('main.working')) + '</p>'
api.openPort(port).then(function (outcome) {
showResult(outcome)
}).catch(function (err) {
resultEl.innerHTML = '<p class="formMessage error" style="margin-top:14px;">' +
escapeHtml(tt('main.error', { message: (err && err.message) || String(err) })) + '</p>'
}).then(function () {
setBusy(false)
})
})
closeBtn.addEventListener('click', function () {
var port = parsePort()
portEl.value = String(port)
setBusy(true)
api.closePort(port).then(function () {
resultEl.innerHTML = '<p class="formMessage" style="margin-top:14px;">' +
escapeHtml(tt('main.closed', { port: port })) + '</p>'
}).then(function () {
setBusy(false)
})
})
quitBtn.addEventListener('click', function () { api.quit() })
}
;(async function () {
try { I18N = (await api.loadLocale()) || {} } catch (_) { I18N = {} }
applyStaticI18n()
renderMain()
})()

View File

@@ -141,70 +141,109 @@ function renderStep1() {
}
// 약관 동의 페이지: 1단계 직후, 2단계 설치 진입 전에 노출.
// rp 인스톨러는 리소스팩·설치기 두 약관만 확인·동의하면 된다.
// v0.3.4~ : 사이트의 visibility 토글에 따라 표시할 약관이 결정된다. 명시적으로 빈 목록(terms:[])
// 정상 응답일 때만 단계를 건너뛰고, 네트워크/서버 오류는 차단 후 다시 시도 UI를 보여준다.
function renderAgreement() {
setActiveStep(1)
clearPage()
var KINDS = [
{ id: 'resourcepack', tab: tt('agreement.tabResourcepack') },
{ id: 'installer-rp', tab: tt('agreement.tabInstaller') }
]
var loadingSection = document.createElement('section')
loadingSection.className = 'page'
loadingSection.innerHTML = '<h2>' + escapeHtml(tt('agreement.heading')) + '</h2>' +
'<p class="formMessage">' + escapeHtml(tt('agreement.loading')) + '</p>'
pageHost.appendChild(loadingSection)
api.getTermsList().then(function (res) {
if (!res || !res.ok) {
showAgreementError((res && res.message) || 'unknown')
return
}
var terms = (res.terms || []).map(function (t) {
return { id: t.kind, tab: t.label }
})
if (terms.length === 0) {
renderStep2()
return
}
clearPage()
renderAgreementWithKinds(terms)
}).catch(function (err) {
showAgreementError(err && err.message ? err.message : 'unknown')
})
}
// 약관 목록을 못 받아왔을 때: 사용자에게 오류 + 다시 시도 옵션. 동의 없이 설치 단계로
// 자동 진입하지 않도록 next 버튼을 두지 않는다.
function showAgreementError(message) {
clearPage()
var section = document.createElement('section')
section.className = 'page'
section.innerHTML =
'<h2>' + escapeHtml(tt('agreement.heading')) + '</h2>' +
'<p class="formMessage">' + escapeHtml(tt('agreement.intro')) + '</p>' +
'<div class="tabBar" id="agTabs">' +
KINDS.map(function (k, i) {
return '<button type="button" class="tabBtn' + (i === 0 ? ' active' : '') + '" data-ag="' + k.id + '">' + escapeHtml(k.tab) + '</button>'
}).join('') +
'</div>' +
'<div class="agreementBody" id="agBody">' + escapeHtml(tt('agreement.loading')) + '</div>' +
'<label class="toggleRow" style="margin-top:12px;"><input type="checkbox" id="agAccept" /> ' +
escapeHtml(tt('agreement.agreeAll')) + '</label>' +
'<p class="formMessage error">' + escapeHtml(tt('agreement.listLoadFailed', { message: message })) + '</p>' +
'<div class="actionRow">' +
'<button class="secondaryBtn" id="back">' + escapeHtml(tt('common.back')) + '</button>' +
'<button class="primaryBtn" id="retry">' + escapeHtml(tt('agreement.retry')) + '</button>' +
'</div>'
pageHost.appendChild(section)
section.querySelector('#back').addEventListener('click', renderStep1)
section.querySelector('#retry').addEventListener('click', renderAgreement)
}
// 약관을 한 건씩 페이지로 보여준다. 각 약관마다 "해당 약관에 동의합니다" 체크가 있고,
// 끝까지 스크롤해 읽어야 체크할 수 있으며, [다음] 을 누르면 다음 약관 페이지가 화면
// 맨 위에서부터 나온다. 마지막 약관까지 동의하면 다음 단계(step2)로 진행한다.
function renderAgreementWithKinds(KINDS) {
var idx = 0
var accepted = {} // kind -> true (뒤로 갔다 와도 동의 상태 유지)
var cache = {} // kind -> 렌더된 HTML
var section = document.createElement('section')
section.className = 'page'
pageHost.appendChild(section)
function renderCurrent() {
var k = KINDS[idx]
var isLast = idx === KINDS.length - 1
section.innerHTML =
'<h2>' + escapeHtml(tt('agreement.heading')) + '</h2>' +
'<p class="formMessage">' + escapeHtml(tt('agreement.stepLabel', { current: idx + 1, total: KINDS.length, label: k.tab })) + '</p>' +
'<div class="agreementBody" id="agBody" style="border-radius:10px;">' + escapeHtml(tt('agreement.loading')) + '</div>' +
'<div class="formMessage" id="agHint">' + escapeHtml(tt('agreement.readToBottom')) + '</div>' +
'<label class="toggleRow" style="margin-top:8px;"><input type="checkbox" id="agAccept" disabled /> ' +
escapeHtml(tt('agreement.agreeThis')) + '</label>' +
'<div class="formMessage" id="agMsg"></div>' +
'<div class="actionRow">' +
' <button class="secondaryBtn" id="back">' + escapeHtml(tt('common.back')) + '</button>' +
' <button class="primaryBtn" id="next" disabled>' + escapeHtml(tt('common.next')) + '</button>' +
'</div>'
pageHost.appendChild(section)
var body = section.querySelector('#agBody')
var tabs = section.querySelectorAll('[data-ag]')
var nextBtn = section.querySelector('#next')
var accept = section.querySelector('#agAccept')
var nextBtn = section.querySelector('#next')
var msg = section.querySelector('#agMsg')
var hint = section.querySelector('#agHint')
// 본문 캐시. 탭 전환 시 재요청하지 않음.
var cache = {}
// 새 약관 페이지는 화면 맨 위에서부터 보이도록 스크롤을 올린다.
if (pageHost) pageHost.scrollTop = 0
function showKind(kind) {
if (cache[kind]) { body.innerHTML = cache[kind]; return }
body.textContent = tt('agreement.loading')
api.getTerm(kind).then(function (res) {
if (!res.ok) {
body.innerHTML = '<p class="formMessage error">' + escapeHtml(tt('agreement.loadFailed', { message: res.message || '' })) + '</p>'
return
// 약관 본문이 정상 로드된 뒤에만 동의를 허용한다. 로드 실패 상태에서는
// 스크롤을 해도 동의 체크가 켜지지 않는다("무조건 약관을 읽도록").
var termLoaded = false
function markReadable() {
if (!termLoaded || !accept.disabled) return
accept.disabled = false
hint.textContent = ''
}
var html = renderTermsMarkdown(res.content || '')
cache[kind] = html
body.innerHTML = html
}).catch(function (err) {
body.innerHTML = '<p class="formMessage error">' + escapeHtml(tt('agreement.loadFailed', { message: err.message })) + '</p>'
})
function checkScrolled() {
if (body.scrollHeight - body.scrollTop - body.clientHeight <= 6) markReadable()
}
tabs.forEach(function (b) {
b.addEventListener('click', function () {
tabs.forEach(function (x) { x.classList.remove('active') })
b.classList.add('active')
showKind(b.getAttribute('data-ag'))
})
})
body.addEventListener('scroll', checkScrolled)
accept.addEventListener('change', function () {
accepted[k.id] = accept.checked
nextBtn.disabled = !accept.checked
if (accept.checked) msg.textContent = ''
if (accept.checked) { msg.textContent = ''; msg.classList.remove('error') }
})
nextBtn.addEventListener('click', function () {
@@ -213,11 +252,69 @@ function renderAgreement() {
msg.classList.add('error')
return
}
renderStep2()
if (isLast) renderStep2()
else { idx++; renderCurrent() }
})
section.querySelector('#back').addEventListener('click', function () {
if (idx === 0) renderStep1()
else { idx--; renderCurrent() }
})
section.querySelector('#back').addEventListener('click', renderStep1)
showKind(KINDS[0].id)
function afterLoad() {
termLoaded = true
body.scrollTop = 0
if (accepted[k.id]) {
accept.disabled = false
accept.checked = true
nextBtn.disabled = false
hint.textContent = ''
}
setTimeout(function () {
if (body.scrollHeight - body.clientHeight <= 6) markReadable()
else checkScrolled()
}, 0)
}
// 약관 본문 로드 실패: 동의 불가 상태를 유지하고 다시 시도만 허용한다.
function showLoadError(message) {
termLoaded = false
accept.disabled = true
accept.checked = false
accepted[k.id] = false
nextBtn.disabled = true
hint.textContent = tt('agreement.readToBottom')
body.innerHTML =
'<p class="formMessage error">' + escapeHtml(tt('agreement.loadFailed', { message: message || '' })) + '</p>' +
'<div class="actionRow" style="margin-top:10px;"><button class="secondaryBtn" id="agRetry">' + escapeHtml(tt('agreement.retry')) + '</button></div>'
var retry = section.querySelector('#agRetry')
if (retry) retry.addEventListener('click', loadTerm)
}
function loadTerm() {
if (cache[k.id]) {
body.innerHTML = cache[k.id]
afterLoad()
return
}
body.textContent = tt('agreement.loading')
api.getTerm(k.id).then(function (res) {
if (!res.ok) {
showLoadError(res.message || '')
return
}
var html = renderTermsMarkdown(res.content || '')
cache[k.id] = html
body.innerHTML = html
afterLoad()
}).catch(function (err) {
showLoadError(err && err.message ? err.message : '')
})
}
loadTerm()
}
renderCurrent()
}
// 인스톨러용 미니 markdown 렌더러. 사이트 termsEditor 와 같은 규칙을 처리한다.
@@ -444,10 +541,43 @@ function renderStep2() {
}).catch(function (err) {
state.installing = false
if (stopProgress) stopProgress()
if (!cancelInitiated) {
alert(tt('common.installFailed', { message: (err && err.message) || err }))
}
if (cancelInitiated) {
// 취소: backend 가 임시 파일을 이미 정리했음. 조용히 처음 단계로.
renderStep1()
return
}
// 그 외 오류: 받아둔 음악·사진은 보존되어 있으므로 '재시도' 로 이어받을 수 있다.
showInstallError((err && err.message) || String(err))
})
}
// 설치 실패 화면: 이어받기('재시도')와 처음으로('처음으로') 선택지를 제공한다.
// 재시도 시 이미 받아둔 곡·사진은 건너뛰고 실패한 지점부터 이어서 설치한다.
function showInstallError(message) {
setActiveStep(2)
clearPage()
var section = document.createElement('section')
section.className = 'page'
section.innerHTML =
'<h2>' + escapeHtml(tt('step2.heading')) + '</h2>' +
'<p class="formMessage error">' + escapeHtml(tt('install.errorMessage', { message: message })) + '</p>' +
'<p class="formMessage">' + escapeHtml(tt('install.resumeHint')) + '</p>' +
'<div class="actionRow">' +
' <button class="secondaryBtn" id="startOver">' + escapeHtml(tt('install.startOver')) + '</button>' +
' <button class="primaryBtn" id="retry">' + escapeHtml(tt('install.retry')) + '</button>' +
'</div>'
pageHost.appendChild(section)
section.querySelector('#retry').addEventListener('click', function () {
// 같은 음악퀴즈로 설치를 다시 시작. backend 가 받아둔 산출물을 건너뛴다.
renderStep2()
})
section.querySelector('#startOver').addEventListener('click', function () {
// 이어받지 않고 처음으로: 받아둔 임시 파일을 정리한 뒤 1단계로.
api.discardInstall().then(function () {
renderStep1()
}).catch(function () {
renderStep1()
})
})
}
@@ -460,6 +590,7 @@ function renderStep3() {
section.innerHTML =
'<h2>' + escapeHtml(tt('step3.heading')) + '</h2>' +
'<p class="formMessage">' + escapeHtml(tt('step3.message')) + '</p>' +
'<p class="formMessage">' + escapeHtml(tt('step3.applyNotice')) + '</p>' +
(state.resourcepackPath
? '<p class="formMessage"><code>' + escapeHtml(state.resourcepackPath) + '</code></p>'
: '') +

View File

@@ -0,0 +1,22 @@
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8" />
<title>음악퀴즈 파일제거</title>
<link rel="stylesheet" href="../installer/styles.css" />
</head>
<body>
<header class="appHeader">
<h1>음악퀴즈 파일제거</h1>
</header>
<main id="pageHost"></main>
<aside class="logViewer" id="logViewer" hidden>
<header><h2>로그</h2><button type="button" id="logToggle">접기</button></header>
<pre id="logBody"></pre>
</aside>
<script src="./renderer.js"></script>
</body>
</html>

View File

@@ -0,0 +1,209 @@
'use strict'
const api = window.uninstaller
let I18N = {}
function tt(key, params) {
var parts = String(key).split('.')
var cur = I18N
for (var i = 0; i < parts.length; i++) {
if (cur && typeof cur === 'object' && parts[i] in cur) {
cur = cur[parts[i]]
} else {
return key
}
}
if (typeof cur !== 'string') return key
if (!params) return cur
return cur.replace(/\{\{\s*(\w+)\s*\}\}/g, function (_m, name) {
return name in params ? String(params[name]) : '{{' + name + '}}'
})
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, function (c) {
return c === '&' ? '&amp;' : c === '<' ? '&lt;' : c === '>' ? '&gt;' : c === '"' ? '&quot;' : '&#39;'
})
}
const pageHost = document.getElementById('pageHost')
const logViewer = document.getElementById('logViewer')
const logBody = document.getElementById('logBody')
const logToggle = document.getElementById('logToggle')
logToggle.addEventListener('click', function () {
logViewer.classList.toggle('collapsed')
if (logViewer.classList.contains('collapsed')) {
logViewer.style.height = '36px'
logToggle.textContent = tt('logViewer.expand')
} else {
logViewer.style.height = ''
logToggle.textContent = tt('logViewer.collapse')
}
})
api.onLog(function (line) {
logViewer.hidden = false
logBody.textContent += line + '\n'
logBody.scrollTop = logBody.scrollHeight
})
function applyStaticI18n() {
document.title = tt('app.title')
var h1 = document.querySelector('.appHeader h1')
if (h1) h1.textContent = tt('app.title')
var logH2 = logViewer.querySelector('header h2')
if (logH2) logH2.textContent = tt('logViewer.heading')
logToggle.textContent = tt('logViewer.collapse')
}
// ── 1단계: 삭제 동의 ──────────────────────────────
function renderConfirm() {
pageHost.innerHTML =
'<section class="page">' +
' <h2>' + escapeHtml(tt('confirm.heading')) + '</h2>' +
' <p class="formMessage" style="margin-top:8px;font-size:15px;">' + escapeHtml(tt('confirm.question')) + '</p>' +
' <p class="formMessage" style="margin-top:8px;">' + escapeHtml(tt('confirm.detail')) + '</p>' +
' <div id="previewBox" class="progressCard" style="margin-top:14px;"><p class="formMessage">' +
escapeHtml(tt('confirm.loadingPreview')) + '</p></div>' +
' <div class="actionRow" style="margin-top:16px;">' +
' <button class="primaryBtn" id="agreeBtn" disabled>' + escapeHtml(tt('confirm.agreeBtn')) + '</button>' +
' <button class="secondaryBtn" id="cancelBtn">' + escapeHtml(tt('confirm.cancelBtn')) + '</button>' +
' </div>' +
'</section>'
var agreeBtn = document.getElementById('agreeBtn')
var cancelBtn = document.getElementById('cancelBtn')
var previewBox = document.getElementById('previewBox')
cancelBtn.addEventListener('click', function () { api.quit() })
api.preview().then(function (p) {
var existingDirs = p.existingDirs || []
var items = []
if (existingDirs.length) {
for (var d = 0; d < existingDirs.length; d++) {
items.push(tt('confirm.itemCustomDir', { path: existingDirs[d] }))
}
} else {
var first = (p.allTargetDirs && p.allTargetDirs[0]) || ''
items.push(tt('confirm.itemCustomDirMissing', { path: first }))
}
if (p.shortcutExists) items.push(tt('confirm.itemShortcut'))
if (p.launcherProfiles && p.launcherProfiles.length) {
items.push(tt('confirm.itemProfiles', { names: p.launcherProfiles.join(', ') }))
}
var nothing = !existingDirs.length && !p.shortcutExists && (!p.launcherProfiles || !p.launcherProfiles.length)
var html = '<p class="formMessage"><strong>' + escapeHtml(tt('confirm.previewTitle')) + '</strong></p><ul>'
for (var i = 0; i < items.length; i++) html += '<li>' + escapeHtml(items[i]) + '</li>'
html += '</ul>'
if (nothing) html += '<p class="formMessage">' + escapeHtml(tt('confirm.nothingFound')) + '</p>'
previewBox.innerHTML = html
agreeBtn.disabled = false
agreeBtn.addEventListener('click', function () { renderChoose(p) })
}).catch(function (err) {
previewBox.innerHTML = '<p class="formMessage error">' +
escapeHtml(tt('confirm.previewFail', { message: (err && err.message) || String(err) })) + '</p>'
agreeBtn.disabled = false
agreeBtn.addEventListener('click', function () { renderChoose({ existingDirs: [], allTargetDirs: [], shortcutExists: false, launcherProfiles: [] }) })
})
}
// ── 2단계: 삭제 방식 선택 ─────────────────────────
function renderChoose(preview) {
pageHost.innerHTML =
'<section class="page">' +
' <h2>' + escapeHtml(tt('choose.heading')) + '</h2>' +
' <p class="formMessage" style="margin-top:8px;">' + escapeHtml(tt('choose.intro')) + '</p>' +
' <div class="actionRow" style="margin-top:18px;flex-direction:column;gap:12px;align-items:stretch;">' +
' <button class="secondaryBtn" id="trashBtn" style="padding:16px;text-align:left;">' +
' <strong>' + escapeHtml(tt('choose.trashTitle')) + '</strong><br/>' +
' <span class="formMessage">' + escapeHtml(tt('choose.trashDesc')) + '</span></button>' +
' <button class="secondaryBtn" id="permBtn" style="padding:16px;text-align:left;">' +
' <strong>' + escapeHtml(tt('choose.permTitle')) + '</strong><br/>' +
' <span class="formMessage">' + escapeHtml(tt('choose.permDesc')) + '</span></button>' +
' </div>' +
' <div class="actionRow" style="margin-top:16px;">' +
' <button class="secondaryBtn" id="backBtn">' + escapeHtml(tt('choose.backBtn')) + '</button>' +
' </div>' +
' <div id="runState"></div>' +
'</section>'
var trashBtn = document.getElementById('trashBtn')
var permBtn = document.getElementById('permBtn')
var backBtn = document.getElementById('backBtn')
var runState = document.getElementById('runState')
backBtn.addEventListener('click', function () { renderConfirm() })
function runMode(mode) {
var warn = mode === 'permanent' ? tt('choose.confirmPermanent') : tt('choose.confirmTrash')
if (!window.confirm(warn)) return
trashBtn.disabled = true
permBtn.disabled = true
backBtn.disabled = true
runState.innerHTML = '<p class="formMessage" style="margin-top:14px;">' + escapeHtml(tt('choose.running')) + '</p>'
api.run(mode).then(function (result) {
renderResult(result, mode)
}).catch(function (err) {
runState.innerHTML = '<p class="formMessage error" style="margin-top:14px;">' +
escapeHtml(tt('choose.error', { message: (err && err.message) || String(err) })) + '</p>'
trashBtn.disabled = false
permBtn.disabled = false
backBtn.disabled = false
})
}
trashBtn.addEventListener('click', function () { runMode('trash') })
permBtn.addEventListener('click', function () { runMode('permanent') })
}
// ── 3단계: 결과 ──────────────────────────────────
function renderResult(result, mode) {
var total = (result.removed ? result.removed.length : 0) + (result.profilesRemoved ? result.profilesRemoved.length : 0)
var hasErr = result.errors && result.errors.length
var cls = hasErr ? 'error' : 'done'
var badge = hasErr ? tt('result.badgePartial') : tt('result.badgeOk')
var lines = ''
if (result.removed && result.removed.length) {
lines += '<p class="formMessage"><strong>' + escapeHtml(tt('result.removedTitle')) + '</strong></p><ul>'
for (var i = 0; i < result.removed.length; i++) lines += '<li>' + escapeHtml(result.removed[i]) + '</li>'
lines += '</ul>'
}
if (result.profilesRemoved && result.profilesRemoved.length) {
lines += '<p class="formMessage"><strong>' + escapeHtml(tt('result.profilesTitle')) + '</strong></p><ul>'
for (var j = 0; j < result.profilesRemoved.length; j++) lines += '<li>' + escapeHtml(result.profilesRemoved[j]) + '</li>'
lines += '</ul>'
}
if (hasErr) {
lines += '<p class="formMessage error"><strong>' + escapeHtml(tt('result.errorsTitle')) + '</strong></p><ul>'
for (var k = 0; k < result.errors.length; k++) lines += '<li>' + escapeHtml(result.errors[k]) + '</li>'
lines += '</ul>'
}
if (total === 0 && !hasErr) {
lines += '<p class="formMessage">' + escapeHtml(tt('result.nothing')) + '</p>'
}
pageHost.innerHTML =
'<section class="page">' +
' <div class="progressCard ' + cls + '" style="margin-top:6px;">' +
' <div class="cardTop"><span class="statusBadge ' + (hasErr ? 'fail' : 'ok') + '">' + escapeHtml(badge) + '</span> ' +
' <span class="label">' + escapeHtml(tt(mode === 'permanent' ? 'mode.permanent' : 'mode.trash')) + '</span></div>' +
lines +
' <p class="formMessage" style="margin-top:10px;"><small>' + escapeHtml(tt('result.note')) + '</small></p>' +
' </div>' +
' <div class="actionRow" style="margin-top:16px;">' +
' <button class="primaryBtn" id="quitBtn">' + escapeHtml(tt('result.quitBtn')) + '</button>' +
' </div>' +
'</section>'
document.getElementById('quitBtn').addEventListener('click', function () { api.quit() })
}
;(async function () {
try { I18N = (await api.loadLocale()) || {} } catch (_) { I18N = {} }
applyStaticI18n()
renderConfirm()
})()

View File

@@ -96,6 +96,20 @@ function clearPage() {
pageHost.innerHTML = ''
}
// 첫 진입 안내 페이지: 마인크래프트 런처를 끄고 시작하도록 안내.
function renderIntro() {
setActiveStep(1)
clearPage()
var section = document.createElement('section')
section.className = 'page'
section.innerHTML =
'<h2>' + tt('intro.heading') + '</h2>' +
'<p class="formMessage">' + tt('intro.message') + '</p>' +
'<div class="actionRow"><button class="primaryBtn" id="introNext">' + tt('common.next') + '</button></div>'
pageHost.appendChild(section)
section.querySelector('#introNext').addEventListener('click', renderStep1)
}
function renderStep1() {
setActiveStep(1)
clearPage()
@@ -134,7 +148,7 @@ function renderStep1() {
if (!state.selectedPackKey) return
await installerApi.setSelectedPack(state.selectedPackKey)
state.stepDone[1] = true
renderAgreement()
renderCloseNotice()
})
;(async function () {
@@ -148,72 +162,129 @@ function renderStep1() {
})()
}
// 퀴즈팩 선택 직후 노출하는 "마인크래프트/런처 종료" 강조 안내. 크게 표시.
function renderCloseNotice() {
setActiveStep(1)
clearPage()
var section = document.createElement('section')
section.className = 'page'
section.innerHTML =
'<div style="margin:24px 0;padding:30px 24px;border:2px solid var(--danger);border-radius:14px;background:rgba(248,81,73,0.12);text-align:center;">' +
' <div style="font-size:15px;font-weight:800;color:var(--danger);letter-spacing:2px;">' + escapeHtml(tt('closeNotice.badge')) + '</div>' +
' <div style="font-size:30px;font-weight:900;line-height:1.45;margin-top:16px;">' + escapeHtml(tt('closeNotice.message')) + '</div>' +
' <div style="font-size:14px;color:var(--text-muted);margin-top:18px;">' + escapeHtml(tt('closeNotice.sub')) + '</div>' +
'</div>' +
'<div class="actionRow"><button class="secondaryBtn" id="back">' + tt('common.back') + '</button><button class="primaryBtn" id="next">' + tt('common.next') + '</button></div>'
pageHost.appendChild(section)
section.querySelector('#back').addEventListener('click', renderStep1)
section.querySelector('#next').addEventListener('click', renderAgreement)
}
// 약관 동의 페이지: 음악퀴즈 선택 직후, 싱글/멀티 선택(step2) 진입 전에 노출.
// 메인 설치기는 맵·모드·설치기 세 약관을 모두 확인·동의해야 다음 단계로 갈 수 있다.
// v0.3.4~ : 어떤 약관을 표시할지는 사이트(/manifest/terms/<pack>/index.json) 가
// 결정. 메인 인스톨러용으로 표시 토글된 항목만 받아 탭을 만든다. 목록이 비어 있는 (terms:[])
// 정상 응답일 때만 단계 자체를 건너뛴다. 네트워크 오류/404/서버 오류는 사용자가 약관 동의
// 없이 설치로 넘어가는 것을 막기 위해 오류 화면 + 다시 시도 버튼으로 차단한다.
function renderAgreement() {
setActiveStep(1)
clearPage()
var KINDS = [
{ id: 'map', tab: tt('agreement.tabMap') },
{ id: 'mod', tab: tt('agreement.tabMod') },
{ id: 'installer', tab: tt('agreement.tabInstaller') }
]
var loadingSection = document.createElement('section')
loadingSection.className = 'page'
loadingSection.innerHTML = '<h2>' + tt('agreement.heading') + '</h2>' +
'<p class="formMessage">' + tt('agreement.loading') + '</p>'
pageHost.appendChild(loadingSection)
installerApi.getTermsList().then(function (res) {
if (!res || !res.ok) {
showAgreementError((res && res.message) || 'unknown')
return
}
var terms = (res.terms || []).map(function (t) {
return { id: t.kind, tab: t.label }
})
if (terms.length === 0) {
// 명시적으로 표시 대상이 0개라고 서버가 알려준 정상 응답 → 약관 단계 스킵.
renderStep2()
return
}
clearPage()
renderAgreementWithKinds(terms)
}).catch(function (err) {
showAgreementError(err && err.message ? err.message : 'unknown')
})
}
// 약관 목록을 못 받아왔을 때: 사용자에게 오류 + 다시 시도/뒤로 가기 옵션을 보여준다.
// 동의 없이 설치 단계로 넘어가지 않도록 next 버튼을 두지 않는다.
function showAgreementError(message) {
clearPage()
var section = document.createElement('section')
section.className = 'page'
section.innerHTML =
'<h2>' + tt('agreement.heading') + '</h2>' +
'<p class="formMessage">' + tt('agreement.intro') + '</p>' +
'<div class="tabBar" id="agTabs">' +
KINDS.map(function (k, i) {
return '<button type="button" class="tabBtn' + (i === 0 ? ' active' : '') + '" data-ag="' + k.id + '">' + k.tab + '</button>'
}).join('') +
'</div>' +
'<div class="agreementBody" id="agBody">' + tt('agreement.loading') + '</div>' +
'<label class="toggleRow" style="margin-top:12px;"><input type="checkbox" id="agAccept" /> ' +
tt('agreement.agreeAll') + '</label>' +
'<div class="formMessage" id="agMsg"></div>' +
'<div class="actionRow"><button class="secondaryBtn" id="back">' + tt('common.back') + '</button><button class="primaryBtn" id="next" disabled>' + tt('common.next') + '</button></div>'
'<p class="formMessage error">' + tt('agreement.listLoadFailed', { message: message }) + '</p>' +
'<div class="actionRow">' +
'<button class="secondaryBtn" id="back">' + tt('common.back') + '</button>' +
'<button class="primaryBtn" id="retry">' + tt('agreement.retry') + '</button>' +
'</div>'
pageHost.appendChild(section)
section.querySelector('#back').addEventListener('click', renderStep1)
section.querySelector('#retry').addEventListener('click', renderAgreement)
}
// 약관을 한 건씩 페이지로 보여준다. 각 약관마다 "해당 약관에 동의합니다" 체크가 있고,
// 끝까지 스크롤해 읽어야 체크할 수 있으며, [다음] 을 누르면 다음 약관 페이지가 화면
// 맨 위에서부터 나온다. 마지막 약관까지 동의하면 다음 단계(step2)로 진행한다.
function renderAgreementWithKinds(KINDS) {
var idx = 0
var accepted = {} // kind -> true (뒤로 갔다 와도 동의 상태 유지)
var cache = {} // kind -> 렌더된 HTML
var section = document.createElement('section')
section.className = 'page'
pageHost.appendChild(section)
function renderCurrent() {
var k = KINDS[idx]
var isLast = idx === KINDS.length - 1
section.innerHTML =
'<h2>' + tt('agreement.heading') + '</h2>' +
'<p class="formMessage">' + escapeHtml(tt('agreement.stepLabel', { current: idx + 1, total: KINDS.length, label: k.tab })) + '</p>' +
'<div class="agreementBody" id="agBody" style="border-radius:10px;">' + tt('agreement.loading') + '</div>' +
'<div class="formMessage" id="agHint">' + tt('agreement.readToBottom') + '</div>' +
'<label class="toggleRow" style="margin-top:8px;"><input type="checkbox" id="agAccept" disabled /> ' +
tt('agreement.agreeThis') + '</label>' +
'<div class="formMessage" id="agMsg"></div>' +
'<div class="actionRow"><button class="secondaryBtn" id="back">' + tt('common.back') + '</button><button class="primaryBtn" id="next" disabled>' + tt('common.next') + '</button></div>'
var body = section.querySelector('#agBody')
var tabs = section.querySelectorAll('[data-ag]')
var nextBtn = section.querySelector('#next')
var accept = section.querySelector('#agAccept')
var nextBtn = section.querySelector('#next')
var msg = section.querySelector('#agMsg')
var hint = section.querySelector('#agHint')
// 약관 본문은 한 번 받으면 캐시. 탭 전환 시 재요청하지 않는다.
var cache = {}
// 약관 페이지는 화면 맨 위에서부터 보이도록 스크롤을 올린다.
if (pageHost) pageHost.scrollTop = 0
function showKind(kind) {
if (cache[kind]) {
body.innerHTML = cache[kind]
return
}
body.textContent = tt('agreement.loading')
installerApi.getTerm(kind).then(function (res) {
if (!res.ok) {
body.innerHTML = '<p class="formMessage error">' + tt('agreement.loadFailed', { message: res.message || '' }) + '</p>'
return
}
var html = renderTermsMarkdown(res.content || '')
cache[kind] = html
body.innerHTML = html
}).catch(function (err) {
body.innerHTML = '<p class="formMessage error">' + tt('agreement.loadFailed', { message: err.message }) + '</p>'
})
}
// 약관 본문이 정상 로드된 뒤에만 동의를 허용한다. 로드 실패 상태에서는
// 스크롤을 해도 동의 체크가 켜지지 않는다("무조건 약관을 읽도록").
var termLoaded = false
tabs.forEach(function (b) {
b.addEventListener('click', function () {
tabs.forEach(function (x) { x.classList.remove('active') })
b.classList.add('active')
showKind(b.getAttribute('data-ag'))
})
})
function markReadable() {
if (!termLoaded || !accept.disabled) return
accept.disabled = false
hint.textContent = ''
}
function checkScrolled() {
// 본문을 끝까지(하단 근처) 내렸으면 동의 체크를 허용한다.
if (body.scrollHeight - body.scrollTop - body.clientHeight <= 6) markReadable()
}
body.addEventListener('scroll', checkScrolled)
accept.addEventListener('change', function () {
accepted[k.id] = accept.checked
nextBtn.disabled = !accept.checked
if (accept.checked) msg.textContent = ''
if (accept.checked) { msg.textContent = ''; msg.classList.remove('error') }
})
nextBtn.addEventListener('click', function () {
@@ -222,11 +293,71 @@ function renderAgreement() {
msg.classList.add('error')
return
}
renderStep2()
if (isLast) renderStep2()
else { idx++; renderCurrent() }
})
section.querySelector('#back').addEventListener('click', function () {
if (idx === 0) renderStep1()
else { idx--; renderCurrent() }
})
section.querySelector('#back').addEventListener('click', renderStep1)
showKind(KINDS[0].id)
function afterLoad() {
termLoaded = true
body.scrollTop = 0
// 이미 동의했던 약관으로 되돌아온 경우: 체크/다음 활성화 유지.
if (accepted[k.id]) {
accept.disabled = false
accept.checked = true
nextBtn.disabled = false
hint.textContent = ''
}
// 레이아웃 확정 후: 스크롤이 필요 없을 만큼 짧은 약관이면 바로 동의 허용.
setTimeout(function () {
if (body.scrollHeight - body.clientHeight <= 6) markReadable()
else checkScrolled()
}, 0)
}
// 약관 본문 로드 실패: 동의 불가 상태를 유지하고 다시 시도만 허용한다.
function showLoadError(message) {
termLoaded = false
accept.disabled = true
accept.checked = false
accepted[k.id] = false
nextBtn.disabled = true
hint.textContent = tt('agreement.readToBottom')
body.innerHTML =
'<p class="formMessage error">' + tt('agreement.loadFailed', { message: message || '' }) + '</p>' +
'<div class="actionRow" style="margin-top:10px;"><button class="secondaryBtn" id="agRetry">' + tt('agreement.retry') + '</button></div>'
var retry = section.querySelector('#agRetry')
if (retry) retry.addEventListener('click', loadTerm)
}
function loadTerm() {
if (cache[k.id]) {
body.innerHTML = cache[k.id]
afterLoad()
return
}
body.textContent = tt('agreement.loading')
installerApi.getTerm(k.id).then(function (res) {
if (!res.ok) {
showLoadError(res.message || '')
return
}
var html = renderTermsMarkdown(res.content || '')
cache[k.id] = html
body.innerHTML = html
afterLoad()
}).catch(function (err) {
showLoadError(err && err.message ? err.message : '')
})
}
loadTerm()
}
renderCurrent()
}
// 인스톨러용 미니 markdown 렌더러. 사이트 termsEditor 와 동일한 규칙을 처리한다.
@@ -462,10 +593,17 @@ function renderSubStep31(host, back, done) {
}
function renderSubStep32(host, back, done) {
// 선택한 음악퀴즈(pack)의 권장 JDK. 설치기는 이 버전을 우선 찾고/설치한다.
var selPack = (state.packs && state.packs.find)
? state.packs.find(function (p) { return p.key === state.selectedPackKey })
: null
var recommendedJdk = (selPack && selPack.pack && selPack.pack.recommendedJdk) ? selPack.pack.recommendedJdk : 25
host.innerHTML =
'<h3>' + tt('step3.sub32.heading') + '</h3>' +
'<p class="formMessage">' + tt('step3.sub32.description') + '</p>' +
'<div class="fieldset"><label><input id="jdkPath" type="text" placeholder="C:\\Program Files\\Java\\jdk-17" value="' + (state.serverInstall.jdk || '') + '" /></label>' +
'<p class="formMessage"><strong>' + tt('step3.sub32.recommended', { major: recommendedJdk }) + '</strong></p>' +
'<div class="fieldset"><label><input id="jdkPath" type="text" placeholder="C:\\Program Files\\Java\\jdk-' + recommendedJdk + '" value="' + (state.serverInstall.jdk || '') + '" /></label>' +
'<button class="secondaryBtn" id="pickJdk">' + tt('step3.sub32.pickFolder') + '</button>' +
'<button class="secondaryBtn" id="auto">' + tt('step3.sub32.auto') + '</button>' +
'<button class="secondaryBtn" id="install">' + tt('step3.sub32.install') + '</button></div>' +
@@ -502,14 +640,20 @@ function renderSubStep32(host, back, done) {
autoBtn.addEventListener('click', async function () {
if (installing) return
var detect = await installerApi.detectJdk()
if (detect.found) {
var detect = await installerApi.detectJdk(recommendedJdk)
if (detect.found && detect.match) {
input.value = detect.path
msg.textContent = tt('step3.sub32.found', { path: detect.path })
msg.textContent = tt('step3.sub32.foundRecommended', { path: detect.path, major: recommendedJdk })
msg.classList.remove('error')
msg.classList.add('success')
} else if (detect.found) {
// 권장 버전이 아닌 다른 JDK 를 찾음 → 경고와 함께 채워 넣는다.
input.value = detect.path
msg.textContent = tt('step3.sub32.foundMismatch', { path: detect.path, major: detect.major, required: recommendedJdk })
msg.classList.remove('success')
msg.classList.add('error')
} else {
msg.textContent = tt('step3.sub32.notFound')
msg.textContent = tt('step3.sub32.notFound', { major: recommendedJdk })
msg.classList.remove('success')
msg.classList.add('error')
}
@@ -531,7 +675,7 @@ function renderSubStep32(host, back, done) {
msg.classList.remove('success', 'error')
msg.textContent = tt('step3.sub32.downloading')
try {
var result = await installerApi.installJdk()
var result = await installerApi.installJdk(recommendedJdk)
if (result.ok && result.path) {
input.value = result.path
state.serverInstall.jdk = result.path
@@ -555,24 +699,62 @@ function renderSubStep32(host, back, done) {
if (installing) return
back()
})
nextBtn.addEventListener('click', function () {
nextBtn.addEventListener('click', async function () {
if (installing) return
if (!input.value.trim()) {
var val = input.value.trim()
if (!val) {
msg.textContent = tt('step3.sub32.pathRequired')
msg.classList.add('error')
return
}
state.serverInstall.jdk = input.value.trim()
// 직접 입력/선택한 JDK 를 확인한다. 자바를 못 읽으면 진행을 막고, 권장과 다른
// 버전이면 "정상 실행이 안 될 수 있다"는 경고를 띄운 뒤 사용자가 동의하면 진행한다.
nextBtn.disabled = true
msg.classList.remove('success', 'error')
msg.textContent = tt('step3.sub32.verifying')
var required = recommendedJdk
try {
var v = await installerApi.verifyJdk(val, recommendedJdk)
required = (v && v.required) || recommendedJdk
if (!v || !v.major) {
msg.classList.add('error')
msg.textContent = tt('step3.sub32.versionUnknown')
nextBtn.disabled = false
return
}
if (!v.match) {
// 권장 버전과 다름 → 경고 후 동의 시에만 계속.
var proceed = window.confirm(tt('step3.sub32.mismatchConfirm', { major: v.major, required: required }))
if (!proceed) {
msg.classList.add('error')
msg.textContent = tt('step3.sub32.foundMismatch', { path: val, major: v.major, required: required })
nextBtn.disabled = false
return
}
}
} catch (err) {
msg.classList.add('error')
msg.textContent = tt('step3.sub32.versionUnknown')
nextBtn.disabled = false
return
}
nextBtn.disabled = false
state.serverInstall.jdk = val
done()
})
;(async function () {
var detect = await installerApi.detectJdk()
var detect = await installerApi.detectJdk(recommendedJdk)
if (detect.found && !input.value) {
input.value = detect.path
msg.textContent = tt('step3.sub32.autoDetected', { path: detect.path })
if (detect.match) {
msg.textContent = tt('step3.sub32.foundRecommended', { path: detect.path, major: recommendedJdk })
msg.classList.add('success')
} else {
msg.textContent = tt('step3.sub32.foundMismatch', { path: detect.path, major: detect.major, required: recommendedJdk })
msg.classList.add('error')
}
} else if (!detect.found) {
msg.textContent = tt('step3.sub32.notFoundHint')
msg.textContent = tt('step3.sub32.notFoundHint', { major: recommendedJdk })
}
})()
}
@@ -763,16 +945,20 @@ function renderSubStep35(host, back, done) {
var result = await installerApi.checkPortForward(port)
state.serverInstall.portStatus = result
var address = formatServerAddress(result.externalIp, result.port)
if (result.status === 'preForwarded') {
resultMsg.innerHTML = tt('step3.sub35.preForwarded', { address: address })
resultMsg.classList.add('success')
} else if (result.status === 'upnpOk') {
resultMsg.innerHTML = tt('step3.sub35.upnpOk', { address: address })
resultMsg.classList.add('success')
if (result.status === 'open') {
// 열려 있으면 외부 접속 주소를 크게 표시.
resultMsg.innerHTML =
'<div style="margin-top:12px;padding:18px;border:1px solid var(--success);border-radius:10px;background:rgba(63,185,80,0.12);text-align:center;">' +
'<div style="font-size:14px;color:var(--text-muted);">' + escapeHtml(tt('step3.sub35.openTitle')) + '</div>' +
'<div style="font-size:30px;font-weight:800;margin-top:8px;user-select:all;word-break:break-all;">' + escapeHtml(address) + '</div>' +
'</div>'
} else {
resultMsg.innerHTML = (result.message || tt('step3.sub35.manualHint')) +
tt('step3.sub35.manualDetail', { address: address })
resultMsg.classList.add('warn')
// 안 열려 있으면 "직접 포트포워딩 해주세요" 를 크게 표시.
resultMsg.innerHTML =
'<div style="margin-top:12px;padding:18px;border:1px solid var(--danger);border-radius:10px;background:rgba(248,81,73,0.10);text-align:center;">' +
'<div style="font-size:26px;font-weight:800;">' + escapeHtml(tt('step3.sub35.notOpenBig')) + '</div>' +
'<div style="font-size:13px;color:var(--text-muted);margin-top:10px;">' + escapeHtml(tt('step3.sub35.notOpenHint', { address: address, port: result.port })) + '</div>' +
'</div>'
}
nextBtn.disabled = false
} catch (err) {
@@ -917,11 +1103,17 @@ function renderStep5() {
})
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, function (c) {
return c === '&' ? '&amp;' : c === '<' ? '&lt;' : c === '>' ? '&gt;' : c === '"' ? '&quot;' : '&#39;'
})
}
// 시작 진입점: 사전을 먼저 받아서 정적 텍스트 갱신 후 첫 페이지 렌더.
;(async function () {
try {
I18N = (await installerApi.loadLocale()) || {}
} catch (_) { I18N = {} }
applyStaticI18n()
renderStep1()
renderIntro()
})()

View File

@@ -181,12 +181,15 @@ main {
overflow-y: auto;
font-size: 13px;
line-height: 1.65;
/* 약관 본문은 더 진한 순백으로(제목/굵은글씨/목록). */
color: #fff;
}
.agreementBody h1, .agreementBody h2, .agreementBody h3 { margin: 12px 0 6px; }
.agreementBody h1 { font-size: 17px; }
.agreementBody h2 { font-size: 15px; }
.agreementBody h3 { font-size: 14px; }
.agreementBody p { margin: 6px 0; }
/* 본문 문단은 기존 회색(--text-muted) 대신 이전 흰색 톤(#e6edf3)으로 올린다. */
.agreementBody p { margin: 6px 0; color: #e6edf3; }
.agreementBody ul, .agreementBody ol { margin: 6px 0; padding-left: 22px; }
.agreementBody li { margin: 2px 0; }
.agreementBody code { background: rgba(255,255,255,0.08); padding: 1px 4px; border-radius: 3px; font-family: 'Consolas', monospace; }

View File

@@ -0,0 +1,73 @@
{
"app": {
"title": "마인크래프트 간편 포트포워딩"
},
"logViewer": {
"heading": "로그",
"collapse": "접기",
"expand": "펼치기"
},
"verdict": {
"success": "성공",
"fail": "실패",
"unknown": "확인 불가"
},
"main": {
"heading": "포트 열기",
"intro": "UPnP 로 라우터에 포트를 열고, 외부에서 실제로 닿는지 확인합니다. 마인크래프트 자바 서버는 TCP 25565 를 사용합니다.",
"portLabel": "포트",
"openBtn": "포트 열기 / 확인",
"closeBtn": "포트 닫기",
"quitBtn": "종료",
"working": "포트를 여는 중입니다… (외부 점검까지 최대 1분 정도 걸릴 수 있어요)",
"ipUnknown": "외부IP-확인불가",
"successMsg": "외부에서 접속 가능합니다. 접속 주소: {{addr}}",
"alreadyOpen": "(이미 열려 있던 상태입니다)",
"failMsg": "외부에서 포트에 닿지 않습니다. 라우터 UPnP 설정, 이중 NAT(CGNAT), Windows 방화벽, 또는 포워딩 대상 IP 를 확인하세요.",
"unknownMsg": "외부 도달 여부를 확정하지 못했습니다(외부 점검 서비스 응답 없음). 포트 매핑은 등록되었을 수 있습니다. 잠시 후 다시 시도하거나, 실제 접속으로 확인하세요.",
"manualForward": "자동(UPnP) 개방이 안 되면 라우터 관리페이지에서 수동 포워딩: 외부 TCP {{port}} → 이 PC({{localIp}}) : {{port}}. 그리고 Windows 방화벽에서 TCP {{port}} 인바운드를 허용하세요.",
"manualForwardNoIp": "이 PC 의 LAN IP 를 확인하지 못했습니다. 라우터에서 이 PC 로 외부 TCP {{port}} 포워딩과 Windows 방화벽 인바운드 허용을 설정하세요.",
"cgnatWarn": "주의: CGNAT/이중 NAT 로 보입니다(공인 IP {{public}} ≠ 라우터 WAN {{wan}}, 또는 WAN 이 사설/CGNAT 대역). 이 경우 공유기 포트포워딩만으로는 외부 접속이 불가능하며, ISP 에 공인 IP 를 요청하거나 별도 터널링이 필요합니다.",
"cgnatUnknown": "참고: 외부 IP({{ip}})만으로는 CGNAT(이중 NAT) 를 확정하거나 배제할 수 없습니다(라우터 UPnP 미응답으로 WAN IP 미확인). 라우터 관리페이지의 WAN(인터넷) IP 가 100.64~100.127 이거나 10.x / 192.168.x / 172.16~31 대역이면 이중 NAT 라 공유기 포워딩만으론 외부 접속이 안 됩니다.",
"detailLabel": "점검 상세: {{detail}}",
"error": "오류: {{message}}",
"closed": "포트 {{port}} 매핑을 제거했습니다."
},
"log": {
"start": "포트포워딩 시작: TCP {{port}}",
"localIp": "이 PC LAN IP: {{ip}}",
"routerWan": "라우터 WAN(UPnP) IP: {{ip}}",
"routerWanUnknown": "라우터 WAN IP 확인 불가(UPnP 미응답/거부) → 외부 IP 만으로는 CGNAT 확정/배제 불가",
"cgnatDetected": "CGNAT/이중 NAT 감지: 공인 IP {{public}} vs 라우터 WAN {{wan}}. 공유기 포워딩만으론 외부 접속 불가.",
"cgnatUnknown": "CGNAT 여부 확정 불가(라우터 WAN IP 미확인). 라우터 관리페이지에서 WAN IP 를 확인하세요.",
"upnpUnavailable": "라우터가 UPnP 제어 연결을 거부/미지원(ECONNREFUSED/타임아웃). 라우터에서 UPnP 를 켜거나 수동 포워딩이 필요합니다.",
"cleanup": "이전 UPnP 매핑 정리 중…",
"externalIpHttp": "외부 IP(HTTP): {{ip}}",
"externalIpHttpFail": "외부 IP HTTP 조회 실패 → UPnP 게이트웨이로 폴백",
"probeStart": "외부 포트 점검 시작…",
"probeResult": "점검 결과: {{verdict}} ({{detail}})",
"preForwarded": "이미 외부에서 접속 가능한 상태입니다.",
"upnpTry": "UPnP 포트 개방 시도: TCP {{port}}",
"upnpReqOk": "UPnP 매핑 요청 성공.",
"upnpTryFail": "UPnP 개방 실패: {{message}}",
"recheck": "UPnP 반영 재점검 {{attempt}}/3…",
"upnpDone": "UPnP 개방 확인 완료: TCP {{port}}",
"upnpUnconfirmed": "UPnP 매핑은 등록됐지만 외부 도달은 확정되지 않았습니다.",
"closeTry": "UPnP 매핑 제거 시도: TCP {{port}}",
"upnpRemoveAttempt": "UPnP 매핑 제거 시도: {{message}}",
"upnpRemoveDone": "UPnP 매핑 제거 완료: TCP {{port}}",
"internalError": "내부 오류(무시하고 계속): {{message}}",
"upnpClientFail": "UPnP 클라이언트 생성 실패: {{message}}",
"portInUse": "포트 {{port}}이(가) 이미 사용 중 → 임시 리스너 없이 외부 서비스 응답만으로 판정.",
"listenerBindFail": "임시 리스너 바인딩 실패: {{message}}",
"detailListenerHit": "임시 리스너 도달={{value}}",
"detailListenerSkip": "임시 리스너=skip(포트 사용중)",
"detailIfconfig": "ifconfig.co reachable={{reachable}} ip={{ip}}",
"detailIfconfigFail": "ifconfig.co 실패={{error}}",
"detailNone": "결과 없음"
},
"errors": {
"requestTimeout": "요청 시간 초과",
"upnpTimeout": "UPnP 요청 시간 초과"
}
}

View File

@@ -33,12 +33,17 @@
},
"agreement": {
"heading": "약관 동의",
"intro": "리소스팩을 설치하기 전에 아래 약관을 모두 확인하고 동의해 주세요.",
"intro": "리소스팩을 설치하기 전에 아래 약관을 한 건씩 끝까지 읽고 동의해 주세요.",
"tabResourcepack": "리소스팩 약관",
"tabInstaller": "리소스팩 설치기 약관",
"loading": "약관을 불러오는 중...",
"loadFailed": "약관 로드 실패: {{message}}",
"agreeAll": "위 모든 약관(리소스팩·설치기)에 동의합니다.",
"listLoadFailed": "약관 표시에 실패하여 설치를 진행할 수 없습니다.\n사유: {{message}}\n네트워크 상태를 확인하고 다시 시도하거나, 처음 단계로 돌아가 주세요.",
"retry": "다시 시도",
"agreeAll": "위 모든 약관에 동의합니다.",
"agreeThis": "해당 약관에 동의합니다.",
"readToBottom": "약관을 끝까지 내려서 확인하면 동의할 수 있습니다.",
"stepLabel": "약관 {{current}}/{{total}} — {{label}}",
"agreeRequired": "약관에 동의해야 다음 단계로 진행할 수 있습니다.",
"cancelling": "취소 중…"
},
@@ -61,7 +66,14 @@
},
"step3": {
"heading": "완료",
"message": "리소스팩 설치를 완료했습니다."
"message": "사용자 동의하에 리소스팩 설치되었습니다.",
"applyNotice": "리소스팩은 직접 적용해주세요."
},
"install": {
"errorMessage": "설치 중 오류가 발생했습니다: {{message}}",
"resumeHint": "재시도를 누르면 이미 받아둔 음악·사진은 건너뛰고 실패한 지점부터 이어서 설치합니다. 처음으로를 누르거나 프로그램을 닫으면 지금까지 받아둔 파일은 삭제됩니다.",
"retry": "재시도",
"startOver": "처음으로"
},
"log": {
"manifestDownload": "manifest 다운로드: {{url}}",
@@ -80,9 +92,16 @@
"musicStart": "음악 다운로드 시작 ({{total}}곡, 동시 {{concurrency}}개, 시차 {{stagger}}ms)",
"musicTrackStart": "{{idx}}번 노래 다운로드 시작",
"musicTrackDone": "{{idx}}번 노래 완료: {{name}}",
"musicTrackSkip": "{{idx}}번 노래는 이전에 받아둠 → 건너뜀(이어받기)",
"musicRefreshRetry": "{{count}}곡 다운로드 실패 → yt-dlp/ffmpeg 최신 버전으로 재설치 후 실패한 곡만 재시도",
"ytdlpReinstall": "yt-dlp.exe 최신 버전으로 강제 재설치 중…",
"ffmpegReinstall": "ffmpeg.exe 최신 버전으로 강제 재설치 중…",
"imageStart": "사진 다운로드 시작 ({{total}}장)",
"imageDownloading": "{{idx}}번 사진 다운로드 중…",
"imageDone": "{{idx}}번 사진 완료: {{name}}",
"imageSkip": "{{idx}}번 사진은 이전에 받아둠 → 건너뜀(이어받기)",
"imageCooldown": "음악 다운로드 직후라 유튜브 속도제한을 피하려고 {{secs}}초 대기합니다…",
"imageRetry": "{{idx}}번 사진 재시도 {{attempt}}회차 (HTTP {{code}}) — {{secs}}초 후 다시 시도",
"baseDownload": "베이스 리소스팩 다운로드: {{path}}",
"baseUrl": " URL: {{url}}",
"baseReceived": "베이스 리소스팩 받음 ({{kb}} KB)",
@@ -104,6 +123,8 @@
"packFormatFallback": "pack_format = {{format}} (mcVersion \"{{version}}\" 매칭 실패, 최신 폴백)",
"packFormatRange": "호환 범위 선언: pack_format {{min}} ~ {{max}} (supported_formats / min_format / max_format 모두 기록)",
"soundsMerged": "기존 sounds.json 병합 ({{count}}개 항목)",
"tracksAdded": "음악 트랙 추가됨: {{count}}곡",
"paintingsAdded": "사진 텍스처 추가됨: {{count}}장",
"ytdlpLine": "yt-dlp> {{line}}"
},
"progress": {
@@ -114,7 +135,8 @@
"baseDownloading": "베이스 리소스팩 다운로드 중",
"buildingWithBase": "베이스에 음악·사진 추가 중",
"buildingZip": "zip 빌드 중",
"installComplete": "설치 완료"
"installComplete": "설치 완료",
"imageRetry": "속도제한(HTTP {{code}}) — {{secs}}초 후 재시도"
},
"pack": {
"description": "음악퀴즈 리소스팩 - {{name}}"
@@ -126,6 +148,7 @@
"cancelledByUser": "사용자가 설치를 취소했습니다.",
"musicDownloadFailed": "{{idx}}번 노래 다운로드 실패: {{message}}",
"imageDownloadFailed": "{{idx}}번 사진 다운로드 실패: {{message}}",
"imageRateLimitHint": "유튜브가 IP를 잠시 속도제한(429)했습니다. 몇 분 뒤 다시 설치를 시도하면 이미 받은 사진은 건너뛰고 이어받습니다.",
"imageNormalizeFailed": "{{idx}}번 사진 정규화 실패: {{message}}",
"baseDownloadFailed": "베이스 리소스팩 다운로드 실패: {{message}}",
"ytdlpSignal": "yt-dlp 가 신호 {{signal}} 로 종료됨",
@@ -133,10 +156,13 @@
"ytdlpNoStderr": "(stderr 없음)",
"ytdlpMissingOutput": "예상 출력파일이 없음: {{path}}",
"imageMetaUnknown": "이미지 크기를 읽지 못함",
"imageDataUrlInvalid": "data: URL 형식이 올바르지 않아 이미지를 디코드하지 못했습니다.",
"ytdlpVerifyFailed": "yt-dlp.exe 다운로드는 됐지만 실행 검증에 실패했습니다.",
"ytdlpInstallFailed": "yt-dlp.exe 자동 설치 실패: {{message}}",
"ffmpegNotInZip": "zip 내부에서 ffmpeg.exe 를 찾을 수 없습니다.",
"ffmpegVerifyFailed": "ffmpeg.exe 다운로드는 됐지만 실행 검증에 실패했습니다.",
"ffmpegInstallFailed": "ffmpeg.exe 자동 설치 실패: {{message}}"
"ffmpegInstallFailed": "ffmpeg.exe 자동 설치 실패: {{message}}",
"baseTrackCollision": "베이스 리소스팩에 같은 트랙 ID 가 이미 있어 설치를 중단합니다: {{trackId}}\n베이스 자산을 보존하면서 새 트랙을 같은 ID 로 추가할 수 없습니다. 베이스의 sounds.json 엔트리/sounds 폴더에서 충돌하는 항목을 제거하거나 다른 베이스를 사용하세요.",
"basePaintingCollision": "베이스 리소스팩에 같은 사진 파일이 이미 있어 설치를 중단합니다: {{name}}\n베이스의 painting 텍스처를 보존하면서 같은 파일명을 추가할 수 없습니다. 베이스에서 충돌하는 파일을 제거하거나 다른 베이스를 사용하세요."
}
}

View File

@@ -0,0 +1,63 @@
{
"app": {
"title": "음악퀴즈 파일제거"
},
"logViewer": {
"heading": "로그",
"collapse": "접기",
"expand": "펼치기"
},
"mode": {
"trash": "휴지통으로 이동",
"permanent": "컴퓨터에서 완전 삭제"
},
"confirm": {
"heading": "음악퀴즈 파일제거",
"question": "음악퀴즈 간편설치기로 설치한 내용들과, 음악퀴즈 관련된 내용을 전부 삭제하시겠습니까?",
"detail": "음악퀴즈 간편설치기·리소스팩설치기가 만든 게임 폴더와 캐시, 마인크래프트 런처의 음악퀴즈 프로필을 정리합니다. 평소 쓰던 .minecraft 본체는 건드리지 않습니다.",
"loadingPreview": "삭제 대상을 확인하는 중…",
"previewTitle": "삭제 대상",
"itemCustomDir": "음악퀴즈 전용 폴더: {{path}}",
"itemCustomDirMissing": "음악퀴즈 전용 폴더가 없음(이미 삭제됨): {{path}}",
"itemShortcut": "바탕화면의 'MusicQuiz Server' 바로가기",
"itemProfiles": "마인크래프트 런처 프로필: {{names}}",
"nothingFound": "삭제할 음악퀴즈 관련 항목을 찾지 못했습니다. 이미 정리된 상태일 수 있습니다.",
"previewFail": "삭제 대상 확인 실패: {{message}}",
"agreeBtn": "동의하고 계속",
"cancelBtn": "취소(종료)"
},
"choose": {
"heading": "삭제 방식 선택",
"intro": "삭제 방식을 선택하세요.",
"trashTitle": "휴지통으로 이동",
"trashDesc": "휴지통으로 옮깁니다. 실수했을 때 되돌릴 수 있습니다.",
"permTitle": "컴퓨터에서 완전 삭제",
"permDesc": "휴지통을 거치지 않고 즉시 완전히 지웁니다. 되돌릴 수 없습니다.",
"backBtn": "뒤로",
"confirmTrash": "선택한 음악퀴즈 관련 항목을 휴지통으로 이동합니다. 계속하시겠습니까?",
"confirmPermanent": "선택한 음악퀴즈 관련 항목을 컴퓨터에서 완전히 삭제합니다. 되돌릴 수 없습니다. 계속하시겠습니까?",
"running": "삭제하는 중…",
"error": "삭제 중 오류: {{message}}"
},
"result": {
"badgeOk": "완료",
"badgePartial": "일부 실패",
"removedTitle": "삭제한 항목",
"profilesTitle": "제거한 런처 프로필",
"errorsTitle": "삭제하지 못한 항목",
"nothing": "삭제할 항목이 없었습니다.",
"note": "직접 지정한 위치에 서버를 설치했다면 그 폴더는 위치를 알 수 없어 자동 삭제되지 않습니다. 필요하면 직접 삭제하세요.",
"quitBtn": "종료"
},
"log": {
"start": "삭제 시작 ({{mode}})",
"removedDir": "폴더 제거: {{path}}",
"removedShortcut": "바로가기 제거: {{path}}",
"removedProfile": "런처 프로필 제거: {{name}}",
"removeFail": "제거 실패: {{path}} — {{message}}",
"customDirMissing": "음악퀴즈 폴더가 이미 없음: {{path}}",
"launcherParseFail": "launcher_profiles.json 을 읽지 못함: {{path}}",
"launcherWriteFail": "launcher_profiles.json 갱신 실패: {{message}}",
"done": "정리 완료 — 총 {{count}}개 항목 처리"
}
}

View File

@@ -1,4 +1,13 @@
{
"intro": {
"heading": "시작하기 전에",
"message": "마인크래프트 런처를 끄고 시작해주세요."
},
"closeNotice": {
"badge": "⚠ 매우 중요",
"message": "마인크래프트와 마인크래프트 런처를 종료한 뒤 진행해주세요",
"sub": "실행 중이면 설치 설정이 제대로 적용되지 않을 수 있습니다."
},
"common": {
"back": "이전",
"next": "다음",
@@ -32,13 +41,18 @@
},
"agreement": {
"heading": "약관 동의",
"intro": "설치 전에 아래 약관을 모두 확인하고 동의해 주세요.",
"intro": "설치 전에 아래 약관을 한 건씩 끝까지 읽고 동의해 주세요.",
"tabMap": "맵 약관",
"tabMod": "모드 약관",
"tabInstaller": "설치기 약관",
"loading": "약관을 불러오는 중...",
"loadFailed": "약관 로드 실패: {{message}}",
"agreeAll": "위 모든 약관(맵·모드·설치기)에 동의합니다.",
"listLoadFailed": "약관 표시에 실패하여 설치를 진행할 수 없습니다.\n사유: {{message}}\n네트워크 상태를 확인하고 다시 시도하거나, 처음 단계로 돌아가 주세요.",
"retry": "다시 시도",
"agreeAll": "위 모든 약관에 동의합니다.",
"agreeThis": "해당 약관에 동의합니다.",
"readToBottom": "약관을 끝까지 내려서 확인하면 동의할 수 있습니다.",
"stepLabel": "약관 {{current}}/{{total}} — {{label}}",
"agreeRequired": "약관에 동의해야 다음 단계로 진행할 수 있습니다."
},
"step1": {
@@ -76,17 +90,24 @@
"auto": "자동 탐색",
"install": "자동 설치",
"installCancel": "설치 취소",
"recommended": "권장 JDK: Java {{major}} (이 음악퀴즈 서버 실행용)",
"found": "JDK 발견: {{path}}",
"foundRecommended": "권장 JDK(Java {{major}}) 발견: {{path}}",
"foundMismatch": "⚠ 권장(Java {{required}})이 아닌 Java {{major}} 를 찾았습니다: {{path}} — 권장 버전과 달라 서버가 정상 실행되지 않을 수 있습니다. 권장 버전을 쓰려면 \"자동 설치\" 를 누르세요.",
"mismatchConfirm": "선택한 Java {{major}} 는 권장 버전(Java {{required}})과 다릅니다. 권장 버전과 달라 서버가 정상 실행되지 않을 수 있습니다. 이대로 계속하시겠습니까?",
"autoDetected": "JDK 자동 탐색됨: {{path}}",
"notFound": "JDK를 자동으로 찾지 못했습니다. \"자동 설치\" 를 눌러 JDK를 설치하거나 직접 선택해 주세요.",
"notFoundHint": "JDK를 자동으로 찾지 못했습니다. \"자동 설치\" 를 누르면 JDK를 받아 설치합니다.",
"notFound": "서버 실행에 필요한 Java {{major}} 이상을 찾지 못했습니다(낮은 버전이 설치돼 있어도 서버가 뜨지 않습니다). \"자동 설치\" 를 눌러 설치하거나 직접 선택해 주세요.",
"notFoundHint": "Java {{major}} 이상을 찾지 못했습니다. \"자동 설치\" 를 누르면 Temurin {{major}} 를 받아 설치합니다.",
"cancelRequested": "JDK 설치 취소 요청 중...",
"downloading": "JDK 다운로드 중...",
"installComplete": "JDK 자동 설치 완료: {{path}}",
"installCanceled": "JDK 설치 취소됨",
"installFailed": "JDK 설치 실패: {{message}}",
"installError": "JDK 설치 오류: {{message}}",
"pathRequired": "JDK 경로를 입력해 주세요."
"pathRequired": "JDK 경로를 입력해 주세요.",
"verifying": "선택한 JDK 버전을 확인하는 중…",
"versionTooLow": "선택한 Java {{major}} 는 너무 낮습니다. 서버 실행에는 Java {{required}} 이상이 필요합니다. \"자동 설치\" 로 Temurin {{required}} 를 받거나 Java {{required}} 이상 폴더를 선택해 주세요.",
"versionUnknown": "선택한 경로에서 Java 실행 파일을 찾지 못했거나 버전을 확인할 수 없습니다. JDK 폴더(bin\\java.exe 가 있는 곳)를 선택하거나 \"자동 설치\" 를 눌러 주세요."
},
"sub33": {
"heading": "서버 다운로드 및 설치",
@@ -118,14 +139,13 @@
},
"sub35": {
"heading": "포트포워딩",
"description": "UPNP를 개방해 외부 접속을 허용합니다.",
"description": "포트가 외부에서 열려 있는지 확인합니다. (설치기가 직접 열지는 않습니다)",
"portLabel": "포트",
"recheck": "재점검",
"checking": "확인 중...",
"preForwarded": "포트포워딩 성공! 친구는 <strong>{{address}}</strong> 주소로 서버에 접속할 수 있습니다. (이미 외부 개방되어 있음)",
"upnpOk": "포트포워딩 성공! 친구는 <strong>{{address}}</strong> 주소로 서버에 접속할 수 있습니다. (UPnP로 자동 개방 완료)",
"manualHint": "직접 포트포워딩을 해주세요.",
"manualDetail": "<br><small>외부 주소: {{address}}</small>",
"openTitle": "포트가 열려 있습니다! 친구 접속 주소",
"notOpenBig": "직접 포트포워딩 해주세요.",
"notOpenHint": "공유기에서 외부 TCP {{port}} 를 이 PC 로 포워딩하세요. (외부 주소: {{address}})",
"checkFailed": "점검 실패: {{message}}",
"ipUnknown": "확인 불가"
}
@@ -181,7 +201,6 @@
"fabricLoaderRequired": "Fabric 로더 버전이 음악퀴즈에 지정되지 않았습니다. 관리 사이트에서 platform.loaderVersion 을 설정해 주세요.",
"fabricInstallerListEmpty": "Fabric installer 목록을 받지 못했습니다.",
"portAllocFail": "포트를 할당할 수 없습니다.",
"upnpTimeout": "UPnP 응답 없음(타임아웃 15s). 라우터의 UPnP가 꺼져 있거나 SSDP 패킷이 차단됐을 수 있습니다.",
"parseResponseFailed": "응답 파싱 실패: {{snippet}}"
},
"log": {
@@ -189,7 +208,7 @@
"packLoadFail": "pack 로드 실패 ({{file}}): {{message}}",
"packsLoaded": "로드된 음악퀴즈: {{count}}개",
"selectedPack": "선택: {{key}}",
"jdkInstallStart": "JDK(Temurin 21) 자동 설치 시작 — 다운로드 중...",
"jdkInstallStart": "JDK(Temurin {{major}}) 자동 설치 시작 — 다운로드 중...",
"jdkDownloadProgress": "JDK 다운로드: {{percent}}% ({{loaded}}MB / {{total}}MB)",
"jdkExtracting": "JDK 압축 해제 중...",
"jdkDoneRoot": "JDK 자동 설치 완료: {{path}}",
@@ -212,15 +231,12 @@
"skipResourcepack": "resourcepackPath가 비어 있어 리소스팩 다운로드를 건너뜁니다.",
"resourcepackDownload": "리소스팩 다운로드: {{url}}",
"serverInstallPath": "서버 설치 경로: {{path}}",
"runBatMissing": "run.bat 이 없어 UPnP 자동 등록 스크립트 주입을 건너뜁니다.",
"runBatAlreadyInjected": "run.bat 에 이미 UPnP 자동 등록 스크립트가 들어 있어 건너뜁니다.",
"runBatNoJava": "run.bat 에서 java 호출 라인을 찾지 못해 UPnP 자동 등록 주입을 건너뜁니다.",
"runBatInjected": "run.bat 에 서버 기동/종료 시 UPnP 자동 등록·해제 스크립트를 추가했습니다.",
"runBatJavaPatched": "run.bat 이 설치기가 준비한 자바를 쓰도록 수정했습니다: {{java}}",
"runBatJavaSkip": "설치기가 준비한 JDK 를 찾지 못해 run.bat 의 자바 경로는 그대로 둡니다(시스템 자바 사용).",
"mojangEulaFetchFail": "Minecraft EULA 페이지 조회 실패: {{message}}",
"eulaAccepted": "EULA 동의 저장 완료.",
"configEditorOpen": "서버 설정 편집기 실행: {{url}}",
"portCheckStart": "포트포워딩 점검 시작: 포트 {{port}}",
"upnpCleanup": "이전 실행의 UPnP 매핑이 남아 있으면 제거합니다(중복 방지)...",
"externalIpHttp": "외부 IP 확인(HTTP): {{ip}}",
"externalIpHttpFail": "외부 IP 확인 실패(HTTP). UPnP 게이트웨이를 통한 조회 시도...",
"externalIpUpnp": "외부 IP 확인(UPnP): {{ip}}",
@@ -232,15 +248,6 @@
"probeVerdictUnknown": "확인 불가",
"probePreForwarded": "외부에서 {{addr}}:{{port}} 접근 확인됨. 사용자 규칙으로 포워딩 됨.",
"ipUnknown": "(IP 미상)",
"upnpTryOpen": "UPnP로 포트 {{port}} 자동 개방 시도(TCP)...",
"upnpReqOk": "UPnP portMapping 요청 성공. 외부 접근을 재확인합니다.",
"upnpTryFail": "UPnP 시도 실패: {{message}}",
"upnpFailDetail": "UPnP 실패: {{message}}. 라우터에서 UPnP가 꺼져 있을 수 있습니다. 직접 포트포워딩을 해주세요.",
"upnpRecheck": "UPnP 적용 후 재점검 {{attempt}}/3...",
"upnpDone": "UPnP로 포트 {{port}} 자동 개방 완료. 테스트 매핑을 제거합니다(실제 개방은 run.bat 이 서버 기동 시 자동으로 처리).",
"upnpCleanupTest": "테스트용 UPnP 매핑을 정리합니다.",
"upnpFailReason1": "UPnP 매핑은 등록됐지만 외부 포트체크 서비스에서 연결이 닿지 않았습니다. ISP 차단, 이중 NAT, 또는 방화벽 설정을 확인하세요.",
"upnpFailReason2": "외부 포트체크 결과를 받지 못했습니다({{detail}}). UPnP 매핑은 등록됐을 수 있습니다.",
"upnpClientFail": "UPnP 클라이언트 생성 실패: {{message}}",
"upnpExternalTimeout": "UPnP externalIp 조회 타임아웃(8s).",
"upnpExternalErr": "UPnP externalIp 오류: {{message}}",
@@ -251,10 +258,6 @@
"detailIfconfig": "ifconfig.co reachable={{reachable}} ip={{ip}}",
"detailIfconfigFail": "ifconfig.co 실패={{error}}",
"detailNone": "결과 없음",
"upnpClientFailRemove": "UPnP 클라이언트 생성 실패(매핑 제거 단계): {{message}}",
"upnpRemoveTimeout": "UPnP 매핑 제거 응답 없음(타임아웃 8s). 라우터에 우리가 만든 규칙이 없을 수 있습니다.",
"upnpRemoveAttempt": "UPnP 매핑 제거 시도 결과: {{message}} (없으면 정상)",
"upnpRemoveDone": "UPnP 매핑 제거 완료(포트 {{port}}).",
"platformDownload": "플랫폼({{type}}) 다운로드: {{url}}",
"platformSaved": "플랫폼 설치파일 저장: {{path}} (사용자가 직접 실행하거나 마인크래프트 런처에서 인식할 수 있습니다.)",
"platformSkipped": "플랫폼 설치 건너뜀. 바닐라로 진행합니다.",
@@ -291,7 +294,8 @@
"launcherAppsFolderFail": "AppsFolder 실행 실패: {{message}}",
"launcherUrlSchemeFallback": "마지막 시도: minecraft:// URL 스킴 (런처가 없으면 MS Store 가 열릴 수 있음).",
"launcherUrlSchemeFail": "URL 스킴 실행 실패: {{message}}.",
"launcherAllFail": "Minecraft Launcher 실행 시도가 모두 실패했습니다. minecraft.net 또는 Microsoft Store 에서 \"Minecraft Launcher\" 를 설치한 뒤 다시 시도해 주세요."
"launcherAllFail": "Minecraft Launcher 실행 시도가 모두 실패했습니다. minecraft.net 또는 Microsoft Store 에서 \"Minecraft Launcher\" 를 설치한 뒤 다시 시도해 주세요.",
"internalError": "내부 오류(무시하고 계속): {{message}}"
},
"candidates": {
"winProgramFiles86": "Win32 설치(Program Files (x86))",

View File

@@ -30,7 +30,8 @@
"title": "관리자 로그인",
"password": "비밀번호",
"submit": "로그인",
"wrongPassword": "비밀번호가 올바르지 않습니다."
"wrongPassword": "비밀번호가 올바르지 않습니다.",
"tooManyAttempts": "로그인 시도가 너무 많습니다. 약 {{minutes}}분 후 다시 시도해 주세요."
},
"dashboard": {
"title": "음악퀴즈 목록",
@@ -78,6 +79,11 @@
"aliasPlaceholder": "별칭 입력",
"aliasRemove": "삭제",
"aliasHint": "정답으로 인정할 다른 표기·번역·약칭을 추가할 수 있습니다.",
"descBtn": "설명",
"descModalTitle": "설명 - {{title}}",
"descBack": "← 돌아가기",
"descPlaceholder": "이 곡에 대한 설명을 입력하세요",
"descHint": "곡 소개·트리비아 등 자유 메모. 정답 채점이나 데이터팩에는 사용되지 않습니다.",
"metaLoading": "메타데이터 가져오는 중…",
"metaFailedShort": "메타 조회 실패",
"metaFailedTitle": "메타데이터 조회 실패",
@@ -119,6 +125,13 @@
"serverMaxRam": "서버 최대 램 (MB)",
"clientMinRam": "클라이언트 최소 램 (MB)",
"clientRecommendedRam": "클라이언트 권장 램 (MB)",
"recommendedJdk": "권장 JDK (서버 실행용)",
"recommendedJdkHint": "설치기가 이 버전을 우선 찾고, 없으면 자동 설치합니다. 서버가 요구하는 자바 버전에 맞춰 고르세요(최신 마인크래프트는 보통 Java 25). 목록은 Adoptium(Temurin)에서 실제 배포되는 버전을 불러옵니다.",
"jdkShowDetails": "자세히 보기 (모든 버전·스냅샷)",
"jdkDetailsGa": "정식(GA)",
"jdkDetailsEa": "개발 스냅샷(EA)",
"jdkDetailsNone": "상세 버전 정보를 불러오지 못했습니다.",
"jdkLtsSuffix": " (LTS)",
"mapPath": "맵 파일 (.zip)",
"mapPathHint": "/file/maps/ 아래 zip 파일 이름.",
"serverPath": "서버 파일 (.zip)",
@@ -136,6 +149,9 @@
"terms": {
"browserTitle": "약관 수정",
"title": "약관 수정",
"pickPackHint": "약관을 수정할 음악퀴즈를 선택하세요. 각 음악퀴즈마다 약관을 따로 보관합니다.",
"packBrowserTitle": "{{name}} — 약관 수정",
"packTitle": "{{name}} 약관 수정",
"hint": "수정할 약관을 선택하세요. 사이트에서 저장한 내용은 인스톨러가 약관 동의 화면에서 사용합니다.",
"editorBrowserTitle": "{{label}} 편집",
"editorTitle": "{{label}}",
@@ -157,7 +173,11 @@
"slashQuote": "인용",
"slashCode": "코드",
"leaveConfirm": "저장하지 않은 변경사항이 있습니다.\n저장 없이 이 페이지를 떠나시겠습니까?",
"builtinBadge": "기본",
"visibilityHeading": "표시 대상 (중복 선택 가능)",
"visibilityInstaller": "설치기에 표시",
"visibilityInstallerRp": "리소스팩 설치기에 표시",
"visibilityInstallerShort": "설치기",
"visibilityInstallerRpShort": "리소스팩",
"addHeading": "약관 추가",
"kindLabel": "식별자",
"kindPlaceholder": "예: privacy",
@@ -169,7 +189,16 @@
"deleteConfirm": "정말 \"{{label}}\" 약관을 삭제할까요? 이 동작은 되돌릴 수 없습니다.",
"invalidKind": "식별자는 소문자/숫자/하이픈만, 32자 이내여야 합니다.",
"createFailed": "약관 추가 실패",
"cannotDeleteBuiltin": "기본 약관은 삭제할 수 없습니다."
"cannotDeleteBuiltin": "기본 약관은 삭제할 수 없습니다.",
"importHeading": "다른 음악퀴즈에서 불러오기",
"importSourceLabel": "가져올 음악퀴즈",
"importSourcePlaceholder": "음악퀴즈를 선택하세요",
"importHint": "선택한 음악퀴즈의 모든 약관(.md + 라벨)을 현재 음악퀴즈로 복사합니다. 같은 식별자의 약관이 있으면 덮어씁니다.",
"importButton": "불러오기",
"importEmpty": "불러올 수 있는 다른 음악퀴즈가 없습니다.",
"importConfirm": "선택한 음악퀴즈의 약관을 현재 음악퀴즈로 복사합니다. 같은 식별자의 약관은 덮어쓰여집니다. 진행할까요?",
"importFailed": "약관 불러오기 실패",
"invalidImportSource": "올바르지 않은 음악퀴즈입니다."
},
"datapack": {
"browserTitle": "데이터팩 수정",
@@ -204,9 +233,11 @@
"youtube": {
"ytdlpUnavailable": "yt-dlp 를 준비하지 못했습니다. (수동 입력으로 진행)",
"ytdlpVerifyFailed": "yt-dlp 다운로드는 됐지만 실행 검증에 실패했습니다.",
"ytdlpVerifyFailedDetail": "yt-dlp 를 사용할 수 없습니다. 시도한 경로 진단: {{detail}}",
"ytdlpInstallFailed": "yt-dlp 자동 설치에 실패했습니다: {{message}}",
"ytdlpVideoFailed": "yt-dlp 영상 조회 실패 (code={{code}}): {{detail}}",
"ytdlpPlaylistFailed": "yt-dlp 플레이리스트 조회 실패 (code={{code}}): {{detail}}",
"tooManyRedirects": "redirect 가 너무 많습니다."
"tooManyRedirects": "redirect 가 너무 많습니다.",
"invalidUrl": "올바르지 않은 URL 입니다. http/https 주소만 허용됩니다."
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "minecraft-music-quiz-installer",
"version": "0.3.1",
"version": "0.4.10",
"description": "마인크래프트 음악퀴즈 간편설치기 + 관리 사이트",
"main": "dist/installer/main.js",
"scripts": {
@@ -9,10 +9,16 @@
"dev:server": "tsc -p tsconfig.server.json && node dist/server/app.js",
"installer": "tsc -p tsconfig.installer.json && electron .",
"installer:rp": "tsc -p tsconfig.installer-rp.json && electron dist/installer-rp/main.js",
"installer:pf": "tsc -p tsconfig.installer-pf.json && electron dist/installer-pf/main.js",
"installer:uninstall": "tsc -p tsconfig.installer-uninstall.json && electron dist/installer-uninstall/main.js",
"preinstall:sharp-win32": "npm install --no-save --force @img/sharp-win32-x64@0.34.5",
"build:launcher-icon": "node scripts/build-launcher-icon.cjs",
"dist:win": "npm run preinstall:sharp-win32 && npm run build:launcher-icon && tsc -p tsconfig.installer.json && electron-builder --win --config electron-builder.yml",
"dist:win:rp": "npm run preinstall:sharp-win32 && tsc -p tsconfig.installer-rp.json && electron-builder --win --config electron-builder-rp.yml"
"dist:win:rp": "npm run preinstall:sharp-win32 && tsc -p tsconfig.installer-rp.json && electron-builder --win --config electron-builder-rp.yml",
"dist:win:pf": "tsc -p tsconfig.installer-pf.json && electron-builder --win --config electron-builder-pf.yml",
"dist:win:dev": "npm run preinstall:sharp-win32 && npm run build:launcher-icon && tsc -p tsconfig.installer.json && electron-builder --win --config electron-builder-dev.yml",
"dist:win:rp:dev": "npm run preinstall:sharp-win32 && tsc -p tsconfig.installer-rp.json && electron-builder --win --config electron-builder-rp-dev.yml",
"dist:win:uninstall": "tsc -p tsconfig.installer-uninstall.json && electron-builder --win --config electron-builder-uninstall.yml"
},
"dependencies": {
"@types/archiver": "^7.0.0",

View File

@@ -103,6 +103,7 @@
var aliasLabel = aliasCount > 0
? tt('aliasBtnWithCount', { count: aliasCount })
: tt('aliasBtn')
var hasDesc = typeof entry.description === 'string' && entry.description.trim().length > 0
li.innerHTML =
'<span class="rowNum">' + (idx + 1) + '</span>' +
'<img class="rowThumb" src="' + thumbUrl(entry.url) + '" alt="" loading="lazy" draggable="false"/>' +
@@ -114,12 +115,16 @@
escapeHtml(entry.artist || '') +
'</div>' +
'</div>' +
'<button type="button" class="descBtn' + (hasDesc ? ' hasDesc' : '') + '" data-desc-open="' + idx + '" draggable="false">' +
escapeHtml(tt('descBtn')) +
'</button>' +
'<button type="button" class="aliasBtn' + (aliasCount > 0 ? ' hasAliases' : '') + '" data-alias-open="' + idx + '" draggable="false">' +
escapeHtml(aliasLabel) +
'</button>' +
'<span class="rowDur">' + fmtTime(entry.durationSec) + '</span>'
attachDraggable(li, 'music', idx)
attachInlineEdit(li, idx)
attachDescBtn(li, idx)
attachAliasBtn(li, idx)
ol.appendChild(li)
})
@@ -391,7 +396,10 @@
url: meta.url || url,
title: meta.title || prev.title || '',
artist: meta.channel || prev.artist || '',
durationSec: typeof meta.durationSec === 'number' ? meta.durationSec : (prev.durationSec || 0)
durationSec: typeof meta.durationSec === 'number' ? meta.durationSec : (prev.durationSec || 0),
// URL 만 바뀌었다고 운영자가 손으로 입력한 메타(별칭/설명)까지 날려선 안 된다.
aliases: Array.isArray(prev.aliases) ? prev.aliases : [],
description: typeof prev.description === 'string' ? prev.description : ''
}
markDirty()
closeAllModals()
@@ -527,6 +535,57 @@
if (e.target === aliasModal) closeAliasModalSaving()
})
// ── 설명 모달 (음악) ─────────────────────────────────
// 별칭 모달과 같은 패턴: 모달 닫힐 때 textarea 값을 state.music[idx].description 에 저장.
var descModal = document.getElementById('descModal')
var descTextarea = document.getElementById('desc-textarea')
var descModalTitleEl = document.getElementById('desc-modal-title')
var descBackBtn = document.getElementById('desc-back')
var descEditingIdx = -1
function attachDescBtn(li, idx) {
var btn = li.querySelector('[data-desc-open]')
if (!btn) return
btn.addEventListener('mousedown', function (e) { e.stopPropagation() })
btn.addEventListener('click', function (e) {
e.stopPropagation()
openDescModal(idx)
})
}
function openDescModal(idx) {
if (!state.music[idx]) return
descEditingIdx = idx
var entry = state.music[idx]
descModalTitleEl.textContent = tt('descModalTitle', { title: entry.title || tt('titleFallback') })
descTextarea.value = typeof entry.description === 'string' ? entry.description : ''
descModal.hidden = false
setTimeout(function () { descTextarea.focus() }, 0)
}
function closeDescModalSaving() {
if (descEditingIdx < 0 || !state.music[descEditingIdx]) {
descModal.hidden = true
descEditingIdx = -1
return
}
// textarea 값을 그대로 저장하되, 줄바꿈은 보존하고 양끝 공백만 다듬는다.
var nextDesc = (descTextarea.value || '').replace(/\r\n/g, '\n').trim()
var prev = state.music[descEditingIdx].description || ''
if (nextDesc !== prev) {
state.music[descEditingIdx].description = nextDesc
markDirty()
renderMusic()
}
descModal.hidden = true
descEditingIdx = -1
}
descBackBtn.addEventListener('click', closeDescModalSaving)
descModal.addEventListener('click', function (e) {
if (e.target === descModal) closeDescModalSaving()
})
// ── 사진목록: 음악목록 그대로 복사 ─────────────────
document.getElementById('image-from-music').addEventListener('click', function () {
if (state.music.length === 0) {
@@ -637,7 +696,7 @@
var entries = result.body.entries || []
if (target === 'music') {
state.music = entries.map(function (e) {
return { url: e.url, title: e.title || '', artist: e.channel || '', durationSec: e.durationSec || 0 }
return { url: e.url, title: e.title || '', artist: e.channel || '', durationSec: e.durationSec || 0, aliases: [], description: '' }
})
renderMusic()
} else {

View File

@@ -407,19 +407,24 @@ body.siteBody.centerLayout {
.trackList { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 4px; }
.trackRow {
display: grid;
grid-template-columns: 36px 80px 1fr auto auto;
grid-template-columns: 36px 80px 1fr auto auto auto;
gap: 12px; align-items: center;
padding: 8px 12px; background: var(--bg-card);
border: 1px solid var(--border); border-radius: 8px;
cursor: grab; user-select: none;
}
.aliasBtn {
.aliasBtn, .descBtn {
background: var(--bg); border: 1px solid var(--border); color: var(--text);
padding: 6px 10px; border-radius: 6px; cursor: pointer; font-size: 12px;
white-space: nowrap;
}
.aliasBtn:hover { border-color: var(--accent); }
.aliasBtn.hasAliases { border-color: var(--accent); color: var(--accent); }
.aliasBtn:hover, .descBtn:hover { border-color: var(--accent); }
.aliasBtn.hasAliases, .descBtn.hasDesc { border-color: var(--accent); color: var(--accent); }
.descTextarea {
width: 100%; min-height: 140px; resize: vertical;
font-family: inherit; font-size: 13px; line-height: 1.5;
padding: 8px 10px;
}
/* 별칭 모달 */
.aliasModalHeader {

View File

@@ -15,6 +15,8 @@
var dirtyMark = document.getElementById('dirty-mark')
var saveBtn = document.getElementById('saveBtn')
var tabBtns = document.querySelectorAll('.tabBar .tabBtn')
var visInstaller = document.getElementById('visInstaller')
var visInstallerRp = document.getElementById('visInstallerRp')
editor.value = INITIAL || ''
var dirty = false
@@ -23,6 +25,10 @@
dirtyMark.hidden = !v
}
// 토글이 바뀌어도 dirty 표시. 저장 시 함께 전송된다.
if (visInstaller) visInstaller.addEventListener('change', function () { setDirty(true) })
if (visInstallerRp) visInstallerRp.addEventListener('change', function () { setDirty(true) })
// ─── markdown 미리 보기용 미니 렌더러 ────────────────────────────────
// 정식 markdown 파서는 아니지만, 본 편집기가 만들어 내는 형태(#, ##, ###,
// - , 1. , > , ---, ``` , 토글 details) 정도는 충실히 처리한다.
@@ -162,10 +168,13 @@
function save() {
status.classList.remove('error')
status.textContent = I18N.saving
fetch('/op/agreement/' + encodeURIComponent(TERM_KIND), {
var payload = { content: editor.value }
if (visInstaller) payload.showInInstaller = !!visInstaller.checked
if (visInstallerRp) payload.showInInstallerRp = !!visInstallerRp.checked
fetch('/op/agreement/' + encodeURIComponent(PACK_KEY) + '/' + encodeURIComponent(TERM_KIND), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content: editor.value })
body: JSON.stringify(payload)
}).then(function (r) {
return r.json().then(function (j) { return { ok: r.ok && j && j.ok !== false, body: j } })
}).then(function (res) {

View File

@@ -8,26 +8,45 @@
// build/ 폴더는 electron-builder 가 exe 아이콘으로만 쓰고 asar 에
// 포함되지 않아서, 런타임에 그 파일을 읽을 수 없다. 대신 빌드(개발) 시점에
// 이 스크립트를 돌려 PNG 를 소스 코드에 인라인한다.
//
// 마인크래프트 런처의 사용자 지정 설치 아이콘 규격은 "128x128 PNG" 로
// 고정돼 있다(https://minecraft.wiki/w/Launcher). 이 규격과 다른 크기
// (예: 원본 256x256)를 주면 런처가 아이콘을 무시하고 기본 아이콘(화로)으로
// 폴백한다. 그래서 build/icon.png 를 정확히 128x128 로 리사이즈해서 박는다.
// exe 아이콘(build/icon.ico, build/icon.png)은 256x256 그대로 둔다.
'use strict'
const fs = require('node:fs')
const path = require('node:path')
const sharp = require('sharp')
const repoRoot = path.resolve(__dirname, '..')
const pngPath = path.join(repoRoot, 'build', 'icon.png')
const tsPath = path.join(repoRoot, 'src', 'installer', 'launcherIcon.ts')
const buf = fs.readFileSync(pngPath)
const ICON_SIZE = 128
async function main() {
const buf = await sharp(pngPath)
.resize(ICON_SIZE, ICON_SIZE, { fit: 'cover' })
.png({ compressionLevel: 9 })
.toBuffer()
const b64 = buf.toString('base64')
const ts = `// AUTO-GENERATED by scripts/build-launcher-icon.cjs from build/icon.png.
// 마인크래프트 런처의 "설치 설정" 화면에서 보이는 프로필 아이콘. exe 와 같은
// 이미지를 쓰기 위해 빌드 시점에 PNG 를 data URL 로 인라인한다. 변경하려면
// build/icon.png 교체 후 \`node scripts/build-launcher-icon.cjs\` 재실행.
// 이미지를 ${ICON_SIZE}x${ICON_SIZE} 로 줄여 빌드 시점에 data URL 로 인라인한다.
// 변경하려면 build/icon.png 교체 후 \`node scripts/build-launcher-icon.cjs\` 재실행.
export const LAUNCHER_PROFILE_ICON =
'data:image/png;base64,${b64}'
`
fs.writeFileSync(tsPath, ts, 'utf8')
console.log(`wrote ${tsPath} (${buf.length} bytes PNG → ${b64.length} chars base64)`)
console.log(`wrote ${tsPath} (${ICON_SIZE}x${ICON_SIZE}, ${buf.length} bytes PNG → ${b64.length} chars base64)`)
}
main().catch((err) => {
console.error(err)
process.exit(1)
})

468
src/installer-pf/main.ts Normal file
View File

@@ -0,0 +1,468 @@
import { app, BrowserWindow, ipcMain } from 'electron'
import http from 'node:http'
import https from 'node:https'
import net from 'node:net'
import os from 'node:os'
import path from 'node:path'
import { URL } from 'node:url'
import natUpnp from 'nat-upnp'
import { loadComponentI18n } from '../shared/i18n.js'
// 포트포워딩 전용 독립 도구. 메인 설치기의 UPnP 개방 + 외부 포트 점검 로직만
// 떼어내 단독 실행한다. (음악퀴즈 설치/리소스팩과 무관)
const i18n = loadComponentI18n('installer-pf')
const t = i18n.t
const localeDict = i18n.dict
let mainWindow: BrowserWindow | null = null
// 이 도구가 UPnP 로 직접 열어둔 포트. 앱이 살아 있는 동안 매핑을 유지하고,
// 창을 닫거나 종료할 때 이 포트의 매핑을 제거한다(사용자가 라우터에 직접 만든
// 영구 규칙으로 이미 열려 있던 preForwarded 포트는 우리 것이 아니므로 추적하지 않음).
let activePort: number | null = null
// before-quit 재진입 가드. 매핑 정리를 마친 뒤에만 실제 종료로 넘어가게 한다.
let cleanupDone = false
function createMainWindow(): void {
const iconPath = path.join(__dirname, '..', '..', 'build', process.platform === 'win32' ? 'icon.ico' : 'icon.png')
mainWindow = new BrowserWindow({
width: 760,
height: 620,
icon: iconPath,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false
}
})
mainWindow.removeMenu()
void mainWindow.loadFile(path.join(__dirname, '..', '..', 'installer-pf', 'index.html'))
}
function sendLog(line: string): void {
if (!mainWindow || mainWindow.isDestroyed()) return
const stamped = `[${new Date().toLocaleTimeString('ko-KR', { hour12: false })}] ${line}`
mainWindow.webContents.send('log', stamped)
}
// nat-upnp 는 라우터가 UPnP 를 거부/미지원할 때 콜백 밖에서 비동기 소켓 오류를
// 낼 수 있다. 처리되지 않으면 Electron 메인 프로세스가 그대로 종료되어 창이 갑자기
// 닫힌다("오류나면서 끝남"). 전역 가드로 잡아 로그만 남기고 앱은 계속 살려 둔다.
process.on('uncaughtException', (err) => {
try { sendLog(t('log.internalError', { message: (err as Error)?.message || String(err) })) } catch {}
})
process.on('unhandledRejection', (reason) => {
try { sendLog(t('log.internalError', { message: reason instanceof Error ? reason.message : String(reason) })) } catch {}
})
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))
/** 이 PC 의 LAN IPv4(사설 대역 우선). 수동 포워딩 대상 IP 안내에 쓴다. */
function detectLocalIpv4(): string {
const ifaces = os.networkInterfaces()
const candidates: string[] = []
for (const name of Object.keys(ifaces)) {
for (const info of ifaces[name] || []) {
if (info.family === 'IPv4' && !info.internal && !info.address.startsWith('169.254.')) {
candidates.push(info.address)
}
}
}
const priv = candidates.find((a) => /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(a))
return priv || candidates[0] || ''
}
/** CGNAT(이중 NAT) 대역 100.64.0.0/10 인지. */
function isCgnat(ip: string): boolean {
const m = ip.match(/^100\.(\d+)\./)
if (!m) return false
const octet = Number(m[1])
return octet >= 64 && octet <= 127
}
/** 사설(RFC1918) IPv4 인지. 라우터 WAN 이 사설이면 앞단에 NAT 이 또 있다는 뜻(이중 NAT). */
function isPrivateIpv4(ip: string): boolean {
return /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(ip)
}
/**
* CGNAT/이중 NAT 여부 판별. HTTP 로 본 공인 egress IP 하나만으로는 배제할 수 없다
* (전형적 CGNAT 은 egress 는 ISP 공인 IP, 라우터 WAN 만 100.64/10 이라 egress 검사로는 놓침).
* 그래서 라우터 WAN(IGD 외부) IP 를 함께 보고 비교한다.
* - 'yes' : 공인 IP 가 CGNAT 대역이거나, 라우터 WAN 이 사설/CGNAT 이거나 공인 IP 와 다름.
* - 'no' : 라우터 WAN 이 HTTP 공인 IP 와 동일 → 단일 NAT 확정.
* - 'unknown' : 라우터 WAN 을 못 읽음(UPnP 미응답/거부) → 외부 IP 만으로는 확정/배제 불가.
*/
function classifyCgnat(publicIp: string, wanIp: string): 'yes' | 'no' | 'unknown' {
if (publicIp && isCgnat(publicIp)) return 'yes'
if (wanIp) {
if (isCgnat(wanIp) || isPrivateIpv4(wanIp)) return 'yes'
if (publicIp && wanIp !== publicIp) return 'yes'
if (publicIp && wanIp === publicIp) return 'no'
}
return 'unknown'
}
function fetchBuffer(url: string): Promise<Buffer> {
return new Promise((resolve, reject) => {
const target = new URL(url)
const transport = target.protocol === 'https:' ? https : http
const request = transport.get(target, { timeout: 15000 }, (response) => {
const code = response.statusCode ?? 0
if ((code === 301 || code === 302) && response.headers.location) {
response.resume()
fetchBuffer(new URL(response.headers.location, target).toString()).then(resolve, reject)
return
}
if (code >= 400) {
response.resume()
reject(new Error(`HTTP ${code}`))
return
}
const chunks: Buffer[] = []
response.on('data', (c: Buffer) => chunks.push(c))
response.on('end', () => resolve(Buffer.concat(chunks)))
})
request.on('error', reject)
request.on('timeout', () => request.destroy(new Error(t('errors.requestTimeout'))))
})
}
async function detectExternalIpHttp(): Promise<string> {
const endpoints = ['https://api.ipify.org', 'https://ifconfig.me/ip', 'https://icanhazip.com']
for (const url of endpoints) {
try {
const buffer = await fetchBuffer(url)
const ip = buffer.toString('utf8').trim()
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(ip)) return ip
} catch {
// try next
}
}
return ''
}
function detectExternalIpUpnp(): Promise<string> {
return new Promise((resolve) => {
let settled = false
const finish = (ip: string) => { if (!settled) { settled = true; resolve(ip) } }
let client: ReturnType<typeof natUpnp.createClient> | null = null
try {
client = natUpnp.createClient()
} catch (err) {
sendLog(t('log.upnpClientFail', { message: (err as Error).message }))
finish('')
return
}
const timer = setTimeout(() => {
try { client && client.close() } catch {}
finish('')
}, 6000)
client.externalIp((err: Error | null, ip?: string) => {
clearTimeout(timer)
try { client && client.close() } catch {}
finish(err || !ip ? '' : ip)
})
})
}
function openPortViaUpnp(port: number): Promise<void> {
return new Promise((resolve, reject) => {
let settled = false
const done = (err?: Error) => {
if (settled) return
settled = true
if (err) reject(err)
else resolve()
}
let client: ReturnType<typeof natUpnp.createClient> | null = null
try {
client = natUpnp.createClient()
} catch (err) {
done(err as Error)
return
}
const timer = setTimeout(() => {
try { client && client.close() } catch {}
done(new Error(t('errors.upnpTimeout')))
}, 15000)
client.portMapping(
{ public: port, private: port, ttl: 0, description: 'MusicQuiz PortForward', protocol: 'tcp' },
(error: Error | null) => {
clearTimeout(timer)
try { client && client.close() } catch {}
done(error || undefined)
}
)
})
}
function removeUpnpMapping(port: number): Promise<void> {
return new Promise((resolve) => {
let settled = false
const fin = () => { if (!settled) { settled = true; resolve() } }
let client: ReturnType<typeof natUpnp.createClient> | null = null
try {
client = natUpnp.createClient()
} catch (err) {
sendLog(t('log.upnpClientFail', { message: (err as Error).message }))
fin()
return
}
const timer = setTimeout(() => {
try { client && client.close() } catch {}
fin()
}, 8000)
client.portUnmapping({ public: port, protocol: 'tcp' }, (err: Error | null) => {
clearTimeout(timer)
try { client && client.close() } catch {}
if (err) sendLog(t('log.upnpRemoveAttempt', { message: err.message }))
else sendLog(t('log.upnpRemoveDone', { port }))
fin()
})
})
}
type IfconfigPortResult = { ok: true; reachable: boolean | null; ip: string } | { ok: false; error: string }
// ifconfig.co 는 간헐적으로 타임아웃/레이트리밋을 낸다. 1회 재시도로 일시적 실패를 줄인다.
async function fetchIfconfigCoPort(port: number): Promise<IfconfigPortResult> {
let last: IfconfigPortResult = { ok: false, error: 'no attempt' }
for (let attempt = 0; attempt < 2; attempt++) {
last = await fetchIfconfigCoPortOnce(port)
if (last.ok) return last
if (attempt === 0) await sleep(1500)
}
return last
}
function fetchIfconfigCoPortOnce(port: number): Promise<IfconfigPortResult> {
return new Promise((resolve) => {
const target = new URL(`https://ifconfig.co/port/${port}`)
const req = https.get(target, {
timeout: 15000,
headers: { 'Accept': 'application/json', 'User-Agent': 'MusicQuiz-PortForward' }
}, (res) => {
if ((res.statusCode ?? 0) >= 400) {
res.resume()
resolve({ ok: false, error: `HTTP ${res.statusCode}` })
return
}
const chunks: Buffer[] = []
res.on('data', (c: Buffer) => chunks.push(c))
res.on('end', () => {
const text = Buffer.concat(chunks).toString('utf8').trim()
try {
const json = JSON.parse(text)
const reachable = typeof json.reachable === 'boolean' ? json.reachable : null
const ip = typeof json.ip === 'string' ? json.ip : ''
resolve({ ok: true, reachable, ip })
} catch {
resolve({ ok: false, error: text.slice(0, 80) })
}
})
})
req.on('error', (err) => resolve({ ok: false, error: err.message }))
req.on('timeout', () => req.destroy(new Error(t('errors.requestTimeout'))))
})
}
/**
* 외부에서 지정 포트가 닿는지 검사한다.
* 1) 임시 TCP 리스너를 0.0.0.0:port 에 띄운다(서버가 안 떠 있어도 검증 가능).
* 2) ifconfig.co 에게 외부 IP:port 로 접속을 시킨다.
* 3) 리스너에 인바운드가 오거나 ifconfig.co 가 reachable=true 면 성공.
* '닫힘(false)' 은 ifconfig.co 가 명시적으로 false 를 줄 때만. 외부 판정이 없으면 null(확인 불가).
*/
async function probePortFromOutside(
port: number,
hintIp: string
): Promise<{ reachable: boolean | null; detail: string; detectedIp: string }> {
let server: net.Server | null = null
let listenerBound = false
try {
server = net.createServer()
await new Promise<void>((resolve, reject) => {
const onError = (err: Error) => { server!.removeListener('error', onError); reject(err) }
server!.once('error', onError)
server!.listen(port, '0.0.0.0', () => {
server!.removeListener('error', onError)
listenerBound = true
resolve()
})
})
} catch (err) {
const code = (err as NodeJS.ErrnoException).code
if (code === 'EADDRINUSE') sendLog(t('log.portInUse', { port }))
else sendLog(t('log.listenerBindFail', { message: (err as Error).message }))
try { server && server.close() } catch {}
server = null
}
let gotInbound = false
const inboundPromise = new Promise<void>((resolve) => {
if (!server) { resolve(); return }
server.on('connection', (sock: net.Socket) => {
gotInbound = true
try { sock.destroy() } catch {}
resolve()
})
})
const externalProbe = fetchIfconfigCoPort(port).catch((err) => ({ ok: false as const, error: (err as Error).message }))
await Promise.race([inboundPromise, sleep(12000)])
const externalResult = await externalProbe
try { server && server.close() } catch {}
let reachable: boolean | null = null
const details: string[] = []
if (listenerBound) {
details.push(t('log.detailListenerHit', { value: gotInbound ? 'yes' : 'no' }))
if (gotInbound) reachable = true
} else {
details.push(t('log.detailListenerSkip'))
}
let detectedIp = ''
if ('ok' in externalResult && externalResult.ok) {
details.push(t('log.detailIfconfig', { reachable: String(externalResult.reachable), ip: externalResult.ip || '?' }))
detectedIp = externalResult.ip || ''
if (externalResult.reachable === true) reachable = true
else if (reachable !== true && externalResult.reachable === false) reachable = false
} else if ('ok' in externalResult && !externalResult.ok) {
details.push(t('log.detailIfconfigFail', { error: (externalResult as { error: string }).error }))
}
// 외부 점검 서비스가 명시적 false 를 준 경우에만 닫힘. 리스너 미도달만으로는 단정하지 않는다
// (ifconfig.co 실패 시 외부 시도 자체가 없었고, 리스너 수신 주체가 이 도구라 방화벽 영향도 받음).
return {
reachable,
detail: details.join(', ') || t('log.detailNone'),
detectedIp: detectedIp || hintIp || ''
}
}
interface PortForwardOutcome {
externalIp: string
localIp: string
wanIp: string
cgnat: 'yes' | 'no' | 'unknown'
port: number
reachable: boolean | null
preForwarded: boolean
detail: string
}
ipcMain.handle('pf:i18n:dict', () => localeDict)
ipcMain.handle('pf:open', async (_event, portInput: number): Promise<PortForwardOutcome> => {
const port = Number.isFinite(portInput) && portInput > 0 && portInput < 65536 ? Math.floor(portInput) : 25565
sendLog(t('log.start', { port }))
const localIp = detectLocalIpv4()
if (localIp) sendLog(t('log.localIp', { ip: localIp }))
// 다른 포트를 이미 우리가 열어둔 상태에서 새 포트를 열면, 이전 포트 매핑을 먼저 닫아
// 매핑이 새는 것을 막는다.
if (activePort !== null && activePort !== port) {
await removeUpnpMapping(activePort)
activePort = null
}
// 이전에 남은 매핑을 먼저 제거해 "사용자 라우터 규칙으로 이미 열린 상태" 와 구별.
sendLog(t('log.cleanup'))
await removeUpnpMapping(port)
let externalIp = await detectExternalIpHttp()
if (externalIp) sendLog(t('log.externalIpHttp', { ip: externalIp }))
else sendLog(t('log.externalIpHttpFail'))
// 라우터 WAN(IGD 외부) IP 를 UPnP 로 조회해 HTTP 공인 IP 와 비교 → CGNAT/이중 NAT 판별.
const wanIp = await detectExternalIpUpnp()
if (wanIp) sendLog(t('log.routerWan', { ip: wanIp }))
else sendLog(t('log.routerWanUnknown'))
if (!externalIp && wanIp) externalIp = wanIp
const cgnat = classifyCgnat(externalIp, wanIp)
if (cgnat === 'yes') sendLog(t('log.cgnatDetected', { public: externalIp || '?', wan: wanIp || '?' }))
else if (cgnat === 'unknown') sendLog(t('log.cgnatUnknown'))
const wrap = (reachable: boolean | null, preForwarded: boolean, detail: string): PortForwardOutcome =>
({ externalIp, localIp, wanIp, cgnat, port, reachable, preForwarded, detail })
// 1차 점검: 이미 외부에서 닿는지.
sendLog(t('log.probeStart'))
let probe = await probePortFromOutside(port, externalIp)
if (!externalIp && probe.detectedIp) externalIp = probe.detectedIp
sendLog(t('log.probeResult', { verdict: verdictText(probe.reachable), detail: probe.detail }))
if (probe.reachable === true) {
sendLog(t('log.preForwarded'))
return wrap(true, true, probe.detail)
}
// UPnP 개방 시도.
sendLog(t('log.upnpTry', { port }))
try {
await openPortViaUpnp(port)
// 우리가 연 포트로 기록 → 앱 종료/창 닫힘 시 자동으로 매핑 제거.
activePort = port
sendLog(t('log.upnpReqOk'))
} catch (error) {
const msg = (error as Error).message
sendLog(t('log.upnpTryFail', { message: msg }))
// ECONNREFUSED/타임아웃 = 라우터가 UPnP 제어를 거부/미지원. 수동 포워딩 안내로 유도.
if (/ECONNREFUSED|ETIMEDOUT|timed out|시간 초과/i.test(msg)) sendLog(t('log.upnpUnavailable'))
return wrap(probe.reachable, false, probe.detail)
}
// NAT 반영 지연 고려 재점검.
for (let attempt = 1; attempt <= 3; attempt++) {
await sleep(1500)
sendLog(t('log.recheck', { attempt }))
probe = await probePortFromOutside(port, externalIp)
if (!externalIp && probe.detectedIp) externalIp = probe.detectedIp
if (probe.reachable === true) {
sendLog(t('log.upnpDone', { port }))
return wrap(true, false, probe.detail)
}
}
sendLog(t('log.upnpUnconfirmed'))
return wrap(probe.reachable, false, probe.detail)
})
ipcMain.handle('pf:close', async (_event, portInput: number): Promise<void> => {
const port = Number.isFinite(portInput) && portInput > 0 && portInput < 65536 ? Math.floor(portInput) : 25565
sendLog(t('log.closeTry', { port }))
await removeUpnpMapping(port)
if (activePort === port) activePort = null
})
ipcMain.handle('pf:quit', async () => {
app.quit()
})
function verdictText(reachable: boolean | null): string {
return reachable === true ? t('verdict.success') : reachable === false ? t('verdict.fail') : t('verdict.unknown')
}
app.whenReady().then(() => {
createMainWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createMainWindow()
})
})
// 창을 닫거나 종료할 때, 이 도구가 열어둔 UPnP 매핑을 제거한 뒤 실제 종료로 넘어간다.
// removeUpnpMapping 은 비동기라 before-quit 을 한 번 막고(cleanup) 끝나면 다시 quit 한다.
app.on('before-quit', (event) => {
if (cleanupDone || activePort === null) return
event.preventDefault()
const port = activePort
activePort = null
sendLog(t('log.closeTry', { port }))
void removeUpnpMapping(port).finally(() => {
cleanupDone = true
app.quit()
})
})
app.on('window-all-closed', () => {
app.quit()
})

View File

@@ -0,0 +1,41 @@
import { contextBridge, ipcRenderer } from 'electron'
interface PortForwardOutcome {
externalIp: string
localIp: string
wanIp: string
cgnat: 'yes' | 'no' | 'unknown'
port: number
reachable: boolean | null
preForwarded: boolean
detail: string
}
const api = {
/** i18n 사전을 렌더러에 전달. */
loadLocale: (): Promise<Record<string, unknown>> => ipcRenderer.invoke('pf:i18n:dict'),
/** 지정 포트를 UPnP 로 개방 시도하고 외부에서 닿는지 점검. */
openPort: (port: number): Promise<PortForwardOutcome> => ipcRenderer.invoke('pf:open', port),
/** UPnP 포트 매핑 제거. */
closePort: (port: number): Promise<void> => ipcRenderer.invoke('pf:close', port),
/** 프로그램 종료. */
quit: (): Promise<void> => ipcRenderer.invoke('pf:quit'),
/** 로그 스트림 구독. */
onLog: (handler: (line: string) => void): (() => void) => {
const listener = (_event: unknown, line: string) => handler(line)
ipcRenderer.on('log', listener)
return () => ipcRenderer.removeListener('log', listener)
}
}
contextBridge.exposeInMainWorld('pfTool', api)
declare global {
interface Window {
pfTool: typeof api
}
}

View File

@@ -39,9 +39,15 @@ async function migrateLegacyExe(target: string): Promise<void> {
}
}
/** BtbN/FFmpeg-Builds 의 win64-gpl 빌드. zip 내부에 bin/ffmpeg.exe 가 들어 있음. */
/**
* BtbN/FFmpeg-Builds 의 win64-gpl 빌드. zip 내부에 bin/ffmpeg.exe 가 들어 있음.
* `releases/download/latest/` 형태(=항상 최신 자산이 붙어 있는 롤링 `latest` 태그)를
* 쓴다. `releases/latest/download/`(GitHub 의 "최신 릴리스" 자동 포인터)는 갓
* 만들어진 `autobuild-<날짜>` 릴리스로 리다이렉트되는데, 그 릴리스에 자산이 아직
* 업로드되지 않았거나 없으면 HTTP 404 가 나서 ffmpeg 설치가 실패한다.
*/
const FFMPEG_ZIP_URL =
'https://github.com/BtbN/FFmpeg-Builds/releases/latest/download/ffmpeg-master-latest-win64-gpl.zip'
'https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip'
let installPromise: Promise<string> | null = null
@@ -50,14 +56,20 @@ let installPromise: Promise<string> | null = null
* ffmpeg.exe 만 추출해 설치하고 절대경로를 돌려준다.
*/
export async function ensureFfmpegExe(
log?: (line: string) => void
log?: (line: string) => void,
force = false
): Promise<string> {
const target = getFfmpegExePath()
await migrateLegacyExe(target)
if (await canExecute(target)) {
if (!force && await canExecute(target)) {
log?.(t('log.ffmpegExists', { path: target }))
return target
}
if (force) {
// 강제 재설치: 오래됐을 수 있는 캐시본을 지워 최신 버전을 받게 한다.
log?.(t('log.ffmpegReinstall'))
try { await fs.unlink(target) } catch { /* noop */ }
}
if (installPromise) return installPromise
installPromise = (async () => {

View File

@@ -29,8 +29,41 @@ export function ytIdFromUrl(url: string): string {
}
}
/** 단순 HTTP/HTTPS GET (302 따라감, 4xx/5xx 는 reject). */
function fetchBuffer(url: string, redirects = 0): Promise<Buffer> {
/**
* 일시적(transient) 으로 보고 재시도할 HTTP 상태코드.
* 429 = Too Many Requests (i.ytimg.com 썸네일 서버가 연속 요청을 속도제한).
* 5xx 게이트웨이 계열도 잠깐 뒤 다시 받으면 성공하는 경우가 많다.
*/
const TRANSIENT_CODES = new Set([408, 425, 429, 500, 502, 503, 504])
const MAX_RETRIES = 6
/** 백오프 상한(ms). Retry-After 헤더가 비정상적으로 커도 이 이상은 기다리지 않는다. */
const MAX_BACKOFF_MS = 60000
/**
* 재시도가 일어날 때 호출되는 훅. 상위(main)에서 로그/진행률로 표시해, 429 백오프
* 대기 중에도 화면이 멈춘 것처럼 보이지 않게 한다.
*/
export type ImageRetryHook = (info: { attempt: number; delayMs: number; code: number | null }) => void
/** Retry-After 헤더(초 또는 HTTP-date) → 대기 ms. 못 읽으면 null. */
function parseRetryAfter(h: string | string[] | undefined): number | null {
if (!h) return null
const v = Array.isArray(h) ? h[0] : h
const secs = Number(v)
if (Number.isFinite(secs)) return Math.min(MAX_BACKOFF_MS, Math.max(0, secs * 1000))
const date = Date.parse(v)
if (!Number.isNaN(date)) return Math.min(MAX_BACKOFF_MS, Math.max(0, date - Date.now()))
return null
}
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))
/**
* 단순 HTTP/HTTPS GET (302 따라감).
* 429/5xx 등 일시적 오류는 지수 백오프(+jitter, Retry-After 우선)로 최대
* MAX_RETRIES 회 재시도한다. 그 외 4xx 나 재시도 소진 시 reject.
*/
function fetchBuffer(url: string, redirects = 0, attempt = 0, onRetry?: ImageRetryHook): Promise<Buffer> {
return new Promise((resolve, reject) => {
if (redirects > 8) {
reject(new Error(t('common.tooManyRedirects')))
@@ -38,6 +71,12 @@ function fetchBuffer(url: string, redirects = 0): Promise<Buffer> {
}
const target = new URL(url)
const lib = target.protocol === 'https:' ? https : http
const retryLater = (headerDelay: number | null, code: number | null): void => {
const backoff = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** attempt) + Math.floor(Math.random() * 500)
const delay = headerDelay ?? backoff
try { onRetry?.({ attempt: attempt + 1, delayMs: delay, code }) } catch { /* noop */ }
sleep(delay).then(() => fetchBuffer(url, redirects, attempt + 1, onRetry).then(resolve, reject))
}
const req = lib.get(target, {
timeout: 30000,
headers: { 'user-agent': 'mc-music-quiz-rp-installer' }
@@ -45,10 +84,15 @@ function fetchBuffer(url: string, redirects = 0): Promise<Buffer> {
const code = res.statusCode || 0
if (code >= 300 && code < 400 && res.headers.location) {
res.resume()
fetchBuffer(new URL(res.headers.location, target).toString(), redirects + 1)
fetchBuffer(new URL(res.headers.location, target).toString(), redirects + 1, attempt, onRetry)
.then(resolve, reject)
return
}
if (TRANSIENT_CODES.has(code) && attempt < MAX_RETRIES) {
res.resume()
retryLater(parseRetryAfter(res.headers['retry-after']), code)
return
}
if (code !== 200) {
res.resume()
reject(new Error(`HTTP ${code}`))
@@ -58,27 +102,57 @@ function fetchBuffer(url: string, redirects = 0): Promise<Buffer> {
res.on('data', (c: Buffer) => chunks.push(c))
res.on('end', () => resolve(Buffer.concat(chunks)))
})
req.on('error', reject)
req.on('error', (err) => {
// 연결 끊김/리셋 등 네트워크 오류도 몇 번은 재시도.
if (attempt < MAX_RETRIES) {
retryLater(null, null)
return
}
reject(err)
})
req.on('timeout', () => req.destroy(new Error(t('common.requestTimeout'))))
})
}
/**
* data: URL 이면 그 안에 들어 있는 바이트를 바로 Buffer 로 디코드한다.
* data: URL 은 이미지 데이터 자체를 품고 있어 네트워크 요청이 필요 없으며,
* http/https 만 다루는 fetchBuffer 에 넘기면 `Protocol "data:" not supported`
* 로 터지므로 여기서 가로챈다. data: URL 이 아니면 null.
*/
function decodeDataUrl(url: string): Buffer | null {
if (!/^data:/i.test(url)) return null
const comma = url.indexOf(',')
if (comma < 0) throw new Error(t('errors.imageDataUrlInvalid'))
const meta = url.slice(5, comma)
const data = url.slice(comma + 1)
// `;base64` 가 있으면 base64, 없으면 percent-encoding 된 텍스트.
const buf = /;base64/i.test(meta)
? Buffer.from(data, 'base64')
: Buffer.from(decodeURIComponent(data), 'utf8')
if (buf.length === 0) throw new Error(t('errors.imageDataUrlInvalid'))
return buf
}
/**
* 이미지 URL 을 다운로드해 Buffer 로 돌려준다.
* - data: URL 이면 내장 바이트를 바로 디코드 (네트워크 없음).
* - 유튜브 영상 URL 이면 `i.ytimg.com/vi/<id>/maxresdefault.jpg` 1차 →
* 실패하면 `hqdefault.jpg` 로 폴백.
* - 그 외 URL 은 HTTP GET 으로 그대로 받음.
*/
export async function downloadImage(rawUrl: string): Promise<Buffer> {
export async function downloadImage(rawUrl: string, onRetry?: ImageRetryHook): Promise<Buffer> {
const dataBuf = decodeDataUrl(rawUrl)
if (dataBuf) return dataBuf
const ytId = ytIdFromUrl(rawUrl)
if (ytId) {
try {
return await fetchBuffer(`https://i.ytimg.com/vi/${ytId}/maxresdefault.jpg`)
return await fetchBuffer(`https://i.ytimg.com/vi/${ytId}/maxresdefault.jpg`, 0, 0, onRetry)
} catch {
return await fetchBuffer(`https://i.ytimg.com/vi/${ytId}/hqdefault.jpg`)
return await fetchBuffer(`https://i.ytimg.com/vi/${ytId}/hqdefault.jpg`, 0, 0, onRetry)
}
}
return fetchBuffer(rawUrl)
return fetchBuffer(rawUrl, 0, 0, onRetry)
}
/**

View File

@@ -9,9 +9,10 @@ import { URL } from 'node:url'
import type { ChildProcess } from 'node:child_process'
import type { Manifest, PackDefinition, PackList } from '../shared/types.js'
import { normalizePackDefinition } from '../shared/store.js'
import { getAppDataDir, getMcCustomDir } from '../shared/paths.js'
import { getAppDataDir, getMcCustomDir, withCustomDirName } from '../shared/paths.js'
import { loadEnv, getManifestUrl } from '../shared/env.js'
import { loadComponentI18n } from '../shared/i18n.js'
import { resolveAudience, isPackVisibleForAudience, type Audience } from '../shared/audience.js'
import type { RpFetchedPack } from './types.js'
import { ensureYtDlpExe } from './ytdlp.js'
import { ensureFfmpegExe } from './ffmpeg.js'
@@ -76,6 +77,13 @@ function pickMusicConcurrency(): number {
*/
const MUSIC_START_STAGGER_MS = 2000
/** 사진(썸네일) 동시 다운로드 상한. 순차 대신 병렬로 받아 속도를 높인다. 429 는 images.ts 의 지수 백오프 재시도가 흡수한다. */
const IMAGE_CONCURRENCY_CAP = 8
/** 음악(yt-dlp) 단계 직후 유튜브 IP throttle 이 남아 있을 수 있어, 사진 단계 전 아주 잠깐만 쉰다. */
const IMAGE_PHASE_COOLDOWN_MS = 1000
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))
/** start-gate. 여러 worker 가 동시에 acquire 해도 직렬화되어 순차 통과. */
let musicStartChain: Promise<void> = Promise.resolve()
let nextMusicStartAt = 0
@@ -89,6 +97,16 @@ function acquireMusicStartSlot(): Promise<void> {
return slot
}
/** 파일이 존재하면 true. 이어받기(재시도) 시 이미 받아둔 산출물 감지에 사용. */
async function fileExists(p: string): Promise<boolean> {
try {
await fsp.access(p)
return true
} catch {
return false
}
}
const DEFAULT_MANIFEST_URL = getManifestUrl()
const state: RpInstallerState = {
@@ -102,6 +120,16 @@ const state: RpInstallerState = {
let mainWindow: BrowserWindow | null = null
// 이 빌드의 대상(일반/개발자용). package.json 의 musicQuizAudience 로 결정.
function getAudience(): Audience {
try {
const pkg = JSON.parse(fs.readFileSync(path.join(app.getAppPath(), 'package.json'), 'utf8'))
return resolveAudience(pkg.musicQuizAudience)
} catch {
return resolveAudience(undefined)
}
}
function deriveBaseUrl(manifestUrl: string): string {
try {
const parsed = new URL(manifestUrl)
@@ -192,9 +220,12 @@ ipcMain.handle('rp:packs:load', async (_event, manifestUrlInput?: string): Promi
}
sendLog(t('log.manifestDownload', { url: state.manifestUrl }))
const manifest = await fetchJson<Manifest>(state.manifestUrl)
const audience = getAudience()
const results: RpFetchedPack[] = []
for (const entry of manifest.packs ?? []) {
if (typeof entry?.file !== 'string') continue
// 대상(audience)에 맞지 않는 pack 은 건너뛴다(일반=public, 개발자용=non-public).
if (!isPackVisibleForAudience(entry.public, audience)) continue
const listUrl = `${state.baseUrl}/file/list/${encodeURIComponent(entry.file)}.json`
const packUrl = `${state.baseUrl}/manifest/${encodeURIComponent(entry.file)}.json`
try {
@@ -249,17 +280,37 @@ ipcMain.handle('rp:packs:select', async (_event, packKey: string) => {
sendLog(t('log.selectedPack', { key: packKey }))
})
ipcMain.handle('rp:i18n:dict', () => localeDict)
// 개발자용 빌드(musicQuizAudience=developer)면 렌더러에 넘기는 사전의 제목 앞에
// "(개발자용) " 을 붙여, 창 제목/헤더에 개발자용임을 표시한다.
function dictForRenderer(): Record<string, unknown> {
// 커스텀 폴더명을 UI 문구에 반영.
const base = withCustomDirName(localeDict)
if (getAudience() !== 'developer') return base
const prefix = '(개발자용) '
const appBlock = (base.app ?? {}) as Record<string, unknown>
const title = appBlock.title
return {
...base,
app: {
...appBlock,
title: typeof title === 'string' && !title.startsWith(prefix) ? prefix + title : title
}
}
}
ipcMain.handle('rp:i18n:dict', () => dictForRenderer())
// ── IPC: 약관 다운로드 ──────────────────────────────
// 사이트가 /manifest/terms/<kind>.md 로 노출하는 md 파일을 그대로 받아 본문(string) 으로 반환.
// rp 인스톨러에서는 'resourcepack' 과 'installer-rp' 두 종류만 실제로 사용하지만, 메인
// 인스톨러와 동일한 화이트리스트를 둬서 사이트 컴포넌트 분류와 1:1 로 매칭되게 한다.
const TERM_KIND_WHITELIST = new Set(['map', 'resourcepack', 'mod', 'installer', 'installer-rp'])
// v0.3.4~ : 사이트에서 임의 kind 가 만들어질 수 있으니 5종 화이트리스트 대신
// kind 형식만 검증한다. 어떤 약관을 rp 인스톨러에 보여줄지는 사이트의 visibility 토글이 결정.
const TERM_KIND_RE = /^[a-z0-9][a-z0-9-]{0,31}$/
ipcMain.handle('rp:terms:get', async (_event, kind: string) => {
if (!TERM_KIND_WHITELIST.has(kind)) return { ok: false, message: 'unknown term kind' }
if (typeof kind !== 'string' || !TERM_KIND_RE.test(kind)) {
return { ok: false, message: 'invalid term kind' }
}
if (!state.selectedKey) return { ok: false, message: 'pack not selected' }
try {
const url = `${state.baseUrl}/manifest/terms/${encodeURIComponent(kind)}.md`
const url = `${state.baseUrl}/manifest/terms/${encodeURIComponent(state.selectedKey)}/${encodeURIComponent(kind)}.md`
const buf = await fetchBuffer(url)
return { ok: true, content: buf.toString('utf8') }
} catch (error) {
@@ -267,6 +318,31 @@ ipcMain.handle('rp:terms:get', async (_event, kind: string) => {
}
})
// rp 인스톨러용 약관 목록. /manifest/terms/<packKey>/index.json 을 받아
// showInInstallerRp=true 인 항목만 추려 반환. 비어 있으면 렌더러가 약관 단계를 건너뛴다.
ipcMain.handle('rp:terms:list', async (): Promise<{ ok: boolean; terms?: Array<{ kind: string; label: string }>; message?: string }> => {
if (!state.selectedKey) return { ok: false, message: 'pack not selected' }
try {
const url = `${state.baseUrl}/manifest/terms/${encodeURIComponent(state.selectedKey)}/index.json`
const buf = await fetchBuffer(url)
const parsed = JSON.parse(buf.toString('utf8')) as { terms?: unknown }
const items = Array.isArray(parsed.terms) ? parsed.terms : []
const terms: Array<{ kind: string; label: string }> = []
for (const it of items) {
if (!it || typeof it !== 'object') continue
const entry = it as Record<string, unknown>
if (entry.showInInstallerRp !== true) continue
const kind = typeof entry.kind === 'string' ? entry.kind : ''
const label = typeof entry.label === 'string' ? entry.label : ''
if (!TERM_KIND_RE.test(kind) || label.length === 0) continue
terms.push({ kind, label })
}
return { ok: true, terms }
} catch (error) {
return { ok: false, message: (error as Error).message }
}
})
// ── IPC: 2단계 설치 ──────────────────────────────────
ipcMain.handle('rp:install:start', async (): Promise<{ resourcepackPath: string }> => {
if (!state.selectedKey) throw new Error(t('errors.selectPackFirst'))
@@ -284,16 +360,30 @@ ipcMain.handle('rp:install:start', async (): Promise<{ resourcepackPath: string
// 2-1. yt-dlp / ffmpeg 준비 (%appdata%/.mc_custom/{yt-dlp,ffmpeg}.exe)
sendLog(t('log.ytdlpPreparing'))
sendProgress({ phase: 'prep', message: t('progress.ytdlpPreparing') })
const ytDlpBin = await ensureYtDlpExe(sendLog)
let ytDlpBin = await ensureYtDlpExe(sendLog)
sendLog(t('log.ytdlpPath', { path: ytDlpBin }))
throwIfCancelled()
sendLog(t('log.ffmpegPreparing'))
sendProgress({ phase: 'prep', message: t('progress.ffmpegPreparing') })
const ffmpegBin = await ensureFfmpegExe(sendLog)
let ffmpegBin = await ensureFfmpegExe(sendLog)
sendLog(t('log.ffmpegPath', { path: ffmpegBin }))
sendProgress({ phase: 'prep', message: t('progress.ready'), done: true })
throwIfCancelled()
// 음악 다운로드가 실패하면 yt-dlp/ffmpeg 가 너무 오래된 버전이라 유튜브 변경을
// 못 따라가는 경우일 수 있다. 그때 최신 버전으로 한 번만 강제 재설치한다.
// 워커 여러 개가 동시에 실패해도 재설치는 단 한 번만 일어나도록 락으로 직렬화.
let binRefreshPromise: Promise<void> | null = null
async function refreshBinariesOnce(): Promise<void> {
if (!binRefreshPromise) {
binRefreshPromise = (async () => {
ytDlpBin = await ensureYtDlpExe(sendLog, true)
ffmpegBin = await ensureFfmpegExe(sendLog, true)
})()
}
await binRefreshPromise
}
// 2-2. 음악 다운로드 (CPU 코어 수 기반 자동 동시 다운로드, 시차 출발, ogg 변환)
const musicDir = path.join(tempRoot, 'music')
await fsp.mkdir(musicDir, { recursive: true })
@@ -306,17 +396,17 @@ ipcMain.handle('rp:install:start', async (): Promise<{ resourcepackPath: string
// 클로저 안에서 narrowing 이 풀리지 않도록 로컬 alias.
const musicList = pack.list.music
let nextIndex = 0
async function musicWorker(): Promise<void> {
while (true) {
if (state.cancelRequested) return
const i = nextIndex++
if (i >= musicTotal) return
// 시차 게이트: 새 다운로드 시작은 직전 시작과 최소 MUSIC_START_STAGGER_MS 간격을 둠.
await acquireMusicStartSlot()
if (state.cancelRequested) return
// 곡별 마지막 실패 메시지(재시도 단계에서 최종 에러 메시지로 사용).
const failedMessages = new Map<number, string>()
// 한 곡을 한 번 받아본다. 성공 true / 실패 false.
// emitErrorProgress=false 면 실패해도 UI 에 'error' 상태를 보내지 않는다(재시도 예정).
async function tryDownloadTrack(i: number, emitErrorProgress: boolean): Promise<boolean> {
const entry = musicList[i]
const idx = i + 1
// 최종 산출물 경로. 실패 시 부분 생성된 파일을 지워, 다음 재시도(이어받기)에서
// 완성본으로 오인해 건너뛰는 일을 막는다.
const expectedOut = path.join(musicDir, String(idx).padStart(2, '0') + '.ogg')
sendLog(t('log.musicTrackStart', { idx }))
sendProgress({ phase: 'item', kind: 'music', index: idx, total: musicTotal, percent: 0, status: 'running' })
let child: ChildProcess | null = null
@@ -343,15 +433,47 @@ ipcMain.handle('rp:install:start', async (): Promise<{ resourcepackPath: string
if (child) state.activeChildren.delete(child)
sendLog(t('log.musicTrackDone', { idx, name: path.basename(outPath) }))
sendProgress({ phase: 'item', kind: 'music', index: idx, total: musicTotal, percent: 100, status: 'done' })
return true
} catch (err) {
if (child) state.activeChildren.delete(child)
// 부분 생성된 .ogg 를 제거(이어받기 시 완성본 오인 방지).
await fsp.rm(expectedOut, { force: true }).catch(() => {})
if (state.cancelRequested) {
sendProgress({ phase: 'item', kind: 'music', index: idx, total: musicTotal, percent: 0, status: 'error', message: t('progress.cancelled') })
return
return false
}
failedMessages.set(i, (err as Error).message)
if (emitErrorProgress) {
sendProgress({ phase: 'item', kind: 'music', index: idx, total: musicTotal, percent: 0, status: 'error', message: (err as Error).message })
throw new Error(t('errors.musicDownloadFailed', { idx, message: (err as Error).message }))
}
return false
}
}
// 1차 다운로드: 동시 워커로 전부 받아보고, 실패한 곡 인덱스만 모은다.
// 여기서는 yt-dlp/ffmpeg 재설치를 하지 않는다(다른 워커가 같은 exe 를 실행 중일 수
// 있어 Windows 파일 잠금으로 삭제/덮어쓰기가 실패할 수 있기 때문).
const failed: number[] = []
let nextIndex = 0
async function musicWorker(): Promise<void> {
while (true) {
if (state.cancelRequested) return
const i = nextIndex++
if (i >= musicTotal) return
const idx = i + 1
// 이전 시도에서 이미 받아둔 곡(.ogg 존재)은 시차 게이트 없이 즉시 완료 처리
// 한다. '재시도' 로 이어받을 때 받았던 곡을 다시 받지 않기 위함.
const outPath = path.join(musicDir, String(idx).padStart(2, '0') + '.ogg')
if (await fileExists(outPath)) {
sendLog(t('log.musicTrackSkip', { idx }))
sendProgress({ phase: 'item', kind: 'music', index: idx, total: musicTotal, percent: 100, status: 'done' })
continue
}
// 시차 게이트: 새 다운로드 시작은 직전 시작과 최소 MUSIC_START_STAGGER_MS 간격을 둠.
await acquireMusicStartSlot()
if (state.cancelRequested) return
const ok = await tryDownloadTrack(i, false)
if (!ok && !state.cancelRequested) failed.push(i)
}
}
@@ -361,35 +483,104 @@ ipcMain.handle('rp:install:start', async (): Promise<{ resourcepackPath: string
await Promise.all(workers)
throwIfCancelled()
// 1차에서 실패한 곡이 있으면, 모든 워커가 끝나 실행 중인 yt-dlp/ffmpeg 자식
// 프로세스가 하나도 없는 지금 시점에 단 한 번 최신 버전으로 강제 재설치한다.
// (각 워커 promise 는 자식 프로세스 close 후 resolve 되므로 여기선 exe 가 잠겨
// 있지 않다 → Windows 파일 잠금 문제 없음.) 그런 다음 실패한 곡만 순차 재시도.
if (failed.length > 0) {
failed.sort((a, b) => a - b)
sendLog(t('log.musicRefreshRetry', { count: failed.length }))
await refreshBinariesOnce()
throwIfCancelled()
nextMusicStartAt = Date.now()
for (const i of failed) {
throwIfCancelled()
await acquireMusicStartSlot()
throwIfCancelled()
const ok = await tryDownloadTrack(i, true)
if (!ok) {
throwIfCancelled()
const idx = i + 1
throw new Error(t('errors.musicDownloadFailed', { idx, message: failedMessages.get(i) ?? '' }))
}
}
}
// 2-3. 사진 다운로드 + painting variant 정규화
const paintingDir = path.join(tempRoot, 'painting')
await fsp.mkdir(paintingDir, { recursive: true })
sendLog(t('log.imageStart', { total: imageTotal }))
for (let i = 0; i < imageTotal; i++) {
throwIfCancelled()
const entry = pack.list.images[i]
// 음악(yt-dlp) 단계에서 유튜브를 많이 두드렸다면 IP throttle 이 남아 사진 첫 장부터
// 429 가 날 수 있다. 다운로드할 사진이 실제로 있고 직전에 음악을 받았다면 잠깐 쉰다.
if (imageTotal > 0 && musicTotal > 0) {
sendLog(t('log.imageCooldown', { secs: Math.round(IMAGE_PHASE_COOLDOWN_MS / 1000) }))
await sleep(IMAGE_PHASE_COOLDOWN_MS)
}
// 여러 장을 동시에 받아 속도를 높인다(순차+딜레이 대신 워커 풀). 유튜브 429 는
// 각 다운로드의 지수 백오프 재시도(images.ts)가 흡수하고, 첫 하드 실패를 만나면
// 새 작업 배정을 멈춘 뒤 워커가 모두 끝나면 그 오류를 던진다.
const images = pack.list.images
let imageNext = 0
let imageError: Error | null = null
async function imageWorker(): Promise<void> {
while (true) {
if (state.cancelRequested || imageError) return
const i = imageNext++
if (i >= imageTotal) return
const idx = i + 1
const entry = images[i]
const coverPath = path.join(paintingDir, coverFileName(idx))
// 이전 시도에서 이미 정규화해둔 사진은 건너뛴다(이어받기).
if (await fileExists(coverPath)) {
sendLog(t('log.imageSkip', { idx }))
sendProgress({ phase: 'item', kind: 'image', index: idx, total: imageTotal, percent: 100, status: 'done' })
continue
}
sendLog(t('log.imageDownloading', { idx }))
sendProgress({ phase: 'item', kind: 'image', index: idx, total: imageTotal, percent: 10, status: 'running' })
let buf: Buffer
try {
buf = await downloadImage(entry.url)
buf = await downloadImage(entry.url, (info) => {
const secs = Math.ceil(info.delayMs / 1000)
sendLog(t('log.imageRetry', { idx, attempt: info.attempt, code: info.code ?? '-', secs }))
sendProgress({
phase: 'item', kind: 'image', index: idx, total: imageTotal, percent: 10, status: 'running',
message: t('progress.imageRetry', { code: info.code ?? '-', secs })
})
})
} catch (err) {
sendProgress({ phase: 'item', kind: 'image', index: idx, total: imageTotal, percent: 0, status: 'error', message: (err as Error).message })
throw new Error(t('errors.imageDownloadFailed', { idx, message: (err as Error).message }))
// 부분 생성됐을 수 있는 커버 파일 제거(이어받기 시 완성본 오인 방지).
await fsp.rm(coverPath, { force: true }).catch(() => {})
const rawMsg = (err as Error).message
// 429(rate limit)는 유튜브가 IP 를 일시 차단한 것. 잠시 뒤 다시 시도하면
// 이미 받은 사진은 건너뛰고 이어받는다는 안내를 덧붙인다.
const msg = /429/.test(rawMsg) ? `${rawMsg}${t('errors.imageRateLimitHint')}` : rawMsg
sendProgress({ phase: 'item', kind: 'image', index: idx, total: imageTotal, percent: 0, status: 'error', message: msg })
if (!imageError) imageError = new Error(t('errors.imageDownloadFailed', { idx, message: msg }))
return
}
throwIfCancelled()
if (state.cancelRequested || imageError) return
sendProgress({ phase: 'item', kind: 'image', index: idx, total: imageTotal, percent: 60, status: 'running' })
const outPath = path.join(paintingDir, coverFileName(idx))
try {
await normalizeToCover(buf, outPath)
await normalizeToCover(buf, coverPath)
} catch (err) {
// 변환 중 부분 생성된 PNG 제거(이어받기 시 완성본 오인 방지).
await fsp.rm(coverPath, { force: true }).catch(() => {})
sendProgress({ phase: 'item', kind: 'image', index: idx, total: imageTotal, percent: 0, status: 'error', message: (err as Error).message })
throw new Error(t('errors.imageNormalizeFailed', { idx, message: (err as Error).message }))
if (!imageError) imageError = new Error(t('errors.imageNormalizeFailed', { idx, message: (err as Error).message }))
return
}
sendLog(t('log.imageDone', { idx, name: path.basename(outPath) }))
sendLog(t('log.imageDone', { idx, name: path.basename(coverPath) }))
sendProgress({ phase: 'item', kind: 'image', index: idx, total: imageTotal, percent: 100, status: 'done' })
}
}
const imageWorkerCount = Math.min(IMAGE_CONCURRENCY_CAP, Math.max(1, imageTotal), Math.max(concurrency, 4))
const imageWorkers: Promise<void>[] = []
for (let w = 0; w < imageWorkerCount; w++) imageWorkers.push(imageWorker())
await Promise.all(imageWorkers)
throwIfCancelled()
if (imageError) throw imageError
// 2-4. 베이스 리소스팩 다운로드 (있을 때만)
throwIfCancelled()
@@ -457,11 +648,23 @@ ipcMain.handle('rp:install:start', async (): Promise<{ resourcepackPath: string
}
sendProgress({ phase: 'package', message: t('progress.installComplete'), done: true })
// 성공: 임시 파일 정리
await fsp.rm(tempRoot, { recursive: true, force: true }).catch(() => {})
return { resourcepackPath }
} finally {
// 임시 파일 정리
} catch (err) {
// 사용자가 취소한 경우에만 임시 파일을 지운다(처음부터 새로 시작).
// 그 외 오류는 받아둔 음악·사진을 보존해 '재시도' 시 실패 지점부터 이어받게 한다.
// (재시도 없이 프로그램을 닫으면 window-all-closed 에서 .temp 를 정리한다.)
if (state.cancelRequested) {
await fsp.rm(tempRoot, { recursive: true, force: true }).catch(() => {})
}
throw err
}
})
// '처음으로' 버튼: 재시도하지 않고 처음 단계로 돌아갈 때 받아둔 임시 파일을 정리한다.
ipcMain.handle('rp:install:discard', async () => {
await fsp.rm(path.join(getMcCustomDir(), '.temp'), { recursive: true, force: true }).catch(() => {})
})
ipcMain.handle('rp:install:cancel', async () => {

View File

@@ -131,6 +131,10 @@ export async function buildResourcepackZip(opts: BuildResourcepackOptions): Prom
opts.log?.(t('log.packFormatRange', { min: minFmt, max: maxFmt }))
// 2) 음악 파일 복사 + sounds.json 생성/병합
// 핵심 정책: 베이스 리소스팩에 이미 있는 자산은 절대 덮어쓰지 않는다.
// - 베이스 sounds.json 의 엔트리는 그대로 보존하고, 우리 트랙은 그 위에 "추가" 만 한다.
// - 베이스 sounds/track_NN.ogg 가 이미 있으면 덮어쓰지 않고 건너뛴다.
// - 키나 파일명이 충돌하면 우리 트랙을 스킵하고 로그로 알린다.
const musicFiles = (await fs.readdir(opts.musicDir))
.filter((n) => n.toLowerCase().endsWith('.ogg'))
.sort()
@@ -152,7 +156,19 @@ export async function buildResourcepackZip(opts: BuildResourcepackOptions): Prom
// NN.ogg → track_NN.ogg 로 리네임해 패키지.
const stem = path.basename(fname, path.extname(fname)) // "01"
const trackId = `track_${stem}`
await fs.copyFile(path.join(opts.musicDir, fname), path.join(soundsDir, `${trackId}.ogg`))
const destFile = path.join(soundsDir, `${trackId}.ogg`)
// 베이스에 같은 trackId 의 엔트리/파일이 있으면 두 선택지 다 깨진다:
// (a) 덮어쓰면 베이스의 기존 곡이 사라지고,
// (b) 새 곡을 스킵하면 데이터팩이 가리키는 곡이 빠진 채로 설치된다.
// 안전하게 설치를 즉시 실패시키고 어떤 키가 충돌했는지 알린다.
let collides = soundsJson[trackId] !== undefined
if (!collides) {
try { await fs.access(destFile); collides = true } catch { /* 없음 → OK */ }
}
if (collides) {
throw new Error(t('errors.baseTrackCollision', { trackId }))
}
await fs.copyFile(path.join(opts.musicDir, fname), destFile)
soundsJson[trackId] = {
sounds: [
{ name: `${NAMESPACE}:${trackId}`, stream: true }
@@ -160,16 +176,25 @@ export async function buildResourcepackZip(opts: BuildResourcepackOptions): Prom
}
}
await fs.writeFile(soundsJsonPath, JSON.stringify(soundsJson, null, 2) + '\n')
opts.log?.(t('log.tracksAdded', { count: musicFiles.length }))
throwIfCancelled(cancel)
// 3) painting 텍스처 복사 (이미 cover_NN.png 형태). 같은 파일명은 덮어씀.
// 3) painting 텍스처 복사 (이미 cover_NN.png 형태).
// 음악과 동일한 정책: 베이스에 같은 파일명이 이미 있으면 설치를 실패시킨다.
const paintingFiles = (await fs.readdir(opts.paintingDir))
.filter((n) => n.toLowerCase().endsWith('.png'))
.sort()
for (const fname of paintingFiles) {
throwIfCancelled(cancel)
await fs.copyFile(path.join(opts.paintingDir, fname), path.join(paintingOutDir, fname))
const destFile = path.join(paintingOutDir, fname)
let collides = false
try { await fs.access(destFile); collides = true } catch { /* 없음 → OK */ }
if (collides) {
throw new Error(t('errors.basePaintingCollision', { name: fname }))
}
await fs.copyFile(path.join(opts.paintingDir, fname), destFile)
}
opts.log?.(t('log.paintingsAdded', { count: paintingFiles.length }))
throwIfCancelled(cancel)
// 4) zip 으로 묶기. 이 단계가 가장 길어서 별도로 cancel 폴링이 들어간다.

View File

@@ -12,10 +12,14 @@ const api = {
selectPack: (packKey: string): Promise<void> =>
ipcRenderer.invoke('rp:packs:select', packKey),
/** 약관(Markdown) 다운로드. kind: 'resourcepack' | 'installer-rp'. */
/** 약관(Markdown) 다운로드. v0.3.4~ : 임의 kind 허용 (사이트에서 설정). */
getTerm: (kind: string): Promise<{ ok: boolean; content?: string; message?: string }> =>
ipcRenderer.invoke('rp:terms:get', kind),
/** rp 인스톨러에 표시할 약관 목록 (사이트의 visibility 토글로 필터링). */
getTermsList: (): Promise<{ ok: boolean; terms?: Array<{ kind: string; label: string }>; message?: string }> =>
ipcRenderer.invoke('rp:terms:list'),
/** 리소스팩 빌드/설치 시작. 완료 또는 취소될 때까지 resolve 되지 않을 수 있음. */
startInstall: (): Promise<{ resourcepackPath: string }> =>
ipcRenderer.invoke('rp:install:start'),
@@ -23,6 +27,10 @@ const api = {
cancelInstall: (): Promise<void> =>
ipcRenderer.invoke('rp:install:cancel'),
/** 재시도하지 않고 처음으로 돌아갈 때 받아둔 임시 파일을 정리한다. */
discardInstall: (): Promise<void> =>
ipcRenderer.invoke('rp:install:discard'),
/** %appdata%/.mc_custom/resourcepacks/ 폴더를 OS 파일 탐색기로 연다. */
openResourcepackFolder: (): Promise<void> =>
ipcRenderer.invoke('rp:finish:openFolder'),

View File

@@ -47,14 +47,20 @@ let installPromise: Promise<string> | null = null
* 의 최신 yt-dlp.exe 를 받아 설치하고, 그 절대경로를 돌려준다.
*/
export async function ensureYtDlpExe(
log?: (line: string) => void
log?: (line: string) => void,
force = false
): Promise<string> {
const target = getYtDlpExePath()
await migrateLegacyExe(target)
if (await canExecute(target)) {
if (!force && await canExecute(target)) {
log?.(t('log.ytdlpExists', { path: target }))
return target
}
if (force) {
// 강제 재설치: 오래됐을 수 있는 캐시본을 지워 최신 버전을 받게 한다.
log?.(t('log.ytdlpReinstall'))
try { await fs.unlink(target) } catch { /* noop */ }
}
if (installPromise) return installPromise
installPromise = (async () => {

View File

@@ -0,0 +1,224 @@
import { app, BrowserWindow, ipcMain, shell } from 'electron'
import path from 'node:path'
import fs from 'node:fs'
import fsp from 'node:fs/promises'
import { loadEnv } from '../shared/env.js'
import { getAppDataDir, getMcCustomDir } from '../shared/paths.js'
import { loadComponentI18n } from '../shared/i18n.js'
// 음악퀴즈 파일제거 도구. 음악퀴즈 간편설치기 / 리소스팩설치기가 만든 데이터를
// 한 번에 정리한다. (설치기 exe 자체는 사용자가 임의 위치에 둔 포터블이라
// 위치를 알 수 없어 삭제 대상에서 제외)
loadEnv()
const i18n = loadComponentI18n('installer-uninstall')
const t = i18n.t
const localeDict = i18n.dict
let mainWindow: BrowserWindow | null = null
function createMainWindow(): void {
const iconPath = path.join(__dirname, '..', '..', 'build', process.platform === 'win32' ? 'icon.ico' : 'icon.png')
mainWindow = new BrowserWindow({
width: 720,
height: 620,
icon: iconPath,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false
}
})
mainWindow.removeMenu()
void mainWindow.loadFile(path.join(__dirname, '..', '..', 'installer-uninstall', 'index.html'))
}
function sendLog(line: string): void {
if (!mainWindow || mainWindow.isDestroyed()) return
const stamped = `[${new Date().toLocaleTimeString('ko-KR', { hour12: false })}] ${line}`
mainWindow.webContents.send('log', stamped)
}
/** 마인크래프트 런처 프로필 파일 경로. */
function launcherProfilesPath(): string {
return path.join(getAppDataDir(), '.minecraft', 'launcher_profiles.json')
}
/** 데스크톱에 설치기가 만든 서버 실행 바로가기 경로. */
function serverShortcutPath(): string {
return path.join(app.getPath('desktop'), 'MusicQuiz Server.lnk')
}
/** 기본 폴더 이름(.mc_custom) 경로. MC_CUSTOM_DIR 을 바꿔 빌드해도, 예전 기본 폴더가 남아 있을 수 있으므로 함께 지운다. */
function defaultCustomDir(): string {
return path.join(getAppDataDir(), '.mc_custom')
}
/** 삭제 대상 커스텀 폴더 후보(현재 설정값 + 기본 .mc_custom)를 대소문자 무시로 중복 제거. */
function targetCustomDirs(): string[] {
const seen = new Set<string>()
const out: string[] = []
for (const dir of [getMcCustomDir(), defaultCustomDir()]) {
const key = path.resolve(dir).toLowerCase()
if (!seen.has(key)) {
seen.add(key)
out.push(dir)
}
}
return out
}
/** 두 경로가 같은 폴더거나, a 가 b 하위인지(대소문자 무시 — Windows 파일계). */
function isSameOrInside(child: string, parent: string): boolean {
const c = path.resolve(child).replace(/[\\/]+$/, '').toLowerCase()
const p = path.resolve(parent).replace(/[\\/]+$/, '').toLowerCase()
return c === p || c.startsWith(p + path.sep.toLowerCase()) || c.startsWith(p + '/')
}
interface UninstallPreview {
existingDirs: string[]
allTargetDirs: string[]
shortcutExists: boolean
launcherProfiles: string[]
}
/** 삭제 전 미리보기: 실제로 존재하는 대상만 추려 렌더러에 보여준다. */
ipcMain.handle('uninstall:preview', async (): Promise<UninstallPreview> => {
const allTargetDirs = targetCustomDirs()
const existingDirs = allTargetDirs.filter((d) => fs.existsSync(d))
const shortcutExists = fs.existsSync(serverShortcutPath())
const launcherProfiles = findMusicQuizProfiles(allTargetDirs)
return { existingDirs, allTargetDirs, shortcutExists, launcherProfiles }
})
/** launcher_profiles.json 에서 gameDir 가 커스텀 폴더(또는 그 하위)인 프로필 이름 목록. */
function findMusicQuizProfiles(customDirs: string[]): string[] {
const file = launcherProfilesPath()
if (!fs.existsSync(file)) return []
try {
const json = JSON.parse(fs.readFileSync(file, 'utf8')) as {
profiles?: Record<string, { name?: string; gameDir?: string }>
}
const profiles = json.profiles ?? {}
const names: string[] = []
for (const [key, prof] of Object.entries(profiles)) {
const gameDir = typeof prof?.gameDir === 'string' ? prof.gameDir : ''
if (gameDir && customDirs.some((d) => isSameOrInside(gameDir, d))) {
names.push(typeof prof?.name === 'string' && prof.name ? prof.name : key)
}
}
return names
} catch {
return []
}
}
interface UninstallResult {
removed: string[]
profilesRemoved: string[]
errors: string[]
}
/** 하나의 파일/폴더를 mode 에 따라 휴지통 이동 또는 완전 삭제. */
async function removeOne(target: string, mode: 'trash' | 'permanent'): Promise<void> {
if (mode === 'trash') {
await shell.trashItem(target)
} else {
await fsp.rm(target, { recursive: true, force: true })
}
}
/** launcher_profiles.json 에서 음악퀴즈 프로필만 제거하고 나머지는 보존. */
async function cleanLauncherProfiles(customDirs: string[]): Promise<string[]> {
const file = launcherProfilesPath()
if (!fs.existsSync(file)) return []
let json: { profiles?: Record<string, { name?: string; gameDir?: string }> }
try {
json = JSON.parse(await fsp.readFile(file, 'utf8'))
} catch {
sendLog(t('log.launcherParseFail', { path: file }))
return []
}
const profiles = json.profiles ?? {}
const removed: string[] = []
for (const [key, prof] of Object.entries(profiles)) {
const gameDir = typeof prof?.gameDir === 'string' ? prof.gameDir : ''
if (gameDir && customDirs.some((d) => isSameOrInside(gameDir, d))) {
removed.push(typeof prof?.name === 'string' && prof.name ? prof.name : key)
delete profiles[key]
}
}
if (removed.length > 0) {
json.profiles = profiles
await fsp.writeFile(file, `${JSON.stringify(json, null, 2)}\n`, 'utf8')
}
return removed
}
ipcMain.handle('uninstall:run', async (_event, modeInput: unknown): Promise<UninstallResult> => {
const mode: 'trash' | 'permanent' = modeInput === 'permanent' ? 'permanent' : 'trash'
const customDirs = targetCustomDirs()
const removed: string[] = []
const errors: string[] = []
sendLog(t('log.start', { mode: t(mode === 'trash' ? 'mode.trash' : 'mode.permanent') }))
// 1) 커스텀 게임/캐시 폴더 통째로(현재 설정값 + 기본 .mc_custom).
for (const customDir of customDirs) {
if (fs.existsSync(customDir)) {
try {
await removeOne(customDir, mode)
removed.push(customDir)
sendLog(t('log.removedDir', { path: customDir }))
} catch (err) {
const msg = (err as Error).message
errors.push(`${customDir}: ${msg}`)
sendLog(t('log.removeFail', { path: customDir, message: msg }))
}
} else {
sendLog(t('log.customDirMissing', { path: customDir }))
}
}
// 2) 데스크톱 서버 실행 바로가기.
const shortcut = serverShortcutPath()
if (fs.existsSync(shortcut)) {
try {
await removeOne(shortcut, mode)
removed.push(shortcut)
sendLog(t('log.removedShortcut', { path: shortcut }))
} catch (err) {
const msg = (err as Error).message
errors.push(`${shortcut}: ${msg}`)
sendLog(t('log.removeFail', { path: shortcut, message: msg }))
}
}
// 3) 마인크래프트 런처 프로필에서 음악퀴즈 설정 제거.
let profilesRemoved: string[] = []
try {
profilesRemoved = await cleanLauncherProfiles(customDirs)
for (const name of profilesRemoved) sendLog(t('log.removedProfile', { name }))
} catch (err) {
const msg = (err as Error).message
errors.push(`launcher_profiles.json: ${msg}`)
sendLog(t('log.launcherWriteFail', { message: msg }))
}
sendLog(t('log.done', { count: removed.length + profilesRemoved.length }))
return { removed, profilesRemoved, errors }
})
ipcMain.handle('uninstall:i18n:dict', () => localeDict)
ipcMain.handle('uninstall:quit', () => app.quit())
app.whenReady().then(() => {
createMainWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createMainWindow()
})
})
app.on('window-all-closed', () => {
app.quit()
})

View File

@@ -0,0 +1,43 @@
import { contextBridge, ipcRenderer } from 'electron'
interface UninstallPreview {
customDir: string
customDirExists: boolean
shortcutExists: boolean
launcherProfiles: string[]
}
interface UninstallResult {
removed: string[]
profilesRemoved: string[]
errors: string[]
}
const api = {
/** i18n 사전을 렌더러에 전달. */
loadLocale: (): Promise<Record<string, unknown>> => ipcRenderer.invoke('uninstall:i18n:dict'),
/** 삭제 전, 실제로 존재하는 대상 미리보기. */
preview: (): Promise<UninstallPreview> => ipcRenderer.invoke('uninstall:preview'),
/** 삭제 실행. mode: 'trash'(휴지통) | 'permanent'(완전 삭제). */
run: (mode: 'trash' | 'permanent'): Promise<UninstallResult> => ipcRenderer.invoke('uninstall:run', mode),
/** 프로그램 종료. */
quit: (): Promise<void> => ipcRenderer.invoke('uninstall:quit'),
/** 로그 스트림 구독. */
onLog: (handler: (line: string) => void): (() => void) => {
const listener = (_event: unknown, line: string) => handler(line)
ipcRenderer.on('log', listener)
return () => ipcRenderer.removeListener('log', listener)
}
}
contextBridge.exposeInMainWorld('uninstaller', api)
declare global {
interface Window {
uninstaller: typeof api
}
}

File diff suppressed because one or more lines are too long

View File

@@ -6,7 +6,7 @@ import os from 'node:os'
import path from 'node:path'
import fs from 'node:fs'
import fsp from 'node:fs/promises'
import { spawn } from 'node:child_process'
import { spawn, spawnSync } from 'node:child_process'
import { URL } from 'node:url'
import natUpnp from 'nat-upnp'
// extract-zip은 CommonJS 기본 export.
@@ -19,13 +19,25 @@ import type {
ServerInstallPayload
} from './types.js'
import type { Manifest, PackDefinition } from '../shared/types.js'
import { normalizePackDefinition } from '../shared/store.js'
import { normalizePackDefinition, normalizeRecommendedJdk } from '../shared/store.js'
import { getMcCustomDirName, withCustomDirName } from '../shared/paths.js'
import { loadEnv, getManifestUrl } from '../shared/env.js'
import { loadComponentI18n } from '../shared/i18n.js'
import { resolveAudience, isPackVisibleForAudience, type Audience } from '../shared/audience.js'
import { LAUNCHER_PROFILE_ICON } from './launcherIcon.js'
loadEnv()
// 이 빌드의 대상(일반/개발자용). package.json 의 musicQuizAudience 로 결정.
function getAudience(): Audience {
try {
const pkg = JSON.parse(fs.readFileSync(path.join(app.getAppPath(), 'package.json'), 'utf8'))
return resolveAudience(pkg.musicQuizAudience)
} catch {
return resolveAudience(undefined)
}
}
const i18n = loadComponentI18n('installer')
const t = i18n.t
export const localeDict = i18n.dict
@@ -87,6 +99,16 @@ function sendLog(line: string): void {
mainWindow.webContents.send('log', stamped)
}
// nat-upnp(detectExternalIpUpnp) 등이 콜백 밖에서 비동기 소켓 오류를 내면 처리되지
// 않아 Electron 메인이 종료되며 창이 갑자기 닫힐 수 있다. 전역 가드로 잡아 로그만
// 남기고 앱은 계속 살려 둔다(포트포워딩 전용 도구 v0.3.18 과 동일한 대비책).
process.on('uncaughtException', (err) => {
try { sendLog(t('log.internalError', { message: (err as Error)?.message || String(err) })) } catch {}
})
process.on('unhandledRejection', (reason) => {
try { sendLog(t('log.internalError', { message: reason instanceof Error ? reason.message : String(reason) })) } catch {}
})
function fetchBuffer(url: string): Promise<Buffer> {
return new Promise((resolve, reject) => {
const target = new URL(url)
@@ -136,9 +158,12 @@ ipcMain.handle('packs:load', async (_event, manifestUrlInput?: string): Promise<
}
sendLog(t('log.manifestDownload', { url: state.manifestUrl }))
const manifest = await fetchJson<Manifest>(state.manifestUrl)
const audience = getAudience()
const results: FetchedPack[] = []
for (const entry of manifest.packs ?? []) {
if (typeof entry?.file !== 'string') continue
// 대상(audience)에 맞지 않는 pack 은 건너뛴다(일반=public, 개발자용=non-public).
if (!isPackVisibleForAudience(entry.public, audience)) continue
const packUrl = `${state.baseUrl}/manifest.json`.replace(/manifest\.json$/, `manifest/${entry.file}.json`)
try {
const raw = await fetchJson<Partial<PackDefinition>>(packUrl)
@@ -154,15 +179,18 @@ ipcMain.handle('packs:load', async (_event, manifestUrlInput?: string): Promise<
return results
})
// 약관(Markdown) 을 사이트(/manifest/terms/<kind>.md) 에서 받아와 그대로 돌려준다.
// 화이트리스트로 5종 제한. 네트워크 실패 시 에러 메시지가 그대로 화면에 노출된다.
const TERM_KIND_WHITELIST = new Set(['map', 'resourcepack', 'mod', 'installer', 'installer-rp'])
// 약관(Markdown) 을 사이트(/manifest/terms/<packKey>/<kind>.md) 에서 받아와 그대로 돌려준다.
// v0.3.4~ : 사이트에서 임의 kind 등록 가능 → 하드코딩 5종 화이트리스트 대신 kind 형식만 검증.
const TERM_KIND_RE = /^[a-z0-9][a-z0-9-]{0,31}$/
ipcMain.handle('terms:get', async (_event, kind: string): Promise<{ ok: boolean; content?: string; message?: string }> => {
if (!TERM_KIND_WHITELIST.has(kind)) {
return { ok: false, message: 'unknown term kind' }
if (typeof kind !== 'string' || !TERM_KIND_RE.test(kind)) {
return { ok: false, message: 'invalid term kind' }
}
if (!state.selectedKey) {
return { ok: false, message: 'pack not selected' }
}
try {
const url = `${state.baseUrl}/manifest/terms/${kind}.md`
const url = `${state.baseUrl}/manifest/terms/${encodeURIComponent(state.selectedKey)}/${kind}.md`
const buf = await fetchBuffer(url)
return { ok: true, content: buf.toString('utf8') }
} catch (error) {
@@ -170,6 +198,31 @@ ipcMain.handle('terms:get', async (_event, kind: string): Promise<{ ok: boolean;
}
})
// 메인 인스톨러용 약관 목록. /manifest/terms/<packKey>/index.json 을 받아
// showInInstaller=true 인 항목만 추려 반환. 비어 있으면 렌더러가 약관 단계를 건너뛴다.
ipcMain.handle('terms:list', async (): Promise<{ ok: boolean; terms?: Array<{ kind: string; label: string }>; message?: string }> => {
if (!state.selectedKey) return { ok: false, message: 'pack not selected' }
try {
const url = `${state.baseUrl}/manifest/terms/${encodeURIComponent(state.selectedKey)}/index.json`
const buf = await fetchBuffer(url)
const parsed = JSON.parse(buf.toString('utf8')) as { terms?: unknown }
const items = Array.isArray(parsed.terms) ? parsed.terms : []
const terms: Array<{ kind: string; label: string }> = []
for (const it of items) {
if (!it || typeof it !== 'object') continue
const entry = it as Record<string, unknown>
if (entry.showInInstaller !== true) continue
const kind = typeof entry.kind === 'string' ? entry.kind : ''
const label = typeof entry.label === 'string' ? entry.label : ''
if (!TERM_KIND_RE.test(kind) || label.length === 0) continue
terms.push({ kind, label })
}
return { ok: true, terms }
} catch (error) {
return { ok: false, message: (error as Error).message }
}
})
ipcMain.handle('packs:select', async (_event, packKey: string) => {
if (!state.packs.has(packKey)) {
throw new Error(t('errors.packNotFound'))
@@ -199,43 +252,186 @@ ipcMain.handle('install:validatePath', async (_event, target: string) => {
return { ok: true, message: absolute }
})
ipcMain.handle('jdk:detect', async () => {
const candidates: string[] = []
if (process.env.JAVA_HOME) candidates.push(process.env.JAVA_HOME)
if (process.env.JDK_HOME) candidates.push(process.env.JDK_HOME)
// 자동 설치 위치(우리 설치기가 만든 JDK)도 후보에 포함.
candidates.push(path.join(getAppDataDir(), 'jdk', 'temurin-21'))
candidates.push('C:\\Program Files\\Java')
// 권장 JDK 메이저는 사이트의 pack.recommendedJdk 로 결정된다(미지정/이상값은 기본값 25).
// 최신 마인크래프트 서버 jar 이 "class file version 69.0"(=Java 25)처럼 특정 자바 버전을
// 요구하며, 그보다 낮은 자바로 실행하면 UnsupportedClassVersionError 로 서버가 뜨지 않는다.
/** 자동 설치 폴더 이름(예: temurin-25). */
function jdkDirName(major: number): string {
return `temurin-${major}`
}
for (const candidate of candidates) {
if (!candidate) continue
/**
* java 실행 파일의 메이저 버전을 조회한다(`java -version` 은 stderr 로 출력).
* 'openjdk version "25.0.3"' → 25, '"1.8.0_xx"' → 8.
* 실행 실패/파싱 실패 시 0.
*/
function getJavaMajor(javaExe: string): number {
try {
const stat = await fsp.stat(candidate)
if (stat.isFile()) {
return { found: true, path: candidate }
}
if (stat.isDirectory()) {
const javaExe = path.join(candidate, 'bin', process.platform === 'win32' ? 'java.exe' : 'java')
if (fs.existsSync(javaExe)) {
return { found: true, path: candidate }
}
const entries = await fsp.readdir(candidate)
for (const entry of entries) {
const child = path.join(candidate, entry)
const childJava = path.join(child, 'bin', process.platform === 'win32' ? 'java.exe' : 'java')
if (fs.existsSync(childJava)) {
return { found: true, path: child }
const res = spawnSync(javaExe, ['-version'], { encoding: 'utf8', timeout: 8000 })
const out = `${res.stdout || ''}${res.stderr || ''}`
const m = out.match(/version\s+"(\d+)(?:\.(\d+))?/i)
if (!m) return 0
let major = parseInt(m[1], 10)
if (major === 1 && m[2]) major = parseInt(m[2], 10) // 1.8 → 8
return Number.isNaN(major) ? 0 : major
} catch {
return 0
}
}
/** 후보 JDK 홈에서 java 실행 파일 경로를 찾는다(홈 직하 또는 한 단계 감싼 jdk-* 하위까지). */
function findJavaExeInHome(candidate: string): string {
const javaName = process.platform === 'win32' ? 'java.exe' : 'java'
try {
const stat = fs.statSync(candidate)
if (stat.isFile()) return candidate
const direct = path.join(candidate, 'bin', javaName)
if (fs.existsSync(direct)) return direct
for (const entry of fs.readdirSync(candidate)) {
const childJava = path.join(candidate, entry, 'bin', javaName)
if (fs.existsSync(childJava)) return childJava
}
} catch {
continue
return ''
}
return ''
}
/** %appdata%/<.mc_custom>. 자동 설치 JDK 는 이 폴더 아래 jdk/ 에 둔다. */
function customRootDir(): string {
return path.join(getAppDataDir(), getMcCustomDirName())
}
/** 설치기 자동 설치 JDK 의 루트(.mc_custom/jdk). */
function installerJdkRoot(): string {
return path.join(customRootDir(), 'jdk')
}
/** dir(또는 그 한 단계 하위 jdk-* 폴더)에서 java 를 찾아 실제 JDK 홈(<home>/bin/java)을 돌려준다. 없으면 ''. */
function resolveJdkHome(dir: string): string {
const javaExe = findJavaExeInHome(dir)
if (!javaExe) return ''
// findJavaExeInHome 은 항상 <home>/bin/java(.exe) 를 돌려준다 → 상위 두 단계가 홈.
return path.basename(path.dirname(javaExe)) === 'bin' ? path.dirname(path.dirname(javaExe)) : dir
}
/**
* parent 아래에서 JDK 홈들을 모두 찾는다. parent 자신, 그리고 각 하위 폴더를 검사하되,
* Adoptium zip 처럼 한 단계 더 감싼 `jdk-*` 하위까지 resolveJdkHome 으로 풀어낸다.
* (예: .mc_custom/jdk/temurin-25/jdk-25.0.3+9/bin/java.exe)
*/
function jdkHomesUnder(parent: string): string[] {
const out: string[] = []
const add = (h: string): void => { if (h) out.push(h) }
add(resolveJdkHome(parent))
try {
for (const entry of fs.readdirSync(parent)) {
add(resolveJdkHome(path.join(parent, entry)))
}
} catch {
/* 폴더 없음 등 무시 */
}
return out
}
interface JdkEntry { home: string; major: number }
/** 홈 목록 → {home, major} 목록(중복/버전0 제거). */
function homesToEntries(homes: string[]): JdkEntry[] {
const javaName = process.platform === 'win32' ? 'java.exe' : 'java'
const seen = new Set<string>()
const out: JdkEntry[] = []
for (const home of homes) {
const key = home.toLowerCase()
if (seen.has(key)) continue
seen.add(key)
const major = getJavaMajor(path.join(home, 'bin', javaName))
if (major > 0) out.push({ home, major })
}
return out
}
/** 설치기 자동 설치 위치(.mc_custom/jdk, 구버전 %APPDATA%/jdk 호환)의 JDK 들. */
function mcCustomJdkEntries(): JdkEntry[] {
const homes: string[] = []
for (const base of [installerJdkRoot(), path.join(getAppDataDir(), 'jdk')]) {
homes.push(...jdkHomesUnder(base))
}
return homesToEntries(homes)
}
/** 환경변수(JAVA_HOME/JDK_HOME)에 등록된 JDK 들. */
function envJdkEntries(): JdkEntry[] {
const homes: string[] = []
for (const env of [process.env.JAVA_HOME, process.env.JDK_HOME]) {
if (env) {
const h = resolveJdkHome(env)
if (h) homes.push(h)
}
}
return { found: false, path: '' }
return homesToEntries(homes)
}
/** 기본 자바 설치 위치 C:\Program Files\Java 아래의 JDK 들. */
function programFilesJdkEntries(): JdkEntry[] {
return homesToEntries(jdkHomesUnder('C:\\Program Files\\Java'))
}
// JDK 탐색 우선순위(요청 사양):
// ① .mc_custom/jdk(설치기가 설치해둔 위치)가 있으면 먼저 사용 — 권장 버전이면 그대로,
// 혹시 다른 버전이면 경고(match=false).
// ② 환경변수(JAVA_HOME/JDK_HOME) 가 권장 버전이면 사용.
// ③ 기본 폴더 C:\Program Files\Java 에 권장 버전이 있으면 사용.
// ④ 없으면 환경변수 자바로 폴백하고 "권장과 다름" 경고(match=false).
// (환경변수 자바도 없으면 Program Files 자바로 폴백, 그것도 없으면 not found → 자동 설치 유도.)
ipcMain.handle('jdk:detect', async (_event, recommendedInput?: number) => {
const required = normalizeRecommendedJdk(recommendedInput)
const recommended = (entries: JdkEntry[]): JdkEntry | undefined => entries.find((e) => e.major === required)
const best = (entries: JdkEntry[]): JdkEntry => entries.slice().sort((a, b) => b.major - a.major)[0]
// ① .mc_custom/jdk 우선.
const mc = mcCustomJdkEntries()
if (mc.length > 0) {
const rec = recommended(mc)
if (rec) return { found: true, path: rec.home, major: required, match: true }
const b = best(mc)
return { found: true, path: b.home, major: b.major, match: false }
}
// ② 환경변수 JDK 가 권장 버전이면 사용.
const env = envJdkEntries()
const envRec = recommended(env)
if (envRec) return { found: true, path: envRec.home, major: required, match: true }
// ③ 기본 폴더(Program Files\Java)에 권장 버전이 있으면 사용.
const pf = programFilesJdkEntries()
const pfRec = recommended(pf)
if (pfRec) return { found: true, path: pfRec.home, major: required, match: true }
// ④ 폴백: 환경변수 자바 → (없으면) Program Files 자바 + 경고.
if (env.length > 0) {
const b = best(env)
return { found: true, path: b.home, major: b.major, match: false }
}
if (pf.length > 0) {
const b = best(pf)
return { found: true, path: b.home, major: b.major, match: false }
}
return { found: false, path: '', major: required, match: false }
})
// ── JDK 자동 설치(Temurin 21, 취소 가능) ──────────────────────────────
// 사용자가 직접 입력/선택한 JDK 경로의 자바 버전을 확인한다.
// major=0 → 경로에서 java 를 못 찾거나 버전을 못 읽음(진행 차단용).
// match=true → 권장 버전과 정확히 일치.
// match=false → 다른 버전(진행은 허용하되 렌더러가 경고를 띄운다).
ipcMain.handle('jdk:verify', async (_event, jdkPath: string, recommendedInput?: number): Promise<{ ok: boolean; major: number; required: number; match: boolean }> => {
const required = normalizeRecommendedJdk(recommendedInput)
const javaExe = jdkPath ? findJavaExeInHome(jdkPath) : ''
const major = javaExe ? getJavaMajor(javaExe) : 0
return { ok: major > 0, major, required, match: major === required }
})
// ── JDK 자동 설치(권장 버전 Temurin, .mc_custom/jdk 에 설치, 취소 가능) ──────
interface JdkInstallState {
controller: AbortController | null
destDir: string | null
@@ -309,22 +505,24 @@ function downloadStream(
})
}
ipcMain.handle('jdk:install', async (): Promise<{ ok: boolean; path?: string; message?: string }> => {
ipcMain.handle('jdk:install', async (_event, recommendedInput?: number): Promise<{ ok: boolean; path?: string; message?: string }> => {
if (jdkInstall.inProgress) {
return { ok: false, message: t('errors.jdkBusy') }
}
const required = normalizeRecommendedJdk(recommendedInput)
jdkInstall.inProgress = true
const controller = new AbortController()
jdkInstall.controller = controller
const tmpRoot = path.join(getAppDataDir(), 'jdk-cache')
// 자동 설치 JDK 는 .mc_custom/jdk 아래에 둔다(파일제거기가 .mc_custom 통째로 정리 가능).
const tmpRoot = path.join(installerJdkRoot(), '.cache')
await fsp.mkdir(tmpRoot, { recursive: true })
const tempZip = path.join(tmpRoot, `temurin-21-${Date.now()}.zip`)
const destDir = path.join(getAppDataDir(), 'jdk', 'temurin-21')
const tempZip = path.join(tmpRoot, `${jdkDirName(required)}-${Date.now()}.zip`)
const destDir = path.join(installerJdkRoot(), jdkDirName(required))
jdkInstall.destDir = destDir
try {
// Adoptium API v3: latest GA JDK 21 Windows x64. 본문은 307 로 GitHub 릴리즈로 리다이렉트.
const url = 'https://api.adoptium.net/v3/binary/latest/21/ga/windows/x64/jdk/hotspot/normal/eclipse?project=jdk'
sendLog(t('log.jdkInstallStart'))
// Adoptium API v3: latest GA JDK(Windows x64). 본문은 307 로 GitHub 릴리즈로 리다이렉트.
const url = `https://api.adoptium.net/v3/binary/latest/${required}/ga/windows/x64/jdk/hotspot/normal/eclipse?project=jdk`
sendLog(t('log.jdkInstallStart', { major: required }))
let lastPctReported = -1
await downloadStream(url, tempZip, controller.signal, (loaded, total) => {
if (total > 0) {
@@ -561,6 +759,54 @@ async function downloadResourcepackZip(pack: PackDefinition, customRoot: string)
await downloadFile(url, target)
}
/**
* run.bat 에 넣을 java 실행 명령을 만든다. 자동 설치 JDK 는 %APPDATA% 아래에 있으므로
* 사용자명이 한글이어도 인코딩 문제 없이 실행되도록 `%APPDATA%\...\java.exe` 형태로
* 만든다(사용자명은 cmd 가 런타임에 전개). %APPDATA% 밖(예: Program Files)이면 절대경로.
*/
function javaCommandForRunBat(javaExe: string): string {
const appData = getAppDataDir()
const rel = path.relative(appData, javaExe)
if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) {
return `"%APPDATA%\\${rel.split(/[\\/]/).join('\\')}"`
}
return `"${javaExe}"`
}
/**
* 서버 zip 의 run.bat 이 시스템 PATH 의 `java` 를 그대로 쓰면, 사용자의 낡은 자바(예: 17)로
* 실행돼 최신 마인크래프트 서버가 UnsupportedClassVersionError 로 뜨지 않는다.
* 설치기가 준비/선택한 JDK 의 java 를 쓰도록 run.bat 의 `java` 실행 토큰을 치환한다.
* - `java ... -jar ...`, `java @args nogui`, `"java" ...` 형태 지원.
* - 이미 경로/다른 실행기를 쓰는 줄은 건드리지 않는다.
* 바이트 보존을 위해 latin1 로 읽고 쓰되(비-ASCII 주석 깨짐 방지), 삽입하는 경로는
* %APPDATA% 전개형이라 ASCII 라 안전하다.
*/
async function patchServerRunBatJava(installPath: string, jdkPath: string): Promise<void> {
const runBat = path.join(installPath, 'run.bat')
if (!fs.existsSync(runBat)) return
const javaExe = findJavaExeInHome(jdkPath)
if (!javaExe) {
sendLog(t('log.runBatJavaSkip'))
return
}
const command = javaCommandForRunBat(javaExe)
const original = await fsp.readFile(runBat, { encoding: 'latin1' })
const lines = original.split(/\r?\n/)
let changed = false
for (let i = 0; i < lines.length; i++) {
const m = lines[i].match(/^(\s*)"?java(?:\.exe)?"?(\s+.*)$/i)
if (m && /(-jar|\bnogui\b|@|-Xm)/i.test(m[2])) {
lines[i] = `${m[1]}${command}${m[2]}`
changed = true
}
}
if (changed) {
await fsp.writeFile(runBat, lines.join('\r\n'), { encoding: 'latin1' })
sendLog(t('log.runBatJavaPatched', { java: command }))
}
}
ipcMain.handle('server:install', async (_event, payload: ServerInstallPayload) => {
const pack = state.packs.get(payload.packKey)
if (!pack) throw new Error(t('errors.packNotFound2'))
@@ -575,83 +821,12 @@ ipcMain.handle('server:install', async (_event, payload: ServerInstallPayload) =
await downloadServerZip(pack.pack, installPath)
// 다운로드한 zip에 들어있을 수 있는 eula.txt를 그대로 보존한다.
// 동의 흐름은 renderer가 별도 IPC로 읽고 동의 시 덮어쓴다.
// run.bat 에 서버 기동/종료시 UPnP 자동 등록/해제 로직 주입.
// 이렇게 해야 서버가 안 떠 있는 동안에는 포트가 닫혀 있게 된다.
await injectUpnpToRunBat(installPath)
// 설치기는 포트를 직접 열지 않는다(요청). run.bat 에 UPnP 자동 개방을 주입하지
// 않으며, 사용자가 라우터에서 수동 포워딩을 하고 포트포워딩 페이지에서 확인만 한다.
// 단, run.bat 이 시스템의 낡은 자바를 쓰지 않도록 설치기가 준비한 JDK 로 바꿔준다.
await patchServerRunBatJava(installPath, payload.jdkPath)
})
/**
* 추출된 서버 zip 의 run.bat 에 UPnP 자동 등록(서버 시작 시) / 자동 해제(서버 종료 후)
* 스크립트를 끼워 넣는다. 이미 우리가 주입했던 마커가 있으면 다시 건드리지 않는다.
*
* 동작:
* 1) 서버 시작 직전: server.properties 의 server-port 값(없으면 25565) 으로 PowerShell
* 을 통해 HNetCfg.NATUPnP.1 COM 객체를 이용해 정적 포트 매핑 추가.
* 2) 서버 프로세스 종료 후(=pause 직전 또는 파일 끝): 동일한 포트의 매핑 제거.
*
* 제한: 사용자가 콘솔 창을 X 버튼으로 강제 종료하면 teardown 이 실행되지 않는다.
* 이 경우 라우터의 UPnP TTL 에 의해 자동 만료되며, 다음 실행 시 Add 전에 Remove 를
* 시도하므로 idempotent.
*/
async function injectUpnpToRunBat(installPath: string): Promise<void> {
const runBat = path.join(installPath, 'run.bat')
if (!fs.existsSync(runBat)) {
sendLog(t('log.runBatMissing'))
return
}
const MARKER = 'REM === UPNP MANAGED BY MUSICQUIZ INSTALLER ==='
const original = await fsp.readFile(runBat, 'utf8')
if (original.includes(MARKER)) {
sendLog(t('log.runBatAlreadyInjected'))
return
}
const lines = original.split(/\r?\n/)
const javaIdx = lines.findIndex((line) => /^\s*java(\.exe)?[\s"]/i.test(line))
if (javaIdx === -1) {
sendLog(t('log.runBatNoJava'))
return
}
let pauseIdx = -1
for (let i = javaIdx + 1; i < lines.length; i++) {
if (/^\s*pause\b/i.test(lines[i])) { pauseIdx = i; break }
}
if (pauseIdx === -1) pauseIdx = lines.length
// PowerShell 한 줄로 처리: server.properties 의 server-port 우선, 없으면 25565.
// Add 전에 같은 포트의 매핑이 남아 있으면 먼저 Remove 하여 idempotent 하게 만든다.
const addBlock = [
MARKER,
'REM 서버 시작 직전: server-port 추출 후 UPnP 매핑 등록.',
'set "_MQ_PORT=25565"',
'for /f "tokens=2 delims==" %%a in (\'findstr /b /c:"server-port=" server.properties 2^>nul\') do set "_MQ_PORT=%%a"',
'set "_MQ_PORT=%_MQ_PORT: =%"',
'echo [MusicQuiz] UPnP 등록 시도: TCP %_MQ_PORT%',
'powershell -NoProfile -Command "$port=[int]$env:_MQ_PORT; $ip=(Get-NetIPAddress -AddressFamily IPv4 -PrefixOrigin Dhcp,Manual -ErrorAction SilentlyContinue ^| Where-Object {$_.IPAddress -notlike \'169.254.*\' -and $_.IPAddress -ne \'127.0.0.1\'} ^| Select-Object -First 1).IPAddress; if (-not $ip) { Write-Host \'[MusicQuiz] 로컬 IPv4 검색 실패\'; exit 1 }; try { $u = New-Object -ComObject HNetCfg.NATUPnP.1; $c=$u.StaticPortMappingCollection; if ($c) { try { $c.Remove($port,\'TCP\') ^| Out-Null } catch {}; $c.Add($port,\'TCP\',$port,$ip,$true,\'MusicQuiz Minecraft Server\') ^| Out-Null; Write-Host (\'[MusicQuiz] UPnP 등록 성공: \' + $ip + \':\' + $port + \' TCP\') } else { Write-Host \'[MusicQuiz] UPnP 컬렉션 사용 불가(라우터 UPnP 꺼짐?)\' } } catch { Write-Host (\'[MusicQuiz] UPnP 등록 실패: \' + $_.Exception.Message) }"'
]
const removeBlock = [
'REM 서버 종료 후: UPnP 매핑 해제.',
'echo [MusicQuiz] UPnP 해제 시도: TCP %_MQ_PORT%',
'powershell -NoProfile -Command "$port=[int]$env:_MQ_PORT; try { $u = New-Object -ComObject HNetCfg.NATUPnP.1; $c=$u.StaticPortMappingCollection; if ($c) { $c.Remove($port,\'TCP\') ^| Out-Null; Write-Host (\'[MusicQuiz] UPnP 해제 완료: TCP \' + $port) } } catch { Write-Host (\'[MusicQuiz] UPnP 해제 실패: \' + $_.Exception.Message) }"'
]
const merged: string[] = []
merged.push(...lines.slice(0, javaIdx))
merged.push(...addBlock)
merged.push(lines[javaIdx])
merged.push(...lines.slice(javaIdx + 1, pauseIdx))
merged.push(...removeBlock)
merged.push(...lines.slice(pauseIdx))
// bat 파일은 CRLF 가 안전.
const output = merged.join('\r\n')
await fsp.writeFile(runBat, output, 'utf8')
sendLog(t('log.runBatInjected'))
}
ipcMain.handle('server:readEula', async (_event, installPath: string): Promise<{ exists: boolean; content: string }> => {
if (!installPath) return { exists: false, content: '' }
const target = path.join(path.resolve(installPath), 'eula.txt')
@@ -677,7 +852,12 @@ ipcMain.handle('server:fetchMinecraftEula', async (): Promise<{ url: string; htm
ipcMain.handle('server:acceptEula', async (_event, installPath: string) => {
const target = path.join(installPath, 'eula.txt')
await fsp.writeFile(target, `# Generated by music quiz installer\neula=true\n`, 'utf8')
const acceptedAt = new Date()
await fsp.writeFile(
target,
`# Generated by music quiz installer\n# EULA accepted at: ${acceptedAt.toISOString()}\neula=true\n`,
'utf8',
)
sendLog(t('log.eulaAccepted'))
})
@@ -832,12 +1012,7 @@ ipcMain.handle('server:portForward', async (_event, port: number): Promise<PortF
const targetPort = Number.isFinite(port) && port > 0 ? port : 25565
sendLog(t('log.portCheckStart', { port: targetPort }))
// 1차 점검 전에 우리가 이전 실행에서 만든 UPnP 매핑이 남아 있으면 먼저 제거한다.
// 이렇게 해야 "사용자 라우터 규칙이 활성화돼서 외부 접근이 가능한 상태" 와 "UPnP 매핑 덕분에 접근 가능한 상태" 가 구별된다.
// 사용자 규칙이 비활성/없으면 1차 점검은 false 가 되어 UPnP 시도 단계로 자연스럽게 넘어간다.
sendLog(t('log.upnpCleanup'))
await removeUpnpMapping(targetPort)
// 설치기는 포트를 직접 열지 않는다. 외부에서 이미 열려 있는지만 확인한다.
// 외부 IP 확보: 공용 API → 실패 시 UPnP 게이트웨이의 외부 IP로 폴백.
let externalIp = await detectExternalIpHttp()
if (externalIp) {
@@ -849,9 +1024,9 @@ ipcMain.handle('server:portForward', async (_event, port: number): Promise<PortF
else sendLog(t('log.externalIpUpnpFail'))
}
// 1차 점검: 외부에서 이미 접근 가능한지 (서버가 떠 있거나, 우리가 임시 리스너 띄워서 검증).
// 외부에서 포트가 닿는지 점검(서버가 떠 있거나, 임시 리스너 검증).
sendLog(t('log.probeStart'))
let probe = await probePortFromOutside(targetPort, externalIp)
const probe = await probePortFromOutside(targetPort, externalIp)
if (!externalIp && probe.detectedIp) externalIp = probe.detectedIp
const verdict = probe.reachable === true
? t('log.probeVerdictSuccess')
@@ -860,47 +1035,9 @@ ipcMain.handle('server:portForward', async (_event, port: number): Promise<PortF
if (probe.reachable === true) {
sendLog(t('log.probePreForwarded', { addr: externalIp || t('log.ipUnknown'), port: targetPort }))
return { status: 'preForwarded', externalIp, port: targetPort }
return { status: 'open', externalIp, port: targetPort }
}
// UPnP 시도.
sendLog(t('log.upnpTryOpen', { port: targetPort }))
try {
await openPortViaUpnp(targetPort)
sendLog(t('log.upnpReqOk'))
} catch (error) {
const msg = (error as Error).message || String(error)
sendLog(t('log.upnpTryFail', { message: msg }))
return {
status: 'upnpFailed',
externalIp,
port: targetPort,
message: t('log.upnpFailDetail', { message: msg })
}
}
// NAT 반영 지연을 고려해 최대 3회 재점검.
for (let attempt = 1; attempt <= 3; attempt++) {
await sleep(1500)
sendLog(t('log.upnpRecheck', { attempt }))
probe = await probePortFromOutside(targetPort, externalIp)
if (!externalIp && probe.detectedIp) externalIp = probe.detectedIp
if (probe.reachable === true) {
sendLog(t('log.upnpDone', { port: targetPort }))
await removeUpnpMapping(targetPort)
return { status: 'upnpOk', externalIp, port: targetPort }
}
}
// 테스트 목적으로 만든 매핑 정리. 실제 개방은 run.bat 이 담당.
sendLog(t('log.upnpCleanupTest'))
await removeUpnpMapping(targetPort)
const reason = probe.reachable === false
? t('log.upnpFailReason1')
: t('log.upnpFailReason2', { detail: probe.detail })
sendLog(reason)
return { status: 'upnpFailed', externalIp, port: targetPort, message: reason }
return { status: 'notOpen', externalIp, port: targetPort }
})
async function detectExternalIpHttp(): Promise<string> {
@@ -1035,8 +1172,14 @@ async function probePortFromOutside(
details.push(t('log.detailIfconfigFail', { error: (externalResult as { error: string }).error }))
}
// 임시 리스너가 떴고 외부 서비스도 닿지 않았다면 명확한 false.
if (reachable === null && listenerBound && !gotInboundConnection) reachable = false
// '닫힘(false)' 판정은 외부 점검 서비스(ifconfig.co)가 명시적으로 reachable=false
// 돌려준 경우에만 인정한다(위 분기에서 처리). 임시 리스너에 인바운드가 안 왔다는 사실만으로는
// false 로 단정하지 않는다:
// - ifconfig.co 가 타임아웃/레이트리밋으로 실패하면 애초에 외부에서 연결을 시도한 적이 없으므로
// '리스너 미도달'은 아무 의미가 없다(과거엔 이 경우를 false 로 오탐했다).
// - 인바운드를 받는 주체가 마크 서버가 아니라 설치기(node/electron) 프로세스라, Windows 방화벽이
// 설치기 인바운드만 막아도 포워딩이 정상이어도 '리스너 미도달'이 된다.
// 따라서 외부 판정이 없으면 reachable=null(확인 불가)로 남겨 UPnP 시도/안내 단계로 넘긴다.
return {
reachable,
@@ -1045,7 +1188,21 @@ async function probePortFromOutside(
}
}
function fetchIfconfigCoPort(port: number): Promise<{ ok: true; reachable: boolean | null; ip: string } | { ok: false; error: string }> {
type IfconfigPortResult = { ok: true; reachable: boolean | null; ip: string } | { ok: false; error: string }
// ifconfig.co 는 간헐적으로 타임아웃/레이트리밋(429)을 낸다. 실패를 곧장 '확인 불가'로
// 넘기기 전에 한 번 더 시도해서 일시적 실패로 인한 오탐/미확인을 줄인다.
async function fetchIfconfigCoPort(port: number): Promise<IfconfigPortResult> {
let last: IfconfigPortResult = { ok: false, error: 'no attempt' }
for (let attempt = 0; attempt < 2; attempt++) {
last = await fetchIfconfigCoPortOnce(port)
if (last.ok) return last
if (attempt === 0) await sleep(1500)
}
return last
}
function fetchIfconfigCoPortOnce(port: number): Promise<IfconfigPortResult> {
return new Promise((resolve) => {
const target = new URL(`https://ifconfig.co/port/${port}`)
const req = https.get(target, {
@@ -1076,64 +1233,6 @@ function fetchIfconfigCoPort(port: number): Promise<{ ok: true; reachable: boole
})
}
function removeUpnpMapping(port: number): Promise<void> {
return new Promise((resolve) => {
let settled = false
const done = () => { if (!settled) { settled = true; resolve() } }
let client: ReturnType<typeof natUpnp.createClient> | null = null
try {
client = natUpnp.createClient()
} catch (err) {
sendLog(t('log.upnpClientFailRemove', { message: (err as Error).message }))
done()
return
}
const timer = setTimeout(() => {
try { client && client.close() } catch {}
sendLog(t('log.upnpRemoveTimeout'))
done()
}, 8000)
client.portUnmapping({ public: port, protocol: 'tcp' }, (err: Error | null) => {
clearTimeout(timer)
try { client && client.close() } catch {}
if (err) sendLog(t('log.upnpRemoveAttempt', { message: err.message }))
else sendLog(t('log.upnpRemoveDone', { port }))
done()
})
})
}
function openPortViaUpnp(port: number): Promise<void> {
return new Promise((resolve, reject) => {
let settled = false
const done = (err?: Error) => {
if (settled) return
settled = true
if (err) reject(err)
else resolve()
}
let client: ReturnType<typeof natUpnp.createClient> | null = null
try {
client = natUpnp.createClient()
} catch (err) {
done(err as Error)
return
}
const timer = setTimeout(() => {
try { client && client.close() } catch {}
done(new Error(t('errors.upnpTimeout')))
}, 15000)
client.portMapping(
{ public: port, private: port, ttl: 0, description: 'MusicQuiz Server', protocol: 'tcp' },
(error: Error | null) => {
clearTimeout(timer)
try { client && client.close() } catch {}
done(error || undefined)
}
)
})
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
@@ -1141,7 +1240,7 @@ function sleep(ms: number): Promise<void> {
ipcMain.handle('client:install', async (_event, payload: ClientInstallPayload) => {
const pack = state.packs.get(payload.packKey)
if (!pack) throw new Error(t('errors.packNotFound2'))
const customRoot = path.join(getAppDataDir(), '.mc_custom')
const customRoot = path.join(getAppDataDir(), getMcCustomDirName())
await fsp.mkdir(path.join(customRoot, 'mods'), { recursive: true })
await fsp.mkdir(path.join(customRoot, 'resourcepacks'), { recursive: true })
@@ -1684,7 +1783,27 @@ ipcMain.handle('finish:startLauncher', async () => {
sendLog(t('log.launcherAllFail'))
})
ipcMain.handle('i18n:dict', () => localeDict)
// 개발자용 빌드(musicQuizAudience=developer)면 렌더러에 넘기는 사전의 제목 앞에
// "(개발자용) " 을 붙여, 창 제목/헤더에 개발자용임을 표시한다.
function dictForRenderer(): Record<string, unknown> {
// 커스텀 폴더명을 UI 문구에 반영.
const base = withCustomDirName(localeDict)
if (getAudience() !== 'developer') return base
const prefix = '(개발자용) '
const appBlock = (base.app ?? {}) as Record<string, unknown>
const withPrefix = (v: unknown): unknown =>
typeof v === 'string' && !v.startsWith(prefix) ? prefix + v : v
return {
...base,
app: {
...appBlock,
browserTitle: withPrefix(appBlock.browserTitle),
headerTitle: withPrefix(appBlock.headerTitle)
}
}
}
ipcMain.handle('i18n:dict', () => dictForRenderer())
ipcMain.handle('app:quit', () => {
// 모든 창을 닫고 앱 종료. macOS에서도 종료(설치기는 한 번 쓰고 끝이니 잔류시키지 않음).

View File

@@ -14,6 +14,9 @@ const api = {
// 약관(Markdown) 다운로드
getTerm: (kind: string): Promise<{ ok: boolean; content?: string; message?: string }> =>
ipcRenderer.invoke('terms:get', kind),
// 메인 인스톨러용 약관 목록 (사이트의 visibility 토글에 따라 필터링됨)
getTermsList: (): Promise<{ ok: boolean; terms?: Array<{ kind: string; label: string }>; message?: string }> =>
ipcRenderer.invoke('terms:list'),
// 3-1
pickFolder: (): Promise<string | null> => ipcRenderer.invoke('dialog:pickFolder'),
@@ -21,8 +24,12 @@ const api = {
ipcRenderer.invoke('install:validatePath', target),
// 3-2
detectJdk: (): Promise<{ found: boolean; path: string }> => ipcRenderer.invoke('jdk:detect'),
installJdk: (): Promise<{ ok: boolean; path?: string; message?: string }> => ipcRenderer.invoke('jdk:install'),
detectJdk: (recommendedJdk?: number): Promise<{ found: boolean; path: string; major: number; match: boolean }> =>
ipcRenderer.invoke('jdk:detect', recommendedJdk),
verifyJdk: (jdkPath: string, recommendedJdk?: number): Promise<{ ok: boolean; major: number; required: number; match: boolean }> =>
ipcRenderer.invoke('jdk:verify', jdkPath, recommendedJdk),
installJdk: (recommendedJdk?: number): Promise<{ ok: boolean; path?: string; message?: string }> =>
ipcRenderer.invoke('jdk:install', recommendedJdk),
cancelJdkInstall: (): Promise<{ ok: boolean }> => ipcRenderer.invoke('jdk:cancelInstall'),
// 3-3

View File

@@ -36,7 +36,8 @@ export interface RamCheckResult {
}
export interface PortForwardResult {
status: 'preForwarded' | 'upnpOk' | 'upnpFailed'
// 설치기는 포트를 직접 열지 않고 "열려 있는지"만 확인한다.
status: 'open' | 'notOpen'
externalIp?: string
port: number
message?: string

View File

@@ -1,12 +1,17 @@
import express from 'express'
import session from 'express-session'
import path from 'node:path'
import fs from 'node:fs'
import fsp from 'node:fs/promises'
import crypto from 'node:crypto'
import {
manifestRootPath, manifestDirPath, manifestTermsDirPath,
fileDirPath, viewsDirPath, publicDirPath
fileDirPath, viewsDirPath, publicDirPath, projectRoot,
accountFilePath, accountLocalFilePath
} from '../shared/paths.js'
import { isPublicTermsFile } from '../shared/store.js'
import {
ensurePackTermsDir, isPublicTermsFile, listTermsWithLabels, loadPackDefinition
} from '../shared/store.js'
import { loadEnv } from '../shared/env.js'
import { t, localeDict } from './i18n.js'
import { indexRouter } from './routes/index.js'
@@ -23,7 +28,24 @@ const app = express()
app.set('view engine', 'ejs')
app.set('views', viewsDirPath)
app.set('trust proxy', 1)
// 리버스 프록시 뒤일 때만 켠다. 항상 켜두면 직접 노출 시 X-Forwarded-For 조작으로
// req.ip 를 위조해 로그인 rate limit 을 우회할 수 있다. 프록시 뒤라면 TRUST_PROXY=true.
app.set('trust proxy', process.env.TRUST_PROXY === 'true' ? 1 : false)
// 추적되는 account.json(과거 평문 노출)을 gitignore 된 account.local.json 으로 시드한다.
// 로컬 파일이 이미 있으면 건드리지 않음. 이후 계정 쓰기/자동 해시 업그레이드는 로컬
// 파일에만 반영되어, 재배포로 account.json 을 추적 해제해도 로그인이 유지된다.
function seedLocalAccounts(): void {
try {
if (fs.existsSync(accountLocalFilePath)) return
if (!fs.existsSync(accountFilePath)) return
fs.copyFileSync(accountFilePath, accountLocalFilePath)
fs.chmodSync(accountLocalFilePath, 0o600)
} catch {
// 실패해도 readAccounts 가 account.json 으로 폴백하므로 치명적이지 않음.
}
}
seedLocalAccounts()
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
@@ -36,13 +58,36 @@ app.use((_req, res, next) => {
next()
})
// 세션 시크릿: 환경변수 우선, 없으면 하드코딩(위조 위험) 대신 영구 랜덤 시크릿을
// 파일로 생성/보관한다(재시작해도 세션 유지). 파일 접근 불가 시엔 프로세스 수명 동안만
// 유효한 랜덤값으로 폴백(그래도 하드코딩보다 안전).
function resolveSessionSecret(): string {
const fromEnv = process.env.SESSION_SECRET
if (fromEnv && fromEnv.length >= 16) return fromEnv
const secretPath = path.join(projectRoot, '.session-secret')
try {
if (fs.existsSync(secretPath)) {
const existing = fs.readFileSync(secretPath, 'utf8').trim()
if (existing.length >= 16) return existing
}
const generated = crypto.randomBytes(32).toString('hex')
fs.writeFileSync(secretPath, generated, { mode: 0o600 })
return generated
} catch {
return crypto.randomBytes(32).toString('hex')
}
}
app.use(session({
secret: process.env.SESSION_SECRET ?? 'music-quiz-installer-dev-secret',
secret: resolveSessionSecret(),
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
sameSite: 'lax',
// HTTPS 전용 배포면 SESSION_COOKIE_SECURE=true 로 secure 쿠키 활성화.
// HTTP 접근이 섞이면 로그인 쿠키가 안 실리므로 기본값은 false.
secure: process.env.SESSION_COOKIE_SECURE === 'true',
maxAge: 1000 * 60 * 60 * 8
}
}))
@@ -64,18 +109,57 @@ app.get('/manifest.json', (_req, res) => {
})
// 설치기 + 사이트가 약관(markdown) 을 가져갈 수 있도록 .md 만 허용한다.
// 음악퀴즈(pack) 별로 manifest/terms/<packKey>/<file>.md 에서 노출한다.
// _meta.json 같은 시스템 파일이나 경로 탈출은 isPublicTermsFile 에서 차단.
app.get('/manifest/terms/:fileName', (req, res) => {
const fileName = req.params.fileName
if (!isPublicTermsFile(fileName)) {
//
// fresh 배포에서 관리자가 약관 페이지를 한 번도 열지 않은 상태로 설치기가 약관을
// 요청하는 경우에도 작동하도록, 실제 pack 이면 ensurePackTermsDir 로 v0.3.1
// 전역 .md 들을 시드 복사한 뒤 sendFile 한다. 임의 packKey 로 빈 폴더가
// 생성되는 것은 loadPackDefinition 으로 차단.
// 설치기가 자기에게 표시할 약관 목록을 받아갈 수 있도록 packKey 별 index.json.
// 응답: [{ kind, label, showInInstaller, showInInstallerRp }]. v0.3.4~ builtin 개념이
// 없어졌으므로 인스톨러는 이 목록을 받아 자기 인스톨러용(`showInInstaller` / `showInInstallerRp`)
// 으로 필터링해서 탭을 만든다.
app.get('/manifest/terms/:packKey/index.json', async (req, res, next) => {
try {
const { packKey } = req.params
if (!/^[a-zA-Z0-9_\-]+$/.test(packKey)) {
res.status(404).json({ terms: [] })
return
}
const pack = await loadPackDefinition(packKey)
if (!pack) {
res.status(404).json({ terms: [] })
return
}
const terms = await listTermsWithLabels(packKey)
res.json({ terms })
} catch (error) {
next(error)
}
})
app.get('/manifest/terms/:packKey/:fileName', async (req, res, next) => {
try {
const { packKey, fileName } = req.params
if (!isPublicTermsFile(packKey, fileName)) {
res.status(404).send('Not Found')
return
}
const pack = await loadPackDefinition(packKey)
if (!pack) {
res.status(404).send('Not Found')
return
}
await ensurePackTermsDir(packKey)
res.type('text/markdown; charset=utf-8')
res.sendFile(path.join(manifestTermsDirPath, fileName), (err) => {
res.sendFile(path.join(manifestTermsDirPath, packKey, fileName), (err) => {
if (!err || res.headersSent) return
res.status(404).send('Not Found')
})
} catch (error) {
next(error)
}
})
// 설치기에서 개별 음악퀴즈 JSON을 가져갈 수 있도록 파일 단위로만 허용.
@@ -102,7 +186,7 @@ app.use((req, res, next) => {
})
// 모드 폴더 안의 .jar 파일 목록을 JSON으로 반환. 설치기가 자동 다운로드용으로 사용.
app.get('/file/mods/:folder/index.json', async (req, res) => {
app.get('/file/mods/:folder/index.json', async (req, res, next) => {
const folder = req.params.folder
if (!/^[a-zA-Z0-9_\-]+$/.test(folder)) {
res.status(404).json({ files: [] })
@@ -121,7 +205,8 @@ app.get('/file/mods/:folder/index.json', async (req, res) => {
res.status(404).json({ files: [] })
return
}
throw error
// async 핸들러의 throw 는 Express4 가 잡지 못해 unhandledRejection 이 되므로 next 로 위임.
next(error)
}
})

View File

@@ -1,8 +1,17 @@
import type { MusicListEntry, PackList } from '../shared/types.js'
/** SNBT 문자열 리터럴 안에 들어갈 문자열을 escape. */
/**
* SNBT 문자열 리터럴 안에 들어갈 문자열을 escape.
* 백슬래시·따옴표 외에도 줄바꿈·탭을 이스케이프해서 `data modify` 한 줄 명령이
* description 같은 멀티라인 입력 때문에 깨지지 않게 한다.
*/
function escapeSnbtString(input: string): string {
return input.replace(/\\/g, '\\\\').replace(/"/g, '\\"')
return input
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
}
/** alias 배열을 SNBT 리스트 리터럴로 변환. 빈 배열도 `[]` 로 출력. */
@@ -12,13 +21,18 @@ function aliasListSnbt(aliases: string[]): string {
return `[${parts.join(',')}]`
}
/** 한 곡(MusicListEntry) → `{title:"...", author:"...", alias:[...]}` SNBT. */
/** 한 곡(MusicListEntry) → `{volume:0.5, title:"...", author:"...", alias:[...], description:"...", video:"..."}` SNBT. */
function entrySnbt(entry: MusicListEntry): string {
const title = escapeSnbtString(entry.title ?? '')
// launcher 의 artist → 데이터팩 SNBT 의 author. 빈 값은 빈 문자열로 그대로 둔다.
const author = escapeSnbtString(entry.artist ?? '')
const alias = aliasListSnbt(entry.aliases ?? [])
return `{title:"${title}", author:"${author}", alias:${alias}}`
const description = escapeSnbtString(entry.description ?? '')
// video = 곡의 유튜브 영상 주소(MusicListEntry.url).
const video = escapeSnbtString(entry.url ?? '')
// launcher 가 생성하는 항목에는 volume 기본값 0.5 를 항상 넣는다.
// 운영자는 생성된 mcfunction 에서 곡별로 직접 값을 바꿔 사용한다.
return `{volume:0.5, title:"${title}", author:"${author}", alias:${alias}, description:"${description}", video:"${video}"}`
}
/**
@@ -29,11 +43,11 @@ function entrySnbt(entry: MusicListEntry): string {
export function buildSongsMcfunction(list: PackList): string {
const lines: string[] = []
lines.push('# 곡 한 개 = 한 줄.')
lines.push('# 필수 — title, author, alias')
lines.push('# 필수 — title, author, alias, description, video')
lines.push('# 선택 — volume (이 곡만의 /playsound 음량. 미지정시 init/config.mcfunction')
lines.push('# 의 audio.volume 사용)')
lines.push('# 곡 순서가 리소스팩의 track_NN / cover_NN 인덱스와 1:1 매칭된다.')
lines.push('# 예) {title:"Quiet Song", author:"...", alias:[...], volume:2.0}')
lines.push('# 예) {volume:0.5, title:"Quiet Song", author:"...", alias:[...], description:"...", video:"..."}')
lines.push('data modify storage mq:main songs set value []')
for (const entry of list.music) {
lines.push(`data modify storage mq:main songs append value ${entrySnbt(entry)}`)

48
src/server/password.ts Normal file
View File

@@ -0,0 +1,48 @@
import crypto from 'node:crypto'
// 운영자 비밀번호 저장/검증. 외부 의존성 없이 Node 내장 scrypt 사용.
// 저장 형식: `scrypt$<saltHex>$<hashHex>`. 검증은 항상 상수시간 비교.
// 기존 account.json 의 평문 비밀번호는 verifyPassword 가 그대로 검증할 수 있고,
// 로그인 성공 시 호출측에서 hashPassword 로 재저장(자동 업그레이드)한다.
const SCHEME = 'scrypt'
const KEY_LEN = 32
const SALT_LEN = 16
export function hashPassword(plain: string): string {
const salt = crypto.randomBytes(SALT_LEN)
const hash = crypto.scryptSync(plain, salt, KEY_LEN)
return `${SCHEME}$${salt.toString('hex')}$${hash.toString('hex')}`
}
export function isHashed(stored: string): boolean {
return typeof stored === 'string' && stored.startsWith(`${SCHEME}$`)
}
export function verifyPassword(plain: string, stored: string): boolean {
if (typeof stored !== 'string' || stored.length === 0) return false
if (isHashed(stored)) {
const parts = stored.split('$')
if (parts.length !== 3) return false
let salt: Buffer
let expected: Buffer
try {
salt = Buffer.from(parts[1], 'hex')
expected = Buffer.from(parts[2], 'hex')
} catch {
return false
}
if (expected.length === 0) return false
let derived: Buffer
try {
derived = crypto.scryptSync(plain, salt, expected.length)
} catch {
return false
}
return derived.length === expected.length && crypto.timingSafeEqual(derived, expected)
}
// 레거시 평문: 길이 노출을 피하려 양쪽을 sha256 으로 고정 길이화한 뒤 상수시간 비교.
const a = crypto.createHash('sha256').update(plain, 'utf8').digest()
const b = crypto.createHash('sha256').update(stored, 'utf8').digest()
return crypto.timingSafeEqual(a, b)
}

View File

@@ -8,9 +8,9 @@ indexRouter.get('/', async (_req, res, next) => {
const manifest = await readManifest()
const definitionMap = new Map<string, Awaited<ReturnType<typeof loadPackDefinition>>>()
const keys = await listPackKeys()
for (const key of keys) {
definitionMap.set(key, await loadPackDefinition(key))
}
// 팩 정의를 병렬 로드(op.ts 와 동일 패턴). 순차 await 보다 빠름.
const definitions = await Promise.all(keys.map((key) => loadPackDefinition(key)))
keys.forEach((key, i) => definitionMap.set(key, definitions[i]))
const packs = manifest.packs.map((entry) => ({
name: entry.name,
file: entry.file,

View File

@@ -5,8 +5,8 @@ import {
createTerm,
deletePackKeys,
deleteTerm,
getTermLabel,
isBuiltinTermKind,
getTermEntry,
importTerms,
isTermKind,
listPackKeys,
listTermsWithLabels,
@@ -16,12 +16,19 @@ import {
normalizePackDefinition,
normalizePackList,
readAccounts,
readManifest,
renamePack,
sanitizePackKey,
saveTerm,
savePackList
savePackList,
setPackPublic,
setTermVisibility,
writeAccounts,
SUPPORTED_JDK_MAJORS
} from '../../shared/store.js'
import { hashPassword, isHashed, verifyPassword } from '../password.js'
import { fetchReleaseVersions } from '../../shared/mojang.js'
import { fetchJdkAvailability, fetchJdkReleaseNames } from '../../shared/jdkVersions.js'
import { fetchPlaylistEntries, fetchVideoMeta, YtDlpUnavailableError } from '../youtube.js'
import { requireAuth } from '../middleware/auth.js'
import type { PackDefinition, PackList } from '../../shared/types.js'
@@ -30,6 +37,40 @@ import { buildSongsMcfunction } from '../datapack.js'
export const opRouter = Router()
// 로그인 브루트포스 + scrypt CPU 남용 방지용 IP 기준 인메모리 실패 제한.
const LOGIN_WINDOW_MS = 15 * 60 * 1000
const LOGIN_MAX_FAILS = 10
const loginFails = new Map<string, { count: number; first: number; blockedUntil: number }>()
function loginClientKey(req: { ip?: string; socket?: { remoteAddress?: string } }): string {
return req.ip || req.socket?.remoteAddress || 'unknown'
}
/** 차단 중이면 남은 ms, 아니면 0. 접근 시 만료된 항목은 정리. */
function loginBlockedMs(key: string): number {
const now = Date.now()
const entry = loginFails.get(key)
if (!entry) return 0
if (entry.blockedUntil > now) return entry.blockedUntil - now
if (now - entry.first > LOGIN_WINDOW_MS) loginFails.delete(key)
return 0
}
function recordLoginFail(key: string): void {
const now = Date.now()
let entry = loginFails.get(key)
if (!entry || now - entry.first > LOGIN_WINDOW_MS) entry = { count: 0, first: now, blockedUntil: 0 }
entry.count += 1
if (entry.count >= LOGIN_MAX_FAILS) entry.blockedUntil = now + LOGIN_WINDOW_MS
loginFails.set(key, entry)
// 맵 무한 성장 방지(분산 시도 대비): 상한 초과 시 만료 항목 정리.
if (loginFails.size > 5000) {
for (const [k, v] of loginFails) {
if (v.blockedUntil <= now && now - v.first > LOGIN_WINDOW_MS) loginFails.delete(k)
}
}
}
function pickFirstValue(value: unknown): string {
if (Array.isArray(value)) return typeof value[0] === 'string' ? value[0] : ''
return typeof value === 'string' ? value : ''
@@ -53,13 +94,32 @@ opRouter.get('/op', (req, res) => {
opRouter.post('/op', async (req, res, next) => {
try {
const clientKey = loginClientKey(req)
const blockedMs = loginBlockedMs(clientKey)
if (blockedMs > 0) {
res.status(429).render('op/login', {
error: t('login.tooManyAttempts', { minutes: Math.ceil(blockedMs / 60000) })
})
return
}
const password = pickFirstValue(req.body.password)
const accounts = await readAccounts()
const matched = accounts.find((entry) => entry.password === password)
const matched = accounts.find((entry) => verifyPassword(password, entry.password))
if (!matched) {
recordLoginFail(clientKey)
res.status(401).render('op/login', { error: t('login.wrongPassword') })
return
}
loginFails.delete(clientKey)
// 평문으로 저장돼 있던 비밀번호는 로그인 성공 시 scrypt 해시로 자동 업그레이드.
if (!isHashed(matched.password)) {
try {
matched.password = hashPassword(password)
await writeAccounts(accounts)
} catch {
// 업그레이드 실패는 로그인 자체에 영향 주지 않음.
}
}
req.session.userId = matched.id
res.redirect('/op/dashboard')
} catch (error) {
@@ -121,17 +181,47 @@ opRouter.get('/op/dashboard/:packName', requireAuth, async (req, res, next) => {
return
}
const releases = await fetchReleaseVersions()
const manifest = await readManifest()
const entry = manifest.packs.find((e) => e.file === packKey)
const isPublic = entry ? entry.public !== false : true
res.render('op/editor', {
userId: req.session.userId,
packKey,
pack: definition,
releases
releases,
isPublic,
jdkOptions: SUPPORTED_JDK_MAJORS
})
} catch (error) {
next(error)
}
})
// ─── /op/jdk-versions ───────────────────────────────────────────────────
// Adoptium(Temurin) 에서 실제 배포되는 JDK 메이저 목록을 프록시(브라우저 직접 호출은
// CORS 로 막힘). 편집기의 "권장 JDK" 드롭다운을 이 결과로 채운다.
opRouter.get('/op/jdk-versions', requireAuth, async (_req, res, next) => {
try {
res.json(await fetchJdkAvailability())
} catch (error) {
next(error)
}
})
// 특정 메이저의 상세 릴리스 이름(GA + EA 스냅샷). "자세히 보기" 에서 사용.
opRouter.get('/op/jdk-versions/:major', requireAuth, async (req, res, next) => {
try {
const major = Number(req.params.major)
if (!Number.isInteger(major) || major < 8 || major > 99) {
res.status(400).json({ error: 'invalid major' })
return
}
res.json(await fetchJdkReleaseNames(major))
} catch (error) {
next(error)
}
})
// ─── /op/list ──────────────────────────────────────────────────────────
// 음악퀴즈를 카드 한 줄로 표시. 카드 클릭 → /op/list/:packName
opRouter.get('/op/list', requireAuth, async (req, res, next) => {
@@ -292,8 +382,8 @@ opRouter.get('/op/datapack/:packName/images-zip', requireAuth, async (req, res,
asset_id: `musicquiz:cover_${nn}`,
width: size,
height: size,
title: { text: `Cover ${nn}` },
author: { text: 'music quiz' }
author: 'musicquiz',
title: `cover_${nn}`
}
archive.append(JSON.stringify(json, null, 2) + '\n', { name: `cover_${nn}.json` })
}
@@ -304,64 +394,147 @@ opRouter.get('/op/datapack/:packName/images-zip', requireAuth, async (req, res,
})
// ─── /op/agreement ─────────────────────────────────────────────────────
// 약관(Markdown) 편집기. builtin 5종은 항상 존재하고 삭제 불가, 그 외 임의 kind 는
// 사이트에서 추가/삭제 가능. 인스톨러는 /manifest/terms/<kind>.md 로 받아 표시한다.
// 약관(Markdown) 편집기. 음악퀴즈(pack) 단위로 따로 저장한다.
// 5종 기본 약관(map/mod/installer/resourcepack/installer-rp) 은 첫 접근 시 시드되지만
// 사용자가 자유롭게 삭제/추가/표시 대상 변경할 수 있다 (v0.3.4~). 인스톨러는
// /manifest/terms/<packKey>/index.json 으로 자신에게 표시할 약관 목록을 받는다.
// /op/agreement → 음악퀴즈 선택(/op/list 와 동일한 카드 형식).
opRouter.get('/op/agreement', requireAuth, async (req, res, next) => {
try {
const items = await listTermsWithLabels()
const keys = await listPackKeys()
const items = await Promise.all(keys.map(async (key) => ({
key,
definition: await loadPackDefinition(key)
})))
res.render('op/terms', { userId: req.session.userId, items })
} catch (error) {
next(error)
}
})
opRouter.post('/op/agreement/create', requireAuth, async (req, res, next) => {
// /op/agreement/:packName → 해당 pack 의 약관 목록 + 추가/불러오기/삭제.
opRouter.get('/op/agreement/:packName', requireAuth, async (req, res, next) => {
try {
const packKey = sanitizePackKey(pickFirstValue(req.params.packName))
const definition = await loadPackDefinition(packKey)
if (!definition) {
res.status(404).send(t('errors.packNotFound'))
return
}
const items = await listTermsWithLabels(packKey)
// 불러오기 source 후보: 현재 pack 을 제외한 나머지.
const allKeys = await listPackKeys()
const sourceCandidates = await Promise.all(
allKeys
.filter((k) => k !== packKey)
.map(async (k) => ({ key: k, definition: await loadPackDefinition(k) }))
)
res.render('op/terms-pack', {
userId: req.session.userId,
packKey,
pack: definition,
items,
sourceCandidates
})
} catch (error) {
next(error)
}
})
opRouter.post('/op/agreement/:packName/create', requireAuth, async (req, res, next) => {
try {
const packKey = sanitizePackKey(pickFirstValue(req.params.packName))
const definition = await loadPackDefinition(packKey)
if (!definition) {
res.status(404).send(t('errors.packNotFound'))
return
}
const kindInput = pickFirstValue(req.body.kind).trim().toLowerCase()
const label = pickFirstValue(req.body.label)
if (!isTermKind(kindInput)) {
res.status(400).send(t('terms.invalidKind'))
return
}
await createTerm(kindInput, label)
res.redirect(`/op/agreement/${kindInput}`)
await createTerm(packKey, kindInput, label)
res.redirect(`/op/agreement/${packKey}/${kindInput}`)
} catch (error) {
res.status(400).send((error as Error).message || t('terms.createFailed'))
}
})
opRouter.post('/op/agreement/:kind/delete', requireAuth, async (req, res, next) => {
opRouter.post('/op/agreement/:packName/import', requireAuth, async (req, res, next) => {
try {
const packKey = sanitizePackKey(pickFirstValue(req.params.packName))
const definition = await loadPackDefinition(packKey)
if (!definition) {
res.status(404).send(t('errors.packNotFound'))
return
}
const sourceKey = sanitizePackKey(pickFirstValue(req.body.source))
if (!sourceKey || sourceKey === packKey) {
res.status(400).send(t('terms.invalidImportSource'))
return
}
const sourceDefinition = await loadPackDefinition(sourceKey)
if (!sourceDefinition) {
res.status(404).send(t('terms.invalidImportSource'))
return
}
await importTerms(packKey, sourceKey)
res.redirect(`/op/agreement/${packKey}`)
} catch (error) {
res.status(400).send((error as Error).message || t('terms.importFailed'))
}
})
opRouter.post('/op/agreement/:packName/:kind/delete', requireAuth, async (req, res, next) => {
try {
const packKey = sanitizePackKey(pickFirstValue(req.params.packName))
const definition = await loadPackDefinition(packKey)
if (!definition) {
res.status(404).send(t('errors.packNotFound'))
return
}
const kind = pickFirstValue(req.params.kind)
if (!isTermKind(kind)) {
res.status(400).send(t('terms.invalidKind'))
return
}
if (isBuiltinTermKind(kind)) {
res.status(400).send(t('terms.cannotDeleteBuiltin'))
return
}
await deleteTerm(kind)
res.redirect('/op/agreement')
await deleteTerm(packKey, kind)
res.redirect(`/op/agreement/${packKey}`)
} catch (error) {
next(error)
}
})
opRouter.get('/op/agreement/:kind', requireAuth, async (req, res, next) => {
opRouter.get('/op/agreement/:packName/:kind', requireAuth, async (req, res, next) => {
try {
const packKey = sanitizePackKey(pickFirstValue(req.params.packName))
const definition = await loadPackDefinition(packKey)
if (!definition) {
res.status(404).send(t('errors.packNotFound'))
return
}
const kind = pickFirstValue(req.params.kind)
if (!isTermKind(kind)) {
res.status(404).send(t('errors.unknown'))
return
}
const content = await loadTerm(kind)
const label = await getTermLabel(kind)
const entry = await getTermEntry(packKey, kind)
if (!entry) {
res.status(404).send(t('errors.unknown'))
return
}
const content = await loadTerm(packKey, kind)
res.render('op/termsEditor', {
userId: req.session.userId,
packKey,
pack: definition,
kind,
label,
label: entry.label,
showInInstaller: entry.showInInstaller,
showInInstallerRp: entry.showInInstallerRp,
content
})
} catch (error) {
@@ -369,15 +542,32 @@ opRouter.get('/op/agreement/:kind', requireAuth, async (req, res, next) => {
}
})
opRouter.post('/op/agreement/:kind', requireAuth, async (req, res, next) => {
opRouter.post('/op/agreement/:packName/:kind', requireAuth, async (req, res, next) => {
try {
const packKey = sanitizePackKey(pickFirstValue(req.params.packName))
const definition = await loadPackDefinition(packKey)
if (!definition) {
res.status(404).json({ ok: false, message: t('errors.packNotFoundJson') })
return
}
const kind = pickFirstValue(req.params.kind)
if (!isTermKind(kind)) {
res.status(404).json({ ok: false, message: t('errors.unknown') })
return
}
const content = typeof req.body?.content === 'string' ? req.body.content : ''
await saveTerm(kind, content)
await saveTerm(packKey, kind, content)
// visibility 토글이 함께 전송되면 동시에 갱신. 두 값이 모두 false 면 어디에도
// 표시되지 않지만 사용자가 의도적으로 선택한 결과이므로 그대로 저장한다.
if (
typeof req.body?.showInInstaller === 'boolean'
|| typeof req.body?.showInInstallerRp === 'boolean'
) {
await setTermVisibility(packKey, kind, {
showInInstaller: req.body.showInInstaller === true,
showInInstallerRp: req.body.showInInstallerRp === true
})
}
res.json({ ok: true })
} catch (error) {
next(error)
@@ -408,6 +598,7 @@ opRouter.post('/op/dashboard/:packName', requireAuth, async (req, res, next) =>
serverMaxRam: Number(pickFirstValue(req.body.serverMaxRam)),
clientMinRam: Number(pickFirstValue(req.body.clientMinRam)),
clientRecommendedRam: Number(pickFirstValue(req.body.clientRecommendedRam)),
recommendedJdk: Number(pickFirstValue(req.body.recommendedJdk)),
mapPath: pickFirstValue(req.body.mapPath),
serverPath: pickFirstValue(req.body.serverPath)
}
@@ -418,6 +609,9 @@ opRouter.post('/op/dashboard/:packName', requireAuth, async (req, res, next) =>
return
}
const finalKey = await renamePack(packKey, requestedKey, normalized)
// 체크박스는 체크됐을 때만 전송되므로, 없으면 비공개(개발자용).
const isPublic = pickFirstValue(req.body.isPublic) === 'on' || pickFirstValue(req.body.isPublic) === 'true'
await setPackPublic(finalKey, isPublic)
res.redirect(`/op/dashboard/${finalKey}`)
} catch (error) {
next(error)

View File

@@ -32,48 +32,63 @@ function getYtDlpAssetName(): string {
return 'yt-dlp' // 그 외 OS: 순수 파이썬 zipapp. python3 가 PATH 에 있어야 동작
}
/** 로컬 설치 경로: %appdata%/.mc_custom/<asset> */
/**
* 로컬 설치 경로: OS별 사용자 데이터 디렉터리 안의 .mc_custom/<asset>.
* - Windows: %APPDATA%/.mc_custom/yt-dlp.exe
* - macOS : ~/Library/Application Support/.mc_custom/yt-dlp_macos
* - Linux 등: $XDG_CONFIG_HOME 또는 ~/.config/.mc_custom/yt-dlp_linux (arch 따라 다름)
*/
export function getYtDlpInstallPath(): string {
return path.join(getMcCustomDir(), getYtDlpAssetName())
}
/** 순수 파이썬 zipapp(`yt-dlp`) 의 로컬 설치 경로. python3 가 PATH 에 있어야 동작. */
function getYtDlpZipappPath(): string {
return path.join(getMcCustomDir(), 'yt-dlp_zipapp')
}
/** 한 번에 한 다운로드만 진행하도록 락 (서버 동시 요청 보호). */
let installPromise: Promise<string> | null = null
type ProbeResult = { ok: true } | { ok: false; detail: string }
/**
* %appdata%/.mc_custom/ 에 yt-dlp 가 준비됐는지 확인하고, 없으면 GitHub Releases 에서
* 현재 OS/아키텍처용 바이너리를 자동으로 받아 설치한다. 성공 시 실행 경로 반환.
* .mc_custom/ 디렉터리에 yt-dlp 가 준비됐는지 확인하고, 없으면 GitHub Releases 에서
* 현재 OS/아키텍처용 네이티브 바이너리를 자동으로 받아 설치한다. 성공 시 실행 경로 반환.
*
* 네이티브 바이너리가 실행되지 않는 환경(glibc 미스매치, musl libc, antivirus 차단 등)
* 이면 다음 순서로 폴백한다:
* 1) PATH 의 `yt-dlp(.exe)` (시스템에 따로 깐 거)
* 2) (POSIX 한정) 범용 파이썬 zipapp `yt-dlp` 를 다운로드 후 shebang 실행 — python3 필요
* 전부 실패하면 각 시도의 진단정보가 포함된 에러를 던진다.
*/
export async function ensureYtDlp(): Promise<string> {
export async function ensureYtDlp(force = false): Promise<string> {
const target = getYtDlpInstallPath()
// 이미 설치돼 있고 실행 가능하면 그대로 사용
if (await canExecute(target)) return target
if (!force) {
// Fast path: 이미 설치돼 있고 실행도 잘 되면 그대로 사용
if (await fileExists(target)) {
const probe = await probeVersion(target)
if (probe.ok) return target
}
// Fast path: 네이티브가 안 도는 환경에서 이전에 받아둔 zipapp 이 살아있으면 그걸 재사용
if (process.platform !== 'win32') {
const zipappPath = getYtDlpZipappPath()
if (await fileExists(zipappPath)) {
const probe = await probeVersion(zipappPath)
if (probe.ok) return zipappPath
}
}
} else {
// 강제 재설치: 캐시된(=오래됐을 수 있는) 바이너리를 지워 최신으로 다시 받게 한다.
try { await fs.unlink(target) } catch { /* noop */ }
if (process.platform !== 'win32') {
try { await fs.unlink(getYtDlpZipappPath()) } catch { /* noop */ }
}
}
if (installPromise) return installPromise
installPromise = (async () => {
try {
const dir = getMcCustomDir()
await fs.mkdir(dir, { recursive: true })
const asset = getYtDlpAssetName()
const url = `https://github.com/yt-dlp/yt-dlp/releases/latest/download/${asset}`
await downloadToFile(url, target)
// POSIX 계열은 실행 권한 부여
if (process.platform !== 'win32') {
await fs.chmod(target, 0o755)
}
// 검증
const okVersion = await probeVersion(target)
if (!okVersion) {
throw new YtDlpUnavailableError(t('youtube.ytdlpVerifyFailed'))
}
return target
} catch (err) {
// 실패 흔적(부분 다운로드) 삭제
try { await fs.unlink(target) } catch { /* noop */ }
throw err instanceof YtDlpUnavailableError
? err
: new YtDlpUnavailableError(
t('youtube.ytdlpInstallFailed', { message: err instanceof Error ? err.message : String(err) })
)
return await prepareYtDlp(target, force)
} finally {
installPromise = null
}
@@ -81,31 +96,121 @@ export async function ensureYtDlp(): Promise<string> {
return installPromise
}
async function canExecute(filePath: string): Promise<boolean> {
try {
await fs.access(filePath, fsConst.F_OK)
} catch {
return false
}
// POSIX 면 X 비트도 확인
if (process.platform !== 'win32') {
try {
await fs.access(filePath, fsConst.X_OK)
} catch {
return false
}
}
// 실제로 --version 으로 한 번 더 확인
return probeVersion(filePath)
async function prepareYtDlp(target: string, force = false): Promise<string> {
const diagnostics: string[] = []
// 강제 재설치(force)면 기존 캐시·PATH 시도를 건너뛰고 곧장 최신 버전을 받는다.
if (!force) {
// 1a. 기존 네이티브 파일이 있으면 우선 그걸로 시도
if (await fileExists(target)) {
const probe = await probeVersion(target)
if (probe.ok) return target
diagnostics.push(`기존 ${path.basename(target)} 검증 실패: ${probe.detail}`)
}
function probeVersion(bin: string): Promise<boolean> {
// 1b. (POSIX) 기존 zipapp 이 있으면 재다운로드 전에 먼저 시도
if (process.platform !== 'win32') {
const existingZipapp = getYtDlpZipappPath()
if (await fileExists(existingZipapp)) {
const probe = await probeVersion(existingZipapp)
if (probe.ok) return existingZipapp
diagnostics.push(`기존 yt-dlp_zipapp 검증 실패: ${probe.detail}`)
}
}
// 2. PATH 에 yt-dlp(.exe) 가 시스템 전역으로 설치돼 있으면 그걸 사용
const pathCmd = process.platform === 'win32' ? 'yt-dlp.exe' : 'yt-dlp'
const pathProbe = await probeVersion(pathCmd)
if (pathProbe.ok) return pathCmd
diagnostics.push(`PATH 의 ${pathCmd} 사용 불가: ${pathProbe.detail}`)
}
// 3. 최후 수단: 새로 다운로드해서 시도
try {
await fs.mkdir(getMcCustomDir(), { recursive: true })
const asset = getYtDlpAssetName()
const url = `https://github.com/yt-dlp/yt-dlp/releases/latest/download/${asset}`
try { await fs.unlink(target) } catch { /* noop */ }
await downloadToFile(url, target)
if (process.platform !== 'win32') {
await fs.chmod(target, 0o755)
} else {
// Windows: 인터넷에서 받은 파일에는 NTFS ADS 'Zone.Identifier' 가 붙어
// SmartScreen/Attachment Manager 가 실행을 막을 수 있다. 베스트에포트로 제거.
try { await fs.unlink(`${target}:Zone.Identifier`) } catch { /* noop */ }
}
const probe = await probeVersion(target)
if (probe.ok) return target
diagnostics.push(`새로 받은 ${asset} 검증 실패: ${probe.detail}`)
try { await fs.unlink(target) } catch { /* noop */ }
} catch (err) {
diagnostics.push(`다운로드 실패: ${err instanceof Error ? err.message : String(err)}`)
try { await fs.unlink(target) } catch { /* noop */ }
}
// 4. POSIX 한정 최후 폴백: 범용 파이썬 zipapp `yt-dlp` 다운로드 후 shebang 실행.
// 네이티브 바이너리가 glibc/musl/arch 문제로 못 도는 리눅스 환경이라도
// python3 가 PATH 에 있으면 동작한다. ~ 3MB 짜리 스크립트.
if (process.platform !== 'win32') {
const zipappPath = getYtDlpZipappPath()
try {
try { await fs.unlink(zipappPath) } catch { /* noop */ }
await downloadToFile('https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp', zipappPath)
await fs.chmod(zipappPath, 0o755)
const probe = await probeVersion(zipappPath)
if (probe.ok) return zipappPath
diagnostics.push(`zipapp yt-dlp 검증 실패: ${probe.detail} (python3 누락이거나 PATH 에 없음)`)
try { await fs.unlink(zipappPath) } catch { /* noop */ }
} catch (err) {
diagnostics.push(`zipapp 다운로드 실패: ${err instanceof Error ? err.message : String(err)}`)
try { await fs.unlink(zipappPath) } catch { /* noop */ }
}
}
throw new YtDlpUnavailableError(
t('youtube.ytdlpVerifyFailedDetail', { detail: diagnostics.join(' | ') })
)
}
async function fileExists(filePath: string): Promise<boolean> {
try {
await fs.access(filePath, fsConst.F_OK)
return true
} catch {
return false
}
}
function probeVersion(bin: string): Promise<ProbeResult> {
return new Promise((resolve) => {
const child = spawn(bin, ['--version'], { stdio: ['ignore', 'pipe', 'pipe'] })
let ok = false
child.stdout.on('data', () => { ok = true })
child.on('error', () => resolve(false))
child.on('close', (code) => resolve(ok && code === 0))
let child: ReturnType<typeof spawn>
try {
child = spawn(bin, ['--version'], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
} catch (err) {
resolve({ ok: false, detail: `spawn throw: ${err instanceof Error ? err.message : String(err)}` })
return
}
let stdout = ''
let stderr = ''
child.stdout?.on('data', (chunk: Buffer) => { stdout += chunk.toString('utf8') })
child.stderr?.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8') })
child.on('error', (err: NodeJS.ErrnoException) => {
const code = err.code ? `${err.code} ` : ''
resolve({ ok: false, detail: `spawn error: ${code}${err.message}` })
})
child.on('close', (code, signal) => {
const out = stdout.trim()
if (out && code === 0) {
resolve({ ok: true })
return
}
const parts: string[] = []
parts.push(`exit=${code === null ? `signal:${signal}` : code}`)
if (!out) parts.push('stdout=(empty)')
const errLine = stderr.trim().split('\n')[0]
if (errLine) parts.push(`stderr="${errLine.slice(0, 200)}"`)
resolve({ ok: false, detail: parts.join(', ') })
})
})
}
@@ -141,37 +246,78 @@ function downloadToFile(url: string, dest: string, redirects = 0): Promise<void>
})
}
/** yt-dlp 를 한 번 실행하고 종료코드·stdout·stderr 를 모은다. reject 하지 않는다. */
function spawnYtDlp(bin: string, args: string[]): Promise<{ code: number | null; stdout: string; stderr: string }> {
return new Promise((resolve) => {
let child: ReturnType<typeof spawn>
try {
child = spawn(bin, args, { stdio: ['ignore', 'pipe', 'pipe'] })
} catch (err) {
resolve({ code: null, stdout: '', stderr: err instanceof Error ? err.message : String(err) })
return
}
let stdout = ''
let stderr = ''
let settled = false
const done = (r: { code: number | null; stdout: string; stderr: string }) => {
if (settled) return
settled = true
resolve(r)
}
child.stdout?.on('data', (chunk: Buffer) => (stdout += chunk.toString('utf8')))
child.stderr?.on('data', (chunk: Buffer) => (stderr += chunk.toString('utf8')))
child.on('error', (err) => done({ code: null, stdout, stderr: stderr || (err as Error).message }))
child.on('close', (code) => done({ code, stdout, stderr }))
})
}
/**
* yt-dlp 를 실행하고 stdout 을 돌려준다. 첫 시도가 실패(0 이 아닌 종료코드/실행 불가)하면
* yt-dlp 가 오래돼 유튜브 변경을 못 따라가는 상황일 수 있으므로, 최신 버전으로 강제
* 재설치한 뒤 한 번 더 시도한다. 그래도 실패하면 makeError 로 만든 에러를 던진다.
*/
async function runYtDlp(args: string[], makeError: (code: string, detail: string) => Error): Promise<string> {
let bin = await ensureYtDlp()
let res = await spawnYtDlp(bin, args)
if (res.code !== 0) {
let refreshed = false
try {
bin = await ensureYtDlp(true)
refreshed = true
} catch { /* 재설치 실패 시 아래에서 원래 실패로 보고 */ }
if (refreshed) {
res = await spawnYtDlp(bin, args)
}
if (res.code !== 0) {
throw makeError(String(res.code), res.stderr.trim() || res.stdout.trim())
}
}
return res.stdout
}
/**
* 단일 영상 URL 의 메타데이터를 가져온다.
* `--no-playlist` 로 플레이리스트 URL 이 들어와도 단일 영상 정보만 뽑음.
*/
export async function fetchVideoMeta(url: string): Promise<YtPlaylistEntry | null> {
const bin = await ensureYtDlp()
return new Promise((resolve, reject) => {
const child = spawn(bin, [
'--dump-json',
'--no-warnings',
'--no-playlist',
'--skip-download',
url
], { stdio: ['ignore', 'pipe', 'pipe'] })
let stdout = ''
let stderr = ''
child.stdout.on('data', (chunk: Buffer) => (stdout += chunk.toString('utf8')))
child.stderr.on('data', (chunk: Buffer) => (stderr += chunk.toString('utf8')))
child.on('error', (err) => reject(err))
child.on('close', (code) => {
if (code !== 0) {
reject(new Error(t('youtube.ytdlpVideoFailed', { code: String(code), detail: stderr.trim() || stdout.trim() })))
return
/** 운영자 입력 URL 이 yt-dlp 인자(플래그)로 오인되지 않도록 http(s) 스킴만 허용. */
function assertHttpUrl(url: string): void {
if (!/^https?:\/\//i.test(url.trim())) {
throw new Error(t('youtube.invalidUrl'))
}
}
export async function fetchVideoMeta(url: string): Promise<YtPlaylistEntry | null> {
assertHttpUrl(url)
const stdout = await runYtDlp(
['--dump-json', '--no-warnings', '--no-playlist', '--skip-download', url],
(code, detail) => new Error(t('youtube.ytdlpVideoFailed', { code, detail }))
)
const line = stdout.trim().split('\n').find((l) => l.trim().length > 0)
if (!line) { resolve(null); return }
try {
if (!line) return null
const obj = JSON.parse(line) as Record<string, unknown>
const id = typeof obj.id === 'string' ? obj.id : ''
if (!id) { resolve(null); return }
resolve({
if (!id) return null
return {
id,
title: typeof obj.title === 'string' ? obj.title : '',
channel: typeof obj.channel === 'string'
@@ -181,12 +327,7 @@ export async function fetchVideoMeta(url: string): Promise<YtPlaylistEntry | nul
url: typeof obj.webpage_url === 'string' && obj.webpage_url.length > 0
? obj.webpage_url
: `https://www.youtube.com/watch?v=${id}`
})
} catch (err) {
reject(err)
}
})
})
}
/**
@@ -194,24 +335,11 @@ export async function fetchVideoMeta(url: string): Promise<YtPlaylistEntry | nul
* `--flat-playlist --dump-json` 출력은 한 줄당 한 JSON.
*/
export async function fetchPlaylistEntries(url: string): Promise<YtPlaylistEntry[]> {
const bin = await ensureYtDlp()
return new Promise((resolve, reject) => {
const child = spawn(bin, [
'--flat-playlist',
'--dump-json',
'--no-warnings',
url
], { stdio: ['ignore', 'pipe', 'pipe'] })
let stdout = ''
let stderr = ''
child.stdout.on('data', (chunk: Buffer) => (stdout += chunk.toString('utf8')))
child.stderr.on('data', (chunk: Buffer) => (stderr += chunk.toString('utf8')))
child.on('error', (err) => reject(err))
child.on('close', (code) => {
if (code !== 0) {
reject(new Error(t('youtube.ytdlpPlaylistFailed', { code: String(code), detail: stderr.trim() || stdout.trim() })))
return
}
assertHttpUrl(url)
const stdout = await runYtDlp(
['--flat-playlist', '--dump-json', '--no-warnings', url],
(code, detail) => new Error(t('youtube.ytdlpPlaylistFailed', { code, detail }))
)
const lines = stdout.split('\n').map((l) => l.trim()).filter((l) => l.length > 0)
const parsed: YtPlaylistEntry[] = []
for (const line of lines) {
@@ -234,7 +362,5 @@ export async function fetchPlaylistEntries(url: string): Promise<YtPlaylistEntry
// 한 줄이 깨져도 나머지는 살림
}
}
resolve(parsed)
})
})
return parsed
}

20
src/shared/audience.ts Normal file
View File

@@ -0,0 +1,20 @@
// 설치기 "대상(audience)" 구분. 빌드 시 package.json 에 박히는 musicQuizAudience
// 값으로 결정한다(electron-builder extraMetadata).
// - 'public' : 일반 설치기. manifest 의 public!==false 인 pack 만 노출.
// - 'developer' : 개발자용 설치기. public===false 인 pack 만 노출.
// 이 모듈은 electron 에 의존하지 않는 순수 로직만 둔다(server 빌드에도 포함되므로).
export type Audience = 'public' | 'developer'
export function resolveAudience(raw: unknown): Audience {
return raw === 'developer' ? 'developer' : 'public'
}
/**
* 주어진 pack 의 public 플래그가 현재 audience 에게 보여야 하는지.
* public 미지정(undefined)은 공개로 간주한다(하위호환).
*/
export function isPackVisibleForAudience(isPublic: boolean | undefined, audience: Audience): boolean {
const isPublicPack = isPublic !== false
return audience === 'developer' ? !isPublicPack : isPublicPack
}

View File

@@ -73,7 +73,9 @@ export function createI18n(filePath: string): I18n {
* 1. 패키징된 Electron 앱이면 `process.resourcesPath/locales/<component>/ko-kr.json`
* 2. `<프로젝트 루트>/locales/<component>/ko-kr.json`
*/
export function loadComponentI18n(component: 'server' | 'installer' | 'installer-rp'): I18n {
export function loadComponentI18n(
component: 'server' | 'installer' | 'installer-rp' | 'installer-pf' | 'installer-uninstall'
): I18n {
// 컴파일된 dist/shared/i18n.js 기준으로 프로젝트 루트는 2단계 위.
const projectRoot = path.resolve(__dirname, '..', '..')

118
src/shared/jdkVersions.ts Normal file
View File

@@ -0,0 +1,118 @@
import https from 'node:https'
// Adoptium(Temurin) API 로부터 실제 배포되는 JDK 버전을 가져온다. 설치기가 이 벤더를
// 쓰므로 사이트의 "권장 JDK" 목록도 같은 소스에서 채운다(하드코딩 금지). 네트워크
// 실패 시에는 정적 폴백을 돌려줘 편집기가 항상 동작하도록 한다.
const AVAILABLE_URL = 'https://api.adoptium.net/v3/info/available_releases'
const CACHE_TTL_MS = 6 * 60 * 60 * 1000 // 6시간
const FALLBACK_MAJORS = [8, 11, 17, 21, 25]
const FALLBACK_LTS = [8, 11, 17, 21, 25]
export interface JdkAvailability {
/** 배포되는 모든 메이저(예: 8,11,17,21,25,26). 내림차순. */
available: number[]
/** LTS 메이저만(예: 8,11,17,21,25). 내림차순. */
lts: number[]
mostRecentLts: number
mostRecentFeature: number
}
export interface JdkReleaseNames {
major: number
/** 정식(GA) 릴리스 이름들(예: jdk-25.0.3+9). */
ga: string[]
/** 개발 스냅샷(EA) 릴리스 이름들(예: jdk-25.0.4+6-ea-beta). */
ea: string[]
}
let availCache: { data: JdkAvailability; at: number } | null = null
const releaseNamesCache = new Map<number, { data: JdkReleaseNames; at: number }>()
function fetchJson<T>(url: string): Promise<T> {
return new Promise((resolve, reject) => {
const request = https.get(url, { timeout: 8000, headers: { accept: 'application/json' } }, (response) => {
const code = response.statusCode ?? 0
if (code !== 200) {
response.resume()
reject(new Error(`Adoptium HTTP ${code}`))
return
}
const chunks: Buffer[] = []
response.on('data', (c: Buffer) => chunks.push(c))
response.on('end', () => {
try {
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')) as T)
} catch (error) {
reject(error as Error)
}
})
})
request.on('error', reject)
request.on('timeout', () => request.destroy(new Error('Adoptium timeout')))
})
}
const sortDesc = (nums: number[]): number[] => [...new Set(nums)].sort((a, b) => b - a)
export async function fetchJdkAvailability(): Promise<JdkAvailability> {
if (availCache && Date.now() - availCache.at < CACHE_TTL_MS) return availCache.data
try {
const raw = await fetchJson<{
available_releases?: number[]
available_lts_releases?: number[]
most_recent_lts?: number
most_recent_feature_release?: number
}>(AVAILABLE_URL)
const available = sortDesc(
(Array.isArray(raw.available_releases) ? raw.available_releases : FALLBACK_MAJORS).filter((n) => Number.isInteger(n))
)
const lts = sortDesc(
(Array.isArray(raw.available_lts_releases) ? raw.available_lts_releases : FALLBACK_LTS).filter((n) => Number.isInteger(n))
)
const data: JdkAvailability = {
available,
lts,
mostRecentLts: Number(raw.most_recent_lts) || (lts[0] ?? 21),
mostRecentFeature: Number(raw.most_recent_feature_release) || (available[0] ?? 25)
}
availCache = { data, at: Date.now() }
return data
} catch {
return (
availCache?.data ?? {
available: sortDesc(FALLBACK_MAJORS),
lts: sortDesc(FALLBACK_LTS),
mostRecentLts: 25,
mostRecentFeature: 25
}
)
}
}
async function fetchReleaseNames(major: number, type: 'ga' | 'ea'): Promise<string[]> {
const url =
`https://api.adoptium.net/v3/assets/feature_releases/${major}/${type}` +
'?architecture=x64&image_type=jdk&os=windows&vendor=eclipse&page_size=10'
try {
const arr = await fetchJson<Array<{ release_name?: string }>>(url)
if (!Array.isArray(arr)) return []
const names: string[] = []
for (const r of arr) {
if (typeof r?.release_name === 'string' && !names.includes(r.release_name)) names.push(r.release_name)
}
return names
} catch {
return []
}
}
export async function fetchJdkReleaseNames(major: number): Promise<JdkReleaseNames> {
const cached = releaseNamesCache.get(major)
if (cached && Date.now() - cached.at < CACHE_TTL_MS) return cached.data
const [ga, ea] = await Promise.all([fetchReleaseNames(major, 'ga'), fetchReleaseNames(major, 'ea')])
const data: JdkReleaseNames = { major, ga, ea }
releaseNamesCache.set(major, { data, at: Date.now() })
return data
}

View File

@@ -6,7 +6,17 @@ export const projectRoot = path.resolve(__dirname, '..', '..')
export const manifestRootPath = path.join(projectRoot, 'manifest.json')
export const manifestDirPath = path.join(projectRoot, 'manifest')
export const manifestTermsDirPath = path.join(manifestDirPath, 'terms')
// 추적되는 account.json(과거 평문 노출)을 대체할, gitignore 된 운영 계정 파일.
// readAccounts 는 이 파일을 우선 사용하고, 없을 때만 account.json 을 시드로 읽는다.
//
// TODO(untrack-after-redeploy): account.json 은 아직 git 추적 상태다. 절대 지금
// 같은 커밋에서 `git rm --cached account.json` 하지 말 것 — 서버에 account.local.json
// 이 아직 없을 때 시드 소스가 사라져 로그인이 막힌다(chicken-and-egg).
// 안전한 순서: (1) 이 커밋 배포 → 서버가 account.local.json(0o600) 자동 생성 확인 →
// (2) 그 다음 후속 커밋에서 account.json 추적 해제.
// 주의: 추적 해제는 위생일 뿐, 히스토리의 평문 비밀번호는 지워지지 않는다 → 비밀번호 로테이션이 실질 조치.
export const accountFilePath = path.join(projectRoot, 'account.json')
export const accountLocalFilePath = path.join(projectRoot, 'account.local.json')
export const fileDirPath = path.join(projectRoot, 'file')
export const fileListDirPath = path.join(fileDirPath, 'list')
export const fileDatapacksDirPath = path.join(fileDirPath, 'datapacks')
@@ -29,9 +39,43 @@ export function getAppDataDir(): string {
return process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config')
}
/** %appdata%/.mc_custom — 음악퀴즈 관련 외부 도구/캐시 보관 디렉터리. */
/**
* 커스텀 게임 디렉터리의 폴더 이름. 기본은 `.mc_custom` 이지만 환경변수
* `MC_CUSTOM_DIR` 로 다른 이름을 지정할 수 있다(.env / .env.build 로 주입).
* 경로 구분자·상위경로 이스케이프(`/`, `\`, `..`)는 제거해 항상 %appdata%
* 바로 아래 단일 폴더로 강제한다.
*/
export function getMcCustomDirName(): string {
const raw = (process.env.MC_CUSTOM_DIR ?? '').trim()
if (!raw) return '.mc_custom'
const sanitized = raw.replace(/[\\/]+/g, '').replace(/\.\.+/g, '.')
return sanitized || '.mc_custom'
}
/** %appdata%/<MC_CUSTOM_DIR|.mc_custom> — 음악퀴즈 관련 게임 폴더/외부 도구/캐시 보관 디렉터리. */
export function getMcCustomDir(): string {
return path.join(getAppDataDir(), '.mc_custom')
return path.join(getAppDataDir(), getMcCustomDirName())
}
/**
* 사전/문자열 구조 안의 리터럴 `.mc_custom` 을 실제 폴더 이름으로 치환한 깊은
* 복사본을 돌려준다. 기본값(`.mc_custom`)이면 원본을 그대로 반환한다. 렌더러로
* 넘기는 i18n 사전에 적용해 UI 안내 문구가 실제 폴더 이름과 어긋나지 않게 한다.
*/
export function withCustomDirName<T>(value: T): T {
const name = getMcCustomDirName()
if (name === '.mc_custom') return value
const replace = (v: unknown): unknown => {
if (typeof v === 'string') return v.split('.mc_custom').join(name)
if (Array.isArray(v)) return v.map(replace)
if (v && typeof v === 'object') {
const out: Record<string, unknown> = {}
for (const [k, val] of Object.entries(v as Record<string, unknown>)) out[k] = replace(val)
return out
}
return v
}
return replace(value) as T
}
/**

View File

@@ -3,7 +3,7 @@ import fsp from 'node:fs/promises'
import path from 'node:path'
import {
manifestRootPath, manifestDirPath, manifestTermsDirPath,
accountFilePath, fileListDirPath
accountFilePath, accountLocalFilePath, fileListDirPath
} from './paths.js'
import type {
Manifest, ManifestEntry, PackDefinition, AccountEntry, LoaderType,
@@ -18,8 +18,15 @@ export async function readManifest(): Promise<Manifest> {
return { packs: [] }
}
return {
packs: parsed.packs.filter((entry): entry is ManifestEntry =>
packs: parsed.packs
.filter((entry): entry is ManifestEntry =>
typeof entry?.name === 'string' && typeof entry?.file === 'string')
.map((entry) => ({
name: entry.name,
file: entry.file,
// public 은 명시적 boolean 만 보존. 미지정은 그대로 undefined(=공개 취급).
...(typeof entry.public === 'boolean' ? { public: entry.public } : {})
}))
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
@@ -45,6 +52,7 @@ export function defaultPackDefinition(name: string): PackDefinition {
serverMaxRam: 4096,
clientMinRam: 2048,
clientRecommendedRam: 4096,
recommendedJdk: DEFAULT_JDK_MAJOR,
mapPath: '',
serverPath: ''
}
@@ -71,6 +79,24 @@ function sanitizeFolderName(input: unknown): string {
const ALLOWED_LOADERS: LoaderType[] = ['vanilla', 'forge', 'fabric', 'neoforge']
/**
* 편집기 드롭다운의 정적 폴백 목록(LTS). 실제 목록은 Adoptium API 에서 가져오며,
* 네트워크 실패 시에만 이 값을 쓴다.
* 마인크래프트 버전대별: 8(구버전) / 11(1.17) / 17(1.18~1.20.4) / 21(1.20.5~) / 25(최신).
*/
export const SUPPORTED_JDK_MAJORS: number[] = [8, 11, 17, 21, 25]
/** recommendedJdk 미지정/이상값일 때의 기본 권장 버전. */
export const DEFAULT_JDK_MAJOR = 25
/**
* 입력값을 JDK 메이저로 보정. 특정 목록에 얽매이지 않고 실제 배포되는 자바 메이저
* 범위(8~99)면 허용하고, 벗어나면 기본값. (목록은 Adoptium 에서 동적으로 온다.)
*/
export function normalizeRecommendedJdk(input: unknown): number {
const n = Math.floor(Number(input))
return Number.isFinite(n) && n >= 8 && n <= 99 ? n : DEFAULT_JDK_MAJOR
}
export function normalizePackDefinition(input: Partial<PackDefinition> & Record<string, unknown>): PackDefinition {
const fallback = defaultPackDefinition(typeof input.name === 'string' ? input.name : 'new')
const platform = (input.platform ?? {}) as Partial<PackDefinition['platform']>
@@ -105,6 +131,7 @@ export function normalizePackDefinition(input: Partial<PackDefinition> & Record<
serverMaxRam: clampNumber(input.serverMaxRam, fallback.serverMaxRam),
clientMinRam: clampNumber(input.clientMinRam, fallback.clientMinRam),
clientRecommendedRam: clampNumber(input.clientRecommendedRam, fallback.clientRecommendedRam),
recommendedJdk: normalizeRecommendedJdk(input.recommendedJdk),
mapPath: sanitizeZipFileName(input.mapPath),
serverPath: sanitizeZipFileName(input.serverPath)
}
@@ -178,6 +205,14 @@ export async function deletePackKeys(keys: string[]): Promise<void> {
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
}
// pack 이 삭제되면 약관 폴더도 함께 정리한다. 동일 packKey 로 재생성될 때
// 옛 약관이 부활하는 것을 막기 위함.
const termsDir = path.join(manifestTermsDirPath, key)
try {
await fsp.rm(termsDir, { recursive: true, force: true })
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
}
await syncManifestWith(key, '', 'remove')
}
}
@@ -198,6 +233,31 @@ export async function renamePack(oldKey: string, newKey: string, pack: PackDefin
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
}
// 음악·사진 목록 JSON(file/list/<key>.json)도 함께 이름을 바꾼다. 이걸 빼먹으면
// manifest 정의는 새 키로 옮겨졌는데 정작 목록 데이터는 옛 키 파일에 남아,
// 새 packKey 로는 빈 목록만 보이고 인스톨러도 곡/사진을 받지 못한다.
const oldListFile = path.join(fileListDirPath, `${oldKey}.json`)
const newListFile = path.join(fileListDirPath, `${safeNew}.json`)
try {
await fsp.mkdir(fileListDirPath, { recursive: true })
await fsp.rename(oldListFile, newListFile)
} catch (error) {
// 옛 목록 파일이 없으면(한 번도 저장 안 한 새 pack) 그냥 둔다.
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
}
// 약관 폴더도 함께 이름을 바꾼다 (있는 경우만). pack 이름이 바뀌었는데 약관이
// 옛 폴더에 남아 있으면 인스톨러가 새 packKey 로 약관을 받지 못한다.
const oldTermsDir = path.join(manifestTermsDirPath, oldKey)
const newTermsDir = path.join(manifestTermsDirPath, safeNew)
try {
await fsp.rename(oldTermsDir, newTermsDir)
} catch (error) {
const code = (error as NodeJS.ErrnoException).code
// 옛 약관 폴더가 없으면 그대로 둔다. 새 폴더가 이미 있어 충돌하면 그것도 그냥 둔다
// (renamePack 단계에서 사용자에게 보낼 마땅한 UX 가 없고, 다음 약관 접근 때
// 새 폴더 내용이 정상적으로 사용된다).
if (code !== 'ENOENT' && code !== 'ENOTEMPTY' && code !== 'EEXIST') throw error
}
await syncManifestWith(oldKey, '', 'remove')
}
await syncManifestWith(safeNew, pack.name, 'upsert')
@@ -212,15 +272,32 @@ type ManifestSyncAction = 'add' | 'remove' | 'upsert'
async function syncManifestWith(key: string, name: string, action: ManifestSyncAction): Promise<void> {
const manifest = await readManifest()
const existing = manifest.packs.find((entry) => entry.file === key)
const filtered = manifest.packs.filter((entry) => entry.file !== key)
if (action === 'remove') {
await writeManifest({ packs: filtered })
return
}
filtered.push({ name: name || key, file: key })
const entry: ManifestEntry = { name: name || key, file: key }
// 기존 public 값은 이름 변경/수정(upsert) 시에도 보존. 신규(add)는 기본 공개(true).
entry.public = existing && typeof existing.public === 'boolean' ? existing.public : true
filtered.push(entry)
await writeManifest({ packs: filtered })
}
/** manifest 엔트리의 public(공개 여부) 플래그를 설정한다. */
export async function setPackPublic(key: string, isPublic: boolean): Promise<void> {
const manifest = await readManifest()
let changed = false
for (const entry of manifest.packs) {
if (entry.file === key) {
entry.public = isPublic
changed = true
}
}
if (changed) await writeManifest(manifest)
}
function defaultPackList(): PackList {
return { musicPlaylistUrl: '', imagePlaylistUrl: '', music: [], images: [] }
}
@@ -266,7 +343,8 @@ export function normalizePackList(input: unknown): PackList {
title: sanitizeStr(entry.title),
artist: sanitizeStr(entry.artist),
durationSec: sanitizeNumber(entry.durationSec),
aliases: sanitizeAliases(entry.aliases)
aliases: sanitizeAliases(entry.aliases),
description: sanitizeStr(entry.description)
}))
.filter((entry) => entry.url.length > 0),
images: images
@@ -296,23 +374,32 @@ export async function savePackList(packKey: string, list: PackList): Promise<voi
// ─── Terms (Markdown 약관) ─────────────────────────────────────────────
// 사이트와 인스톨러가 약관을 보여주기 위해 사용하는 markdown 파일.
// - 5개 builtin 종류는 인스톨러가 직접 참조하므로 삭제할 수 없다.
// - 그 외 임의 kind 는 사이트에서 추가/삭제 가능. 라벨은 _meta.json 에 저장.
// - 음악퀴즈(pack)별로 독립 폴더(`manifest/terms/<packKey>/`) 에 저장한다.
// - 각 약관(.md) `_meta.json` 의 `terms.<kind>` 엔트리로 라벨/표시 대상이 관리된다.
// 엔트리: { label, showInInstaller, showInInstallerRp }
// - 모든 약관은 추가/삭제 가능. builtin 같은 보호 개념은 더 이상 없음 (v0.3.4~).
// 인스톨러는 하드코딩 5종 대신 `index.json` 에서 자기 인스톨러용 약관 목록을 받는다.
// - 첫 접근 시 5개 기본 약관(map/mod/installer + resourcepack/installer-rp) 을 시드.
// - 파일명 규칙: `[a-z0-9][a-z0-9-]{0,31}\.md` (소문자/숫자/하이픈, 32자 이내).
// - 레거시(전역) `manifest/terms/*.md` 파일이 남아 있으면 packKey 폴더 첫 접근 시 자동 시드.
export type TermKind = string
/** 인스톨러가 하드코딩으로 참조하는 builtin kind. 삭제 금지. */
export const BUILTIN_TERM_KINDS = ['map', 'resourcepack', 'mod', 'installer', 'installer-rp'] as const
export type BuiltinTermKind = typeof BUILTIN_TERM_KINDS[number]
/** builtin 라벨. 사용자 정의 kind 는 _meta.json 에 저장된 라벨을 쓴다. */
const BUILTIN_TERM_LABELS: Record<BuiltinTermKind, string> = {
'map': '맵 약관',
'resourcepack': '리소스팩 약관',
'mod': '모드 약관',
'installer': '설치기 약관',
'installer-rp': '리소스팩 설치기 약관'
}
/**
* 처음 pack 폴더를 만들 때 시드되는 기본 약관 5종 + 기본 표시 대상.
* 사용자는 이후 자유롭게 삭제하거나 표시 대상을 바꿀 수 있다.
*/
const DEFAULT_TERM_SEEDS: Array<{
kind: string
label: string
showInInstaller: boolean
showInInstallerRp: boolean
}> = [
{ kind: 'map', label: '맵 약관', showInInstaller: true, showInInstallerRp: false },
{ kind: 'mod', label: '모드 약관', showInInstaller: true, showInInstallerRp: false },
{ kind: 'installer', label: '설치기 약관', showInInstaller: true, showInInstallerRp: false },
{ kind: 'resourcepack', label: '리소스팩 약관', showInInstaller: false, showInInstallerRp: true },
{ kind: 'installer-rp', label: '리소스팩 설치기 약관', showInInstaller: false, showInInstallerRp: true }
]
const TERM_KIND_RE = /^[a-z0-9][a-z0-9-]{0,31}$/
@@ -320,38 +407,189 @@ export function isTermKind(value: unknown): value is TermKind {
return typeof value === 'string' && TERM_KIND_RE.test(value)
}
export function isBuiltinTermKind(value: string): value is BuiltinTermKind {
return (BUILTIN_TERM_KINDS as readonly string[]).includes(value)
export interface TermEntry {
label: string
showInInstaller: boolean
showInInstallerRp: boolean
}
interface TermsMeta {
/** 사용자 정의 kind 라벨. builtin 은 들어가지 않는다. */
customLabels: Record<string, string>
terms: Record<string, TermEntry>
}
const TERMS_META_FILE = '_meta.json'
async function loadTermsMeta(): Promise<TermsMeta> {
function termsDirForPack(packKey: string): string {
return path.join(manifestTermsDirPath, packKey)
}
function isValidPackKey(packKey: string): boolean {
return typeof packKey === 'string'
&& packKey.length > 0
&& /^[a-zA-Z0-9_\-]+$/.test(packKey)
}
/**
* 해당 pack 폴더가 없으면 만든다. 이전 버전(v0.3.1) 의 전역 `manifest/terms/*.md`
* 파일이 남아 있는 경우 첫 접근 시 그 내용을 그대로 새 폴더에 복사해 시드한다.
* 시드는 한 번만 발생: 폴더가 이미 있으면 아무것도 안 한다.
*
* 공개 라우트(`/manifest/terms/<packKey>/<file>`) 에서도 호출되므로 export 한다.
* 라우트 측은 packKey 가 실제 존재하는 pack 인지 확인한 다음에 호출해야 한다
* (그렇지 않으면 임의 키로 빈 폴더가 생성될 수 있다).
*/
export async function ensurePackTermsDir(packKey: string): Promise<string> {
const dir = termsDirForPack(packKey)
let isNew = false
try {
const raw = await fsp.readFile(path.join(manifestTermsDirPath, TERMS_META_FILE), 'utf8')
const parsed = JSON.parse(raw)
const customLabels: Record<string, string> = {}
if (parsed && typeof parsed === 'object' && parsed.customLabels && typeof parsed.customLabels === 'object') {
for (const [k, v] of Object.entries(parsed.customLabels as Record<string, unknown>)) {
if (typeof v === 'string' && TERM_KIND_RE.test(k)) customLabels[k] = v
}
}
return { customLabels }
await fsp.access(dir)
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { customLabels: {} }
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
isNew = true
await fsp.mkdir(dir, { recursive: true })
// 레거시(전역) .md 파일이 남아 있으면 그대로 복사 (.md 만, _meta.json 은 새 스키마로 새로 씀).
try {
const legacyEntries = await fsp.readdir(manifestTermsDirPath, { withFileTypes: true })
for (const ent of legacyEntries) {
if (!ent.isFile()) continue
const name = ent.name
if (!name.toLowerCase().endsWith('.md')) continue
const kind = name.slice(0, -3)
if (!TERM_KIND_RE.test(kind)) continue
try {
await fsp.copyFile(
path.join(manifestTermsDirPath, name),
path.join(dir, name)
)
} catch { /* ignore */ }
}
} catch (error2) {
if ((error2 as NodeJS.ErrnoException).code !== 'ENOENT') throw error2
}
}
// 폴더가 새로 만들어졌든 기존이든, _meta.json 이 없거나 구 스키마면 5종 기본 + .md 매칭으로 보완.
await ensureMetaInitialized(dir, isNew)
return dir
}
/**
* `_meta.json` 이 없으면 5종 기본 + 디스크 .md 매칭으로 새로 작성한다.
* 구 스키마(`customLabels`) 가 있으면 새 스키마(`terms`) 로 변환한다.
* 이미 새 스키마면 그대로 둔다 (사용자가 끈 visibility 가 다시 켜지지 않도록).
*/
async function ensureMetaInitialized(dir: string, dirWasJustCreated: boolean): Promise<void> {
const metaPath = path.join(dir, TERMS_META_FILE)
let parsed: unknown = null
try {
const raw = await fsp.readFile(metaPath, 'utf8')
parsed = JSON.parse(raw)
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
}
// 이미 새 스키마면 종료. 빠진 default kind 가 디스크에 있다면 그것만 보충.
if (parsed && typeof parsed === 'object' && (parsed as Record<string, unknown>).terms) {
const meta = parsed as { terms: Record<string, unknown> }
let changed = false
for (const seed of DEFAULT_TERM_SEEDS) {
if (meta.terms[seed.kind]) continue
// .md 가 실제로 디스크에 있을 때만 보충 (없는 약관까지 자동 부활시키지 않음).
try {
await fsp.access(path.join(dir, `${seed.kind}.md`))
} catch {
continue
}
meta.terms[seed.kind] = {
label: seed.label,
showInInstaller: seed.showInInstaller,
showInInstallerRp: seed.showInInstallerRp
}
changed = true
}
if (changed) {
await fsp.writeFile(metaPath, `${JSON.stringify(meta, null, 2)}\n`, 'utf8')
}
return
}
// 구 스키마 customLabels 만 있던 경우 → 새 스키마로 변환.
const oldCustomLabels: Record<string, string> = {}
if (parsed && typeof parsed === 'object' && (parsed as Record<string, unknown>).customLabels
&& typeof (parsed as Record<string, unknown>).customLabels === 'object') {
for (const [k, v] of Object.entries((parsed as { customLabels: Record<string, unknown> }).customLabels)) {
if (typeof v === 'string' && TERM_KIND_RE.test(k)) oldCustomLabels[k] = v
}
}
const terms: Record<string, TermEntry> = {}
// 5종 기본: 디스크에 .md 가 있을 때만 추가 (없는 건 사용자가 의도적으로 지운 것일 수 있음).
// 다만 폴더가 막 생성된 경우는 5종을 무조건 시드 (legacy 시드가 비어 있어도).
for (const seed of DEFAULT_TERM_SEEDS) {
if (!dirWasJustCreated) {
try {
await fsp.access(path.join(dir, `${seed.kind}.md`))
} catch {
continue
}
} else {
// 폴더 새로 생성 케이스: .md 가 없으면 빈 파일 만들어 줌.
const filePath = path.join(dir, `${seed.kind}.md`)
try {
await fsp.access(filePath)
} catch {
await fsp.writeFile(filePath, `# ${seed.label}\n\n`, 'utf8')
}
}
terms[seed.kind] = {
label: seed.label,
showInInstaller: seed.showInInstaller,
showInInstallerRp: seed.showInInstallerRp
}
}
// 구 스키마의 사용자 정의 약관은 양쪽 인스톨러에 보이도록 기본값으로.
for (const [k, label] of Object.entries(oldCustomLabels)) {
if (terms[k]) continue
try {
await fsp.access(path.join(dir, `${k}.md`))
} catch {
continue
}
terms[k] = { label, showInInstaller: true, showInInstallerRp: true }
}
await fsp.writeFile(metaPath, `${JSON.stringify({ terms }, null, 2)}\n`, 'utf8')
}
async function loadTermsMeta(packKey: string): Promise<TermsMeta> {
const dir = await ensurePackTermsDir(packKey)
try {
const raw = await fsp.readFile(path.join(dir, TERMS_META_FILE), 'utf8')
const parsed = JSON.parse(raw) as unknown
const result: TermsMeta = { terms: {} }
if (parsed && typeof parsed === 'object' && (parsed as Record<string, unknown>).terms
&& typeof (parsed as Record<string, unknown>).terms === 'object') {
for (const [k, v] of Object.entries((parsed as { terms: Record<string, unknown> }).terms)) {
if (!TERM_KIND_RE.test(k)) continue
if (!v || typeof v !== 'object') continue
const entry = v as Record<string, unknown>
const label = typeof entry.label === 'string' ? entry.label : k
result.terms[k] = {
label,
showInInstaller: entry.showInInstaller === true,
showInInstallerRp: entry.showInInstallerRp === true
}
}
}
return result
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { terms: {} }
throw error
}
}
async function saveTermsMeta(meta: TermsMeta): Promise<void> {
await fsp.mkdir(manifestTermsDirPath, { recursive: true })
async function saveTermsMeta(packKey: string, meta: TermsMeta): Promise<void> {
const dir = await ensurePackTermsDir(packKey)
await fsp.writeFile(
path.join(manifestTermsDirPath, TERMS_META_FILE),
path.join(dir, TERMS_META_FILE),
`${JSON.stringify(meta, null, 2)}\n`,
'utf8'
)
@@ -360,53 +598,89 @@ async function saveTermsMeta(meta: TermsMeta): Promise<void> {
export interface TermItem {
kind: string
label: string
builtin: boolean
showInInstaller: boolean
showInInstallerRp: boolean
}
/**
* 디스크의 .md 파일 + _meta.json 을 합쳐 약관 목록을 만든다.
* - builtin 5종은 파일 존재 여부와 무관하게 항상 포함된다 (인스톨러가 fetch 하므로).
* - 디스크에 있고 _meta.json 에 라벨이 있는 사용자 정의 kind 도 포함.
* - builtin → 사용자 정의 순서, builtin 내부는 BUILTIN_TERM_KINDS 정의 순서를 유지.
* 디스크의 .md 파일과 매칭되면서 `_meta.json` 의 `terms` 에 등록된 약관 목록을 반환.
* 정렬: 5종 기본(DEFAULT_TERM_SEEDS 순서) → 그 외 사용자 정의 (kind 사전순).
*/
export async function listTermsWithLabels(): Promise<TermItem[]> {
const meta = await loadTermsMeta()
const items: TermItem[] = []
for (const kind of BUILTIN_TERM_KINDS) {
items.push({ kind, label: BUILTIN_TERM_LABELS[kind], builtin: true })
}
// 디스크에 실제로 존재하는 사용자 정의 .md 파일만 노출.
export async function listTermsWithLabels(packKey: string): Promise<TermItem[]> {
const dir = await ensurePackTermsDir(packKey)
const meta = await loadTermsMeta(packKey)
let onDisk: string[] = []
try {
onDisk = await fsp.readdir(manifestTermsDirPath)
onDisk = await fsp.readdir(dir)
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
}
const customKinds = new Set<string>()
const mdKinds = new Set<string>()
for (const fname of onDisk) {
if (!fname.toLowerCase().endsWith('.md')) continue
const kind = fname.slice(0, -3)
if (!TERM_KIND_RE.test(kind)) continue
if (isBuiltinTermKind(kind)) continue
customKinds.add(kind)
mdKinds.add(kind)
}
// _meta.json 에 라벨이 등록된 것만 노출 (라벨 없는 orphan .md 는 무시).
for (const kind of Object.keys(meta.customLabels).sort((a, b) => a.localeCompare(b, 'ko'))) {
if (!customKinds.has(kind)) continue
items.push({ kind, label: meta.customLabels[kind], builtin: false })
const items: TermItem[] = []
const seen = new Set<string>()
// 1) 기본 시드 순서 우선.
for (const seed of DEFAULT_TERM_SEEDS) {
const entry = meta.terms[seed.kind]
if (!entry) continue
if (!mdKinds.has(seed.kind)) continue
items.push({
kind: seed.kind,
label: entry.label,
showInInstaller: entry.showInInstaller,
showInInstallerRp: entry.showInInstallerRp
})
seen.add(seed.kind)
}
// 2) 그 외 사용자 정의: 사전순.
const rest = Object.keys(meta.terms).filter((k) => !seen.has(k))
rest.sort((a, b) => a.localeCompare(b, 'ko'))
for (const kind of rest) {
if (!mdKinds.has(kind)) continue
const entry = meta.terms[kind]
items.push({
kind,
label: entry.label,
showInInstaller: entry.showInInstaller,
showInInstallerRp: entry.showInInstallerRp
})
}
return items
}
export async function getTermLabel(kind: string): Promise<string> {
if (isBuiltinTermKind(kind)) return BUILTIN_TERM_LABELS[kind]
const meta = await loadTermsMeta()
return meta.customLabels[kind] ?? kind
export async function getTermLabel(packKey: string, kind: string): Promise<string> {
const meta = await loadTermsMeta(packKey)
return meta.terms[kind]?.label ?? kind
}
export async function loadTerm(kind: TermKind): Promise<string> {
export async function getTermEntry(packKey: string, kind: string): Promise<TermEntry | null> {
const meta = await loadTermsMeta(packKey)
return meta.terms[kind] ?? null
}
export async function setTermVisibility(
packKey: string,
kind: string,
visibility: { showInInstaller: boolean; showInInstallerRp: boolean }
): Promise<void> {
if (!isTermKind(kind)) throw new Error('invalid term kind')
const meta = await loadTermsMeta(packKey)
const entry = meta.terms[kind]
if (!entry) throw new Error('term not found')
entry.showInInstaller = !!visibility.showInInstaller
entry.showInInstallerRp = !!visibility.showInInstallerRp
await saveTermsMeta(packKey, meta)
}
export async function loadTerm(packKey: string, kind: TermKind): Promise<string> {
if (!isTermKind(kind)) return ''
const filePath = path.join(manifestTermsDirPath, `${kind}.md`)
const dir = await ensurePackTermsDir(packKey)
const filePath = path.join(dir, `${kind}.md`)
try {
return await fsp.readFile(filePath, 'utf8')
} catch (error) {
@@ -415,24 +689,27 @@ export async function loadTerm(kind: TermKind): Promise<string> {
}
}
export async function saveTerm(kind: TermKind, markdown: string): Promise<void> {
export async function saveTerm(packKey: string, kind: TermKind, markdown: string): Promise<void> {
if (!isTermKind(kind)) throw new Error('invalid term kind')
await fsp.mkdir(manifestTermsDirPath, { recursive: true })
const filePath = path.join(manifestTermsDirPath, `${kind}.md`)
const dir = await ensurePackTermsDir(packKey)
const filePath = path.join(dir, `${kind}.md`)
const normalized = (markdown ?? '').replace(/\r\n/g, '\n')
await fsp.writeFile(filePath, normalized.endsWith('\n') ? normalized : `${normalized}\n`, 'utf8')
}
/** 새로운 사용자 정의 약관 추가. kind 충돌/builtin 충돌은 예외. 빈 .md 파일을 만든다. */
export async function createTerm(kind: string, label: string): Promise<void> {
/**
* 새 약관 추가. kind 충돌은 예외. 빈 `.md` 파일을 만든다.
* v0.3.4~: builtin 보호 개념이 없어 임의 kind 를 추가/삭제할 수 있다. 다만
* `meta.terms` 에 이미 있는 kind 와 충돌하면 거부. 표시 대상 기본값은 양쪽 인스톨러 모두.
*/
export async function createTerm(packKey: string, kind: string, label: string): Promise<void> {
if (!isTermKind(kind)) throw new Error('invalid term kind')
if (isBuiltinTermKind(kind)) throw new Error('builtin term kind cannot be created')
const cleanLabel = label.trim()
if (cleanLabel.length === 0 || cleanLabel.length > 50) throw new Error('invalid label length')
const meta = await loadTermsMeta()
if (meta.customLabels[kind]) throw new Error('term kind already exists')
await fsp.mkdir(manifestTermsDirPath, { recursive: true })
const filePath = path.join(manifestTermsDirPath, `${kind}.md`)
const meta = await loadTermsMeta(packKey)
if (meta.terms[kind]) throw new Error('term kind already exists')
const dir = await ensurePackTermsDir(packKey)
const filePath = path.join(dir, `${kind}.md`)
// 파일 충돌도 막는다 (수동 생성된 .md 가 있을 수 있음).
try {
await fsp.access(filePath)
@@ -441,44 +718,104 @@ export async function createTerm(kind: string, label: string): Promise<void> {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
}
await fsp.writeFile(filePath, `# ${cleanLabel}\n\n`, 'utf8')
meta.customLabels[kind] = cleanLabel
await saveTermsMeta(meta)
// 기본 시드 kind 면 그 시드의 visibility 기본을 따르고, 그 외는 양쪽 인스톨러 모두 표시.
const seed = DEFAULT_TERM_SEEDS.find((s) => s.kind === kind)
meta.terms[kind] = {
label: cleanLabel,
showInInstaller: seed ? seed.showInInstaller : true,
showInInstallerRp: seed ? seed.showInInstallerRp : true
}
await saveTermsMeta(packKey, meta)
}
/** 사용자 정의 약관 삭제. builtin 은 거부. */
export async function deleteTerm(kind: string): Promise<void> {
/** 약관 삭제. v0.3.4~: builtin 보호 없음 — 모든 kind 삭제 가능. */
export async function deleteTerm(packKey: string, kind: string): Promise<void> {
if (!isTermKind(kind)) throw new Error('invalid term kind')
if (isBuiltinTermKind(kind)) throw new Error('builtin term kind cannot be deleted')
const filePath = path.join(manifestTermsDirPath, `${kind}.md`)
const dir = await ensurePackTermsDir(packKey)
const filePath = path.join(dir, `${kind}.md`)
try {
await fsp.unlink(filePath)
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
}
const meta = await loadTermsMeta()
if (meta.customLabels[kind]) {
delete meta.customLabels[kind]
await saveTermsMeta(meta)
const meta = await loadTermsMeta(packKey)
if (meta.terms[kind]) {
delete meta.terms[kind]
await saveTermsMeta(packKey, meta)
}
}
/** 공개 라우트(`/manifest/terms/<file>`)에서 호출. _meta.json 같은 시스템 파일을 차단하기 위함. */
export function isPublicTermsFile(fileName: string): boolean {
// .md 만 허용, 이름 규칙 일치, builtin 또는 정상 kind 패턴.
/**
* 다른 음악퀴즈의 약관 전체를 현재 pack 으로 복사한다 (불러오기).
* - source 의 모든 .md 를 target 에 덮어쓴다.
* - target 에만 있던 약관 엔트리는 그대로 둔다 (source 에는 없으니 안 건드림).
* - 동일한 kind 가 source 에도 있다면 source 의 라벨/표시 대상으로 덮어씀.
*/
export async function importTerms(targetPackKey: string, sourcePackKey: string): Promise<void> {
if (!isValidPackKey(targetPackKey) || !isValidPackKey(sourcePackKey)) {
throw new Error('invalid pack key')
}
if (targetPackKey === sourcePackKey) throw new Error('source and target are identical')
const sourceDir = await ensurePackTermsDir(sourcePackKey)
const targetDir = await ensurePackTermsDir(targetPackKey)
const sourceMeta = await loadTermsMeta(sourcePackKey)
const targetMeta = await loadTermsMeta(targetPackKey)
// source 의 .md 파일을 모두 target 으로 복사.
let entries: string[] = []
try {
entries = await fsp.readdir(sourceDir)
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
}
for (const name of entries) {
if (!name.toLowerCase().endsWith('.md')) continue
const kind = name.slice(0, -3)
if (!TERM_KIND_RE.test(kind)) continue
await fsp.copyFile(path.join(sourceDir, name), path.join(targetDir, name))
}
// 약관 엔트리도 source 기준으로 머지 (덮어쓰기).
const mergedTerms: Record<string, TermEntry> = { ...targetMeta.terms }
for (const [k, v] of Object.entries(sourceMeta.terms)) {
mergedTerms[k] = { ...v }
}
await saveTermsMeta(targetPackKey, { terms: mergedTerms })
}
/**
* 공개 라우트(`/manifest/terms/<packKey>/<file>`)에서 호출.
* - packKey 가 영문/숫자/언더스코어/하이픈만 사용했는지 검사.
* - 파일명이 .md 로 끝나고 정상 kind 패턴인지 검사.
* - _meta.json 같은 시스템 파일은 차단.
*/
export function isPublicTermsFile(packKey: string, fileName: string): boolean {
if (!isValidPackKey(packKey)) return false
if (!fileName.toLowerCase().endsWith('.md')) return false
const kind = fileName.slice(0, -3)
return TERM_KIND_RE.test(kind)
}
export async function readAccounts(): Promise<AccountEntry[]> {
// gitignore 된 account.local.json 우선. 없으면(ENOENT) 추적되는 account.json 을 시드로.
for (const filePath of [accountLocalFilePath, accountFilePath]) {
try {
const raw = await fsp.readFile(accountFilePath, 'utf8')
const raw = await fsp.readFile(filePath, 'utf8')
const parsed = JSON.parse(raw)
if (!Array.isArray(parsed)) return []
return parsed.filter((entry): entry is AccountEntry =>
typeof entry?.id === 'string' && typeof entry?.password === 'string')
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []
if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue
throw error
}
}
return []
}
// 운영 계정 저장은 항상 gitignore 된 account.local.json 에만 한다(추적 파일 오염 방지).
// 비밀번호(해시) 파일이므로 소유자만 읽기/쓰기(0o600).
export async function writeAccounts(accounts: AccountEntry[]): Promise<void> {
await fsp.writeFile(accountLocalFilePath, `${JSON.stringify(accounts, null, 2)}\n`, { mode: 0o600 })
}

View File

@@ -28,6 +28,11 @@ export interface PackDefinition {
serverMaxRam: number
clientMinRam: number
clientRecommendedRam: number
/**
* 서버 실행에 권장하는 JDK 메이저 버전(예: 25). 설치기가 이 버전을 우선 탐색/설치한다.
* 사이트에서 선택하며, 허용 목록(SUPPORTED_JDK_MAJORS) 밖의 값은 기본값으로 보정된다.
*/
recommendedJdk: number
/** /file/maps/<mapPath> 에서 받아 .mc_custom/saves 로 풀 zip 파일 이름. */
mapPath: string
/** /file/servers/<serverPath> 에서 받아 서버 설치 경로로 풀 zip 파일 이름. */
@@ -37,6 +42,11 @@ export interface PackDefinition {
export interface ManifestEntry {
name: string
file: string
/**
* 공개 여부. true(또는 미지정)면 일반 설치기(간편/리소스팩)에 노출,
* false 면 개발자용 설치기에만 노출된다. 하위호환: 값이 없으면 공개로 간주.
*/
public?: boolean
}
export interface Manifest {
@@ -57,6 +67,8 @@ export interface MusicListEntry {
durationSec: number
/** 정답으로 인정할 별칭 목록. 빈 배열이면 정답은 title 뿐. */
aliases: string[]
/** 곡 설명 / 트리비아 메모. 정답 채점이나 데이터팩 생성에는 사용되지 않는다. */
description: string
}
export interface ImageListEntry {

View File

@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"include": ["src/installer-pf/**/*.ts", "src/shared/**/*.ts"]
}

View File

@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"include": ["src/installer-uninstall/**/*.ts", "src/shared/**/*.ts"]
}

View File

@@ -30,6 +30,11 @@
</label>
</div>
<label style="display:flex;align-items:center;gap:10px;margin:8px 0;">
<input type="checkbox" name="isPublic" <%= (typeof isPublic === 'undefined' || isPublic) ? 'checked' : '' %> style="width:auto;" />
<span>공개 (체크 시 일반 설치기에 표시 / 해제 시 개발자용 설치기에만 표시)</span>
</label>
<div class="gridTwo">
<label>
<span><%= t('editor.mcVersion') %></span>
@@ -75,6 +80,17 @@
<span><%= t('editor.clientRecommendedRam') %></span>
<input type="number" name="clientRecommendedRam" value="<%= pack.clientRecommendedRam %>" min="512" required />
</label>
<label>
<span><%= t('editor.recommendedJdk') %></span>
<select name="recommendedJdk" id="recommendedJdk" data-current="<%= pack.recommendedJdk %>" required>
<option value="<%= pack.recommendedJdk %>" selected>Java <%= pack.recommendedJdk %></option>
</select>
<label class="muted" style="font-weight:normal;display:flex;align-items:center;gap:6px;margin-top:4px;">
<input type="checkbox" id="jdkShowDetails" style="width:auto;" /> <%= t('editor.jdkShowDetails') %>
</label>
<div id="jdkDetails" class="muted" hidden style="margin-top:4px;font-size:12px;line-height:1.6;word-break:break-all;"></div>
<small class="muted"><%= t('editor.recommendedJdkHint') %></small>
</label>
<label>
<span><%= t('editor.mapPath') %></span>
<input name="mapPath" value="<%= pack.mapPath %>" placeholder="my-map.zip" pattern=".+\.zip" />
@@ -121,6 +137,83 @@
function formatLoaderLoadFailed(message) {
return I18N.loaderLoadFailedPrefix.replace('__M__', message)
}
var JDK = {
current: <%= pack.recommendedJdk %>,
fallback: <%- JSON.stringify(jdkOptions) %>,
detailsGa: <%- JSON.stringify(t('editor.jdkDetailsGa')) %>,
detailsEa: <%- JSON.stringify(t('editor.jdkDetailsEa')) %>,
detailsLoading: <%- JSON.stringify(t('common.loading')) %>,
detailsNone: <%- JSON.stringify(t('editor.jdkDetailsNone')) %>,
ltsSuffix: <%- JSON.stringify(t('editor.jdkLtsSuffix')) %>
}
</script>
<script>
(function () {
var sel = document.getElementById('recommendedJdk')
var details = document.getElementById('jdkDetails')
var toggle = document.getElementById('jdkShowDetails')
if (!sel || !toggle) return
var current = Number(sel.getAttribute('data-current')) || JDK.current
var avail = null // { available:[], lts:[] }
function rebuild() {
var availList, ltsList
if (avail) { availList = avail.available; ltsList = avail.lts }
else { availList = JDK.fallback.slice().sort(function (a, b) { return b - a }); ltsList = availList }
var ltsSet = {}
ltsList.forEach(function (m) { ltsSet[m] = true })
var list = toggle.checked ? availList.slice() : ltsList.slice()
if (list.indexOf(current) < 0) list = [current].concat(list)
var seen = {}, html = ''
list.forEach(function (m) {
if (seen[m]) return
seen[m] = true
var label = 'Java ' + m + (ltsSet[m] ? JDK.ltsSuffix : '')
html += '<option value="' + m + '"' + (m === current ? ' selected' : '') + '>' + label + '</option>'
})
sel.innerHTML = html
sel.value = String(current)
}
function escHtml(s) {
return String(s).replace(/[&<>"']/g, function (c) {
return c === '&' ? '&amp;' : c === '<' ? '&lt;' : c === '>' ? '&gt;' : c === '"' ? '&quot;' : '&#39;'
})
}
function detailRow(label, names) {
return '<div><strong>' + escHtml(label) + ':</strong> ' +
names.slice(0, 6).map(escHtml).join(', ') + '</div>'
}
function loadDetails(major) {
details.hidden = false
details.textContent = JDK.detailsLoading
fetch('/op/jdk-versions/' + major)
.then(function (r) { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json() })
.then(function (d) {
// release_name 은 외부 API 값이라 반드시 escape 후 삽입(관리 페이지 XSS 방지).
var html = ''
if (d.ga && d.ga.length) html += detailRow(JDK.detailsGa, d.ga)
if (d.ea && d.ea.length) html += detailRow(JDK.detailsEa, d.ea)
details.innerHTML = html || escHtml(JDK.detailsNone)
})
.catch(function () { details.textContent = JDK.detailsNone })
}
sel.addEventListener('change', function () {
current = Number(sel.value)
if (toggle.checked) loadDetails(current)
})
toggle.addEventListener('change', function () {
rebuild()
if (toggle.checked) loadDetails(current)
else { details.hidden = true; details.innerHTML = '' }
})
fetch('/op/jdk-versions')
.then(function (r) { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json() })
.then(function (d) { avail = d; rebuild() })
.catch(function () { rebuild() })
})()
</script>
<script>
(function () {

View File

@@ -124,6 +124,21 @@
</div>
</div>
<!-- Description modal (music) -->
<div class="modalOverlay" id="descModal" hidden>
<div class="modalCard">
<header class="aliasModalHeader">
<button type="button" class="ghostLink" id="desc-back"><%= t('listEditor.descBack') %></button>
<h3 id="desc-modal-title"></h3>
<span></span>
</header>
<div class="modalBody">
<p class="muted" style="margin:0;font-size:12px;"><%= t('listEditor.descHint') %></p>
<textarea id="desc-textarea" class="textInput descTextarea" placeholder="<%= t('listEditor.descPlaceholder') %>" rows="6"></textarea>
</div>
</div>
</div>
<!-- Edit modal (image) -->
<div class="modalOverlay" id="editImageModal" hidden>
<div class="modalCard">

154
views/op/terms-pack.ejs Normal file
View File

@@ -0,0 +1,154 @@
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title><%= t('terms.packBrowserTitle', { name: pack.name }) %></title>
<link rel="stylesheet" href="/static/styles.css" />
<style>
/* 약관 목록 — 카드 한 줄(가로 풀폭) 씩 세로로 쌓이도록. */
.termsList { display: flex; flex-direction: column; gap: 10px; margin-top: 16px; }
.termsRow {
display: flex; align-items: center; justify-content: space-between;
gap: 12px;
background: var(--bg-card);
border: 1px solid var(--border, #30363d);
border-radius: 10px;
padding: 14px 18px;
}
.termsRow .termsRowMain { display: flex; flex-direction: column; min-width: 0; flex: 1; }
.termsRow .termsRowLabel { display: flex; align-items: center; gap: 8px; }
.termsRow .termsRowLabel h2 { margin: 0; font-size: 16px; }
.termsRow .termsRowSub { color: var(--text-muted); font-size: 12px; margin-top: 2px; }
.termsRow .termsRowActions { display: flex; gap: 8px; align-items: center; }
.visibilityBadges {
display: flex; gap: 6px; flex-wrap: wrap;
}
.visibilityBadge {
display: inline-flex; align-items: center; padding: 2px 8px; border-radius: 999px;
background: rgba(76, 175, 80, 0.15); color: #8ed68f;
border: 1px solid rgba(76, 175, 80, 0.35);
font-size: 11px;
}
.visibilityBadge.off {
background: rgba(255,255,255,0.05); color: var(--text-muted);
border-color: rgba(255,255,255,0.12);
}
.termsSideBySide {
display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-top: 24px;
}
@media (max-width: 900px) {
.termsSideBySide { grid-template-columns: 1fr; }
}
.termsSection {
background: var(--bg-card);
border: 1px solid var(--border, #30363d);
border-radius: 10px;
padding: 16px 18px;
}
.termsSection h2 { margin: 0 0 12px; font-size: 15px; }
.termsAddForm { display: grid; grid-template-columns: 1fr 2fr; gap: 10px; align-items: end; }
.termsAddForm .field { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
.termsAddForm label { font-size: 12px; color: var(--text-muted); }
.termsAddForm input, .termsImportForm select {
background: var(--bg-alt); color: var(--text);
border: 1px solid var(--border, #30363d); border-radius: 6px;
padding: 8px 10px; font-size: 13px;
}
.termsAddForm .hint { color: var(--text-muted); font-size: 11px; }
.termsAddForm .formActions { grid-column: 1 / -1; display: flex; justify-content: flex-end; }
.termsImportForm { display: grid; grid-template-columns: 1fr; gap: 10px; }
.termsImportForm .field { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
.termsImportForm label { font-size: 12px; color: var(--text-muted); }
.termsImportForm .formActions { display: flex; justify-content: flex-end; }
.termsImportForm .hint { color: var(--text-muted); font-size: 11px; }
</style>
</head>
<body class="siteBody">
<%- include('../partials/navbar', { userId }) %>
<main class="pageWrap">
<section class="dashboardHeader">
<div>
<a class="ghostLink" href="/op/agreement"><%= t('common.back') %></a>
<h1 style="margin-top:20px;"><%= t('terms.packTitle', { name: pack.name }) %></h1>
<p class="muted"><%= packKey %>.json</p>
</div>
</section>
<p class="muted"><%= t('terms.hint') %></p>
<section class="termsList">
<% items.forEach(function (item) { %>
<article class="termsRow">
<a class="termsRowMain" href="/op/agreement/<%= packKey %>/<%= item.kind %>" style="text-decoration:none; color:inherit;">
<div class="termsRowLabel">
<h2><%= item.label %></h2>
<span class="visibilityBadges">
<span class="visibilityBadge <%= item.showInInstaller ? '' : 'off' %>"><%= t('terms.visibilityInstallerShort') %></span>
<span class="visibilityBadge <%= item.showInInstallerRp ? '' : 'off' %>"><%= t('terms.visibilityInstallerRpShort') %></span>
</span>
</div>
<div class="termsRowSub"><%= item.kind %>.md</div>
</a>
<div class="termsRowActions">
<a class="secondaryButton" href="/op/agreement/<%= packKey %>/<%= item.kind %>"><%= t('terms.edit') %></a>
<form method="post" action="/op/agreement/<%= packKey %>/<%= item.kind %>/delete"
onsubmit="return confirm('<%= t('terms.deleteConfirm', { label: item.label }).replace(/'/g, "\\'") %>');"
style="margin:0;">
<button type="submit" class="dangerButton"><%= t('terms.deleteButton') %></button>
</form>
</div>
</article>
<% }) %>
</section>
<section class="termsSideBySide">
<div class="termsSection">
<h2><%= t('terms.addHeading') %></h2>
<form method="post" action="/op/agreement/<%= packKey %>/create" class="termsAddForm">
<div class="field">
<label for="newKind"><%= t('terms.kindLabel') %></label>
<input id="newKind" name="kind" type="text" required
pattern="[a-z0-9][a-z0-9-]{0,31}"
placeholder="<%= t('terms.kindPlaceholder') %>" />
<span class="hint"><%= t('terms.kindHint') %></span>
</div>
<div class="field">
<label for="newLabel"><%= t('terms.labelLabel') %></label>
<input id="newLabel" name="label" type="text" required maxlength="50"
placeholder="<%= t('terms.labelPlaceholder') %>" />
</div>
<div class="formActions">
<button type="submit" class="primaryButton"><%= t('terms.addButton') %></button>
</div>
</form>
</div>
<div class="termsSection">
<h2><%= t('terms.importHeading') %></h2>
<% if (sourceCandidates.length === 0) { %>
<p class="muted"><%= t('terms.importEmpty') %></p>
<% } else { %>
<form method="post" action="/op/agreement/<%= packKey %>/import" class="termsImportForm"
onsubmit="return confirm('<%= t('terms.importConfirm').replace(/'/g, "\\'") %>');">
<div class="field">
<label for="importSource"><%= t('terms.importSourceLabel') %></label>
<select id="importSource" name="source" required>
<option value=""><%= t('terms.importSourcePlaceholder') %></option>
<% sourceCandidates.forEach(function (cand) { %>
<option value="<%= cand.key %>"><%= cand.definition ? cand.definition.name : cand.key %> (<%= cand.key %>)</option>
<% }) %>
</select>
<span class="hint"><%= t('terms.importHint') %></span>
</div>
<div class="formActions">
<button type="submit" class="primaryButton"><%= t('terms.importButton') %></button>
</div>
</form>
<% } %>
</div>
</section>
</main>
</body>
</html>

View File

@@ -5,48 +5,6 @@
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title><%= t('terms.browserTitle') %></title>
<link rel="stylesheet" href="/static/styles.css" />
<style>
/* 약관 목록 — 카드 한 줄(가로 풀폭) 씩 세로로 쌓이도록. */
.termsList { display: flex; flex-direction: column; gap: 10px; margin-top: 16px; }
.termsRow {
display: flex; align-items: center; justify-content: space-between;
gap: 12px;
background: var(--bg-card);
border: 1px solid var(--border, #30363d);
border-radius: 10px;
padding: 14px 18px;
}
.termsRow .termsRowMain { display: flex; flex-direction: column; min-width: 0; flex: 1; }
.termsRow .termsRowLabel { display: flex; align-items: center; gap: 8px; }
.termsRow .termsRowLabel h2 { margin: 0; font-size: 16px; }
.termsRow .termsRowSub { color: var(--text-muted); font-size: 12px; margin-top: 2px; }
.termsRow .termsRowActions { display: flex; gap: 8px; align-items: center; }
.builtinBadge {
display: inline-block; padding: 2px 8px; border-radius: 999px;
background: rgba(255,255,255,0.08); color: var(--text-muted);
font-size: 11px;
}
.termsAddSection {
margin-top: 24px;
background: var(--bg-card);
border: 1px solid var(--border, #30363d);
border-radius: 10px;
padding: 16px 18px;
}
.termsAddSection h2 { margin: 0 0 12px; font-size: 15px; }
.termsAddForm { display: grid; grid-template-columns: 1fr 2fr auto; gap: 10px; align-items: end; }
.termsAddForm .field { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
.termsAddForm label { font-size: 12px; color: var(--text-muted); }
.termsAddForm input {
background: var(--bg-alt); color: var(--text);
border: 1px solid var(--border, #30363d); border-radius: 6px;
padding: 8px 10px; font-size: 13px;
}
.termsAddForm .hint { color: var(--text-muted); font-size: 11px; }
@media (max-width: 700px) {
.termsAddForm { grid-template-columns: 1fr; }
}
</style>
</head>
<body class="siteBody">
<%- include('../partials/navbar', { userId }) %>
@@ -59,55 +17,28 @@
</div>
</section>
<p class="muted"><%= t('terms.hint') %></p>
<p class="muted"><%= t('terms.pickPackHint') %></p>
<section class="termsList">
<section class="cardRow horizontalScroll">
<% if (items.length === 0) { %>
<p class="muted"><%= t('site.empty') %></p>
<% } %>
<% items.forEach(function (item) { %>
<article class="termsRow">
<a class="termsRowMain" href="/op/agreement/<%= item.kind %>" style="text-decoration:none; color:inherit;">
<div class="termsRowLabel">
<h2><%= item.label %></h2>
<% if (item.builtin) { %>
<span class="builtinBadge"><%= t('terms.builtinBadge') %></span>
<article class="packCard">
<a class="cardLink" href="/op/agreement/<%= item.key %>">
<h2><%= item.definition ? item.definition.name : item.key %></h2>
<p class="muted"><%= item.key %>.json</p>
<% if (item.definition) { %>
<ul class="metaList">
<li><%= t('dashboard.mcShort') %> <%= item.definition.mcVersion %></li>
<li><%= t('site.platform') %> <%= item.definition.platform.type %></li>
<li><%= t('site.modsFolder') %> <%= item.definition.modsFolder || t('site.noneFallback') %></li>
</ul>
<% } %>
</div>
<div class="termsRowSub"><%= item.kind %>.md</div>
</a>
<div class="termsRowActions">
<a class="secondaryButton" href="/op/agreement/<%= item.kind %>"><%= t('terms.edit') %></a>
<% if (!item.builtin) { %>
<form method="post" action="/op/agreement/<%= item.kind %>/delete"
onsubmit="return confirm('<%= t('terms.deleteConfirm', { label: item.label }).replace(/'/g, "\\'") %>');"
style="margin:0;">
<button type="submit" class="dangerButton"><%= t('terms.deleteButton') %></button>
</form>
<% } %>
</div>
</article>
<% }) %>
</section>
<section class="termsAddSection">
<h2><%= t('terms.addHeading') %></h2>
<form method="post" action="/op/agreement/create" class="termsAddForm">
<div class="field">
<label for="newKind"><%= t('terms.kindLabel') %></label>
<input id="newKind" name="kind" type="text" required
pattern="[a-z0-9][a-z0-9-]{0,31}"
placeholder="<%= t('terms.kindPlaceholder') %>" />
<span class="hint"><%= t('terms.kindHint') %></span>
</div>
<div class="field">
<label for="newLabel"><%= t('terms.labelLabel') %></label>
<input id="newLabel" name="label" type="text" required maxlength="50"
placeholder="<%= t('terms.labelPlaceholder') %>" />
</div>
<div class="field">
<label>&nbsp;</label>
<button type="submit" class="primaryButton"><%= t('terms.addButton') %></button>
</div>
</form>
</section>
</main>
</body>
</html>

View File

@@ -13,9 +13,9 @@
<main class="pageWrap">
<section class="dashboardHeader">
<div>
<a class="ghostLink" href="/op/agreement"><%= t('common.back') %></a>
<a class="ghostLink" href="/op/agreement/<%= packKey %>"><%= t('common.back') %></a>
<h1 style="margin-top:20px;"><%= t('terms.editorTitle', { label: label }) %></h1>
<p class="muted"><%= kind %>.md</p>
<p class="muted"><%= pack.name %> · <%= kind %>.md</p>
</div>
<div class="dirtyMark" id="dirty-mark" hidden>*</div>
</section>
@@ -29,6 +29,19 @@
<span class="statusText" id="status"></span>
</div>
<!-- 표시 대상 토글: 어느 인스톨러에서 이 약관을 보여줄지 (중복 선택 가능). -->
<fieldset class="termsVisibility" style="margin-top:16px; padding:10px 14px; border:1px solid var(--border, #30363d); border-radius:8px;">
<legend style="padding:0 6px; font-size:12px; color:var(--text-muted);"><%= t('terms.visibilityHeading') %></legend>
<label style="display:inline-flex; align-items:center; gap:6px; margin-right:18px;">
<input type="checkbox" id="visInstaller" <%= showInInstaller ? 'checked' : '' %> />
<span><%= t('terms.visibilityInstaller') %></span>
</label>
<label style="display:inline-flex; align-items:center; gap:6px;">
<input type="checkbox" id="visInstallerRp" <%= showInInstallerRp ? 'checked' : '' %> />
<span><%= t('terms.visibilityInstallerRp') %></span>
</label>
</fieldset>
<p class="muted" style="font-size:12px;"><%= t('terms.slashHint') %></p>
<div id="editorWrap" class="termsEditorWrap">
@@ -39,6 +52,7 @@
</main>
<script>
var PACK_KEY = <%- JSON.stringify(packKey) %>;
var TERM_KIND = <%- JSON.stringify(kind) %>;
var INITIAL = <%- JSON.stringify(content) %>;
var I18N = <%- JSON.stringify(localeDict.terms) %>;