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 app init (#6842)

Peter Chinmanfded1f0eb6fc
diff --git a/apps/web/.env.production b/apps/web/.env.production
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/apps/web/README.md b/apps/web/README.md
index 5e39b75167..ad6f03b5db 100644
--- a/apps/web/README.md
+++ b/apps/web/README.md
@@ -6,6 +6,14 @@ We use the [bun](https://bun.sh/) as a javascript package manager and runtime fo
The production application is compiled down to a static javascript bundle using a traditional SPA-like architecture.
+## Production analytics configuration
+
+For local production builds, set `VITE_POSTHOG_API_KEY` in the ignored
+`apps/web/.env.production.local`. Vite loads this file automatically; use the
+existing build commands. The shared value is stored in Doppler `web-release/prd`.
+CI continues to inject the GitHub `POSTHOG_API_KEY` secret. Keep the value out of
+tracked env files.
+
### Toolchain Management
If you have the [nix](https://nixos.org/learn/) package manager installed on your system then you can drop into a nix shell where everything you need is installed for you.
diff --git a/apps/web/justfile b/apps/web/justfile
index 171b0f3f8f..2a7351808c 100644
--- a/apps/web/justfile
+++ b/apps/web/justfile
@@ -1,3 +1,12 @@
+set positional-arguments
+
+# Android: SDK/JDK setup and optional Firebase config are handled by the launcher.
+android-dev *ARGS:
+ bash scripts/android.sh dev "$@"
+
+android-build *ARGS:
+ bash scripts/android.sh build "$@"
+
# iOS: dev-facing, for testing in Simulator. Honors PORT like the web dev
# server (`PORT=3001 just ios-dev`): the vite server picks PORT up through
# beforeDevCommand's environment, and the --config merge points the webview's
diff --git a/apps/web/scripts/android-assetlinks.ts b/apps/web/scripts/android-assetlinks.ts
new file mode 100644
index 0000000000..21c2d3b363
--- /dev/null
+++ b/apps/web/scripts/android-assetlinks.ts
@@ -0,0 +1,16 @@
+const fingerprints = process.argv.slice(2).map((value) => value.toUpperCase());
+if (
+ fingerprints.length === 0 ||
+ fingerprints.some((value) => !/^(?:[A-F0-9]{2}:){31}[A-F0-9]{2}$/.test(value))
+) {
+ throw new Error('Pass one or more SHA-256 signing fingerprints (32 colon-separated bytes)');
+}
+
+console.log(JSON.stringify([{
+ relation: ['delegate_permission/common.handle_all_urls'],
+ target: {
+ namespace: 'android_app',
+ package_name: 'com.macro.app.prod',
+ sha256_cert_fingerprints: [...new Set(fingerprints)],
+ },
+}], null, 2));
diff --git a/apps/web/scripts/android-firebase.test.ts b/apps/web/scripts/android-firebase.test.ts
new file mode 100644
index 0000000000..af615111c6
--- /dev/null
+++ b/apps/web/scripts/android-firebase.test.ts
@@ -0,0 +1,102 @@
+import { spawnSync } from 'node:child_process';
+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';
+
+const config = (project: string, packageName = 'com.macro.app.prod') => ({
+ project_info: { project_id: project, project_number: '123456789' },
+ client: [
+ {
+ client_info: {
+ mobilesdk_app_id: '1:123456789:android:test',
+ android_client_info: { package_name: packageName },
+ },
+ api_key: [{ current_key: 'test-api-key' }],
+ },
+ ],
+});
+
+describe('Android Firebase environment selection', () => {
+ it('accepts the matching existing dev and production projects', () => {
+ expect(() =>
+ validateAndroidFirebase(config('macro-app-dev-12ae0'), 'dev')
+ ).not.toThrow();
+ expect(() =>
+ validateAndroidFirebase(config('macro-app-955f1'), 'build')
+ ).not.toThrow();
+ });
+
+ it('rejects crossed environments even with the correct package', () => {
+ expect(() =>
+ validateAndroidFirebase(config('macro-app-dev-12ae0'), 'build')
+ ).toThrow('must use macro-app-955f1');
+ expect(() =>
+ validateAndroidFirebase(config('macro-app-955f1'), 'dev')
+ ).toThrow('must use macro-app-dev-12ae0');
+ });
+
+ it.each([undefined, ''])(
+ 'rejects missing or empty Firebase fields (%s)',
+ (value) => {
+ const valid = config('macro-app-dev-12ae0');
+ const client = valid.client[0];
+ for (const incomplete of [
+ {
+ ...valid,
+ project_info: { ...valid.project_info, project_number: value },
+ },
+ {
+ ...valid,
+ client: [
+ {
+ ...client,
+ client_info: { ...client.client_info, mobilesdk_app_id: value },
+ },
+ ],
+ },
+ { ...valid, client: [{ ...client, api_key: [{ current_key: value }] }] },
+ { ...valid, client: [{ ...client, api_key: [] }] },
+ { ...valid, client: [{ ...client, api_key: undefined }] },
+ ]) {
+ expect(() => validateAndroidFirebase(incomplete, 'dev')).toThrow(
+ 'Invalid Android Firebase configuration'
+ );
+ }
+ }
+ );
+
+ it('copies Firebase config before the Android project directory exists', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'android-firebase-'));
+ try {
+ const source = join(root, 'google-services.json');
+ const destination = join(root, 'gen/android/app/google-services.json');
+ const contents = JSON.stringify(config('macro-app-dev-12ae0'));
+ await writeFile(source, contents);
+ const result = spawnSync('bun', [
+ fileURLToPath(new URL('./android-firebase.ts', import.meta.url)),
+ 'dev',
+ source,
+ destination,
+ ]);
+ expect(result.status, result.stderr.toString()).toBe(0);
+ expect(await readFile(destination, 'utf8')).toBe(contents);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it('rejects old scaffold packages and malformed configurations', () => {
+ expect(() =>
+ validateAndroidFirebase(
+ config('macro-app-dev-12ae0', 'com.tauri.dev'),
+ 'dev'
+ )
+ ).toThrow('must contain com.macro.app.prod');
+ expect(() => validateAndroidFirebase(null, 'dev')).toThrow(
+ 'Invalid Android Firebase configuration'
+ );
+ });
+});
diff --git a/apps/web/scripts/android-firebase.ts b/apps/web/scripts/android-firebase.ts
new file mode 100644
index 0000000000..f3661dcb6c
--- /dev/null
+++ b/apps/web/scripts/android-firebase.ts
@@ -0,0 +1,55 @@
+import { copyFile, mkdir } from 'node:fs/promises';
+import { dirname, resolve } from 'node:path';
+import { z } from 'zod';
+
+// 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_number: z.string().min(1),
+ }),
+ client: z.array(
+ z.object({
+ client_info: z.object({
+ mobilesdk_app_id: z.string().min(1),
+ android_client_info: z.object({ package_name: z.string() }),
+ }),
+ api_key: z.array(z.object({ current_key: z.string().min(1) })).min(1),
+ })
+ ),
+});
+
+export function validateAndroidFirebase(
+ config: unknown,
+ action: 'dev' | 'build'
+) {
+ const parsed = configSchema.safeParse(config);
+ if (!parsed.success)
+ throw new Error('Invalid Android Firebase configuration');
+ if (
+ !parsed.data.client.some(
+ (client) =>
+ client.client_info.android_client_info.package_name ===
+ 'com.macro.app.prod'
+ )
+ )
+ throw new Error('Firebase config must contain com.macro.app.prod');
+ if (parsed.data.project_info.project_id !== projects[action])
+ throw new Error(
+ `Firebase config for ${action} must use ${projects[action]}`
+ );
+}
+
+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'
+ );
+ validateAndroidFirebase(await Bun.file(source).json(), action);
+ if (resolve(source) !== resolve(destination)) {
+ await mkdir(dirname(destination), { recursive: true });
+ await copyFile(source, destination);
+ }
+}
diff --git a/apps/web/scripts/android-launcher.test.ts b/apps/web/scripts/android-launcher.test.ts
new file mode 100644
index 0000000000..31b06f1bfc
--- /dev/null
+++ b/apps/web/scripts/android-launcher.test.ts
@@ -0,0 +1,134 @@
+import { spawnSync } from 'node:child_process';
+import {
+ copyFileSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+const web = dirname(dirname(fileURLToPath(import.meta.url)));
+
+describe('Android launcher arguments', () => {
+ let root: string;
+ let app: string;
+ let caller: string;
+ let env: NodeJS.ProcessEnv;
+
+ beforeEach(() => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'macro android ')));
+ app = join(root, 'app');
+ caller = join(root, 'caller');
+ for (const path of [
+ 'app/scripts',
+ 'app/tauri/src-tauri',
+ 'caller/config files',
+ 'bin',
+ 'sdk/platforms/android-36',
+ 'ndk/toolchains/llvm',
+ ]) {
+ mkdirSync(join(root, path), { recursive: true });
+ }
+ copyFileSync(join(web, 'justfile'), join(app, 'justfile'));
+ copyFileSync(
+ join(web, 'scripts/android.sh'),
+ join(app, 'scripts/android.sh')
+ );
+ writeFileSync(join(caller, 'config files/google-services.json'), '{}');
+ for (const command of ['bun', 'cargo']) {
+ writeFileSync(
+ join(root, 'bin', command),
+ `#!/bin/sh\nprintf '%s\\0' "$@" > "$CAPTURE_${command.toUpperCase()}"\n`,
+ { mode: 0o700 }
+ );
+ }
+ env = {
+ ...process.env,
+ // CI's Nix startup file resets PATH, hiding the fixture's bun/cargo stubs.
+ BASH_ENV: '',
+ PATH: `${join(root, 'bin')}:${process.env.PATH}`,
+ ANDROID_HOME: join(root, 'sdk'),
+ NDK_HOME: join(root, 'ndk'),
+ CAPTURE_BUN: join(root, 'bun.args'),
+ CAPTURE_CARGO: join(root, 'cargo.args'),
+ };
+ });
+
+ afterEach(() => rmSync(root, { recursive: true, force: true }));
+
+ const captured = (path: string) =>
+ readFileSync(path, 'utf8').split('\0').slice(0, -1);
+
+ for (const action of ['dev', 'build']) {
+ 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"}';
+ const result = spawnSync(
+ 'just',
+ [
+ '--justfile',
+ join(app, 'justfile'),
+ `android-${action}`,
+ '--firebase-config',
+ config,
+ '--config',
+ extra,
+ ],
+ { cwd: caller, env }
+ );
+ expect(result.stderr.toString()).not.toContain(
+ 'Firebase configuration file not found'
+ );
+ expect(result.status, result.stderr.toString()).toBe(0);
+ expect(captured(join(root, 'bun.args'))).toEqual([
+ 'scripts/android-firebase.ts',
+ action,
+ config,
+ 'tauri/src-tauri/gen/android/app/google-services.json',
+ ]);
+ const args = captured(join(root, 'cargo.args'));
+ expect(args.slice(0, 3)).toEqual(['tauri', 'android', action]);
+ expect(args).toContain(extra);
+ });
+ }
+
+ it('resolves a relative Firebase path against the direct caller directory', () => {
+ const result = spawnSync(
+ 'bash',
+ [
+ join(app, 'scripts/android.sh'),
+ 'build',
+ '--firebase-config',
+ 'config files/google-services.json',
+ ],
+ { cwd: caller, env }
+ );
+ expect(result.status, result.stderr.toString()).toBe(0);
+ expect(captured(join(root, 'bun.args'))[2]).toBe(
+ join(caller, 'config files/google-services.json')
+ );
+ });
+
+ it('rejects missing Firebase input before invoking build tools', () => {
+ for (const args of [
+ ['--firebase-config'],
+ ['--firebase-config', 'missing.json'],
+ ]) {
+ const result = spawnSync(
+ 'bash',
+ [join(app, 'scripts/android.sh'), 'build', ...args],
+ { cwd: caller, env }
+ );
+ expect(result.status).toBe(1);
+ expect(result.stderr.toString()).toContain(
+ 'Firebase configuration file not found'
+ );
+ }
+ });
+});
diff --git a/apps/web/scripts/android.sh b/apps/web/scripts/android.sh
new file mode 100644
index 0000000000..dd00e43dc2
--- /dev/null
+++ b/apps/web/scripts/android.sh
@@ -0,0 +1,57 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+action="${1:-dev}"
+shift || true
+case "$action" in
+ dev|build) ;;
+ *) echo "Usage: android.sh {dev|build} [--firebase-config /path/google-services.json] [Tauri arguments]" >&2; exit 1 ;;
+esac
+
+firebase_config=""
+if [[ "${1:-}" == "--firebase-config" ]]; then
+ firebase_config="${2:-}"
+ [[ -n "$firebase_config" ]] || { echo "Firebase configuration file not found" >&2; exit 1; }
+ [[ "$firebase_config" = /* ]] || firebase_config="$PWD/$firebase_config"
+ shift 2
+fi
+
+script_dir="$(\cd "$(dirname "$0")" && pwd)"
+\cd "$script_dir/.."
+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
+
+if [[ "$(uname)" == "Darwin" ]]; then
+ export ANDROID_HOME="${ANDROID_HOME:-$HOME/Library/Android/sdk}"
+ if [[ -z "${JAVA_HOME:-}" && -d /opt/homebrew/opt/openjdk@21/libexec/openjdk.jdk/Contents/Home ]]; then
+ export JAVA_HOME=/opt/homebrew/opt/openjdk@21/libexec/openjdk.jdk/Contents/Home
+ fi
+else
+ export ANDROID_HOME="${ANDROID_HOME:-$HOME/Android/Sdk}"
+fi
+export NDK_HOME="${NDK_HOME:-$ANDROID_HOME/ndk/30.0.16248370}"
+[[ -d "$NDK_HOME/toolchains/llvm" ]] || { echo "Install NDK 30.0.16248370 or set NDK_HOME" >&2; exit 1; }
+[[ -d "$ANDROID_HOME/platforms/android-36" ]] || { echo "Install Android SDK Platform 36" >&2; exit 1; }
+export PATH="${JAVA_HOME:+$JAVA_HOME/bin:}$ANDROID_HOME/platform-tools:$PATH"
+
+\cd tauri/src-tauri
+if [[ "$action" == "dev" ]]; then
+ export PORT="${PORT:-3000}"
+ exec cargo tauri android dev --config "{\"build\":{\"devUrl\":\"http://localhost:${PORT}\"}}" "$@" -- --no-default-features
+else
+ exec cargo tauri android build --target aarch64 "$@"
+fi
diff --git a/apps/web/src/features/auth/GithubReauthenticationPrompt.test.tsx b/apps/web/src/features/auth/GithubReauthenticationPrompt.test.tsx
index 4840204ae8..2c490c1801 100644
--- a/apps/web/src/features/auth/GithubReauthenticationPrompt.test.tsx
+++ b/apps/web/src/features/auth/GithubReauthenticationPrompt.test.tsx
@@ -12,6 +12,24 @@ const mocks = vi.hoisted(() => ({
toastCustom: vi.fn(),
toastDismiss: vi.fn(),
toastFailure: vi.fn(),
+ nativeMobile: false,
+ authenticate: vi.fn(),
+ invalidateGithubLinkStatus: vi.fn(),
+}));
+
+vi.mock('@core/mobile/isNativeMobilePlatform', () => ({
+ isNativeMobilePlatform: () => mocks.nativeMobile,
+}));
+
+vi.mock('@core/auth/native-auth', () => ({
+ createNativeAuthSession: () => ({
+ callbackUrl: 'macro://android-auth/test-attempt',
+ authenticate: mocks.authenticate,
+ }),
+}));
+
+vi.mock('@queries/auth', () => ({
+ invalidateGithubLinkStatus: mocks.invalidateGithubLinkStatus,
}));
vi.mock('@core/component/Toast/Toast', () => ({
@@ -85,6 +103,10 @@ beforeEach(() => {
mocks.toastCustom.mockReset();
mocks.toastDismiss.mockReset();
mocks.toastFailure.mockReset();
+ mocks.nativeMobile = false;
+ mocks.authenticate.mockReset();
+ mocks.invalidateGithubLinkStatus.mockReset();
+ mocks.invalidateGithubLinkStatus.mockResolvedValue(undefined);
mocks.toastCustom.mockReturnValue(101);
});
@@ -95,6 +117,48 @@ afterEach(() => {
});
describe('GithubReauthenticationPrompt', () => {
+ it.each([
+ { result: { success: true }, invalidates: true, failure: false },
+ {
+ result: { success: false, error: 'User canceled login' },
+ invalidates: false,
+ failure: false,
+ },
+ {
+ result: { success: false, error: 'Authentication browser failed' },
+ invalidates: false,
+ failure: true,
+ },
+ ])(
+ 'handles native reconnect result $result',
+ async ({ result, invalidates, failure }) => {
+ mocks.nativeMobile = true;
+ mocks.checkGithubLinkStatus.mockResolvedValue(
+ resultErr([{ code: 'REAUTHENTICATION_REQUIRED', message: 'Reconnect' }])
+ );
+ const originalUrl = window.location.href;
+ const authorizationUrl = 'https://github.com/login/oauth/authorize';
+ mocks.reauthenticateGithub.mockResolvedValue(resultOk(authorizationUrl));
+ mocks.authenticate.mockResolvedValue(result);
+
+ const cleanup = renderPrompt();
+ await flushPromises();
+ await getReconnectAction().onClick();
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(mocks.reauthenticateGithub).toHaveBeenCalledWith(
+ 'macro://android-auth/test-attempt'
+ );
+ expect(mocks.authenticate).toHaveBeenCalledWith(authorizationUrl);
+ expect(window.location.href).toBe(originalUrl);
+ expect(mocks.invalidateGithubLinkStatus).toHaveBeenCalledTimes(
+ invalidates ? 1 : 0
+ );
+ expect(mocks.toastFailure).toHaveBeenCalledTimes(failure ? 1 : 0);
+ cleanup();
+ }
+ );
+
it('shows a reconnect toast globally when GitHub reauthentication is required', async () => {
mocks.checkGithubLinkStatus.mockResolvedValue(
resultErr([
diff --git a/apps/web/src/features/auth/GithubReauthenticationPrompt.tsx b/apps/web/src/features/auth/GithubReauthenticationPrompt.tsx
index 6c16dfe3c1..a11b3d4225 100644
--- a/apps/web/src/features/auth/GithubReauthenticationPrompt.tsx
+++ b/apps/web/src/features/auth/GithubReauthenticationPrompt.tsx
@@ -1,5 +1,7 @@
+import { authorizeGithub } from '@core/auth/authorize-github';
import { toast } from '@core/component/Toast/Toast';
import { useKeyedPersistentToasts } from '@core/component/Toast/useKeyedPersistentToasts';
+import { throwOnErr } from '@core/util/result';
import { authServiceClient } from '@service-auth/client';
import { createSignal, onMount } from 'solid-js';
@@ -12,18 +14,17 @@ async function checkGithubReauthenticationStatus(): Promise<boolean> {
);
}
-/** Kick off the OAuth flow; on success the browser navigates away. */
+/** Kick off the OAuth flow; the web navigates away, native completes in-app. */
async function startGithubReauthentication(): Promise<void> {
- const result = await authServiceClient.reauthenticateGithub(
- window.location.href
- );
-
- if (result.isErr()) {
+ try {
+ await authorizeGithub(
+ (callbackUrl) =>
+ throwOnErr(() => authServiceClient.reauthenticateGithub(callbackUrl)),
+ 'Failed to reconnect GitHub'
+ );
+ } catch {
toast.failure('Failed to start GitHub reconnect flow');
- return;
}
-
- window.location.href = result.value;
}
/**
@@ -51,8 +52,8 @@ export function GithubReauthenticationPrompt() {
{
label: 'Reconnect',
onClick: () => {
- // Suppress re-prompting while the OAuth flow runs; success
- // navigates the page away entirely.
+ // Suppress re-prompting while the OAuth flow runs. On the web
+ // success navigates away; on native the link status is refetched.
dismiss();
void startGithubReauthentication();
},
diff --git a/apps/web/src/features/auth/mobile-onboarding/OnboardingConnectAccounts.tsx b/apps/web/src/features/auth/mobile-onboarding/OnboardingConnectAccounts.tsx
index 5a77b549c0..fbbf1688eb 100644
--- a/apps/web/src/features/auth/mobile-onboarding/OnboardingConnectAccounts.tsx
+++ b/apps/web/src/features/auth/mobile-onboarding/OnboardingConnectAccounts.tsx
@@ -1,16 +1,14 @@
+import { authorizeGithub } from '@core/auth/authorize-github';
import { toast } from '@core/component/Toast/Toast';
import { useIsAuthenticated } from '@core/context/user';
import { useAddInboxFlow } from '@core/email-link';
-import { getNativeMobilePlatform } from '@core/util/platform';
import IconGoogle from '@icon/macro-google.svg';
import GithubIcon from '@icon/mcp-github.svg';
import {
- invalidateGithubLinkStatus,
useGithubLinkStatusQuery,
useInitGithubLinkMutation,
} from '@queries/auth';
import { useEmailLinksQuery } from '@queries/email/link';
-import { invoke } from '@tauri-apps/api/core';
import { Button } from '@ui';
import { createSignal, For, type JSX, Show } from 'solid-js';
@@ -59,42 +57,12 @@ export function OnboardingConnectAccounts() {
toast.success('GitHub connected (debug)');
return;
}
- const isIos = getNativeMobilePlatform() === 'ios';
try {
- const authorizationUrl = await initGithubLink.mutateAsync(
- isIos ? 'macro://github-link-callback' : window.location.href
+ const linked = await authorizeGithub(
+ (callbackUrl) => initGithubLink.mutateAsync(callbackUrl),
+ 'Failed to connect GitHub'
);
-
- if (!isIos) {
- // Web / non-iOS native: the OAuth callback redirects back to original_url.
- window.location.href = authorizationUrl;
- return;
- }
-
- // iOS: run the OAuth inline in an ASWebAuthenticationSession via the Tauri
- // auth plugin; the GitHub link is completed server-side when the callback
- // fires, so we just refresh the status afterwards.
- const auth = await invoke<{
- success: boolean;
- token?: string;
- error?: string;
- }>('plugin:auth|authenticate', {
- payload: {
- authUrl: authorizationUrl,
- callbackScheme: 'macro',
- ephemeralSession: true,
- },
- });
-
- if (!auth.success) {
- if (auth.error !== 'User canceled login') {
- toast.failure('Failed to connect GitHub');
- }
- return;
- }
-
- await invalidateGithubLinkStatus();
- toast.success('GitHub connected');
+ if (linked) toast.success('GitHub connected');
} catch (error) {
console.error('connect github failed', error);
toast.failure('Failed to connect GitHub');
diff --git a/apps/web/src/features/auth/useSsoLogin.test.ts b/apps/web/src/features/auth/useSsoLogin.test.ts
new file mode 100644
index 0000000000..9bd83c4fe3
--- /dev/null
+++ b/apps/web/src/features/auth/useSsoLogin.test.ts
@@ -0,0 +1,145 @@
+import type { RedirectLocation } from '@core/util/authRedirect';
+import { ok } from 'neverthrow';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ nativeMobile: false,
+ servers: { 'auth-service': '' },
+ location: { state: undefined as RedirectLocation | undefined },
+ track: vi.fn(),
+ createNativeAuthSession: vi.fn(),
+ authenticate: vi.fn(),
+ sessionLogin: vi.fn(),
+ unsetTokenPromise: vi.fn(),
+ invalidateAllAfterLogin: vi.fn(),
+ initEmailLink: vi.fn(),
+}));
+
+vi.mock('@app/lib/analytics/analytics-context', () => ({
+ useAnalytics: () => ({ track: mocks.track }),
+}));
+vi.mock('@solidjs/router', () => ({ useLocation: () => mocks.location }));
+vi.mock('@core/constant/servers', () => ({ SERVER_HOSTS: mocks.servers }));
+vi.mock('@core/mobile/isNativeMobilePlatform', () => ({
+ isNativeMobilePlatform: () => mocks.nativeMobile,
+}));
+vi.mock('@core/auth/native-auth', () => ({
+ createNativeAuthSession: mocks.createNativeAuthSession,
+}));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { failure: vi.fn() },
+}));
+vi.mock('@core/email-link', () => ({
+ useEmailLinks: () => ({ initEmailLink: mocks.initEmailLink }),
+}));
+vi.mock('@core/util/fetchWithToken', () => ({
+ unsetTokenPromise: mocks.unsetTokenPromise,
+}));
+vi.mock('@queries/auth/user-info', () => ({
+ invalidateAllAfterLogin: mocks.invalidateAllAfterLogin,
+}));
+vi.mock('@service-auth/client', () => ({
+ authServiceClient: { sessionLogin: mocks.sessionLogin },
+}));
+
+import { useSsoLogin } from './useSsoLogin';
+
+const loginUrl = 'https://localhost:3003/app/login?referral_code=invite';
+const proxyAuthHost = 'https://localhost:3003/__macro_dev/gateway/auth';
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.stubGlobal('window', {
+ location: { href: loginUrl, origin: new URL(loginUrl).origin },
+ });
+ mocks.nativeMobile = false;
+ mocks.servers['auth-service'] = proxyAuthHost;
+ mocks.location.state = undefined;
+ mocks.createNativeAuthSession.mockReturnValue({
+ callbackUrl: 'macro://android-auth/test-attempt',
+ authenticate: mocks.authenticate,
+ });
+ mocks.authenticate.mockResolvedValue({
+ success: true,
+ token: 'session-code',
+ });
+ mocks.sessionLogin.mockResolvedValue(ok(undefined));
+ mocks.initEmailLink.mockReturnValue(ok(undefined));
+});
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe('useSsoLogin', () => {
+ it.each([
+ { host: proxyAuthHost, mobile: 'true' },
+ { host: 'https://gateway.macro.com/auth', mobile: null },
+ ])('redirects browser SSO through $host', async ({ host, mobile }) => {
+ mocks.servers['auth-service'] = host;
+
+ await useSsoLogin()('google');
+
+ const redirect = new URL(window.location.href);
+ expect(`${redirect.origin}${redirect.pathname}`).toBe(`${host}/login/sso`);
+ expect(redirect.searchParams.get('is_mobile')).toBe(mobile);
+ expect(redirect.searchParams.get('original_url')).toBe(loginUrl);
+ expect(redirect.searchParams.get('referral_code')).toBe('invite');
+ expect(redirect.searchParams.get('idp_name')).toBe('google');
+ expect(mocks.createNativeAuthSession).not.toHaveBeenCalled();
+ expect(mocks.sessionLogin).not.toHaveBeenCalled();
+ expect(mocks.track).toHaveBeenCalledWith('login', { method: 'google' }, [
+ 'posthog',
+ ]);
+ });
+
+ it('preserves the original browser destination through proxy SSO', async () => {
+ window.location.href = 'https://localhost:3003/app/login';
+ mocks.location.state = {
+ originalLocation: {
+ state: null,
+ key: '',
+ query: { referral_code: 'original-invite' },
+ pathname: '/app/doc/document-id',
+ search: '?referral_code=original-invite',
+ hash: '#comment',
+ },
+ };
+
+ await useSsoLogin({ signupMode: true })('google');
+
+ const redirect = new URL(window.location.href);
+ expect(redirect.searchParams.get('original_url')).toBe(
+ 'https://localhost:3003/app/doc/document-id?referral_code=original-invite#comment'
+ );
+ expect(redirect.searchParams.get('referral_code')).toBe('original-invite');
+ expect(mocks.createNativeAuthSession).not.toHaveBeenCalled();
+ expect(mocks.track).toHaveBeenCalledWith(
+ 'sign_up_click',
+ { method: 'google' },
+ ['posthog']
+ );
+ });
+
+ it.each([proxyAuthHost, 'https://gateway.macro.com/auth'])(
+ 'uses native authentication and redeems the session code through %s',
+ async (host) => {
+ mocks.nativeMobile = true;
+ mocks.servers['auth-service'] = host;
+
+ await useSsoLogin()('google');
+
+ expect(mocks.createNativeAuthSession).toHaveBeenCalledWith('login');
+ const authUrl = new URL(mocks.authenticate.mock.calls[0][0]);
+ expect(authUrl.searchParams.get('is_mobile')).toBe('true');
+ expect(authUrl.searchParams.get('original_url')).toBe(
+ 'macro://android-auth/test-attempt'
+ );
+ expect(mocks.sessionLogin).toHaveBeenCalledWith({
+ session_code: 'session-code',
+ });
+ expect(mocks.unsetTokenPromise).toHaveBeenCalledOnce();
+ expect(mocks.invalidateAllAfterLogin).toHaveBeenCalledOnce();
+ expect(mocks.initEmailLink).toHaveBeenCalledOnce();
+ expect(window.location.href).toBe(loginUrl);
+ }
+ );
+});
diff --git a/apps/web/src/features/auth/useSsoLogin.ts b/apps/web/src/features/auth/useSsoLogin.ts
index fba9763240..7aef34fe1d 100644
--- a/apps/web/src/features/auth/useSsoLogin.ts
+++ b/apps/web/src/features/auth/useSsoLogin.ts
@@ -1,16 +1,15 @@
import type { AnalyticsProvider } from '@app/lib/analytics';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
+import { createNativeAuthSession } from '@core/auth/native-auth';
import { toast } from '@core/component/Toast/Toast';
import { SERVER_HOSTS } from '@core/constant/servers';
import { useEmailLinks } from '@core/email-link';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import type { RedirectLocation } from '@core/util/authRedirect';
import { unsetTokenPromise } from '@core/util/fetchWithToken';
-import { getNativeMobilePlatform } from '@core/util/platform';
import { invalidateAllAfterLogin } from '@queries/auth/user-info';
import { authServiceClient } from '@service-auth/client';
import { useLocation } from '@solidjs/router';
-import { invoke } from '@tauri-apps/api/core';
import { DEVELOPMENT_PROXY_PREFIX } from '../../lib/core/constant/developmentProxy';
export function useSsoLogin(opts?: { signupMode?: boolean }) {
@@ -45,22 +44,10 @@ export function useSsoLogin(opts?: { signupMode?: boolean }) {
authUrl.searchParams.set('is_mobile', 'true');
}
- if (getNativeMobilePlatform() === 'ios') {
- // iOS: use ASWebAuthenticationSession via tauri-plugin-auth
- // so the auth flow stays in-app (required by App Store)
- authUrl.searchParams.set('original_url', 'macro://login');
-
- const result = await invoke<{
- success: boolean;
- token?: string;
- error?: string;
- }>('plugin:auth|authenticate', {
- payload: {
- authUrl: authUrl.toString(),
- callbackScheme: 'macro',
- ephemeralSession: true,
- },
- });
+ if (isNativeMobilePlatform()) {
+ const session = createNativeAuthSession('login');
+ authUrl.searchParams.set('original_url', session.callbackUrl);
+ const result = await session.authenticate(authUrl.toString());
if (!result.success || !result.token) {
// A canceled sheet is a deliberate user action, not a failure.
diff --git a/apps/web/src/features/paywall/use-checkout-completion-listener.test.ts b/apps/web/src/features/paywall/use-checkout-completion-listener.test.ts
new file mode 100644
index 0000000000..76eaef17ce
--- /dev/null
+++ b/apps/web/src/features/paywall/use-checkout-completion-listener.test.ts
@@ -0,0 +1,128 @@
+// @vitest-environment jsdom
+
+import { createRoot } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ track: vi.fn(),
+ success: vi.fn(),
+ refetch: vi.fn(),
+ setSearch: (_value: string) => {},
+}));
+
+vi.mock('@app/lib/analytics/analytics-context', () => ({
+ useAnalytics: () => ({ track: mocks.track }),
+}));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { success: mocks.success },
+}));
+vi.mock('@queries/auth/user-info', () => ({
+ useUserInfoQuery: () => ({ refetch: mocks.refetch }),
+}));
+vi.mock('@solidjs/router', async () => {
+ const { createSignal } = await import('solid-js');
+ const [search, setSearch] = createSignal('');
+ mocks.setSearch = setSearch;
+ return {
+ useSearchParams: () => [
+ {
+ get subscriptionSuccess() {
+ return new URLSearchParams(search()).get('subscriptionSuccess');
+ },
+ get subscriptionCancel() {
+ return new URLSearchParams(search()).get('subscriptionCancel');
+ },
+ get type() {
+ return new URLSearchParams(search()).get('type');
+ },
+ get tier() {
+ return new URLSearchParams(search()).get('tier');
+ },
+ },
+ () => {},
+ ],
+ };
+});
+
+import { useCheckoutCompletionListener } from './use-checkout-completion-listener';
+
+let dispose: (() => void) | undefined;
+function mount() {
+ return createRoot((cleanup) => {
+ dispose = cleanup;
+ return useCheckoutCompletionListener();
+ });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.setSearch('');
+ mocks.refetch.mockResolvedValue({ data: { licenseStatus: 'active' } });
+});
+afterEach(() => {
+ dispose?.();
+ dispose = undefined;
+ vi.useRealTimers();
+});
+
+describe('checkout completion query changes', () => {
+ it('gates a late success immediately, refreshes, and handles it only once', async () => {
+ let finish!: (value: { data: { licenseStatus: string } }) => void;
+ mocks.refetch.mockReturnValue(
+ new Promise((resolve) => {
+ finish = resolve;
+ })
+ );
+ const pending = mount();
+ expect(pending()).toBe(false);
+
+ mocks.setSearch('?subscriptionSuccess=true&type=pro');
+ expect(pending()).toBe(true);
+ expect(mocks.refetch).toHaveBeenCalledTimes(1);
+ expect(mocks.track).toHaveBeenCalledWith('subscription_success', {
+ type: 'pro',
+ });
+ finish({ data: { licenseStatus: 'active' } });
+ await vi.waitFor(() => expect(pending()).toBe(false));
+
+ mocks.setSearch('');
+ mocks.setSearch('?subscriptionSuccess=true&type=team');
+ expect(mocks.refetch).toHaveBeenCalledTimes(1);
+ expect(mocks.success).toHaveBeenCalledTimes(1);
+ expect(pending()).toBe(false);
+ });
+
+ it('retains initial-query refresh behavior', async () => {
+ mocks.setSearch('?subscriptionSuccess=true&type=pro');
+ const pending = mount();
+ expect(pending()).toBe(true);
+ await vi.waitFor(() => expect(pending()).toBe(false));
+ expect(mocks.refetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('records a late cancellation once without blocking navigation', () => {
+ const pending = mount();
+ mocks.setSearch('?subscriptionCancel=true&tier=pro');
+ expect(mocks.track).toHaveBeenCalledWith('subscription_cancel', {
+ tier: 'pro',
+ });
+ mocks.setSearch('');
+ mocks.setSearch('?subscriptionCancel=true&tier=team');
+ expect(mocks.track).toHaveBeenCalledTimes(1);
+ expect(mocks.refetch).not.toHaveBeenCalled();
+ expect(pending()).toBe(false);
+ });
+
+ it('stops polling after disposal during the retry delay', async () => {
+ vi.useFakeTimers();
+ mocks.refetch.mockResolvedValue({ data: { licenseStatus: 'inactive' } });
+ mount();
+ mocks.setSearch('?subscriptionSuccess=true');
+ await Promise.resolve();
+ expect(mocks.refetch).toHaveBeenCalledTimes(1);
+ dispose?.();
+ dispose = undefined;
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(mocks.refetch).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/web/src/features/paywall/use-checkout-completion-listener.ts b/apps/web/src/features/paywall/use-checkout-completion-listener.ts
index 35ed80b6af..35edf54bea 100644
--- a/apps/web/src/features/paywall/use-checkout-completion-listener.ts
+++ b/apps/web/src/features/paywall/use-checkout-completion-listener.ts
@@ -2,7 +2,7 @@ import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { toast } from '@core/component/Toast/Toast';
import { useUserInfoQuery } from '@queries/auth/user-info';
import { useSearchParams } from '@solidjs/router';
-import { createSignal, onCleanup, onMount } from 'solid-js';
+import { createEffect, createSignal, on, onCleanup } from 'solid-js';
const CHECKOUT_REFRESH_ATTEMPTS = 10;
const CHECKOUT_REFRESH_INTERVAL_MS = 1_000;
@@ -15,56 +15,60 @@ export function useCheckoutCompletionListener() {
const analytics = useAnalytics();
const [searchParams] = useSearchParams();
const userInfoQuery = useUserInfoQuery();
- const subscriptionSuccess = searchParams.subscriptionSuccess;
- const [refreshPending, setRefreshPending] = createSignal(
- subscriptionSuccess === 'true'
- );
+ const [refreshComplete, setRefreshComplete] = createSignal(false);
+ let handledSuccess = false;
+ let handledCancel = false;
let cancelled = false;
onCleanup(() => {
cancelled = true;
});
- onMount(() => {
- if (subscriptionSuccess === 'true') {
- toast.success('Your plan has been activated!');
- analytics.track('subscription_success', { type: searchParams.type });
-
- void (async () => {
- try {
- for (
- let attempt = 0;
- attempt < CHECKOUT_REFRESH_ATTEMPTS;
- attempt++
- ) {
- const result = await userInfoQuery.refetch();
- const licenseStatus = result.data?.licenseStatus;
- if (
- cancelled ||
- licenseStatus === 'active' ||
- licenseStatus === 'trialing'
- ) {
- break;
- }
-
- if (attempt < CHECKOUT_REFRESH_ATTEMPTS - 1) {
- await new Promise((resolve) =>
- setTimeout(resolve, CHECKOUT_REFRESH_INTERVAL_MS)
- );
- }
- }
- } catch (error) {
- console.error('Failed to refresh user info after checkout', error);
- } finally {
- if (!cancelled) setRefreshPending(false);
+ async function refreshLicense() {
+ try {
+ for (let attempt = 0; attempt < CHECKOUT_REFRESH_ATTEMPTS; attempt++) {
+ if (cancelled) break;
+ const result = await userInfoQuery.refetch();
+ const licenseStatus = result.data?.licenseStatus;
+ if (
+ cancelled ||
+ licenseStatus === 'active' ||
+ licenseStatus === 'trialing'
+ )
+ break;
+ if (attempt < CHECKOUT_REFRESH_ATTEMPTS - 1) {
+ await new Promise((resolve) =>
+ setTimeout(resolve, CHECKOUT_REFRESH_INTERVAL_MS)
+ );
}
- })();
+ }
+ } catch (error) {
+ console.error('Failed to refresh user info after checkout', error);
+ } finally {
+ if (!cancelled) setRefreshComplete(true);
}
+ }
- if (searchParams.subscriptionCancel === 'true') {
- analytics.track('subscription_cancel', { tier: searchParams.tier });
- }
- });
+ createEffect(
+ on(
+ () => [searchParams.subscriptionSuccess, searchParams.subscriptionCancel],
+ ([success, cancel]) => {
+ if (success === 'true' && !handledSuccess) {
+ handledSuccess = true;
+ toast.success('Your plan has been activated!');
+ analytics.track('subscription_success', { type: searchParams.type });
+ void refreshLicense();
+ }
+ if (cancel === 'true' && !handledCancel) {
+ handledCancel = true;
+ analytics.track('subscription_cancel', { tier: searchParams.tier });
+ }
+ }
+ )
+ );
- return refreshPending;
+ // Gate navigation immediately when a late native link changes the query,
+ // before the effect starts its refresh, and release it when polling settles.
+ return () =>
+ searchParams.subscriptionSuccess === 'true' && !refreshComplete();
}
diff --git a/apps/web/src/features/settings/GitHub.tsx b/apps/web/src/features/settings/GitHub.tsx
index d8292866fd..ca7bf4ec37 100644
--- a/apps/web/src/features/settings/GitHub.tsx
+++ b/apps/web/src/features/settings/GitHub.tsx
@@ -1,3 +1,4 @@
+import { authorizeGithub } from '@core/auth/authorize-github';
import { toast } from '@core/component/Toast/Toast';
import { SERVER_HOSTS } from '@core/constant/servers';
import GithubIcon from '@icon/mcp-github.svg';
@@ -38,8 +39,9 @@ export function GitHubCard() {
const handleGithubEnable = async () => {
try {
- window.location.href = await initGithubLink.mutateAsync(
- window.location.href
+ await authorizeGithub(
+ (callbackUrl) => initGithubLink.mutateAsync(callbackUrl),
+ 'Failed to connect GitHub'
);
} catch {
toast.failure('Failed to start GitHub connect flow');
@@ -56,8 +58,9 @@ export function GitHubCard() {
const handleGithubReconnect = async () => {
try {
- window.location.href = await reauthenticateGithub.mutateAsync(
- window.location.href
+ await authorizeGithub(
+ (callbackUrl) => reauthenticateGithub.mutateAsync(callbackUrl),
+ 'Failed to reconnect GitHub'
);
} catch {
toast.failure('Failed to start GitHub reconnect flow');
diff --git a/apps/web/src/lib/core/auth/authorize-github.ts b/apps/web/src/lib/core/auth/authorize-github.ts
new file mode 100644
index 0000000000..890341c159
--- /dev/null
+++ b/apps/web/src/lib/core/auth/authorize-github.ts
@@ -0,0 +1,35 @@
+import { createNativeAuthSession } from '@core/auth/native-auth';
+import { toast } from '@core/component/Toast/Toast';
+import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
+import { invalidateGithubLinkStatus } from '@queries/auth';
+
+/**
+ * Run a GitHub OAuth grant. On the web the browser navigates to GitHub and the
+ * callback returns to this page, so nothing after the call runs. On native
+ * mobile the grant completes in the system browser and the link status query
+ * is refreshed; resolves to whether that grant succeeded. Rejects when the
+ * authorization URL cannot be obtained.
+ */
+export async function authorizeGithub(
+ getAuthorizationUrl: (callbackUrl: string) => Promise<string>,
+ failureMessage: string
+): Promise<boolean> {
+ const session = isNativeMobilePlatform()
+ ? createNativeAuthSession('github-link-callback')
+ : undefined;
+ const url = await getAuthorizationUrl(
+ session?.callbackUrl ?? window.location.href
+ );
+ if (!session) {
+ window.location.href = url;
+ return false;
+ }
+ const result = await session.authenticate(url);
+ if (result.success) {
+ await invalidateGithubLinkStatus();
+ return true;
+ }
+ // A canceled browser is a deliberate user action, not a failure.
+ if (result.error !== 'User canceled login') toast.failure(failureMessage);
+ return false;
+}
diff --git a/apps/web/src/lib/core/auth/logout.ts b/apps/web/src/lib/core/auth/logout.ts
index 49f1912002..e994cadfae 100644
--- a/apps/web/src/lib/core/auth/logout.ts
+++ b/apps/web/src/lib/core/auth/logout.ts
@@ -3,6 +3,7 @@ import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { SERVER_HOSTS } from '@core/constant/servers';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { syncLoginStorage } from '@core/util/cookies';
+import { clearPostLoginRedirect } from '@core/util/postLoginRedirect';
import { clearRegisteredCaches } from '@graphql-cache/lifecycle';
import { authKeys, type UserInfoData } from '@queries/auth/user-info';
import { queryClient } from '@queries/client';
@@ -57,6 +58,7 @@ export function useLogout() {
const navigate = useNavigate();
return createCallback(async () => {
+ clearPostLoginRedirect();
// Must run before the session is torn down — the unregister call is
// authenticated. Time-boxed so a hung request can't block logout.
await raceTimeout(unregisterPushRegistrationsForLogout(), 3000);
diff --git a/apps/web/src/lib/core/auth/native-auth.test.ts b/apps/web/src/lib/core/auth/native-auth.test.ts
new file mode 100644
index 0000000000..445ef8c669
--- /dev/null
+++ b/apps/web/src/lib/core/auth/native-auth.test.ts
@@ -0,0 +1,82 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ platform: vi.fn(),
+ invoke: vi.fn(),
+}));
+vi.mock('@core/util/platform', () => ({
+ getNativeMobilePlatform: mocks.platform,
+}));
+vi.mock('@tauri-apps/api/core', () => ({ invoke: mocks.invoke }));
+
+import { createNativeAuthSession } from './native-auth';
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.platform.mockReturnValue('android');
+});
+
+describe('native browser authentication', () => {
+ it('binds each Android attempt to a distinct callback before starting OAuth', async () => {
+ const first = createNativeAuthSession('login');
+ const second = createNativeAuthSession('login');
+ expect(first.callbackUrl).toMatch(/^macro:\/\/android-auth\/[\da-f-]{36}$/);
+ expect(second.callbackUrl).not.toBe(first.callbackUrl);
+ mocks.invoke.mockResolvedValue({ success: true, token: 'one-time-code' });
+ await expect(
+ first.authenticate('https://gateway.macro.com/auth/login/sso')
+ ).resolves.toEqual({
+ success: true,
+ token: 'one-time-code',
+ });
+ expect(mocks.invoke).toHaveBeenCalledWith(
+ 'plugin:android-auth|authenticate',
+ {
+ payload: {
+ authUrl: 'https://gateway.macro.com/auth/login/sso',
+ callbackUrl: first.callbackUrl,
+ },
+ }
+ );
+ });
+
+ it('preserves the iOS plugin contract', async () => {
+ mocks.platform.mockReturnValue('ios');
+ const session = createNativeAuthSession('inbox-link-callback');
+ expect(session.callbackUrl).toBe('macro://inbox-link-callback');
+ await session.authenticate('https://accounts.google.com/authorize');
+ expect(mocks.invoke).toHaveBeenCalledWith('plugin:auth|authenticate', {
+ payload: {
+ authUrl: 'https://accounts.google.com/authorize',
+ callbackScheme: 'macro',
+ ephemeralSession: true,
+ },
+ });
+ });
+
+ it('settles bridge errors and preserves user cancellation', async () => {
+ mocks.invoke.mockRejectedValueOnce(new Error('bridge unavailable'));
+ const session = createNativeAuthSession('login');
+ await expect(session.authenticate('https://example.com')).resolves.toEqual({
+ success: false,
+ error: 'Unable to start authentication',
+ });
+ mocks.invoke.mockResolvedValueOnce({
+ success: false,
+ error: 'User canceled login',
+ });
+ await expect(session.authenticate('https://example.com')).resolves.toEqual({
+ success: false,
+ error: 'User canceled login',
+ });
+ });
+
+ it('accepts account-link callbacks without a login session token', async () => {
+ mocks.invoke.mockResolvedValue({ success: true });
+ await expect(
+ createNativeAuthSession('github-link-callback').authenticate(
+ 'https://github.com/login/oauth/authorize'
+ )
+ ).resolves.toEqual({ success: true });
+ });
+});
diff --git a/apps/web/src/lib/core/auth/native-auth.ts b/apps/web/src/lib/core/auth/native-auth.ts
new file mode 100644
index 0000000000..73152b35f8
--- /dev/null
+++ b/apps/web/src/lib/core/auth/native-auth.ts
@@ -0,0 +1,38 @@
+import { getNativeMobilePlatform } from '@core/util/platform';
+import { invoke } from '@tauri-apps/api/core';
+
+export type NativeAuthResult = {
+ success: boolean;
+ token?: string;
+ error?: string;
+};
+
+/** Create the callback before asking the backend to construct OAuth state. */
+export function createNativeAuthSession(iosCallbackHost: string) {
+ const android = getNativeMobilePlatform() === 'android';
+ const callbackUrl = android
+ ? `macro://android-auth/${crypto.randomUUID()}`
+ : `macro://${iosCallbackHost}`;
+
+ return {
+ callbackUrl,
+ async authenticate(authUrl: string): Promise<NativeAuthResult> {
+ try {
+ return await invoke<NativeAuthResult>(
+ android
+ ? 'plugin:android-auth|authenticate'
+ : 'plugin:auth|authenticate',
+ {
+ payload: android
+ ? { authUrl, callbackUrl }
+ : { authUrl, callbackScheme: 'macro', ephemeralSession: true },
+ }
+ );
+ } catch {
+ // Bridge failures must settle the caller just like browser cancellation.
+ // Do not log callback URLs or session codes.
+ return { success: false, error: 'Unable to start authentication' };
+ }
+ },
+ };
+}
diff --git a/apps/web/src/lib/core/email-link/index.ts b/apps/web/src/lib/core/email-link/index.ts
index 0eda1c36bc..07cd0014c2 100644
--- a/apps/web/src/lib/core/email-link/index.ts
+++ b/apps/web/src/lib/core/email-link/index.ts
@@ -1,9 +1,10 @@
import { ROUTER_BASE_CONCAT, toBaseRelative } from '@app/constants/routerBase';
import { updateUserAuth } from '@core/auth';
+import { createNativeAuthSession } from '@core/auth/native-auth';
import { toast } from '@core/component/Toast/Toast';
import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';
import { currentSettingsReturnTo } from '@core/constant/SettingsState';
-import { getNativeMobilePlatform } from '@core/util/platform';
+import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { useInitGmailLink } from '@queries/auth';
import { invalidateUserInfo } from '@queries/auth/user-info';
import { invalidateEmailLinks, useEmailLinksQuery } from '@queries/email/link';
@@ -19,7 +20,6 @@ import type {
ResyncResponse,
} from '@service-email/generated/schemas';
import type { UseQueryResult } from '@tanstack/solid-query';
-import { invoke } from '@tauri-apps/api/core';
import { err, okAsync, ResultAsync } from 'neverthrow';
import { createMemo, createSignal } from 'solid-js';
import { rememberInboxLinkReturn } from './return-layout';
@@ -223,7 +223,7 @@ const TOO_MANY_PENDING_LINKS_MESSAGE =
* inbox that is already connected so the user isn't shown mailbox permissions
* they have already granted.
*
- * On native iOS the OAuth runs inline in an `ASWebAuthenticationSession` via
+ * On native mobile OAuth runs in a platform authentication browser via
* the Tauri auth plugin (the app never navigates away), and the link is
* provisioned here directly with the `link_id` from the init response. A
* shared-inbox conflict is surfaced through `requestShareInboxConfirmation`,
@@ -231,7 +231,7 @@ const TOO_MANY_PENDING_LINKS_MESSAGE =
*
* Everywhere else — web and desktop — the consent screen replaces the page, so
* the layout the user was working in is stashed against the new link id first
- * and the callback restores it. iOS needs no stash: its layout never unmounts.
+ * and the callback restores it. Native mobile needs no stash: its layout never unmounts.
*/
export function useAddInboxFlow() {
const initGmailLink = useInitGmailLink();
@@ -263,8 +263,9 @@ export function useAddInboxFlow() {
};
const startNativeFlow = async (scopes: ConsentScopes) => {
+ const session = createNativeAuthSession('inbox-link-callback');
const result = await initGmailLink.mutateAsync({
- originalUrl: 'macro://inbox-link-callback',
+ originalUrl: session.callbackUrl,
scopes,
});
if (result.isErr()) {
@@ -280,22 +281,8 @@ export function useAddInboxFlow() {
return;
}
- let auth: { success: boolean; token?: string; error?: string };
- try {
- auth = await invoke('plugin:auth|authenticate', {
- payload: {
- authUrl: result.value.authorization_url,
- callbackScheme: 'macro',
- ephemeralSession: true,
- },
- });
- } catch (error) {
- console.error('add-inbox authenticate failed', error);
- toast.failure('Failed to add inbox');
- return;
- }
-
- if (!auth.success || !auth.token) {
+ const auth = await session.authenticate(result.value.authorization_url);
+ if (!auth.success) {
if (auth.error !== 'User canceled login') {
toast.failure('Failed to add inbox');
}
@@ -307,7 +294,7 @@ export function useAddInboxFlow() {
return async (options?: { scopes?: ConsentScopes }) => {
const scopes = options?.scopes ?? 'gmail';
- if (getNativeMobilePlatform() === 'ios') {
+ if (isNativeMobilePlatform()) {
await startNativeFlow(scopes);
return;
}
diff --git a/apps/web/src/lib/core/email-link/native-link.test.ts b/apps/web/src/lib/core/email-link/native-link.test.ts
new file mode 100644
index 0000000000..091cde1ba4
--- /dev/null
+++ b/apps/web/src/lib/core/email-link/native-link.test.ts
@@ -0,0 +1,106 @@
+import { ok } from 'neverthrow';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ start: vi.fn(),
+ authenticate: vi.fn(),
+ provision: vi.fn(),
+ refetch: vi.fn(),
+ success: vi.fn(),
+ failure: vi.fn(),
+}));
+
+vi.mock('@app/constants/routerBase', () => ({
+ ROUTER_BASE_CONCAT: '/app/',
+ toBaseRelative: (value: string) => value,
+}));
+vi.mock('@core/auth', () => ({ updateUserAuth: vi.fn() }));
+vi.mock('@core/auth/native-auth', () => ({
+ createNativeAuthSession: () => ({
+ callbackUrl: 'macro://android-auth/test-attempt',
+ authenticate: mocks.authenticate,
+ }),
+}));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { success: mocks.success, failure: mocks.failure },
+}));
+vi.mock('@core/constant/PaywallState', () => ({
+ PaywallKey: { MULTI_INBOX: 'multi-inbox' },
+ usePaywallState: () => ({ showPaywall: vi.fn() }),
+}));
+vi.mock('@core/constant/SettingsState', () => ({
+ currentSettingsReturnTo: () => undefined,
+}));
+vi.mock('@core/mobile/isNativeMobilePlatform', () => ({
+ isNativeMobilePlatform: () => true,
+}));
+vi.mock('@queries/auth', () => ({
+ useInitGmailLink: () => ({ mutateAsync: mocks.start }),
+}));
+vi.mock('@queries/auth/user-info', () => ({ invalidateUserInfo: vi.fn() }));
+vi.mock('@queries/email/link', () => ({
+ invalidateEmailLinks: vi.fn(),
+ useEmailLinksQuery: () => ({ refetch: mocks.refetch }),
+}));
+vi.mock('@service-email/client', () => ({
+ emailClient: { init: mocks.provision },
+ ALREADY_INITIALIZED_CODE: 'ALREADY_INITIALIZED',
+ NO_GMAIL_GRANT_CODE: 'NO_GMAIL_GRANT',
+ SHARED_INBOX_CONFLICT_CODE: 'SHARED_INBOX_CONFLICT',
+}));
+vi.mock('./share-conflict', () => ({ requestShareInboxConfirmation: vi.fn() }));
+
+import { useAddInboxFlow } from './index';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.useFakeTimers();
+ mocks.start.mockResolvedValue(
+ ok({
+ link_id: 'pending-link',
+ authorization_url: 'https://accounts.google.com/authorize',
+ })
+ );
+ mocks.authenticate.mockResolvedValue({ success: true });
+ mocks.provision.mockResolvedValue(ok(undefined));
+ mocks.refetch.mockResolvedValue(undefined);
+});
+
+afterEach(() => {
+ vi.runOnlyPendingTimers();
+ vi.useRealTimers();
+});
+
+describe('native account linking', () => {
+ it.each(['gmail', 'calendar'] as const)(
+ 'completes %s consent without requiring a login session token',
+ async (scopes) => {
+ await useAddInboxFlow()({ scopes });
+ expect(mocks.start).toHaveBeenCalledWith({
+ originalUrl: 'macro://android-auth/test-attempt',
+ scopes,
+ });
+ expect(mocks.authenticate).toHaveBeenCalledWith(
+ 'https://accounts.google.com/authorize'
+ );
+ expect(mocks.provision).toHaveBeenCalledWith({
+ linkId: 'pending-link',
+ forceShare: false,
+ });
+ expect(mocks.refetch).toHaveBeenCalledOnce();
+ expect(mocks.success).toHaveBeenCalledWith('Account connected');
+ expect(mocks.failure).not.toHaveBeenCalled();
+ }
+ );
+
+ it('does not provision an inbox after consent is canceled', async () => {
+ mocks.authenticate.mockResolvedValue({
+ success: false,
+ error: 'User canceled login',
+ });
+ await useAddInboxFlow()();
+ expect(mocks.provision).not.toHaveBeenCalled();
+ expect(mocks.refetch).not.toHaveBeenCalled();
+ expect(mocks.failure).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/lib/core/util/postLoginRedirect.test.ts b/apps/web/src/lib/core/util/postLoginRedirect.test.ts
new file mode 100644
index 0000000000..ef614a88e5
--- /dev/null
+++ b/apps/web/src/lib/core/util/postLoginRedirect.test.ts
@@ -0,0 +1,61 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const native = vi.hoisted(() => vi.fn());
+vi.mock('@core/mobile/isNativeMobilePlatform', () => ({
+ isNativeMobilePlatform: native,
+}));
+
+import {
+ clearPostLoginRedirect,
+ consumePostLoginRedirect,
+ setPostLoginRedirect,
+} from './postLoginRedirect';
+
+beforeEach(() => {
+ localStorage.clear();
+ sessionStorage.clear();
+ native.mockReturnValue(true);
+});
+
+describe('native post-login destinations', () => {
+ it('restores hash-router locations without nesting the router root', () => {
+ setPostLoginRedirect(`${window.location.origin}/#/task/123?view=comments`);
+ expect(consumePostLoginRedirect()).toBe('/task/123?view=comments');
+ setPostLoginRedirect(`${window.location.origin}/#//evil.example/task/123`);
+ expect(consumePostLoginRedirect()).toBeNull();
+ });
+
+ it('survives session storage loss and consumes the destination once', () => {
+ setPostLoginRedirect('/task/123?view=comments#reply');
+ sessionStorage.clear();
+ expect(consumePostLoginRedirect()).toBe('/task/123?view=comments#reply');
+ expect(consumePostLoginRedirect()).toBeNull();
+ });
+
+ it('rejects external URLs and clears destinations on explicit logout', () => {
+ setPostLoginRedirect('https://evil.example/task/123');
+ expect(consumePostLoginRedirect()).toBeNull();
+ setPostLoginRedirect('/task/123');
+ clearPostLoginRedirect();
+ expect(consumePostLoginRedirect()).toBeNull();
+ });
+
+ it('expires abandoned destinations and ignores malformed storage', () => {
+ const clock = vi.spyOn(Date, 'now');
+ clock.mockReturnValue(0);
+ setPostLoginRedirect('/task/123');
+ clock.mockReturnValue(31 * 60 * 1000);
+ expect(consumePostLoginRedirect()).toBeNull();
+ clock.mockRestore();
+ localStorage.setItem('nativePostLoginRedirect', 'broken');
+ expect(consumePostLoginRedirect()).toBeNull();
+ });
+
+ it('preserves the browser session-storage behavior', () => {
+ native.mockReturnValue(false);
+ setPostLoginRedirect('/app/task/123');
+ expect(sessionStorage.getItem('redirectUrl')).toBe('/app/task/123');
+ expect(consumePostLoginRedirect()).toBe('/app/task/123');
+ expect(consumePostLoginRedirect()).toBeNull();
+ });
+});
diff --git a/apps/web/src/lib/core/util/postLoginRedirect.ts b/apps/web/src/lib/core/util/postLoginRedirect.ts
index 7c1a5ddc55..81ea21db0a 100644
--- a/apps/web/src/lib/core/util/postLoginRedirect.ts
+++ b/apps/web/src/lib/core/util/postLoginRedirect.ts
@@ -1,12 +1,71 @@
+import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
+
const POST_LOGIN_REDIRECT_KEY = 'redirectUrl';
+const NATIVE_REDIRECT_KEY = 'nativePostLoginRedirect';
+const NATIVE_REDIRECT_TTL = 30 * 60 * 1000;
+
+function nativeRelativePath(value: string): string | null {
+ const current = new URL(window.location.href);
+ const parsed = new URL(value, current);
+ if (parsed.protocol !== current.protocol || parsed.host !== current.host)
+ return null;
+ // Native uses a hash router; full location URLs must restore the route inside
+ // the hash, not navigate to a second nested hash-router root.
+ if (parsed.hash.startsWith('#/')) {
+ const route = parsed.hash.slice(1);
+ const destination = new URL(route, current);
+ if (
+ destination.protocol !== current.protocol ||
+ destination.host !== current.host
+ )
+ return null;
+ return route;
+ }
+ return `${parsed.pathname}${parsed.search}${parsed.hash}`;
+}
/** Preserves a URL for BasePathComponent to restore after authentication. */
export function setPostLoginRedirect(url: string): void {
+ if (isNativeMobilePlatform()) {
+ const path = nativeRelativePath(url);
+ if (!path) return;
+ localStorage.setItem(
+ NATIVE_REDIRECT_KEY,
+ JSON.stringify({
+ path,
+ expiresAt: Date.now() + NATIVE_REDIRECT_TTL,
+ })
+ );
+ return;
+ }
sessionStorage.setItem(POST_LOGIN_REDIRECT_KEY, url);
}
+/** Explicit logout must not carry a previous account's pending destination. */
+export function clearPostLoginRedirect(): void {
+ localStorage.removeItem(NATIVE_REDIRECT_KEY);
+ sessionStorage.removeItem(POST_LOGIN_REDIRECT_KEY);
+}
+
/** Reads and clears the URL preserved by {@link setPostLoginRedirect}. */
export function consumePostLoginRedirect(): string | null {
+ if (isNativeMobilePlatform()) {
+ const stored = localStorage.getItem(NATIVE_REDIRECT_KEY);
+ localStorage.removeItem(NATIVE_REDIRECT_KEY);
+ if (!stored) return null;
+ try {
+ const value = JSON.parse(stored);
+ if (
+ typeof value.path !== 'string' ||
+ typeof value.expiresAt !== 'number' ||
+ value.expiresAt <= Date.now()
+ )
+ return null;
+ return nativeRelativePath(value.path);
+ } catch {
+ return null;
+ }
+ }
const url = sessionStorage.getItem(POST_LOGIN_REDIRECT_KEY);
if (url !== null) {
sessionStorage.removeItem(POST_LOGIN_REDIRECT_KEY);
diff --git a/apps/web/src/lib/tauri/PushNotification.tsx b/apps/web/src/lib/tauri/PushNotification.tsx
index e029bb950c..9fa297b1db 100644
--- a/apps/web/src/lib/tauri/PushNotification.tsx
+++ b/apps/web/src/lib/tauri/PushNotification.tsx
@@ -217,7 +217,11 @@ export function MaybePushNotificationRegistration(props: {
}) {
const { os } = useExpectTauri();
- if (os !== 'android' && os !== 'ios') {
+ // Android remote push requires the token/permission/watcher implementation
+ // tracked by Android task 02. Its current scaffold throws without Firebase
+ // configuration and does not implement watchNotifications. Keep local
+ // notifications usable while the Android app shell is brought up.
+ if (os !== 'ios') {
return (
<PushNotificationContext.Provider value={'not-supported'}>
<PlatformNotificationProvider
diff --git a/apps/web/src/lib/tauri/navigation.test.ts b/apps/web/src/lib/tauri/navigation.test.ts
new file mode 100644
index 0000000000..d40f502aea
--- /dev/null
+++ b/apps/web/src/lib/tauri/navigation.test.ts
@@ -0,0 +1,83 @@
+// @vitest-environment jsdom
+
+import { createRoot } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ platform: 'android',
+ navigate: vi.fn(),
+ setPostLoginRedirect: vi.fn(),
+ listen: vi.fn(),
+ invoke: vi.fn(),
+}));
+
+vi.mock('@core/util/platform', () => ({
+ getNativeMobilePlatform: () => mocks.platform,
+}));
+vi.mock('@core/util/postLoginRedirect', () => ({
+ setPostLoginRedirect: mocks.setPostLoginRedirect,
+}));
+vi.mock('@solidjs/router', () => ({ useNavigate: () => mocks.navigate }));
+vi.mock('@tauri-apps/api/core', () => ({ invoke: mocks.invoke }));
+vi.mock('@tauri-apps/api/event', () => ({ listen: mocks.listen }));
+vi.mock('./macroLinkInterceptor', () => ({
+ registerMacroLinkInterceptor: () => () => {},
+}));
+
+import { useTauriNavigationEffect } from './navigation';
+
+let dispose: (() => void) | undefined;
+let receive: (event: { payload: { path: string; query: string } }) => void;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.platform = 'android';
+ mocks.invoke.mockResolvedValue(undefined);
+ mocks.listen.mockImplementation(async (_name, handler) => {
+ receive = handler;
+ return () => {};
+ });
+ createRoot((cleanup) => {
+ dispose = cleanup;
+ useTauriNavigationEffect();
+ });
+});
+
+afterEach(() => dispose?.());
+
+describe('native link session routing', () => {
+ it('preserves query parameters on Android root links', () => {
+ receive({
+ payload: { path: '/', query: 'subscriptionSuccess=true&type=pro' },
+ });
+
+ expect(mocks.navigate).toHaveBeenCalledWith(
+ '/?subscriptionSuccess=true&type=pro'
+ );
+ expect(mocks.setPostLoginRedirect).not.toHaveBeenCalled();
+ });
+
+ it('retains an Android destination and its query while checking the session', () => {
+ receive({ payload: { path: '/task/123', query: 'view=comments' } });
+
+ expect(mocks.setPostLoginRedirect).toHaveBeenCalledWith(
+ '/task/123?view=comments'
+ );
+ expect(mocks.navigate).toHaveBeenCalledWith('/');
+ });
+
+ it('leaves direct login links and their queries intact', () => {
+ receive({ payload: { path: '/login', query: 'referral_code=invite' } });
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/login?referral_code=invite');
+ expect(mocks.setPostLoginRedirect).not.toHaveBeenCalled();
+ });
+
+ it('preserves direct routing on other native platforms', () => {
+ mocks.platform = 'ios';
+ receive({ payload: { path: '/task/123', query: 'view=comments' } });
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/task/123?view=comments');
+ expect(mocks.setPostLoginRedirect).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/lib/tauri/navigation.ts b/apps/web/src/lib/tauri/navigation.ts
index 9e1d7721d9..3aef0b4518 100644
--- a/apps/web/src/lib/tauri/navigation.ts
+++ b/apps/web/src/lib/tauri/navigation.ts
@@ -1,3 +1,5 @@
+import { getNativeMobilePlatform } from '@core/util/platform';
+import { setPostLoginRedirect } from '@core/util/postLoginRedirect';
import { useNavigate } from '@solidjs/router';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
@@ -22,11 +24,24 @@ export function useTauriNavigationEffect() {
async function inner() {
unsubscribe = await listen<NavigateEvent>('navigate', (ev) => {
- console.info({ ev });
const path = ev.payload.query
? `${ev.payload.path}?${ev.payload.query}`
: ev.payload.path;
- navigate(path);
+ if (
+ getNativeMobilePlatform() === 'android' &&
+ ev.payload.path !== '/login'
+ ) {
+ // Route through the session gate. During cold start the login marker
+ // can precede the user-info query and is not proof of authentication.
+ if (ev.payload.path === '/') {
+ navigate(path);
+ } else {
+ setPostLoginRedirect(path);
+ navigate('/');
+ }
+ } else {
+ navigate(path);
+ }
});
// On a cold open, the deep-link handler emits `navigate` during
// startup, before this listener exists, and the event is lost — pull
diff --git a/apps/web/src/routes/BasePath.test.tsx b/apps/web/src/routes/BasePath.test.tsx
index d8bee069e8..0d0dbb9058 100644
--- a/apps/web/src/routes/BasePath.test.tsx
+++ b/apps/web/src/routes/BasePath.test.tsx
@@ -3,6 +3,7 @@
*/
import { DEFAULT_ROUTE } from '@app/constants/defaultRoute';
+import { setPostLoginRedirect } from '@core/util/postLoginRedirect';
import { ThrownResultError } from '@core/util/result';
import { QueryClientProvider } from '@tanstack/solid-query';
import type { JSX } from 'solid-js';
@@ -16,6 +17,8 @@ const mocks = vi.hoisted(() => ({
hasLoginCookie: true,
nativeMobile: false,
navigate: vi.fn(),
+ routerSearch: (): string => '',
+ setRouterSearch: (_value: string) => {},
}));
vi.mock('@app/features/paywall/use-checkout-completion-listener', () => ({
@@ -70,14 +73,31 @@ vi.mock('@queries/auth/user-info', async () => {
};
});
-vi.mock('@solidjs/router', () => ({
- // Mirrors the real Navigate component: a replace navigation on render.
- Navigate: (props: { href: string }) => {
- mocks.navigate(props.href, { replace: true });
- return null;
- },
- useSearchParams: () => [{}, () => {}],
-}));
+vi.mock('@solidjs/router', async () => {
+ const { createSignal } = await import('solid-js');
+ const [search, setSearch] = createSignal('');
+ mocks.routerSearch = search;
+ mocks.setRouterSearch = setSearch;
+ return {
+ Navigate: (props: { href: string }) => {
+ mocks.navigate(props.href, { replace: true });
+ return null;
+ },
+ useLocation: () => ({
+ get search() {
+ return search();
+ },
+ }),
+ useSearchParams: () => [
+ {
+ get upgrade() {
+ return new URLSearchParams(search()).get('upgrade');
+ },
+ },
+ () => {},
+ ],
+ };
+});
vi.mock('@ui', () => ({
Button: (props: { children: JSX.Element; onClick?: () => void }) => (
@@ -126,12 +146,14 @@ function flush() {
beforeEach(() => {
mocks.hasLoginCookie = true;
mocks.nativeMobile = false;
+ mocks.setRouterSearch('');
mocks.navigate.mockReset();
mocks.fetchUserInfo.mockReset();
mocks.confirmSessionExpired.mockReset();
mocks.clearLocalAuthSession.mockReset();
mocks.clearLocalAuthSession.mockResolvedValue(undefined);
sessionStorage.clear();
+ localStorage.clear();
queryClient.clear();
window.history.replaceState({}, '', '/app/');
});
@@ -142,6 +164,128 @@ afterEach(() => {
});
describe('BasePathComponent', () => {
+ it.each([true, false])(
+ 'preserves a late native root query while authentication resolves (%s)',
+ async (authenticated) => {
+ mocks.nativeMobile = true;
+ mocks.hasLoginCookie = authenticated;
+ let resolveUserInfo!: (value: { authenticated: boolean }) => void;
+ mocks.fetchUserInfo.mockReturnValue(
+ new Promise<{ authenticated: boolean }>((resolve) => {
+ resolveUserInfo = resolve;
+ })
+ );
+ renderRoute();
+ await vi.waitFor(() => expect(mocks.fetchUserInfo).toHaveBeenCalled());
+ expect(mocks.navigate).not.toHaveBeenCalled();
+
+ mocks.setRouterSearch('?upgrade=true&referral_code=late');
+ await vi.waitFor(() =>
+ expect(sessionStorage.getItem('showUpgradeModal')).toBe('true')
+ );
+ resolveUserInfo({ authenticated });
+
+ await vi.waitFor(() =>
+ expect(mocks.navigate).toHaveBeenCalledWith(
+ `${authenticated ? DEFAULT_ROUTE : '/welcome'}?upgrade=true&referral_code=late`,
+ { replace: true }
+ )
+ );
+ }
+ );
+
+ it('preserves native hash-router queries when entering the app', async () => {
+ mocks.nativeMobile = true;
+ mocks.setRouterSearch('?upgrade=true&referral_code=invite');
+ window.history.replaceState({}, '', `/#/${mocks.routerSearch()}`);
+ mocks.fetchUserInfo.mockResolvedValue({ authenticated: true });
+
+ renderRoute();
+
+ await vi.waitFor(() => {
+ expect(mocks.navigate).toHaveBeenCalledWith(
+ `${DEFAULT_ROUTE}${mocks.routerSearch()}`,
+ { replace: true }
+ );
+ });
+ expect(sessionStorage.getItem('showUpgradeModal')).toBe('true');
+ });
+
+ it('preserves native hash-router queries when sending a new user to welcome', async () => {
+ mocks.nativeMobile = true;
+ mocks.hasLoginCookie = false;
+ mocks.setRouterSearch('?referral_code=invite');
+ window.history.replaceState({}, '', `/#/${mocks.routerSearch()}`);
+ mocks.fetchUserInfo.mockResolvedValue({ authenticated: false });
+
+ renderRoute();
+
+ await vi.waitFor(() => {
+ expect(mocks.navigate).toHaveBeenCalledWith(
+ '/welcome?referral_code=invite',
+ {
+ replace: true,
+ }
+ );
+ });
+ });
+
+ it('preserves native hash-router queries after confirmed session expiry', async () => {
+ mocks.nativeMobile = true;
+ mocks.setRouterSearch('?referral_code=invite');
+ window.history.replaceState({}, '', `/#/${mocks.routerSearch()}`);
+ mocks.fetchUserInfo.mockRejectedValue(UNAUTHORIZED_ERROR());
+ mocks.confirmSessionExpired.mockResolvedValue(true);
+
+ renderRoute();
+
+ await vi.waitFor(() => {
+ expect(mocks.navigate).toHaveBeenCalledWith(
+ '/welcome?referral_code=invite',
+ {
+ replace: true,
+ }
+ );
+ });
+ });
+
+ it('keeps browser query forwarding unchanged', async () => {
+ window.history.replaceState({}, '', '/app/?subscriptionSuccess=true');
+ mocks.fetchUserInfo.mockResolvedValue({ authenticated: true });
+
+ renderRoute();
+
+ await vi.waitFor(() => {
+ expect(mocks.navigate).toHaveBeenCalledWith(
+ `${DEFAULT_ROUTE}?subscriptionSuccess=true`,
+ { replace: true }
+ );
+ });
+ });
+
+ it('retains a native destination until authentication succeeds', async () => {
+ mocks.nativeMobile = true;
+ mocks.hasLoginCookie = false;
+ mocks.fetchUserInfo.mockResolvedValue({ authenticated: false });
+ setPostLoginRedirect('/task/pending');
+
+ renderRoute();
+ await vi.waitFor(() => {
+ expect(mocks.navigate).toHaveBeenCalledWith('/welcome', {
+ replace: true,
+ });
+ });
+ expect(localStorage.getItem('nativePostLoginRedirect')).not.toBeNull();
+
+ queryClient.setQueryData(['auth', 'userInfo'], { authenticated: true });
+ await vi.waitFor(() => {
+ expect(mocks.navigate).toHaveBeenCalledWith('/task/pending', {
+ replace: true,
+ });
+ });
+ expect(localStorage.getItem('nativePostLoginRedirect')).toBeNull();
+ });
+
it('redirects an authenticated session to the default route', async () => {
mocks.fetchUserInfo.mockResolvedValue({ authenticated: true });
diff --git a/apps/web/src/routes/BasePath.tsx b/apps/web/src/routes/BasePath.tsx
index d430558084..0dd9ccdb5c 100644
--- a/apps/web/src/routes/BasePath.tsx
+++ b/apps/web/src/routes/BasePath.tsx
@@ -12,19 +12,22 @@ import {
useUserInfoQuery,
} from '@queries/auth/user-info';
import { queryClient } from '@queries/client';
-import { Navigate, useSearchParams } from '@solidjs/router';
+import { Navigate, useLocation, useSearchParams } from '@solidjs/router';
import { Button } from '@ui';
import {
+ createEffect,
createResource,
createSignal,
Match,
- onMount,
+ on,
Show,
Switch,
} from 'solid-js';
-function getCurrentQueryString() {
- const params = new URLSearchParams(window.location.search);
+function getCurrentQueryString(routerSearch: string) {
+ const params = new URLSearchParams(
+ isNativeMobilePlatform() ? routerSearch : window.location.search
+ );
return params.toString().length > 0 ? `?${params.toString()}` : '';
}
@@ -70,6 +73,7 @@ function SessionVerificationFallback(props: {
}
function SessionExpiredRedirect() {
+ const location = useLocation();
// The UNAUTHORIZED that got us here can come from a latched refresh failure
// without the server ever being consulted, so confirm with a fresh refresh
// before destroying local session state. If the session turns out to be
@@ -91,24 +95,38 @@ function SessionExpiredRedirect() {
return (
<Show when={expired()}>
- <Navigate href={`/welcome${getCurrentQueryString()}`} />
+ <Navigate href={`/welcome${getCurrentQueryString(location.search)}`} />
</Show>
);
}
+function AuthenticatedDestination(props: { fallback: string }) {
+ const pending = isNativeMobilePlatform() ? consumePostLoginRedirect() : null;
+ return <Navigate href={pending ?? props.fallback} />;
+}
+
export function BasePathComponent() {
+ const location = useLocation();
const [searchParams] = useSearchParams();
const userInfoQuery = useUserInfoQuery();
const checkoutRefreshPending = useCheckoutCompletionListener();
- onMount(() => {
- if (searchParams.upgrade === 'true') {
- sessionStorage.setItem('showUpgradeModal', 'true');
- }
- });
+ createEffect(
+ on(
+ () => searchParams.upgrade,
+ (upgrade) => {
+ if (upgrade === 'true')
+ sessionStorage.setItem('showUpgradeModal', 'true');
+ }
+ )
+ );
// check session storage for redirect url
- const redirectUrl = consumePostLoginRedirect();
+ // Native destinations survive process death and must remain pending until
+ // identity is known; consuming during the unauthenticated launch loses them.
+ const redirectUrl = isNativeMobilePlatform()
+ ? null
+ : consumePostLoginRedirect();
if (redirectUrl) {
const relativeUrl = redirectUrl.replace(window.location.origin, '');
window.location.href = relativeUrl;
@@ -116,8 +134,8 @@ export function BasePathComponent() {
}
// Preserve existing query parameters when redirecting
- const queryString = getCurrentQueryString();
- const redirectPath = `${DEFAULT_ROUTE}${queryString}`;
+ const queryString = () => getCurrentQueryString(location.search);
+ const redirectPath = () => `${DEFAULT_ROUTE}${queryString()}`;
return (
<Switch>
@@ -133,7 +151,7 @@ export function BasePathComponent() {
<SessionExpiredRedirect />
</Match>
<Match when={userInfoQuery.data?.authenticated}>
- <Navigate href={redirectPath} />
+ <AuthenticatedDestination fallback={redirectPath()} />
</Match>
{/* A failed remote check does not make an authenticated cached session
unusable: the data branch above enters the local app first. Block only
@@ -156,7 +174,7 @@ export function BasePathComponent() {
<Match
when={!userInfoQuery.isLoading && !userInfoQuery.data?.authenticated}
>
- <Navigate href={`/welcome${queryString}`} />
+ <Navigate href={`/welcome${queryString()}`} />
</Match>
</Switch>
);
diff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lock
index 5368165a36..6296902db8 100644
--- a/apps/web/tauri/Cargo.lock
+++ b/apps/web/tauri/Cargo.lock
@@ -197,6 +197,7 @@ version = "0.1.0"
dependencies = [
"graphql_cache_plugin",
"http",
+ "jni",
"log",
"logger",
"macro_bundle_updater_plugin",
@@ -206,12 +207,14 @@ dependencies = [
"objc2 0.5.2",
"reqwest",
"rootcause",
+ "rustls-platform-verifier",
"serde",
"serde_json",
"serde_qs",
"staged_upload_constants",
"tauri",
"tauri-build",
+ "tauri-plugin-android-auth",
"tauri-plugin-auth",
"tauri-plugin-call-kit",
"tauri-plugin-deep-link",
@@ -6562,6 +6565,15 @@ dependencies = [
"walkdir",
]
+[[package]]
+name = "tauri-plugin-android-auth"
+version = "0.1.0"
+dependencies = [
+ "serde",
+ "tauri",
+ "tauri-plugin",
+]
+
[[package]]
name = "tauri-plugin-auth"
version = "0.1.0"
diff --git a/apps/web/tauri/Cargo.toml b/apps/web/tauri/Cargo.toml
index 60e5cb6867..8b3712046e 100644
--- a/apps/web/tauri/Cargo.toml
+++ b/apps/web/tauri/Cargo.toml
@@ -1,5 +1,6 @@
[workspace]
members = [
+ "android_auth_plugin",
"callkit_plugin",
"edit_menu_plugin",
"graphql_cache_plugin",
diff --git a/apps/web/tauri/android_auth_plugin/.gitignore b/apps/web/tauri/android_auth_plugin/.gitignore
new file mode 100644
index 0000000000..0614a2a0e9
--- /dev/null
+++ b/apps/web/tauri/android_auth_plugin/.gitignore
@@ -0,0 +1,4 @@
+# Tauri-generated Android API sources and local build artifacts.
+.tauri/
+build/
+.gradle/
diff --git a/apps/web/tauri/android_auth_plugin/Cargo.toml b/apps/web/tauri/android_auth_plugin/Cargo.toml
new file mode 100644
index 0000000000..c4b9c3b7cd
--- /dev/null
+++ b/apps/web/tauri/android_auth_plugin/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "tauri-plugin-android-auth"
+version = "0.1.0"
+edition.workspace = true
+links = "tauri-plugin-android-auth"
+
+[build-dependencies]
+tauri-plugin = { version = "2.4", features = ["build"] }
+
+[dependencies]
+serde = { workspace = true, features = ["derive"] }
+tauri = { workspace = true }
diff --git a/apps/web/tauri/android_auth_plugin/android/build.gradle.kts b/apps/web/tauri/android_auth_plugin/android/build.gradle.kts
new file mode 100644
index 0000000000..83223ca335
--- /dev/null
+++ b/apps/web/tauri/android_auth_plugin/android/build.gradle.kts
@@ -0,0 +1,22 @@
+plugins {
+ id("com.android.library")
+ id("org.jetbrains.kotlin.android")
+}
+
+android {
+ namespace = "com.macro.auth"
+ compileSdk = 36
+ defaultConfig { minSdk = 24 }
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_1_8
+ targetCompatibility = JavaVersion.VERSION_1_8
+ }
+ kotlinOptions { jvmTarget = "1.8" }
+}
+
+dependencies {
+ implementation(project(":tauri-android"))
+ implementation("androidx.browser:browser:1.9.0")
+ implementation("androidx.activity:activity-ktx:1.10.1")
+ testImplementation("junit:junit:4.13.2")
+}
diff --git a/apps/web/tauri/android_auth_plugin/android/src/main/AndroidManifest.xml b/apps/web/tauri/android_auth_plugin/android/src/main/AndroidManifest.xml
new file mode 100644
index 0000000000..c1eb92b815
--- /dev/null
+++ b/apps/web/tauri/android_auth_plugin/android/src/main/AndroidManifest.xml
@@ -0,0 +1,20 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <application>
+ <activity
+ android:name="com.macro.auth.AuthActivity"
+ android:exported="false"
+ android:launchMode="singleTop" />
+ <!-- Only the fallback browser path uses this receiver. Auth Tab returns directly. -->
+ <activity
+ android:name="com.macro.auth.AuthRedirectActivity"
+ android:exported="true"
+ android:theme="@android:style/Theme.Translucent.NoTitleBar">
+ <intent-filter>
+ <action android:name="android.intent.action.VIEW" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.BROWSABLE" />
+ <data android:scheme="macro" android:host="android-auth" />
+ </intent-filter>
+ </activity>
+ </application>
+</manifest>
diff --git a/apps/web/tauri/android_auth_plugin/android/src/main/java/com/macro/auth/AuthActivity.kt b/apps/web/tauri/android_auth_plugin/android/src/main/java/com/macro/auth/AuthActivity.kt
new file mode 100644
index 0000000000..06ac68b38a
--- /dev/null
+++ b/apps/web/tauri/android_auth_plugin/android/src/main/java/com/macro/auth/AuthActivity.kt
@@ -0,0 +1,99 @@
+package com.macro.auth
+
+import android.app.Activity
+import android.content.Intent
+import android.net.Uri
+import android.os.Bundle
+import androidx.activity.ComponentActivity
+import androidx.browser.auth.AuthTabIntent
+
+/** Owns the browser result across rotation, without persisting credentials. */
+class AuthActivity : ComponentActivity() {
+ private val launcher = AuthTabIntent.registerActivityResultLauncher(this) { result ->
+ if (!isFinishing) {
+ // Returning to our task can dismiss the fallback browser first.
+ // Its cancellation must not win over an already validated redirect.
+ val received = AuthSession.pending
+ ?.takeIf { it.callbackUrl == intent.getStringExtra("callbackUrl") }
+ ?.receivedCallback
+ val callback = result.resultUri
+ if (received != null) {
+ complete(received)
+ } else if (result.resultCode == AuthTabIntent.RESULT_OK && callback != null) {
+ // The browser has closed, so a mismatch is final rather than a stray intent.
+ if (!complete(callback.toString())) {
+ fail("Authentication callback did not match this session")
+ }
+ } else {
+ fail(if (result.resultCode == AuthTabIntent.RESULT_CANCELED) {
+ "User canceled login"
+ } else {
+ "Authentication browser failed"
+ })
+ }
+ }
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ // A stale browser callback can recreate this activity after process death.
+ // Never redeem it without the original in-memory invocation.
+ val expected = intent.getStringExtra("callbackUrl")
+ val session = AuthSession.pending?.takeIf { it.callbackUrl == expected }
+ if (session == null) {
+ fail("Authentication session expired. Please try again.")
+ return
+ }
+ session.receivedCallback?.let {
+ complete(it)
+ return
+ }
+ if (savedInstanceState == null) {
+ try {
+ AuthTabIntent.Builder().build().launch(launcher, Uri.parse(session.authUrl), "macro")
+ } catch (_: Exception) {
+ fail("No authentication browser available")
+ }
+ }
+ }
+
+ override fun onNewIntent(intent: Intent) {
+ super.onNewIntent(intent)
+ // Retain the original intent, which carries the expected nonce. A stray
+ // redirect that does not match is ignored while the browser stays open.
+ intent.data?.let { complete(it.toString()) }
+ }
+
+ /** Settles this activity for a callback that belongs to its session; false otherwise. */
+ private fun complete(callback: String): Boolean {
+ if (isFinishing) return true
+ val expected = intent.getStringExtra("callbackUrl") ?: return false
+ if (!AuthCallback.matches(expected, callback)) return false
+ try {
+ val params = AuthCallback.parameters(callback)
+ if (params.containsKey("error")) {
+ fail("Authentication was not completed")
+ return true
+ }
+ val result = Intent()
+ params["token"]?.let { result.putExtra("token", it) }
+ setResult(Activity.RESULT_OK, result)
+ finish()
+ } catch (_: Exception) {
+ fail("Invalid authentication callback")
+ }
+ return true
+ }
+
+ override fun onDestroy() {
+ if (isFinishing) {
+ intent.getStringExtra("callbackUrl")?.let { AuthSession.clear(it) }
+ }
+ super.onDestroy()
+ }
+
+ private fun fail(message: String) {
+ setResult(Activity.RESULT_CANCELED, Intent().putExtra("error", message))
+ finish()
+ }
+}
diff --git a/apps/web/tauri/android_auth_plugin/android/src/main/java/com/macro/auth/AuthCallback.kt b/apps/web/tauri/android_auth_plugin/android/src/main/java/com/macro/auth/AuthCallback.kt
new file mode 100644
index 0000000000..31c57e3f33
--- /dev/null
+++ b/apps/web/tauri/android_auth_plugin/android/src/main/java/com/macro/auth/AuthCallback.kt
@@ -0,0 +1,40 @@
+package com.macro.auth
+
+import java.net.URI
+import java.net.URLDecoder
+import java.util.UUID
+
+/** Validate the per-attempt callback before accepting any session code. */
+internal object AuthCallback {
+ fun isExpectedUrl(value: String): Boolean = try {
+ val uri = URI(value)
+ val nonce = uri.path.removePrefix("/")
+ uri.scheme == "macro" && uri.rawAuthority == "android-auth" &&
+ uri.rawQuery == null && uri.rawFragment == null &&
+ UUID.fromString(nonce).toString() == nonce
+ } catch (_: Exception) {
+ false
+ }
+
+ fun matches(expected: String, received: String): Boolean = try {
+ val target = URI(expected)
+ val callback = URI(received)
+ isExpectedUrl(expected) && callback.scheme == target.scheme &&
+ callback.rawAuthority == target.rawAuthority && callback.rawPath == target.rawPath &&
+ callback.rawFragment == null
+ } catch (_: Exception) {
+ false
+ }
+
+ fun parameters(received: String): Map<String, String> {
+ val pairs = URI(received).rawQuery?.split("&") ?: return emptyMap()
+ val result = mutableMapOf<String, String>()
+ for (pair in pairs) {
+ val parts = pair.split("=", limit = 2)
+ val key = URLDecoder.decode(parts[0], "UTF-8")
+ require(!result.containsKey(key)) { "Duplicate callback parameter" }
+ result[key] = URLDecoder.decode(parts.getOrElse(1) { "" }, "UTF-8")
+ }
+ return result
+ }
+}
diff --git a/apps/web/tauri/android_auth_plugin/android/src/main/java/com/macro/auth/AuthPlugin.kt b/apps/web/tauri/android_auth_plugin/android/src/main/java/com/macro/auth/AuthPlugin.kt
new file mode 100644
index 0000000000..df32fe1789
--- /dev/null
+++ b/apps/web/tauri/android_auth_plugin/android/src/main/java/com/macro/auth/AuthPlugin.kt
@@ -0,0 +1,59 @@
+package com.macro.auth
+
+import android.app.Activity
+import android.content.Intent
+import androidx.activity.result.ActivityResult
+import app.tauri.annotation.ActivityCallback
+import app.tauri.annotation.Command
+import app.tauri.annotation.InvokeArg
+import app.tauri.annotation.TauriPlugin
+import app.tauri.plugin.Invoke
+import app.tauri.plugin.JSObject
+import app.tauri.plugin.Plugin
+import java.net.URI
+
+@InvokeArg
+class AuthenticateArgs {
+ lateinit var authUrl: String
+ lateinit var callbackUrl: String
+}
+
+@TauriPlugin
+class AuthPlugin(private val activity: Activity) : Plugin(activity) {
+ @Command
+ fun authenticate(invoke: Invoke) {
+ var started: AuthSession.Pending? = null
+ try {
+ val args = invoke.parseArgs(AuthenticateArgs::class.java)
+ val authUrl = URI(args.authUrl)
+ require(authUrl.scheme == "https" && authUrl.host != null && authUrl.userInfo == null)
+ require(AuthCallback.isExpectedUrl(args.callbackUrl))
+ val session = AuthSession.Pending(args.authUrl, args.callbackUrl, activity.taskId)
+ if (!AuthSession.begin(session)) {
+ invoke.reject("An authentication session is already running")
+ return
+ }
+ started = session
+ val intent = Intent(activity, AuthActivity::class.java)
+ .putExtra("callbackUrl", args.callbackUrl)
+ startActivityForResult(invoke, intent, "authResult")
+ } catch (_: Exception) {
+ started?.let { AuthSession.clear(it.callbackUrl) }
+ invoke.reject("Unable to start authentication")
+ }
+ }
+
+ @ActivityCallback
+ fun authResult(invoke: Invoke, result: ActivityResult) {
+ AuthSession.clear(invoke.parseArgs(AuthenticateArgs::class.java).callbackUrl)
+ val response = JSObject()
+ val success = result.resultCode == Activity.RESULT_OK
+ response.put("success", success)
+ if (success) {
+ result.data?.getStringExtra("token")?.let { response.put("token", it) }
+ } else {
+ response.put("error", result.data?.getStringExtra("error") ?: "User canceled login")
+ }
+ invoke.resolve(response)
+ }
+}
diff --git a/apps/web/tauri/android_auth_plugin/android/src/main/java/com/macro/auth/AuthRedirectActivity.kt b/apps/web/tauri/android_auth_plugin/android/src/main/java/com/macro/auth/AuthRedirectActivity.kt
new file mode 100644
index 0000000000..fd20fa1729
--- /dev/null
+++ b/apps/web/tauri/android_auth_plugin/android/src/main/java/com/macro/auth/AuthRedirectActivity.kt
@@ -0,0 +1,26 @@
+package com.macro.auth
+
+import android.app.Activity
+import android.app.ActivityManager
+import android.content.Intent
+import android.os.Bundle
+
+/** Brings the pending auth activity forward when a browser lacks Auth Tab support. */
+class AuthRedirectActivity : Activity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ intent.data?.let { callback ->
+ val session = AuthSession.matching(callback.toString()) ?: return@let
+ // The receiver may be in the browser's task. Return to the task that
+ // owns the invocation, rather than creating an unrelated auth activity.
+ val task = getSystemService(ActivityManager::class.java).appTasks
+ .firstOrNull { it.taskInfo.id == session.taskId } ?: return@let
+ AuthSession.receive(callback.toString()) ?: return@let
+ task.startActivity(this, Intent(this, AuthActivity::class.java)
+ .putExtra("callbackUrl", session.callbackUrl)
+ .setData(callback)
+ .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP), null)
+ }
+ finish()
+ }
+}
diff --git a/apps/web/tauri/android_auth_plugin/android/src/main/java/com/macro/auth/AuthSession.kt b/apps/web/tauri/android_auth_plugin/android/src/main/java/com/macro/auth/AuthSession.kt
new file mode 100644
index 0000000000..6689b9001d
--- /dev/null
+++ b/apps/web/tauri/android_auth_plugin/android/src/main/java/com/macro/auth/AuthSession.kt
@@ -0,0 +1,37 @@
+package com.macro.auth
+
+/** In-memory only: a browser redirect must never resurrect a process-dead invocation. */
+internal object AuthSession {
+ data class Pending(
+ val authUrl: String,
+ val callbackUrl: String,
+ val taskId: Int,
+ val receivedCallback: String? = null,
+ )
+
+ @Volatile
+ var pending: Pending? = null
+ private set
+
+ @Synchronized
+ fun begin(session: Pending): Boolean {
+ if (pending != null) return false
+ pending = session
+ return true
+ }
+
+ fun matching(callback: String): Pending? =
+ pending?.takeIf { AuthCallback.matches(it.callbackUrl, callback) }
+
+ @Synchronized
+ fun receive(callback: String): Pending? {
+ val session = matching(callback) ?: return null
+ if (session.receivedCallback != null) return null
+ return session.copy(receivedCallback = callback).also { pending = it }
+ }
+
+ @Synchronized
+ fun clear(callbackUrl: String) {
+ if (pending?.callbackUrl == callbackUrl) pending = null
+ }
+}
diff --git a/apps/web/tauri/android_auth_plugin/android/src/test/java/com/macro/auth/AuthCallbackTest.kt b/apps/web/tauri/android_auth_plugin/android/src/test/java/com/macro/auth/AuthCallbackTest.kt
new file mode 100644
index 0000000000..ad0403e986
--- /dev/null
+++ b/apps/web/tauri/android_auth_plugin/android/src/test/java/com/macro/auth/AuthCallbackTest.kt
@@ -0,0 +1,40 @@
+package com.macro.auth
+
+import org.junit.Assert.*
+import org.junit.Test
+
+class AuthCallbackTest {
+ private val expected = "macro://android-auth/123e4567-e89b-42d3-a456-426614174000"
+
+ @Test fun acceptsOnlyTheCurrentAttempt() {
+ assertTrue(AuthCallback.matches(expected, "$expected?token=one-time-code"))
+ assertTrue(AuthCallback.matches(expected, expected)) // GitHub linking has no session code.
+ for (callback in listOf(
+ expected.replace("174000", "174001") + "?token=stale",
+ expected.replace("macro:", "https:"),
+ expected.replace("android-auth", "evil.example"),
+ expected.replace("android-auth", "user@android-auth"),
+ "$expected/extra?token=wrong-path",
+ "$expected#token=fragment",
+ "not a URL"
+ )) {
+ assertFalse(callback, AuthCallback.matches(expected, callback))
+ }
+ }
+
+ @Test fun rejectsInvalidExpectedCallbacks() {
+ assertFalse(AuthCallback.isExpectedUrl("macro://android-auth/fixed"))
+ assertFalse(AuthCallback.isExpectedUrl("$expected?token=old"))
+ assertFalse(AuthCallback.isExpectedUrl("$expected#fragment"))
+ }
+
+ @Test fun decodesParametersOnce() {
+ assertEquals("one+code", AuthCallback.parameters("$expected?token=one%2Bcode")["token"])
+ assertEquals("access_denied", AuthCallback.parameters("$expected?error=access_denied")["error"])
+ }
+
+ @Test(expected = IllegalArgumentException::class)
+ fun rejectsDuplicateTokens() {
+ AuthCallback.parameters("$expected?token=first&%74oken=second")
+ }
+}
diff --git a/apps/web/tauri/android_auth_plugin/android/src/test/java/com/macro/auth/AuthSessionTest.kt b/apps/web/tauri/android_auth_plugin/android/src/test/java/com/macro/auth/AuthSessionTest.kt
new file mode 100644
index 0000000000..0bb394710f
--- /dev/null
+++ b/apps/web/tauri/android_auth_plugin/android/src/test/java/com/macro/auth/AuthSessionTest.kt
@@ -0,0 +1,45 @@
+package com.macro.auth
+
+import org.junit.After
+import org.junit.Assert.*
+import org.junit.Test
+
+class AuthSessionTest {
+ private val expected = "macro://android-auth/123e4567-e89b-42d3-a456-426614174000"
+ private val session = AuthSession.Pending("https://example.com/login", expected, 42)
+
+ @After fun cleanup() {
+ AuthSession.pending?.let { AuthSession.clear(it.callbackUrl) }
+ }
+
+ @Test fun staleCallbackLeavesTheCurrentSessionAvailable() {
+ assertTrue(AuthSession.begin(session))
+ assertNull(AuthSession.receive(expected.replace("174000", "174001") + "?token=stale"))
+ assertEquals(session, AuthSession.matching("$expected?token=current"))
+ assertEquals(42, AuthSession.matching(expected)?.taskId)
+ }
+
+ @Test fun recordsTheFirstValidRedirectBeforeBrowserCancellation() {
+ assertTrue(AuthSession.begin(session))
+ val callback = "$expected?token=current"
+ assertEquals(callback, AuthSession.receive(callback)?.receivedCallback)
+ assertEquals(callback, AuthSession.pending?.receivedCallback)
+ assertNull(AuthSession.receive("$expected?token=duplicate"))
+ assertEquals(callback, AuthSession.pending?.receivedCallback)
+ }
+
+ @Test fun absentOrFinishedSessionsCannotBeResurrectedByCallbacks() {
+ assertNull(AuthSession.matching("$expected?token=orphan"))
+ assertTrue(AuthSession.begin(session))
+ AuthSession.clear(expected)
+ assertNull(AuthSession.matching("$expected?token=duplicate"))
+ assertTrue(AuthSession.begin(session.copy(callbackUrl = expected.replace("174000", "174001"))))
+ }
+
+ @Test fun overlappingAttemptsAndOldCleanupCannotReplaceTheCurrentSession() {
+ assertTrue(AuthSession.begin(session))
+ assertFalse(AuthSession.begin(session.copy(taskId = 99)))
+ AuthSession.clear(expected.replace("174000", "174001"))
+ assertEquals(session, AuthSession.pending)
+ }
+}
diff --git a/apps/web/tauri/android_auth_plugin/build.rs b/apps/web/tauri/android_auth_plugin/build.rs
new file mode 100644
index 0000000000..f867243100
--- /dev/null
+++ b/apps/web/tauri/android_auth_plugin/build.rs
@@ -0,0 +1,5 @@
+fn main() {
+ tauri_plugin::Builder::new(&["authenticate"])
+ .android_path("android")
+ .build();
+}
diff --git a/apps/web/tauri/android_auth_plugin/permissions/autogenerated/commands/authenticate.toml b/apps/web/tauri/android_auth_plugin/permissions/autogenerated/commands/authenticate.toml
new file mode 100644
index 0000000000..be4c9f9b44
--- /dev/null
+++ b/apps/web/tauri/android_auth_plugin/permissions/autogenerated/commands/authenticate.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-authenticate"
+description = "Enables the authenticate command without any pre-configured scope."
+commands.allow = ["authenticate"]
+
+[[permission]]
+identifier = "deny-authenticate"
+description = "Denies the authenticate command without any pre-configured scope."
+commands.deny = ["authenticate"]
diff --git a/apps/web/tauri/android_auth_plugin/permissions/autogenerated/reference.md b/apps/web/tauri/android_auth_plugin/permissions/autogenerated/reference.md
new file mode 100644
index 0000000000..2122c24c9d
--- /dev/null
+++ b/apps/web/tauri/android_auth_plugin/permissions/autogenerated/reference.md
@@ -0,0 +1,35 @@
+## Permission Table
+
+<table>
+<tr>
+<th>Identifier</th>
+<th>Description</th>
+</tr>
+
+
+<tr>
+<td>
+
+`android-auth:allow-authenticate`
+
+</td>
+<td>
+
+Enables the authenticate command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`android-auth:deny-authenticate`
+
+</td>
+<td>
+
+Denies the authenticate command without any pre-configured scope.
+
+</td>
+</tr>
+</table>
diff --git a/apps/web/tauri/android_auth_plugin/permissions/schemas/schema.json b/apps/web/tauri/android_auth_plugin/permissions/schemas/schema.json
new file mode 100644
index 0000000000..ae6ce4cdde
--- /dev/null
+++ b/apps/web/tauri/android_auth_plugin/permissions/schemas/schema.json
@@ -0,0 +1,312 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "title": "PermissionFile",
+ "description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
+ "type": "object",
+ "properties": {
+ "default": {
+ "description": "The default permission set for the plugin",
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DefaultPermission"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "set": {
+ "description": "A list of permissions sets defined",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/PermissionSet"
+ }
+ },
+ "permission": {
+ "description": "A list of inlined permissions",
+ "default": [],
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Permission"
+ }
+ }
+ },
+ "definitions": {
+ "DefaultPermission": {
+ "description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
+ "type": "object",
+ "required": [
+ "permissions"
+ ],
+ "properties": {
+ "version": {
+ "description": "The version of the permission.",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "format": "uint64",
+ "minimum": 1.0
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "permissions": {
+ "description": "All permissions this set contains.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "PermissionSet": {
+ "description": "A set of direct permissions grouped together under a new name.",
+ "type": "object",
+ "required": [
+ "description",
+ "identifier",
+ "permissions"
+ ],
+ "properties": {
+ "identifier": {
+ "description": "A unique identifier for the permission.",
+ "type": "string"
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does.",
+ "type": "string"
+ },
+ "permissions": {
+ "description": "All permissions this set contains.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/PermissionKind"
+ }
+ }
+ }
+ },
+ "Permission": {
+ "description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
+ "type": "object",
+ "required": [
+ "identifier"
+ ],
+ "properties": {
+ "version": {
+ "description": "The version of the permission.",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "format": "uint64",
+ "minimum": 1.0
+ },
+ "identifier": {
+ "description": "A unique identifier for the permission.",
+ "type": "string"
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "commands": {
+ "description": "Allowed or denied commands when using this permission.",
+ "default": {
+ "allow": [],
+ "deny": []
+ },
+ "allOf": [
+ {
+ "$ref": "#/definitions/Commands"
+ }
+ ]
+ },
+ "scope": {
+ "description": "Allowed or denied scoped when using this permission.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/Scopes"
+ }
+ ]
+ },
+ "platforms": {
+ "description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Target"
+ }
+ }
+ }
+ },
+ "Commands": {
+ "description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
+ "type": "object",
+ "properties": {
+ "allow": {
+ "description": "Allowed command.",
+ "default": [],
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "deny": {
+ "description": "Denied command, which takes priority.",
+ "default": [],
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "Scopes": {
+ "description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
+ "type": "object",
+ "properties": {
+ "allow": {
+ "description": "Data that defines what is allowed by the scope.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ },
+ "deny": {
+ "description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ }
+ }
+ },
+ "Value": {
+ "description": "All supported ACL values.",
+ "anyOf": [
+ {
+ "description": "Represents a null JSON value.",
+ "type": "null"
+ },
+ {
+ "description": "Represents a [`bool`].",
+ "type": "boolean"
+ },
+ {
+ "description": "Represents a valid ACL [`Number`].",
+ "allOf": [
+ {
+ "$ref": "#/definitions/Number"
+ }
+ ]
+ },
+ {
+ "description": "Represents a [`String`].",
+ "type": "string"
+ },
+ {
+ "description": "Represents a list of other [`Value`]s.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ },
+ {
+ "description": "Represents a map of [`String`] keys to [`Value`]s.",
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/definitions/Value"
+ }
+ }
+ ]
+ },
+ "Number": {
+ "description": "A valid ACL number.",
+ "anyOf": [
+ {
+ "description": "Represents an [`i64`].",
+ "type": "integer",
+ "format": "int64"
+ },
+ {
+ "description": "Represents a [`f64`].",
+ "type": "number",
+ "format": "double"
+ }
+ ]
+ },
+ "Target": {
+ "description": "Platform target.",
+ "oneOf": [
+ {
+ "description": "MacOS.",
+ "type": "string",
+ "enum": [
+ "macOS"
+ ]
+ },
+ {
+ "description": "Windows.",
+ "type": "string",
+ "enum": [
+ "windows"
+ ]
+ },
+ {
+ "description": "Linux.",
+ "type": "string",
+ "enum": [
+ "linux"
+ ]
+ },
+ {
+ "description": "Android.",
+ "type": "string",
+ "enum": [
+ "android"
+ ]
+ },
+ {
+ "description": "iOS.",
+ "type": "string",
+ "enum": [
+ "iOS"
+ ]
+ }
+ ]
+ },
+ "PermissionKind": {
+ "type": "string",
+ "oneOf": [
+ {
+ "description": "Enables the authenticate command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-authenticate",
+ "markdownDescription": "Enables the authenticate command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the authenticate command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-authenticate",
+ "markdownDescription": "Denies the authenticate command without any pre-configured scope."
+ }
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/apps/web/tauri/android_auth_plugin/src/android.rs b/apps/web/tauri/android_auth_plugin/src/android.rs
new file mode 100644
index 0000000000..f2173271b3
--- /dev/null
+++ b/apps/web/tauri/android_auth_plugin/src/android.rs
@@ -0,0 +1,31 @@
+use serde::{Deserialize, Serialize};
+use tauri::{AppHandle, Manager, Runtime, plugin::PluginHandle};
+
+pub(crate) struct Auth<R: Runtime>(pub PluginHandle<R>);
+
+#[derive(Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct AuthenticateArgs {
+ auth_url: String,
+ callback_url: String,
+}
+
+#[derive(Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct AuthResult {
+ success: bool,
+ token: Option<String>,
+ error: Option<String>,
+}
+
+#[tauri::command]
+pub(crate) async fn authenticate<R: Runtime>(
+ app: AppHandle<R>,
+ payload: AuthenticateArgs,
+) -> Result<AuthResult, String> {
+ app.state::<Auth<R>>()
+ .0
+ .run_mobile_plugin_async("authenticate", payload)
+ .await
+ .map_err(|error| error.to_string())
+}
diff --git a/apps/web/tauri/android_auth_plugin/src/lib.rs b/apps/web/tauri/android_auth_plugin/src/lib.rs
new file mode 100644
index 0000000000..fbaab6a0bf
--- /dev/null
+++ b/apps/web/tauri/android_auth_plugin/src/lib.rs
@@ -0,0 +1,23 @@
+//! Browser authentication for Android. iOS retains its ASWebAuthenticationSession plugin.
+#![deny(missing_docs)]
+
+use tauri::Runtime;
+use tauri::plugin::{Builder, TauriPlugin};
+
+#[cfg(target_os = "android")]
+mod android;
+
+/// Registers the Android browser authentication command and native bridge.
+pub fn init<R: Runtime>() -> TauriPlugin<R> {
+ let builder = Builder::new("android-auth");
+ #[cfg(target_os = "android")]
+ let builder = builder
+ .invoke_handler(tauri::generate_handler![android::authenticate])
+ .setup(|app, api| {
+ use tauri::Manager;
+ let handle = api.register_android_plugin("com.macro.auth", "AuthPlugin")?;
+ app.manage(android::Auth(handle));
+ Ok(())
+ });
+ builder.build()
+}
diff --git a/apps/web/tauri/navigation_plugin/src/lib.rs b/apps/web/tauri/navigation_plugin/src/lib.rs
index 884d5b32c9..1381d8c971 100644
--- a/apps/web/tauri/navigation_plugin/src/lib.rs
+++ b/apps/web/tauri/navigation_plugin/src/lib.rs
@@ -104,20 +104,7 @@ impl MacroNavigationPlugin {
#[tracing::instrument(ret, level = tracing::Level::DEBUG, skip(self))]
fn as_app_link(&self, url: &Url) -> Option<MacroScheme> {
- if !matches!(url.scheme(), "http" | "https") {
- return None;
- }
- let domain = url.domain()?;
- let domain = domain.strip_prefix("www.").unwrap_or(domain);
- if !self
- .app_link_hosts
- .iter()
- .any(|host| domain.eq_ignore_ascii_case(host))
- {
- return None;
- }
- let path = url.path();
- if path != "/app" && !path.starts_with("/app/") {
+ if !is_app_link(self.app_link_hosts, url) {
return None;
}
MacroScheme::from_url(url).ok()
@@ -153,6 +140,21 @@ impl MacroNavigationPlugin {
}
}
+/// Whether `url` is an `http(s)://<host>/app...` link for one of `hosts`,
+/// ignoring a `www.` prefix and host case.
+pub fn is_app_link(hosts: &[&str], url: &Url) -> bool {
+ if !matches!(url.scheme(), "http" | "https") {
+ return false;
+ }
+ let Some(domain) = url.domain() else {
+ return false;
+ };
+ let domain = domain.strip_prefix("www.").unwrap_or(domain);
+ let path = url.path();
+ hosts.iter().any(|host| domain.eq_ignore_ascii_case(host))
+ && (path == "/app" || path.starts_with("/app/"))
+}
+
#[tracing::instrument(ret, level = tracing::Level::DEBUG)]
fn transform_external_url(mut url: Url) -> Url {
let Some(query) = url.query() else {
diff --git a/apps/web/tauri/src-tauri/.well-known/assetlinks.dev.json b/apps/web/tauri/src-tauri/.well-known/assetlinks.dev.json
new file mode 100644
index 0000000000..8e18710ac4
--- /dev/null
+++ b/apps/web/tauri/src-tauri/.well-known/assetlinks.dev.json
@@ -0,0 +1,15 @@
+[
+ {
+ "relation": [
+ "delegate_permission/common.handle_all_urls"
+ ],
+ "target": {
+ "namespace": "android_app",
+ "package_name": "com.macro.app.prod",
+ "sha256_cert_fingerprints": [
+ "1F:E1:30:45:EE:64:BD:02:DA:24:F7:E8:D5:08:8B:1A:B2:88:4E:DB:E3:CB:AE:00:A1:E1:F6:87:E3:0A:3E:06",
+ "89:D3:D8:C4:BB:61:96:DE:43:B3:C9:11:4B:FC:74:49:E1:A5:F3:3E:D2:B0:99:9A:E5:97:C5:DF:B8:F5:85:47"
+ ]
+ }
+ }
+]
diff --git a/apps/web/tauri/src-tauri/.well-known/assetlinks.json b/apps/web/tauri/src-tauri/.well-known/assetlinks.json
index 963f4ac955..fe51488c70 100644
--- a/apps/web/tauri/src-tauri/.well-known/assetlinks.json
+++ b/apps/web/tauri/src-tauri/.well-known/assetlinks.json
@@ -1,14 +1 @@
-[
- {
- "relation": [
- "delegate_permission/common.handle_all_urls"
- ],
- "target": {
- "namespace": "android_app",
- "package_name": "com.tauri.dev",
- "sha256_cert_fingerprints": [
- "30:5B:31:07:B9:52:A7:97:80:4C:BA:50:0C:12:9F:97:2F:53:36:25:D8:66:B2:41:0E:88:AE:60:48:F1:0B:7C"
- ]
- }
- }
-]
\ No newline at end of file
+[]
diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.toml
index b27acba33b..ca996d169e 100644
--- a/apps/web/tauri/src-tauri/Cargo.toml
+++ b/apps/web/tauri/src-tauri/Cargo.toml
@@ -10,7 +10,7 @@ version = "0.1.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
-crate-type = ["rlib", "staticlib"]
+crate-type = ["rlib", "staticlib", "cdylib"]
name = "app_lib"
[build-dependencies]
@@ -33,7 +33,6 @@ rootcause = { workspace = true }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
staged_upload_constants = { path = "../staged_upload_constants" }
-tracing-oslog = { version = "0.3" }
nom = "8.0.0"
reqwest = { workspace = true, features = ["cookies", "stream"] }
@@ -67,17 +66,23 @@ navigation_plugin = { path = "../navigation_plugin" }
tauri-plugin-device-info = "1.0.1"
tauri-plugin-notifications = { git = "https://github.com/macro-inc/tauri-plugins", rev = "6ddd6600e20436388f169e936b610fe93944b7b0" }
tauri-plugin-os = "2"
-tauri-plugin-virtual-keyboard = { git = "https://github.com/voxelbee/tauri-plugin-virtual-keyboard", branch = "main" }
[target."cfg(any(target_os = \"macos\", windows, target_os = \"linux\"))".dependencies]
tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }
[target.'cfg(any(target_os = "android", target_os = "ios"))'.dependencies]
-tauri-plugin-auth = { git = "https://github.com/macro-inc/tauri-plugins", rev = "6ddd6600e20436388f169e936b610fe93944b7b0" }
tauri-plugin-haptics = "2"
+[target.'cfg(target_os = "android")'.dependencies]
+jni = "0.21"
+rustls-platform-verifier = "0.6"
+tauri-plugin-android-auth = { path = "../android_auth_plugin" }
+
[target.'cfg(target_os = "ios")'.dependencies]
+tauri-plugin-auth = { git = "https://github.com/macro-inc/tauri-plugins", rev = "6ddd6600e20436388f169e936b610fe93944b7b0" }
+tauri-plugin-virtual-keyboard = { git = "https://github.com/voxelbee/tauri-plugin-virtual-keyboard", branch = "main" }
+tracing-oslog = { version = "0.3" }
tauri-plugin-call-kit = { path = "../callkit_plugin" }
tauri-plugin-edit-menu = { path = "../edit_menu_plugin" }
tauri-plugin-input-accessory = { path = "../input_accessory_plugin" }
diff --git a/apps/web/tauri/src-tauri/README.md b/apps/web/tauri/src-tauri/README.md
index 6183b645ed..6489434a2d 100644
--- a/apps/web/tauri/src-tauri/README.md
+++ b/apps/web/tauri/src-tauri/README.md
@@ -104,6 +104,14 @@ The `beforeBuildCommand` is `just build-tauri`, which runs `bun run build` and
emits the frontend into `dist`. Tauri then packages that output
according to `tauri.conf.json`.
+The Rust library emits `staticlib` for iOS and `cdylib` for Android. Cargo emits
+both outputs on iOS, but Xcode links only the static archive into the app.
+CallKit's Swift package is part of Xcode's dependency graph, so `build.rs` permits
+its initializer to remain unresolved only in the unused iOS dylib. The final
+Xcode app link must still resolve `init_plugin_call_kit` from the Swift package.
+Do not remove Android's `cdylib` output or disable undefined-symbol checking
+globally to work around an iOS link failure.
+
GraphQL hydration checkpoints require the native
`graphql_cache_current_storage_generation` command. When shipping this frontend
through the bundle updater, set `MIN_NATIVE_BUILD` to the first native build that
diff --git a/apps/web/tauri/src-tauri/build.rs b/apps/web/tauri/src-tauri/build.rs
index 0f3e70b076..3639562bac 100644
--- a/apps/web/tauri/src-tauri/build.rs
+++ b/apps/web/tauri/src-tauri/build.rs
@@ -1,4 +1,12 @@
fn main() {
+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("ios") {
+ // Android needs cdylib, so Cargo also emits an unused iOS dylib. CallKit's
+ // Swift package is linked by Xcode into the final app, not by Cargo.
+ // Defer only this symbol in the dylib; the shipped staticlib/app link
+ // still requires Xcode to supply the real implementation.
+ println!("cargo:rustc-link-arg-cdylib=-Wl,-U,_init_plugin_call_kit");
+ }
+
println!("cargo:rerun-if-changed=.macro-tauri-env");
println!("cargo:rerun-if-changed=../../dist/bundle-manifest.json");
println!("cargo:rerun-if-env-changed=MACRO_BUNDLE_UPDATE_BASE_URL");
diff --git a/apps/web/tauri/src-tauri/capabilities/android.json b/apps/web/tauri/src-tauri/capabilities/android.json
new file mode 100644
index 0000000000..58f5490605
--- /dev/null
+++ b/apps/web/tauri/src-tauri/capabilities/android.json
@@ -0,0 +1,12 @@
+{
+ "identifier": "android-capability",
+ "platforms": [
+ "android"
+ ],
+ "windows": [
+ "main"
+ ],
+ "permissions": [
+ "android-auth:allow-authenticate"
+ ]
+}
diff --git a/apps/web/tauri/src-tauri/capabilities/ios.json b/apps/web/tauri/src-tauri/capabilities/ios.json
new file mode 100644
index 0000000000..262178a42f
--- /dev/null
+++ b/apps/web/tauri/src-tauri/capabilities/ios.json
@@ -0,0 +1,35 @@
+{
+ "identifier": "ios-capability",
+ "platforms": [
+ "iOS"
+ ],
+ "windows": [
+ "main"
+ ],
+ "permissions": [
+ "auth:allow-authenticate",
+ "edit-menu:allow-set-native-menu-suppressed",
+ "pasteboard:allow-read-pasteboard-text",
+ "network-status:allow-watch-status",
+ "pasteboard:allow-stage-pasteboard-image",
+ "photo-library:allow-pick-photo-library-images",
+ "call-kit:allow-register-listener",
+ "call-kit:allow-remove-listener",
+ "call-kit:allow-get-voip-token",
+ "call-kit:allow-end-active-call",
+ "call-kit:allow-get-pending-answered-call",
+ "call-kit:allow-watch-call-answered",
+ "call-kit:allow-watch-call-ended",
+ "call-kit:allow-watch-connection-state",
+ "call-kit:allow-watch-drawer-opened",
+ "call-kit:allow-watch-participant-identities",
+ "call-kit:allow-get-active-call-state",
+ "call-kit:allow-start-outgoing-call",
+ "call-kit:allow-set-video-enabled",
+ "call-kit:allow-set-video-overlay-mode",
+ "call-kit:allow-set-call-drawer-channel-title",
+ "call-kit:allow-set-call-drawer-theme",
+ "call-kit:allow-set-participant-display-name",
+ "call-kit:allow-switch-camera"
+ ]
+}
diff --git a/apps/web/tauri/src-tauri/capabilities/mobile.json b/apps/web/tauri/src-tauri/capabilities/mobile.json
index 7b5afdd16f..a5e4bbcc5a 100644
--- a/apps/web/tauri/src-tauri/capabilities/mobile.json
+++ b/apps/web/tauri/src-tauri/capabilities/mobile.json
@@ -13,30 +13,6 @@
"haptics:allow-selection-feedback",
"haptics:allow-vibrate",
"log:default",
- "auth:allow-authenticate",
- "device-info:default",
- "edit-menu:allow-set-native-menu-suppressed",
- "pasteboard:allow-read-pasteboard-text",
- "network-status:allow-watch-status",
- "pasteboard:allow-stage-pasteboard-image",
- "photo-library:allow-pick-photo-library-images",
- "call-kit:allow-register-listener",
- "call-kit:allow-remove-listener",
- "call-kit:allow-get-voip-token",
- "call-kit:allow-end-active-call",
- "call-kit:allow-get-pending-answered-call",
- "call-kit:allow-watch-call-answered",
- "call-kit:allow-watch-call-ended",
- "call-kit:allow-watch-connection-state",
- "call-kit:allow-watch-drawer-opened",
- "call-kit:allow-watch-participant-identities",
- "call-kit:allow-get-active-call-state",
- "call-kit:allow-start-outgoing-call",
- "call-kit:allow-set-video-enabled",
- "call-kit:allow-set-video-overlay-mode",
- "call-kit:allow-set-call-drawer-channel-title",
- "call-kit:allow-set-call-drawer-theme",
- "call-kit:allow-set-participant-display-name",
- "call-kit:allow-switch-camera"
+ "device-info:default"
]
}
diff --git a/apps/web/tauri/src-tauri/gen/android/.gitignore b/apps/web/tauri/src-tauri/gen/android/.gitignore
index b248203172..d7d0a8b3eb 100644
--- a/apps/web/tauri/src-tauri/gen/android/.gitignore
+++ b/apps/web/tauri/src-tauri/gen/android/.gitignore
@@ -14,6 +14,9 @@ build
.cxx
local.properties
key.properties
+keystore.properties
+*.jks
+*.keystore
/.tauri
-/tauri.settings.gradle
\ No newline at end of file
+/tauri.settings.gradle
diff --git a/apps/web/tauri/src-tauri/gen/android/app/build.gradle.kts b/apps/web/tauri/src-tauri/gen/android/app/build.gradle.kts
index bf05846e06..8882b56de7 100644
--- a/apps/web/tauri/src-tauri/gen/android/app/build.gradle.kts
+++ b/apps/web/tauri/src-tauri/gen/android/app/build.gradle.kts
@@ -4,7 +4,42 @@ plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("rust")
- id("com.google.gms.google-services")
+ id("com.google.gms.google-services") apply false
+}
+
+// Debug auth/navigation work can run before a Firebase project is provisioned.
+// Release artifacts must be built with the real application configuration.
+val firebaseConfigured = file("google-services.json").isFile
+val keystorePropertiesFile = rootProject.file("keystore.properties")
+// Defer signing failures until release work is requested so debug builds remain usable.
+val releaseSigningProperties = runCatching {
+ if (!keystorePropertiesFile.isFile) {
+ throw GradleException("Release builds require keystore.properties; see docs/ANDROID_DEVELOPMENT.md")
+ }
+ val properties = Properties().apply {
+ keystorePropertiesFile.inputStream().use { load(it) }
+ }
+ for (name in listOf("keyAlias", "keyPassword", "storePassword", "storeFile")) {
+ if (properties.getProperty(name).isNullOrBlank()) {
+ throw GradleException("Missing $name in keystore.properties; see docs/ANDROID_DEVELOPMENT.md")
+ }
+ }
+ if (!rootProject.file(properties.getProperty("storeFile")).isFile) {
+ throw GradleException("Signing keystore does not exist")
+ }
+ properties
+}
+
+if (firebaseConfigured) {
+ apply(plugin = "com.google.gms.google-services")
+}
+gradle.taskGraph.whenReady {
+ if (!firebaseConfigured && allTasks.any { it.name.contains("Release") }) {
+ throw GradleException("Release builds require app/google-services.json for com.macro.app.prod; see docs/ANDROID_DEVELOPMENT.md")
+ }
+ if (allTasks.any { it.name.contains("Release") }) {
+ releaseSigningProperties.getOrThrow()
+ }
}
val tauriProperties = Properties().apply {
@@ -25,19 +60,31 @@ android {
versionCode = tauriProperties.getProperty("tauri.android.versionCode", "1").toInt()
versionName = tauriProperties.getProperty("tauri.android.versionName", "1.0")
}
+ signingConfigs {
+ releaseSigningProperties.getOrNull()?.let { properties ->
+ create("release") {
+ keyAlias = properties.getProperty("keyAlias")
+ keyPassword = properties.getProperty("keyPassword")
+ storePassword = properties.getProperty("storePassword")
+ storeFile = rootProject.file(properties.getProperty("storeFile"))
+ }
+ }
+ }
buildTypes {
getByName("debug") {
manifestPlaceholders["usesCleartextTraffic"] = "true"
isDebuggable = true
isJniDebuggable = true
isMinifyEnabled = false
- packaging { jniLibs.keepDebugSymbols.add("*/arm64-v8a/*.so")
+ packaging {
+ jniLibs.keepDebugSymbols.add("*/arm64-v8a/*.so")
jniLibs.keepDebugSymbols.add("*/armeabi-v7a/*.so")
jniLibs.keepDebugSymbols.add("*/x86/*.so")
jniLibs.keepDebugSymbols.add("*/x86_64/*.so")
}
}
getByName("release") {
+ signingConfig = signingConfigs.findByName("release")
isMinifyEnabled = true
proguardFiles(
*fileTree(".") { include("**/*.pro") }
@@ -70,4 +117,5 @@ dependencies {
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.0")
}
-apply(from = "tauri.build.gradle.kts")
\ No newline at end of file
+apply(from = "tauri.build.gradle.kts")
+apply(from = "rustls-verifier.gradle.kts")
diff --git a/apps/web/tauri/src-tauri/gen/android/app/proguard-rules.pro b/apps/web/tauri/src-tauri/gen/android/app/proguard-rules.pro
index 481bb43481..781a96c15b 100644
--- a/apps/web/tauri/src-tauri/gen/android/app/proguard-rules.pro
+++ b/apps/web/tauri/src-tauri/gen/android/app/proguard-rules.pro
@@ -1,4 +1,5 @@
# Add project specific ProGuard rules here.
+-keep,includedescriptorclasses class org.rustls.platformverifier.** { *; }
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
@@ -18,4 +19,4 @@
# If you keep the line number information, uncomment this to
# hide the original source file name.
-#-renamesourcefileattribute SourceFile
\ No newline at end of file
+#-renamesourcefileattribute SourceFile
diff --git a/apps/web/tauri/src-tauri/gen/android/app/rustls-verifier.gradle.kts b/apps/web/tauri/src-tauri/gen/android/app/rustls-verifier.gradle.kts
new file mode 100644
index 0000000000..44c9ebd357
--- /dev/null
+++ b/apps/web/tauri/src-tauri/gen/android/app/rustls-verifier.gradle.kts
@@ -0,0 +1,24 @@
+import groovy.json.JsonSlurper
+
+// Use the Maven artifact shipped by the resolved Rust crate, so its JNI API
+// always matches the Rust verifier. Never substitute a separately versioned AAR.
+val metadata = providers.exec {
+ workingDir(file("../../.."))
+ commandLine("cargo", "metadata", "--format-version", "1", "--locked",
+ "--filter-platform", "aarch64-linux-android")
+}.standardOutput.asText.get()
+val packages = (JsonSlurper().parseText(metadata) as Map<*, *>)["packages"] as List<*>
+val verifier = packages.map { it as Map<*, *> }
+ .single { it["name"] == "rustls-platform-verifier-android" }
+val manifest = File(verifier["manifest_path"] as String)
+
+repositories {
+ maven {
+ url = uri(File(manifest.parentFile, "maven"))
+ metadataSources { artifact() }
+ content { includeGroup("rustls") }
+ }
+}
+dependencies {
+ add("implementation", "rustls:rustls-platform-verifier:${verifier["version"]}@aar")
+}
diff --git a/apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml b/apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml
index 6a759427bb..5461d8ed8b 100644
--- a/apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml
+++ b/apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml
@@ -28,7 +28,7 @@
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="macro" />
-
+ <data android:host="app" />
diff --git a/apps/web/tauri/src-tauri/gen/android/app/src/main/java/com/macro/app/prod/MainActivity.kt b/apps/web/tauri/src-tauri/gen/android/app/src/main/java/com/macro/app/prod/MainActivity.kt
index 86d835d46e..254cf10a2f 100644
--- a/apps/web/tauri/src-tauri/gen/android/app/src/main/java/com/macro/app/prod/MainActivity.kt
+++ b/apps/web/tauri/src-tauri/gen/android/app/src/main/java/com/macro/app/prod/MainActivity.kt
@@ -1,10 +1,20 @@
package com.macro.app.prod
import android.os.Bundle
+import android.content.Context
import androidx.activity.enableEdgeToEdge
class MainActivity : TauriActivity() {
+ companion object {
+ init { System.loadLibrary("app_lib") }
+ }
+
+ private external fun initializeCertificateVerifier(context: Context): Boolean
+
override fun onCreate(savedInstanceState: Bundle?) {
+ check(initializeCertificateVerifier(applicationContext)) {
+ "Unable to initialize Android certificate verification"
+ }
enableEdgeToEdge()
super.onCreate(savedInstanceState)
}
diff --git a/apps/web/tauri/src-tauri/src/android_tls.rs b/apps/web/tauri/src-tauri/src/android_tls.rs
new file mode 100644
index 0000000000..9fee401905
--- /dev/null
+++ b/apps/web/tauri/src-tauri/src/android_tls.rs
@@ -0,0 +1,17 @@
+//! Initializes Android's system certificate verifier before Tauri starts networking.
+
+use jni::{JNIEnv, objects::JObject, sys::jboolean};
+
+#[unsafe(no_mangle)]
+extern "system" fn Java_com_macro_app_prod_MainActivity_initializeCertificateVerifier(
+ mut env: JNIEnv,
+ _activity: JObject,
+ context: JObject,
+) -> jboolean {
+ // MainActivity passes the application context, whose lifetime is the process.
+ // The verifier retains its own global JNI references and initializes once.
+ match rustls_platform_verifier::android::init_with_env(&mut env, context) {
+ Ok(()) => jni::sys::JNI_TRUE,
+ Err(_) => jni::sys::JNI_FALSE,
+ }
+}
diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rs
index f61e1ceec0..57d9e9a6ed 100644
--- a/apps/web/tauri/src-tauri/src/lib.rs
+++ b/apps/web/tauri/src-tauri/src/lib.rs
@@ -23,6 +23,8 @@ use staged_upload::cleanup_stale_staged_files;
use tauri::http::{HeaderMap, HeaderValue};
use tauri::{AppHandle, Emitter, Manager, RunEvent, Runtime};
+#[cfg(target_os = "android")]
+mod android_tls;
mod tauri_protocol;
pub(crate) const APP_SCHEME: &str = "macro";
@@ -87,6 +89,7 @@ mod debug;
/// If the webview attempts to naviate to other domains,
/// they will be opened in the systems default browser
static ALLOWED_DOMAINS: &[&str] = &[
+ "https://tauri.localhost",
"http://tauri.localhost",
"tauri://localhost",
"http://localhost:3000",
@@ -157,7 +160,8 @@ pub fn run() {
#[cfg(target_os = "ios")]
{
builder = builder
- .plugin(tauri_plugin_haptics::init())
+ .plugin(tauri_plugin_auth::init())
+ .plugin(tauri_plugin_virtual_keyboard::init())
.plugin(tauri_plugin_edit_menu::init())
.plugin(tauri_plugin_input_accessory::init())
.plugin(tauri_plugin_network_status::init())
@@ -166,6 +170,11 @@ pub fn run() {
.plugin(tauri_plugin_call_kit::init());
}
+ #[cfg(target_os = "android")]
+ {
+ builder = builder.plugin(tauri_plugin_android_auth::init());
+ }
+
// register the rest of the common plugins
// The log plugin with "tracing" feature emits tracing::event! directly,
// so logs from the webview will go through our tracing subscriber
@@ -211,10 +220,9 @@ pub fn run() {
{
// register mobile specific plugins
builder = builder
+ .plugin(tauri_plugin_haptics::init())
.plugin(tauri_plugin_safe_area_insets::init())
- .plugin(tauri_plugin_notifications::init())
- .plugin(tauri_plugin_virtual_keyboard::init())
- .plugin(tauri_plugin_auth::init());
+ .plugin(tauri_plugin_notifications::init());
}
// Window origin differs by platform:
@@ -445,12 +453,19 @@ enum LaunchState {
}
/// Convert a deep link url into a `navigate` event for the frontend router.
-#[tracing::instrument(err, skip(handle))]
+#[tracing::instrument(err, skip(handle, url))]
fn emit_navigate_for_deep_link(url: Url, handle: &AppHandle) -> Result<(), Report> {
+ // Auth callbacks belong exclusively to the native browser session. They
+ // must not reach SPA routing or application logs, even via an explicit intent.
+ if url.scheme() == APP_SCHEME && url.host_str() == Some("android-auth") {
+ return Ok(());
+ }
// Universal/App links come in as https:// URLs, custom scheme links come in as macro://
let macro_scheme = match url.scheme() {
s if s == APP_SCHEME => MacroScheme::new(url)?,
- "http" | "https" => MacroScheme::from_url(&url)?,
+ "http" | "https" if navigation_plugin::is_app_link(APP_LINK_HOSTS, &url) => {
+ MacroScheme::from_url(&url)?
+ }
scheme => {
return Err(report!("unexpected deep link scheme: {}", scheme));
}
@@ -463,7 +478,6 @@ fn emit_navigate_for_deep_link(url: Url, handle: &AppHandle) -> Result<(), Repor
// we send a navigate event instead of calling navigate directly
// because navigate performs a full browser navigation
- tracing::trace!("{payload:?}");
Ok(handle.emit("navigate", payload)?)
}
@@ -472,7 +486,6 @@ fn attach_deep_link_handler(app: &mut tauri::App) {
let handle = app.handle().clone();
move |ev| {
let urls = ev.urls();
- tracing::trace!("received open url event {urls:?}");
let Some(url) = urls.into_iter().next() else {
tracing::warn!("open url event contained no urls");
return;
@@ -545,7 +558,7 @@ fn flush_launch_deep_link(app: AppHandle, delivery: tauri::State<'_, DeepLinkDel
};
if let Some(url) = to_emit {
- tracing::debug!("flushing deep link {url}");
+ tracing::debug!("flushing launch deep link");
emit_navigate_for_deep_link(url, &app).log_and_consume();
}
}
diff --git a/apps/web/tauri/src-tauri/tauri.android.conf.json b/apps/web/tauri/src-tauri/tauri.android.conf.json
new file mode 100644
index 0000000000..c3a1696a3b
--- /dev/null
+++ b/apps/web/tauri/src-tauri/tauri.android.conf.json
@@ -0,0 +1,26 @@
+{
+ "$schema": "https://schema.tauri.app/config/2",
+ "plugins": {
+ "deep-link": {
+ "mobile": [
+ { "scheme": ["macro"], "host": "app", "appLink": false },
+ { "host": "macro.com", "path": ["/app"], "pathPrefix": ["/app/"] },
+ { "host": "dev.macro.com", "path": ["/app"], "pathPrefix": ["/app/"] },
+ { "host": "staging.macro.com", "path": ["/app"], "pathPrefix": ["/app/"] }
+ ]
+ }
+ },
+ "app": {
+ "windows": [
+ {
+ "title": "Macro",
+ "width": 800,
+ "height": 600,
+ "resizable": true,
+ "fullscreen": false,
+ "backgroundThrottling": "disabled",
+ "useHttpsScheme": true
+ }
+ ]
+ }
+}
diff --git a/docs/AGENT_GUIDE/login.md b/docs/AGENT_GUIDE/login.md
index e55a31576a..5b86e182b0 100644
--- a/docs/AGENT_GUIDE/login.md
+++ b/docs/AGENT_GUIDE/login.md
@@ -18,6 +18,17 @@
failure does not block the remaining content; signup retries repair tags
without resetting task priorities. The guide waits until its tag IDs resolve.
+## Hosted-dev proxy SSO
+
+On an allowed OAuth origin such as `https://localhost:<port>`, Google/SSO
+sign-in navigates the browser to `/__macro_dev/gateway/auth/login/sso` with
+`is_mobile=true` to request the session-code handoff. The `original_url`
+remains the browser destination (including its query and hash). Returning
+from the provider redeems the session code to establish cookies locally.
+This browser flow must not open a native authentication session. Verify the
+redirect separately from provider completion; arbitrary development hostnames
+are not on the hosted OAuth redirect allowlist.
+
## Native iOS 27
The native welcome screen offers `Create new account` and `Log into existing
@@ -37,6 +48,29 @@ Signed universal links and share-sheet flows still need end-to-end verification;
see the [Tauri guide](../../apps/web/tauri/src-tauri/README.md#ios-27-scene-lifecycle)
and [repeatable iOS smoke test](../../apps/web/tests/native/ios/README.md).
+## Native Android
+
+The Android welcome screen also offers `Create new account` and `Log into existing
+account`. Google sign-in opens a system browser Auth Tab; completing or canceling
+returns to Macro. Cancel and retry should open a fresh attempt. Enter provider
+passwords and verification codes only in that browser, never in agent messages.
+For browsers using the Custom Tabs fallback, verify that the callback returns to
+the original Macro task. A callback for another attempt must leave the current
+attempt pending; a callback after process death must not restore that attempt.
+
+After signing in, test background/foreground, force-stop/relaunch, logout, and
+signing in as another account. An entity link opened while signed out should
+remain pending until authentication completes. The destination expires after
+30 minutes and explicit logout clears it. Test both cold and warm delivery;
+forcing an Android intent to Macro proves routing, not verified App Links.
+Root links must preserve query parameters through the welcome or inbox redirect,
+including when Android delivers the link after the session gate mounts. Test
+with a harmless marker query; checkout return parameters can trigger analytics
+and license refreshes and should only be exercised in a checkout test.
+See [Android development](../ANDROID_DEVELOPMENT.md) for build commands and
+certificate-dependent domain verification. Provider completion, account linking,
+and verified links still require end-to-end qualification.
+
## Mailpit (local email)
- UI: `http://localhost:<mailpit-port>/`
diff --git a/docs/ANDROID_DEVELOPMENT.md b/docs/ANDROID_DEVELOPMENT.md
new file mode 100644
index 0000000000..ad99e8511a
--- /dev/null
+++ b/docs/ANDROID_DEVELOPMENT.md
@@ -0,0 +1,217 @@
+# Android development
+
+Macro's Android package is `com.macro.app.prod`. Its Gradle project lives in
+`apps/web/tauri/src-tauri/gen/android`. Keep the project and wrapper in source
+control; do not regenerate them to repair a build error.
+
+## Prerequisites
+
+- Use the repository's Bun version (`packageManager` in the root `package.json`)
+ or a compatible newer version, and confirm `bun --version` in the shell that
+ will run the build. Run `bun install --frozen-lockfile` from the repository root.
+ Older Bun installations can fail to resolve workspace `catalog:` dependencies.
+- Install the Rust toolchain in `rust-toolchain.toml`, `just`, `wasm-pack`, and
+ the Tauri CLI (`cargo tauri`).
+- Install Android SDK Platform **36**, Build Tools 36, Platform Tools, and an
+ Android 16 / API 36 Google Play ARM64 emulator through Android Studio.
+- Install NDK **30.0.16248370**, or set `NDK_HOME` to another intended installed NDK.
+- Use Java **21**. The launcher detects Homebrew's `openjdk@21` on Apple Silicon;
+ otherwise set `JAVA_HOME`. Android Studio's bundled Java may be too new for Gradle.
+- Run `rustup target add aarch64-linux-android`, boot an emulator, and confirm
+ `adb devices -l` lists it as `device`.
+
+The launcher uses `ANDROID_HOME` (default `~/Library/Android/sdk` on macOS,
+`~/Android/Sdk` on Linux), `NDK_HOME`, and `JAVA_HOME` without editing shell profiles.
+
+## Development and builds
+
+From `apps/web`, using an available frontend port:
+
+```sh
+PORT=3004 just android-dev
+just android-build --debug --apk true --aab false
+just android-build --apk true --aab true
+```
+
+Development uses the deployed **dev** backend, builds required WebAssembly assets,
+installs the debug APK, and disables automatic OTA updates. Treat dev data as real.
+Stop the command before starting another native build in this worktree. Additional
+Tauri arguments can select a device or disable watching, e.g. `--no-watch`.
+
+If ADB reconnects and drops the development-server tunnel, an Android emulator
+can reach the host directly at `10.0.2.2`. Use the same port in both places:
+
+```sh
+PORT=3004 just android-dev --no-watch --no-dev-server-wait --config '{"build":{"devUrl":"http://10.0.2.2:3004"}}'
+```
+
+That address is emulator-only; the host-side server check must be skipped.
+
+Build commands embed the production frontend. Outputs are under
+`tauri/src-tauri/gen/android/app/build/outputs/`. The launcher defaults to ARM64.
+Release builds require the signing configuration below and produce signed artifacts.
+
+## Release signing
+
+Obtain the existing upload keystore and signing credentials from the release
+maintainers. Keep them outside the checkout and provision them securely for CI.
+Coordinate key replacement with Play Console; do not generate a new key for
+routine builds.
+
+Gradle reads ignored `tauri/src-tauri/gen/android/keystore.properties`:
+
+```properties
+storeFile=/absolute/path/upload-keystore.jks
+storePassword=YOUR_KEYSTORE_PASSWORD
+keyAlias=upload
+keyPassword=YOUR_KEY_PASSWORD
+```
+
+Restrict the directory to its owner and the keystore/properties files to mode
+`0600`. The properties file can be a symlink to an owner-only file outside the
+checkout. For CI, provision these files from the secret manager before building.
+Missing signing configuration fails a release build; debug builds retain their
+normal debug certificate. No signing secrets belong in Gradle source or logs.
+
+For local qualification of the embedded frontend, disable OTA updates:
+
+```sh
+just android-build --apk true --aab true -- --no-default-features
+```
+
+This still uses production services/Firebase, release optimization, and R8.
+Use a separate emulator for this APK: its certificate differs from the debug
+APK, so it cannot update the existing debug installation. Do not uninstall a
+signed-in development app just to install the release build.
+
+Verify APK signatures with SDK `apksigner verify --verbose --print-certs`, AAB
+signatures with JDK `jarsigner -verify`, and APK native-library alignment with
+`zipalign -c -P 16 4`. Exercise startup, auth, links, and force-stop/relaunch on
+the installed release. OTA-enabled builds and Play-installed upgrades require
+their own qualification; passing this local check does not prove those paths.
+
+The upload certificate identifies locally signed artifacts. When Google creates
+the Play App Signing key, Play-delivered APKs use that separate certificate; add
+its fingerprint to production associations before testing Play-installed links.
+
+## Firebase
+
+Debug builds work without Firebase configuration for auth/navigation development.
+The launcher requires package **com.macro.app.prod** and validates these projects:
+
+| Build command | Firebase 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:
+
+```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.
+
+## Browser authentication
+
+Android uses `android_auth_plugin` and AndroidX Auth Tab, with a Custom Tabs
+fallback. Each attempt creates `macro://android-auth/<random UUID>` before the
+backend creates OAuth state. The receiver checks the exact authority/path;
+mismatched callbacks leave the active attempt pending. Duplicate parameters are
+rejected. The Custom Tabs fallback returns to the task that owns the invocation.
+Canceling settles the request so another attempt can start. Never log callback
+URLs or session codes.
+Android navigation uses `macro://app/<route>`; its MainActivity filter is scoped
+to host `app` so older browsers send `macro://android-auth/...` exclusively to
+the authentication receiver, without an activity chooser.
+
+Login redeems a one-time code using the existing native HTTP cookie jar.
+Gmail/calendar/GitHub linking completes server-side and refreshes queries without
+replacing the Macro session. After process death mid-flow, restart authentication;
+orphaned callbacks must not silently log in the replacement process. Macro logout
+does not sign out of Google/GitHub in the system browser.
+
+## App Links
+
+App Links require a domain association for `com.macro.app.prod` and the certificate
+that signed the installed APK. From `apps/web`, generate a candidate association:
+
+```sh
+bun scripts/android-assetlinks.ts 'AA:BB:...32-byte-SHA256-fingerprint...'
+```
+
+Publish the resulting JSON at `https://<host>/.well-known/assetlinks.json` for each
+intended host: `macro.com`, `dev.macro.com`, `staging.macro.com`. This repository
+does not automatically publish the source file to those domain roots. Production needs
+the **Play App Signing** fingerprint, not merely the upload key; keep debug
+certificates on the development host. Builds do not publish domain associations.
+
+Google's Digital Asset Links service caches association results separately from
+the hosting CDN. A freshly published file can be correct while Android still reports
+the previous result; wait for the service's reported cache lifetime before
+re-verifying. Do not force a domain to `approved` or `verified` to claim success.
+
+After installing an APK signed with an associated certificate:
+
+```sh
+adb shell pm verify-app-links --re-verify com.macro.app.prod
+adb shell pm get-app-links com.macro.app.prod
+adb shell am start -W -a android.intent.action.VIEW -c android.intent.category.DEFAULT -c android.intent.category.BROWSABLE -d 'https://dev.macro.com/app/task/TASK_ID'
+```
+
+Adding `-p com.macro.app.prod` tests routing but does not prove domain verification.
+Test cold/warm links, auth cancellation/retry, email-code login, relaunch with a
+session, logout/account switching, and entity links through login. Repeat with
+signed release builds and actual provider sign-in.
+
+### Publishing associations
+
+Publication procedure for the hosting owner:
+
+1. Recheck the chosen hostname's DNS, valid HTTPS certificate, CDN aliases and
+ `/.well-known/*` origin. Confirm the endpoint returns HTTP 200 with JSON
+ directly, without a redirect or an HTML fallback.
+2. Obtain the SHA-256 **app-signing** fingerprint from Play Console for
+ `com.macro.app.prod`. The upload certificate is only suitable for testing
+ locally signed builds. If staging is used for such a test, explicitly select
+ the local-release certificate; keep debug certificates confined to dev.
+3. Download and retain the existing association JSON, S3 ETag and object metadata.
+ Generate the candidate Macro statement from `apps/web`:
+
+ ```sh
+ bun scripts/android-assetlinks.ts 'PLAY_APP_SIGNING_SHA256' > /tmp/macro-assetlinks-candidate.json
+ ```
+
+ Replace the placeholder with the actual 32-byte colon-separated fingerprint.
+ Merge the generated statement into the downloaded array, preserving unrelated
+ packages, relations and any still-required certificates. The generated file is
+ a candidate statement, not a replacement for the full live object. Removing
+ legacy associations requires a separate ownership/usage check.
+4. Review the merged JSON for the exact package, certificate and
+ `delegate_permission/common.handle_all_urls` relation. Upload only the chosen
+ `.well-known/assetlinks.json` object, using `Content-Type: application/json`,
+ a short cache lifetime (e.g. `max-age=300`) and `--if-match` with its prior ETag.
+ If the ETag changed, fetch and merge again instead of overwriting new content.
+5. Invalidate only `/.well-known/assetlinks.json` on that host's distribution.
+ Fetch the public URL again, confirm the intended JSON and preservation of old
+ entries, and check Google's Digital Asset Links result for the exact
+ host/package/certificate. Allow its independent cache to expire as necessary.
+6. Install the appropriate signed build. Run the verification commands above and
+ require `verified` for each intended host. Test natural cold/warm links with
+ both DEFAULT and BROWSABLE categories, without a package override or forced
+ approval. Exercise an entity link while signed in and through a login detour,
+ including query preservation. Repeat with a Play-installed build when
+ validating the Play App Signing certificate.
+7. Record the artifact certificate, host, served JSON, verification result and
+ route result. If rollback is needed, restore the saved JSON and metadata with
+ a conditional write against the published ETag, then invalidate the same URL.
+ Reconcile concurrent edits before restoring anything.