The minimalistic document archiving platform.
feat(auth): added support for custom oauth2 providers (#295)
Corentin Thomasset438a31171c60
diff --git a/.changeset/chatty-pandas-sin.md b/.changeset/chatty-pandas-sin.mdnew file mode 100644index 00000000..a034a193--- /dev/null+++ b/.changeset/chatty-pandas-sin.md@@ -0,0 +1,7 @@+---+"@papra/app-client": minor+"@papra/app-server": minor+"@papra/docs": minor+---++Added support for custom oauth2 providersdiff --git a/apps/docs/src/content/docs/03-guides/04-setup-custom-oauth2.mdx b/apps/docs/src/content/docs/03-guides/04-setup-custom-oauth2.mdxnew file mode 100644index 00000000..23084687--- /dev/null+++ b/apps/docs/src/content/docs/03-guides/04-setup-custom-oauth2.mdx@@ -0,0 +1,181 @@+---+title: Setup Custom OAuth2 Providers+description: Step-by-step guide to setup custom OAuth2 providers for authentication in your Papra instance.+slug: guides/setup-custom-oauth2-providers+---++import { Aside } from '@astrojs/starlight/components';+import { Steps } from '@astrojs/starlight/components';++This guide will show you how to configure custom OAuth2 providers for authentication in your Papra instance.++<Aside type="note">+ Papra's OAuth2 implementation is based on the [Better Auth Generic OAuth plugin](https://www.better-auth.com/docs/plugins/generic-oauth). For more detailed information about the configuration options and advanced usage, please refer to their documentation.+</Aside>++## Prerequisites++In order to follow this guide, you need:+- A custom OAuth2 provider+- An accessible Papra instance+- Basic understanding of OAuth2 flows++## Configuration++To set up custom OAuth2 providers, you'll need to configure the `AUTH_PROVIDERS_CUSTOMS` environment variable with an array of provider configurations. Here's an example:++```bash+AUTH_PROVIDERS_CUSTOMS='[+ {+ "providerId": "custom-oauth2",+ "providerName": "Custom OAuth2",+ "providerIconUrl": "https://api.iconify.design/tabler:login-2.svg",+ "clientId": "your-client-id",+ "clientSecret": "your-client-secret",+ "type": "oidc",+ "discoveryUrl": "https://your-provider.tld/.well-known/openid-configuration",+ "scopes": ["openid", "profile", "email"]+ }+]'+```++Each provider configuration supports the following fields:++- `providerId`: A unique identifier for the OAuth provider+- `providerName`: The display name of the provider+- `providerIconUrl`: URL of the icon to display (optional) you can use a base64 encoded image or an url to a remote image.+- `clientId`: OAuth client ID+- `clientSecret`: OAuth client secret+- `type`: Type of OAuth flow ("oauth2" or "oidc")+- `discoveryUrl`: URL to fetch OAuth 2.0 configuration (recommended for OIDC providers)+- `authorizationUrl`: URL for the authorization endpoint (required for OAuth2 if not using discoveryUrl)+- `tokenUrl`: URL for the token endpoint (required for OAuth2 if not using discoveryUrl)+- `userInfoUrl`: URL for the user info endpoint (required for OAuth2 if not using discoveryUrl)+- `scopes`: Array of OAuth scopes to request+- `redirectURI`: Custom redirect URI (optional)+- `responseType`: OAuth response type (defaults to "code")+- `prompt`: Controls the authentication experience ("select_account", "consent", "login", "none")+- `pkce`: Whether to use PKCE (Proof Key for Code Exchange)+- `accessType`: Access type for the authorization request++## Setup++<Steps>++1. **Configure your OAuth2 Provider**++ First, you'll need to register your application with your OAuth2 provider. This typically involves:+ - Creating a new application in your provider's dashboard+ - Setting up the redirect URI (usually `https://<your-papra-instance>/api/auth/oauth2/callback/:providerId`)+ - Obtaining the client ID and client secret+ - Configuring the required scopes++2. **Configure Papra**++ Add the `AUTH_PROVIDERS_CUSTOMS` environment variable to your Papra instance. Here are some examples:++ For OIDC providers:+ ```json+ [+ {+ "providerId": "custom-oauth2",+ "providerName": "Custom OAuth2",+ "providerIconUrl": "https://api.iconify.design/tabler:login-2.svg",+ "clientId": "your-client-id",+ "clientSecret": "your-client-secret",+ "type": "oidc",+ "discoveryUrl": "https://your-provider.tld/.well-known/openid-configuration",+ "scopes": ["openid", "profile", "email"]+ }+ ]+ ```++ For standard OAuth2 providers:+ ```json+ [+ {+ "providerId": "custom-oauth2",+ "providerName": "Custom OAuth2",+ "providerIconUrl": "https://api.iconify.design/tabler:login-2.svg",+ "clientId": "your-client-id",+ "clientSecret": "your-client-secret",+ "type": "oauth2",+ "authorizationUrl": "https://your-provider.tld/oauth2/authorize",+ "tokenUrl": "https://your-provider.tld/oauth2/token",+ "userInfoUrl": "https://your-provider.tld/oauth2/userinfo",+ "scopes": ["profile", "email"]+ }+ ]+ ```++ <Aside type="note">+ The `discoveryUrl` is recommended for OIDC providers as it automatically configures all the necessary endpoints.+ For standard OAuth2 providers, you'll need to specify the endpoints manually.+ </Aside>++3. **Test the Configuration**++ - Restart your Papra instance to apply the changes+ - Go to the login page+ - You should see your custom OAuth2 providers as login options+ - Try logging in with a test account++</Steps>++## Troubleshooting++### Providers Not Showing Up++If your OAuth2 providers are not showing up on the login page:+- Check that the JSON configuration in `AUTH_PROVIDERS_CUSTOMS` is valid+- Ensure all required fields are provided+- Verify that the provider IDs are unique++### Authentication Fails++If authentication fails:+- Verify that the redirect URI is correctly configured in your OAuth2 provider+- Check that the client ID and client secret are correct+- Ensure the required scopes are properly configured+- Check the Papra logs for any error messages++### OIDC Discovery Issues++If you're using OIDC and experiencing issues:+- Verify that the `discoveryUrl` is accessible+- Check that the provider supports OIDC discovery+- Ensure the provider's configuration is properly exposed through the discovery endpoint++## Security Considerations++<Aside type="caution">+ Always use HTTPS for your OAuth2 endpoints and ensure your client secret is kept secure.+ Consider using PKCE (Proof Key for Code Exchange) for additional security by setting `pkce: true` in your configuration.+</Aside>++## Multiple Providers++You can configure multiple custom OAuth2 providers by adding them to the array:++```json+[+ {+ "providerId": "custom-oauth2-1",+ "providerName": "Custom OAuth2 Provider 1",+ "type": "oidc",+ "discoveryUrl": "https://provider1.tld/.well-known/openid-configuration",+ "clientId": "client-id-1",+ "clientSecret": "client-secret-1",+ "scopes": ["openid", "profile", "email"]+ },+ {+ "providerId": "custom-oauth2-2",+ "providerName": "Custom OAuth2 Provider 2",+ "type": "oidc",+ "discoveryUrl": "https://provider2.tld/.well-known/openid-configuration",+ "clientId": "client-id-2",+ "clientSecret": "client-secret-2",+ "scopes": ["openid", "profile", "email"]+ }+]+```\ No newline at end of filediff --git a/apps/docs/src/content/navigation.ts b/apps/docs/src/content/navigation.tsindex b9f9a3bd..beab3c3c 100644--- a/apps/docs/src/content/navigation.ts+++ b/apps/docs/src/content/navigation.ts@@ -31,6 +31,10 @@ export const sidebar: StarlightUserConfig['sidebar'] = [label: 'Setup Ingestion Folder',slug: 'guides/setup-ingestion-folder',},+ {+ label: 'Setup Custom OAuth2 Providers',+ slug: 'guides/setup-custom-oauth2-providers',+ },],},{diff --git a/apps/papra-client/src/modules/auth/auth.models.ts b/apps/papra-client/src/modules/auth/auth.models.tsindex c868551d..dfebbe8b 100644--- a/apps/papra-client/src/modules/auth/auth.models.ts+++ b/apps/papra-client/src/modules/auth/auth.models.ts@@ -1,4 +1,5 @@import type { Config } from '../config/config';+import type { SsoProviderConfig } from './auth.types';import { get } from 'lodash-es';import { ssoProviders } from './auth.constants';@@ -8,8 +9,15 @@ export function isAuthErrorWithCode({ error, code }: { error: unknown; code: strexport const isEmailVerificationRequiredError = ({ error }: { error: unknown }) => isAuthErrorWithCode({ error, code: 'EMAIL_NOT_VERIFIED' });-export function getEnabledSsoProviderConfigs({ config }: { config: Config }) {- const enabledSsoProviders = ssoProviders.filter(({ key }) => get(config, `auth.providers.${key}.isEnabled`));+export function getEnabledSsoProviderConfigs({ config }: { config: Config }): SsoProviderConfig[] {+ const enabledSsoProviders: SsoProviderConfig[] = [+ ...ssoProviders.filter(({ key }) => get(config, `auth.providers.${key}.isEnabled`)),+ ...config.auth.providers.customs.map(({ providerId, providerName, providerIconUrl }) => ({+ key: providerId,+ name: providerName,+ icon: providerIconUrl ?? 'i-tabler-login-2',+ })),+ ];return enabledSsoProviders;}diff --git a/apps/papra-client/src/modules/auth/auth.services.ts b/apps/papra-client/src/modules/auth/auth.services.tsindex 11571d03..179d1081 100644--- a/apps/papra-client/src/modules/auth/auth.services.ts+++ b/apps/papra-client/src/modules/auth/auth.services.ts@@ -1,5 +1,8 @@-import { createAuthClient as createBetterAuthClient } from 'better-auth/solid';+import type { Config } from '../config/config';+import type { SsoProviderConfig } from './auth.types';+import { genericOAuthClient } from 'better-auth/client/plugins';+import { createAuthClient as createBetterAuthClient } from 'better-auth/solid';import { buildTimeConfig } from '../config/config';import { trackingServices } from '../tracking/tracking.services';import { createDemoAuthClient } from './auth.demo.services';@@ -7,6 +10,9 @@ import { createDemoAuthClient } from './auth.demo.services';export function createAuthClient() {const client = createBetterAuthClient({baseURL: buildTimeConfig.baseApiUrl,+ plugins: [+ genericOAuthClient(),+ ],});return {@@ -38,3 +44,17 @@ export const {} = buildTimeConfig.isDemoMode? createDemoAuthClient(): createAuthClient();++export async function authWithProvider({ provider, config }: { provider: SsoProviderConfig; config: Config }) {+ const isCustomProvider = config.auth.providers.customs.some(({ providerId }) => providerId === provider.key);++ if (isCustomProvider) {+ signIn.oauth2({+ providerId: provider.key,+ callbackURL: config.baseUrl,+ });+ return;+ }++ await signIn.social({ provider: provider.key as 'github' | 'google', callbackURL: config.baseUrl });+}diff --git a/apps/papra-client/src/modules/auth/auth.types.ts b/apps/papra-client/src/modules/auth/auth.types.tsindex 0d6e6c82..2eab5423 100644--- a/apps/papra-client/src/modules/auth/auth.types.ts+++ b/apps/papra-client/src/modules/auth/auth.types.ts@@ -1,3 +1,4 @@import type { ssoProviders } from './auth.constants';-export type SsoProviderKey = (typeof ssoProviders)[number]['key'];+export type SsoProviderKey = (typeof ssoProviders)[number]['key'] | string & {};+export type SsoProviderConfig = { key: SsoProviderKey; name: string; icon: string };diff --git a/apps/papra-client/src/modules/auth/components/sso-provider-button.component.tsx b/apps/papra-client/src/modules/auth/components/sso-provider-button.component.tsxindex 80b7160c..7abe5ced 100644--- a/apps/papra-client/src/modules/auth/components/sso-provider-button.component.tsx+++ b/apps/papra-client/src/modules/auth/components/sso-provider-button.component.tsx@@ -1,19 +1,33 @@import type { Component } from 'solid-js';-import { createSignal } from 'solid-js';+import { createSignal, Match, Switch } from 'solid-js';import { cn } from '@/modules/shared/style/cn';import { Button } from '@/modules/ui/components/button';-export const SsoProviderButton: Component<{ name: string; icon: string; onClick: () => Promise<void>; label: string }> = (props) => {+export const SsoProviderButton: Component<{ name: string; icon?: string; onClick: () => Promise<void>; label: string }> = (props) => {const [getIsLoading, setIsLoading] = createSignal(false);- const navigateToProvider = async () => {+ const onClick = async () => {setIsLoading(true);await props.onClick();};return (- <Button variant="secondary" class="block w-full flex items-center justify-center" onClick={navigateToProvider} disabled={getIsLoading()}>- <span class={cn(`mr-2 size-4.5 inline-block`, getIsLoading() ? 'i-tabler-loader-2 animate-spin' : props.icon)} />+ <Button variant="secondary" class="block w-full flex items-center justify-center gap-2" onClick={onClick} disabled={getIsLoading()}>++ <Switch>+ <Match when={getIsLoading()}>+ <span class="i-tabler-loader-2 animate-spin" />+ </Match>++ <Match when={props.icon?.startsWith('i-')}>+ <span class={cn(`size-4.5`, props.icon)} />+ </Match>++ <Match when={props.icon}>+ <img src={props.icon} alt={props.name} class="size-4.5" />+ </Match>+ </Switch>+{props.label}</Button>);diff --git a/apps/papra-client/src/modules/auth/pages/login.page.tsx b/apps/papra-client/src/modules/auth/pages/login.page.tsxindex e948ad9d..45697bf9 100644--- a/apps/papra-client/src/modules/auth/pages/login.page.tsx+++ b/apps/papra-client/src/modules/auth/pages/login.page.tsx@@ -1,5 +1,5 @@import type { Component } from 'solid-js';-import type { SsoProviderKey } from '../auth.types';+import type { SsoProviderConfig } from '../auth.types';import { A, useNavigate } from '@solidjs/router';import { createSignal, For, Show } from 'solid-js';import * as v from 'valibot';@@ -12,7 +12,7 @@ import { Separator } from '@/modules/ui/components/separator';import { TextField, TextFieldLabel, TextFieldRoot } from '@/modules/ui/components/textfield';import { AuthLayout } from '../../ui/layouts/auth-layout.component';import { getEnabledSsoProviderConfigs, isEmailVerificationRequiredError } from '../auth.models';-import { signIn } from '../auth.services';+import { authWithProvider, signIn } from '../auth.services';import { AuthLegalLinks } from '../components/legal-links.component';import { SsoProviderButton } from '../components/sso-provider-button.component';@@ -105,8 +105,8 @@ export const LoginPage: Component = () => {const [getShowEmailLogin, setShowEmailLogin] = createSignal(false);- const loginWithProvider = async (provider: { key: SsoProviderKey }) => {- await signIn.social({ provider: provider.key, callbackURL: config.baseUrl });+ const loginWithProvider = async (provider: SsoProviderConfig) => {+ await authWithProvider({ provider, config });};const getHasSsoProviders = () => getEnabledSsoProviderConfigs({ config }).length > 0;diff --git a/apps/papra-client/src/modules/auth/pages/register.page.tsx b/apps/papra-client/src/modules/auth/pages/register.page.tsxindex c0c87e08..300e47b0 100644--- a/apps/papra-client/src/modules/auth/pages/register.page.tsx+++ b/apps/papra-client/src/modules/auth/pages/register.page.tsx@@ -1,5 +1,5 @@import type { Component } from 'solid-js';-import type { ssoProviders } from '../auth.constants';+import type { SsoProviderConfig } from '../auth.types';import { A, useNavigate } from '@solidjs/router';import { createSignal, For, Show } from 'solid-js';import * as v from 'valibot';@@ -11,7 +11,7 @@ import { Separator } from '@/modules/ui/components/separator';import { TextField, TextFieldLabel, TextFieldRoot } from '@/modules/ui/components/textfield';import { AuthLayout } from '../../ui/layouts/auth-layout.component';import { getEnabledSsoProviderConfigs } from '../auth.models';-import { signIn, signUp } from '../auth.services';+import { authWithProvider, signUp } from '../auth.services';import { AuthLegalLinks } from '../components/legal-links.component';import { SsoProviderButton } from '../components/sso-provider-button.component';@@ -133,8 +133,8 @@ export const RegisterPage: Component = () => {const [getShowEmailRegister, setShowEmailRegister] = createSignal(false);- const registerWithProvider = async (provider: typeof ssoProviders[number]) => {- await signIn.social({ provider: provider.key });+ const registerWithProvider = async (provider: SsoProviderConfig) => {+ await authWithProvider({ provider, config });};const getHasSsoProviders = () => getEnabledSsoProviderConfigs({ config }).length > 0;@@ -169,7 +169,7 @@ export const RegisterPage: Component = () => {name={provider.name}icon={provider.icon}onClick={() => registerWithProvider(provider)}- label={t('auth.register.register-with-provider', { provider: t(`auth.register.providers.${provider.key}`) })}+ label={t('auth.register.register-with-provider', { provider: provider.name })}/>)}</For>diff --git a/apps/papra-client/src/modules/config/config.ts b/apps/papra-client/src/modules/config/config.tsindex c6838424..e78a8281 100644--- a/apps/papra-client/src/modules/config/config.ts+++ b/apps/papra-client/src/modules/config/config.ts@@ -18,6 +18,11 @@ export const buildTimeConfig = {providers: {github: { isEnabled: asBoolean(import.meta.env.VITE_AUTH_PROVIDERS_GITHUB_IS_ENABLED, false) },google: { isEnabled: asBoolean(import.meta.env.VITE_AUTH_PROVIDERS_GOOGLE_IS_ENABLED, false) },+ customs: [] as {+ providerId: string;+ providerName: string;+ providerIconUrl: string;+ }[],},},documents: {diff --git a/apps/papra-server/src/modules/app/auth/auth.config.ts b/apps/papra-server/src/modules/app/auth/auth.config.tsindex 055689e3..9ed6f17f 100644--- a/apps/papra-server/src/modules/app/auth/auth.config.ts+++ b/apps/papra-server/src/modules/app/auth/auth.config.ts@@ -1,6 +1,28 @@import type { ConfigDefinition } from 'figue';import { z } from 'zod';import { booleanishSchema } from '../../config/config.schemas';+import { parseJson } from '../../intake-emails/intake-emails.schemas';++const customOAuthProviderSchema = z.object({+ providerId: z.string(),+ providerName: z.string(),+ providerIconUrl: z.string().url().optional(),++ clientId: z.string(),+ clientSecret: z.string(),++ scopes: z.array(z.string()).optional(),+ redirectURI: z.string().optional(),+ tokenUrl: z.string().optional(),+ userInfoUrl: z.string().optional(),+ responseType: z.string().optional(),+ prompt: z.enum(['select_account', 'consent', 'login', 'none']).optional(),+ pkce: booleanishSchema.optional(),+ accessType: z.string().optional(),+ discoveryUrl: z.string().optional(),+ type: z.enum(['oauth2', 'oidc']).optional(),+ authorizationUrl: z.string().optional(),+});export const authConfig = {secret: {@@ -74,6 +96,14 @@ export const authConfig = {env: 'AUTH_PROVIDERS_GOOGLE_CLIENT_SECRET',},},-+ customs: {+ doc: 'The list of custom OAuth providers, as a JSON string, see https://www.better-auth.com/docs/plugins/generic-oauth#configuration for more details',+ schema: z.union([+ z.string().transform(parseJson).pipe(z.array(customOAuthProviderSchema)),+ z.array(customOAuthProviderSchema),+ ]),+ default: [],+ env: 'AUTH_PROVIDERS_CUSTOMS',+ },},} as const satisfies ConfigDefinition;diff --git a/apps/papra-server/src/modules/app/auth/auth.services.ts b/apps/papra-server/src/modules/app/auth/auth.services.tsindex f6076e40..fc3206b4 100644--- a/apps/papra-server/src/modules/app/auth/auth.services.ts+++ b/apps/papra-server/src/modules/app/auth/auth.services.ts@@ -4,6 +4,7 @@ import type { Database } from '../database/database.types';import type { AuthEmailsServices } from './auth.emails.services';import { betterAuth } from 'better-auth';import { drizzleAdapter } from 'better-auth/adapters/drizzle';+import { genericOAuth } from 'better-auth/plugins';import { createLogger } from '../../shared/logger/logger';import { usersTable } from '../../users/users.table';import { getTrustedOrigins } from './auth.models';@@ -105,6 +106,11 @@ export function getAuth({changeEmail: { enabled: false },deleteUser: { enabled: false },},+ plugins: [+ ...(config.auth.providers.customs.length > 0+ ? [genericOAuth({ config: config.auth.providers.customs })]+ : []),+ ],});return {diff --git a/apps/papra-server/src/modules/config/config.models.test.ts b/apps/papra-server/src/modules/config/config.models.test.tsindex c9318d6e..b84535c1 100644--- a/apps/papra-server/src/modules/config/config.models.test.ts+++ b/apps/papra-server/src/modules/config/config.models.test.ts@@ -30,6 +30,7 @@ describe('config models', () => {google: {isEnabled: false,},+ customs: [],},},documents: {@@ -55,6 +56,8 @@ describe('config models', () => {google: {isEnabled: false,},+ customs: [],+},},documents: {diff --git a/apps/papra-server/src/modules/config/config.models.ts b/apps/papra-server/src/modules/config/config.models.tsindex da95adbd..b4ccc116 100644--- a/apps/papra-server/src/modules/config/config.models.ts+++ b/apps/papra-server/src/modules/config/config.models.ts@@ -1,19 +1,32 @@import type { DeepPartial } from '@corentinth/chisels';import type { Config } from './config.types';-import { pick } from 'lodash-es';+import { merge, pick } from 'lodash-es';export function getPublicConfig({ config }: { config: Config }) {- const publicConfig: DeepPartial<Config> = pick(config, [- 'auth.isEmailVerificationRequired',- 'auth.isPasswordResetEnabled',- 'auth.isRegistrationEnabled',- 'auth.showLegalLinksOnAuthPage',- 'auth.providers.github.isEnabled',- 'auth.providers.google.isEnabled',- 'documents.deletedDocumentsRetentionDays',- 'intakeEmails.isEnabled',- 'intakeEmails.emailGenerationDomain',- ]);+ const publicConfig: DeepPartial<Config> = merge(+ pick(config, [+ 'auth.isEmailVerificationRequired',+ 'auth.isPasswordResetEnabled',+ 'auth.isRegistrationEnabled',+ 'auth.showLegalLinksOnAuthPage',+ 'auth.providers.github.isEnabled',+ 'auth.providers.google.isEnabled',+ 'documents.deletedDocumentsRetentionDays',+ 'intakeEmails.isEnabled',+ 'intakeEmails.emailGenerationDomain',+ ]),+ {+ auth: {+ providers: {+ customs: config?.auth?.providers?.customs?.map(custom => pick(custom, [+ 'providerId',+ 'providerName',+ 'providerIconUrl',+ ])) ?? [],+ },+ },+ },+ );return {publicConfig,