Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(android): fetch pinned Firebase configuration from Doppler (#7273)

Peter Chinmande48657be1b3
diff --git a/apps/web/justfile b/apps/web/justfile
index 62c998f47c..52c28e5b05 100644
--- a/apps/web/justfile
+++ b/apps/web/justfile
@@ -1,6 +1,6 @@
set positional-arguments
-# Android: SDK/JDK setup and optional Firebase config are handled by the launcher.
+# Android: the launcher fetches pinned Firebase config from Doppler by default.
android-dev *ARGS:
bash scripts/android.sh dev "$@"
diff --git a/apps/web/scripts/android-firebase.lock.json b/apps/web/scripts/android-firebase.lock.json
new file mode 100644
index 0000000000..de01472508
--- /dev/null
+++ b/apps/web/scripts/android-firebase.lock.json
@@ -0,0 +1,14 @@
+{
+ "dev": {
+ "project": "android-release",
+ "config": "dev",
+ "secret": "GOOGLE_SERVICES_JSON_V1",
+ "sha256": "2462d00a44657518daad1da298f57e108811ebc2e6dea00673696a30dd8dbbae"
+ },
+ "build": {
+ "project": "android-release",
+ "config": "prd",
+ "secret": "GOOGLE_SERVICES_JSON_V1",
+ "sha256": "8d16839be88a544f205edfbf25e9561f20fd5016bcc0c0fdf3f8a313d29b780a"
+ }
+}
diff --git a/apps/web/scripts/android-firebase.test.ts b/apps/web/scripts/android-firebase.test.ts
index af615111c6..21d83ddc7e 100644
--- a/apps/web/scripts/android-firebase.test.ts
+++ b/apps/web/scripts/android-firebase.test.ts
@@ -1,10 +1,22 @@
-import { spawnSync } from 'node:child_process';
+import { execFileSync, spawnSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { describe, expect, it } from 'vitest';
-import { validateAndroidFirebase } from './android-firebase';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ fetchAndroidFirebase,
+ prepareAndroidFirebase,
+ validateAndroidFirebase,
+} from './android-firebase';
+
+vi.mock('node:child_process', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('node:child_process')>()),
+ execFileSync: vi.fn(),
+}));
+
+afterEach(() => vi.mocked(execFileSync).mockReset());
const config = (project: string, packageName = 'com.macro.app.prod') => ({
project_info: { project_id: project, project_number: '123456789' },
@@ -38,6 +50,18 @@ describe('Android Firebase environment selection', () => {
).toThrow('must use macro-app-dev-12ae0');
});
+ it('allows a fork project only with an explicit override', () => {
+ const fork = config('my-fork');
+ expect(() => validateAndroidFirebase(fork, 'build')).toThrow();
+ expect(() => validateAndroidFirebase(fork, 'build', true)).not.toThrow();
+ expect(() =>
+ validateAndroidFirebase(config('macro-app-dev-12ae0'), 'build', true)
+ ).toThrow('must use macro-app-955f1');
+ expect(() =>
+ validateAndroidFirebase(config('my-fork', 'wrong.package'), 'build', true)
+ ).toThrow('must contain com.macro.app.prod');
+ });
+
it.each([undefined, ''])(
'rejects missing or empty Firebase fields (%s)',
(value) => {
@@ -57,7 +81,10 @@ describe('Android Firebase environment selection', () => {
},
],
},
- { ...valid, client: [{ ...client, api_key: [{ current_key: value }] }] },
+ {
+ ...valid,
+ client: [{ ...client, api_key: [{ current_key: value }] }],
+ },
{ ...valid, client: [{ ...client, api_key: [] }] },
{ ...valid, client: [{ ...client, api_key: undefined }] },
]) {
@@ -100,3 +127,90 @@ describe('Android Firebase environment selection', () => {
);
});
});
+
+describe('Pinned Android Firebase download', () => {
+ const contents = JSON.stringify(config('macro-app-955f1'));
+ const pin = {
+ project: 'android-release',
+ config: 'prd',
+ secret: 'GOOGLE_SERVICES_JSON_V1',
+ sha256: createHash('sha256').update(contents).digest('hex'),
+ };
+
+ it('fetches only the pinned key and verifies it, ignoring CLI whitespace', () => {
+ vi.mocked(execFileSync).mockReturnValue(`${contents}\n`);
+ expect(fetchAndroidFirebase(pin)).toBe(contents);
+ expect(execFileSync).toHaveBeenCalledWith(
+ 'doppler',
+ [
+ 'secrets',
+ 'get',
+ pin.secret,
+ '--project',
+ pin.project,
+ '--config',
+ pin.config,
+ '--plain',
+ '--raw',
+ '--no-check-version',
+ ],
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }
+ );
+ });
+
+ it('rejects a changed remote value without printing its contents', () => {
+ vi.mocked(execFileSync).mockReturnValue('private-config-marker');
+ expect(() => fetchAndroidFirebase(pin)).toThrow('checksum mismatch');
+ expect(() => fetchAndroidFirebase(pin)).not.toThrow(
+ 'private-config-marker'
+ );
+ });
+
+ it('reports authentication or CLI failures without exposing subprocess output', () => {
+ vi.mocked(execFileSync).mockImplementation(() => {
+ throw new Error('private-config-marker');
+ });
+ expect(() => fetchAndroidFirebase(pin)).toThrow('Install the Doppler CLI');
+ expect(() => fetchAndroidFirebase(pin)).not.toThrow(
+ 'private-config-marker'
+ );
+ });
+
+ it('never falls back to an existing destination when fetching fails', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'android-firebase-'));
+ const destination = join(root, 'google-services.json');
+ try {
+ await writeFile(destination, contents);
+ vi.mocked(execFileSync).mockImplementation(() => {
+ throw new Error('offline');
+ });
+ await expect(
+ prepareAndroidFirebase('build', '--doppler', destination)
+ ).rejects.toThrow('Unable to fetch');
+ expect(await readFile(destination, 'utf8')).toBe(contents);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it('keeps the destination intact on invalid JSON and supports offline overrides', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'android-firebase-'));
+ const source = join(root, 'source.json');
+ const destination = join(root, 'google-services.json');
+ try {
+ await writeFile(destination, contents);
+ await writeFile(source, 'invalid-private-config-marker');
+ await expect(
+ prepareAndroidFirebase('build', source, destination)
+ ).rejects.toThrow('Invalid Android Firebase configuration JSON');
+ expect(await readFile(destination, 'utf8')).toBe(contents);
+ const fork = JSON.stringify(config('my-fork'));
+ await writeFile(source, fork);
+ await prepareAndroidFirebase('build', source, destination);
+ expect(await readFile(destination, 'utf8')).toBe(fork);
+ expect(execFileSync).not.toHaveBeenCalled();
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/apps/web/scripts/android-firebase.ts b/apps/web/scripts/android-firebase.ts
index f3661dcb6c..be5740cdb4 100644
--- a/apps/web/scripts/android-firebase.ts
+++ b/apps/web/scripts/android-firebase.ts
@@ -1,12 +1,22 @@
-import { copyFile, mkdir } from 'node:fs/promises';
-import { dirname, resolve } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ rename,
+ rm,
+ writeFile,
+} from 'node:fs/promises';
+import { dirname, join } from 'node:path';
import { z } from 'zod';
+import pins from './android-firebase.lock.json';
// These projects match the dev/prod FCM credentials used by notification-service.
const projects = { dev: 'macro-app-dev-12ae0', build: 'macro-app-955f1' };
const configSchema = z.object({
project_info: z.object({
- project_id: z.string(),
+ project_id: z.string().min(1),
project_number: z.string().min(1),
}),
client: z.array(
@@ -22,7 +32,8 @@ const configSchema = z.object({
export function validateAndroidFirebase(
config: unknown,
- action: 'dev' | 'build'
+ action: 'dev' | 'build',
+ allowCustomProject = false
) {
const parsed = configSchema.safeParse(config);
if (!parsed.success)
@@ -35,21 +46,86 @@ export function validateAndroidFirebase(
)
)
throw new Error('Firebase config must contain com.macro.app.prod');
- if (parsed.data.project_info.project_id !== projects[action])
+ const project = parsed.data.project_info.project_id;
+ if (
+ project !== projects[action] &&
+ (!allowCustomProject || Object.values(projects).includes(project))
+ )
throw new Error(
`Firebase config for ${action} must use ${projects[action]}`
);
}
+export function fetchAndroidFirebase(pin: (typeof pins)['dev']) {
+ let contents: string;
+ try {
+ contents = execFileSync(
+ 'doppler',
+ [
+ 'secrets',
+ 'get',
+ pin.secret,
+ '--project',
+ pin.project,
+ '--config',
+ pin.config,
+ '--plain',
+ '--raw',
+ '--no-check-version',
+ ],
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }
+ ).trim();
+ } catch {
+ throw new Error(
+ `Unable to fetch Android Firebase config from Doppler ${pin.project}/${pin.config}. Install the Doppler CLI and authenticate with access to this config (CI: DOPPLER_TOKEN), or pass --firebase-config. See docs/ANDROID_DEVELOPMENT.md.`
+ );
+ }
+ if (createHash('sha256').update(contents).digest('hex') !== pin.sha256)
+ throw new Error(
+ 'Android Firebase config checksum mismatch. Restore the pinned Doppler value or review an update to android-firebase.lock.json.'
+ );
+ return contents;
+}
+
+export async function prepareAndroidFirebase(
+ action: 'dev' | 'build',
+ source: string,
+ destination: string
+) {
+ const pinned = source === '--doppler';
+ const contents = pinned
+ ? fetchAndroidFirebase(pins[action])
+ : await readFile(source, 'utf8');
+ let config: unknown;
+ try {
+ config = JSON.parse(contents);
+ } catch {
+ throw new Error('Invalid Android Firebase configuration JSON');
+ }
+ validateAndroidFirebase(config, action, !pinned);
+ await mkdir(dirname(destination), { recursive: true });
+ const temporary = await mkdtemp(join(dirname(destination), '.firebase-'));
+ try {
+ const file = join(temporary, 'google-services.json');
+ await writeFile(file, contents, { mode: 0o600 });
+ await rename(file, destination);
+ } finally {
+ await rm(temporary, { recursive: true, force: true });
+ }
+}
+
if (import.meta.main) {
const [action, source, destination] = process.argv.slice(2);
if ((action !== 'dev' && action !== 'build') || !source || !destination)
throw new Error(
- 'Usage: android-firebase.ts {dev|build} source destination'
+ 'Usage: android-firebase.ts {dev|build} {--doppler|source} destination'
+ );
+ try {
+ await prepareAndroidFirebase(action, source, destination);
+ } catch (error) {
+ console.error(
+ error instanceof Error ? error.message : 'Firebase setup failed'
);
- validateAndroidFirebase(await Bun.file(source).json(), action);
- if (resolve(source) !== resolve(destination)) {
- await mkdir(dirname(destination), { recursive: true });
- await copyFile(source, destination);
+ process.exitCode = 1;
}
}
diff --git a/apps/web/scripts/android-launcher.test.ts b/apps/web/scripts/android-launcher.test.ts
index 31b06f1bfc..bafe4ea5e6 100644
--- a/apps/web/scripts/android-launcher.test.ts
+++ b/apps/web/scripts/android-launcher.test.ts
@@ -66,6 +66,33 @@ describe('Android launcher arguments', () => {
readFileSync(path, 'utf8').split('\0').slice(0, -1);
for (const action of ['dev', 'build']) {
+ it(`fetches pinned config for android-${action} even when local files exist`, () => {
+ for (const directory of [
+ 'firebase/dev',
+ 'firebase/prod',
+ 'gen/android/app',
+ ]) {
+ const path = join(app, 'tauri/src-tauri', directory);
+ mkdirSync(path, { recursive: true });
+ writeFileSync(join(path, 'google-services.json'), '{}');
+ }
+ const result = spawnSync(
+ 'bash',
+ [join(app, 'scripts/android.sh'), action],
+ {
+ cwd: caller,
+ env,
+ }
+ );
+ expect(result.status, result.stderr.toString()).toBe(0);
+ expect(captured(join(root, 'bun.args'))).toEqual([
+ 'scripts/android-firebase.ts',
+ action,
+ '--doppler',
+ 'tauri/src-tauri/gen/android/app/google-services.json',
+ ]);
+ });
+
it(`forwards spaced paths and literal shell characters through android-${action}`, () => {
const config = join(caller, 'config files/google-services.json');
const extra = '{"label":"two words; $HOME"}';
@@ -98,6 +125,22 @@ describe('Android launcher arguments', () => {
});
}
+ it('does not invoke Cargo when Firebase setup fails', () => {
+ writeFileSync(join(root, 'bin', 'bun'), '#!/bin/sh\nexit 1\n', {
+ mode: 0o700,
+ });
+ const result = spawnSync(
+ 'bash',
+ [join(app, 'scripts/android.sh'), 'build'],
+ {
+ cwd: caller,
+ env,
+ }
+ );
+ expect(result.status).toBe(1);
+ expect(() => captured(join(root, 'cargo.args'))).toThrow();
+ });
+
it('resolves a relative Firebase path against the direct caller directory', () => {
const result = spawnSync(
'bash',
diff --git a/apps/web/scripts/android.sh b/apps/web/scripts/android.sh
index dd00e43dc2..fed32dc468 100644
--- a/apps/web/scripts/android.sh
+++ b/apps/web/scripts/android.sh
@@ -22,18 +22,8 @@ if [[ -n "$firebase_config" ]]; then
[[ -f "$firebase_config" ]] || { echo "Firebase configuration file not found" >&2; exit 1; }
fi
-firebase_environment=prod
-[[ "$action" != "dev" ]] || firebase_environment=dev
firebase_destination=tauri/src-tauri/gen/android/app/google-services.json
-firebase_default="tauri/src-tauri/firebase/$firebase_environment/google-services.json"
-if [[ -z "$firebase_config" && -f "$firebase_default" ]]; then
- firebase_config="$firebase_default"
-elif [[ -z "$firebase_config" && -f "$firebase_destination" ]]; then
- firebase_config="$firebase_destination"
-fi
-if [[ -n "$firebase_config" ]]; then
- bun scripts/android-firebase.ts "$action" "$firebase_config" "$firebase_destination"
-fi
+bun scripts/android-firebase.ts "$action" "${firebase_config:---doppler}" "$firebase_destination"
if [[ "$(uname)" == "Darwin" ]]; then
export ANDROID_HOME="${ANDROID_HOME:-$HOME/Library/Android/sdk}"
diff --git a/docs/ANDROID_DEVELOPMENT.md b/docs/ANDROID_DEVELOPMENT.md
index 40a9719ae3..eb9aaa67d9 100644
--- a/docs/ANDROID_DEVELOPMENT.md
+++ b/docs/ANDROID_DEVELOPMENT.md
@@ -96,8 +96,8 @@ its fingerprint to production associations before testing Play-installed links.
## Firebase
-Debug builds work without Firebase configuration for auth/navigation development.
-Remote notifications require the matching Firebase configuration and Google Play
+The launcher fetches Firebase configuration before both development and release
+builds. Remote notifications require the matching configuration and Google Play
services on the device. Notification permission alone does not register the
device: sign in to Macro and enable notifications in Settings. Android 13 and
newer show a runtime permission prompt; older versions use the app's system
@@ -125,22 +125,83 @@ The launcher requires package **com.macro.app.prod** and validates these project
| `android-dev` | `macro-app-dev-12ae0` |
| `android-build` (including `--debug`) | `macro-app-955f1` |
-Download `google-services.json` for that package from the matching Firebase
-project's settings. Keep local copies in ignored
-`tauri/src-tauri/firebase/dev/google-services.json` and
-`tauri/src-tauri/firebase/prod/google-services.json`; the launcher selects the
-matching file automatically. Alternatively, inject a downloaded configuration:
+### Reproducible configuration
+
+Install the Doppler CLI and run `doppler login` with access to the `android-release`
+project. A fresh checkout then needs no manually downloaded Firebase files:
+
+```sh
+just android-dev
+just android-build
+```
+
+The launcher reads `scripts/android-firebase.lock.json`, fetches only its named
+Doppler key (`dev` for development, `prd` for production), and checks the SHA-256
+of the UTF-8 value with leading/trailing whitespace removed. It validates the
+Firebase project and Android package before atomically writing the ignored
+`tauri/src-tauri/gen/android/app/google-services.json` consumed by Gradle.
+
+Each config has a versioned key, initially `GOOGLE_SERVICES_JSON_V1`. Missing
+authentication, a missing key, a checksum mismatch, or an invalid config stops
+the build before Cargo starts. Existing local config files are not a fallback:
+they cannot silently change which Firebase configuration a commit builds with.
+The config is fetched on each invocation, so the default path requires network
+access. The lock file pins Firebase configuration, not every input needed for
+byte-identical APKs; the toolchain, dependencies, frontend configuration, and
+release signing must also be supplied consistently.
+
+For CI, install the Doppler CLI and provide a read-only Doppler service token for
+`android-release/prd` as the CI secret `DOPPLER_TOKEN` (`android-release/dev` for
+development). Run the same `just android-build` command. The CLI uses this token
+without an interactive login. Never expose the production token to builds of
+untrusted fork PRs. This setup retrieves Firebase configuration only; release
+signing still uses the credentials described above.
+
+### Custom builds and forks
+
+To build without Doppler, explicitly supply a config downloaded from Firebase:
```sh
just android-dev --firebase-config /absolute/path/google-services.json
just android-build --firebase-config /absolute/path/google-services.json
```
-The launcher validates both the package and Firebase project before copying the
-file to ignored `gen/android/app/google-services.json`. It also validates an
-existing destination when no source is supplied, so switching build modes cannot
-silently reuse the wrong environment. Do not commit these files. Release builds
-fail with an explicit error if configuration is absent.
+An explicit file bypasses the Doppler fetch and checksum pin. It still must
+contain `com.macro.app.prod`, the current Android package. Other Firebase project
+IDs are allowed for forks; Macro's known dev/prod projects are still rejected
+when used with the opposite build command. Forks changing the Android package
+must also update the package validation in `scripts/android-firebase.ts` and
+configure their own backend. Local files under `firebase/dev` or `firebase/prod`
+are used only if passed explicitly with `--firebase-config`.
+
+Do not commit Firebase config files or Doppler tokens. Only the lock file belongs
+in Git; keeping the actual configs outside this public repository lets forks use
+their own Firebase resources.
+
+### Updating the pinned configuration
+
+1. Download the updated Android config from the intended Firebase project and
+ validate its package and project ID.
+2. Store it under a **new** key in the matching `android-release` Doppler config
+ (for example, `GOOGLE_SERVICES_JSON_V2`). Keep every older pinned key unchanged
+ so older commits remain buildable. Pass the value through stdin, not a command
+ argument, and suppress command output to avoid printing it:
+
+ ```sh
+ doppler secrets set GOOGLE_SERVICES_JSON_V2 --project android-release --config prd < /path/google-services.json > /dev/null
+ ```
+
+3. Update that environment's key and SHA-256 in `scripts/android-firebase.lock.json`.
+ Compute the checksum using the same whitespace normalization as the downloader:
+
+ ```sh
+ bun -e 'const text = (await Bun.file(process.argv[1]).text()).trim(); console.log(new Bun.CryptoHasher("sha256").update(text).digest("hex"));' /path/google-services.json
+ ```
+
+4. Test retrieval into a new temporary destination with
+ `bun scripts/android-firebase.ts build --doppler /tmp/android-firebase-check/google-services.json`
+ (use `dev` for development). Review and commit the lock-file change; never
+ replace the checksum just to silence an unexpected mismatch.
## Browser authentication