The minimalistic document archiving platform.
feat(config): introduce appBaseUrl for overriding client and server base URLs (#405)
Corentin Thomasset3401cfbfdc7e
diff --git a/.changeset/easy-lions-talk.md b/.changeset/easy-lions-talk.mdnew file mode 100644index 00000000..3ab03dce--- /dev/null+++ b/.changeset/easy-lions-talk.md@@ -0,0 +1,7 @@+---+"@papra/app-server": patch+"@papra/docs": patch+"@papra/app-client": patch+---++Introduce APP_BASE_URL to mutualize server and client base urldiff --git a/apps/docs/src/content/docs/02-self-hosting/03-configuration.mdx b/apps/docs/src/content/docs/02-self-hosting/03-configuration.mdxindex a6dcd10a..b3391a93 100644--- a/apps/docs/src/content/docs/02-self-hosting/03-configuration.mdx+++ b/apps/docs/src/content/docs/02-self-hosting/03-configuration.mdx@@ -11,6 +11,19 @@ import { Code } from '@astrojs/starlight/components';Configuring your self hosted Papra allows you to customize the application to better suit your environment and requirements. This guide covers the key environment variables you can set to control various aspects of the application, including port settings, security options, and storage configurations.+## Complete .env++Here is the full configuration file that you can use to configure Papra. The variables values are the default values.++<Code code={fullDotEnv} language="env" title=".env" />++## Configuration variables++Here is the complete list of configuration variables that you can use to configure Papra. You can set these variables in the `.env` file or pass them as environment variables when running the Docker container.++<Fragment set:html={sectionsHtml} />++## Configuration filesYou can configure Papra using standard environment variables or use some configuration files.@@ -71,17 +84,4 @@ Example of configuration files:</Tabs>-You'll find the complete list of configuration variables with their environment variables equivalents and path for files in the next section.--## Complete .env--Here is the full configuration file that you can use to configure Papra. The variables values are the default values.--<Code code={fullDotEnv} language="env" title=".env" />--## Configuration variables--Here is the complete list of configuration variables that you can use to configure Papra. You can set these variables in the `.env` file or pass them as environment variables when running the Docker container.--<Fragment set:html={sectionsHtml} />-+You'll find the complete list of configuration variables with their environment variables equivalents and path for files in the previous section.\ No newline at end of filediff --git a/apps/docs/src/docker-compose-generator/dc-generator.astro b/apps/docs/src/docker-compose-generator/dc-generator.astroindex 29a9292f..cdf91c3a 100644--- a/apps/docs/src/docker-compose-generator/dc-generator.astro+++ b/apps/docs/src/docker-compose-generator/dc-generator.astro@@ -16,8 +16,7 @@ services:- 1221:1221environment:- AUTH_SECRET=change-me- - CLIENT_BASE_URL=http://localhost:1221- - SERVER_BASE_URL=http://localhost:1221+ - APP_BASE_URL=http://localhost:1221volumes:- ./app-data:/app/app-datauser: 1000:1000@@ -281,19 +280,14 @@ function getDockerComposeYml() {const intakeEmailEnabled = intakeEmailEnabledSelect.value === 'true';const intakeDriver = intakeDriverSelect.value;const webhookSecret = webhookSecretInput.value;- const appBaseUrl = appBaseUrlInput.value.trim();+ const appBaseUrl = appBaseUrlInput.value.trim() || `http://localhost:${port}`;const version = isRootless ? 'latest' : 'latest-root';const fullImage = `${image}:${version}`;- // Determine base URLs- const clientBaseUrl = appBaseUrl || `http://localhost:${port}`;- const serverBaseUrl = appBaseUrl || `http://localhost:${port}`;-const environment = [`AUTH_SECRET=${authSecret}`,- `CLIENT_BASE_URL=${clientBaseUrl}`,- `SERVER_BASE_URL=${serverBaseUrl}`,+ `APP_BASE_URL=${appBaseUrl}`,isIngestionEnabled && 'INGESTION_FOLDER_IS_ENABLED=true',intakeEmailEnabled && 'INTAKE_EMAILS_IS_ENABLED=true',intakeEmailEnabled && `INTAKE_EMAILS_DRIVER=${intakeDriver}`,diff --git a/apps/papra-server/src/modules/app/auth/auth.models.test.ts b/apps/papra-server/src/modules/app/auth/auth.models.test.tsindex ebae37d9..3bc8b226 100644--- a/apps/papra-server/src/modules/app/auth/auth.models.test.ts+++ b/apps/papra-server/src/modules/app/auth/auth.models.test.ts@@ -46,6 +46,32 @@ describe('auth models', () => {'http://localhost:3002',]);});++ test('if the app baseUrl is set, it should be used instead of the client baseUrl', () => {+ const config = {+ appBaseUrl: 'https://papra.app',+ client: {+ baseUrl: 'http://localhost:3000',+ },+ server: {+ trustedOrigins: [+ 'http://localhost:3000',+ 'http://localhost:3001',+ 'http://localhost:3001',+ 'http://localhost:3002',+ ],+ },+ } as Config;++ const { trustedOrigins } = getTrustedOrigins({ config });++ expect(trustedOrigins).to.deep.equal([+ 'https://papra.app',+ 'http://localhost:3000',+ 'http://localhost:3001',+ 'http://localhost:3002',+ ]);+ });});describe('checkAuthentication', () => {diff --git a/apps/papra-server/src/modules/app/auth/auth.models.ts b/apps/papra-server/src/modules/app/auth/auth.models.tsindex 66e403dd..be42b15e 100644--- a/apps/papra-server/src/modules/app/auth/auth.models.ts+++ b/apps/papra-server/src/modules/app/auth/auth.models.ts@@ -3,6 +3,7 @@ import type { Config } from '../../config/config.types';import type { Context } from '../server.types';import type { Session } from './auth.types';import { uniq } from 'lodash-es';+import { getClientBaseUrl } from '../../config/config.models';import { createError } from '../../shared/errors/errors';import { isNil } from '../../shared/utils';@@ -32,11 +33,11 @@ export function getSession({ context }: { context: Context }) {}export function getTrustedOrigins({ config }: { config: Config }) {- const { baseUrl } = config.client;+ const { clientBaseUrl } = getClientBaseUrl({ config });const { trustedOrigins } = config.server;return {- trustedOrigins: uniq([baseUrl, ...trustedOrigins]),+ trustedOrigins: uniq([clientBaseUrl, ...trustedOrigins]),};}diff --git a/apps/papra-server/src/modules/app/auth/auth.services.ts b/apps/papra-server/src/modules/app/auth/auth.services.tsindex 185eff8e..95dcbedf 100644--- a/apps/papra-server/src/modules/app/auth/auth.services.ts+++ b/apps/papra-server/src/modules/app/auth/auth.services.ts@@ -5,6 +5,7 @@ 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 { getServerBaseUrl } from '../../config/config.models';import { createLogger } from '../../shared/logger/logger';import { usersTable } from '../../users/users.table';import { getTrustedOrigins } from './auth.models';@@ -28,10 +29,11 @@ export function getAuth({const { secret } = config.auth;const { trustedOrigins } = getTrustedOrigins({ config });+ const { serverBaseUrl } = getServerBaseUrl({ config });const auth = betterAuth({secret,- baseURL: config.server.baseUrl,+ baseURL: serverBaseUrl,trustedOrigins,logger: {disabled: false,diff --git a/apps/papra-server/src/modules/app/server.routes.test.ts b/apps/papra-server/src/modules/app/server.routes.test.tsindex f2c59057..cbbfce8d 100644--- a/apps/papra-server/src/modules/app/server.routes.test.ts+++ b/apps/papra-server/src/modules/app/server.routes.test.ts@@ -1,5 +1,6 @@import { inspectRoutes } from 'hono/dev';import { describe, expect, test } from 'vitest';+import { overrideConfig } from '../config/config.test-utils';import { createInMemoryDatabase } from './database/database.test-utils';import { createServer } from './server';@@ -27,7 +28,7 @@ function setValidParams(path: string) {describe('server routes', () => {test('all routes should respond with a 401 when non-authenticated, except for public and auth-related routes', async () => {const { db } = await createInMemoryDatabase();- const { app } = await createServer({ db });+ const { app } = await createServer({ db, config: overrideConfig() });const publicRoutes = ['GET /api/ping',diff --git a/apps/papra-server/src/modules/config/config.models.test.ts b/apps/papra-server/src/modules/config/config.models.test.tsindex bae0e240..5c44a8e8 100644--- a/apps/papra-server/src/modules/config/config.models.test.ts+++ b/apps/papra-server/src/modules/config/config.models.test.ts@@ -1,7 +1,7 @@import type { DeepPartial } from '@corentinth/chisels';import type { Config } from './config.types';import { describe, expect, test } from 'vitest';-import { getPublicConfig } from './config.models';+import { getClientBaseUrl, getPublicConfig, getServerBaseUrl } from './config.models';import { overrideConfig } from './config.test-utils';describe('config models', () => {@@ -73,4 +73,20 @@ describe('config models', () => {});});});++ describe('getServerBaseUrl', () => {+ test('use the generic baseUrl if set, otherwise use the server baseUrl', () => {+ expect(getServerBaseUrl({ config: { appBaseUrl: 'https://papra.app' } as Config })).to.eql({ serverBaseUrl: 'https://papra.app' });+ expect(getServerBaseUrl({ config: { server: { baseUrl: 'http://localhost:1221' } } as Config })).to.eql({ serverBaseUrl: 'http://localhost:1221' });+ expect(getServerBaseUrl({ config: { appBaseUrl: 'https://papra.app', server: { baseUrl: 'http://localhost:1221' } } as Config })).to.eql({ serverBaseUrl: 'https://papra.app' });+ });+ });++ describe('getClientBaseUrl', () => {+ test('use the generic baseUrl if set, otherwise use the client baseUrl', () => {+ expect(getClientBaseUrl({ config: { appBaseUrl: 'https://papra.app' } as Config })).to.eql({ clientBaseUrl: 'https://papra.app' });+ expect(getClientBaseUrl({ config: { client: { baseUrl: 'http://localhost:3000' } } as Config })).to.eql({ clientBaseUrl: 'http://localhost:3000' });+ expect(getClientBaseUrl({ config: { appBaseUrl: 'https://papra.app', client: { baseUrl: 'http://localhost:3000' } } as Config })).to.eql({ clientBaseUrl: 'https://papra.app' });+ });+ });});diff --git a/apps/papra-server/src/modules/config/config.models.ts b/apps/papra-server/src/modules/config/config.models.tsindex 321e1f6e..72bb14e5 100644--- a/apps/papra-server/src/modules/config/config.models.ts+++ b/apps/papra-server/src/modules/config/config.models.ts@@ -32,3 +32,15 @@ export function getPublicConfig({ config }: { config: Config }) {publicConfig,};}++export function getServerBaseUrl({ config }: { config: Config }) {+ return {+ serverBaseUrl: config.appBaseUrl ?? config.server.baseUrl,+ };+}++export function getClientBaseUrl({ config }: { config: Config }) {+ return {+ clientBaseUrl: config.appBaseUrl ?? config.client.baseUrl,+ };+}diff --git a/apps/papra-server/src/modules/config/config.ts b/apps/papra-server/src/modules/config/config.tsindex 65485aa4..f0a0d327 100644--- a/apps/papra-server/src/modules/config/config.ts+++ b/apps/papra-server/src/modules/config/config.ts@@ -27,9 +27,15 @@ export const configDefinition = {default: 'development',env: 'NODE_ENV',},+ appBaseUrl: {+ doc: 'The base URL of the application. Will override the client baseUrl and server baseUrl when set. Use this one over the client and server baseUrl when the server is serving the client assets (like in docker).',+ schema: z.string().url().optional(),+ env: 'APP_BASE_URL',+ default: undefined,+ },client: {baseUrl: {- doc: 'The URL of the client, when using docker, it should be the same as the server baseUrl',+ doc: 'The URL of the client, when using docker, prefer using the `APP_BASE_URL` environment variable instead.',schema: z.string().url(),default: 'http://localhost:3000',env: 'CLIENT_BASE_URL',@@ -37,7 +43,7 @@ export const configDefinition = {},server: {baseUrl: {- doc: 'The base URL of the server, when using docker, it should be the same as the client baseUrl',+ doc: 'The base URL of the server, when using docker, prefer using the `APP_BASE_URL` environment variable instead.',schema: z.string().url(),default: 'http://localhost:1221',env: 'SERVER_BASE_URL',diff --git a/apps/papra-server/src/modules/intake-emails/drivers/owlrelay/owlrelay.intake-email-driver.ts b/apps/papra-server/src/modules/intake-emails/drivers/owlrelay/owlrelay.intake-email-driver.tsindex 3063c29c..cbcf5301 100644--- a/apps/papra-server/src/modules/intake-emails/drivers/owlrelay/owlrelay.intake-email-driver.ts+++ b/apps/papra-server/src/modules/intake-emails/drivers/owlrelay/owlrelay.intake-email-driver.ts@@ -1,6 +1,7 @@import { buildUrl, safely } from '@corentinth/chisels';import { generateId as generateHumanReadableId } from '@corentinth/friendly-ids';import { createClient } from '@owlrelay/api-sdk';+import { getServerBaseUrl } from '../../../config/config.models';import { createLogger } from '../../../shared/logger/logger';import { INTAKE_EMAILS_INGEST_ROUTE } from '../../intake-emails.constants';import { buildEmailAddress } from '../../intake-emails.models';@@ -11,7 +12,7 @@ export const OWLRELAY_INTAKE_EMAIL_DRIVER_NAME = 'owlrelay';const logger = createLogger({ namespace: 'intake-emails.drivers.owlrelay' });export const owlrelayIntakeEmailDriverFactory = defineIntakeEmailDriver(({ config }) => {- const { baseUrl } = config.server;+ const { serverBaseUrl } = getServerBaseUrl({ config });const { webhookSecret } = config.intakeEmails;const { owlrelayApiKey, webhookUrl: configuredWebhookUrl } = config.intakeEmails.drivers.owlrelay;@@ -19,7 +20,7 @@ export const owlrelayIntakeEmailDriverFactory = defineIntakeEmailDriver(({ confiapiKey: owlrelayApiKey,});- const webhookUrl = configuredWebhookUrl ?? buildUrl({ baseUrl, path: INTAKE_EMAILS_INGEST_ROUTE });+ const webhookUrl = configuredWebhookUrl ?? buildUrl({ baseUrl: serverBaseUrl, path: INTAKE_EMAILS_INGEST_ROUTE });return {name: OWLRELAY_INTAKE_EMAIL_DRIVER_NAME,diff --git a/apps/papra-server/src/modules/organizations/organizations.usecases.ts b/apps/papra-server/src/modules/organizations/organizations.usecases.tsindex 43671ff4..1b38315b 100644--- a/apps/papra-server/src/modules/organizations/organizations.usecases.ts+++ b/apps/papra-server/src/modules/organizations/organizations.usecases.ts@@ -11,6 +11,7 @@ import type { OrganizationRole } from './organizations.types';import { buildUrl } from '@corentinth/chisels';import { addDays } from 'date-fns';import { createForbiddenError } from '../app/auth/auth.errors';+import { getClientBaseUrl } from '../config/config.models';import { getOrganizationPlan } from '../plans/plans.usecases';import { sanitize } from '../shared/html/html';import { createLogger } from '../shared/logger/logger';@@ -302,13 +303,14 @@ export async function sendOrganizationInvitationEmail({config: Config;}) {const { organization } = await organizationsRepository.getOrganizationById({ organizationId });+ const { clientBaseUrl } = getClientBaseUrl({ config });if (!organization) {throw createOrganizationNotFoundError();}const invitationLink = buildUrl({- baseUrl: config.client.baseUrl,+ baseUrl: clientBaseUrl,path: '/invitations',});diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.services.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.services.tsindex d298a445..32866753 100644--- a/apps/papra-server/src/modules/subscriptions/subscriptions.services.ts+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.services.ts@@ -2,6 +2,7 @@ import type { Buffer } from 'node:buffer';import type { Config } from '../config/config.types';import { buildUrl, injectArguments } from '@corentinth/chisels';import Stripe from 'stripe';+import { getClientBaseUrl } from '../config/config.models';export type SubscriptionsServices = ReturnType<typeof createSubscriptionsServices>;@@ -47,10 +48,10 @@ export async function createCheckoutUrl({seatsCount: number;config: Config;}) {- const { baseUrl } = config.client;+ const { clientBaseUrl } = getClientBaseUrl({ config });- const successUrl = buildUrl({ baseUrl, path: '/checkout-success?sessionId={CHECKOUT_SESSION_ID}' });- const cancelUrl = buildUrl({ baseUrl, path: '/checkout-cancel' });+ const successUrl = buildUrl({ baseUrl: clientBaseUrl, path: '/checkout-success?sessionId={CHECKOUT_SESSION_ID}' });+ const cancelUrl = buildUrl({ baseUrl: clientBaseUrl, path: '/checkout-cancel' });const session = await stripeClient.checkout.sessions.create({customer: customerId,@@ -80,16 +81,18 @@ async function getCustomerPortalUrl({stripeClient,customerId,config,- returnUrl = config.client.baseUrl,+ returnUrl,}: {stripeClient: Stripe;customerId: string;returnUrl?: string;config: Config;}) {+ const { clientBaseUrl } = getClientBaseUrl({ config });+const session = await stripeClient.billingPortal.sessions.create({customer: customerId,- return_url: returnUrl,+ return_url: returnUrl ?? clientBaseUrl,});return { customerPortalUrl: session.url };diff --git a/apps/papra-server/src/scripts/send-intake-email.script.ts b/apps/papra-server/src/scripts/send-intake-email.script.tsindex 7cbf299e..57535e64 100644--- a/apps/papra-server/src/scripts/send-intake-email.script.ts+++ b/apps/papra-server/src/scripts/send-intake-email.script.ts@@ -1,15 +1,16 @@import { buildUrl } from '@corentinth/chisels';import { triggerWebhook } from '@owlrelay/webhook';+import { getServerBaseUrl } from '../modules/config/config.models';import { INTAKE_EMAILS_INGEST_ROUTE } from '../modules/intake-emails/intake-emails.constants';import { runScript } from './commons/run-script';await runScript({ scriptName: 'simulate-intake-email' },async ({ config }) => {- const { baseUrl } = config.server;+ const { serverBaseUrl } = getServerBaseUrl({ config });const { webhookSecret } = config.intakeEmails;- const webhookUrl = buildUrl({ baseUrl, path: INTAKE_EMAILS_INGEST_ROUTE });+ const webhookUrl = buildUrl({ baseUrl: serverBaseUrl, path: INTAKE_EMAILS_INGEST_ROUTE });await triggerWebhook({webhookUrl,