Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(mobile): add custom headers support (#1367)

Corentin Thomasset6d77043e7cb9
diff --git a/apps/mobile/app/index.tsx b/apps/mobile/app/index.tsx
index 0151cb5f..06a80fd8 100644
--- a/apps/mobile/app/index.tsx
+++ b/apps/mobile/app/index.tsx
@@ -1,7 +1,7 @@
import { useQuery } from '@tanstack/react-query';
import { Redirect } from 'expo-router';
import { createAuthClient } from '@/modules/auth/auth.client';
-import { configLocalStorage } from '@/modules/config/config.local-storage';
+import { configQueryOptions } from '@/modules/config/config.queries';
if (__DEV__) {
// eslint-disable-next-line ts/no-require-imports
@@ -9,10 +9,7 @@ if (__DEV__) {
}
export default function Index() {
- const query = useQuery({
- queryKey: ['api-server-url'],
- queryFn: configLocalStorage.getApiServerBaseUrl,
- });
+ const query = useQuery(configQueryOptions);
const getRedirection = () => {
if (query.isLoading) {
@@ -23,7 +20,7 @@ export default function Index() {
return <Redirect href="/config/server-selection" />;
}
- const authClient = createAuthClient({ baseUrl: query.data });
+ const authClient = createAuthClient(query.data);
if (authClient.getCookie()) {
return <Redirect href="/(app)/(with-organizations)/(tabs)/list" />;
}
diff --git a/apps/mobile/src/modules/api/api.client.ts b/apps/mobile/src/modules/api/api.client.ts
index 87ca7659..e24a731b 100644
--- a/apps/mobile/src/modules/api/api.client.ts
+++ b/apps/mobile/src/modules/api/api.client.ts
@@ -8,9 +8,11 @@ export type ApiClient = ReturnType<typeof createApiClient>;
export function createApiClient({
baseUrl,
getAuthCookie,
+ customHeaders = {},
}: {
baseUrl: string;
getAuthCookie: () => string;
+ customHeaders?: Record<string, string>;
}) {
return async <T, R extends ResponseType = 'json'>({
path,
@@ -21,6 +23,7 @@ export function createApiClient({
url: path,
credentials: Platform.OS === 'web' ? 'include' : 'omit',
headers: {
+ ...customHeaders,
...(Platform.OS === 'web'
? {}
: {
diff --git a/apps/mobile/src/modules/api/providers/api.provider.tsx b/apps/mobile/src/modules/api/providers/api.provider.tsx
index e55210aa..b40db2d4 100644
--- a/apps/mobile/src/modules/api/providers/api.provider.tsx
+++ b/apps/mobile/src/modules/api/providers/api.provider.tsx
@@ -5,7 +5,7 @@ import { useQuery } from '@tanstack/react-query';
import { createContext, useContext, useEffect, useState } from 'react';
import { createApiClient } from '@/modules/api/api.client';
import { createAuthClient } from '@/modules/auth/auth.client';
-import { configLocalStorage } from '@/modules/config/config.local-storage';
+import { configQueryOptions } from '@/modules/config/config.queries';
type ApiProviderProps = {
children: ReactNode;
@@ -18,22 +18,25 @@ export function ApiProvider({ children }: ApiProviderProps) {
const [authClient, setAuthClient] = useState<AuthClient | undefined>(undefined);
const [apiClient, setApiClient] = useState<ApiClient | undefined>(undefined);
- const { data: baseUrl } = useQuery({
- queryKey: ['api-server-url'],
- queryFn: configLocalStorage.getApiServerBaseUrl,
- });
+ const { data: apiServerConfig } = useQuery(configQueryOptions);
useEffect(() => {
- if (baseUrl == null) {
+ if (apiServerConfig == null) {
return;
}
- const authClient = createAuthClient({ baseUrl });
+ const { baseUrl, customHeaders } = apiServerConfig;
+
+ const authClient = createAuthClient({ baseUrl, customHeaders });
setAuthClient(() => authClient);
- const apiClient = createApiClient({ baseUrl, getAuthCookie: () => authClient.getCookie() });
+ const apiClient = createApiClient({
+ baseUrl,
+ customHeaders,
+ getAuthCookie: () => authClient.getCookie(),
+ });
setApiClient(() => apiClient);
- }, [baseUrl]);
+ }, [apiServerConfig]);
return (
<>
diff --git a/apps/mobile/src/modules/auth/auth.client.ts b/apps/mobile/src/modules/auth/auth.client.ts
index bf76dd74..dcb47f5a 100644
--- a/apps/mobile/src/modules/auth/auth.client.ts
+++ b/apps/mobile/src/modules/auth/auth.client.ts
@@ -7,9 +7,18 @@ import { APP_SCHEME } from '../app/app.constants';
export type AuthClient = ReturnType<typeof createAuthClient>;
-export function createAuthClient({ baseUrl }: { baseUrl: string }) {
+export function createAuthClient({
+ baseUrl,
+ customHeaders = {},
+}: {
+ baseUrl: string;
+ customHeaders?: Record<string, string>;
+}) {
return createBetterAuthClient({
baseURL: baseUrl,
+ fetchOptions: {
+ headers: customHeaders,
+ },
plugins: [
twoFactorClient(),
expoClient({
diff --git a/apps/mobile/src/modules/config/config.local-storage.ts b/apps/mobile/src/modules/config/config.local-storage.ts
index 5f974ee8..5e7b20a3 100644
--- a/apps/mobile/src/modules/config/config.local-storage.ts
+++ b/apps/mobile/src/modules/config/config.local-storage.ts
@@ -1,10 +1,33 @@
+import type { ApiServerConfig } from './config.models';
+import { safelySync } from '@corentinth/chisels';
import { buildStorageKey } from '../lib/local-storage/local-storage.models';
-import { storage } from '../lib/local-storage/local-storage.services';
+import { parseApiServerConfig } from './config.models';
+import * as secureStore from 'expo-secure-store';
-const CONFIG_API_SERVER_URL_KEY = buildStorageKey(['config', 'api-server-url']);
+const CONFIG_API_SERVER_KEY = buildStorageKey(['config', 'api-server']);
export const configLocalStorage = {
- getApiServerBaseUrl: async () => storage.getItem(CONFIG_API_SERVER_URL_KEY),
- setApiServerBaseUrl: async ({ apiServerBaseUrl }: { apiServerBaseUrl: string }) =>
- storage.setItem(CONFIG_API_SERVER_URL_KEY, apiServerBaseUrl),
+ getApiServerConfig: async (): Promise<ApiServerConfig | null> => {
+ const rawConfig = await secureStore.getItemAsync(CONFIG_API_SERVER_KEY);
+
+ if (rawConfig == null) {
+ return null;
+ }
+
+ const [apiServerConfig] = safelySync(() =>
+ parseApiServerConfig({ config: JSON.parse(rawConfig) }),
+ );
+
+ return apiServerConfig ?? null;
+ },
+ setApiServerConfig: async ({ apiServerConfig }: { apiServerConfig: ApiServerConfig }) => {
+ try {
+ await secureStore.setItemAsync(CONFIG_API_SERVER_KEY, JSON.stringify(apiServerConfig));
+ } catch (error) {
+ throw new Error(
+ 'Could not save the server configuration. It may be too large for secure storage, try removing or shortening custom headers.',
+ { cause: error },
+ );
+ }
+ },
};
diff --git a/apps/mobile/src/modules/config/config.models.test.ts b/apps/mobile/src/modules/config/config.models.test.ts
index 5342a055..c5366586 100644
--- a/apps/mobile/src/modules/config/config.models.test.ts
+++ b/apps/mobile/src/modules/config/config.models.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'vitest';
-import { validateServerUrl } from './config.models';
+import { validateCustomHeaders, validateServerUrl } from './config.models';
describe('config models', () => {
describe('validateServerUrl', () => {
@@ -44,4 +44,105 @@ describe('config models', () => {
);
});
});
+
+ describe('validateCustomHeaders', () => {
+ test('headers are trimmed and returned as a record', () => {
+ expect(
+ validateCustomHeaders({
+ headers: [
+ { name: ' X-Api-Key ', value: ' secret ' },
+ { name: 'Authorization', value: 'Basic dXNlcjpwYXNz' },
+ ],
+ }),
+ ).to.eql({
+ 'X-Api-Key': 'secret',
+ 'Authorization': 'Basic dXNlcjpwYXNz',
+ });
+ });
+
+ test('fully empty rows are ignored', () => {
+ expect(
+ validateCustomHeaders({
+ headers: [
+ { name: '', value: '' },
+ { name: ' ', value: '' },
+ { name: 'X-Foo', value: 'bar' },
+ ],
+ }),
+ ).to.eql({ 'X-Foo': 'bar' });
+
+ expect(validateCustomHeaders({ headers: [] })).to.eql({});
+ });
+
+ test('a header with a value but no name is rejected', () => {
+ expect(() => validateCustomHeaders({ headers: [{ name: '', value: 'foo' }] })).toThrow(
+ 'Header names cannot be empty.',
+ );
+ });
+
+ test('header names with invalid characters are rejected', () => {
+ expect(() => validateCustomHeaders({ headers: [{ name: 'X Foo', value: 'bar' }] })).toThrow(
+ 'The header name "X Foo" is invalid.',
+ );
+ expect(() =>
+ validateCustomHeaders({ headers: [{ name: 'X-Foo:', value: 'bar' }] }),
+ ).toThrow();
+ expect(() => validateCustomHeaders({ headers: [{ name: 'X-Fôo', value: 'bar' }] })).toThrow();
+ });
+
+ test('headers managed by the app are denied, regardless of casing', () => {
+ expect(() => validateCustomHeaders({ headers: [{ name: 'Cookie', value: 'a=b' }] })).toThrow(
+ 'The header "Cookie" is managed by the app and cannot be overridden.',
+ );
+ expect(() =>
+ validateCustomHeaders({ headers: [{ name: 'cookie', value: 'a=b' }] }),
+ ).toThrow();
+ expect(() =>
+ validateCustomHeaders({ headers: [{ name: 'HOST', value: 'evil.com' }] }),
+ ).toThrow();
+ expect(() =>
+ validateCustomHeaders({ headers: [{ name: 'Content-Type', value: 'text/plain' }] }),
+ ).toThrow();
+ expect(() => validateCustomHeaders({ headers: [{ name: 'Origin', value: 'x' }] })).toThrow();
+ expect(() => validateCustomHeaders({ headers: [{ name: 'Referer', value: 'x' }] })).toThrow();
+ });
+
+ test('headers with denied prefixes are rejected', () => {
+ expect(() =>
+ validateCustomHeaders({ headers: [{ name: 'Proxy-Authorization', value: 'x' }] }),
+ ).toThrow();
+ expect(() =>
+ validateCustomHeaders({ headers: [{ name: 'Sec-Fetch-Mode', value: 'cors' }] }),
+ ).toThrow();
+ expect(() =>
+ validateCustomHeaders({
+ headers: [{ name: 'Access-Control-Request-Method', value: 'GET' }],
+ }),
+ ).toThrow();
+ });
+
+ test('values containing newlines are rejected', () => {
+ expect(() =>
+ validateCustomHeaders({ headers: [{ name: 'X-Foo', value: 'bar\r\nbaz' }] }),
+ ).toThrow('The value of the header "X-Foo" is invalid.');
+ });
+
+ test('common reverse-proxy auth headers are allowed', () => {
+ expect(
+ validateCustomHeaders({
+ headers: [
+ { name: 'Authorization', value: 'Bearer token' },
+ { name: 'CF-Access-Client-Id', value: 'id' },
+ { name: 'CF-Access-Client-Secret', value: 'secret' },
+ { name: 'X-Forwarded-User', value: 'corentin' },
+ ],
+ }),
+ ).to.eql({
+ 'Authorization': 'Bearer token',
+ 'CF-Access-Client-Id': 'id',
+ 'CF-Access-Client-Secret': 'secret',
+ 'X-Forwarded-User': 'corentin',
+ });
+ });
+ });
});
diff --git a/apps/mobile/src/modules/config/config.models.ts b/apps/mobile/src/modules/config/config.models.ts
index 5336c898..725a96c8 100644
--- a/apps/mobile/src/modules/config/config.models.ts
+++ b/apps/mobile/src/modules/config/config.models.ts
@@ -10,3 +10,94 @@ const urlSchema = v.pipe(
export function validateServerUrl({ url }: { url: string }) {
return v.parse(urlSchema, url);
}
+
+const apiServerConfigSchema = v.object({
+ baseUrl: v.pipe(v.string(), v.url()),
+ customHeaders: v.record(v.string(), v.string()),
+});
+
+export type ApiServerConfig = v.InferOutput<typeof apiServerConfigSchema>;
+
+export function parseApiServerConfig({ config }: { config: unknown }) {
+ return v.parse(apiServerConfigSchema, config);
+}
+
+export type CustomHeader = {
+ name: string;
+ value: string;
+};
+
+// RFC 9110 token characters, the only ones allowed in a header name
+const HEADER_NAME_REGEX = /^[!#$%&'*+\-.^_`|~a-z0-9]+$/i;
+
+// Headers that are either managed by the app (auth cookies, content negotiation)
+// or reserved by the fetch spec, and must not be overridden by user-provided headers
+const FORBIDDEN_HEADER_NAMES = new Set([
+ 'accept-charset',
+ 'accept-encoding',
+ 'connection',
+ 'content-length',
+ 'content-type',
+ 'cookie',
+ 'cookie2',
+ 'date',
+ 'dnt',
+ 'expect',
+ 'host',
+ 'keep-alive',
+ 'origin',
+ 'referer',
+ 'set-cookie',
+ 'te',
+ 'trailer',
+ 'transfer-encoding',
+ 'upgrade',
+ 'via',
+]);
+
+const FORBIDDEN_HEADER_PREFIXES = ['proxy-', 'sec-', 'access-control-'];
+
+export function isForbiddenHeaderName({ name }: { name: string }) {
+ const lowerCasedName = name.toLowerCase();
+
+ return (
+ FORBIDDEN_HEADER_NAMES.has(lowerCasedName) ||
+ FORBIDDEN_HEADER_PREFIXES.some((prefix) => lowerCasedName.startsWith(prefix))
+ );
+}
+
+export function validateCustomHeaders({
+ headers,
+}: {
+ headers: CustomHeader[];
+}): Record<string, string> {
+ const validatedHeaders: Record<string, string> = {};
+
+ for (const header of headers) {
+ const name = header.name.trim();
+ const value = header.value.trim();
+
+ // Fully empty rows are just leftovers from the form, skip them
+ if (name === '' && value === '') {
+ continue;
+ }
+
+ if (!HEADER_NAME_REGEX.test(name)) {
+ throw new Error(
+ name === '' ? 'Header names cannot be empty.' : `The header name "${name}" is invalid.`,
+ );
+ }
+
+ if (isForbiddenHeaderName({ name })) {
+ throw new Error(`The header "${name}" is managed by the app and cannot be overridden.`);
+ }
+
+ if (/[\r\n]/.test(value)) {
+ throw new Error(`The value of the header "${name}" is invalid.`);
+ }
+
+ validatedHeaders[name] = value;
+ }
+
+ return validatedHeaders;
+}
diff --git a/apps/mobile/src/modules/config/config.queries.ts b/apps/mobile/src/modules/config/config.queries.ts
new file mode 100644
index 00000000..2260c0c0
--- /dev/null
+++ b/apps/mobile/src/modules/config/config.queries.ts
@@ -0,0 +1,7 @@
+import { queryOptions } from '@tanstack/react-query';
+import { configLocalStorage } from './config.local-storage';
+
+export const configQueryOptions = queryOptions({
+ queryKey: ['api-server-config'],
+ queryFn: configLocalStorage.getApiServerConfig,
+});
diff --git a/apps/mobile/src/modules/config/config.services.ts b/apps/mobile/src/modules/config/config.services.ts
index 80dfd299..85c3375e 100644
--- a/apps/mobile/src/modules/config/config.services.ts
+++ b/apps/mobile/src/modules/config/config.services.ts
@@ -10,8 +10,18 @@ export async function fetchServerConfig({ apiClient }: { apiClient: ApiClient })
});
}
-export async function pingServer({ url }: { url: string }): Promise<true> {
- const response = await httpClient<{ status: 'ok' | 'error' }>({ url: `/api/ping`, baseUrl: url })
+export async function pingServer({
+ url,
+ headers,
+}: {
+ url: string;
+ headers?: Record<string, string>;
+}): Promise<true> {
+ const response = await httpClient<{ status: 'ok' | 'error' }>({
+ url: `/api/ping`,
+ baseUrl: url,
+ headers,
+ })
.then(() => true)
.catch(() => false);
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 ae5b16b2..007ea52a 100644
--- a/apps/mobile/src/modules/config/screens/server-selection.screen.tsx
+++ b/apps/mobile/src/modules/config/screens/server-selection.screen.tsx
@@ -1,7 +1,8 @@
import type { ThemeColors } from '@/modules/ui/theme.constants';
+import type { CustomHeader } from '../config.models';
import { safelySync } from '@corentinth/chisels';
import { useRouter } from 'expo-router';
-import { useState } from 'react';
+import { useRef, useState } from 'react';
import {
ActivityIndicator,
KeyboardAvoidingView,
@@ -20,8 +21,9 @@ 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 { validateCustomHeaders, validateServerUrl } from '../config.models';
import { pingServer } from '../config.services';
+import { configQueryOptions } from '../config.queries';
function getDefaultCustomServerUrl() {
if (!__DEV__) {
@@ -41,11 +43,29 @@ export function ServerSelectionScreen() {
const [selectedOption, setSelectedOption] = useState<'managed' | 'self-hosted'>('managed');
const [customUrl, setCustomUrl] = useState(getDefaultCustomServerUrl());
+ const [customHeaderRows, setCustomHeaderRows] = useState<(CustomHeader & { id: number })[]>([]);
+ const [areCustomHeadersExpanded, setAreCustomHeadersExpanded] = useState(false);
const [isValidating, setIsValidating] = useState(false);
+ const nextHeaderRowId = useRef(0);
const isSelfHosted = selectedOption === 'self-hosted';
const canContinue = !isValidating && (!isSelfHosted || customUrl.trim() !== '');
+ const addCustomHeaderRow = () => {
+ const id = nextHeaderRowId.current;
+ nextHeaderRowId.current += 1;
+
+ setCustomHeaderRows((rows) => [...rows, { id, name: '', value: '' }]);
+ };
+
+ const updateCustomHeaderRow = ({ id, ...patch }: { id: number } & Partial<CustomHeader>) => {
+ setCustomHeaderRows((rows) => rows.map((row) => (row.id === id ? { ...row, ...patch } : row)));
+ };
+
+ const deleteCustomHeaderRow = ({ id }: { id: number }) => {
+ setCustomHeaderRows((rows) => rows.filter((row) => row.id !== id));
+ };
+
const handleContinue = async () => {
const rawUrl = isSelfHosted ? customUrl : MANAGED_SERVER_URL;
@@ -63,8 +83,21 @@ export function ServerSelectionScreen() {
return;
}
+ const [customHeaders, headersValidationError] = safelySync(() =>
+ validateCustomHeaders({ headers: isSelfHosted ? customHeaderRows : [] }),
+ );
+
+ if (headersValidationError) {
+ showAlert({
+ title: 'Invalid Custom Header',
+ message: headersValidationError.message,
+ });
+ setIsValidating(false);
+ return;
+ }
+
try {
- await pingServer({ url });
+ await pingServer({ url, headers: customHeaders });
} catch {
showAlert({
title: 'Connection Failed',
@@ -75,14 +108,19 @@ export function ServerSelectionScreen() {
}
try {
- await configLocalStorage.setApiServerBaseUrl({ apiServerBaseUrl: url });
- await queryClient.invalidateQueries({ queryKey: ['api-server-url'] });
+ await configLocalStorage.setApiServerConfig({
+ apiServerConfig: { baseUrl: url, customHeaders },
+ });
+ await queryClient.invalidateQueries({ queryKey: configQueryOptions.queryKey });
router.replace('/auth/login');
- } catch {
+ } catch (error) {
showAlert({
title: 'Something Went Wrong',
- message: 'Could not save the server configuration. Please try again.',
+ message:
+ error instanceof Error
+ ? error.message
+ : 'Could not save the server configuration. Please try again.',
});
} finally {
setIsValidating(false);
@@ -153,6 +191,76 @@ export function ServerSelectionScreen() {
keyboardType="url"
editable={!isValidating}
/>
+
+ <TouchableOpacity
+ style={styles.customHeadersToggle}
+ onPress={() => setAreCustomHeadersExpanded((isExpanded) => !isExpanded)}
+ disabled={isValidating}
+ accessibilityRole="button"
+ accessibilityState={{ expanded: areCustomHeadersExpanded, disabled: isValidating }}
+ >
+ <Icon
+ name={areCustomHeadersExpanded ? 'chevron-down' : 'chevron-right'}
+ size={18}
+ color={themeColors.mutedForeground}
+ />
+ <Text style={styles.customHeadersToggleLabel}>
+ Custom headers
+ {customHeaderRows.length > 0 ? ` (${customHeaderRows.length})` : ''}
+ </Text>
+ </TouchableOpacity>
+
+ {areCustomHeadersExpanded && (
+ <View style={styles.customHeadersList}>
+ {customHeaderRows.map((row) => (
+ <View key={row.id} style={styles.customHeaderRow}>
+ <TextInput
+ style={[styles.input, styles.customHeaderInput]}
+ placeholder="Name"
+ placeholderTextColor={themeColors.mutedForeground}
+ value={row.name}
+ onChangeText={(name) => updateCustomHeaderRow({ id: row.id, name })}
+ autoCapitalize="none"
+ autoCorrect={false}
+ editable={!isValidating}
+ />
+ <TextInput
+ style={[
+ styles.input,
+ styles.customHeaderInput,
+ styles.customHeaderValueInput,
+ ]}
+ placeholder="Value"
+ placeholderTextColor={themeColors.mutedForeground}
+ value={row.value}
+ onChangeText={(value) => updateCustomHeaderRow({ id: row.id, value })}
+ autoCapitalize="none"
+ autoCorrect={false}
+ editable={!isValidating}
+ />
+ <TouchableOpacity
+ style={styles.customHeaderDeleteButton}
+ onPress={() => deleteCustomHeaderRow({ id: row.id })}
+ disabled={isValidating}
+ accessibilityRole="button"
+ accessibilityLabel={`Delete header ${row.name || 'row'}`}
+ >
+ <Icon name="trash-2" size={18} color={themeColors.mutedForeground} />
+ </TouchableOpacity>
+ </View>
+ ))}
+
+ <TouchableOpacity
+ style={styles.addHeaderButton}
+ onPress={addCustomHeaderRow}
+ disabled={isValidating}
+ accessibilityRole="button"
+ >
+ <Icon name="plus" size={16} color={themeColors.foreground} />
+ <Text style={styles.addHeaderButtonLabel}>Add header</Text>
+ </TouchableOpacity>
+ </View>
+ )}
</>
)}
</View>
@@ -262,6 +370,56 @@ function createStyles({ themeColors }: { themeColors: ThemeColors }) {
color: themeColors.foreground,
backgroundColor: themeColors.secondaryBackground,
},
+ customHeadersToggle: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 6,
+ paddingVertical: 8,
+ },
+ customHeadersToggleLabel: {
+ fontSize: 14,
+ fontWeight: '600',
+ color: themeColors.mutedForeground,
+ },
+ customHeadersList: {
+ gap: 8,
+ },
+ customHeaderRow: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 8,
+ },
+ customHeaderInput: {
+ flex: 1,
+ height: 44,
+ paddingHorizontal: 12,
+ fontSize: 14,
+ },
+ customHeaderValueInput: {
+ flex: 1.4,
+ },
+ customHeaderDeleteButton: {
+ height: 44,
+ width: 36,
+ justifyContent: 'center',
+ alignItems: 'center',
+ },
+ addHeaderButton: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: 6,
+ height: 44,
+ borderWidth: 1,
+ borderStyle: 'dashed',
+ borderColor: themeColors.border,
+ borderRadius: 8,
+ },
+ addHeaderButtonLabel: {
+ fontSize: 14,
+ fontWeight: '600',
+ color: themeColors.foreground,
+ },
footer: {
paddingHorizontal: 24,
paddingTop: 12,
diff --git a/apps/mobile/src/modules/documents/components/document-action-sheet.tsx b/apps/mobile/src/modules/documents/components/document-action-sheet.tsx
index 50befb09..fc8f6a06 100644
--- a/apps/mobile/src/modules/documents/components/document-action-sheet.tsx
+++ b/apps/mobile/src/modules/documents/components/document-action-sheet.tsx
@@ -16,7 +16,6 @@ import {
View,
} from 'react-native';
import { useApiClient, useAuthClient } from '@/modules/api/providers/api.provider';
-import { configLocalStorage } from '@/modules/config/config.local-storage';
import { RenameDocumentDialog } from '@/modules/documents/components/rename-document-dialog';
import {
deleteDocument,
@@ -79,16 +78,6 @@ export function DocumentActionSheet({
const handleDownloadAndShare = async () => {
onClose();
- const baseUrl = await configLocalStorage.getApiServerBaseUrl();
-
- if (baseUrl == null) {
- showAlert({
- title: 'Error',
- message: 'Base URL not found',
- });
- return;
- }
-
const canShare = await Sharing.isAvailableAsync();
if (!canShare) {
showAlert({
@@ -102,7 +91,6 @@ export function DocumentActionSheet({
const fileUri = await fetchDocumentFile({
document,
organizationId: document.organizationId,
- baseUrl,
authClient,
});
diff --git a/apps/mobile/src/modules/documents/documents.services.ts b/apps/mobile/src/modules/documents/documents.services.ts
index 7b0fa22e..021f854f 100644
--- a/apps/mobile/src/modules/documents/documents.services.ts
+++ b/apps/mobile/src/modules/documents/documents.services.ts
@@ -4,6 +4,7 @@ import type { AuthClient } from '../auth/auth.client';
import type { Document } from './documents.types';
import * as FileSystem from 'expo-file-system/legacy';
import { coerceDates } from '../api/api.models';
+import { configLocalStorage } from '../config/config.local-storage';
export function getFormData(pojo: Record<string, string | FormDataValue | Blob>): FormData {
const formData = new FormData();
@@ -133,17 +134,23 @@ export async function renameDocument({
export async function fetchDocumentFile({
document,
organizationId,
- baseUrl,
authClient,
}: {
document: CoerceDates<Document>;
organizationId: string;
- baseUrl: string;
authClient: AuthClient;
}) {
+ const apiServerConfig = await configLocalStorage.getApiServerConfig();
+
+ if (apiServerConfig == null) {
+ throw new Error('Server configuration not found');
+ }
+
+ const { baseUrl, customHeaders } = apiServerConfig;
const cookies = authClient.getCookie();
const uri = `${baseUrl}/api/organizations/${organizationId}/documents/${document.id}/file`;
const headers = {
+ ...customHeaders,
'Cookie': cookies,
'Content-Type': document.mimeType,
};
diff --git a/apps/mobile/src/modules/documents/screens/document-details.screen.tsx b/apps/mobile/src/modules/documents/screens/document-details.screen.tsx
index f271ad93..cb09abdd 100644
--- a/apps/mobile/src/modules/documents/screens/document-details.screen.tsx
+++ b/apps/mobile/src/modules/documents/screens/document-details.screen.tsx
@@ -18,7 +18,6 @@ import {
import { SafeAreaView } from 'react-native-safe-area-context';
import * as Sharing from 'expo-sharing';
import { useApiClient, useAuthClient } from '@/modules/api/providers/api.provider';
-import { configLocalStorage } from '@/modules/config/config.local-storage';
import { DocumentActionSheet } from '@/modules/documents/components/document-action-sheet';
import { fetchDocument, fetchDocumentFile } from '@/modules/documents/documents.services';
import { Icon } from '@/modules/ui/components/icon';
@@ -146,12 +145,7 @@ export function DocumentDetailsScreen() {
throw new Error('Document not loaded');
}
- const baseUrl = await configLocalStorage.getApiServerBaseUrl();
- if (baseUrl == null) {
- throw new Error('Base URL not found');
- }
-
- return fetchDocumentFile({ document, organizationId, baseUrl, authClient });
+ return fetchDocumentFile({ document, organizationId, authClient });
};
const handleOpen = () => {
diff --git a/apps/mobile/src/modules/documents/screens/document-view.screen.tsx b/apps/mobile/src/modules/documents/screens/document-view.screen.tsx
index ee4d9a17..4636ab60 100644
--- a/apps/mobile/src/modules/documents/screens/document-view.screen.tsx
+++ b/apps/mobile/src/modules/documents/screens/document-view.screen.tsx
@@ -18,7 +18,6 @@ import {
import Pdf from 'react-native-pdf';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useApiClient, useAuthClient } from '@/modules/api/providers/api.provider';
-import { configLocalStorage } from '@/modules/config/config.local-storage';
import { DocumentActionSheet } from '@/modules/documents/components/document-action-sheet';
import { fetchDocument, fetchDocumentFile } from '@/modules/documents/documents.services';
import { useAlert } from '@/modules/ui/providers/alert-provider';
@@ -176,15 +175,9 @@ export default function DocumentViewScreen() {
throw new Error('Document not loaded');
}
- const baseUrl = await configLocalStorage.getApiServerBaseUrl();
- if (baseUrl == null) {
- throw new Error('Base URL not found');
- }
-
const fileUri = await fetchDocumentFile({
document: documentQuery.data.document,
organizationId,
- baseUrl,
authClient,
});
diff --git a/apps/mobile/src/modules/lib/local-storage/local-storage.constants.ts b/apps/mobile/src/modules/lib/local-storage/local-storage.constants.ts
index 70d8a577..84ecdefa 100644
--- a/apps/mobile/src/modules/lib/local-storage/local-storage.constants.ts
+++ b/apps/mobile/src/modules/lib/local-storage/local-storage.constants.ts
@@ -1 +1,3 @@
-export const STORAGE_KEY_BASE_PREFIX = '@papra';
+export const STORAGE_KEY_BASE_PREFIX = 'papra';
+export const STORAGE_KEY_SEPARATOR = '.';
+export const STORAGE_KEY_SECTION_REGEX = /^[a-z0-9-]+$/;
diff --git a/apps/mobile/src/modules/lib/local-storage/local-storage.models.test.ts b/apps/mobile/src/modules/lib/local-storage/local-storage.models.test.ts
new file mode 100644
index 00000000..b52fb889
--- /dev/null
+++ b/apps/mobile/src/modules/lib/local-storage/local-storage.models.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, test } from 'vitest';
+import { buildStorageKey } from './local-storage.models';
+
+describe('local-storage.models', () => {
+ describe('buildStorageKey', () => {
+ test('create a storage key from the provided sections, prefixed with "papra", with sections separated by "."', () => {
+ expect(buildStorageKey(['stuff'])).to.eql('papra.stuff');
+ expect(buildStorageKey(['config', 'api-server'])).to.eql('papra.config.api-server');
+ });
+
+ test('sections are trimmed', () => {
+ expect(buildStorageKey([' stuff '])).to.eql('papra.stuff');
+ expect(buildStorageKey([' config ', ' api-server '])).to.eql('papra.config.api-server');
+ });
+
+ test('throws an error if any section is empty', () => {
+ expect(() => buildStorageKey(['stuff', ''])).toThrow();
+ expect(() => buildStorageKey(['stuff', '\n'])).toThrow();
+ expect(() => buildStorageKey(['stuff', '\n \r \t'])).toThrow();
+ });
+
+ test('throws an error if no sections are provided', () => {
+ expect(() => buildStorageKey([] as unknown as [string, ...string[]])).toThrow();
+ expect(() => buildStorageKey([''])).toThrow();
+ expect(() => buildStorageKey(['\n'])).toThrow();
+ expect(() => buildStorageKey(['\n \r \t'])).toThrow();
+ });
+
+ test('throws an error if any section contains non-lowercase letters, numbers, or dashes as expo secure store key are strict', () => {
+ expect(() => buildStorageKey(['Stuff'])).toThrow();
+ expect(() => buildStorageKey(['_stuff'])).toThrow();
+ expect(() => buildStorageKey(['?'])).toThrow();
+ expect(() => buildStorageKey(['stuff', 'api_server'])).toThrow();
+ });
+ });
+});
diff --git a/apps/mobile/src/modules/lib/local-storage/local-storage.models.ts b/apps/mobile/src/modules/lib/local-storage/local-storage.models.ts
index 29722410..02d988bc 100644
--- a/apps/mobile/src/modules/lib/local-storage/local-storage.models.ts
+++ b/apps/mobile/src/modules/lib/local-storage/local-storage.models.ts
@@ -1,5 +1,29 @@
-import { STORAGE_KEY_BASE_PREFIX } from './local-storage.constants';
+import {
+ STORAGE_KEY_BASE_PREFIX,
+ STORAGE_KEY_SECTION_REGEX,
+ STORAGE_KEY_SEPARATOR,
+} from './local-storage.constants';
-export function buildStorageKey(sections: string[]): string {
- return [STORAGE_KEY_BASE_PREFIX, ...sections].join(':');
+export function buildStorageKey(rawSections: [string, ...string[]]): string {
+ const sections = rawSections.map((section) => section.trim());
+
+ const hasEmptySection = sections.some((section) => section.length === 0);
+
+ if (hasEmptySection) {
+ throw new Error('Empty section names are not allowed when building a storage key.');
+ }
+
+ if (sections.length === 0) {
+ throw new Error('At least one section must be provided to build a storage key.');
+ }
+
+ sections.forEach((section) => {
+ if (!STORAGE_KEY_SECTION_REGEX.test(section)) {
+ throw new Error(
+ 'Invalid section name provided to build a storage key. Section names must only contain lowercase letters, numbers, and dashes.',
+ );
+ }
+ });
+
+ return [STORAGE_KEY_BASE_PREFIX, ...sections].join(STORAGE_KEY_SEPARATOR);
}