Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(mobile): add server URL validation (#835)

Corentin Thomasseta754c68a114c
diff --git a/apps/mobile/src/modules/app/app.constants.ts b/apps/mobile/src/modules/app/app.constants.ts
new file mode 100644
index 00000000..1f2f4efe
--- /dev/null
+++ b/apps/mobile/src/modules/app/app.constants.ts
@@ -0,0 +1,3 @@
+import Constants from 'expo-constants';
+
+export const APP_SCHEME = String(Constants.expoConfig?.scheme ?? 'papra');
diff --git a/apps/mobile/src/modules/auth/auth.client.ts b/apps/mobile/src/modules/auth/auth.client.ts
index ad7dede3..b0c45b5c 100644
--- a/apps/mobile/src/modules/auth/auth.client.ts
+++ b/apps/mobile/src/modules/auth/auth.client.ts
@@ -1,8 +1,8 @@
import { expoClient } from '@better-auth/expo/client';
import { createAuthClient as createBetterAuthClient } from 'better-auth/react';
-import Constants from 'expo-constants';
import * as SecureStore from 'expo-secure-store';
import { Platform } from 'react-native';
+import { APP_SCHEME } from '../app/app.constants';
export type AuthClient = ReturnType<typeof createAuthClient>;
@@ -11,8 +11,8 @@ export function createAuthClient({ baseUrl}: { baseUrl: string }) {
baseURL: baseUrl,
plugins: [
expoClient({
- scheme: String(Constants.expoConfig?.scheme ?? 'papra'),
- storagePrefix: String(Constants.expoConfig?.scheme ?? 'papra'),
+ scheme: APP_SCHEME,
+ storagePrefix: APP_SCHEME,
storage: Platform.OS === 'web'
? localStorage
: SecureStore,
diff --git a/apps/mobile/src/modules/auth/auth.models.test.ts b/apps/mobile/src/modules/auth/auth.models.test.ts
new file mode 100644
index 00000000..0c0e1a6e
--- /dev/null
+++ b/apps/mobile/src/modules/auth/auth.models.test.ts
@@ -0,0 +1,76 @@
+import type { ServerConfig } from '../config/config.types';
+import { describe, expect, test } from 'vitest';
+import { getEnabledOAuthProviders } from './auth.models';
+
+describe('auth models', () => {
+ describe('getEnabledOAuthProviders', () => {
+ test('build an ordered list of enabled OAuth providers', () => {
+ expect(
+ getEnabledOAuthProviders({ serverConfig: {
+ auth: {
+ providers: {
+ google: { isEnabled: true },
+ github: { isEnabled: true },
+ customs: [
+ { providerId: 'custom1', providerName: 'Custom 1' },
+ ],
+ },
+ },
+ } as ServerConfig }),
+ ).to.eql([
+ { providerId: 'google', providerName: 'Google' },
+ { providerId: 'github', providerName: 'GitHub' },
+ { providerId: 'custom1', providerName: 'Custom 1' },
+ ]);
+
+ expect(
+ getEnabledOAuthProviders({ serverConfig: {
+ auth: {
+ providers: {
+ google: { isEnabled: true },
+ github: { isEnabled: false },
+ customs: [
+ { providerId: 'custom1', providerName: 'Custom 1' },
+ ],
+ },
+ },
+ } as ServerConfig }),
+ ).to.eql([
+ { providerId: 'google', providerName: 'Google' },
+ { providerId: 'custom1', providerName: 'Custom 1' },
+ ]);
+
+ expect(
+ getEnabledOAuthProviders({ serverConfig: {
+ auth: {
+ providers: {
+ google: { isEnabled: false },
+ github: { isEnabled: false },
+ customs: [
+ { providerId: 'custom1', providerName: 'Custom 1' },
+ ],
+ },
+ },
+ } as ServerConfig }),
+ ).to.eql([
+ { providerId: 'custom1', providerName: 'Custom 1' },
+ ]);
+
+ expect(
+ getEnabledOAuthProviders({ serverConfig: {
+ auth: {
+ providers: {
+ google: { isEnabled: false },
+ github: { isEnabled: false },
+ customs: [] as { providerId: string; providerName: string }[],
+ },
+ },
+ } as ServerConfig }),
+ ).to.eql([]);
+ });
+
+ test('returns an empty array if serverConfig is undefined, like during initial loading', () => {
+ expect(getEnabledOAuthProviders({ serverConfig: undefined })).to.eql([]);
+ });
+ });
+});
diff --git a/apps/mobile/src/modules/auth/auth.models.ts b/apps/mobile/src/modules/auth/auth.models.ts
new file mode 100644
index 00000000..8cab542b
--- /dev/null
+++ b/apps/mobile/src/modules/auth/auth.models.ts
@@ -0,0 +1,15 @@
+import type { ServerConfig } from '../config/config.types';
+
+export function getEnabledOAuthProviders({ serverConfig }: { serverConfig?: ServerConfig }) {
+ if (!serverConfig) {
+ return [];
+ }
+
+ const providers = serverConfig.auth.providers;
+
+ return [
+ ...(providers.google.isEnabled ? [{ providerId: 'google', providerName: 'Google' }] : []),
+ ...(providers.github.isEnabled ? [{ providerId: 'github', providerName: 'GitHub' }] : []),
+ ...providers.customs,
+ ];
+}
diff --git a/apps/mobile/src/modules/auth/screens/login.screen.tsx b/apps/mobile/src/modules/auth/screens/login.screen.tsx
index 89973e90..ddec0473 100644
--- a/apps/mobile/src/modules/auth/screens/login.screen.tsx
+++ b/apps/mobile/src/modules/auth/screens/login.screen.tsx
@@ -19,6 +19,7 @@ import { useAuthClient } from '@/modules/api/providers/api.provider';
import { useAlert } from '@/modules/ui/providers/alert-provider';
import { useThemeColor } from '@/modules/ui/providers/use-theme-color';
import { useServerConfig } from '../../config/hooks/use-server-config';
+import { getEnabledOAuthProviders } from '../auth.models';
import { BackToServerSelectionButton } from '../components/back-to-server-selection';
const loginSchema = v.object({
@@ -34,7 +35,7 @@ export function LoginScreen() {
const insets = useSafeAreaInsets();
const [isSubmitting, setIsSubmitting] = useState(false);
- const { data: serverConfig, isLoading: isLoadingConfig } = useServerConfig();
+ const { serverConfig, isLoading: isConfigLoading } = useServerConfig();
const form = useForm({
defaultValues: {
@@ -80,15 +81,14 @@ export function LoginScreen() {
}
};
- const authConfig = serverConfig?.config?.auth;
+ const authConfig = serverConfig?.auth;
const isEmailEnabled = authConfig?.providers?.email?.isEnabled ?? false;
- const isGoogleEnabled = authConfig?.providers?.google?.isEnabled ?? false;
- const isGithubEnabled = authConfig?.providers?.github?.isEnabled ?? false;
- const customProviders = authConfig?.providers?.customs ?? [];
+
+ const oauthProviders = getEnabledOAuthProviders({ serverConfig });
const styles = createStyles({ themeColors });
- if (isLoadingConfig) {
+ if (isConfigLoading) {
return (
<View style={[styles.container, styles.centerContent]}>
<ActivityIndicator size="large" color={themeColors.primary} />
@@ -168,7 +168,7 @@ export function LoginScreen() {
</View>
)}
- {(isGoogleEnabled || isGithubEnabled || customProviders.length > 0) && (
+ {(oauthProviders.length > 0) && (
<>
{isEmailEnabled && (
<View style={styles.divider}>
@@ -179,25 +179,7 @@ export function LoginScreen() {
)}
<View style={styles.socialButtons}>
- {isGoogleEnabled && (
- <TouchableOpacity
- style={styles.socialButton}
- onPress={async () => handleSocialSignIn('google')}
- >
- <Text style={styles.socialButtonText}>Continue with Google</Text>
- </TouchableOpacity>
- )}
-
- {isGithubEnabled && (
- <TouchableOpacity
- style={styles.socialButton}
- onPress={async () => handleSocialSignIn('github')}
- >
- <Text style={styles.socialButtonText}>Continue with GitHub</Text>
- </TouchableOpacity>
- )}
-
- {customProviders.map(provider => (
+ {oauthProviders.map(provider => (
<TouchableOpacity
key={provider.providerId}
style={styles.socialButton}
diff --git a/apps/mobile/src/modules/auth/screens/signup.screen.tsx b/apps/mobile/src/modules/auth/screens/signup.screen.tsx
index d0a6f17d..8a3e45d1 100644
--- a/apps/mobile/src/modules/auth/screens/signup.screen.tsx
+++ b/apps/mobile/src/modules/auth/screens/signup.screen.tsx
@@ -35,7 +35,7 @@ export function SignupScreen() {
const insets = useSafeAreaInsets();
const [isSubmitting, setIsSubmitting] = useState(false);
- const { data: serverConfig, isLoading: isLoadingConfig } = useServerConfig();
+ const { serverConfig, isLoading: isConfigLoading } = useServerConfig();
const form = useForm({
defaultValues: {
@@ -53,7 +53,7 @@ export function SignupScreen() {
await authClient.signUp.email({ name, email, password });
- const isEmailVerificationRequired = serverConfig?.config?.auth?.isEmailVerificationRequired ?? false;
+ const isEmailVerificationRequired = serverConfig?.auth?.isEmailVerificationRequired ?? false;
if (isEmailVerificationRequired) {
showAlert({
@@ -75,12 +75,12 @@ export function SignupScreen() {
},
});
- const authConfig = serverConfig?.config?.auth;
+ const authConfig = serverConfig?.auth;
const isRegistrationEnabled = authConfig?.isRegistrationEnabled ?? false;
const styles = createStyles({ themeColors });
- if (isLoadingConfig) {
+ if (isConfigLoading) {
return (
<View style={[styles.container, styles.centerContent]}>
<ActivityIndicator size="large" color={themeColors.primary} />
diff --git a/apps/mobile/src/modules/config/config.models.test.ts b/apps/mobile/src/modules/config/config.models.test.ts
new file mode 100644
index 00000000..332b99c0
--- /dev/null
+++ b/apps/mobile/src/modules/config/config.models.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, test } from 'vitest';
+import { validateServerUrl } from './config.models';
+
+describe('config models', () => {
+ describe('validateServerUrl', () => {
+ test('non-url are rejected', () => {
+ expect(() => validateServerUrl({ url: 'not-a-url' })).toThrow();
+ expect(() => validateServerUrl({ url: '' })).toThrow();
+ });
+
+ test('urls are trimmed', () => {
+ expect(validateServerUrl({ url: ' https://example.com ' })).to.eql('https://example.com');
+ });
+
+ test('if the url ends with a /api it is removed', () => {
+ expect(validateServerUrl({ url: 'https://example.com/api' })).to.eql('https://example.com');
+ expect(validateServerUrl({ url: 'https://example.com/api/' })).to.eql('https://example.com');
+ expect(validateServerUrl({ url: 'https://example.com/papra/api/' })).to.eql('https://example.com/papra');
+ expect(validateServerUrl({ url: 'https://example.com/papi' })).to.eql('https://example.com/papi');
+ });
+
+ test('protocol must be present', () => {
+ expect(() => validateServerUrl({ url: 'example.com' })).toThrow();
+ expect(() => validateServerUrl({ url: '192.168.0.0' })).toThrow();
+ });
+
+ test('standard urls are returned as-is', () => {
+ expect(validateServerUrl({ url: 'https://example.com' })).to.eql('https://example.com');
+ expect(validateServerUrl({ url: 'https://example.com/' })).to.eql('https://example.com/');
+ expect(validateServerUrl({ url: 'http://example.com' })).to.eql('http://example.com');
+ expect(validateServerUrl({ url: 'https://192.168.0.0' })).to.eql('https://192.168.0.0');
+ expect(validateServerUrl({ url: 'https://sub.domain.example.com' })).to.eql('https://sub.domain.example.com');
+ expect(validateServerUrl({ url: 'https://example.com:8080' })).to.eql('https://example.com:8080');
+ expect(validateServerUrl({ url: 'https://example.com/papra' })).to.eql('https://example.com/papra');
+ });
+ });
+});
diff --git a/apps/mobile/src/modules/config/config.models.ts b/apps/mobile/src/modules/config/config.models.ts
new file mode 100644
index 00000000..0706a5d5
--- /dev/null
+++ b/apps/mobile/src/modules/config/config.models.ts
@@ -0,0 +1,12 @@
+import * as v from 'valibot';
+
+const urlSchema = v.pipe(
+ v.string(),
+ v.trim(),
+ v.url(),
+ v.transform(url => url.replace(/\/api\/?$/, '')),
+);
+
+export function validateServerUrl({ url }: { url: string }) {
+ return v.parse(urlSchema, url);
+}
diff --git a/apps/mobile/src/modules/config/config.services.ts b/apps/mobile/src/modules/config/config.services.ts
index 24bb87d6..cb8afa2c 100644
--- a/apps/mobile/src/modules/config/config.services.ts
+++ b/apps/mobile/src/modules/config/config.services.ts
@@ -1,31 +1,10 @@
import type { ApiClient } from '../api/api.client';
+import type { ServerConfig } from './config.types';
import { httpClient } from '../api/http.client';
export async function fetchServerConfig({ apiClient}: { apiClient: ApiClient }) {
return apiClient<{
- config: {
- auth: {
- isEmailVerificationRequired: boolean;
- isPasswordResetEnabled: boolean;
- isRegistrationEnabled: boolean;
- showLegalLinksOnAuthPage: boolean;
- providers: {
- email: {
- isEnabled: boolean;
- };
- github: {
- isEnabled: boolean;
- };
- google: {
- isEnabled: boolean;
- };
- customs: {
- providerId: string;
- providerName: string;
- }[];
- };
- };
- };
+ config: ServerConfig;
}>({
path: '/api/config',
});
diff --git a/apps/mobile/src/modules/config/config.types.ts b/apps/mobile/src/modules/config/config.types.ts
new file mode 100644
index 00000000..0292b0cb
--- /dev/null
+++ b/apps/mobile/src/modules/config/config.types.ts
@@ -0,0 +1,23 @@
+export type ServerConfig = {
+ auth: {
+ isEmailVerificationRequired: boolean;
+ isPasswordResetEnabled: boolean;
+ isRegistrationEnabled: boolean;
+ showLegalLinksOnAuthPage: boolean;
+ providers: {
+ email: {
+ isEnabled: boolean;
+ };
+ github: {
+ isEnabled: boolean;
+ };
+ google: {
+ isEnabled: boolean;
+ };
+ customs: {
+ providerId: string;
+ providerName: string;
+ }[];
+ };
+ };
+};
diff --git a/apps/mobile/src/modules/config/hooks/use-server-config.ts b/apps/mobile/src/modules/config/hooks/use-server-config.ts
index 85c787d7..48b529de 100644
--- a/apps/mobile/src/modules/config/hooks/use-server-config.ts
+++ b/apps/mobile/src/modules/config/hooks/use-server-config.ts
@@ -5,8 +5,13 @@ import { fetchServerConfig } from '../config.services';
export function useServerConfig() {
const apiClient = useApiClient();
- return useQuery({
+ const query = useQuery({
queryKey: ['server', 'config'],
queryFn: async () => fetchServerConfig({ apiClient }),
});
+
+ return {
+ ...query,
+ serverConfig: query.data?.config,
+ };
}
diff --git a/apps/mobile/src/modules/config/screens/server-selection.screen.tsx b/apps/mobile/src/modules/config/screens/server-selection.screen.tsx
index 557d78fa..115130ee 100644
--- a/apps/mobile/src/modules/config/screens/server-selection.screen.tsx
+++ b/apps/mobile/src/modules/config/screens/server-selection.screen.tsx
@@ -1,4 +1,5 @@
import type { ThemeColors } from '@/modules/ui/theme.constants';
+import { safelySync } from '@corentinth/chisels';
import { useRouter } from 'expo-router';
import { useState } from 'react';
import {
@@ -17,6 +18,7 @@ import { useAlert } from '@/modules/ui/providers/alert-provider';
import { useThemeColor } from '@/modules/ui/providers/use-theme-color';
import { MANAGED_SERVER_URL } from '../config.constants';
import { configLocalStorage } from '../config.local-storage';
+import { validateServerUrl } from '../config.models';
import { pingServer } from '../config.services';
function getDefaultCustomServerUrl() {
@@ -38,8 +40,20 @@ export function ServerSelectionScreen() {
const [customUrl, setCustomUrl] = useState(getDefaultCustomServerUrl());
const [isValidating, setIsValidating] = useState(false);
- const handleValidateCustomUrl = async ({ url}: { url: string }) => {
+ const handleValidateCustomUrl = async ({ url: rawUrl }: { url: string }) => {
setIsValidating(true);
+
+ const [url, urlValidationError] = safelySync(() => validateServerUrl({ url: rawUrl }));
+
+ if (urlValidationError) {
+ showAlert({
+ title: 'Invalid URL',
+ message: 'Please enter a valid server URL. Make sure to include the protocol (http:// or https://).',
+ });
+ setIsValidating(false);
+ return;
+ }
+
try {
await pingServer({ url });
await configLocalStorage.setApiServerBaseUrl({ apiServerBaseUrl: url });
@@ -108,7 +122,7 @@ export function ServerSelectionScreen() {
>
{isValidating
? (
- <ActivityIndicator color="#fff" />
+ <ActivityIndicator color={themeColors.primaryForeground} />
)
: (
<Text style={styles.buttonText}>Continue with Managed</Text>
@@ -137,7 +151,7 @@ export function ServerSelectionScreen() {
>
{isValidating
? (
- <ActivityIndicator color="#fff" />
+ <ActivityIndicator color={themeColors.primaryForeground} />
)
: (
<Text style={styles.buttonText}>Connect</Text>