From d4e052815625bc630fec3ec9f1c437b05b0d9569 Mon Sep 17 00:00:00 2001 From: sangyup Date: Tue, 17 Nov 2026 17:22:54 +0900 Subject: [PATCH 1/3] chore: add App Store download reporting scripts --- automation/app-store-discord/.env.example | 8 + automation/app-store-discord/.gitignore | 11 + automation/app-store-discord/README.md | 86 +++++ .../app-store-discord/package-lock.json | 15 + automation/app-store-discord/package.json | 15 + .../app-store-discord/scripts/preview.mjs | 9 + .../scripts/request-reports.mjs | 49 +++ .../app-store-discord/scripts/run-report.mjs | 63 ++++ automation/app-store-discord/src/apple.mjs | 319 ++++++++++++++++++ automation/app-store-discord/src/reports.mjs | 69 ++++ .../app-store-discord/src/run-report.mjs | 115 +++++++ automation/app-store-discord/src/webhook.mjs | 74 ++++ .../app-store-discord/test/apple.test.mjs | 161 +++++++++ .../app-store-discord/test/reports.test.mjs | 56 +++ .../test/run-report.test.mjs | 158 +++++++++ .../app-store-discord/test/webhook.test.mjs | 78 +++++ 16 files changed, 1286 insertions(+) create mode 100644 automation/app-store-discord/.env.example create mode 100644 automation/app-store-discord/.gitignore create mode 100644 automation/app-store-discord/README.md create mode 100644 automation/app-store-discord/package-lock.json create mode 100644 automation/app-store-discord/package.json create mode 100644 automation/app-store-discord/scripts/preview.mjs create mode 100644 automation/app-store-discord/scripts/request-reports.mjs create mode 100644 automation/app-store-discord/scripts/run-report.mjs create mode 100644 automation/app-store-discord/src/apple.mjs create mode 100644 automation/app-store-discord/src/reports.mjs create mode 100644 automation/app-store-discord/src/run-report.mjs create mode 100644 automation/app-store-discord/src/webhook.mjs create mode 100644 automation/app-store-discord/test/apple.test.mjs create mode 100644 automation/app-store-discord/test/reports.test.mjs create mode 100644 automation/app-store-discord/test/run-report.test.mjs create mode 100644 automation/app-store-discord/test/webhook.test.mjs diff --git a/automation/app-store-discord/.env.example b/automation/app-store-discord/.env.example new file mode 100644 index 0000000..7b81638 --- /dev/null +++ b/automation/app-store-discord/.env.example @@ -0,0 +1,8 @@ +# 실제 값은 .env 또는 GitHub Actions Secrets에 저장한다. Git에 커밋하지 않는다. +ASC_APP_ID=6791870747 +ASC_KEY_ID= +ASC_ISSUER_ID= +ASC_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nREPLACE_ME\n-----END PRIVATE KEY-----" +DISCORD_WEBHOOK_URL= +# 선택 사항: 여러 ONGOING 요청 중 하나를 지정할 때 사용 +ASC_REPORT_REQUEST_ID= diff --git a/automation/app-store-discord/.gitignore b/automation/app-store-discord/.gitignore new file mode 100644 index 0000000..904eeff --- /dev/null +++ b/automation/app-store-discord/.gitignore @@ -0,0 +1,11 @@ +node_modules/ +.wrangler/ +.dev.vars +.dev.vars.* +!.dev.vars.example +.env +.env.* +!.env.example +wrangler.jsonc +dist/ +*.p8 diff --git a/automation/app-store-discord/README.md b/automation/app-store-discord/README.md new file mode 100644 index 0000000..69f2d45 --- /dev/null +++ b/automation/app-store-discord/README.md @@ -0,0 +1,86 @@ +# 루티 다운로드 리포트 + +GitHub Actions가 App Store Connect의 **최초 다운로드 수**를 조회해 Discord 웹훅으로 전송한다. 별도 서버·Cloudflare·Discord 명령어용 앱은 사용하지 않는다. + +## 실행 방법 + +- **자동 전송:** 매주 수요일 10:17 KST, 지난주 월요일~일요일 **UTC** 자료. +- **수동 실행:** 저장소 → Actions → **Routee App Store Downloads** → **Run workflow**. +- 실행 브랜치는 기본 브랜치인 `develop`을 선택한다. 다른 브랜치에서는 실제 조회·전송을 실행하지 않는다. +- `period`: `last_week`(지난주), `last_7_days`(최근 7일), `last_30_days`(최근 30일). +- `send_to_discord`: 체크하면 전송하고, 해제하면 API 조회만 검증한다. 최근 7일·30일의 종료일은 실행일 UTC의 이틀 전이다. +- GitHub의 **Re-run jobs**는 중복 전송을 막기 위해 전송하지 않는다. 의도적으로 다시 보내려면 먼저 Discord 채널을 확인하고 새 **Run workflow**를 실행한다. + +수동 실행에는 저장소 쓰기 권한이 필요하다. 예약 실행은 지연될 수 있고, 공개 저장소에 60일간 활동이 없으면 GitHub가 예약 실행을 비활성화할 수 있다. + +## 집계 기준 + +`App Store Downloads Standard` 보고서에서 `Download Type = First-time Download`인 행의 `Counts`를 합산한다. Apple 계정 기준 처음 받기/구입을 누른 횟수이며 재다운로드·업데이트·회원가입 수와 구분한다. + +- 모든 세그먼트를 수집한 다음 집계한다. +- 동일한 데이터 날짜가 여러 보고서에 있으면 최신 `processingDate` 값으로 교체한다. 과거 값과 더하지 않는다. +- 해당 날짜로부터 2일 이상 뒤에 생성된 자료를 완료된 자료로 사용한다. +- 다른 다운로드 유형만 있는 날짜의 최초 다운로드는 0건이다. 날짜 자체가 없거나 자료가 미완성인 경우에는 0건으로 추정하지 않는다. +- 미확인 날짜가 있으면 **확인된 소계와 미확인 날짜**를 보낸다. 완전한 주간 합계로 표시하지 않는다. +- Apple 조회가 실패하면 수치를 만들어 보내지 않고 실행을 실패로 표시한다. +- 매 실행에서 최근 처리일 35일 내 파일을 새로 읽는다. 별도 DB·캐시가 필요 없으며 출시 이후 누적 지표는 제공하지 않는다. + +## 최초 설정 + +Apple API 접근 승인, API 키 발급, 보고서 생성 요청이 필요하다. 새 ONGOING 요청 생성은 Admin 키가 필요하고, 이후 운영 조회에는 **Sales and Reports** 권한의 팀 API 키를 사용한다. 최초 보고서 생성에는 24~48시간이 걸릴 수 있다. + +1. 초기 설정용 Admin 키로 아래 관리 명령을 실행한다. 기존 활성 ONGOING 요청이 있으면 새로 만들지 않는다. +2. 초기 설정용 키는 운영 workflow에 등록하지 않는다. 임시 키로 발급했다면 설정 후 폐기한다. +3. 운영 조회용 키와 웹훅을 저장소의 **Settings → Secrets and variables → Actions**에 등록한다. + +| Repository Secret | 내용 | +| --- | --- | +| `ROUTEE_ASC_KEY_ID` | 운영 조회용 API Key ID | +| `ROUTEE_ASC_ISSUER_ID` | 팀 Issuer ID | +| `ROUTEE_ASC_PRIVATE_KEY` | 운영 조회용 `.p8` PEM 전체 | +| `ROUTEE_DISCORD_WEBHOOK_URL` | 리포트를 받을 Discord 채널 웹훅 URL | + +대상 앱 ID는 출시용 루티 `6791870747`이다. 활성 ONGOING 요청이 여러 개라면 Repository Variable `ROUTEE_ASC_REPORT_REQUEST_ID`로 하나를 지정한다. + +처음에는 `send_to_discord`를 해제해 조회를 확인한다. 보고서가 준비된 후 전송을 실행한다. ONGOING 생성 이전의 전체 이력을 보장하지 않으며 ONE_TIME_SNAPSHOT의 과거 자료 수집은 현재 구현하지 않았다. + +## 로컬 실행 + +Node.js 22 이상이 필요하며 외부 런타임 패키지는 사용하지 않는다. workflow는 Node.js 24를 사용한다. + +```sh +cd automation/app-store-discord +npm test +npm run preview +``` + +`preview`는 명시적으로 표시된 가상 수치만 출력하며 외부에 전송하지 않는다. 실제 설정은 `.env.example`을 참고해 Git에서 제외된 `.env`에 저장한다. 기존 `.env`를 덮어쓰지 않는다. + +```sh +# 기본값은 안내만 출력. --apply일 때만 기존 요청 조회/생성을 실행한다. +node --env-file=.env scripts/request-reports.mjs --apply + +# 실제 조회만 검증. 통계 본문은 콘솔에 출력하지 않는다. +node --env-file=.env scripts/run-report.mjs --period last_week + +# 실제 Discord 전송 +node --env-file=.env scripts/run-report.mjs --period last_week --send +``` + +관리 스크립트는 PEM 대신 `ASC_PRIVATE_KEY_PATH`로 로컬 `.p8` 경로를 받을 수 있다. 운영 workflow에는 PEM을 Secret으로 전달한다. + +## 공개 저장소에서의 정보 처리 + +- 실제 다운로드 수·보고서 본문·원본 파일은 GitHub 로그, Job Summary, Artifact에 남기지 않는다. Discord에만 전송한다. +- API 키와 웹훅 URL은 코드에 넣지 않는다. 네트워크 예외 원문도 출력하지 않는다. +- PR에서는 모의 테스트만 실행하며 Secrets에 접근하지 않는다. 실제 조회는 `develop`의 예약·수동 실행에 한정한다. +- workflow 권한은 `contents: read`이며, 외부 Actions는 검증한 커밋 SHA에 고정한다. +- 웹훅 전송은 자동 재시도하지 않는다. 결과가 불확실하면 Discord 채널 확인 후 새 수동 실행을 선택한다. + +## 공식 근거 + +- [Apple 다운로드 보고서](https://developer.apple.com/documentation/analytics-reports/app-download) +- [Apple 정정 데이터 처리](https://developer.apple.com/documentation/analytics-reports/data-completeness-corrections) +- [보고서 생성·다운로드 권한](https://developer.apple.com/documentation/appstoreconnectapi/downloading-analytics-reports) +- [GitHub 예약 실행](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows#schedule) +- [GitHub 수동 실행](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/manually-run-a-workflow) diff --git a/automation/app-store-discord/package-lock.json b/automation/app-store-discord/package-lock.json new file mode 100644 index 0000000..2344353 --- /dev/null +++ b/automation/app-store-discord/package-lock.json @@ -0,0 +1,15 @@ +{ + "name": "routee-app-store-discord", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "routee-app-store-discord", + "version": "0.1.0", + "engines": { + "node": ">=22" + } + } + } +} diff --git a/automation/app-store-discord/package.json b/automation/app-store-discord/package.json new file mode 100644 index 0000000..ff2414e --- /dev/null +++ b/automation/app-store-discord/package.json @@ -0,0 +1,15 @@ +{ + "name": "routee-app-store-discord", + "version": "0.1.0", + "private": true, + "type": "module", + "engines": { + "node": ">=22" + }, + "scripts": { + "test": "node --test test/*.test.mjs", + "preview": "node scripts/preview.mjs", + "request-reports": "node scripts/request-reports.mjs", + "report": "node scripts/run-report.mjs" + } +} diff --git a/automation/app-store-discord/scripts/preview.mjs b/automation/app-store-discord/scripts/preview.mjs new file mode 100644 index 0000000..7a401a4 --- /dev/null +++ b/automation/app-store-discord/scripts/preview.mjs @@ -0,0 +1,9 @@ +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)) { + days[day] = { count: 3, processingDate: addDays(day, 2) }; +} +console.log('예시 데이터입니다. 실제 루티 통계가 아니며 Discord에 전송하지 않습니다.\n'); +console.log(formatReport({ days, syncedAt: now.toISOString() }, 'last_week', now)); diff --git a/automation/app-store-discord/scripts/request-reports.mjs b/automation/app-store-discord/scripts/request-reports.mjs new file mode 100644 index 0000000..995a6e3 --- /dev/null +++ b/automation/app-store-discord/scripts/request-reports.mjs @@ -0,0 +1,49 @@ +import { readFile } from 'node:fs/promises'; +import { createAppleJWT } from '../src/apple.mjs'; + +if (!process.argv.includes('--apply')) { + console.log('준비 작업: 앱의 기존 ONGOING 요청을 조회하고, 없으면 ONGOING 보고서 생성을 요청합니다.'); + console.log('새 요청 생성에는 Admin API 키가 필요합니다. --apply 없이는 네트워크 요청을 보내지 않습니다.'); +} else { + try { + const env = { ...process.env }; + if (env.ASC_PRIVATE_KEY_PATH && !env.ASC_PRIVATE_KEY) { + env.ASC_PRIVATE_KEY = await readFile(env.ASC_PRIVATE_KEY_PATH, 'utf8'); + } + if (!/^\d+$/.test(env.ASC_APP_ID ?? '')) throw new Error('configuration'); + const token = await createAppleJWT(env); + const origin = 'https://api.appstoreconnect.apple.com'; + const headers = { Authorization: `Bearer ${token}`, 'content-type': 'application/json' }; + let next = `${origin}/v1/apps/${env.ASC_APP_ID}/analyticsReportRequests?filter%5BaccessType%5D=ONGOING&limit=200`; + const requests = []; + const visited = new Set(); + while (next) { + const url = new URL(next, origin); + if (url.origin !== origin || visited.has(url.href) || visited.size >= 10) throw new Error('pagination'); + visited.add(url.href); + const response = await fetch(url, { headers, redirect: 'error', signal: AbortSignal.timeout(10_000) }); + if (!response.ok) throw new Error('list'); + const result = await response.json(); + if (!Array.isArray(result.data)) throw new Error('schema'); + requests.push(...result.data); + next = result.links?.next; + } + const active = requests.filter(item => item.attributes?.accessType === 'ONGOING' && item.attributes.stoppedDueToInactivity === false); + if (active.length) { + console.log(`기존 활성 ONGOING 보고서 요청 ${active.length}개를 확인했습니다. 새 요청은 생성하지 않았습니다.`); + } else { + const response = await fetch(`${origin}/v1/analyticsReportRequests`, { + method: 'POST', headers, redirect: 'error', signal: AbortSignal.timeout(10_000), + body: JSON.stringify({ data: { type: 'analyticsReportRequests', attributes: { accessType: 'ONGOING' }, + relationships: { app: { data: { type: 'apps', id: env.ASC_APP_ID } } } } }), + }); + if (!response.ok) throw new Error('creation'); + const result = await response.json(); + if (!result.data?.id) throw new Error('verification'); + console.log('ONGOING 보고서 생성 요청을 확인했습니다. 최초 생성에는 24~48시간이 걸릴 수 있습니다.'); + } + } catch { + console.error('보고서 요청 상태를 확인하지 못했습니다. API 키·권한·앱 ID를 확인하세요. 응답이 끊겼다면 재실행 시 기존 요청부터 조회합니다.'); + process.exitCode = 1; + } +} diff --git a/automation/app-store-discord/scripts/run-report.mjs b/automation/app-store-discord/scripts/run-report.mjs new file mode 100644 index 0000000..90e3ad5 --- /dev/null +++ b/automation/app-store-discord/scripts/run-report.mjs @@ -0,0 +1,63 @@ +import { appendFile } from 'node:fs/promises'; +import { pathToFileURL } from 'node:url'; + +import { ReportRunError, runReport } from '../src/run-report.mjs'; + +export function parseArguments(args, env = process.env) { + const options = { period: 'last_week', send: false, summaryPath: env.GITHUB_STEP_SUMMARY }; + const seen = new Set(); + for (let index = 0; index < args.length; index++) { + const argument = args[index]; + const [flag, ...inlineParts] = argument.split('='); + if (seen.has(flag)) throw new ReportRunError('INVALID_ARGUMENT', '같은 실행 옵션을 여러 번 지정할 수 없습니다.'); + seen.add(flag); + if (flag === '--send' && inlineParts.length === 0) options.send = true; + else if (flag === '--help' && inlineParts.length === 0) options.help = true; + else if (flag === '--period' || flag === '--summary-path') { + const value = inlineParts.length ? inlineParts.join('=') : args[++index]; + if (!value || value.startsWith('--')) throw new ReportRunError('INVALID_ARGUMENT', '실행 옵션의 값을 확인해 주세요.'); + options[flag === '--period' ? 'period' : 'summaryPath'] = value; + } else throw new ReportRunError('INVALID_ARGUMENT', '지원하지 않는 실행 옵션입니다.'); + } + return options; +} + +export async function main(args = process.argv.slice(2), env = process.env, { execute = runReport } = {}) { + let options; + 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('--send가 없으면 조회만 검증합니다. 통계 수치와 본문은 콘솔이나 GitHub 요약에 출력하지 않습니다.'); + return 0; + } + const result = await execute(env, options); + if (options.summaryPath) { + try { + await appendFile(options.summaryPath, result.summary, 'utf8'); + } catch { + console.error('실행 요약 파일을 저장하지 못했습니다. 리포트 처리 결과는 유지됩니다.'); + } + } + console.log(`루티 리포트 실행 완료: ${result.status}`); + return 0; + } catch (error) { + const safe = error instanceof ReportRunError ? error + : new ReportRunError('REPORT_RUN_FAILED', '리포트 실행을 완료하지 못했습니다.'); + const message = `${safe.code}: ${safe.message}`; + console.error(message); + const summaryPath = options?.summaryPath ?? env.GITHUB_STEP_SUMMARY; + if (summaryPath) { + try { + await appendFile(summaryPath, `## 루티 다운로드 리포트 실행\n\n- 실행 결과: 실패\n- ${message}\n`, 'utf8'); + } catch { + console.error('실행 요약 파일을 저장하지 못했습니다.'); + } + } + 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/src/apple.mjs b/automation/app-store-discord/src/apple.mjs new file mode 100644 index 0000000..a4df3fa --- /dev/null +++ b/automation/app-store-discord/src/apple.mjs @@ -0,0 +1,319 @@ +const API_ORIGIN = 'https://api.appstoreconnect.apple.com'; +const DAY_MS = 86_400_000; +const MAX_PAGES = 40; +const MAX_ITEMS = 10_000; +const MAX_SEGMENTS = 200; +const MAX_JSON_BYTES = 4 * 1024 * 1024; +const MAX_COMPRESSED_BYTES = 20 * 1024 * 1024; +const MAX_EXPANDED_BYTES = 50 * 1024 * 1024; +const MAX_FETCHES = 40; + +export class AppleReportError extends Error { + constructor(code, message) { + super(message); + this.name = 'AppleReportError'; + this.code = code; + } +} + +function fail(code, message) { + throw new AppleReportError(code, message); +} + +function required(env, name) { + const value = env[name]; + if (typeof value !== 'string' || !value.trim()) { + fail('CONFIGURATION', `${name} is required.`); + } + return value.trim(); +} + +function base64url(bytes) { + let binary = ''; + for (const byte of bytes) binary += String.fromCharCode(byte); + return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, ''); +} + +function encodedJSON(value) { + return base64url(new TextEncoder().encode(JSON.stringify(value))); +} + +export async function createAppleJWT(env, { now = new Date() } = {}) { + const keyId = required(env, 'ASC_KEY_ID'); + const issuerId = required(env, 'ASC_ISSUER_ID'); + const pem = required(env, 'ASC_PRIVATE_KEY').replaceAll('\\n', '\n'); + if (!Number.isFinite(now.getTime())) fail('CONFIGURATION', 'Invalid current time.'); + try { + const match = pem.match(/^-----BEGIN PRIVATE KEY-----\s+([A-Za-z0-9+/=\s]+)\s+-----END PRIVATE KEY-----$/); + if (!match) fail('CONFIGURATION', 'ASC_PRIVATE_KEY must be a PKCS#8 PEM private key.'); + const binary = atob(match[1].replace(/\s/g, '')); + const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0)); + const key = await crypto.subtle.importKey('pkcs8', bytes, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign']); + const issuedAt = Math.floor(now.getTime() / 1000); + const unsigned = `${encodedJSON({ alg: 'ES256', kid: keyId, typ: 'JWT' })}.${encodedJSON({ iss: issuerId, iat: issuedAt, exp: issuedAt + 900, aud: 'appstoreconnect-v1' })}`; + const signature = await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, new TextEncoder().encode(unsigned)); + return `${unsigned}.${base64url(new Uint8Array(signature))}`; + } catch (error) { + if (error instanceof AppleReportError) throw error; + fail('CONFIGURATION', 'Unable to sign the App Store Connect token. Check the API key configuration.'); + } +} + +function isDate(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 shiftDate(value, offset) { + return new Date(Date.parse(`${value}T00:00:00Z`) + offset * DAY_MS).toISOString().slice(0, 10); +} + +function resourceId(value) { + if (typeof value !== 'string' || !value || value.length > 256) fail('SCHEMA', 'Apple returned an invalid resource identifier.'); + return encodeURIComponent(value); +} + +function apiURL(value) { + let url; + try { url = new URL(value, API_ORIGIN); } catch { fail('SCHEMA', 'Apple returned an invalid API URL.'); } + if (url.origin !== API_ORIGIN || !url.pathname.startsWith('/v1/') || url.username || url.password || url.hash) { + fail('UNSAFE_URL', 'Apple returned an unexpected API URL.'); + } + return url.toString(); +} + +function downloadURL(value) { + let url; + try { url = new URL(value); } catch { fail('SCHEMA', 'Apple returned an invalid report URL.'); } + const trustedHost = url.hostname.endsWith('.apple.com') || url.hostname.endsWith('.amazonaws.com'); + if (url.protocol !== 'https:' || !trustedHost || url.username || url.password || url.port || url.hash) { + fail('UNSAFE_URL', 'Apple returned an unexpected report download host.'); + } + return url.toString(); +} + +async function boundedBytes(body, maximum) { + if (!body) fail('SCHEMA', 'Apple returned an empty response body.'); + const reader = body.getReader(); + const chunks = []; + let total = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + total += value.byteLength; + if (total > maximum) { + await reader.cancel(); + fail('LIMIT', 'The report exceeds the configured processing size limit.'); + } + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + const output = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + output.set(chunk, offset); + offset += chunk.byteLength; + } + return output; +} + +function parseTSV(text) { + const rows = []; + let row = []; + let field = ''; + let quoted = false; + let closedQuote = false; + const source = text.replace(/^\uFEFF/, ''); + const endField = () => { row.push(field); field = ''; closedQuote = false; }; + const endRow = () => { + endField(); + if (row.some((value) => value !== '')) rows.push(row); + row = []; + if (rows.length > 500_000) fail('LIMIT', 'The report contains too many rows.'); + }; + for (let index = 0; index < source.length; index += 1) { + const character = source[index]; + if (quoted) { + if (character === '"' && source[index + 1] === '"') { field += '"'; index += 1; } + else if (character === '"') { quoted = false; closedQuote = true; } + else field += character; + } else if (character === '\t') endField(); + else if (character === '\n' || character === '\r') { + if (character === '\r' && source[index + 1] === '\n') index += 1; + endRow(); + } else if (character === '"' && !field && !closedQuote) quoted = true; + else { + if (closedQuote || character === '"') fail('SCHEMA', 'The report contains malformed TSV quoting.'); + field += character; + } + } + if (quoted) fail('SCHEMA', 'The report contains unterminated TSV quoting.'); + if (field || row.length || closedQuote) endRow(); + return rows; +} + +function accumulate(text, appId, processingDate, totals, oldestDate) { + const [header, ...rows] = parseTSV(text); + if (!header || new Set(header).size !== header.length) fail('SCHEMA', 'The report has missing or duplicate columns.'); + const columns = ['Date', 'App Apple Identifier', 'Download Type', 'Counts'].map((name) => header.indexOf(name)); + if (columns.some((index) => index < 0)) fail('SCHEMA', 'The report is missing required download columns.'); + for (const row of rows) { + if (row.length !== header.length) fail('SCHEMA', 'The report contains a malformed row.'); + const [date, rowAppId, type, rawCount] = columns.map((index) => row[index].trim()); + if (rowAppId !== appId) continue; + if (!isDate(date) || date > processingDate || !type || !/^\d+$/.test(rawCount)) fail('SCHEMA', 'The report contains invalid download values.'); + const count = Number(rawCount); + if (!Number.isSafeInteger(count)) fail('SCHEMA', 'The report contains an invalid download count.'); + if (date < oldestDate) continue; + // A date with only other download types is a known zero. An absent date stays unknown. + const previous = totals.get(date) ?? 0; + const next = previous + (type.toLowerCase().replace(/\s+/g, ' ') === 'first-time download' ? count : 0); + if (!Number.isSafeInteger(next)) fail('SCHEMA', 'The download total exceeds the supported range.'); + totals.set(date, next); + } +} + +/** Read existing ONGOING reports. This function never creates report requests or mutates previous. */ +export async function collectDownloads(env, previous = { days: {} }, { fetchImpl = fetch, now = new Date() } = {}) { + const appId = required(env, 'ASC_APP_ID'); + if (!/^\d+$/.test(appId)) fail('CONFIGURATION', 'ASC_APP_ID must be a numeric Apple app ID.'); + 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); + 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.'); + for (const [date, value] of Object.entries(previous.days)) { + if (!isDate(date) || !value || !Number.isSafeInteger(value.count) || value.count < 0 || !isDate(value.processingDate) || value.processingDate < date) { + fail('CACHE_SCHEMA', 'The saved download data is invalid.'); + } + if (date >= oldestDate && date <= today) days[date] = { count: value.count, processingDate: value.processingDate }; + } + const token = await createAppleJWT(env, { now }); + const maxInstances = Number(env.ASC_MAX_INSTANCES_PER_SYNC ?? 12); + if (!Number.isInteger(maxInstances) || maxInstances < 1 || maxInstances > 20) fail('CONFIGURATION', 'ASC_MAX_INSTANCES_PER_SYNC must be an integer from 1 to 20.'); + let requestCount = 0; + let downloadedSegments = 0; + let expandedBytes = 0; + + async function request(url, appleAPI) { + if (requestCount >= MAX_FETCHES) fail('FETCH_BUDGET', 'The current report sync reached its request budget.'); + requestCount += 1; + try { + const response = await fetchImpl(url, { + headers: appleAPI ? { Authorization: `Bearer ${token}`, Accept: 'application/json' } : {}, + redirect: 'error', + signal: AbortSignal.timeout(10_000), + }); + if (!response.ok) fail('HTTP', `${appleAPI ? 'Apple API' : 'Report download'} failed (HTTP ${response.status}).`); + return response; + } catch (error) { + if (error instanceof AppleReportError) throw error; + fail('NETWORK', `${appleAPI ? 'Apple API' : 'Report download'} could not be completed. Retry later.`); + } + } + + async function list(path) { + let next = apiURL(path); + const visited = new Set(); + const items = new Map(); + while (next) { + if (visited.has(next)) fail('PAGINATION', 'Apple returned a pagination cycle.'); + if (visited.size >= MAX_PAGES) fail('LIMIT', 'Apple returned too many report pages.'); + visited.add(next); + const response = await request(next, true); + let json; + try { + const bytes = await boundedBytes(response.body, MAX_JSON_BYTES); + json = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); + } catch (error) { + if (error instanceof AppleReportError) throw error; + fail('SCHEMA', 'Apple returned invalid report metadata.'); + } + if (!Array.isArray(json.data)) fail('SCHEMA', 'Apple returned an invalid resource list.'); + for (const item of json.data) { + resourceId(item?.id); + if (!item.attributes || typeof item.attributes !== 'object') fail('SCHEMA', 'Apple returned incomplete resource metadata.'); + const earlier = items.get(item.id); + if (earlier && JSON.stringify(earlier.attributes) !== JSON.stringify(item.attributes)) fail('SCHEMA', 'Apple returned inconsistent duplicate resources.'); + items.set(item.id, item); + if (items.size > MAX_ITEMS) fail('LIMIT', 'Apple returned too many report resources.'); + } + const link = json.links?.next; + if (link != null && typeof link !== 'string') fail('SCHEMA', 'Apple returned invalid pagination metadata.'); + next = link ? apiURL(link) : null; + } + return [...items.values()]; + } + + const requests = await list(`/v1/apps/${appId}/analyticsReportRequests?filter%5BaccessType%5D=ONGOING&limit=200`); + const requestedId = typeof env.ASC_REPORT_REQUEST_ID === 'string' ? env.ASC_REPORT_REQUEST_ID.trim() : ''; + const active = requests.filter((item) => item.attributes.accessType === 'ONGOING' && item.attributes.stoppedDueToInactivity === false && (!requestedId || item.id === requestedId)); + if (active.length !== 1) fail('REPORT_REQUEST', 'A single active ONGOING report request is required. Complete the App Store Connect report setup.'); + const requestId = active[0].id; + const reports = await list(`/v1/analyticsReportRequests/${resourceId(requestId)}/reports?limit=200`); + const standard = reports.filter((item) => item.attributes.name === 'App Store Downloads Standard'); + if (standard.length !== 1) fail('REPORT_NOT_READY', 'The App Store Downloads Standard report is not available yet. Initial generation can take 24–48 hours.'); + const reportId = standard[0].id; + const instances = await list(`/v1/analyticsReports/${resourceId(reportId)}/instances?filter%5Bgranularity%5D=DAILY&limit=200`); + const recent = instances.filter((instance) => { + const { processingDate, granularity } = instance.attributes; + if (!isDate(processingDate) || processingDate > today || granularity !== 'DAILY') fail('SCHEMA', 'Apple returned invalid daily report metadata.'); + return processingDate >= earliestProcessingDate; + }).sort((left, right) => right.attributes.processingDate.localeCompare(left.attributes.processingDate)); + if (previous.processedInstanceIds != null && (!Array.isArray(previous.processedInstanceIds) || previous.processedInstanceIds.some((id) => typeof id !== 'string'))) { + fail('CACHE_SCHEMA', 'The saved processed report identifiers are invalid.'); + } + const availableIds = new Set(recent.map((instance) => instance.id)); + const processed = new Set((previous.processedInstanceIds ?? []).filter((id) => availableIds.has(id))); + let completedInstances = 0; + + for (const instance of recent) { + if (processed.has(instance.id)) continue; + if (completedInstances >= maxInstances || requestCount >= MAX_FETCHES) break; + const processingDate = instance.attributes.processingDate; + const totals = new Map(); + try { + const segments = await list(`/v1/analyticsReportInstances/${resourceId(instance.id)}/segments?limit=200`); + if (segments.length === 0) fail('REPORT_NOT_READY', 'A report instance has no downloadable segments yet. Retry later.'); + // Leave an instance entirely pending if its complete set cannot fit this run. + if (segments.length > MAX_FETCHES - requestCount) break; + for (const segment of segments) { + downloadedSegments += 1; + if (downloadedSegments > MAX_SEGMENTS) fail('LIMIT', 'The report contains too many download segments.'); + const response = await request(downloadURL(segment.attributes.url), false); + try { + const compressed = await boundedBytes(response.body, MAX_COMPRESSED_BYTES); + const inflated = new Blob([compressed]).stream().pipeThrough(new DecompressionStream('gzip')); + const bytes = await boundedBytes(inflated, MAX_EXPANDED_BYTES); + expandedBytes += bytes.byteLength; + if (expandedBytes > 100 * 1024 * 1024) fail('LIMIT', 'The report collection exceeds the processing size limit.'); + accumulate(new TextDecoder('utf-8', { fatal: true }).decode(bytes), appId, processingDate, totals, oldestDate); + } catch (error) { + if (error instanceof AppleReportError) throw error; + fail('SCHEMA', 'A report segment could not be decompressed or decoded.'); + } + } + } catch (error) { + if (error instanceof AppleReportError && error.code === 'FETCH_BUDGET') break; + throw error; + } + for (const [date, count] of totals) { + const saved = days[date]; + if (saved?.processingDate === processingDate && saved.count !== count) fail('CONFLICTING_REPORTS', 'Reports with the same processing date disagree. Retry after Apple finishes processing.'); + if (!saved || processingDate >= saved.processingDate) days[date] = { count, processingDate }; + } + processed.add(instance.id); + completedInstances += 1; + } + return { + appId, 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/reports.mjs b/automation/app-store-discord/src/reports.mjs new file mode 100644 index 0000000..c1e807d --- /dev/null +++ b/automation/app-store-discord/src/reports.mjs @@ -0,0 +1,69 @@ +const DAY_MS = 86_400_000; +export const PERIODS = new Set(['last_week', 'last_7_days', 'last_30_days']); + +export function dateOnly(value) { + return new Date(value).toISOString().slice(0, 10); +} + +export function addDays(value, count) { + return dateOnly(Date.parse(`${value}T00:00:00Z`) + count * DAY_MS); +} + +export function lastWeek(now = new Date()) { + const today = dateOnly(now); + const monday = addDays(today, -((now.getUTCDay() + 6) % 7)); + return { start: addDays(monday, -7), end: addDays(monday, -1) }; +} + +function finalized(day, record, now) { + return record && Number.isSafeInteger(record.count) && record.count >= 0 + && /^\d{4}-\d{2}-\d{2}$/.test(record.processingDate) + && record.processingDate >= addDays(day, 2) + && day <= addDays(dateOnly(now), -2); +} + +export function summarize(snapshot, period = 'last_week', now = new Date()) { + if (!PERIODS.has(period)) throw new Error('지원하지 않는 조회 기간입니다.'); + const days = snapshot?.days ?? {}; + const available = Object.keys(days).filter(day => finalized(day, days[day], now)).sort(); + let range; + if (period === 'last_week') { + range = lastWeek(now); + } else { + const end = addDays(dateOnly(now), -2); + range = { start: addDays(end, period === 'last_30_days' ? -29 : -6), end }; + } + const missing = []; + let total = 0; + let count = 0; + for (let day = range.start; day <= range.end; day = addDays(day, 1)) { + if (finalized(day, days[day], now)) { + total += days[day].count; + count++; + } else { + missing.push(day); + } + } + if (!Number.isSafeInteger(total)) throw new Error('집계 범위를 초과했습니다.'); + return { ...range, total, availableDays: count, missing, complete: missing.length === 0, + syncedAt: snapshot?.syncedAt ?? null, latestDate: available.at(-1) ?? null }; +} + +export function formatReport(snapshot, period = 'last_week', now = new Date()) { + const report = summarize(snapshot, period, 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) { + lines.push(`최초 다운로드: **${report.total.toLocaleString('ko-KR')}건**`); + } else { + lines.push('**전체 합계 확인 대기**', + `확인된 ${report.availableDays}일의 소계: ${report.total.toLocaleString('ko-KR')}건`, + `미확인 날짜: ${report.missing.join(', ')}`, + '보고서가 없거나 아직 완성되지 않은 날짜는 0건으로 계산하지 않습니다.'); + } + 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 보고서를 수집하지 못했습니다.'); + lines.push('Apple 계정 기준 최초 받기/구입 · 재다운로드/업데이트 제외'); + return lines.join('\n'); +} diff --git a/automation/app-store-discord/src/run-report.mjs b/automation/app-store-discord/src/run-report.mjs new file mode 100644 index 0000000..0e34fe6 --- /dev/null +++ b/automation/app-store-discord/src/run-report.mjs @@ -0,0 +1,115 @@ +import { collectDownloads } from './apple.mjs'; +import { formatReport, PERIODS, summarize } from './reports.mjs'; +import { sendWebhook } from './webhook.mjs'; + +export class ReportRunError extends Error { + constructor(code, message, delivery) { + super(message); + this.name = 'ReportRunError'; + this.code = code; + if (delivery) this.delivery = delivery; + } +} + +function fail(code, message) { + throw new ReportRunError(code, message); +} + +function validateSnapshot(snapshot, appId) { + if (!snapshot || snapshot.appId !== appId || !snapshot.days || typeof snapshot.days !== 'object' + || Array.isArray(snapshot.days) || !Number.isSafeInteger(snapshot.pendingInstances) + || snapshot.pendingInstances < 0 || !Array.isArray(snapshot.processedInstanceIds) + || snapshot.processedInstanceIds.some(id => typeof id !== 'string' || !id) + || new Set(snapshot.processedInstanceIds).size !== snapshot.processedInstanceIds.length + || typeof snapshot.syncedAt !== 'string' || !Number.isFinite(Date.parse(snapshot.syncedAt))) { + fail('INVALID_COLLECTION_RESULT', 'Apple 보고서 수집 결과를 확인할 수 없습니다.'); + } +} + +function collectionError(error) { + if (error?.code === 'REPORT_NOT_READY') { + return new ReportRunError('APPLE_REPORT_NOT_READY', 'Apple 보고서가 아직 준비되지 않았습니다. 최초 생성에는 24~48시간이 걸릴 수 있습니다.'); + } + if (error?.code === 'REPORT_REQUEST') { + return new ReportRunError('APPLE_REPORT_REQUEST_REQUIRED', '활성 ONGOING 보고서 요청을 먼저 설정해 주세요.'); + } + return new ReportRunError('APPLE_COLLECTION_FAILED', 'Apple 보고서를 수집하지 못했습니다. API 키·권한·보고서 상태를 확인해 주세요.'); +} + +function publicSummary(report, status) { + const label = { + preview: '조회 검증 완료 · 디스코드 전송 안 함', + preview_partial: '조회 검증 완료 · 일부 자료 미확인 · 디스코드 전송 안 함', + sent: '디스코드 전송 완료', + sent_partial: '디스코드 전송 완료 · 일부 자료 미확인', + }[status]; + // This repository is public. Counts, raw reports and message text must never appear here. + return ['## 루티 다운로드 리포트 실행', '', + `- 집계 기간: ${report.start} ~ ${report.end} (UTC)`, + `- 실행 결과: ${label}`, + '- 실제 다운로드 수와 리포트 본문은 GitHub 로그·요약에 기록하지 않습니다.', ''].join('\n'); +} + +/** Stateless per-run collection. 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, + collect = collectDownloads, deliver = sendWebhook, +} = {}) { + if (!PERIODS.has(period)) fail('INVALID_PERIOD', '조회 기간은 last_week, last_7_days, last_30_days 중 하나여야 합니다.'); + if (typeof send !== 'boolean' || !Number.isFinite(now.getTime()) + || !Number.isInteger(maxRounds) || maxRounds < 1 || maxRounds > 10) { + fail('INVALID_OPTIONS', '리포트 실행 설정을 확인해 주세요.'); + } + if (send) { + const attempt = Number(env.GITHUB_RUN_ATTEMPT ?? 1); + if (!Number.isInteger(attempt) || attempt < 1) fail('INVALID_RUN_ATTEMPT', 'GitHub 실행 회차를 확인할 수 없습니다.'); + if (attempt > 1) { + fail('REPLAY_BLOCKED', '중복 전송을 막기 위해 재실행에서는 전송하지 않습니다. Discord 채널을 확인한 뒤 새 Run workflow로 실행해 주세요.'); + } + } + const collectionEnv = { ...env, 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++) { + const previousIds = new Set(snapshot.processedInstanceIds ?? []); + let next; + try { + next = await collect(collectionEnv, snapshot, { now }); + } catch (error) { + throw collectionError(error); + } + validateSnapshot(next, env.ASC_APP_ID); + snapshot = next; + if (snapshot.pendingInstances === 0) { + finished = true; + break; + } + if (!snapshot.processedInstanceIds.some(id => !previousIds.has(id))) { + fail('COLLECTION_NO_PROGRESS', '남은 보고서를 수집하지 못했습니다. 파일 크기나 수집 한도를 확인해 주세요.'); + } + } + if (!finished) fail('COLLECTION_LIMIT_REACHED', '보고서 수집이 실행 한도 안에 완료되지 않아 전송하지 않았습니다.'); + + let report; + let content; + try { + report = summarize(snapshot, period, now); + content = formatReport(snapshot, period, now); + } catch { + fail('REPORT_FORMAT_FAILED', '수집 자료를 리포트로 변환하지 못해 전송하지 않았습니다.'); + } + let status = report.complete ? 'preview' : 'preview_partial'; + if (send) { + try { + await deliver(env.DISCORD_WEBHOOK_URL, content); + } catch (error) { + const knownFailure = error?.delivery === 'not_sent'; + throw new ReportRunError(knownFailure ? 'WEBHOOK_NOT_SENT' : 'WEBHOOK_DELIVERY_UNCERTAIN', + knownFailure ? '디스코드가 전송을 거절했습니다. 웹훅 설정을 확인해 주세요.' + : '디스코드 전송 결과를 확인할 수 없습니다. 재전송하기 전에 채널을 확인해 주세요.', + knownFailure ? 'not_sent' : 'unknown'); + } + status = report.complete ? 'sent' : 'sent_partial'; + } + return { snapshot, content, status, summary: publicSummary(report, status) }; +} diff --git a/automation/app-store-discord/src/webhook.mjs b/automation/app-store-discord/src/webhook.mjs new file mode 100644 index 0000000..c297db3 --- /dev/null +++ b/automation/app-store-discord/src/webhook.mjs @@ -0,0 +1,74 @@ +const ID_PATTERN = /^\d{1,25}$/; + +export class WebhookDeliveryError extends Error { + constructor(code, message, delivery, httpStatus) { + super(message); + this.name = "WebhookDeliveryError"; + this.code = code; + // unknown means Discord may have accepted the message; do not retry automatically. + this.delivery = delivery; + if (httpStatus !== undefined) this.httpStatus = httpStatus; + } +} + +function webhookEndpoint(value) { + let url; + try { + url = new URL(value); + } catch { + throw new WebhookDeliveryError("INVALID_WEBHOOK", "디스코드 웹훅 주소를 확인해 주세요.", "not_sent"); + } + if (url.protocol !== "https:" || url.hostname !== "discord.com" || url.port || url.username + || url.password || url.hash + || !/^\/api\/(?:v10\/)?webhooks\/\d{1,25}\/[A-Za-z\d._-]+$/.test(url.pathname) + || [...url.searchParams.keys()].some((key) => !["thread_id", "wait"].includes(key)) + || (url.searchParams.has("thread_id") && !ID_PATTERN.test(url.searchParams.get("thread_id")))) { + throw new WebhookDeliveryError("INVALID_WEBHOOK", "디스코드 웹훅 주소를 확인해 주세요.", "not_sent"); + } + url.searchParams.set("wait", "true"); + return url; +} + +/** Sends once. Callers must persist an uncertain outcome instead of blindly retrying. */ +export async function sendWebhook(webhookURL, content, { fetchImpl = fetch } = {}) { + const url = webhookEndpoint(webhookURL); + if (typeof content !== "string" || !content.trim() || content.length > 2000) { + throw new WebhookDeliveryError("INVALID_MESSAGE", "전송할 리포트 형식을 확인해 주세요.", "not_sent"); + } + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 10_000); + try { + const response = await fetchImpl(url.toString(), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ content, allowed_mentions: { parse: [] } }), + signal: controller.signal, + redirect: "error", + }); + if (!response.ok) { + const notSent = response.status >= 400 && response.status < 500 && response.status !== 408; + throw new WebhookDeliveryError( + response.status === 429 ? "WEBHOOK_RATE_LIMITED" : "WEBHOOK_REJECTED", + "디스코드 리포트 전송을 완료하지 못했습니다.", + notSent ? "not_sent" : "unknown", + response.status, + ); + } + let result; + try { + result = await response.json(); + } catch { + throw new WebhookDeliveryError("WEBHOOK_RESPONSE_UNKNOWN", "디스코드 전송 결과를 확인할 수 없습니다.", "unknown"); + } + if (typeof result?.id !== "string" || !ID_PATTERN.test(result.id)) { + throw new WebhookDeliveryError("WEBHOOK_RESPONSE_UNKNOWN", "디스코드 전송 결과를 확인할 수 없습니다.", "unknown"); + } + return { id: result.id }; + } catch (error) { + if (error instanceof WebhookDeliveryError) throw error; + // Fetch errors may include the token-bearing URL. Never retain the raw error/cause. + throw new WebhookDeliveryError("WEBHOOK_DELIVERY_UNKNOWN", "디스코드 전송 결과를 확인할 수 없습니다.", "unknown"); + } finally { + clearTimeout(timeout); + } +} diff --git a/automation/app-store-discord/test/apple.test.mjs b/automation/app-store-discord/test/apple.test.mjs new file mode 100644 index 0000000..655123b --- /dev/null +++ b/automation/app-store-discord/test/apple.test.mjs @@ -0,0 +1,161 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { gzipSync } from 'node:zlib'; + +import { collectDownloads, createAppleJWT } from '../src/apple.mjs'; + +const NOW = new Date('2026-11-19T04:00:00Z'); +const API = 'https://api.appstoreconnect.apple.com'; +const HEADER = 'Date\tApp Apple Identifier\tDownload Type\tCounts\n'; +const keys = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify']); +const privateBytes = new Uint8Array(await crypto.subtle.exportKey('pkcs8', keys.privateKey)); +const privatePEM = `-----BEGIN PRIVATE KEY-----\n${Buffer.from(privateBytes).toString('base64')}\n-----END PRIVATE KEY-----`; +const ENV = { ASC_APP_ID: '1234', ASC_KEY_ID: 'KEY123', ASC_ISSUER_ID: 'issuer-id', ASC_PRIVATE_KEY: privatePEM }; + +function row(date, count, type = 'First-time Download', appId = '1234') { + return `${date}\t${appId}\t${type}\t${count}\n`; +} + +function metadata(id, attributes) { return { id, attributes }; } +function page(data, next = null) { return Response.json({ data, links: { next } }); } + +function fixture(instances, override) { + const calls = []; + const fetchImpl = async (input, options) => { + const url = new URL(input); + calls.push({ url, options }); + const changed = await override?.(url, options, calls); + if (changed) return changed; + if (url.pathname === '/v1/apps/1234/analyticsReportRequests') { + return page([metadata('request', { accessType: 'ONGOING', stoppedDueToInactivity: false })]); + } + if (url.pathname === '/v1/analyticsReportRequests/request/reports') { + return page([metadata('detailed', { name: 'App Store Downloads Detailed' }), metadata('report', { name: 'App Store Downloads Standard' })]); + } + if (url.pathname === '/v1/analyticsReports/report/instances') { + return page(instances.map((item) => metadata(item.id, { granularity: 'DAILY', processingDate: item.processingDate }))); + } + for (const instance of instances) { + if (url.pathname === `/v1/analyticsReportInstances/${instance.id}/segments`) { + return page(instance.segments.map((_, index) => metadata(`${instance.id}-${index}`, { url: `https://reports.s3.amazonaws.com/${instance.id}/${index}.gz?signature=secret` }))); + } + for (let index = 0; index < instance.segments.length; index += 1) { + if (url.pathname === `/${instance.id}/${index}.gz`) return new Response(gzipSync(HEADER + instance.segments[index])); + } + } + throw new Error('Unexpected mock URL.'); + }; + return { calls, fetchImpl }; +} + +test('JWT has valid ES256 signature, Apple audience, and a 15 minute lifetime', async () => { + const token = await createAppleJWT(ENV, { now: NOW }); + const [header, payload, signature] = token.split('.'); + assert.deepEqual(JSON.parse(Buffer.from(header, 'base64url')), { alg: 'ES256', kid: 'KEY123', typ: 'JWT' }); + const claims = JSON.parse(Buffer.from(payload, 'base64url')); + assert.equal(claims.iss, ENV.ASC_ISSUER_ID); + assert.equal(claims.aud, 'appstoreconnect-v1'); + assert.equal(claims.iat, NOW.getTime() / 1000); + assert.equal(claims.exp - claims.iat, 900); + assert.equal(await crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, keys.publicKey, Buffer.from(signature, 'base64url'), new TextEncoder().encode(`${header}.${payload}`)), true); +}); + +test('newer processing dates replace old totals; all segments and download types are handled', async () => { + const { fetchImpl, calls } = fixture([ + { id: 'older', processingDate: '2026-11-17', segments: [row('2026-11-16', 300)] }, + { id: 'newer', processingDate: '2026-11-18', segments: [row('2026-11-16', 2), row('2026-11-16', 3) + row('2026-11-17', 8, 'Redownload') + row('2026-11-15', 900, 'First-time Download', '9999')] }, + ]); + const result = await collectDownloads(ENV, undefined, { fetchImpl, now: NOW }); + assert.deepEqual(result.days, { + '2026-11-16': { count: 5, processingDate: '2026-11-18' }, + '2026-11-17': { count: 0, processingDate: '2026-11-18' }, + }); + assert.equal(result.appId, '1234'); + assert.equal(result.pendingInstances, 0); + assert.equal(result.syncedAt, NOW.toISOString()); + for (const call of calls) { + assert.equal(call.options.redirect, 'error'); + if (call.url.origin === API) assert.match(call.options.headers.Authorization, /^Bearer /); + else assert.deepEqual(call.options.headers, {}); + } +}); + +test('paginates every collection and deduplicates repeated instance IDs', async () => { + const item = { id: 'one', processingDate: '2026-11-18', segments: [row('2026-11-16', 4), row('2026-11-16', 6)] }; + const { fetchImpl, calls } = fixture([item], (url) => { + if (url.origin !== API) return; + if (!url.searchParams.has('cursor')) return page([], `${url.origin}${url.pathname}?cursor=next`); + if (url.pathname.endsWith('/instances')) { + const resource = metadata('one', { granularity: 'DAILY', processingDate: '2026-11-18' }); + return page([resource, resource]); + } + }); + const result = await collectDownloads(ENV, undefined, { fetchImpl, now: NOW }); + assert.equal(result.days['2026-11-16'].count, 10); + assert.equal(calls.filter((call) => call.url.origin !== API).length, 2); + assert.deepEqual(result.processedInstanceIds, ['one']); +}); + +test('limits cold-start work and resumes pending immutable instances on the next sync', async () => { + const instances = [16, 17, 18].map((day) => ({ id: `day-${day}`, processingDate: `2026-11-${day}`, segments: [row(`2026-11-${day - 2}`, day)] })); + const first = fixture(instances); + const firstResult = await collectDownloads({ ...ENV, ASC_MAX_INSTANCES_PER_SYNC: '2' }, undefined, { fetchImpl: first.fetchImpl, now: NOW }); + assert.equal(firstResult.pendingInstances, 1); + assert.deepEqual(firstResult.processedInstanceIds, ['day-18', 'day-17']); + const second = fixture(instances); + const secondResult = await collectDownloads(ENV, firstResult, { fetchImpl: second.fetchImpl, now: NOW }); + assert.equal(secondResult.pendingInstances, 0); + assert.equal(Object.keys(secondResult.days).length, 3); + assert.equal(second.calls.filter((call) => call.url.origin !== API).length, 1); + assert.equal(firstResult.pendingInstances, 1); +}); + +test('request budget keeps an unfinished multi-segment instance entirely pending', async () => { + const { fetchImpl, calls } = fixture([ + { id: 'newest', processingDate: '2026-11-18', segments: Array.from({ length: 20 }, () => row('2026-11-16', 1)) }, + { id: 'older', processingDate: '2026-11-17', segments: Array.from({ length: 20 }, () => row('2026-11-15', 1)) }, + ]); + const result = await collectDownloads(ENV, undefined, { fetchImpl, now: NOW }); + assert.deepEqual(result.days, { '2026-11-16': { count: 20, processingDate: '2026-11-18' } }); + assert.deepEqual(result.processedInstanceIds, ['newest']); + assert.equal(result.pendingInstances, 1); + assert.ok(calls.length <= 40); + assert.equal(calls.some((call) => call.url.pathname.startsWith('/older/')), false); +}); + +test('a failed collection never changes old state or leaks download URLs in the error', async () => { + const previous = { appId: '1234', days: { '2026-11-15': { count: 2, processingDate: '2026-11-17' } }, processedInstanceIds: [] }; + const before = structuredClone(previous); + const { fetchImpl } = fixture([ + { id: 'success', processingDate: '2026-11-18', segments: [row('2026-11-16', 9)] }, + { id: 'failure', processingDate: '2026-11-17', segments: [row('2026-11-15', 2)] }, + ], (url) => { + if (url.pathname === '/failure/0.gz') throw new Error(`Network error at ${url}`); + }); + await assert.rejects(collectDownloads(ENV, previous, { fetchImpl, now: NOW }), (error) => { + assert.equal(error.code, 'NETWORK'); + assert.equal(error.message.includes('signature'), false); + return true; + }); + assert.deepEqual(previous, before); +}); + +test('rejects pagination to another origin and cyclic pages without forwarding authorization', async () => { + const unsafe = fixture([], () => page([], 'https://attacker.invalid/v1/next')); + await assert.rejects(collectDownloads(ENV, undefined, { fetchImpl: unsafe.fetchImpl, now: NOW }), { code: 'UNSAFE_URL' }); + assert.equal(unsafe.calls.length, 1); + const cyclic = fixture([], (url) => page([], url.toString())); + await assert.rejects(collectDownloads(ENV, undefined, { fetchImpl: cyclic.fetchImpl, now: NOW }), { code: 'PAGINATION' }); + assert.equal(cyclic.calls.length, 1); +}); + +test('validates schema and refuses inactive requests or a different app cache', async () => { + const invalid = fixture([{ id: 'bad', processingDate: '2026-11-18', segments: [] }], (url) => { + if (url.pathname.endsWith('/segments')) return page([metadata('bad', { url: 'https://reports.s3.amazonaws.com/bad.gz' })]); + if (url.pathname === '/bad.gz') return new Response(gzipSync('Date\tCounts\n2026-11-16\t4\n')); + }); + await assert.rejects(collectDownloads(ENV, undefined, { fetchImpl: invalid.fetchImpl, now: NOW }), { code: 'SCHEMA' }); + const inactive = fixture([], () => page([metadata('request', { accessType: 'ONGOING', stoppedDueToInactivity: true })])); + 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' }); +}); diff --git a/automation/app-store-discord/test/reports.test.mjs b/automation/app-store-discord/test/reports.test.mjs new file mode 100644 index 0000000..1be18bf --- /dev/null +++ b/automation/app-store-discord/test/reports.test.mjs @@ -0,0 +1,56 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { addDays, formatReport, lastWeek, summarize } from '../src/reports.mjs'; + +const now = new Date('2026-11-18T01:17:00Z'); +function sample() { + const days = {}; + for (let date = '2026-11-09'; date <= '2026-11-15'; date = addDays(date, 1)) { + days[date] = { count: 3, processingDate: addDays(date, 2) }; + } + return { days, syncedAt: now.toISOString() }; +} + +test('last week is Monday–Sunday UTC across year boundary', () => { + assert.deepEqual(lastWeek(now), { start: '2026-11-09', end: '2026-11-15' }); + assert.deepEqual(lastWeek(new Date('2027-01-04T01:00:00Z')), + { start: '2026-12-28', end: '2027-01-03' }); +}); + +test('weekly report totals all seven finalized days including explicit zero', () => { + const snapshot = sample(); + snapshot.days['2026-11-10'].count = 0; + const result = summarize(snapshot, 'last_week', now); + assert.equal(result.total, 18); + assert.equal(result.complete, true); + assert.match(formatReport(snapshot, 'last_week', now), /18건/); +}); + +test('absent dates are missing, not zero', () => { + const snapshot = sample(); + delete snapshot.days['2026-11-11']; + assert.equal(summarize(snapshot, 'last_week', now).complete, false); + assert.match(formatReport(snapshot, 'last_week', now), /전체 합계 확인 대기/); + assert.match(formatReport(snapshot, 'last_week', now), /미확인 날짜: 2026-11-11/); +}); + +test('old partial data does not become finalized merely by waiting', () => { + const snapshot = sample(); + snapshot.days['2026-11-15'].processingDate = '2026-11-16'; + assert.deepEqual(summarize(snapshot, 'last_week', now).missing, ['2026-11-15']); +}); + +test('rolling range stays relative to now so an outage cannot disguise an old period as recent', () => { + const result = summarize(sample(), 'last_7_days', now); + assert.equal(result.end, '2026-11-16'); + assert.equal(result.start, '2026-11-10'); + assert.equal(result.total, 18); + assert.equal(result.complete, false); + assert.equal(summarize(sample(), 'last_30_days', now).missing.length, 23); +}); + +test('empty snapshot cannot report a complete zero', () => { + const report = summarize(null, 'last_week', now); + assert.equal(report.complete, false); + assert.equal(report.missing.length, 7); +}); diff --git a/automation/app-store-discord/test/run-report.test.mjs b/automation/app-store-discord/test/run-report.test.mjs new file mode 100644 index 0000000..476d60d --- /dev/null +++ b/automation/app-store-discord/test/run-report.test.mjs @@ -0,0 +1,158 @@ +import assert from 'node:assert/strict'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; + +import { main, parseArguments } from '../scripts/run-report.mjs'; +import { addDays } from '../src/reports.mjs'; +import { ReportRunError, runReport } from '../src/run-report.mjs'; + +const now = new Date('2026-11-18T01:17:00Z'); +const env = { ASC_APP_ID: '123', DISCORD_WEBHOOK_URL: 'https://discord.com/api/webhooks/123/private-token' }; +function snapshot({ start = '2026-10-13', end = '2026-11-16', count = 17 } = {}) { + const days = {}; + 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 }; +} + +test('collects 35 days across multiple batches with the same reference time and sends once', async () => { + let calls = 0; + let deliveries = 0; + const result = await runReport(env, { now, send: true, collect: async (config, previous, options) => { + calls++; + assert.equal(config.ASC_MAX_INSTANCES_PER_SYNC, '20'); + assert.equal(options.now, now); + if (calls === 1) { + assert.deepEqual(previous, { days: {} }); + return { ...snapshot({ start: '2026-10-29' }), processedInstanceIds: ['first'], pendingInstances: 15 }; + } + assert.deepEqual(previous.processedInstanceIds, ['first']); + return { ...snapshot(), processedInstanceIds: ['first', 'second'] }; + }, deliver: async (url, content) => { + deliveries++; + assert.equal(url, env.DISCORD_WEBHOOK_URL); + assert.match(content, /119건/); + return { id: '123' }; + } }); + assert.equal(calls, 2); + assert.equal(deliveries, 1); + assert.equal(result.status, 'sent'); +}); + +test('public summary never contains metrics, raw data, message text or webhook', async () => { + const result = await runReport(env, { now, collect: async () => snapshot({ count: 987654 }) }); + assert.match(result.content, /6,913,578건/); + assert.equal(result.summary.includes('987654'), false); + assert.equal(result.summary.includes('6,913,578'), false); + assert.equal(result.summary.includes('최초 다운로드:'), false); + assert.equal(result.summary.includes(env.DISCORD_WEBHOOK_URL), false); + assert.match(result.summary, /2026-11-09 ~ 2026-11-15/); +}); + +test('dry-run validates all requested periods without sending', async () => { + for (const [period, expected] of [['last_week', 119], ['last_7_days', 119], ['last_30_days', 510]]) { + const result = await runReport(env, { now, period, collect: async () => snapshot(), deliver: async () => assert.fail('Must not send') }); + assert.equal(result.status, 'preview'); + assert.match(result.content, new RegExp(`${expected}건`)); + } +}); + +test('invalid period and replayed send are rejected before collecting', async () => { + const collect = async () => assert.fail('Must not collect'); + await assert.rejects(runReport(env, { period: 'secret-in-invalid-input', collect }), { code: 'INVALID_PERIOD' }); + await assert.rejects(runReport({ ...env, GITHUB_RUN_ATTEMPT: '2' }, { send: true, collect }), { code: 'REPLAY_BLOCKED' }); + await assert.rejects(runReport({ ...env, GITHUB_RUN_ATTEMPT: '0' }, { send: true, collect }), { code: 'INVALID_RUN_ATTEMPT' }); +}); + +test('a replay may still perform a preview without delivery', async () => { + const result = await runReport({ ...env, GITHUB_RUN_ATTEMPT: '3' }, { now, collect: async () => snapshot() }); + assert.equal(result.status, 'preview'); +}); + +test('no progress and round limit never send a truncated collection', async () => { + let round = 0; + const deliver = async () => assert.fail('Must not send'); + await assert.rejects(runReport(env, { now, send: true, deliver, collect: async () => ({ ...snapshot(), processedInstanceIds: [], pendingInstances: 2 }) }), { code: 'COLLECTION_NO_PROGRESS' }); + await assert.rejects(runReport(env, { now, send: true, maxRounds: 2, deliver, + collect: async () => ({ ...snapshot(), processedInstanceIds: Array.from({ length: ++round }, (_, i) => String(i)), pendingInstances: 2 }) }), + { code: 'COLLECTION_LIMIT_REACHED' }); +}); + +test('collection/schema failures never send and discard potentially secret-bearing errors', async () => { + const options = { now, send: true, deliver: async () => assert.fail('Must not send') }; + await assert.rejects(runReport(env, { ...options, collect: async () => { throw new Error(env.DISCORD_WEBHOOK_URL); } }), error => { + assert.ok(error instanceof ReportRunError); + assert.equal(error.code, 'APPLE_COLLECTION_FAILED'); + assert.equal(error.message.includes('private-token'), false); + assert.equal(error.cause, undefined); + return true; + }); + await assert.rejects(runReport(env, { ...options, collect: async () => ({ ...snapshot(), pendingInstances: undefined }) }), { code: 'INVALID_COLLECTION_RESULT' }); + await assert.rejects(runReport(env, { ...options, collect: async () => ({ ...snapshot(), appId: 'other' }) }), { code: 'INVALID_COLLECTION_RESULT' }); +}); + +test('not-ready/report-request failures have safe setup guidance', async () => { + for (const [code, expected] of [['REPORT_NOT_READY', 'APPLE_REPORT_NOT_READY'], ['REPORT_REQUEST', 'APPLE_REPORT_REQUEST_REQUIRED']]) { + await assert.rejects(runReport(env, { now, collect: async () => { throw Object.assign(new Error('secret'), { code }); } }), { code: expected }); + } +}); + +test('partial and empty reports do not invent a complete zero', async () => { + const partial = snapshot(); + delete partial.days['2026-11-11']; + let received; + const result = await runReport(env, { now, send: true, collect: async () => partial, deliver: async (_, content) => { received = content; } }); + assert.equal(result.status, 'sent_partial'); + assert.match(received, /전체 합계 확인 대기/); + assert.match(received, /확인된 6일의 소계: 102건/); + const empty = await runReport(env, { now, collect: async () => ({ ...snapshot(), days: {} }) }); + assert.equal(empty.status, 'preview_partial'); + assert.doesNotMatch(empty.content, /최초 다운로드: \*\*0건/); + assert.equal(empty.summary.includes('102건'), false); +}); + +test('delivery errors remain classified but never expose credentials or retry', async () => { + for (const delivery of ['not_sent', 'unknown', undefined]) { + let sends = 0; + await assert.rejects(runReport(env, { now, send: true, collect: async () => snapshot(), deliver: async () => { + sends++; + throw Object.assign(new Error(env.DISCORD_WEBHOOK_URL), { delivery }); + } }), error => { + assert.equal(error.delivery, delivery === 'not_sent' ? 'not_sent' : 'unknown'); + assert.equal(error.message.includes('private-token'), false); + assert.equal(error.cause, undefined); + return true; + }); + assert.equal(sends, 1); + } +}); + +test('CLI accepts explicit options and GitHub summary path while rejecting unknown input safely', () => { + assert.deepEqual(parseArguments(['--send', '--period', 'last_30_days'], { GITHUB_STEP_SUMMARY: '/tmp/summary' }), + { send: true, period: 'last_30_days', summaryPath: '/tmp/summary' }); + assert.equal(parseArguments(['--summary-path=/tmp/a=b'], {}).summaryPath, '/tmp/a=b'); + for (const args of [['--period'], ['--send=true'], ['--unknown-secret'], ['--send', '--send']]) { + assert.throws(() => parseArguments(args, {}), error => error instanceof ReportRunError && !error.message.includes('unknown-secret')); + } +}); + +test('a summary file failure preserves a successful send status without leaking its path or report', async t => { + const directory = await mkdtemp(join(tmpdir(), 'routee-private-summary-')); + t.after(() => rm(directory, { recursive: true, force: true })); + const messages = []; + t.mock.method(console, 'log', message => messages.push(message)); + t.mock.method(console, 'error', message => messages.push(message)); + let executions = 0; + const exitCode = await main(['--send'], { GITHUB_STEP_SUMMARY: directory }, { execute: async () => { + executions++; + return { status: 'sent', summary: 'safe summary', content: 'private metric 987654' }; + } }); + assert.equal(exitCode, 0); + assert.equal(executions, 1); + assert.ok(messages.some(message => message === '루티 리포트 실행 완료: sent')); + assert.ok(messages.some(message => message.includes('요약 파일을 저장하지 못했습니다'))); + assert.ok(messages.every(message => !message.includes(directory) && !message.includes('987654') && !message.includes('REPORT_RUN_FAILED'))); +}); diff --git a/automation/app-store-discord/test/webhook.test.mjs b/automation/app-store-discord/test/webhook.test.mjs new file mode 100644 index 0000000..d0b9e70 --- /dev/null +++ b/automation/app-store-discord/test/webhook.test.mjs @@ -0,0 +1,78 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { sendWebhook, WebhookDeliveryError } from "../src/webhook.mjs"; + +const neverRead = () => assert.fail("Invalid input must not send a request"); + +const webhookURL = "https://discord.com/api/webhooks/123456789012345678/EXAMPLE_TOKEN"; + +test("webhook waits for acknowledgment, disables mentions, and returns only message ID", async () => { + const result = await sendWebhook(webhookURL + "?wait=false", "주간 합계 142건 @everyone", { + fetchImpl: async (url, options) => { + assert.equal(new URL(url).searchParams.get("wait"), "true"); + assert.equal(options.method, "POST"); + assert.equal(options.redirect, "error"); + assert.deepEqual(JSON.parse(options.body), { content: "주간 합계 142건 @everyone", allowed_mentions: { parse: [] } }); + assert.ok(options.signal instanceof AbortSignal); + return Response.json({ id: "923456789012345678", content: "private statistics" }); + }, + }); + assert.deepEqual(result, { id: "923456789012345678" }); +}); + +test("webhook rejects non-Discord destinations and invalid content without sending", async () => { + for (const url of [ + "https://evil.example/api/webhooks/1/token", + "https://discord.com.evil.example/api/webhooks/1/token", + "http://discord.com/api/webhooks/1/token", + "https://user:password@discord.com/api/webhooks/1/token", + webhookURL + "#secret", + webhookURL + "?thread_id=bad", + webhookURL + "?unknown=secret", + ]) { + await assert.rejects(sendWebhook(url, "리포트", { fetchImpl: neverRead }), (error) => { + assert.ok(error instanceof WebhookDeliveryError); + assert.equal(error.delivery, "not_sent"); + assert.doesNotMatch(error.message, /secret|token|password/); + return true; + }); + } + for (const content of ["", " ", "x".repeat(2001)]) { + await assert.rejects(sendWebhook(webhookURL, content, { fetchImpl: neverRead }), { code: "INVALID_MESSAGE", delivery: "not_sent" }); + } +}); + +test("webhook classifies definite rejections and uncertain deliveries without retrying", async () => { + for (const [status, delivery] of [[400, "not_sent"], [401, "not_sent"], [404, "not_sent"], [429, "not_sent"], [408, "unknown"], [500, "unknown"], [503, "unknown"]]) { + let calls = 0; + await assert.rejects(sendWebhook(webhookURL, "리포트", { + fetchImpl: async () => { + calls += 1; + return new Response("secret response body", { status }); + }, + }), (error) => { + assert.equal(error.delivery, delivery); + assert.equal(error.httpStatus, status); + assert.doesNotMatch(error.message, /secret|EXAMPLE_TOKEN/); + return true; + }); + assert.equal(calls, 1); + } +}); + +test("webhook network errors and malformed success bodies preserve uncertainty, not raw errors", async () => { + for (const fetchImpl of [ + async () => { throw new Error("failed POST " + webhookURL); }, + async () => new Response("invalid JSON"), + async () => Response.json({ content: "missing-id" }), + async () => new Response(null, { status: 204 }), + ]) { + await assert.rejects(sendWebhook(webhookURL, "리포트", { fetchImpl }), (error) => { + assert.equal(error.delivery, "unknown"); + assert.equal(error.cause, undefined); + assert.doesNotMatch(String(error), /EXAMPLE_TOKEN|discord\.com/); + return true; + }); + } +}); From f1b35c6477b2a9380f1fc14fd1c31a53cf47ec48 Mon Sep 17 00:00:00 2001 From: Sangyup Lee <108389915+sangyup12@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:23:54 +0900 Subject: [PATCH 2/3] chore: schedule weekly App Store reports in GitHub Actions --- .github/workflows/app-store-downloads.yml | 85 +++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 .github/workflows/app-store-downloads.yml diff --git a/.github/workflows/app-store-downloads.yml b/.github/workflows/app-store-downloads.yml new file mode 100644 index 0000000..5205ec5 --- /dev/null +++ b/.github/workflows/app-store-downloads.yml @@ -0,0 +1,85 @@ +name: Routee App Store Downloads + +on: + schedule: + # Wednesday 10:17 Asia/Seoul. Report window: previous Monday–Sunday in UTC. + - cron: '17 1 * * 3' + workflow_dispatch: + inputs: + period: + description: '조회 기간 (Apple UTC 기준)' + type: choice + options: + - last_week + - last_7_days + - last_30_days + default: last_week + required: true + send_to_discord: + description: '디스코드에 전송 (해제하면 API 조회만 검증)' + type: boolean + default: true + required: true + pull_request: + paths: + - 'automation/app-store-discord/**' + - '.github/workflows/app-store-downloads.yml' + +permissions: + contents: read + +jobs: + test: + name: Validate report logic + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: '24' + package-manager-cache: false + - name: Run tests without credentials + working-directory: automation/app-store-discord + run: npm test + + report: + name: Collect and deliver + needs: test + if: >- + github.event_name != 'pull_request' && + github.repository == 'Team-Routee/Routee-iOS' && + github.ref == 'refs/heads/develop' + runs-on: ubuntu-latest + timeout-minutes: 10 + concurrency: + group: routee-app-store-downloads-delivery + cancel-in-progress: false + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: '24' + package-manager-cache: false + - name: Collect Apple report and optionally post to Discord + working-directory: automation/app-store-discord + env: + ASC_APP_ID: '6791870747' + ASC_KEY_ID: ${{ secrets.ROUTEE_ASC_KEY_ID }} + 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 }} + 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[@]}" From bbd49c0f1e88f48f10e11a9ddaafa483ba7450c1 Mon Sep 17 00:00:00 2001 From: sangyup Date: Tue, 17 Nov 2026 17:46:22 +0900 Subject: [PATCH 3/3] fix: normalize App Store app ID before report validation --- .../app-store-discord/scripts/request-reports.mjs | 7 ++++--- automation/app-store-discord/src/run-report.mjs | 5 +++-- automation/app-store-discord/test/run-report.test.mjs | 11 +++++++++++ 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/automation/app-store-discord/scripts/request-reports.mjs b/automation/app-store-discord/scripts/request-reports.mjs index 995a6e3..65f43be 100644 --- a/automation/app-store-discord/scripts/request-reports.mjs +++ b/automation/app-store-discord/scripts/request-reports.mjs @@ -10,11 +10,12 @@ if (!process.argv.includes('--apply')) { if (env.ASC_PRIVATE_KEY_PATH && !env.ASC_PRIVATE_KEY) { env.ASC_PRIVATE_KEY = await readFile(env.ASC_PRIVATE_KEY_PATH, 'utf8'); } - if (!/^\d+$/.test(env.ASC_APP_ID ?? '')) throw new Error('configuration'); + const appId = String(env.ASC_APP_ID ?? '').trim(); + if (!/^\d+$/.test(appId)) throw new Error('configuration'); const token = await createAppleJWT(env); const origin = 'https://api.appstoreconnect.apple.com'; const headers = { Authorization: `Bearer ${token}`, 'content-type': 'application/json' }; - let next = `${origin}/v1/apps/${env.ASC_APP_ID}/analyticsReportRequests?filter%5BaccessType%5D=ONGOING&limit=200`; + let next = `${origin}/v1/apps/${appId}/analyticsReportRequests?filter%5BaccessType%5D=ONGOING&limit=200`; const requests = []; const visited = new Set(); while (next) { @@ -35,7 +36,7 @@ if (!process.argv.includes('--apply')) { const response = await fetch(`${origin}/v1/analyticsReportRequests`, { method: 'POST', headers, redirect: 'error', signal: AbortSignal.timeout(10_000), body: JSON.stringify({ data: { type: 'analyticsReportRequests', attributes: { accessType: 'ONGOING' }, - relationships: { app: { data: { type: 'apps', id: env.ASC_APP_ID } } } } }), + relationships: { app: { data: { type: 'apps', id: appId } } } } }), }); if (!response.ok) throw new Error('creation'); const result = await response.json(); diff --git a/automation/app-store-discord/src/run-report.mjs b/automation/app-store-discord/src/run-report.mjs index 0e34fe6..3627c15 100644 --- a/automation/app-store-discord/src/run-report.mjs +++ b/automation/app-store-discord/src/run-report.mjs @@ -67,7 +67,8 @@ export async function runReport(env, { fail('REPLAY_BLOCKED', '중복 전송을 막기 위해 재실행에서는 전송하지 않습니다. Discord 채널을 확인한 뒤 새 Run workflow로 실행해 주세요.'); } } - const collectionEnv = { ...env, ASC_MAX_INSTANCES_PER_SYNC: env.ASC_MAX_INSTANCES_PER_SYNC ?? '20' }; + 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++) { @@ -78,7 +79,7 @@ export async function runReport(env, { } catch (error) { throw collectionError(error); } - validateSnapshot(next, env.ASC_APP_ID); + validateSnapshot(next, appId); snapshot = next; if (snapshot.pendingInstances === 0) { finished = true; diff --git a/automation/app-store-discord/test/run-report.test.mjs b/automation/app-store-discord/test/run-report.test.mjs index 476d60d..3dc32e5 100644 --- a/automation/app-store-discord/test/run-report.test.mjs +++ b/automation/app-store-discord/test/run-report.test.mjs @@ -52,6 +52,17 @@ test('public summary never contains metrics, raw data, message text or webhook', assert.match(result.summary, /2026-11-09 ~ 2026-11-15/); }); +test('normalizes app ID whitespace for collection and snapshot validation without changing the input', async () => { + const paddedEnv = { ...env, ASC_APP_ID: ' \t123\n' }; + const result = await runReport(paddedEnv, { now, collect: async config => { + assert.equal(config.ASC_APP_ID, '123'); + return snapshot(); + } }); + assert.equal(result.status, 'preview'); + assert.equal(result.snapshot.appId, '123'); + assert.equal(paddedEnv.ASC_APP_ID, ' \t123\n'); +}); + test('dry-run validates all requested periods without sending', async () => { for (const [period, expected] of [['last_week', 119], ['last_7_days', 119], ['last_30_days', 510]]) { const result = await runReport(env, { now, period, collect: async () => snapshot(), deliver: async () => assert.fail('Must not send') });