diff --git a/.github/workflows/app-store-downloads.yml b/.github/workflows/app-store-downloads.yml index 5205ec5..8e018ce 100644 --- a/.github/workflows/app-store-downloads.yml +++ b/.github/workflows/app-store-downloads.yml @@ -47,6 +47,9 @@ jobs: report: name: Collect and deliver + permissions: + contents: read + actions: read needs: test if: >- github.event_name != 'pull_request' && @@ -65,7 +68,32 @@ jobs: with: node-version: '24' package-manager-cache: false - - name: Collect Apple report and optionally post to Discord + - name: Find latest encrypted history + id: history + working-directory: automation/app-store-discord + env: + GITHUB_TOKEN: ${{ github.token }} + run: node scripts/restore-history.mjs + - name: Restore encrypted history + if: steps.history.outputs.run_id != '' + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + artifact-ids: ${{ steps.history.outputs.artifact_id }} + run-id: ${{ steps.history.outputs.run_id }} + github-token: ${{ github.token }} + path: ${{ runner.temp }}/routee-history-input + merge-multiple: true + - name: Prepare encrypted input and output + env: + HISTORY_RUN_ID: ${{ steps.history.outputs.run_id }} + shell: bash + run: | + mkdir -p "$RUNNER_TEMP/routee-history-input" "$RUNNER_TEMP/routee-history-output" + if [[ -z "$HISTORY_RUN_ID" ]]; then + cp automation/app-store-discord/history-seed.enc.json "$RUNNER_TEMP/routee-history-input/history.enc.json" + fi + test -s "$RUNNER_TEMP/routee-history-input/history.enc.json" + - name: Collect Apple report and encrypt complete history working-directory: automation/app-store-discord env: ASC_APP_ID: '6791870747' @@ -73,13 +101,30 @@ jobs: ASC_ISSUER_ID: ${{ secrets.ROUTEE_ASC_ISSUER_ID }} ASC_PRIVATE_KEY: ${{ secrets.ROUTEE_ASC_PRIVATE_KEY }} ASC_REPORT_REQUEST_ID: ${{ vars.ROUTEE_ASC_REPORT_REQUEST_ID }} + HISTORY_KEY: ${{ secrets.ROUTEE_DOWNLOAD_HISTORY_KEY }} + REPORT_PERIOD: ${{ inputs.period || 'last_week' }} + shell: bash + run: | + node scripts/run-report.mjs --period "$REPORT_PERIOD" \ + --history-in "$RUNNER_TEMP/routee-history-input/history.enc.json" \ + --history-out "$RUNNER_TEMP/routee-history-output/history.enc.json" + - name: Preserve encrypted history before sending + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: routee-download-history + path: ${{ runner.temp }}/routee-history-output/history.enc.json + if-no-files-found: error + retention-days: 90 + compression-level: 0 + - name: Send the saved report to Discord + if: github.event_name == 'schedule' || inputs.send_to_discord + working-directory: automation/app-store-discord + env: + ASC_APP_ID: '6791870747' + HISTORY_KEY: ${{ secrets.ROUTEE_DOWNLOAD_HISTORY_KEY }} DISCORD_WEBHOOK_URL: ${{ secrets.ROUTEE_DISCORD_WEBHOOK_URL }} REPORT_PERIOD: ${{ inputs.period || 'last_week' }} - REPORT_SEND: ${{ github.event_name == 'schedule' || inputs.send_to_discord }} shell: bash run: | - args=(--period "$REPORT_PERIOD") - if [[ "$REPORT_SEND" == 'true' ]]; then - args+=(--send) - fi - node scripts/run-report.mjs "${args[@]}" + node scripts/run-report.mjs --period "$REPORT_PERIOD" --send --deliver-only \ + --history-in "$RUNNER_TEMP/routee-history-output/history.enc.json" diff --git a/automation/app-store-discord/.env.example b/automation/app-store-discord/.env.example index 7b81638..4ea1b36 100644 --- a/automation/app-store-discord/.env.example +++ b/automation/app-store-discord/.env.example @@ -6,3 +6,6 @@ ASC_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nREPLACE_ME\n-----END PRIVATE KEY-- DISCORD_WEBHOOK_URL= # 선택 사항: 여러 ONGOING 요청 중 하나를 지정할 때 사용 ASC_REPORT_REQUEST_ID= + +# ROUTEE_DOWNLOAD_HISTORY_KEY와 같은 32바이트 base64 암호화 키 +HISTORY_KEY= diff --git a/automation/app-store-discord/.gitignore b/automation/app-store-discord/.gitignore index 904eeff..8f2d950 100644 --- a/automation/app-store-discord/.gitignore +++ b/automation/app-store-discord/.gitignore @@ -9,3 +9,5 @@ node_modules/ wrangler.jsonc dist/ *.p8 + +.history/ diff --git a/automation/app-store-discord/README.md b/automation/app-store-discord/README.md index 69f2d45..eb47560 100644 --- a/automation/app-store-discord/README.md +++ b/automation/app-store-discord/README.md @@ -1,6 +1,6 @@ # 루티 다운로드 리포트 -GitHub Actions가 App Store Connect의 **최초 다운로드 수**를 조회해 Discord 웹훅으로 전송한다. 별도 서버·Cloudflare·Discord 명령어용 앱은 사용하지 않는다. +GitHub Actions가 App Store Connect의 **기간별 최초 다운로드 수와 출시 이후 전체 최초 다운로드 수**를 Discord 웹훅으로 전송한다. 별도 서버·Cloudflare·Discord 명령어용 앱은 사용하지 않는다. ## 실행 방법 @@ -23,7 +23,8 @@ GitHub Actions가 App Store Connect의 **최초 다운로드 수**를 조회해 - 다른 다운로드 유형만 있는 날짜의 최초 다운로드는 0건이다. 날짜 자체가 없거나 자료가 미완성인 경우에는 0건으로 추정하지 않는다. - 미확인 날짜가 있으면 **확인된 소계와 미확인 날짜**를 보낸다. 완전한 주간 합계로 표시하지 않는다. - Apple 조회가 실패하면 수치를 만들어 보내지 않고 실행을 실패로 표시한다. -- 매 실행에서 최근 처리일 35일 내 파일을 새로 읽는다. 별도 DB·캐시가 필요 없으며 출시 이후 누적 지표는 제공하지 않는다. +- 전체 최초 다운로드는 출시일부터 연속으로 확인된 일별 수치를 합산하고, 누적 기간과 기준일을 항상 표시한다. 중간 날짜가 빠지면 그 전까지의 확인된 누적값에 **이후 집계 확인 대기**를 표시한다. +- 매 실행에서 최근 처리일 35일 내 파일을 다시 읽어 기존 전체 이력에 반영한다. 오래된 날짜의 정정도 기존 날짜를 교체하며, 이력을 90일 뒤 삭제하지 않는다. ## 최초 설정 @@ -39,10 +40,29 @@ Apple API 접근 승인, API 키 발급, 보고서 생성 요청이 필요하다 | `ROUTEE_ASC_ISSUER_ID` | 팀 Issuer ID | | `ROUTEE_ASC_PRIVATE_KEY` | 운영 조회용 `.p8` PEM 전체 | | `ROUTEE_DISCORD_WEBHOOK_URL` | 리포트를 받을 Discord 채널 웹훅 URL | +| `ROUTEE_DOWNLOAD_HISTORY_KEY` | 누적 이력 AES-256-GCM 암호화 키: 무작위 32바이트를 base64로 인코딩한 값 | 대상 앱 ID는 출시용 루티 `6791870747`이다. 활성 ONGOING 요청이 여러 개라면 Repository Variable `ROUTEE_ASC_REPORT_REQUEST_ID`로 하나를 지정한다. -처음에는 `send_to_discord`를 해제해 조회를 확인한다. 보고서가 준비된 후 전송을 실행한다. ONGOING 생성 이전의 전체 이력을 보장하지 않으며 ONE_TIME_SNAPSHOT의 과거 자료 수집은 현재 구현하지 않았다. +처음에는 `send_to_discord`를 해제해 조회와 암호화 이력 보관을 확인한다. 보고서가 준비된 후 전송을 실행한다. + +## 전체 누적 이력 + +Apple report instance는 생성 35일 뒤 만료되므로 ONGOING 조회만으로 출시 이후 누적을 매번 재구성할 수 없다. + +- 초기 이력 `history-seed.enc.json`은 App Store Connect **누적 기간 / 최초 다운로드 수 / 날짜별 CSV**에서 준비했다. 출시일부터 2026-11-15 UTC까지 모든 일별 행(명시적 0 포함)이 있는지, 일별 합계가 화면 누적과 같은지 대조했다. 원본 수치는 이 저장소에 포함하지 않는다. +- 매 실행은 같은 workflow의 `develop` 예약·수동 실행에서 만든 최신 `routee-download-history` artifact를 복원한다. 최초 실행에는 암호화된 초기 이력을 사용한다. +- 일별 전체 이력을 AES-256-GCM으로 암호화하고 **90일 보관 artifact**로 먼저 업로드한다. 보관에 성공한 뒤 동일한 이력·집계 시각으로 Discord에 전송한다. 수동 조회만 실행해도 이력을 갱신한다. +- 암호화 키 오류·변조·앱 불일치·만료된 artifact·GitHub 조회 오류가 있으면 전송하지 않는다. 수집한 이력을 보관하지 못한 경우에도 전송하지 않는다. +- 모든 artifact가 삭제되어 초기 이력으로 돌아가거나 실행이 오래 중단되어 35일보다 오래된 공백이 생기면, 누적값은 과거 기준으로 남을 수 있다. 마지막 확인 기준일과 대기 표시를 확인하고 전체 이력을 복구해야 한다. 초기 값에 최근 합계만 더해 공백을 숨기지 않는다. + +복구 시 App Store Connect에서 **출시일부터 최신 완료일까지의 일별 CSV**를 다시 내보내거나 Admin 권한으로 `ONE_TIME_SNAPSHOT`을 요청한다(월 1회 제한). 모든 날짜와 화면 누적 합계를 검증한 뒤 아래 구조의 JSON을 Git에서 제외된 `.history/verified.json`에 만든다. `processingDate`는 확인일 UTC이며, 기준일은 최소 이틀 전이어야 한다. 실제 값을 GitHub 코드·로그·PR에 붙여 넣지 않는다. + +```json +{"appId":"123","startDate":"2026-01-01","days":{"2026-01-01":{"count":2,"processingDate":"2026-01-03"}},"syncedAt":"2026-01-03T12:00:00.000Z"} +``` + +동일한 암호화 키로 `encryptHistory()`를 이용해 새 `history-seed.enc.json`을 만든다. 기존 artifact가 남아 있다면 초기 파일보다 우선하므로 복구한 암호화 파일을 다음 실행의 이력 입력으로 사용해야 한다. 키를 변경할 때는 기존 이력과 seed를 새 키로 함께 암호화해야 한다. 키 자체는 보관된 실제 통계를 복호화할 수 있으므로 Secrets 밖으로 공개하지 않는다. ## 로컬 실행 @@ -60,21 +80,24 @@ npm run preview # 기본값은 안내만 출력. --apply일 때만 기존 요청 조회/생성을 실행한다. node --env-file=.env scripts/request-reports.mjs --apply -# 실제 조회만 검증. 통계 본문은 콘솔에 출력하지 않는다. -node --env-file=.env scripts/run-report.mjs --period last_week +# 실제 조회와 이력 갱신. 통계 본문은 콘솔에 출력하지 않는다. +mkdir -p .history +node --env-file=.env scripts/run-report.mjs --period last_week \ + --history-in history-seed.enc.json --history-out .history/history.enc.json -# 실제 Discord 전송 -node --env-file=.env scripts/run-report.mjs --period last_week --send +# 보관된 이력으로 실제 Discord 전송 (Apple을 다시 조회하지 않음) +node --env-file=.env scripts/run-report.mjs --period last_week --send --deliver-only \ + --history-in .history/history.enc.json ``` 관리 스크립트는 PEM 대신 `ASC_PRIVATE_KEY_PATH`로 로컬 `.p8` 경로를 받을 수 있다. 운영 workflow에는 PEM을 Secret으로 전달한다. ## 공개 저장소에서의 정보 처리 -- 실제 다운로드 수·보고서 본문·원본 파일은 GitHub 로그, Job Summary, Artifact에 남기지 않는다. Discord에만 전송한다. +- 실제 다운로드 수·보고서 본문·원본 파일은 GitHub 로그, Job Summary, Artifact에 평문으로 남기지 않는다. 저장소와 Artifact에는 인증 암호화된 이력만 저장하고, 실제 리포트는 Discord에 전송한다. - API 키와 웹훅 URL은 코드에 넣지 않는다. 네트워크 예외 원문도 출력하지 않는다. - PR에서는 모의 테스트만 실행하며 Secrets에 접근하지 않는다. 실제 조회는 `develop`의 예약·수동 실행에 한정한다. -- workflow 권한은 `contents: read`이며, 외부 Actions는 검증한 커밋 SHA에 고정한다. +- workflow는 `contents: read`, 실제 보고 job은 이력 복원을 위한 `actions: read`를 추가로 사용한다. 외부 Actions는 검증한 커밋 SHA에 고정한다. - 웹훅 전송은 자동 재시도하지 않는다. 결과가 불확실하면 Discord 채널 확인 후 새 수동 실행을 선택한다. ## 공식 근거 diff --git a/automation/app-store-discord/history-seed.enc.json b/automation/app-store-discord/history-seed.enc.json new file mode 100644 index 0000000..b1e2959 --- /dev/null +++ b/automation/app-store-discord/history-seed.enc.json @@ -0,0 +1 @@ +{"version":1,"iv":"mVPdI/wzfk66nHMH","tag":"q9b4rd+RcFp1ebS5ysZ8ng==","ciphertext":"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"} diff --git a/automation/app-store-discord/scripts/preview.mjs b/automation/app-store-discord/scripts/preview.mjs index 7a401a4..19fe5a7 100644 --- a/automation/app-store-discord/scripts/preview.mjs +++ b/automation/app-store-discord/scripts/preview.mjs @@ -2,8 +2,8 @@ import { addDays, formatReport } from '../src/reports.mjs'; const now = new Date('2026-11-18T01:17:00Z'); const days = {}; -for (let day = '2026-11-09'; day <= '2026-11-15'; day = addDays(day, 1)) { +for (let day = '2026-11-01'; day <= '2026-11-16'; day = addDays(day, 1)) { days[day] = { count: 3, processingDate: addDays(day, 2) }; } console.log('예시 데이터입니다. 실제 루티 통계가 아니며 Discord에 전송하지 않습니다.\n'); -console.log(formatReport({ days, syncedAt: now.toISOString() }, 'last_week', now)); +console.log(formatReport({ startDate: '2026-11-01', days, syncedAt: now.toISOString() }, 'last_week', now)); diff --git a/automation/app-store-discord/scripts/restore-history.mjs b/automation/app-store-discord/scripts/restore-history.mjs new file mode 100644 index 0000000..1aa5ec8 --- /dev/null +++ b/automation/app-store-discord/scripts/restore-history.mjs @@ -0,0 +1,123 @@ +import { appendFile } from 'node:fs/promises'; +import { pathToFileURL } from 'node:url'; + +import { HistoryError } from '../src/history.mjs'; + +const ARTIFACT_NAME = 'routee-download-history'; +const WORKFLOW_PATH = '.github/workflows/app-store-downloads.yml'; +const MAX_RESPONSE_BYTES = 2 * 1024 * 1024; + +function fail(code, message) { + throw new HistoryError(code, message); +} + +function id(value) { + return Number.isSafeInteger(value) && value > 0; +} + +async function readJSON(response) { + const reader = response.body?.getReader(); + if (!reader) fail('HISTORY_RESTORE_FAILED', '집계 이력 목록을 읽을 수 없습니다.'); + const chunks = []; + let size = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > MAX_RESPONSE_BYTES) { + await reader.cancel(); + fail('HISTORY_RESTORE_FAILED', '집계 이력 목록이 지원하는 크기를 초과했습니다.'); + } + chunks.push(value); + } + return JSON.parse(Buffer.concat(chunks).toString('utf8')); + } finally { + reader.releaseLock(); + } +} + +/** Only selects metadata; download-artifact downloads the exact encrypted artifact ID. */ +export async function findHistoryArtifact(env, { fetchImpl = fetch } = {}) { + const repository = env.GITHUB_REPOSITORY; + if (typeof repository !== 'string' || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository) + || typeof env.GITHUB_TOKEN !== 'string' || !env.GITHUB_TOKEN.trim()) { + fail('HISTORY_RESTORE_CONFIGURATION', '집계 이력 조회용 GitHub 실행 설정을 확인해 주세요.'); + } + let requests = 0; + async function request(path) { + if (++requests > 80) fail('HISTORY_RESTORE_FAILED', '집계 이력 조회가 실행 한도를 초과했습니다.'); + try { + const response = await fetchImpl(`https://api.github.com/repos/${repository}${path}`, { + headers: { Authorization: `Bearer ${env.GITHUB_TOKEN}`, Accept: 'application/vnd.github+json', + 'X-GitHub-Api-Version': '2022-11-28' }, + redirect: 'error', signal: AbortSignal.timeout(10_000), + }); + if (!response.ok) fail('HISTORY_RESTORE_FAILED', 'GitHub 집계 이력 조회에 실패했습니다.'); + return await readJSON(response); + } catch { + fail('HISTORY_RESTORE_FAILED', 'GitHub 집계 이력을 확인하지 못해 초기 이력으로 대체하지 않았습니다.'); + } + } + + const artifacts = new Map(); + let complete = false; + for (let page = 1; page <= 40; page++) { + const data = await request(`/actions/artifacts?name=${ARTIFACT_NAME}&per_page=100&page=${page}`); + if (!Array.isArray(data.artifacts) || !Number.isSafeInteger(data.total_count) || data.total_count < 0) { + fail('HISTORY_RESTORE_FAILED', 'GitHub 집계 이력 목록 형식을 확인할 수 없습니다.'); + } + for (const artifact of data.artifacts) { + if (artifact.name !== ARTIFACT_NAME || !id(artifact.id) || !id(artifact.workflow_run?.id) + || typeof artifact.expired !== 'boolean' || !Number.isFinite(Date.parse(artifact.created_at))) { + fail('HISTORY_RESTORE_FAILED', 'GitHub 집계 이력 메타데이터를 확인할 수 없습니다.'); + } + artifacts.set(artifact.id, artifact); + } + if (data.artifacts.length < 100 || artifacts.size >= data.total_count) { + complete = true; + break; + } + } + if (!complete) fail('HISTORY_RESTORE_FAILED', '집계 이력 목록을 모두 확인하지 못했습니다.'); + + const candidates = [...artifacts.values()] + .filter(artifact => artifact.workflow_run.head_branch === 'develop') + .sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at) || b.id - a.id); + const runs = new Map(); + for (const artifact of candidates) { + const runId = artifact.workflow_run.id; + if (!runs.has(runId)) runs.set(runId, await request(`/actions/runs/${runId}`)); + const run = runs.get(runId); + if (!id(run.id) || run.id !== runId || typeof run.path !== 'string' || typeof run.event !== 'string' + || typeof run.repository?.full_name !== 'string' || typeof run.head_repository?.full_name !== 'string') { + fail('HISTORY_RESTORE_FAILED', '집계 이력을 생성한 실행 정보를 확인할 수 없습니다.'); + } + if (run.path !== WORKFLOW_PATH || run.head_branch !== 'develop' + || !['schedule', 'workflow_dispatch'].includes(run.event) + || run.repository.full_name.toLowerCase() !== repository.toLowerCase() + || run.head_repository.full_name.toLowerCase() !== repository.toLowerCase()) continue; + if (artifact.expired) fail('HISTORY_EXPIRED', '이전 집계 이력이 만료되었습니다. 누적 이력을 복구한 뒤 다시 실행해 주세요.'); + return { runId, artifactId: artifact.id }; + } + return null; +} + +export async function main(env = process.env, { find = findHistoryArtifact, write = appendFile } = {}) { + try { + if (!env.GITHUB_OUTPUT) fail('HISTORY_RESTORE_CONFIGURATION', 'GitHub 출력 파일 설정이 필요합니다.'); + const artifact = await find(env); + await write(env.GITHUB_OUTPUT, `run_id=${artifact?.runId ?? ''}\nartifact_id=${artifact?.artifactId ?? ''}\n`, 'utf8'); + console.log(artifact ? '암호화된 집계 이력을 선택했습니다.' : '기존 집계 이력이 없어 암호화된 초기 이력을 사용합니다.'); + return 0; + } catch (error) { + const safe = error instanceof HistoryError ? error + : new HistoryError('HISTORY_RESTORE_FAILED', '집계 이력 복원을 준비하지 못했습니다.'); + console.error(`${safe.code}: ${safe.message}`); + return 1; + } +} + +if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) { + process.exitCode = await main(); +} diff --git a/automation/app-store-discord/scripts/run-report.mjs b/automation/app-store-discord/scripts/run-report.mjs index 90e3ad5..2df7187 100644 --- a/automation/app-store-discord/scripts/run-report.mjs +++ b/automation/app-store-discord/scripts/run-report.mjs @@ -1,7 +1,8 @@ -import { appendFile } from 'node:fs/promises'; +import { appendFile, readFile, writeFile } from 'node:fs/promises'; import { pathToFileURL } from 'node:url'; import { ReportRunError, runReport } from '../src/run-report.mjs'; +import { decryptHistory, encryptHistory } from '../src/history.mjs'; export function parseArguments(args, env = process.env) { const options = { period: 'last_week', send: false, summaryPath: env.GITHUB_STEP_SUMMARY }; @@ -12,11 +13,12 @@ export function parseArguments(args, env = process.env) { if (seen.has(flag)) throw new ReportRunError('INVALID_ARGUMENT', '같은 실행 옵션을 여러 번 지정할 수 없습니다.'); seen.add(flag); if (flag === '--send' && inlineParts.length === 0) options.send = true; + else if (flag === '--deliver-only' && inlineParts.length === 0) options.deliverOnly = true; else if (flag === '--help' && inlineParts.length === 0) options.help = true; - else if (flag === '--period' || flag === '--summary-path') { + else if (['--period', '--summary-path', '--history-in', '--history-out'].includes(flag)) { const value = inlineParts.length ? inlineParts.join('=') : args[++index]; if (!value || value.startsWith('--')) throw new ReportRunError('INVALID_ARGUMENT', '실행 옵션의 값을 확인해 주세요.'); - options[flag === '--period' ? 'period' : 'summaryPath'] = value; + options[({ '--period': 'period', '--summary-path': 'summaryPath', '--history-in': 'historyIn', '--history-out': 'historyOut' })[flag]] = value; } else throw new ReportRunError('INVALID_ARGUMENT', '지원하지 않는 실행 옵션입니다.'); } return options; @@ -27,10 +29,18 @@ export async function main(args = process.argv.slice(2), env = process.env, { ex try { options = parseArguments(args, env); if (options.help) { - console.log('node scripts/run-report.mjs [--period last_week|last_7_days|last_30_days] [--send] [--summary-path FILE]'); + console.log('node scripts/run-report.mjs [--period last_week|last_7_days|last_30_days] [--send] [--history-in ENCRYPTED_FILE] [--history-out ENCRYPTED_FILE] [--deliver-only] [--summary-path FILE]'); console.log('--send가 없으면 조회만 검증합니다. 통계 수치와 본문은 콘솔이나 GitHub 요약에 출력하지 않습니다.'); return 0; } + if (options.historyIn) { + try { options.initialSnapshot = decryptHistory(await readFile(options.historyIn, 'utf8'), env.HISTORY_KEY, String(env.ASC_APP_ID ?? '').trim()); } + catch { throw new ReportRunError('HISTORY_LOAD_FAILED', '누적 이력을 복원하지 못했습니다. 암호화 키와 이력 파일을 확인해 주세요.'); } + } + if (options.deliverOnly && options.initialSnapshot) options.now = new Date(options.initialSnapshot.syncedAt); + if (options.historyOut) { + options.persist = async snapshot => writeFile(options.historyOut, encryptHistory(snapshot, env.HISTORY_KEY), { mode: 0o600 }); + } const result = await execute(env, options); if (options.summaryPath) { try { diff --git a/automation/app-store-discord/src/apple.mjs b/automation/app-store-discord/src/apple.mjs index a4df3fa..70d5e84 100644 --- a/automation/app-store-discord/src/apple.mjs +++ b/automation/app-store-discord/src/apple.mjs @@ -184,7 +184,11 @@ export async function collectDownloads(env, previous = { days: {} }, { fetchImpl if (!Number.isFinite(now.getTime())) fail('CONFIGURATION', 'Invalid current time.'); if (previous.appId && previous.appId !== appId) fail('CACHE_APP_MISMATCH', 'The saved report belongs to a different app.'); const today = now.toISOString().slice(0, 10); - const oldestDate = shiftDate(today, -89); + if (previous.startDate != null && (!isDate(previous.startDate) || previous.startDate > today)) { + fail('CACHE_SCHEMA', 'The saved history start date is invalid.'); + } + // Lifetime history must survive Apple's 35-day instance retention, including old corrections. + const oldestDate = previous.startDate ?? shiftDate(today, -89); const earliestProcessingDate = shiftDate(today, -34); const days = {}; if (!previous.days || typeof previous.days !== 'object' || Array.isArray(previous.days)) fail('CACHE_SCHEMA', 'The saved download data is invalid.'); @@ -312,7 +316,8 @@ export async function collectDownloads(env, previous = { days: {} }, { fetchImpl completedInstances += 1; } return { - appId, days, syncedAt: now.toISOString(), requestId, reportId, + appId, ...(previous.startDate ? { startDate: previous.startDate } : {}), + days, syncedAt: now.toISOString(), requestId, reportId, processedInstanceIds: [...processed], pendingInstances: recent.filter((instance) => !processed.has(instance.id)).length, }; diff --git a/automation/app-store-discord/src/history.mjs b/automation/app-store-discord/src/history.mjs new file mode 100644 index 0000000..668388d --- /dev/null +++ b/automation/app-store-discord/src/history.mjs @@ -0,0 +1,105 @@ +import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'; + +const MAX_BYTES = 2 * 1024 * 1024; +const PURPOSE = Buffer.from('routee-app-store-discord/download-history/v1', 'utf8'); + +export class HistoryError extends Error { + constructor(code, message) { + super(message); + this.name = 'HistoryError'; + this.code = code; + } +} + +function fail(code, message) { + throw new HistoryError(code, message); +} + +function object(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value) + && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null); +} + +function date(value) { + return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value) + && Number.isFinite(Date.parse(`${value}T00:00:00Z`)) + && new Date(`${value}T00:00:00Z`).toISOString().slice(0, 10) === value; +} + +function decode(value, size, code = 'HISTORY_DECRYPT_FAILED') { + if (typeof value !== 'string' || !value || value.length > MAX_BYTES + || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) { + fail(code, '집계 이력의 암호화 설정 또는 파일을 확인해 주세요.'); + } + const bytes = Buffer.from(value, 'base64'); + if (bytes.toString('base64') !== value || (size !== undefined && bytes.length !== size)) { + fail(code, '집계 이력의 암호화 설정 또는 파일을 확인해 주세요.'); + } + return bytes; +} + +/** Copies only durable fields. Per-run collection cursors must never be persisted. */ +export function validateHistory(snapshot, expectedAppId) { + if (!object(snapshot) || typeof snapshot.appId !== 'string' || !/^\d+$/.test(snapshot.appId) + || (expectedAppId !== undefined && snapshot.appId !== expectedAppId) + || !date(snapshot.startDate) || !object(snapshot.days) + || typeof snapshot.syncedAt !== 'string' || !Number.isFinite(Date.parse(snapshot.syncedAt)) + || new Date(snapshot.syncedAt).toISOString() !== snapshot.syncedAt + || snapshot.startDate > snapshot.syncedAt.slice(0, 10)) { + fail('HISTORY_INVALID', '집계 이력의 앱·기간·자료 형식을 확인할 수 없습니다.'); + } + const days = {}; + const entries = Object.entries(snapshot.days); + if (entries.length > 20_000) fail('HISTORY_INVALID', '집계 이력이 지원하는 크기를 초과했습니다.'); + for (const [day, record] of entries.sort(([a], [b]) => a.localeCompare(b))) { + if (!date(day) || day < snapshot.startDate || !object(record) + || !Number.isSafeInteger(record.count) || record.count < 0 + || !date(record.processingDate) || record.processingDate < day + || record.processingDate > snapshot.syncedAt.slice(0, 10)) { + fail('HISTORY_INVALID', '집계 이력의 날짜별 자료를 확인할 수 없습니다.'); + } + days[day] = { count: record.count, processingDate: record.processingDate }; + } + const history = { appId: snapshot.appId, startDate: snapshot.startDate, days, syncedAt: snapshot.syncedAt }; + if (Buffer.byteLength(JSON.stringify(history)) > MAX_BYTES) { + fail('HISTORY_INVALID', '집계 이력이 지원하는 크기를 초과했습니다.'); + } + return history; +} + +/** AES-256-GCM authenticates both the ciphertext and its fixed application purpose. */ +export function encryptHistory(snapshot, key) { + const history = validateHistory(snapshot); + const keyBytes = decode(key, 32, 'HISTORY_KEY_INVALID'); + const iv = randomBytes(12); + const cipher = createCipheriv('aes-256-gcm', keyBytes, iv); + cipher.setAAD(PURPOSE); + const ciphertext = Buffer.concat([cipher.update(JSON.stringify(history), 'utf8'), cipher.final()]); + const envelope = JSON.stringify({ version: 1, iv: iv.toString('base64'), + tag: cipher.getAuthTag().toString('base64'), ciphertext: ciphertext.toString('base64') }); + if (Buffer.byteLength(envelope) > MAX_BYTES) fail('HISTORY_INVALID', '집계 이력이 지원하는 크기를 초과했습니다.'); + return `${envelope}\n`; +} + +export function decryptHistory(text, key, expectedAppId) { + const keyBytes = decode(key, 32, 'HISTORY_KEY_INVALID'); + if (typeof text !== 'string' || Buffer.byteLength(text) > MAX_BYTES) { + fail('HISTORY_DECRYPT_FAILED', '암호화된 집계 이력을 읽을 수 없습니다.'); + } + let snapshot; + try { + const envelope = JSON.parse(text); + if (!object(envelope) || envelope.version !== 1 + || Object.keys(envelope).sort().join(',') !== 'ciphertext,iv,tag,version') { + fail('HISTORY_DECRYPT_FAILED', '암호화된 집계 이력 형식을 확인할 수 없습니다.'); + } + const decipher = createDecipheriv('aes-256-gcm', keyBytes, decode(envelope.iv, 12)); + decipher.setAAD(PURPOSE); + decipher.setAuthTag(decode(envelope.tag, 16)); + const plaintext = Buffer.concat([decipher.update(decode(envelope.ciphertext)), decipher.final()]); + snapshot = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(plaintext)); + } catch { + fail('HISTORY_DECRYPT_FAILED', '집계 이력 복호화에 실패했습니다. 암호화 키와 이력 파일을 확인해 주세요.'); + } + return validateHistory(snapshot, expectedAppId); +} diff --git a/automation/app-store-discord/src/reports.mjs b/automation/app-store-discord/src/reports.mjs index c1e807d..d8125d2 100644 --- a/automation/app-store-discord/src/reports.mjs +++ b/automation/app-store-discord/src/reports.mjs @@ -49,8 +49,40 @@ export function summarize(snapshot, period = 'last_week', now = new Date()) { syncedAt: snapshot?.syncedAt ?? null, latestDate: available.at(-1) ?? null }; } +/** Only a continuous, finalized history from launch can establish a lifetime total. */ +export function summarizeLifetime(snapshot, now = new Date()) { + const start = snapshot?.startDate; + const targetEnd = addDays(dateOnly(now), -2); + if (!start) { + return { configured: false, start: null, end: null, targetEnd, total: null, + complete: false, missingFrom: null, availableDays: 0 }; + } + if (typeof start !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(start) + || !Number.isFinite(Date.parse(`${start}T00:00:00Z`)) || dateOnly(`${start}T00:00:00Z`) !== start) { + throw new Error('누적 집계 시작일을 확인할 수 없습니다.'); + } + const days = snapshot?.days ?? {}; + let end = null; + let total = 0; + let availableDays = 0; + let missingFrom = null; + for (let day = start; day <= targetEnd; day = addDays(day, 1)) { + if (!finalized(day, days[day], now)) { + missingFrom = day; + break; + } + total += days[day].count; + if (!Number.isSafeInteger(total)) throw new Error('누적 집계 범위를 초과했습니다.'); + end = day; + availableDays++; + } + return { configured: true, start, end, targetEnd, total: end ? total : null, + complete: end === targetEnd, missingFrom, availableDays }; +} + export function formatReport(snapshot, period = 'last_week', now = new Date()) { const report = summarize(snapshot, period, now); + const lifetime = summarizeLifetime(snapshot, now); const title = { last_week: '지난주', last_7_days: '최근 7일', last_30_days: '최근 30일' }[period]; const lines = ['📊 루티 최초 다운로드 리포트', `${title}: ${report.start} ~ ${report.end} (UTC)`]; if (report.complete) { @@ -61,6 +93,16 @@ export function formatReport(snapshot, period = 'last_week', now = new Date()) { `미확인 날짜: ${report.missing.join(', ')}`, '보고서가 없거나 아직 완성되지 않은 날짜는 0건으로 계산하지 않습니다.'); } + lines.push(''); + if (lifetime.end) { + lines.push(`전체 최초 다운로드: **${lifetime.total.toLocaleString('ko-KR')}건**`, + `누적 기간: ${lifetime.start} ~ ${lifetime.end} (UTC)`); + if (!lifetime.complete) lines.push(`${lifetime.end} 기준 · 이후 집계 확인 대기`); + } else { + lines.push('전체 최초 다운로드: 확인 대기', + '출시일부터 이어지는 완성된 이력이 있어야 누적 합계를 표시할 수 있습니다.'); + } + lines.push(''); if (report.latestDate) lines.push(`완성된 데이터의 최신 날짜: ${report.latestDate} (UTC)`); if (report.syncedAt) lines.push(`마지막 수집: ${new Date(report.syncedAt).toISOString().replace('T', ' ').slice(0, 16)} UTC`); else lines.push('아직 Apple 보고서를 수집하지 못했습니다.'); diff --git a/automation/app-store-discord/src/run-report.mjs b/automation/app-store-discord/src/run-report.mjs index 3627c15..0e01bb5 100644 --- a/automation/app-store-discord/src/run-report.mjs +++ b/automation/app-store-discord/src/run-report.mjs @@ -1,5 +1,6 @@ import { collectDownloads } from './apple.mjs'; -import { formatReport, PERIODS, summarize } from './reports.mjs'; +import { formatReport, PERIODS, summarize, summarizeLifetime } from './reports.mjs'; +import { validateHistory } from './history.mjs'; import { sendWebhook } from './webhook.mjs'; export class ReportRunError extends Error { @@ -50,9 +51,10 @@ function publicSummary(report, status) { '- 실제 다운로드 수와 리포트 본문은 GitHub 로그·요약에 기록하지 않습니다.', ''].join('\n'); } -/** Stateless per-run collection. Only the returned content is sent to the private Discord channel. */ +/** Refresh saved daily history; only the returned content is sent to the private Discord channel. */ export async function runReport(env, { period = 'last_week', send = false, now = new Date(), maxRounds = 6, + initialSnapshot, deliverOnly = false, persist, collect = collectDownloads, deliver = sendWebhook, } = {}) { if (!PERIODS.has(period)) fail('INVALID_PERIOD', '조회 기간은 last_week, last_7_days, last_30_days 중 하나여야 합니다.'); @@ -70,8 +72,14 @@ export async function runReport(env, { const appId = String(env.ASC_APP_ID ?? '').trim(); const collectionEnv = { ...env, ASC_APP_ID: appId, ASC_MAX_INSTANCES_PER_SYNC: env.ASC_MAX_INSTANCES_PER_SYNC ?? '20' }; let snapshot = { days: {} }; - let finished = false; - for (let round = 0; round < maxRounds; round++) { + if (initialSnapshot) { + try { snapshot = validateHistory(initialSnapshot, appId); } + catch { fail('INVALID_HISTORY', '저장된 누적 이력을 확인할 수 없어 전송하지 않았습니다.'); } + } + if (deliverOnly && !initialSnapshot) fail('HISTORY_REQUIRED', '전송할 검증된 누적 이력이 필요합니다.'); + // Instance IDs are intentionally reset between runs so that recent corrections are read again. + let finished = deliverOnly; + for (let round = 0; !deliverOnly && round < maxRounds; round++) { const previousIds = new Set(snapshot.processedInstanceIds ?? []); let next; try { @@ -93,13 +101,19 @@ export async function runReport(env, { let report; let content; + let complete; try { report = summarize(snapshot, period, now); + complete = report.complete && summarizeLifetime(snapshot, now).complete; content = formatReport(snapshot, period, now); } catch { fail('REPORT_FORMAT_FAILED', '수집 자료를 리포트로 변환하지 못해 전송하지 않았습니다.'); } - let status = report.complete ? 'preview' : 'preview_partial'; + if (persist) { + try { await persist(snapshot); } + catch { fail('HISTORY_SAVE_FAILED', '누적 이력을 안전하게 보관하지 못해 전송하지 않았습니다.'); } + } + let status = complete ? 'preview' : 'preview_partial'; if (send) { try { await deliver(env.DISCORD_WEBHOOK_URL, content); @@ -110,7 +124,7 @@ export async function runReport(env, { : '디스코드 전송 결과를 확인할 수 없습니다. 재전송하기 전에 채널을 확인해 주세요.', knownFailure ? 'not_sent' : 'unknown'); } - status = report.complete ? 'sent' : 'sent_partial'; + status = complete ? 'sent' : 'sent_partial'; } return { snapshot, content, status, summary: publicSummary(report, status) }; } diff --git a/automation/app-store-discord/test/apple.test.mjs b/automation/app-store-discord/test/apple.test.mjs index 655123b..8e1a797 100644 --- a/automation/app-store-discord/test/apple.test.mjs +++ b/automation/app-store-discord/test/apple.test.mjs @@ -159,3 +159,16 @@ test('validates schema and refuses inactive requests or a different app cache', await assert.rejects(collectDownloads(ENV, undefined, { fetchImpl: inactive.fetchImpl, now: NOW }), { code: 'REPORT_REQUEST' }); await assert.rejects(collectDownloads(ENV, { appId: '9999', days: {} }, { now: NOW }), { code: 'CACHE_APP_MISMATCH' }); }); + +test('lifetime history survives retention and accepts corrections to an old date', async () => { + const previous = { appId: '1234', startDate: '2026-01-01', days: { + '2026-01-01': { count: 11, processingDate: '2026-01-03' }, + '2026-02-01': { count: 22, processingDate: '2026-02-03' }, + } }; + const { fetchImpl } = fixture([{ id: 'correction', processingDate: '2026-11-18', segments: [row('2026-01-01', 8)] }]); + const result = await collectDownloads(ENV, previous, { fetchImpl, now: NOW }); + assert.equal(result.startDate, '2026-01-01'); + assert.equal(result.days['2026-01-01'].count, 8); + assert.equal(result.days['2026-02-01'].count, 22); + assert.equal(previous.days['2026-01-01'].count, 11); +}); diff --git a/automation/app-store-discord/test/history.test.mjs b/automation/app-store-discord/test/history.test.mjs new file mode 100644 index 0000000..c46b451 --- /dev/null +++ b/automation/app-store-discord/test/history.test.mjs @@ -0,0 +1,125 @@ +import assert from 'node:assert/strict'; +import { randomBytes } from 'node:crypto'; +import test from 'node:test'; + +import { findHistoryArtifact, main } from '../scripts/restore-history.mjs'; +import { decryptHistory, encryptHistory, validateHistory } from '../src/history.mjs'; + +const key = randomBytes(32).toString('base64'); +const history = { + appId: '123', startDate: '2026-01-01', syncedAt: '2026-01-05T01:00:00.000Z', + days: { '2026-01-01': { count: 27, processingDate: '2026-01-03' }, + '2026-01-02': { count: 0, processingDate: '2026-01-04' } }, +}; +const env = { GITHUB_REPOSITORY: 'example/repository', GITHUB_TOKEN: 'private-token' }; + +function artifact(artifactId, runId, createdAt, extra = {}) { + return { id: artifactId, name: 'routee-download-history', expired: false, created_at: createdAt, + workflow_run: { id: runId, head_branch: 'develop' }, ...extra }; +} + +function run(runId, extra = {}) { + return { id: runId, path: '.github/workflows/app-store-downloads.yml', event: 'workflow_dispatch', + head_branch: 'develop', repository: { full_name: env.GITHUB_REPOSITORY }, + head_repository: { full_name: env.GITHUB_REPOSITORY }, ...extra }; +} + +function api(artifacts, runs = {}, calls = []) { + return async (url, options) => { + calls.push(url); + assert.equal(new URL(url).origin, 'https://api.github.com'); + assert.equal(options.headers.Authorization, `Bearer ${env.GITHUB_TOKEN}`); + assert.equal(options.redirect, 'error'); + const resource = url.includes('/actions/artifacts?') + ? { total_count: artifacts.length, artifacts } + : runs[url.split('/').at(-1)]; + assert.ok(resource, 'Unexpected API request'); + return Response.json(resource); + }; +} + +test('encrypted history round trips with unique IVs and excludes per-run fields', () => { + const withCursor = { ...history, processedInstanceIds: ['discard'], pendingInstances: 0 }; + const first = encryptHistory(withCursor, key); + const second = encryptHistory(withCursor, key); + assert.notEqual(first, second); + assert.deepEqual(decryptHistory(first, key, '123'), history); + assert.equal(first.includes('2026-01'), false); + assert.equal(first.includes('count'), false); + assert.equal(first.includes('discard'), false); +}); + +test('tampering, incorrect keys and cross-app histories are rejected', () => { + const encrypted = encryptHistory(history, key); + const envelope = JSON.parse(encrypted); + const bytes = Buffer.from(envelope.ciphertext, 'base64'); + bytes[0] ^= 1; + envelope.ciphertext = bytes.toString('base64'); + assert.throws(() => decryptHistory(JSON.stringify(envelope), key), { code: 'HISTORY_DECRYPT_FAILED' }); + assert.throws(() => decryptHistory(encrypted, randomBytes(32).toString('base64')), { code: 'HISTORY_DECRYPT_FAILED' }); + assert.throws(() => decryptHistory(encrypted, key, '456'), { code: 'HISTORY_INVALID' }); + assert.throws(() => decryptHistory(encrypted, 'bad-key'), { code: 'HISTORY_KEY_INVALID' }); +}); + +test('invalid dates, future processing, unsafe counts and malformed envelopes fail closed', () => { + for (const invalid of [ + { ...history, startDate: '2026-02-30' }, + { ...history, syncedAt: 'invalid' }, + { ...history, days: { '2026-02-30': { count: 1, processingDate: '2026-03-02' } } }, + { ...history, days: { '2026-01-01': { count: 1, processingDate: '2026-01-06' } } }, + { ...history, days: { '2026-01-01': { count: Number.MAX_SAFE_INTEGER + 1, processingDate: '2026-01-03' } } }, + { ...history, days: { '2025-12-31': { count: 1, processingDate: '2026-01-03' } } }, + ]) assert.throws(() => validateHistory(invalid), { code: 'HISTORY_INVALID' }); + for (const text of ['{}', 'not JSON', JSON.stringify({ ...JSON.parse(encryptHistory(history, key)), version: 2 }), 'x'.repeat(2 * 1024 * 1024 + 1)]) { + assert.throws(() => decryptHistory(text, key), { code: 'HISTORY_DECRYPT_FAILED' }); + } +}); + +test('selects newest trusted artifact including a run whose later delivery failed', async () => { + const artifacts = [artifact(1, 11, '2026-01-01T00:00:00Z'), artifact(2, 12, '2026-01-03T00:00:00Z')]; + const selected = await findHistoryArtifact(env, { fetchImpl: api(artifacts, { 12: run(12, { conclusion: 'failure' }) }) }); + assert.deepEqual(selected, { runId: 12, artifactId: 2 }); +}); + +test('rejects untrusted branch, workflow, event and fork before choosing history', async () => { + const artifacts = [ + artifact(5, 15, '2026-01-05T00:00:00Z', { workflow_run: { id: 15, head_branch: 'feature' } }), + artifact(4, 14, '2026-01-04T00:00:00Z'), artifact(3, 13, '2026-01-03T00:00:00Z'), + artifact(2, 12, '2026-01-02T00:00:00Z'), artifact(1, 11, '2026-01-01T00:00:00Z'), + ]; + const calls = []; + const selected = await findHistoryArtifact(env, { fetchImpl: api(artifacts, { + 14: run(14, { path: '.github/workflows/other.yml' }), + 13: run(13, { event: 'pull_request' }), + 12: run(12, { head_repository: { full_name: 'untrusted/fork' } }), 11: run(11), + }, calls) }); + assert.deepEqual(selected, { runId: 11, artifactId: 1 }); + assert.ok(calls.every(url => !url.endsWith('/15'))); +}); + +test('expired newest history and API failures do not silently fall back to an older seed', async () => { + await assert.rejects(findHistoryArtifact(env, { fetchImpl: api([ + artifact(2, 12, '2026-01-02T00:00:00Z', { expired: true }), artifact(1, 11, '2026-01-01T00:00:00Z'), + ], { 12: run(12) }) }), { code: 'HISTORY_EXPIRED' }); + await assert.rejects(findHistoryArtifact(env, { fetchImpl: async () => { throw new Error('private-token'); } }), error => { + assert.equal(error.code, 'HISTORY_RESTORE_FAILED'); + assert.equal(error.message.includes('private-token'), false); + return true; + }); + assert.equal(await findHistoryArtifact(env, { fetchImpl: api([]) }), null); +}); + +test('restore CLI writes only artifact identifiers and masks unexpected failures', async t => { + const messages = []; + const output = []; + t.mock.method(console, 'log', value => messages.push(value)); + t.mock.method(console, 'error', value => messages.push(value)); + assert.equal(await main({ ...env, GITHUB_OUTPUT: '/test-output' }, { + find: async () => ({ runId: 12, artifactId: 2 }), write: async (...args) => output.push(args), + }), 0); + assert.deepEqual(output[0], ['/test-output', 'run_id=12\nartifact_id=2\n', 'utf8']); + assert.equal(await main({ ...env, GITHUB_OUTPUT: '/test-output' }, { + find: async () => { throw new Error('private-token'); }, write: async () => assert.fail('Must not write'), + }), 1); + assert.ok(messages.every(message => !message.includes('private-token'))); +}); diff --git a/automation/app-store-discord/test/reports.test.mjs b/automation/app-store-discord/test/reports.test.mjs index 1be18bf..8b6bf47 100644 --- a/automation/app-store-discord/test/reports.test.mjs +++ b/automation/app-store-discord/test/reports.test.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import { addDays, formatReport, lastWeek, summarize } from '../src/reports.mjs'; +import { addDays, formatReport, lastWeek, summarize, summarizeLifetime } from '../src/reports.mjs'; const now = new Date('2026-11-18T01:17:00Z'); function sample() { @@ -54,3 +54,83 @@ test('empty snapshot cannot report a complete zero', () => { assert.equal(report.complete, false); assert.equal(report.missing.length, 7); }); + +function history(start, end, count = 2) { + const days = {}; + for (let day = start; day <= end; day = addDays(day, 1)) { + days[day] = { count, processingDate: addDays(day, 2) }; + } + return { startDate: start, days }; +} + +test('lifetime includes history outside the selected weekly period', () => { + const snapshot = history('2026-10-30', '2026-11-16'); + assert.equal(summarize(snapshot, 'last_week', now).total, 14); + assert.deepEqual(summarizeLifetime(snapshot, now), { + configured: true, start: '2026-10-30', end: '2026-11-16', targetEnd: '2026-11-16', + total: 36, complete: true, missingFrom: null, availableDays: 18, + }); + const content = formatReport(snapshot, 'last_week', now); + assert.match(content, /최초 다운로드: \*\*14건\*\*/); + assert.match(content, /전체 최초 다운로드: \*\*36건\*\*/); + assert.match(content, /누적 기간: 2026-10-30 ~ 2026-11-16 \(UTC\)/); + assert.doesNotMatch(content, /이후 집계 확인 대기/); +}); + +test('lifetime crosses a year boundary and includes confirmed zero days', () => { + const snapshot = history('2026-12-30', '2027-01-03'); + snapshot.days['2027-01-01'].count = 0; + const result = summarizeLifetime(snapshot, new Date('2027-01-05T12:00:00Z')); + assert.equal(result.total, 8); + assert.equal(result.end, '2027-01-03'); + assert.equal(result.complete, true); +}); + +test('lifetime stops at the first gap and labels the verified earlier total', () => { + const snapshot = history('2026-11-01', '2026-11-16'); + delete snapshot.days['2026-11-04']; + snapshot.days['2026-11-05'].count = 100; + const result = summarizeLifetime(snapshot, now); + assert.equal(result.total, 6); + assert.equal(result.end, '2026-11-03'); + assert.equal(result.missingFrom, '2026-11-04'); + assert.equal(result.complete, false); + const content = formatReport(snapshot, 'last_week', now); + assert.match(content, /전체 최초 다운로드: \*\*6건\*\*/); + assert.match(content, /2026-11-03 기준 · 이후 집계 확인 대기/); + assert.equal(summarize(snapshot, 'last_week', now).complete, true); +}); + +test('a nonfinalized day cannot extend lifetime even when later dates are complete', () => { + const snapshot = history('2026-11-01', '2026-11-16'); + snapshot.days['2026-11-03'].processingDate = '2026-11-04'; + assert.equal(summarizeLifetime(snapshot, now).end, '2026-11-02'); + assert.equal(summarizeLifetime(snapshot, now).total, 4); +}); + +test('corrected daily totals replace their old contribution to lifetime', () => { + const snapshot = history('2026-11-01', '2026-11-16'); + assert.equal(summarizeLifetime(snapshot, now).total, 32); + snapshot.days['2026-11-02'] = { count: 5, processingDate: '2026-11-17' }; + assert.equal(summarizeLifetime(snapshot, now).total, 35); +}); + +test('missing launch history is always visible without inventing a lifetime zero', () => { + assert.equal(summarizeLifetime(sample(), now).configured, false); + assert.equal(summarizeLifetime(sample(), now).total, null); + const snapshot = history('2026-11-01', '2026-11-16'); + delete snapshot.days['2026-11-01']; + assert.equal(summarizeLifetime(snapshot, now).end, null); + assert.equal(summarizeLifetime(snapshot, now).total, null); + for (const input of [null, sample(), snapshot]) { + const content = formatReport(input, 'last_week', now); + assert.match(content, /전체 최초 다운로드: 확인 대기/); + assert.doesNotMatch(content, /전체 최초 다운로드: \*\*0건/); + } +}); + +test('lifetime rejects impossible launch dates and overflowing totals', () => { + assert.throws(() => summarizeLifetime({ startDate: '2026-02-30', days: {} }, now)); + const snapshot = history('2026-11-15', '2026-11-16', Number.MAX_SAFE_INTEGER); + assert.throws(() => summarizeLifetime(snapshot, now), /집계 범위/); +}); diff --git a/automation/app-store-discord/test/run-report.test.mjs b/automation/app-store-discord/test/run-report.test.mjs index 3dc32e5..1ed2d85 100644 --- a/automation/app-store-discord/test/run-report.test.mjs +++ b/automation/app-store-discord/test/run-report.test.mjs @@ -15,7 +15,7 @@ function snapshot({ start = '2026-10-13', end = '2026-11-16', count = 17 } = {}) for (let day = start; day <= end; day = addDays(day, 1)) { days[day] = { count, processingDate: addDays(day, 2) }; } - return { appId: env.ASC_APP_ID, days, syncedAt: now.toISOString(), processedInstanceIds: ['all'], pendingInstances: 0 }; + return { appId: env.ASC_APP_ID, startDate: start, days, syncedAt: now.toISOString(), processedInstanceIds: ['all'], pendingInstances: 0 }; } test('collects 35 days across multiple batches with the same reference time and sends once', async () => { @@ -167,3 +167,45 @@ test('a summary file failure preserves a successful send status without leaking assert.ok(messages.some(message => message.includes('요약 파일을 저장하지 못했습니다'))); assert.ok(messages.every(message => !message.includes(directory) && !message.includes('987654') && !message.includes('REPORT_RUN_FAILED'))); }); + +test('restored history resets cursors and persistence happens before delivery', async () => { + const events = []; + const initial = snapshot(); + const result = await runReport(env, { now, initialSnapshot: initial, send: true, + collect: async (_, previous) => { + events.push('collect'); + assert.equal(previous.processedInstanceIds, undefined); + assert.equal(previous.startDate, initial.startDate); + assert.deepEqual(previous.days, initial.days); + return snapshot(); + }, persist: async data => { events.push('persist'); assert.equal(data.startDate, initial.startDate); }, + deliver: async () => events.push('deliver'), + }); + assert.deepEqual(events, ['collect', 'persist', 'deliver']); + assert.equal(result.status, 'sent'); + await assert.rejects(runReport(env, { now, initialSnapshot: initial, send: true, + collect: async () => snapshot(), persist: async () => { throw new Error('private history'); }, + deliver: async () => assert.fail('Must not send before saving'), + }), { code: 'HISTORY_SAVE_FAILED' }); +}); + +test('delivery-only uses verified saved history without collecting again', async () => { + let calls = 0; + const result = await runReport(env, { now, initialSnapshot: snapshot(), deliverOnly: true, send: true, + collect: async () => assert.fail('Must not collect'), + deliver: async (_, content) => { calls++; assert.match(content, /전체 최초 다운로드/); }, + }); + assert.equal(calls, 1); + assert.equal(result.status, 'sent'); + await assert.rejects(runReport(env, { now, deliverOnly: true }), { code: 'HISTORY_REQUIRED' }); + await assert.rejects(runReport(env, { now, initialSnapshot: { ...snapshot(), appId: '99' }, deliverOnly: true }), { code: 'INVALID_HISTORY' }); +}); + +test('a complete weekly period with a lifetime gap is a partial report', async () => { + const data = snapshot(); + delete data.days['2026-10-20']; + const result = await runReport(env, { now, collect: async () => data }); + assert.equal(result.status, 'preview_partial'); + assert.match(result.content, /이후 집계 확인 대기/); + assert.match(result.content, /119건/); +});