4 Commits

Author SHA1 Message Date
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
8 changed files with 183 additions and 16 deletions

4
.gitignore vendored
View File

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

3
account.example.json Normal file
View File

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

View File

@@ -30,7 +30,8 @@
"title": "관리자 로그인", "title": "관리자 로그인",
"password": "비밀번호", "password": "비밀번호",
"submit": "로그인", "submit": "로그인",
"wrongPassword": "비밀번호가 올바르지 않습니다." "wrongPassword": "비밀번호가 올바르지 않습니다.",
"tooManyAttempts": "로그인 시도가 너무 많습니다. 약 {{minutes}}분 후 다시 시도해 주세요."
}, },
"dashboard": { "dashboard": {
"title": "음악퀴즈 목록", "title": "음악퀴즈 목록",

View File

@@ -1,10 +1,13 @@
import express from 'express' import express from 'express'
import session from 'express-session' import session from 'express-session'
import path from 'node:path' import path from 'node:path'
import fs from 'node:fs'
import fsp from 'node:fs/promises' import fsp from 'node:fs/promises'
import crypto from 'node:crypto'
import { import {
manifestRootPath, manifestDirPath, manifestTermsDirPath, manifestRootPath, manifestDirPath, manifestTermsDirPath,
fileDirPath, viewsDirPath, publicDirPath fileDirPath, viewsDirPath, publicDirPath, projectRoot,
accountFilePath, accountLocalFilePath
} from '../shared/paths.js' } from '../shared/paths.js'
import { import {
ensurePackTermsDir, isPublicTermsFile, listTermsWithLabels, loadPackDefinition ensurePackTermsDir, isPublicTermsFile, listTermsWithLabels, loadPackDefinition
@@ -25,7 +28,24 @@ const app = express()
app.set('view engine', 'ejs') app.set('view engine', 'ejs')
app.set('views', viewsDirPath) 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.urlencoded({ extended: true }))
app.use(express.json()) app.use(express.json())
@@ -38,13 +58,36 @@ app.use((_req, res, next) => {
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({ app.use(session({
secret: process.env.SESSION_SECRET ?? 'music-quiz-installer-dev-secret', secret: resolveSessionSecret(),
resave: false, resave: false,
saveUninitialized: false, saveUninitialized: false,
cookie: { cookie: {
httpOnly: true, httpOnly: true,
sameSite: 'lax', sameSite: 'lax',
// HTTPS 전용 배포면 SESSION_COOKIE_SECURE=true 로 secure 쿠키 활성화.
// HTTP 접근이 섞이면 로그인 쿠키가 안 실리므로 기본값은 false.
secure: process.env.SESSION_COOKIE_SECURE === 'true',
maxAge: 1000 * 60 * 60 * 8 maxAge: 1000 * 60 * 60 * 8
} }
})) }))

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

@@ -22,8 +22,10 @@ import {
saveTerm, saveTerm,
savePackList, savePackList,
setPackPublic, setPackPublic,
setTermVisibility setTermVisibility,
writeAccounts
} from '../../shared/store.js' } from '../../shared/store.js'
import { hashPassword, isHashed, verifyPassword } from '../password.js'
import { fetchReleaseVersions } from '../../shared/mojang.js' import { fetchReleaseVersions } from '../../shared/mojang.js'
import { fetchPlaylistEntries, fetchVideoMeta, YtDlpUnavailableError } from '../youtube.js' import { fetchPlaylistEntries, fetchVideoMeta, YtDlpUnavailableError } from '../youtube.js'
import { requireAuth } from '../middleware/auth.js' import { requireAuth } from '../middleware/auth.js'
@@ -33,6 +35,40 @@ import { buildSongsMcfunction } from '../datapack.js'
export const opRouter = Router() 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 { function pickFirstValue(value: unknown): string {
if (Array.isArray(value)) return typeof value[0] === 'string' ? value[0] : '' if (Array.isArray(value)) return typeof value[0] === 'string' ? value[0] : ''
return typeof value === 'string' ? value : '' return typeof value === 'string' ? value : ''
@@ -56,13 +92,32 @@ opRouter.get('/op', (req, res) => {
opRouter.post('/op', async (req, res, next) => { opRouter.post('/op', async (req, res, next) => {
try { 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 password = pickFirstValue(req.body.password)
const accounts = await readAccounts() const accounts = await readAccounts()
const matched = accounts.find((entry) => entry.password === password) const matched = accounts.find((entry) => verifyPassword(password, entry.password))
if (!matched) { if (!matched) {
recordLoginFail(clientKey)
res.status(401).render('op/login', { error: t('login.wrongPassword') }) res.status(401).render('op/login', { error: t('login.wrongPassword') })
return return
} }
loginFails.delete(clientKey)
// 평문으로 저장돼 있던 비밀번호는 로그인 성공 시 scrypt 해시로 자동 업그레이드.
if (!isHashed(matched.password)) {
try {
matched.password = hashPassword(password)
await writeAccounts(accounts)
} catch {
// 업그레이드 실패는 로그인 자체에 영향 주지 않음.
}
}
req.session.userId = matched.id req.session.userId = matched.id
res.redirect('/op/dashboard') res.redirect('/op/dashboard')
} catch (error) { } catch (error) {

View File

@@ -6,7 +6,10 @@ export const projectRoot = path.resolve(__dirname, '..', '..')
export const manifestRootPath = path.join(projectRoot, 'manifest.json') export const manifestRootPath = path.join(projectRoot, 'manifest.json')
export const manifestDirPath = path.join(projectRoot, 'manifest') export const manifestDirPath = path.join(projectRoot, 'manifest')
export const manifestTermsDirPath = path.join(manifestDirPath, 'terms') export const manifestTermsDirPath = path.join(manifestDirPath, 'terms')
// 추적되는 account.json(과거 평문 노출)을 대체할, gitignore 된 운영 계정 파일.
// readAccounts 는 이 파일을 우선 사용하고, 없을 때만 account.json 을 시드로 읽는다.
export const accountFilePath = path.join(projectRoot, '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 fileDirPath = path.join(projectRoot, 'file')
export const fileListDirPath = path.join(fileDirPath, 'list') export const fileListDirPath = path.join(fileDirPath, 'list')
export const fileDatapacksDirPath = path.join(fileDirPath, 'datapacks') export const fileDatapacksDirPath = path.join(fileDirPath, 'datapacks')

View File

@@ -3,7 +3,7 @@ import fsp from 'node:fs/promises'
import path from 'node:path' import path from 'node:path'
import { import {
manifestRootPath, manifestDirPath, manifestTermsDirPath, manifestRootPath, manifestDirPath, manifestTermsDirPath,
accountFilePath, fileListDirPath accountFilePath, accountLocalFilePath, fileListDirPath
} from './paths.js' } from './paths.js'
import type { import type {
Manifest, ManifestEntry, PackDefinition, AccountEntry, LoaderType, Manifest, ManifestEntry, PackDefinition, AccountEntry, LoaderType,
@@ -778,14 +778,24 @@ export function isPublicTermsFile(packKey: string, fileName: string): boolean {
} }
export async function readAccounts(): Promise<AccountEntry[]> { export async function readAccounts(): Promise<AccountEntry[]> {
// gitignore 된 account.local.json 우선. 없으면(ENOENT) 추적되는 account.json 을 시드로.
for (const filePath of [accountLocalFilePath, accountFilePath]) {
try { try {
const raw = await fsp.readFile(accountFilePath, 'utf8') const raw = await fsp.readFile(filePath, 'utf8')
const parsed = JSON.parse(raw) const parsed = JSON.parse(raw)
if (!Array.isArray(parsed)) return [] if (!Array.isArray(parsed)) return []
return parsed.filter((entry): entry is AccountEntry => return parsed.filter((entry): entry is AccountEntry =>
typeof entry?.id === 'string' && typeof entry?.password === 'string') typeof entry?.id === 'string' && typeof entry?.password === 'string')
} catch (error) { } catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [] if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue
throw error 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 })
} }