// scripts/ci/set-forgejo-secrets.mjs // Forgejo Actions 저장소 시크릿을 루트 .env 기준으로 점검하거나 맞춘다. // // 원칙: 시크릿 값의 정본은 루트 .env 다. Forgejo 웹 UI 에서 손으로 넣지 말고 // .env 를 고친 뒤 --write 로 밀어 넣는다. Forgejo API 는 값을 돌려주지 않으므로 // --write 는 .env 에 값이 있는 시크릿을 항상 덮어쓴다. // // 배경: 2026-09-26 SUPABASE_URL 시크릿에 로컬 Supabase 주소(127.0.0.1:55321)가 // 들어가 payple-renew 크론이 한 번도 성공하지 못했다. 그래서 운영 시크릿에는 // 로컬 주소를 거부하는 검사를 둔다. // // 사용: // node scripts/ci/set-forgejo-secrets.mjs --check # 등록 여부 + .env 값 검사 // node scripts/ci/set-forgejo-secrets.mjs --write # .env 값으로 등록/덮어쓰기 // node scripts/ci/set-forgejo-secrets.mjs --write SUPABASE_URL CRON_SECRET # 일부만 // // 값은 출력하지 않는다(이름/존재 여부/길이만). FORGEJO_TOKEN(쓰기 스코프 필요)은 // .env 또는 환경변수에서 읽는다. import { readFileSync, existsSync } from 'node:fs' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' // Forgejo 시크릿 이름 → .env 키. required=false 는 값이 없으면 건너뛴다. const SECRETS = [ { name: 'SUPABASE_URL', envKey: 'SUPABASE_URL', required: true, url: true, usedBy: 'payple-renew.yml' }, { name: 'CRON_SECRET', envKey: 'CRON_SECRET', required: true, usedBy: 'payple-renew.yml' }, { name: 'CF_API_TOKEN', envKey: 'CLOUDFLARE_API_TOKEN', required: true, usedBy: 'deploy-site.yml' }, { name: 'CF_ACCOUNT_ID', envKey: 'CLOUDFLARE_ACCOUNT_ID', required: true, usedBy: 'deploy-site.yml' }, { name: 'FORGEJO_TOKEN', envKey: 'FORGEJO_TOKEN', required: true, usedBy: 'release.yml, portable.yml' }, { name: 'WIN_CSC_LINK', envKey: 'WIN_CSC_LINK', required: false, usedBy: 'release.yml' }, { name: 'WIN_CSC_KEY_PASSWORD', envKey: 'WIN_CSC_KEY_PASSWORD', required: false, usedBy: 'release.yml' }, { name: 'D3RO_UPDATE_SIGNING_KEY', envKey: 'D3RO_UPDATE_SIGNING_KEY', required: true, usedBy: 'release.yml' }, ] const LOCAL_HOST = /^(https?:\/\/)?(localhost|127\.|0\.0\.0\.0|\[::1\]|host\.docker\.internal)/i const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..') const args = process.argv.slice(2) const write = args.includes('--write') const only = args.filter((arg) => !arg.startsWith('--')) /** .env(있으면) + 환경변수에서 값 조회. .env 가 우선이다(정본). 값은 로그에 남기지 않는다. */ function readEnv() { const values = { ...process.env } const envPath = join(root, '.env') if (existsSync(envPath)) { for (const line of readFileSync(envPath, 'utf8').split(/\r?\n/)) { if (!/^[A-Z0-9_]+=/.test(line)) continue const index = line.indexOf('=') const value = line.slice(index + 1).trim().replace(/^(['"])(.*)\1$/, '$2') if (value) values[line.slice(0, index)] = value } } return values } /** 값이 운영 시크릿으로 쓸 수 있는지. 문제가 있으면 이유를, 없으면 null. */ function validate(spec, value) { if (!value) return spec.required ? '.env 에 값 없음' : null if (spec.url) { if (LOCAL_HOST.test(value)) return '로컬 주소는 운영 시크릿이 될 수 없음' if (!/^https:\/\/[^/]+$/.test(value.replace(/\/$/, ''))) return 'https:// 형식이어야 함' } return null } const env = readEnv() const token = env.FORGEJO_TOKEN?.trim() const server = (env.GIT_SERVER_URL?.trim() || 'https://git.chanpaca.net').replace(/\/$/, '') const owner = env.GIT_USERNAME?.trim() || 'yunchan' const repo = env.GIT_REPO_NAME?.trim() || 'd3ro-voice' if (!token) { console.error('FORGEJO_TOKEN이 필요합니다 (.env 또는 환경변수).') process.exit(1) } const apiBase = `${server}/api/v1/repos/${owner}/${repo}/actions/secrets` const headers = { Authorization: `token ${token}` } async function listSecrets() { const response = await fetch(apiBase, { headers }) if (!response.ok) { throw new Error(`시크릿 목록 조회 실패: HTTP ${response.status}`) } const body = await response.json() return new Set((Array.isArray(body) ? body : []).map((item) => item.name)) } async function putSecret(name, value) { const response = await fetch(`${apiBase}/${name}`, { method: 'PUT', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ data: value }), }) if (!response.ok) { throw new Error(`${name} 등록 실패: HTTP ${response.status}`) } } const unknown = only.filter((name) => !SECRETS.some((spec) => spec.name === name)) if (unknown.length) { console.error(`알 수 없는 시크릿: ${unknown.join(', ')}`) process.exit(1) } const targets = only.length ? SECRETS.filter((spec) => only.includes(spec.name)) : SECRETS const existing = await listSecrets() console.log(`저장소: ${owner}/${repo} (${server})\n`) let problems = 0 for (const spec of targets) { const value = env[spec.envKey]?.trim() const issue = validate(spec, value) const registered = existing.has(spec.name) ? '등록됨' : '없음' const source = value ? `.env ${spec.envKey} 길이 ${value.length}` : `.env ${spec.envKey} 없음` if (issue && (spec.required || value)) problems += 1 console.log(` [${issue ? '!' : 'x'}] ${spec.name} — ${registered}, ${source}${issue ? ` — ${issue}` : ''} (${spec.usedBy})`) } if (!write) { console.log(problems ? `\n문제 ${problems}건.` : '\n.env 값 검사 통과. --write 로 Forgejo 에 반영한다.') process.exit(problems ? 2 : 0) } if (problems) { console.error('\n.env 값에 문제가 있어 아무것도 쓰지 않았다. .env 를 고친 뒤 다시 실행한다.') process.exit(2) } let written = 0 for (const spec of targets) { const value = env[spec.envKey]?.trim() if (!value) continue await putSecret(spec.name, value) written += 1 console.log(` 반영: ${spec.name}`) } const after = await listSecrets() const stillMissing = targets.filter((spec) => spec.required && !after.has(spec.name)).map((spec) => spec.name) console.log(`\n반영 ${written}건. 남은 누락: ${stillMissing.length ? stillMissing.join(', ') : '없음'}`) process.exit(stillMissing.length === 0 ? 0 : 2)