From 95d807898270f736c4d9511201624863deb137b7 Mon Sep 17 00:00:00 2001 From: Thomas Luizon Rodrigues Gregorio Date: Fri, 19 Jun 2026 14:54:17 -0300 Subject: [PATCH] fix(ci): ship real AdMob ids in production android release (#232) The release workflow set the production AdMob env on the prebuild step but not on the gradle bundleRelease step. bundleRelease re-evaluates app.config.js to regenerate the embedded Constants.expoConfig.extra.adMob snapshot, so without the env it defaulted useTestIds to true and shipped Google test ad unit ids to every free-plan user (0 real requests). - Hoist EAS_BUILD_PROFILE + the four EXPO_PUBLIC_ADMOB_ANDROID vars to the job-level env so prebuild and bundleRelease evaluate app.config.js identically; drop the now-redundant per-step duplicates. - Add a post-bundleRelease guard (assert-aab-admob-config.js) that inspects the shipped AAB's JS bundle and fails on Google sample ids or missing real unit ids -- the prebuild-source guards could not catch this. - Extract the pre-build config assertion into assert-production-admob-config.js shared by both guards. - Fail-fast the local release scripts (android-release-apk/device) when the production AdMob env is missing instead of silently building a test-id release. - Lock the selection contract in use-ad-mob tests: useTestIds=false uses real ids and never TestIds.*, undefined falls back to __DEV__, and a missing prod id yields no ad request. Co-Authored-By: Claude Opus 4.8 (1M context) --- .github/workflows/android-release.yml | 102 +++--------------- .../__tests__/hooks/use-ad-mob.test.tsx | 47 ++++++++ apps/mobile/scripts/android-release-apk.js | 2 + apps/mobile/scripts/android-release-device.js | 16 +-- .../mobile/scripts/assert-aab-admob-config.js | 67 ++++++++++++ .../scripts/assert-production-admob-config.js | 97 +++++++++++++++++ apps/mobile/scripts/production-admob-env.js | 27 +++++ 7 files changed, 263 insertions(+), 95 deletions(-) create mode 100644 apps/mobile/scripts/assert-aab-admob-config.js create mode 100644 apps/mobile/scripts/assert-production-admob-config.js create mode 100644 apps/mobile/scripts/production-admob-env.js diff --git a/.github/workflows/android-release.yml b/.github/workflows/android-release.yml index 06a743722c..b33e4a1063 100644 --- a/.github/workflows/android-release.yml +++ b/.github/workflows/android-release.yml @@ -41,9 +41,11 @@ jobs: runs-on: ubuntu-latest env: RELEASE_WORKDIR: ${{ github.workspace }}/.release-mobile - PROD_ADMOB_ANDROID_APP_ID: ca-app-pub-8521676951882691~5595921738 - PROD_ADMOB_ANDROID_INTERSTITIAL_ID: ca-app-pub-8521676951882691/8083010939 - PROD_ADMOB_ANDROID_REWARDED_ID: ca-app-pub-8521676951882691/3704782221 + EAS_BUILD_PROFILE: production + EXPO_PUBLIC_ADMOB_USE_TEST_IDS: "false" + EXPO_PUBLIC_ADMOB_ANDROID_APP_ID: ca-app-pub-8521676951882691~5595921738 + EXPO_PUBLIC_ADMOB_ANDROID_INTERSTITIAL_ID: ca-app-pub-8521676951882691/8083010939 + EXPO_PUBLIC_ADMOB_ANDROID_REWARDED_ID: ca-app-pub-8521676951882691/3704782221 steps: - uses: actions/checkout@v5 @@ -189,87 +191,12 @@ jobs: env: CI: "1" EXPO_NO_TELEMETRY: "1" - EAS_BUILD_PROFILE: production - EXPO_PUBLIC_ADMOB_USE_TEST_IDS: "false" - EXPO_PUBLIC_ADMOB_ANDROID_APP_ID: ${{ env.PROD_ADMOB_ANDROID_APP_ID }} - EXPO_PUBLIC_ADMOB_ANDROID_INTERSTITIAL_ID: ${{ env.PROD_ADMOB_ANDROID_INTERSTITIAL_ID }} - EXPO_PUBLIC_ADMOB_ANDROID_REWARDED_ID: ${{ env.PROD_ADMOB_ANDROID_REWARDED_ID }} - PROD_ADMOB_ANDROID_APP_ID: ${{ env.PROD_ADMOB_ANDROID_APP_ID }} - PROD_ADMOB_ANDROID_INTERSTITIAL_ID: ${{ env.PROD_ADMOB_ANDROID_INTERSTITIAL_ID }} - PROD_ADMOB_ANDROID_REWARDED_ID: ${{ env.PROD_ADMOB_ANDROID_REWARDED_ID }} run: | set -euo pipefail npx expo config --type public --json > expo-public-config.json - node <<'NODE' - const fs = require('node:fs') - - const SAMPLE_IDS = [ - 'ca-app-pub-3940256099942544~3347511713', - 'ca-app-pub-3940256099942544/1033173712', - 'ca-app-pub-3940256099942544/5224354917', - ] - - const config = JSON.parse(fs.readFileSync('expo-public-config.json', 'utf8')) - const extra = config.extra ?? config.expo?.extra ?? {} - const adMob = extra.adMob ?? {} - const plugins = Array.isArray(config.plugins) - ? config.plugins - : Array.isArray(config.expo?.plugins) - ? config.expo.plugins - : [] - const adMobPlugin = plugins.find((plugin) => - Array.isArray(plugin) - ? plugin[0] === 'react-native-google-mobile-ads' - : plugin === 'react-native-google-mobile-ads' - ) - const adMobPluginOptions = - Array.isArray(adMobPlugin) && adMobPlugin[1] && typeof adMobPlugin[1] === 'object' - ? adMobPlugin[1] - : {} - - if (adMob.useTestIds !== false) { - throw new Error(`Expected extra.adMob.useTestIds=false, got ${String(adMob.useTestIds)}`) - } - - const expectedPluginValues = { - androidAppId: process.env.PROD_ADMOB_ANDROID_APP_ID, - } - - for (const [key, value] of Object.entries(expectedPluginValues)) { - if (!value) { - throw new Error(`Missing expected env value for ${key}`) - } - if (adMobPluginOptions[key] !== value) { - throw new Error( - `Expected react-native-google-mobile-ads.${key}=${value}, got ${String(adMobPluginOptions[key])}` - ) - } - if (SAMPLE_IDS.includes(value) || SAMPLE_IDS.includes(adMobPluginOptions[key])) { - throw new Error(`Detected Google sample AdMob ID for ${key}`) - } - } - - const expectedExtraValues = { - androidInterstitialId: process.env.PROD_ADMOB_ANDROID_INTERSTITIAL_ID, - androidRewardedId: process.env.PROD_ADMOB_ANDROID_REWARDED_ID, - } - - for (const [key, value] of Object.entries(expectedExtraValues)) { - if (!value) { - throw new Error(`Missing expected env value for ${key}`) - } - if (adMob[key] !== value) { - throw new Error(`Expected extra.adMob.${key}=${value}, got ${String(adMob[key])}`) - } - if (SAMPLE_IDS.includes(value) || SAMPLE_IDS.includes(adMob[key])) { - throw new Error(`Detected Google sample AdMob ID for ${key}`) - } - } - - console.log('Expo AdMob config validation passed.') - NODE + node scripts/assert-production-admob-config.js expo-public-config.json - name: Generate Android project with Expo prebuild working-directory: ${{ env.RELEASE_WORKDIR }}/apps/mobile @@ -277,11 +204,6 @@ jobs: env: CI: "1" EXPO_NO_TELEMETRY: "1" - EAS_BUILD_PROFILE: production - EXPO_PUBLIC_ADMOB_USE_TEST_IDS: "false" - EXPO_PUBLIC_ADMOB_ANDROID_APP_ID: ${{ env.PROD_ADMOB_ANDROID_APP_ID }} - EXPO_PUBLIC_ADMOB_ANDROID_INTERSTITIAL_ID: ${{ env.PROD_ADMOB_ANDROID_INTERSTITIAL_ID }} - EXPO_PUBLIC_ADMOB_ANDROID_REWARDED_ID: ${{ env.PROD_ADMOB_ANDROID_REWARDED_ID }} run: | set -euo pipefail @@ -290,8 +212,6 @@ jobs: - name: Validate generated Android project does not contain sample AdMob IDs working-directory: ${{ env.RELEASE_WORKDIR }}/apps/mobile shell: bash - env: - PROD_ADMOB_ANDROID_APP_ID: ${{ env.PROD_ADMOB_ANDROID_APP_ID }} run: | set -euo pipefail @@ -301,7 +221,7 @@ jobs: exit 1 fi - if ! grep -F -q "${PROD_ADMOB_ANDROID_APP_ID}" "${MANIFEST_PATH}"; then + if ! grep -F -q "${EXPO_PUBLIC_ADMOB_ANDROID_APP_ID}" "${MANIFEST_PATH}"; then echo "Android manifest does not contain the expected production AdMob app ID." >&2 exit 1 fi @@ -350,6 +270,14 @@ jobs: chmod +x gradlew ./gradlew --no-daemon bundleRelease + - name: Verify shipped AAB embeds production AdMob IDs + working-directory: ${{ env.RELEASE_WORKDIR }}/apps/mobile + shell: bash + run: | + set -euo pipefail + node scripts/assert-aab-admob-config.js \ + android/app/build/outputs/bundle/release/app-release.aab + - name: Verify Android widget is bundled in release manifest working-directory: ${{ env.RELEASE_WORKDIR }}/apps/mobile/android shell: bash diff --git a/apps/mobile/__tests__/hooks/use-ad-mob.test.tsx b/apps/mobile/__tests__/hooks/use-ad-mob.test.tsx index 13990ad8d9..fe561214c1 100644 --- a/apps/mobile/__tests__/hooks/use-ad-mob.test.tsx +++ b/apps/mobile/__tests__/hooks/use-ad-mob.test.tsx @@ -291,6 +291,53 @@ describe('mobile useAdMob', () => { mocks.state.rewardeds[0]?.emit('rewarded') mocks.state.rewardeds[0]?.emit('closed') await expect(rewardedAttempt).resolves.toBe(true) + + expect(mocks.createInterstitial).not.toHaveBeenCalledWith('test-interstitial') + expect(mocks.createRewarded).not.toHaveBeenCalledWith('test-rewarded') + }) + + it('falls back to test ids in development when useTestIds is not configured', async () => { + mocks.constants.expoConfig.extra = { + adMob: { + androidInterstitialId: 'prod-interstitial', + androidRewardedId: 'prod-rewarded', + }, + } + const { result } = await renderUseAdMob() + + await TestRenderer.act(async () => { + await result.initialize() + }) + + const interstitialAttempt = result.showInterstitialIfDue() + await Promise.resolve() + expect(mocks.createInterstitial).toHaveBeenCalledWith('test-interstitial') + expect(mocks.createInterstitial).not.toHaveBeenCalledWith('prod-interstitial') + mocks.state.interstitials[0]?.emit('loaded') + await Promise.resolve() + mocks.state.interstitials[0]?.emit('closed') + await interstitialAttempt + }) + + it('does not request an ad when production ids are missing', async () => { + mocks.constants.expoConfig.extra = { + adMob: { + useTestIds: false, + androidInterstitialId: null, + androidRewardedId: null, + }, + } + const { result } = await renderUseAdMob() + + await TestRenderer.act(async () => { + await result.initialize() + }) + + await result.showInterstitialIfDue() + await expect(result.showRewardedAd()).resolves.toBe(false) + + expect(mocks.createInterstitial).not.toHaveBeenCalled() + expect(mocks.createRewarded).not.toHaveBeenCalled() }) it('increments the claimed reward count in the profile cache', async () => { diff --git a/apps/mobile/scripts/android-release-apk.js b/apps/mobile/scripts/android-release-apk.js index 6570d4170c..35d3c372f1 100644 --- a/apps/mobile/scripts/android-release-apk.js +++ b/apps/mobile/scripts/android-release-apk.js @@ -2,9 +2,11 @@ const { execSync } = require('child_process') const fs = require('fs') const os = require('os') const path = require('path') +const { resolveProductionAdMobEnv } = require('./production-admob-env') process.env.EXPO_NO_METRO_WORKSPACE_ROOT = '1' process.env.NODE_ENV = process.env.NODE_ENV || 'production' +Object.assign(process.env, resolveProductionAdMobEnv(process.env)) const projectRoot = path.join(__dirname, '..') const androidDir = path.join(__dirname, '..', 'android') diff --git a/apps/mobile/scripts/android-release-device.js b/apps/mobile/scripts/android-release-device.js index a72fd0869f..f50f2f7475 100644 --- a/apps/mobile/scripts/android-release-device.js +++ b/apps/mobile/scripts/android-release-device.js @@ -1,6 +1,7 @@ const { spawn } = require('child_process') const fs = require('fs') const path = require('path') +const { resolveProductionAdMobEnv } = require('./production-admob-env') const projectRoot = path.resolve(__dirname, '..') const androidDir = path.join(projectRoot, 'android') @@ -91,6 +92,11 @@ async function waitForPid(deviceId) { } async function main() { + const releaseEnv = { + ...resolveProductionAdMobEnv(process.env), + EXPO_NO_METRO_WORKSPACE_ROOT: '1', + } + const deviceId = await getConnectedDeviceId() console.log(`Using adb device: ${deviceId}`) @@ -98,20 +104,14 @@ async function main() { await run('cmd.exe', ['/c', 'npx', 'expo', 'prebuild', '--platform', 'android', '--no-install'], { cwd: projectRoot, - env: { - ...process.env, - EXPO_NO_METRO_WORKSPACE_ROOT: '1', - }, + env: releaseEnv, }) console.log('Building release APK with Gradle...') await run('cmd.exe', ['/c', 'gradlew.bat', 'assembleRelease'], { cwd: androidDir, - env: { - ...process.env, - EXPO_NO_METRO_WORKSPACE_ROOT: '1', - }, + env: releaseEnv, }) if (!fs.existsSync(apkPath)) { diff --git a/apps/mobile/scripts/assert-aab-admob-config.js b/apps/mobile/scripts/assert-aab-admob-config.js new file mode 100644 index 0000000000..f7eb2e4d33 --- /dev/null +++ b/apps/mobile/scripts/assert-aab-admob-config.js @@ -0,0 +1,67 @@ +const fs = require("node:fs"); +const { execFileSync } = require("node:child_process"); +const { + SAMPLE_AD_UNIT_IDS, +} = require("./assert-production-admob-config"); + +const JS_BUNDLE_ENTRY = "base/assets/index.android.bundle"; + +function readRequiredEnv(name) { + const value = process.env[name]; + + if (typeof value !== "string" || value.trim().length === 0) { + throw new Error(`Missing required environment variable: ${name}`); + } + + return value.trim(); +} + +function readJsBundle(aabPath) { + return execFileSync("unzip", ["-p", aabPath, JS_BUNDLE_ENTRY], { + maxBuffer: 256 * 1024 * 1024, + }).toString("latin1"); +} + +function assertAabAdMobConfig(aabPath) { + if (!fs.existsSync(aabPath)) { + throw new Error(`AAB not found at ${aabPath}`); + } + + const expectedUnitIds = [ + readRequiredEnv("EXPO_PUBLIC_ADMOB_ANDROID_INTERSTITIAL_ID"), + readRequiredEnv("EXPO_PUBLIC_ADMOB_ANDROID_REWARDED_ID"), + ]; + + const bundle = readJsBundle(aabPath); + + const foundSampleId = SAMPLE_AD_UNIT_IDS.find((sampleId) => + bundle.includes(sampleId) + ); + if (foundSampleId) { + throw new Error( + `Shipped AAB embeds a Google sample AdMob ID: ${foundSampleId}` + ); + } + + const missingUnitId = expectedUnitIds.find( + (unitId) => !bundle.includes(unitId) + ); + if (missingUnitId) { + throw new Error( + `Shipped AAB does not embed the production AdMob ID: ${missingUnitId}` + ); + } +} + +if (require.main === module) { + const aabPath = process.argv[2]; + + if (!aabPath) { + throw new Error( + "Usage: node scripts/assert-aab-admob-config.js " + ); + } + + assertAabAdMobConfig(aabPath); + console.log("Shipped AAB AdMob validation passed."); +} diff --git a/apps/mobile/scripts/assert-production-admob-config.js b/apps/mobile/scripts/assert-production-admob-config.js new file mode 100644 index 0000000000..97189159fe --- /dev/null +++ b/apps/mobile/scripts/assert-production-admob-config.js @@ -0,0 +1,97 @@ +const fs = require("node:fs"); + +const SAMPLE_AD_UNIT_IDS = [ + "ca-app-pub-3940256099942544~3347511713", + "ca-app-pub-3940256099942544/1033173712", + "ca-app-pub-3940256099942544/5224354917", +]; + +function readRequiredEnv(name) { + const value = process.env[name]; + + if (typeof value !== "string" || value.trim().length === 0) { + throw new Error(`Missing required environment variable: ${name}`); + } + + return value.trim(); +} + +function findAdMobPluginOptions(config) { + const plugins = Array.isArray(config.plugins) + ? config.plugins + : Array.isArray(config.expo?.plugins) + ? config.expo.plugins + : []; + + const adMobPlugin = plugins.find((plugin) => + Array.isArray(plugin) + ? plugin[0] === "react-native-google-mobile-ads" + : plugin === "react-native-google-mobile-ads" + ); + + return Array.isArray(adMobPlugin) && + adMobPlugin[1] && + typeof adMobPlugin[1] === "object" + ? adMobPlugin[1] + : {}; +} + +function assertResolvedId(label, actual, expected) { + if (actual !== expected) { + throw new Error(`Expected ${label}=${expected}, got ${String(actual)}`); + } + + if (SAMPLE_AD_UNIT_IDS.includes(actual)) { + throw new Error(`Detected Google sample AdMob ID for ${label}`); + } +} + +function assertProductionAdMobConfig(config) { + const expected = { + androidAppId: readRequiredEnv("EXPO_PUBLIC_ADMOB_ANDROID_APP_ID"), + androidInterstitialId: readRequiredEnv( + "EXPO_PUBLIC_ADMOB_ANDROID_INTERSTITIAL_ID" + ), + androidRewardedId: readRequiredEnv("EXPO_PUBLIC_ADMOB_ANDROID_REWARDED_ID"), + }; + + const extra = config.extra ?? config.expo?.extra ?? {}; + const adMob = extra.adMob ?? {}; + + if (adMob.useTestIds !== false) { + throw new Error( + `Expected extra.adMob.useTestIds=false, got ${String(adMob.useTestIds)}` + ); + } + + assertResolvedId( + "react-native-google-mobile-ads.androidAppId", + findAdMobPluginOptions(config).androidAppId, + expected.androidAppId + ); + assertResolvedId( + "extra.adMob.androidInterstitialId", + adMob.androidInterstitialId, + expected.androidInterstitialId + ); + assertResolvedId( + "extra.adMob.androidRewardedId", + adMob.androidRewardedId, + expected.androidRewardedId + ); +} + +if (require.main === module) { + const configPath = process.argv[2]; + + if (!configPath) { + throw new Error( + "Usage: node scripts/assert-production-admob-config.js " + ); + } + + assertProductionAdMobConfig(JSON.parse(fs.readFileSync(configPath, "utf8"))); + console.log("Expo AdMob config validation passed."); +} + +module.exports = { assertProductionAdMobConfig, SAMPLE_AD_UNIT_IDS }; diff --git a/apps/mobile/scripts/production-admob-env.js b/apps/mobile/scripts/production-admob-env.js new file mode 100644 index 0000000000..602fbe7b39 --- /dev/null +++ b/apps/mobile/scripts/production-admob-env.js @@ -0,0 +1,27 @@ +const REQUIRED_AD_UNIT_ENV_VARS = [ + "EXPO_PUBLIC_ADMOB_ANDROID_APP_ID", + "EXPO_PUBLIC_ADMOB_ANDROID_INTERSTITIAL_ID", + "EXPO_PUBLIC_ADMOB_ANDROID_REWARDED_ID", +]; + +function resolveProductionAdMobEnv(baseEnv) { + const missing = REQUIRED_AD_UNIT_ENV_VARS.filter( + (name) => + typeof baseEnv[name] !== "string" || baseEnv[name].trim().length === 0 + ); + + if (missing.length > 0) { + throw new Error( + `Cannot build a release without production AdMob IDs. Set ${missing.join(", ")} ` + + "before building (a release built without them ships Google test ad units)." + ); + } + + return { + ...baseEnv, + EAS_BUILD_PROFILE: "production", + EXPO_PUBLIC_ADMOB_USE_TEST_IDS: "false", + }; +} + +module.exports = { resolveProductionAdMobEnv };