Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(auth): allow Android passkey origins (#19640)

Tsuki5c12148b8eb7
diff --git a/src/libs/better-auth/define-config.test.ts b/src/libs/better-auth/define-config.test.ts
index 56d3c5fba9b..8f57518170b 100644
--- a/src/libs/better-auth/define-config.test.ts
+++ b/src/libs/better-auth/define-config.test.ts
@@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => {
EnvHttpProxyAgent: vi.fn(function (options) {
return { options };
}),
+ passkey: vi.fn(() => ({ id: 'passkey' })),
serverDB: {},
setGlobalDispatcher: vi.fn(),
};
@@ -21,7 +22,7 @@ vi.mock('@better-auth/expo', () => ({
}));
vi.mock('@better-auth/passkey', () => ({
- passkey: vi.fn(() => ({ id: 'passkey' })),
+ passkey: mocks.passkey,
}));
vi.mock('@lobechat/database', () => ({
@@ -97,6 +98,7 @@ vi.mock('@/libs/better-auth/sso', () => ({
vi.mock('@/libs/better-auth/utils/config', () => ({
createSecondaryStorage: vi.fn(() => ({ id: 'secondary-storage' })),
+ getPasskeyOrigins: vi.fn(() => ['https://example.com']),
getTrustedOrigins: vi.fn(() => ['https://example.com']),
}));
@@ -144,6 +146,20 @@ describe('defineConfig', () => {
process.env = originalEnv;
});
+ it('should configure passkeys with the approved origins', async () => {
+ const { defineConfig } = await import('./define-config');
+
+ defineConfig({ plugins: [] });
+
+ expect(mocks.passkey).toHaveBeenCalledWith(
+ expect.objectContaining({
+ origin: ['https://example.com'],
+ rpID: 'example.com',
+ rpName: 'LobeHub',
+ }),
+ );
+ });
+
it('should revoke existing sessions after password reset by default', async () => {
const { defineConfig } = await import('./define-config');
diff --git a/src/libs/better-auth/define-config.ts b/src/libs/better-auth/define-config.ts
index b5005dc988a..1f531f246fd 100644
--- a/src/libs/better-auth/define-config.ts
+++ b/src/libs/better-auth/define-config.ts
@@ -22,7 +22,11 @@ import {
} from '@/libs/better-auth/email-templates';
import { emailWhitelist } from '@/libs/better-auth/plugins/email-whitelist';
import { initBetterAuthSSOProviders } from '@/libs/better-auth/sso';
-import { createSecondaryStorage, getTrustedOrigins } from '@/libs/better-auth/utils/config';
+import {
+ createSecondaryStorage,
+ getPasskeyOrigins,
+ getTrustedOrigins,
+} from '@/libs/better-auth/utils/config';
import { expireLegacyHostOnlyCookies } from '@/libs/better-auth/utils/host-only-cookies';
import { parseSSOProviders } from '@/libs/better-auth/utils/server';
import { clearMismatchedOIDCSession } from '@/libs/oidc-provider/session-cleanup';
@@ -83,18 +87,6 @@ const getPasskeyRpID = (): string | undefined => {
}
};
-/**
- * Get passkey origins array.
- * Returns undefined if APP_URL is not set (e.g., in e2e tests).
- */
-const getPasskeyOrigins = (): string[] | undefined => {
- if (!appEnv.APP_URL) return undefined;
- try {
- return [new URL(appEnv.APP_URL).origin];
- } catch {
- return undefined;
- }
-};
/**
* Browsers silently drop a cookie whose `Domain` the current host is not a member of.
* Applying a production domain on a preview deployment (`*.vercel.app`) or localhost would
@@ -356,9 +348,7 @@ export function defineConfig(customOptions: CustomBetterAuthOptions) {
// Extract rpID from auth URL (e.g., 'lobehub.com' from 'https://lobehub.com')
// Returns undefined if AUTH_URL is not set (e.g., in e2e tests)
rpID: getPasskeyRpID(),
- // Support multiple origins: web + Android APK key hashes
- // Android origin format: android:apk-key-hash:<base64url-sha256-fingerprint>
- // Returns undefined if AUTH_URL is not set (e.g., in e2e tests)
+ // Keep Android APK origins aligned with the public Digital Asset Links declaration.
origin: getPasskeyOrigins(),
}),
...(genericOAuthProviders.length > 0
diff --git a/src/libs/better-auth/utils/config.test.ts b/src/libs/better-auth/utils/config.test.ts
index b5233a794c5..54ff67097c2 100644
--- a/src/libs/better-auth/utils/config.test.ts
+++ b/src/libs/better-auth/utils/config.test.ts
@@ -59,3 +59,28 @@ describe('getTrustedOrigins', () => {
]);
});
});
+
+describe('getPasskeyOrigins', () => {
+ beforeEach(() => {
+ mocks.appEnv.APP_URL = 'https://app.example.com';
+ });
+
+ it('should trust the web app and Android certificates authorized for login credentials', async () => {
+ const { getPasskeyOrigins } = await import('./config');
+
+ expect(getPasskeyOrigins()).toEqual([
+ 'https://app.example.com',
+ 'android:apk-key-hash:11Tbo3jVi48gAe17mxjTsFvRIqqXK1nhpo4xJCFEDSs',
+ 'android:apk-key-hash:-sYXRdwJA3hvue3mKpYrOZ9zSPC7b4mbgzJmdZEDO5w',
+ 'android:apk-key-hash:GyE4XXJAZfUWIB3J0msEY8Mz8ZeragZmDj7wfmCCfuc',
+ 'android:apk-key-hash:G77UoK5DVuVYAXTEuaALDlq5Xg-pwGUYaM8fqj6PT9s',
+ ]);
+ });
+
+ it('should preserve inferred origins when the web app URL is unavailable', async () => {
+ mocks.appEnv.APP_URL = '';
+ const { getPasskeyOrigins } = await import('./config');
+
+ expect(getPasskeyOrigins()).toBeUndefined();
+ });
+});
diff --git a/src/libs/better-auth/utils/config.ts b/src/libs/better-auth/utils/config.ts
index 7a41a9b2e83..71c1b18f957 100644
--- a/src/libs/better-auth/utils/config.ts
+++ b/src/libs/better-auth/utils/config.ts
@@ -1,3 +1,4 @@
+import assetLinks from '@/../public/.well-known/assetlinks.json';
import { appEnv } from '@/envs/app';
import { authEnv } from '@/envs/auth';
import { getRedisConfig } from '@/envs/redis';
@@ -5,6 +6,8 @@ import { initializeRedis, isRedisEnabled } from '@/libs/redis';
import { isDev } from '@/utils/env';
const APPLE_TRUSTED_ORIGIN = 'https://appleid.apple.com';
+const ANDROID_APP_NAMESPACE = 'android_app';
+const ANDROID_PASSKEY_RELATION = 'delegate_permission/common.get_login_creds';
const MOBILE_APP_SCHEME = 'com.lobehub.app://';
const EXPO_DEV_SCHEME = 'exp://*/*';
@@ -35,12 +38,48 @@ const parseTrustedOrigins = (value?: string) =>
.map((item) => normalizeOrigin(item.trim()))
.filter((origin): origin is string => Boolean(origin));
-const mergeTrustedOrigins = (...originGroups: Array<string[] | undefined>) => {
+const mergeOrigins = (...originGroups: Array<string[] | undefined>) => {
const mergedOrigins = new Set(originGroups.flatMap((origins) => origins ?? []));
return mergedOrigins.size > 0 ? Array.from(mergedOrigins) : undefined;
};
+const fingerprintToAndroidOrigin = (fingerprint: string) => {
+ const hex = fingerprint.replaceAll(':', '');
+ if (!/^[\dA-F]{64}$/i.test(hex)) return undefined;
+
+ return `android:apk-key-hash:${Buffer.from(hex, 'hex').toString('base64url')}`;
+};
+
+const getAndroidPasskeyOrigins = () =>
+ assetLinks.flatMap(({ relation, target }) => {
+ if (
+ target.namespace !== ANDROID_APP_NAMESPACE ||
+ !relation.includes(ANDROID_PASSKEY_RELATION)
+ ) {
+ return [];
+ }
+
+ return target.sha256_cert_fingerprints
+ .map(fingerprintToAndroidOrigin)
+ .filter((origin): origin is string => Boolean(origin));
+ });
+
+/**
+ * Build the exact WebAuthn origins accepted by the passkey plugin.
+ *
+ * Android Credential Manager derives its origin from the APK signing certificate. The public
+ * Digital Asset Links file is already the source of truth for certificates authorized to use
+ * LobeHub credentials, so keep Better Auth's allowlist in sync with it instead of duplicating
+ * hashes in deployment configuration.
+ */
+export const getPasskeyOrigins = () => {
+ const webOrigin = normalizeOrigin(appEnv.APP_URL);
+ if (!webOrigin) return undefined;
+
+ return mergeOrigins([webOrigin], getAndroidPasskeyOrigins());
+};
+
/**
* Build trusted origins with Vercel-aware defaults and optional additions.
* AUTH_TRUSTED_ORIGINS keeps its replacement semantics, while
@@ -51,7 +90,7 @@ export const getTrustedOrigins = (enabledSSOProviders: string[]) => {
const originsFromEnv = parseTrustedOrigins(authEnv.AUTH_TRUSTED_ORIGINS);
if (originsFromEnv?.length) {
- return mergeTrustedOrigins(originsFromEnv, additionalOrigins);
+ return mergeOrigins(originsFromEnv, additionalOrigins);
}
const defaults = [
@@ -67,7 +106,7 @@ export const getTrustedOrigins = (enabledSSOProviders: string[]) => {
? [APPLE_TRUSTED_ORIGIN]
: undefined;
- return mergeTrustedOrigins(defaults, providerOrigins, additionalOrigins);
+ return mergeOrigins(defaults, providerOrigins, additionalOrigins);
};
/**