diff --git a/.github/workflows/code-quality.yml b/.github/workflows/code-quality.yml index eb72246f..f740c5a2 100644 --- a/.github/workflows/code-quality.yml +++ b/.github/workflows/code-quality.yml @@ -50,6 +50,3 @@ jobs: - name: Firestore Rules run: pnpm test:firestore-rules - - - name: Verify release artifact encryption - run: node --test scripts/release-artifact.test.mjs diff --git a/.github/workflows/release-throwl.yaml b/.github/workflows/release-throwl.yaml index e6d12317..a35cbe6f 100644 --- a/.github/workflows/release-throwl.yaml +++ b/.github/workflows/release-throwl.yaml @@ -114,3 +114,116 @@ jobs: IOS_APPLE_ISSUER_ID: ${{ secrets.APPLE_ISSUER_ID }} IOS_APPLE_KEY_CONTENT: ${{ secrets.APPLE_KEY_CONTENT }} IOS_GOOGLE_SERVICE_INFO_PLIST_B64: ${{ secrets.IOS_GOOGLE_SERVICE_INFO_PLIST_B64 }} + + prepare: + name: Submit both tested builds for store review + needs: [deploy_android, deploy_ios] + if: github.event_name == 'push' && github.ref_type == 'tag' && startsWith(github.ref_name, 'v') && !github.event.repository.fork + concurrency: + group: throwl-production-store-preparation + cancel-in-progress: false + runs-on: macos-latest + environment: store-review + permissions: + actions: read + contents: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + + - name: Require recorded store-review approval + env: + GH_TOKEN: ${{ github.token }} + run: | + gh api "repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/approvals" \ + | jq -e 'any(.[]; .state == "approved" and any(.environments[]; .name == "store-review"))' >/dev/null || { + echo 'Configure required reviewers for the store-review environment and approve this run before preparing the stores.' + exit 1 + } + + - name: Read the tested release and validate its store notes + id: release + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ github.ref_name }} + run: | + [[ "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo 'Enter a version tag such as v5.1.2.'; exit 1; } + git merge-base --is-ancestor "$GITHUB_SHA" origin/master + gh api --paginate --slurp "repos/$GITHUB_REPOSITORY/releases" \ + | jq -e '[.[][] | select(.tag_name == env.RELEASE_TAG and .draft)] | if length == 1 then .[0] else error("Expected one GitHub draft for this tag") end' \ + > "$RUNNER_TEMP/draft.json" + jq -er '[ + .body | match("\\s*```json\\r?\\n([\\s\\S]*?)\\r?\\n```"; "g") | .captures[0].string + ] | if length == 1 then .[0] | fromjson else error("Keep one store-notes JSON block in the draft") end + | if .["en-US"] and all(to_entries[]; + (.key | test("^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$")) and + (.value.whatsNew | type == "string" and test("\\S") and length <= 500) and + (.value | if has("iosPromotionalText") then + .iosPromotionalText | type == "string" and length <= 170 + else true end)) + then . else error("Fill in the store notes and check the locale and text lengths") end' \ + "$RUNNER_TEMP/draft.json" > "$RUNNER_TEMP/store-notes.json" + + version=$(jq -er .version apps/throwl/package.json) + gradle=apps/throwl/android/app/build.gradle + xcode=apps/throwl/ios/Throwl.xcodeproj/project.pbxproj + android_build=$(awk '$1 == "versionCode" { print $2 }' "$gradle") + ios_build=$(awk '$1 == "CURRENT_PROJECT_VERSION" { gsub(/;/, "", $3); print $3 }' "$xcode" | sort -u) + android_version=$(awk '$1 == "versionName" { gsub(/"/, "", $2); print $2 }' "$gradle") + ios_version=$(awk '$1 == "MARKETING_VERSION" { gsub(/;/, "", $3); print $3 }' "$xcode" | sort -u) + [[ "$RELEASE_TAG" == "v$version" && "$android_version" == "$version" && "$ios_version" == "$version" ]] + [[ "$android_build" =~ ^[0-9]+$ && "$ios_build" =~ ^[0-9]+$ ]] + { + echo "id=$(jq -er .id "$RUNNER_TEMP/draft.json")" + echo "version=$version" + echo "ios_build=$ios_build" + echo "android_build=$android_build" + } >> "$GITHUB_OUTPUT" + + - name: Set up Ruby + uses: ruby/setup-ruby@145243922b4465b78e04dd66294782c7de45901f # v1.345.0 + with: + working-directory: apps/throwl + bundler-cache: true + + - name: Submit tested iOS build to App Review + id: ios + continue-on-error: true + working-directory: apps/throwl + run: bundle exec fastlane ios submit_tested_build "version:$VERSION" "build:$BUILD_NUMBER" "notes:$RUNNER_TEMP/store-notes.json" + env: + VERSION: ${{ steps.release.outputs.version }} + BUILD_NUMBER: ${{ steps.release.outputs.ios_build }} + DEVELOPER_APP_IDENTIFIER: ${{ secrets.DEVELOPER_APP_IDENTIFIER }} + APPLE_KEY_ID: ${{ secrets.APPLE_KEY_ID }} + APPLE_ISSUER_ID: ${{ secrets.APPLE_ISSUER_ID }} + APPLE_KEY_CONTENT: ${{ secrets.APPLE_KEY_CONTENT }} + + - name: Submit tested Android build for production review + id: android + continue-on-error: true + working-directory: apps/throwl + run: bundle exec fastlane android submit_tested_build "build:$BUILD_NUMBER" "notes:$RUNNER_TEMP/store-notes.json" + env: + BUILD_NUMBER: ${{ steps.release.outputs.android_build }} + PLAY_CONFIG_JSON: ${{ secrets.PLAY_CONFIG_JSON }} + + - name: Record both store results in the GitHub draft + env: + GH_TOKEN: ${{ github.token }} + RELEASE_ID: ${{ steps.release.outputs.id }} + IOS_OUTCOME: ${{ steps.ios.outcome }} + ANDROID_OUTCOME: ${{ steps.android.outcome }} + run: | + printf '### Store preparation\n\n- iOS: %s\n- Android: %s\n' "$IOS_OUTCOME" "$ANDROID_OUTCOME" >> "$GITHUB_STEP_SUMMARY" + [[ "$IOS_OUTCOME" == success && "$ANDROID_OUTCOME" == success ]] || exit 1 + gh api "repos/$GITHUB_REPOSITORY/releases/$RELEASE_ID" > "$RUNNER_TEMP/current-draft.json" + jq -e --slurpfile original "$RUNNER_TEMP/draft.json" ' + if .draft and .body == $original[0].body then + {body: ("\n**Both builds were submitted to their stores for review.** Each store publishes after approval.\n\n" + + (.body | sub("^\\s*\\*\\*[^\\r\\n]*\\s*"; "")))} + else error("The GitHub draft changed during store preparation; update its status manually") end + ' "$RUNNER_TEMP/current-draft.json" > "$RUNNER_TEMP/ready.json" + gh api --method PATCH "repos/$GITHUB_REPOSITORY/releases/$RELEASE_ID" \ + --input "$RUNNER_TEMP/ready.json" --jq .html_url diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 10e9bf64..21d7e303 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -113,3 +113,39 @@ eligible caches from `master`. To check encrypted bundle creation on GitHub without uploading to the stores, run the release workflow manually with `publish: false`. That run requires release signing and the artifact secret, and retains the encrypted bundles. + +### Prepare production store submissions + +Run the usual release target with a GitHub token so release-it creates a +draft directly: + +```sh +GITHUB_TOKEN="$(gh auth token)" pnpm nx run @throwl/throwl:release +``` + +On GitHub, edit the draft's changelog and store notes before approving. +Enter `whatsNew` (up to 500 characters per locale) and optional +`iosPromotionalText` (up to 170 characters). Omit the promotional text field to +preserve existing text or use an empty string to clear it. + +The same tag workflow validates, builds, and uploads both candidate builds, +then waits at **Review deployments**. Test the exact TestFlight and Play +Internal builds before approving `store-review` in that run. + +Before the first release, configure the `store-review` GitHub environment with +required reviewers, allow version tags, and allow self-review if you cut and +approve releases yourself. The job checks the run's approval history before +writing to either store. The App Store Connect key needs permission to submit +versions for review, and the Play service account needs permission to edit production +releases. The workflow reuses the existing Actions credentials. + +Approving the job submits both tested builds for production review. Apple +releases automatically after approval. For Google to publish automatically +after approval, turn off Managed publishing in Play Console. Before +approving, check that Play has no active production review or rollout. +Fastlane's promotion uses Google's default handling for an existing review. +Each store can approve and publish on its own schedule. + +After both lanes succeed, the workflow records their outcomes on the GitHub +draft. Publish that draft separately. If one lane fails, check both store +consoles before retrying because the other lane may have already succeeded. diff --git a/apps/throwl/.release-it.json b/apps/throwl/.release-it.json index f38c2bc0..2d39157b 100644 --- a/apps/throwl/.release-it.json +++ b/apps/throwl/.release-it.json @@ -5,10 +5,12 @@ }, "git": { "commitMessage": "chore(release): v${version}", - "tagName": "v${version}" + "tagName": "v${version}", + "changelog": "cat fastlane/store-release-notes.md" }, "github": { - "release": true + "release": true, + "draft": true }, "hooks": { "after:bump": "nx run throwl:syncNativeVersions --args=\"--version=${version}\"" diff --git a/apps/throwl/fastlane/Fastfile b/apps/throwl/fastlane/Fastfile index 2c471b8c..4c261374 100644 --- a/apps/throwl/fastlane/Fastfile +++ b/apps/throwl/fastlane/Fastfile @@ -1,3 +1,8 @@ +require "base64" +require "json" +require "tmpdir" +require "fileutils" + default_platform(:ios) DEVELOPER_APP_IDENTIFIER = ENV.fetch("DEVELOPER_APP_IDENTIFIER", nil) @@ -66,6 +71,26 @@ platform :ios do notify_external_testers: false ) end + + desc "Submit the approved TestFlight build for automatic release after App Review" + lane :submit_tested_build do |options| + notes = JSON.parse(File.read(options.fetch(:notes))) + deliver( + api_key: testflight_api_key, + app_identifier: DEVELOPER_APP_IDENTIFIER, + app_version: options.fetch(:version).to_s, + build_number: options.fetch(:build).to_s, + release_notes: notes.transform_values { |entry| entry.fetch("whatsNew") }, + promotional_text: notes.filter { |_, entry| entry.key?("iosPromotionalText") } + .transform_values { |entry| entry.fetch("iosPromotionalText") }, + skip_binary_upload: true, + skip_screenshots: true, + force: true, + run_precheck_before_submit: false, + automatic_release: true, + submit_for_review: true + ) + end end platform :android do @@ -104,4 +129,34 @@ platform :android do track: "internal" ) end + + desc "Promote the approved Play Internal build and send it for production review" + lane :submit_tested_build do |options| + code = Integer(options.fetch(:build)) + Dir.mktmpdir("throwl-play-release") do |temporary| + metadata = File.join(temporary, "metadata") + credentials = File.join(temporary, "credentials.json") + File.write(credentials, Base64.strict_decode64(ENV.fetch("PLAY_CONFIG_JSON")), perm: 0o600) + JSON.parse(File.read(options.fetch(:notes))).each do |locale, entry| + directory = File.join(metadata, locale, "changelogs") + FileUtils.mkdir_p(directory) + File.write(File.join(directory, "#{code}.txt"), entry.fetch("whatsNew")) + end + + upload_to_play_store( + json_key: credentials, + track: "internal", + track_promote_to: "production", + version_code: code, + metadata_path: metadata, + skip_upload_apk: true, + skip_upload_aab: true, + skip_upload_metadata: true, + skip_upload_images: true, + skip_upload_screenshots: true, + changes_not_sent_for_review: false, + rescue_changes_not_sent_for_review: false + ) + end + end end diff --git a/apps/throwl/fastlane/store-release-notes.md b/apps/throwl/fastlane/store-release-notes.md new file mode 100644 index 00000000..6dc555ba --- /dev/null +++ b/apps/throwl/fastlane/store-release-notes.md @@ -0,0 +1,18 @@ + + +**Store review is pending.** Add the release notes, test both builds, and approve the workflow to submit them. + +## Changes + +Add the changelog here. + + + +```json +{ + "en-US": { + "whatsNew": "", + "iosPromotionalText": "" + } +} +``` diff --git a/package.json b/package.json index 3e6c7d30..8afc9a33 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,6 @@ "test:firestore-rules": "firebase emulators:exec --project demo-throwl-rules --only firestore \"node --test firebase/firestore.rules.test.mjs\"", "test:affected": "nx affected --target=test --parallel --maxParallel=5", "postinstall": "husky", - "test:firestore-clone": "node --test scripts/clone-firestore-data.test.mjs", "clone:firestore": "node scripts/clone-firestore-data.mjs" }, "packageManager": "pnpm@10.24.0", diff --git a/scripts/clone-firestore-data.test.mjs b/scripts/clone-firestore-data.test.mjs deleted file mode 100644 index 77199dd5..00000000 --- a/scripts/clone-firestore-data.test.mjs +++ /dev/null @@ -1,57 +0,0 @@ -import assert from 'node:assert/strict'; -import { after, describe, test } from 'node:test'; -import { initializeApp, deleteApp } from 'firebase-admin/app'; -import { GeoPoint, Timestamp, getFirestore } from 'firebase-admin/firestore'; -import { remapFirestoreValue } from './clone-firestore-data.mjs'; - -const sourceApp = initializeApp( - { projectId: 'darts-counter-b73d6' }, - 'clone-test-source', -); -const targetApp = initializeApp( - { projectId: 'throwl-dev' }, - 'clone-test-target', -); -const sourceDb = getFirestore(sourceApp); -const targetDb = getFirestore(targetApp); - -after(async () => { - await Promise.all([deleteApp(sourceApp), deleteApp(targetApp)]); -}); - -describe('Firestore clone value transformation', () => { - test('recursively remaps references and preserves native values', () => { - const timestamp = Timestamp.fromMillis(1_700_000_000_123); - const geoPoint = new GeoPoint(52.37, 4.9); - const bytes = Buffer.from([1, 2, 3]); - const inventory = { - referenceCount: 0, - referenceDocumentPaths: new Set(), - referenceProjects: new Set(), - nativeTypes: new Set(), - unsupportedTypes: new Set(), - }; - const transformed = remapFirestoreValue( - { - nested: [ - sourceDb.doc('users/ABC'), - { timestamp, geoPoint, bytes, nil: null, enabled: true }, - ], - }, - targetDb, - inventory, - 'games/game-1', - ); - - assert.equal(transformed.nested[0].path, 'users/ABC'); - assert.equal(transformed.nested[0].firestore.projectId, 'throwl-dev'); - assert.equal(transformed.nested[1].timestamp, timestamp); - assert.equal(transformed.nested[1].geoPoint, geoPoint); - assert.notEqual(transformed.nested[1].bytes, bytes); - assert.deepEqual(transformed.nested[1].bytes, bytes); - assert.equal(inventory.referenceCount, 1); - assert.deepEqual([...inventory.referenceProjects], ['darts-counter-b73d6']); - assert.deepEqual([...inventory.referenceDocumentPaths], ['games/game-1']); - assert.equal(inventory.unsupportedTypes.size, 0); - }); -}); diff --git a/scripts/release-artifact.test.mjs b/scripts/release-artifact.test.mjs deleted file mode 100644 index 94965bc5..00000000 --- a/scripts/release-artifact.test.mjs +++ /dev/null @@ -1,52 +0,0 @@ -import assert from 'node:assert/strict'; -import { spawnSync } from 'node:child_process'; -import { randomBytes } from 'node:crypto'; -import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { test } from 'node:test'; -import { fileURLToPath } from 'node:url'; - -const script = fileURLToPath( - new URL('./release-artifact.mjs', import.meta.url), -); - -test('the upload job recovers the exact signed bundle and rejects altered handoffs', async (t) => { - const directory = await mkdtemp(join(tmpdir(), 'throwl-release-test-')); - t.after(() => rm(directory, { recursive: true, force: true })); - - const original = join(directory, 'original.ipa'); - const encrypted = join(directory, 'release-bundle.enc'); - const recovered = join(directory, 'recovered.ipa'); - const rejected = join(directory, 'rejected.ipa'); - const bytes = randomBytes(8192); - await writeFile(original, bytes); - - const key = randomBytes(32).toString('hex'); - const context = 'release-run:release-commit:apps/throwl/ios'; - const run = (args, secret = key, release = context) => - spawnSync(process.execPath, [script, ...args], { - env: { RELEASE_ARTIFACT_KEY: secret, RELEASE_ARTIFACT_CONTEXT: release }, - encoding: 'utf8', - }); - - assert.notEqual(run(['check'], '').status, 0); - - const encryption = run(['encrypt', original, encrypted]); - assert.equal(encryption.status, 0, encryption.stderr); - assert.notDeepEqual(await readFile(encrypted), bytes); - - const decryption = run(['decrypt', encrypted, recovered]); - assert.equal(decryption.status, 0, decryption.stderr); - assert.deepEqual(await readFile(recovered), bytes); - - const decrypt = ['decrypt', encrypted, rejected]; - assert.notEqual(run(decrypt, randomBytes(32).toString('hex')).status, 0); - assert.notEqual(run(decrypt, key, 'different-release').status, 0); - - const tampered = await readFile(encrypted); - tampered[tampered.length - 1] ^= 1; - await writeFile(encrypted, tampered); - assert.notEqual(run(decrypt).status, 0); - await assert.rejects(readFile(rejected), { code: 'ENOENT' }); -});