Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7b532d6520 | |||
| f0e07e06d6 | |||
| 281dbb644b | |||
| 005c7bf44c | |||
| 05a5dcedc0 |
35
electron-builder-dev.yml
Normal file
35
electron-builder-dev.yml
Normal 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: MusicQuizInstaller-Dev-${version}-Portable.${ext}
|
||||
icon: build/icon.ico
|
||||
portable:
|
||||
artifactName: MusicQuizInstaller-Dev-${version}-Portable.${ext}
|
||||
35
electron-builder-rp-dev.yml
Normal file
35
electron-builder-rp-dev.yml
Normal 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: MusicQuizResourcepackInstaller-Dev-${version}-Portable.${ext}
|
||||
icon: build/icon.ico
|
||||
portable:
|
||||
artifactName: MusicQuizResourcepackInstaller-Dev-${version}-Portable.${ext}
|
||||
@@ -108,11 +108,29 @@ function renderMain() {
|
||||
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>'
|
||||
}
|
||||
|
||||
@@ -820,16 +820,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) {
|
||||
|
||||
@@ -25,12 +25,22 @@
|
||||
"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 게이트웨이로 폴백",
|
||||
@@ -48,6 +58,7 @@
|
||||
"closeTry": "UPnP 매핑 제거 시도: TCP {{port}}",
|
||||
"upnpRemoveAttempt": "UPnP 매핑 제거 시도: {{message}}",
|
||||
"upnpRemoveDone": "UPnP 매핑 제거 완료: TCP {{port}}",
|
||||
"internalError": "내부 오류(무시하고 계속): {{message}}",
|
||||
"upnpClientFail": "UPnP 클라이언트 생성 실패: {{message}}",
|
||||
"portInUse": "포트 {{port}}이(가) 이미 사용 중 → 임시 리스너 없이 외부 서비스 응답만으로 판정.",
|
||||
"listenerBindFail": "임시 리스너 바인딩 실패: {{message}}",
|
||||
|
||||
@@ -124,14 +124,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": "확인 불가"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "minecraft-music-quiz-installer",
|
||||
"version": "0.3.15",
|
||||
"version": "0.3.20",
|
||||
"description": "마인크래프트 음악퀴즈 간편설치기 + 관리 사이트",
|
||||
"main": "dist/installer/main.js",
|
||||
"scripts": {
|
||||
@@ -14,7 +14,9 @@
|
||||
"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:pf": "tsc -p tsconfig.installer-pf.json && electron-builder --win --config electron-builder-pf.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"
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/archiver": "^7.0.0",
|
||||
|
||||
@@ -2,6 +2,7 @@ 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'
|
||||
@@ -37,8 +38,64 @@ function sendLog(line: string): void {
|
||||
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)
|
||||
@@ -93,7 +150,7 @@ function detectExternalIpUpnp(): Promise<string> {
|
||||
const timer = setTimeout(() => {
|
||||
try { client && client.close() } catch {}
|
||||
finish('')
|
||||
}, 8000)
|
||||
}, 6000)
|
||||
client.externalIp((err: Error | null, ip?: string) => {
|
||||
clearTimeout(timer)
|
||||
try { client && client.close() } catch {}
|
||||
@@ -280,6 +337,9 @@ async function probePortFromOutside(
|
||||
|
||||
interface PortForwardOutcome {
|
||||
externalIp: string
|
||||
localIp: string
|
||||
wanIp: string
|
||||
cgnat: 'yes' | 'no' | 'unknown'
|
||||
port: number
|
||||
reachable: boolean | null
|
||||
preForwarded: boolean
|
||||
@@ -292,18 +352,26 @@ ipcMain.handle('pf:open', async (_event, portInput: number): Promise<PortForward
|
||||
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 }))
|
||||
|
||||
// 이전에 남은 매핑을 먼저 제거해 "사용자 라우터 규칙으로 이미 열린 상태" 와 구별.
|
||||
sendLog(t('log.cleanup'))
|
||||
await removeUpnpMapping(port)
|
||||
|
||||
let externalIp = await detectExternalIpHttp()
|
||||
if (externalIp) sendLog(t('log.externalIpHttp', { ip: externalIp }))
|
||||
else {
|
||||
sendLog(t('log.externalIpHttpFail'))
|
||||
externalIp = await detectExternalIpUpnp()
|
||||
if (externalIp) sendLog(t('log.externalIpUpnp', { ip: externalIp }))
|
||||
else sendLog(t('log.externalIpFail'))
|
||||
}
|
||||
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'))
|
||||
@@ -312,7 +380,7 @@ ipcMain.handle('pf:open', async (_event, portInput: number): Promise<PortForward
|
||||
sendLog(t('log.probeResult', { verdict: verdictText(probe.reachable), detail: probe.detail }))
|
||||
if (probe.reachable === true) {
|
||||
sendLog(t('log.preForwarded'))
|
||||
return { externalIp, port, reachable: true, preForwarded: true, detail: probe.detail }
|
||||
return wrap(true, true, probe.detail)
|
||||
}
|
||||
|
||||
// UPnP 개방 시도.
|
||||
@@ -321,8 +389,11 @@ ipcMain.handle('pf:open', async (_event, portInput: number): Promise<PortForward
|
||||
await openPortViaUpnp(port)
|
||||
sendLog(t('log.upnpReqOk'))
|
||||
} catch (error) {
|
||||
sendLog(t('log.upnpTryFail', { message: (error as Error).message }))
|
||||
return { externalIp, port, reachable: probe.reachable, preForwarded: false, detail: probe.detail }
|
||||
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 반영 지연 고려 재점검.
|
||||
@@ -333,11 +404,11 @@ ipcMain.handle('pf:open', async (_event, portInput: number): Promise<PortForward
|
||||
if (!externalIp && probe.detectedIp) externalIp = probe.detectedIp
|
||||
if (probe.reachable === true) {
|
||||
sendLog(t('log.upnpDone', { port }))
|
||||
return { externalIp, port, reachable: true, preForwarded: false, detail: probe.detail }
|
||||
return wrap(true, false, probe.detail)
|
||||
}
|
||||
}
|
||||
sendLog(t('log.upnpUnconfirmed'))
|
||||
return { externalIp, port, reachable: probe.reachable, preForwarded: false, detail: probe.detail }
|
||||
return wrap(probe.reachable, false, probe.detail)
|
||||
})
|
||||
|
||||
ipcMain.handle('pf:close', async (_event, portInput: number): Promise<void> => {
|
||||
|
||||
@@ -2,6 +2,9 @@ import { contextBridge, ipcRenderer } from 'electron'
|
||||
|
||||
interface PortForwardOutcome {
|
||||
externalIp: string
|
||||
localIp: string
|
||||
wanIp: string
|
||||
cgnat: 'yes' | 'no' | 'unknown'
|
||||
port: number
|
||||
reachable: boolean | null
|
||||
preForwarded: boolean
|
||||
|
||||
@@ -12,6 +12,7 @@ import { normalizePackDefinition } from '../shared/store.js'
|
||||
import { getAppDataDir, getMcCustomDir } 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'
|
||||
@@ -112,6 +113,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)
|
||||
@@ -202,9 +213,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 {
|
||||
|
||||
@@ -22,10 +22,21 @@ import type { Manifest, PackDefinition } from '../shared/types.js'
|
||||
import { normalizePackDefinition } from '../shared/store.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
|
||||
@@ -136,9 +147,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)
|
||||
@@ -860,12 +874,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) {
|
||||
@@ -877,9 +886,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')
|
||||
@@ -888,47 +897,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> {
|
||||
@@ -1124,64 +1095,6 @@ function fetchIfconfigCoPortOnce(port: number): Promise<IfconfigPortResult> {
|
||||
})
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
@@ -36,7 +36,8 @@ export interface RamCheckResult {
|
||||
}
|
||||
|
||||
export interface PortForwardResult {
|
||||
status: 'preForwarded' | 'upnpOk' | 'upnpFailed'
|
||||
// 설치기는 포트를 직접 열지 않고 "열려 있는지"만 확인한다.
|
||||
status: 'open' | 'notOpen'
|
||||
externalIp?: string
|
||||
port: number
|
||||
message?: string
|
||||
|
||||
@@ -16,10 +16,12 @@ import {
|
||||
normalizePackDefinition,
|
||||
normalizePackList,
|
||||
readAccounts,
|
||||
readManifest,
|
||||
renamePack,
|
||||
sanitizePackKey,
|
||||
saveTerm,
|
||||
savePackList,
|
||||
setPackPublic,
|
||||
setTermVisibility
|
||||
} from '../../shared/store.js'
|
||||
import { fetchReleaseVersions } from '../../shared/mojang.js'
|
||||
@@ -122,11 +124,15 @@ 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
|
||||
})
|
||||
} catch (error) {
|
||||
next(error)
|
||||
@@ -519,6 +525,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)
|
||||
|
||||
20
src/shared/audience.ts
Normal file
20
src/shared/audience.ts
Normal 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
|
||||
}
|
||||
@@ -18,8 +18,15 @@ export async function readManifest(): Promise<Manifest> {
|
||||
return { packs: [] }
|
||||
}
|
||||
return {
|
||||
packs: parsed.packs.filter((entry): entry is ManifestEntry =>
|
||||
typeof entry?.name === 'string' && typeof entry?.file === 'string')
|
||||
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') {
|
||||
@@ -245,15 +252,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: [] }
|
||||
}
|
||||
|
||||
@@ -37,6 +37,11 @@ export interface PackDefinition {
|
||||
export interface ManifestEntry {
|
||||
name: string
|
||||
file: string
|
||||
/**
|
||||
* 공개 여부. true(또는 미지정)면 일반 설치기(간편/리소스팩)에 노출,
|
||||
* false 면 개발자용 설치기에만 노출된다. 하위호환: 값이 없으면 공개로 간주.
|
||||
*/
|
||||
public?: boolean
|
||||
}
|
||||
|
||||
export interface Manifest {
|
||||
|
||||
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user