Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

refactor(validation): migrated from zod to valibot for the app config validation (#984)

Corentin Thomasset8fe222bb8f99
diff --git a/.changeset/wise-pugs-add.md b/.changeset/wise-pugs-add.md
new file mode 100644
index 00000000..daa4fc06
--- /dev/null
+++ b/.changeset/wise-pugs-add.md
@@ -0,0 +1,9 @@
+---
+"@papra/app": patch
+---
+
+Switched the app configuration validation library to `valibot`. Config validation is now a bit stricter, with slightly different error messages.
+
+- Boolean env variables previously considered non-truthy values as `false`. Now they will throw a validation error if the value is not a valid boolean-ish value
+- `AUTH_PROVIDERS_CUSTOMS` json parsing now accepts only valid boolean values for the `pkce` property, while before it accepted any non-true value as `false`
+- Stricter `AUTH_FORBIDDEN_EMAIL_DOMAINS` domain validation
\ No newline at end of file
diff --git a/apps/papra-server/package.json b/apps/papra-server/package.json
index cb4907b9..9ac6189d 100644
--- a/apps/papra-server/package.json
+++ b/apps/papra-server/package.json
@@ -84,6 +84,7 @@
"sanitize-html": "^2.17.0",
"stripe": "^17.7.0",
"tsx": "catalog:",
+ "valibot": "catalog:",
"zod": "^3.25.67"
},
"devDependencies": {
diff --git a/apps/papra-server/src/modules/app/auth/auth.config.schemas.test.ts b/apps/papra-server/src/modules/app/auth/auth.config.schemas.test.ts
new file mode 100644
index 00000000..ea874fb1
--- /dev/null
+++ b/apps/papra-server/src/modules/app/auth/auth.config.schemas.test.ts
@@ -0,0 +1,67 @@
+import * as v from 'valibot';
+import { describe, expect, test } from 'vitest';
+import { forbiddenEmailDomainsSchema } from './auth.config.schemas';
+
+describe('auth config schemas', () => {
+ describe('forbiddenEmailDomainsSchema', () => {
+ test('create a set of domain from a comma separated string or an array of strings', () => {
+ expect(v.parse(
+ forbiddenEmailDomainsSchema,
+ 'example.com, test.com',
+ )).to.eql(new Set(['example.com', 'test.com']));
+
+ expect(v.parse(
+ forbiddenEmailDomainsSchema,
+ ['example.com', 'test.com'],
+ )).to.eql(new Set(['example.com', 'test.com']));
+ });
+
+ test('the domains are trimmed and lowercased', () => {
+ expect(v.parse(
+ forbiddenEmailDomainsSchema,
+ ' Example.com , TEST.com ',
+ )).to.eql(new Set(['example.com', 'test.com']));
+
+ expect(v.parse(
+ forbiddenEmailDomainsSchema,
+ [' Example.com ', ' TEST.com '],
+ )).to.eql(new Set(['example.com', 'test.com']));
+ });
+
+ test('empty domains are filtered out', () => {
+ expect(v.parse(
+ forbiddenEmailDomainsSchema,
+ 'example.com, , test.com, ',
+ )).to.eql(new Set(['example.com', 'test.com']));
+
+ expect(v.parse(
+ forbiddenEmailDomainsSchema,
+ ['example.com', '', 'test.com', ' '],
+ )).to.eql(new Set(['example.com', 'test.com']));
+ });
+
+ test('duplicate domains are removed', () => {
+ expect(v.parse(
+ forbiddenEmailDomainsSchema,
+ 'example.com, test.com, example.com',
+ )).to.eql(new Set(['example.com', 'test.com']));
+
+ expect(v.parse(
+ forbiddenEmailDomainsSchema,
+ ['example.com', 'test.com', 'example.com'],
+ )).to.eql(new Set(['example.com', 'test.com']));
+ });
+
+ test('invalid domains are rejected', () => {
+ expect(() => v.parse(
+ forbiddenEmailDomainsSchema,
+ 'example.com, inVAlid-domain, test.com',
+ )).to.throw('Invalid domain: Received "invalid-domain"');
+
+ expect(() => v.parse(
+ forbiddenEmailDomainsSchema,
+ ['@example.com'],
+ )).to.throw('Invalid domain: Received "@example.com"');
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/app/auth/auth.config.schemas.ts b/apps/papra-server/src/modules/app/auth/auth.config.schemas.ts
new file mode 100644
index 00000000..20935e3e
--- /dev/null
+++ b/apps/papra-server/src/modules/app/auth/auth.config.schemas.ts
@@ -0,0 +1,10 @@
+import * as v from 'valibot';
+
+export const forbiddenEmailDomainsSchema = v.pipe(
+ v.union([
+ v.pipe(v.string(), v.transform(value => value.split(','))),
+ v.array(v.string()),
+ ]),
+ v.transform(value => new Set(value.map(v => v.trim().toLowerCase()).filter(v => v.length > 0))),
+ v.set(v.pipe(v.string(), v.domain())),
+);
diff --git a/apps/papra-server/src/modules/app/auth/auth.config.ts b/apps/papra-server/src/modules/app/auth/auth.config.ts
index e76c6f85..13f56f8b 100644
--- a/apps/papra-server/src/modules/app/auth/auth.config.ts
+++ b/apps/papra-server/src/modules/app/auth/auth.config.ts
@@ -1,34 +1,37 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
-import { booleanishSchema } from '../../config/config.schemas';
-import { parseJson } from '../../intake-emails/intake-emails.schemas';
+import * as v from 'valibot';
+import { booleanishSchema, urlSchema } from '../../config/config.schemas';
+import { forbiddenEmailDomainsSchema } from './auth.config.schemas';
import { DEFAULT_AUTH_SECRET } from './auth.constants';
-const customOAuthProviderSchema = z.object({
- providerId: z.string(),
- providerName: z.string(),
- providerIconUrl: z.string().url().optional(),
+const customOAuthProviderSchema = v.object({
+ providerId: v.string(),
+ providerName: v.string(),
+ providerIconUrl: v.optional(urlSchema),
- clientId: z.string(),
- clientSecret: z.string(),
+ clientId: v.string(),
+ clientSecret: v.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(),
+ scopes: v.optional(v.array(v.string())),
+ redirectURI: v.optional(v.string()),
+ tokenUrl: v.optional(v.string()),
+ userInfoUrl: v.optional(v.string()),
+ responseType: v.optional(v.string()),
+ prompt: v.optional(v.picklist(['select_account', 'consent', 'login', 'none'])),
+ pkce: v.optional(v.boolean()),
+ accessType: v.optional(v.string()),
+ discoveryUrl: v.optional(v.string()),
+ type: v.optional(v.picklist(['oauth2', 'oidc'])),
+ authorizationUrl: v.optional(v.string()),
});
export const authConfig = {
secret: {
doc: 'The secret for the auth, it should be at least 32 characters long, you can generate a secure one using `openssl rand -hex 48`',
- schema: z.string({ required_error: 'Please provide an auth secret using the AUTH_SECRET environment variable, you can use `openssl rand -hex 48` to generate a secure one' }).min(32),
+ schema: v.pipe(
+ v.string('Please provide an auth secret using the AUTH_SECRET environment variable, you can use `openssl rand -hex 48` to generate a secure one'),
+ v.minLength(32),
+ ),
default: DEFAULT_AUTH_SECRET,
env: 'AUTH_SECRET',
},
@@ -66,23 +69,16 @@ export const authConfig = {
doc: `The header, or comma separated list of headers, to use to get the real IP address of the user, use for rate limiting. Make sur to use a non-spoofable header, one set by your proxy.
- If behind a standard proxy, you might want to set this to "x-forwarded-for".
- If behind Cloudflare, you might want to set this to "cf-connecting-ip".`,
- schema: z.union([
- z.string(),
- z.array(z.string()),
- ]).transform(value => (typeof value === 'string' ? value.split(',').map(v => v.trim()) : value)),
+ schema: v.union([
+ v.pipe(v.string(), v.transform(value => value.split(',').map(v => v.trim()))),
+ v.array(v.string()),
+ ]),
default: ['x-forwarded-for'],
env: 'AUTH_IP_ADDRESS_HEADERS',
},
forbiddenEmailDomains: {
doc: 'A comma separated list of email domains that are forbidden for registration (e.g. "foo.com,bar.com"), if set, it will override the default forbidden domains.',
- schema: z.union([
- z.string(),
- z.array(z.string()),
- ]).transform((value) => {
- const asArray = typeof value === 'string' ? value.split(',') : value;
- const cleaned = asArray.map(v => v.trim().toLowerCase()).filter(v => v.length > 0);
- return new Set(cleaned);
- }),
+ schema: forbiddenEmailDomainsSchema,
default: ['papra.app', 'papra.email', 'owlrelay.email', 'callback.email', 'clb.email'],
env: 'AUTH_FORBIDDEN_EMAIL_DOMAINS',
},
@@ -104,13 +100,13 @@ export const authConfig = {
},
clientId: {
doc: 'The client id for Github OAuth',
- schema: z.string(),
+ schema: v.string(),
default: 'set-me',
env: 'AUTH_PROVIDERS_GITHUB_CLIENT_ID',
},
clientSecret: {
doc: 'The client secret for Github OAuth',
- schema: z.string(),
+ schema: v.string(),
default: 'set-me',
env: 'AUTH_PROVIDERS_GITHUB_CLIENT_SECRET',
},
@@ -124,22 +120,22 @@ export const authConfig = {
},
clientId: {
doc: 'The client id for Google OAuth',
- schema: z.string(),
+ schema: v.string(),
default: 'set-me',
env: 'AUTH_PROVIDERS_GOOGLE_CLIENT_ID',
},
clientSecret: {
doc: 'The client secret for Google OAuth',
- schema: z.string(),
+ schema: v.string(),
default: 'set-me',
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),
+ schema: v.union([
+ v.pipe(v.string(), v.parseJson(), v.array(customOAuthProviderSchema)),
+ v.array(customOAuthProviderSchema),
]),
default: [],
env: 'AUTH_PROVIDERS_CUSTOMS',
diff --git a/apps/papra-server/src/modules/app/database/database.config.ts b/apps/papra-server/src/modules/app/database/database.config.ts
index 1b40eb46..821ed9dd 100644
--- a/apps/papra-server/src/modules/app/database/database.config.ts
+++ b/apps/papra-server/src/modules/app/database/database.config.ts
@@ -1,22 +1,23 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import * as v from 'valibot';
+import { urlSchema } from '../../config/config.schemas';
export const databaseConfig = {
url: {
doc: 'The URL of the database (default as "file:./app-data/db/db.sqlite" when using docker)',
- schema: z.string().url(),
+ schema: urlSchema,
default: 'file:./db.sqlite',
env: 'DATABASE_URL',
},
authToken: {
doc: 'The auth token for the database',
- schema: z.string().optional(),
+ schema: v.optional(v.string()),
default: undefined,
env: 'DATABASE_AUTH_TOKEN',
},
encryptionKey: {
doc: 'The encryption key for the database. If not provided, the database will not be encrypted at rest. Use with caution as if lost, the data will be unrecoverable.',
- schema: z.string().optional(),
+ schema: v.optional(v.string()),
default: undefined,
env: 'DATABASE_ENCRYPTION_KEY',
},
diff --git a/apps/papra-server/src/modules/config/config.schemas.test.ts b/apps/papra-server/src/modules/config/config.schemas.test.ts
index ec183ba0..934b7adf 100644
--- a/apps/papra-server/src/modules/config/config.schemas.test.ts
+++ b/apps/papra-server/src/modules/config/config.schemas.test.ts
@@ -1,38 +1,38 @@
+import * as v from 'valibot';
import { describe, expect, test } from 'vitest';
-import { booleanishSchema, trustedAppSchemeSchema, trustedOriginsSchema } from './config.schemas';
+import { appSchemeSchema, booleanishSchema, coercedUrlListSchema } from './config.schemas';
describe('config schemas', () => {
describe('booleanishSchema', () => {
- test('a zod schema that validates and coerces a string to a boolean, used in the config where we accept env variables and pojo values', () => {
- expect(booleanishSchema.parse(true)).toBe(true);
- expect(booleanishSchema.parse('true')).toBe(true);
- expect(booleanishSchema.parse('TRUE')).toBe(true);
- expect(booleanishSchema.parse('True')).toBe(true);
- expect(booleanishSchema.parse(' True ')).toBe(true);
- expect(booleanishSchema.parse('1')).toBe(true);
- expect(booleanishSchema.parse(1)).toBe(true);
+ test('validates and coerces a string to a boolean, used in the config where we accept env variables or js values', () => {
+ expect(v.parse(booleanishSchema, true)).toBe(true);
+ expect(v.parse(booleanishSchema, 'true')).toBe(true);
+ expect(v.parse(booleanishSchema, 'TRUE')).toBe(true);
+ expect(v.parse(booleanishSchema, 'True')).toBe(true);
+ expect(v.parse(booleanishSchema, ' True ')).toBe(true);
+ expect(v.parse(booleanishSchema, '1')).toBe(true);
- expect(booleanishSchema.parse('false')).toBe(false);
- expect(booleanishSchema.parse('FALSE')).toBe(false);
- expect(booleanishSchema.parse('False')).toBe(false);
- expect(booleanishSchema.parse(' False ')).toBe(false);
- expect(booleanishSchema.parse(false)).toBe(false);
- expect(booleanishSchema.parse('foo')).toBe(false);
- expect(booleanishSchema.parse('0')).toBe(false);
- expect(booleanishSchema.parse(-1)).toBe(false);
- expect(booleanishSchema.parse(0)).toBe(false);
- expect(booleanishSchema.parse(2)).toBe(false);
+ expect(v.parse(booleanishSchema, 'false')).toBe(false);
+ expect(v.parse(booleanishSchema, 'FALSE')).toBe(false);
+ expect(v.parse(booleanishSchema, 'False')).toBe(false);
+ expect(v.parse(booleanishSchema, ' False ')).toBe(false);
+ expect(v.parse(booleanishSchema, false)).toBe(false);
+ expect(v.parse(booleanishSchema, '0')).toBe(false);
+
+ expect(() => v.parse(booleanishSchema, 'foo')).toThrow('Expected a boolean or a string that can be parsed as a boolean');
+ expect(() => v.parse(booleanishSchema, 1)).toThrow('Expected a boolean or a string that can be parsed as a boolean');
+ expect(() => v.parse(booleanishSchema, 2)).toThrow('Expected a boolean or a string that can be parsed as a boolean');
});
});
- describe('trustedOriginsSchema', () => {
+ describe('coercedUrlListSchema', () => {
test('this schema validates and coerces a comma separated string to an array of urls', () => {
- expect(trustedOriginsSchema.parse('http://localhost:3000')).toEqual(['http://localhost:3000']);
- expect(trustedOriginsSchema.parse('http://localhost:3000,http://localhost:3001')).toEqual([
+ expect(v.parse(coercedUrlListSchema, 'http://localhost:3000')).toEqual(['http://localhost:3000']);
+ expect(v.parse(coercedUrlListSchema, 'http://localhost:3000,http://localhost:3001')).toEqual([
'http://localhost:3000',
'http://localhost:3001',
]);
- expect(trustedOriginsSchema.parse([
+ expect(v.parse(coercedUrlListSchema, [
'http://localhost:3000',
'http://localhost:3001',
])).toEqual([
@@ -42,22 +42,14 @@ describe('config schemas', () => {
});
test('otherwise it throws an error', () => {
- expect(() => trustedOriginsSchema.parse('non-url')).toThrow();
+ expect(() => v.parse(coercedUrlListSchema, 'non-url')).toThrow();
});
});
- describe('trustedAppSchemeSchema', () => {
- test('validates app schemes ending with ://', () => {
- expect(trustedAppSchemeSchema.parse('papra://')).toBe('papra://');
- expect(trustedAppSchemeSchema.parse('exp://')).toBe('exp://');
- expect(trustedAppSchemeSchema.parse('my-app+test://')).toBe('my-app+test://');
-
- expect(() => trustedAppSchemeSchema.parse('invalid-scheme')).toThrow();
- expect(() => trustedAppSchemeSchema.parse('http:/')).toThrow();
- expect(() => trustedAppSchemeSchema.parse('papra://foo')).toThrow();
- expect(() => trustedAppSchemeSchema.parse('papra-://')).toThrow();
- expect(() => trustedAppSchemeSchema.parse('papra+://')).toThrow();
- expect(() => trustedAppSchemeSchema.parse('://')).toThrow();
+ describe('appSchemeSchema', () => {
+ test('the app scheme can either be a comma separated string or an array of strings', () => {
+ expect(v.parse(appSchemeSchema, 'papra://,exp://')).toEqual(['papra://', 'exp://']);
+ expect(v.parse(appSchemeSchema, ['papra://', 'exp://'])).toEqual(['papra://', 'exp://']);
});
});
});
diff --git a/apps/papra-server/src/modules/config/config.schemas.ts b/apps/papra-server/src/modules/config/config.schemas.ts
index eb28fcd3..6b86cb07 100644
--- a/apps/papra-server/src/modules/config/config.schemas.ts
+++ b/apps/papra-server/src/modules/config/config.schemas.ts
@@ -1,23 +1,35 @@
-import { z } from 'zod';
+import * as v from 'valibot';
-export const booleanishSchema = z
- .coerce
- .string()
- .trim()
- .toLowerCase()
- .transform(x => ['true', '1'].includes(x))
- .pipe(z.boolean());
+export const urlSchema = v.pipe(
+ v.string(),
+ v.url(),
+);
-export const trustedOriginsSchema = z.union([
- z.array(z.string().url()),
- z.string().transform(value => value.split(',')).pipe(z.array(z.string().url())),
+export const coercedUrlListSchema = v.union([
+ v.array(urlSchema),
+ v.pipe(
+ v.string(),
+ v.transform(value => value.split(',')),
+ v.array(urlSchema),
+ ),
]);
-export const trustedAppSchemeSchema = z.string().regex(/^[a-z][a-z0-9+.-]*[a-z0-9]:\/\/$/i, {
- message: 'Invalid scheme format. Must end with ://, like "papra://"',
-});
+export const booleanishSchema = v.union(
+ [
+ v.boolean(),
+ v.pipe(
+ v.string(),
+ v.trim(),
+ v.parseBoolean(),
+ ),
+ ],
+ 'Expected a boolean or a string that can be parsed as a boolean (e.g. "true", "false", "1", "0")',
+);
-export const trustedAppSchemesSchema = z.union([
- z.array(trustedAppSchemeSchema),
- z.string().transform(value => value.split(',')).pipe(z.array(trustedAppSchemeSchema)),
+export const appSchemeSchema = v.union([
+ v.pipe(
+ v.string(),
+ v.transform(value => value.split(',')),
+ ),
+ v.array(v.string()),
]);
diff --git a/apps/papra-server/src/modules/config/config.ts b/apps/papra-server/src/modules/config/config.ts
index d066ceda..14b7f991 100644
--- a/apps/papra-server/src/modules/config/config.ts
+++ b/apps/papra-server/src/modules/config/config.ts
@@ -3,7 +3,7 @@ import process from 'node:process';
import { memoizeOnce, safelySync } from '@corentinth/chisels';
import { loadConfig } from 'c12';
import { defineConfig } from 'figue';
-import { z } from 'zod';
+import * as v from 'valibot';
import { authConfig } from '../app/auth/auth.config';
import { ensureAuthSecretIsNotDefaultInProduction } from '../app/auth/auth.config.models';
import { databaseConfig } from '../app/database/database.config';
@@ -17,58 +17,58 @@ import { intakeEmailsConfig } from '../intake-emails/intake-emails.config';
import { organizationsConfig } from '../organizations/organizations.config';
import { organizationPlansConfig } from '../plans/plans.config';
import { createLogger } from '../shared/logger/logger';
+import { coercedPositiveIntegerSchema, strictlyPositiveIntegerSchema } from '../shared/schemas/number.schemas';
import { IN_MS } from '../shared/units';
-import { isString } from '../shared/utils';
import { subscriptionsConfig } from '../subscriptions/subscriptions.config';
import { tagsConfig } from '../tags/tags.config';
import { tasksConfig } from '../tasks/tasks.config';
import { trackingConfig } from '../tracking/tracking.config';
import { exitProcessDueToConfigError, validateParsedConfig } from './config.models';
-import { booleanishSchema, trustedOriginsSchema } from './config.schemas';
+import { appSchemeSchema, booleanishSchema, coercedUrlListSchema, urlSchema } from './config.schemas';
import { getCommitInfo } from './config.usecases';
export const configDefinition = {
env: {
doc: 'The application environment.',
- schema: z.enum(['development', 'production', 'test']),
+ schema: v.picklist(['development', 'production', 'test']),
default: 'development',
env: 'NODE_ENV',
showInDocumentation: false,
},
version: {
doc: 'The application version, used for display in the about page. Set by dockerfile build args during release builds.',
- schema: z.string(),
+ schema: v.string(),
default: 'dev',
env: 'PAPRA_VERSION',
},
gitCommitSha: {
doc: 'The git commit hash, used for display in the about page. Set by dockerfile build args during release builds.',
- schema: z.string(),
+ schema: v.string(),
default: 'unknown',
env: 'GIT_COMMIT',
},
gitCommitDate: {
doc: 'The git commit date (ISO 8601 format), used for display in the about page. Set by dockerfile build args during release builds.',
- schema: z.string(),
+ schema: v.string(),
default: 'unknown',
env: 'BUILD_DATE',
},
processMode: {
doc: 'The process mode: "all" runs both web and worker, "web" runs only the API server, "worker" runs only background tasks',
- schema: z.enum(['all', 'web', 'worker']),
+ schema: v.picklist(['all', 'web', 'worker']),
default: 'all',
env: 'PROCESS_MODE',
},
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(),
+ schema: v.optional(urlSchema),
env: 'APP_BASE_URL',
default: undefined,
},
client: {
baseUrl: {
doc: 'The URL of the client, when using docker, prefer using the `APP_BASE_URL` environment variable instead.',
- schema: z.string().url(),
+ schema: urlSchema,
default: 'http://localhost:3000',
env: 'CLIENT_BASE_URL',
},
@@ -76,50 +76,47 @@ export const configDefinition = {
server: {
baseUrl: {
doc: 'The base URL of the server, when using docker, prefer using the `APP_BASE_URL` environment variable instead.',
- schema: z.string().url(),
+ schema: urlSchema,
default: 'http://localhost:1221',
env: 'SERVER_BASE_URL',
},
trustedOrigins: {
doc: 'A comma separated list of origins that are trusted to make requests to the server. The client baseUrl (CLIENT_BASE_URL) is automatically added by default, no need to add it to the list.',
- schema: trustedOriginsSchema,
+ schema: coercedUrlListSchema,
default: [],
env: 'TRUSTED_ORIGINS',
},
trustedAppSchemes: {
doc: 'A comma separated list of app schemes that are trusted for authentication. For example: "papra://,exp://". Note, setting this value will override the default schemes, so make sure to include them if needed.',
- schema: z.union([
- z.array(z.string()),
- z.string().transform(value => value.split(',')),
- ]),
+ schema: appSchemeSchema,
default: ['papra://', 'exp://'],
env: 'TRUSTED_APP_SCHEMES',
},
port: {
doc: 'The port to listen on when using node server',
- schema: z.coerce.number().min(1024).max(65535),
+ schema: v.pipe(coercedPositiveIntegerSchema, v.minValue(1024), v.maxValue(65535)),
default: 1221,
env: 'PORT',
},
hostname: {
doc: 'The hostname to bind to when using node server',
- schema: z.string(),
+ schema: v.string(),
default: '0.0.0.0',
env: 'SERVER_HOSTNAME',
},
defaultRouteTimeoutMs: {
doc: 'The maximum time in milliseconds for a route to complete before timing out',
- schema: z.coerce.number().int().positive(),
+ schema: coercedPositiveIntegerSchema,
default: 20 * IN_MS.SECOND,
env: 'SERVER_API_ROUTES_TIMEOUT_MS',
},
routeTimeouts: {
doc: 'Route-specific timeout overrides. Allows setting different timeouts for specific HTTP method and route paths.',
- schema: z.array(
- z.object({
- method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']),
- route: z.string(),
- timeoutMs: z.number().int().positive(),
+ schema: v.array(
+ v.object({
+ method: v.picklist(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']),
+ route: v.string(),
+ timeoutMs: strictlyPositiveIntegerSchema,
}),
),
default: [
@@ -129,13 +126,11 @@ export const configDefinition = {
timeoutMs: 5 * IN_MS.MINUTE,
},
],
+ showInDocumentation: false, // mainly used for internal overrides
},
corsOrigins: {
doc: 'The CORS origin for the api server',
- schema: z.union([
- z.string(),
- z.array(z.string()),
- ]).transform(value => (isString(value) ? value.split(',') : value)),
+ schema: coercedUrlListSchema,
default: ['http://localhost:3000'],
env: 'SERVER_CORS_ORIGINS',
},
diff --git a/apps/papra-server/src/modules/custom-properties/custom-properties.config.ts b/apps/papra-server/src/modules/custom-properties/custom-properties.config.ts
index 51955412..dbbb1226 100644
--- a/apps/papra-server/src/modules/custom-properties/custom-properties.config.ts
+++ b/apps/papra-server/src/modules/custom-properties/custom-properties.config.ts
@@ -1,10 +1,10 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import { coercedStrictlyPositiveIntegerSchema } from '../shared/schemas/number.schemas';
export const customPropertiesConfig = {
maxCustomPropertiesPerOrganization: {
doc: 'The maximum number of custom property definitions an organization can have',
- schema: z.coerce.number().int().positive(),
+ schema: coercedStrictlyPositiveIntegerSchema,
default: 100,
env: 'MAX_CUSTOM_PROPERTIES_PER_ORGANIZATION',
},
diff --git a/apps/papra-server/src/modules/documents/document-search/document-search.config.ts b/apps/papra-server/src/modules/documents/document-search/document-search.config.ts
index d54dee65..85b6d992 100644
--- a/apps/papra-server/src/modules/documents/document-search/document-search.config.ts
+++ b/apps/papra-server/src/modules/documents/document-search/document-search.config.ts
@@ -1,5 +1,5 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import * as v from 'valibot';
import { DATABASE_FTS5_DOCUMENT_SEARCH_PROVIDER_NAME } from './database-fts5/database-fts5.document-search-provider.constants';
const documentSearchProviderNames = [DATABASE_FTS5_DOCUMENT_SEARCH_PROVIDER_NAME] as const;
@@ -9,6 +9,6 @@ export const documentSearchConfig = {
doc: `The document search provider to use, values can be one of: ${documentSearchProviderNames.map(x => `\`${x}\``).join(', ')}`,
default: DATABASE_FTS5_DOCUMENT_SEARCH_PROVIDER_NAME,
env: 'DOCUMENT_SEARCH_DRIVER',
- schema: z.enum(documentSearchProviderNames),
+ schema: v.picklist(documentSearchProviderNames),
},
} as const satisfies ConfigDefinition;
diff --git a/apps/papra-server/src/modules/documents/documents.config.ts b/apps/papra-server/src/modules/documents/documents.config.ts
index 8f7da465..6bda5b4d 100644
--- a/apps/papra-server/src/modules/documents/documents.config.ts
+++ b/apps/papra-server/src/modules/documents/documents.config.ts
@@ -1,18 +1,19 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import * as v from 'valibot';
import { booleanishSchema } from '../config/config.schemas';
+import { coercedNumberSchema } from '../shared/schemas/number.schemas';
import { ocrLanguagesSchema, stringCoercedOcrLanguagesSchema } from './documents.schemas';
export const documentsConfig = {
deletedDocumentsRetentionDays: {
doc: 'The retention period in days for deleted documents',
- schema: z.coerce.number().int().positive(),
+ schema: v.pipe(coercedNumberSchema, v.integer(), v.minValue(0)),
default: 30,
env: 'DOCUMENTS_DELETED_DOCUMENTS_RETENTION_DAYS',
},
ocrLanguages: {
doc: 'The languages codes to use for OCR, multiple languages can be specified by separating them with a comma. See https://tesseract-ocr.github.io/tessdoc/Data-Files#data-files-for-version-400-november-29-2016',
- schema: z.union([
+ schema: v.union([
stringCoercedOcrLanguagesSchema,
ocrLanguagesSchema,
]),
diff --git a/apps/papra-server/src/modules/documents/documents.schemas.ts b/apps/papra-server/src/modules/documents/documents.schemas.ts
index 5894ed7a..43bf19c9 100644
--- a/apps/papra-server/src/modules/documents/documents.schemas.ts
+++ b/apps/papra-server/src/modules/documents/documents.schemas.ts
@@ -1,6 +1,12 @@
+import * as v from 'valibot';
import { z } from 'zod';
import { DOCUMENT_ID_REGEX, OCR_LANGUAGES } from './documents.constants';
export const documentIdSchema = z.string().regex(DOCUMENT_ID_REGEX);
-export const ocrLanguagesSchema = z.array(z.enum(OCR_LANGUAGES));
-export const stringCoercedOcrLanguagesSchema = z.string().transform(value => value.split(',').map(lang => lang.trim())).pipe(ocrLanguagesSchema);
+
+export const ocrLanguagesSchema = v.array(v.picklist(OCR_LANGUAGES));
+export const stringCoercedOcrLanguagesSchema = v.pipe(
+ v.string(),
+ v.transform(value => value.split(',').map(lang => lang.trim())),
+ ocrLanguagesSchema,
+);
diff --git a/apps/papra-server/src/modules/documents/storage/document-storage.config.ts b/apps/papra-server/src/modules/documents/storage/document-storage.config.ts
index adc0a88a..e0872f5c 100644
--- a/apps/papra-server/src/modules/documents/storage/document-storage.config.ts
+++ b/apps/papra-server/src/modules/documents/storage/document-storage.config.ts
@@ -1,6 +1,7 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import * as v from 'valibot';
import { booleanishSchema } from '../../config/config.schemas';
+import { coercedPositiveIntegerSchema } from '../../shared/schemas/number.schemas';
import { AZ_BLOB_STORAGE_DRIVER_NAME } from './drivers/az-blob/az-blob.storage-driver';
import { FS_STORAGE_DRIVER_NAME } from './drivers/fs/fs.storage-driver';
import { IN_MEMORY_STORAGE_DRIVER_NAME } from './drivers/memory/memory.storage-driver';
@@ -8,16 +9,18 @@ import { S3_STORAGE_DRIVER_NAME } from './drivers/s3/s3.storage-driver';
import { documentEncryptionConfig } from './encryption/document-encryption.config';
import { storagePatternConfig } from './patterns/storage-pattern.config';
+const driverNames = [FS_STORAGE_DRIVER_NAME, S3_STORAGE_DRIVER_NAME, IN_MEMORY_STORAGE_DRIVER_NAME, AZ_BLOB_STORAGE_DRIVER_NAME] as const;
+
export const documentStorageConfig = {
maxUploadSize: {
doc: 'The maximum size in bytes for an uploaded file. Set to 0 to disable the limit and allow uploading documents of any size.',
- schema: z.coerce.number().int().nonnegative(),
+ schema: coercedPositiveIntegerSchema,
default: 10 * 1024 * 1024, // 10MB
env: 'DOCUMENT_STORAGE_MAX_UPLOAD_SIZE',
},
driver: {
- doc: `The driver to use for document storage, values can be one of: ${[FS_STORAGE_DRIVER_NAME, S3_STORAGE_DRIVER_NAME, IN_MEMORY_STORAGE_DRIVER_NAME, AZ_BLOB_STORAGE_DRIVER_NAME].map(x => `\`${x}\``).join(', ')}`,
- schema: z.enum([FS_STORAGE_DRIVER_NAME, S3_STORAGE_DRIVER_NAME, IN_MEMORY_STORAGE_DRIVER_NAME, AZ_BLOB_STORAGE_DRIVER_NAME]),
+ doc: `The driver to use for document storage, values can be one of: ${driverNames.map(x => `\`${x}\``).join(', ')}`,
+ schema: v.picklist(driverNames),
default: FS_STORAGE_DRIVER_NAME,
env: 'DOCUMENT_STORAGE_DRIVER',
},
@@ -25,7 +28,7 @@ export const documentStorageConfig = {
filesystem: {
root: {
doc: 'The root directory to store documents in (default as "./app-data/documents" when using docker)',
- schema: z.string(),
+ schema: v.string(),
default: './local-documents',
env: 'DOCUMENT_STORAGE_FILESYSTEM_ROOT',
},
@@ -33,31 +36,31 @@ export const documentStorageConfig = {
s3: {
accessKeyId: {
doc: 'The AWS access key ID for S3',
- schema: z.string(),
+ schema: v.string(),
default: '',
env: 'DOCUMENT_STORAGE_S3_ACCESS_KEY_ID',
},
secretAccessKey: {
doc: 'The AWS secret access key for S3',
- schema: z.string(),
+ schema: v.string(),
default: '',
env: 'DOCUMENT_STORAGE_S3_SECRET_ACCESS_KEY',
},
bucketName: {
doc: 'The S3 bucket name',
- schema: z.string(),
+ schema: v.string(),
default: '',
env: 'DOCUMENT_STORAGE_S3_BUCKET_NAME',
},
region: {
doc: 'The AWS region for S3',
- schema: z.string(),
+ schema: v.string(),
default: 'auto',
env: 'DOCUMENT_STORAGE_S3_REGION',
},
endpoint: {
doc: 'The S3 endpoint',
- schema: z.string().optional(),
+ schema: v.optional(v.string()),
default: undefined,
env: 'DOCUMENT_STORAGE_S3_ENDPOINT',
},
@@ -71,25 +74,25 @@ export const documentStorageConfig = {
azureBlob: {
connectionString: {
doc: 'The Azure Blob Storage connection string, if provided, the other account name, account key and container name will be ignored',
- schema: z.string().optional(),
+ schema: v.optional(v.string()),
default: undefined,
env: 'DOCUMENT_STORAGE_AZURE_BLOB_CONNECTION_STRING',
},
accountName: {
doc: 'The Azure Blob Storage account name',
- schema: z.string(),
+ schema: v.string(),
default: '',
env: 'DOCUMENT_STORAGE_AZURE_BLOB_ACCOUNT_NAME',
},
accountKey: {
doc: 'The Azure Blob Storage account key',
- schema: z.string(),
+ schema: v.string(),
default: '',
env: 'DOCUMENT_STORAGE_AZURE_BLOB_ACCOUNT_KEY',
},
containerName: {
doc: 'The Azure Blob Storage container name',
- schema: z.string(),
+ schema: v.string(),
default: '',
env: 'DOCUMENT_STORAGE_AZURE_BLOB_CONTAINER_NAME',
},
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.config.ts b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.config.ts
index 1f02f6eb..0893c643 100644
--- a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.config.ts
+++ b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.config.ts
@@ -1,6 +1,6 @@
import type { ConfigDefinition } from 'figue';
import { booleanishSchema } from '../../../config/config.schemas';
-import { documentKeyEncryptionKeysSchema } from './document-encryption.schemas';
+import { coercedDocumentKeyEncryptionKeysListSchema } from './document-encryption.schemas';
export const documentEncryptionConfig = {
isEncryptionEnabled: {
@@ -20,7 +20,7 @@ Formats:
- Versions must be unique and can be any alphabetically sortable string
- The order of the version:key pair is not important
`.trim(),
- schema: documentKeyEncryptionKeysSchema,
+ schema: coercedDocumentKeyEncryptionKeysListSchema,
default: undefined,
env: 'DOCUMENT_STORAGE_DOCUMENT_KEY_ENCRYPTION_KEYS',
},
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.models.test.ts b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.models.test.ts
new file mode 100644
index 00000000..106a6423
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.models.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, test } from 'vitest';
+import { areDocumentKeyEncryptionKeysUnique } from './document-encryption.schemas.models';
+
+describe('document-encryption schemas models', () => {
+ describe('areDocumentKeyEncryptionKeysUnique', () => {
+ test('same versions should return false, different versions should return true', () => {
+ expect(areDocumentKeyEncryptionKeysUnique([
+ { version: '1' },
+ { version: '2' },
+ { version: '3' },
+ ])).toBe(true);
+
+ expect(areDocumentKeyEncryptionKeysUnique([
+ { version: '1' },
+ { version: '2' },
+ { version: '1' },
+ ])).toBe(false);
+
+ expect(areDocumentKeyEncryptionKeysUnique([])).toBe(true);
+ expect(areDocumentKeyEncryptionKeysUnique([{ version: '1' }])).toBe(true);
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.models.ts b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.models.ts
new file mode 100644
index 00000000..5bb125c6
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.models.ts
@@ -0,0 +1,3 @@
+export function areDocumentKeyEncryptionKeysUnique(keys: { version: string }[]) {
+ return keys.length === new Set(keys.map(k => k.version)).size;
+}
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.test.ts b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.test.ts
index 515a3112..731eeb4f 100644
--- a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.test.ts
+++ b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.test.ts
@@ -1,14 +1,17 @@
import { Buffer } from 'node:buffer';
+import * as v from 'valibot';
import { describe, expect, test } from 'vitest';
-import { documentKeyEncryptionKeysSchema } from './document-encryption.schemas';
+
+import { coercedDocumentKeyEncryptionKeysListSchema } from './document-encryption.schemas';
describe('document-encryption schemas', () => {
describe('documentKeyEncryptionKeysSchema', () => {
test('the user can provide a comma separated list of 32 bytes long hex strings env variable', () => {
- const env = '1:0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c,2:abdc13ff846337ef514a62d7d2cd2aa3b517d957ab7c825b8de0c7678f17a843';
-
expect(
- documentKeyEncryptionKeysSchema.parse(env),
+ v.parse(
+ coercedDocumentKeyEncryptionKeysListSchema,
+ '1:0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c,2:abdc13ff846337ef514a62d7d2cd2aa3b517d957ab7c825b8de0c7678f17a843',
+ ),
).to.eql([
{
version: '1',
@@ -21,18 +24,73 @@ describe('document-encryption schemas', () => {
]);
});
+ test('versions should be unique', () => {
+ expect(
+ () =>
+ v.parse(
+ coercedDocumentKeyEncryptionKeysListSchema,
+ '1:0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c,1:abdc13ff846337ef514a62d7d2cd2aa3b517d957ab7c825b8de0c7678f17a843',
+ ),
+ ).toThrow('The keys must have unique versions');
+ });
+
test('the user can provide a single 32 bytes long hex string env variable', () => {
- const env = '0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c';
+ expect(
+ v.parse(
+ coercedDocumentKeyEncryptionKeysListSchema,
+ '0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c',
+ ),
+ ).to.eql([
+ {
+ version: '1',
+ key: Buffer.from('0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c', 'hex'),
+ },
+ ]);
+ });
+ test('the user can provide a single versioned 32 bytes long hex string env variable', () => {
expect(
- documentKeyEncryptionKeysSchema.parse(env),
- ).to.eql([{ version: '1', key: Buffer.from(env, 'hex') }]);
+ v.parse(
+ coercedDocumentKeyEncryptionKeysListSchema,
+ '42:0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c',
+ ),
+ ).to.eql([
+ {
+ version: '42',
+ key: Buffer.from('0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c', 'hex'),
+ },
+ ]);
});
test('no keys provided should not raise an error', () => {
expect(
- documentKeyEncryptionKeysSchema.parse(undefined),
+ v.parse(coercedDocumentKeyEncryptionKeysListSchema, undefined),
).to.eql(undefined);
});
+
+ test('keys should be 32 bytes long hex strings', () => {
+ expect(() =>
+ v.parse(
+ coercedDocumentKeyEncryptionKeysListSchema,
+ '0deba553',
+ ),
+ ).to.throw();
+
+ expect(() =>
+ v.parse(
+ coercedDocumentKeyEncryptionKeysListSchema,
+ // 33 bytes long hex string
+ '0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c8',
+ ),
+ ).to.throw();
+
+ expect(() =>
+ v.parse(
+ coercedDocumentKeyEncryptionKeysListSchema,
+ // 32 bytes long but not a hex string
+ 'Zdeba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c',
+ ),
+ ).to.throw();
+ });
});
});
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.ts b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.ts
index d8b32e03..b839ec76 100644
--- a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.ts
+++ b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.ts
@@ -1,40 +1,57 @@
import { Buffer } from 'node:buffer';
-import { z } from 'zod';
+import * as v from 'valibot';
+import { areDocumentKeyEncryptionKeysUnique } from './document-encryption.schemas.models';
-export const documentKeyEncryptionKeySchema = z.object({
- version: z.string(),
- key: z.instanceof(Buffer).refine(x => x.length === 32, { message: 'The key must be a 32 bytes long hex string' }),
+const documentKeyEncryptionKeySchema = v.object({
+ version: v.string(),
+ key: v.pipe(
+ v.instance(Buffer),
+ v.length(32),
+ ),
});
-const documentKeyEncryptionKeyArraySchema = z
- .array(documentKeyEncryptionKeySchema)
- .refine(x => x.length === new Set(x.map(x => x.version)).size, { message: 'The keys must have unique versions' });
+const documentKeyEncryptionKeyListSchema = v.pipe(
+ v.array(documentKeyEncryptionKeySchema),
+ v.check(
+ keys => areDocumentKeyEncryptionKeysUnique(keys),
+ 'The keys must have unique versions',
+ ),
+);
-export const documentKeyEncryptionKeysSchema = z.union([
- documentKeyEncryptionKeyArraySchema,
- z.string().transform((x) => {
- if (x.match(/^[0-9a-f]{64}$/i)) {
- return [{
- version: '1',
- key: Buffer.from(x, 'hex'),
- }];
+const versionedHexKeySchema = v.pipe(
+ v.string(),
+ v.transform((x): { version?: string; key?: string } => {
+ if (!x.includes(':')) {
+ return { version: '1', key: x };
}
+ const [version, key] = x.split(':');
+ return { version, key };
+ }),
+ v.object({
+ version: v.string(),
+ key: v.pipe(
+ v.string(),
+ v.regex(/^[0-9a-f]{64}$/i, 'The key must be a 64 hex characters string (32 bytes)'),
+ ),
+ }),
+ v.transform(({ version, key }) => ({
+ version,
+ key: Buffer.from(key, 'hex'),
+ })),
+);
- const keys = x.split(',').map(x => x.trim().split(':')).map(([version, key]) => {
- if (version === undefined || key === undefined) {
- return undefined;
- }
-
- return {
- version,
- key: Buffer.from(key, 'hex'),
- };
- });
-
- if (keys.length === 0) {
- return undefined;
- }
-
- return keys;
- }).pipe(documentKeyEncryptionKeyArraySchema),
-]).optional();
+export const coercedDocumentKeyEncryptionKeysListSchema = v.optional(v.union(
+ [
+ documentKeyEncryptionKeyListSchema,
+ v.pipe(
+ v.string(),
+ v.transform(value => value.split(',').map(part => part.trim())),
+ v.array(versionedHexKeySchema),
+ v.check(
+ keys => areDocumentKeyEncryptionKeysUnique(keys),
+ 'The keys must have unique versions',
+ ),
+ ),
+ ],
+ 'The value must be either a 32 bytes long hex string, or a comma separated list of version:key pairs where the key is a 32 bytes long hex string',
+));
diff --git a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.config.ts b/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.config.ts
index 62d6334f..b195c29d 100644
--- a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.config.ts
+++ b/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.config.ts
@@ -1,7 +1,7 @@
import type { AppConfigDefinition } from '../../../config/config.types';
-import { z } from 'zod';
import { booleanishSchema } from '../../../config/config.schemas';
-import { isStoragePatternValid } from './storage-pattern.usecases';
+import { coercedPositiveIntegerSchema } from '../../../shared/schemas/number.schemas';
+import { storagePatternSchema } from './storage-pattern.schemas';
export const storagePatternConfig = {
useLegacyStorageKeyDefinitionSystem: {
@@ -12,7 +12,7 @@ export const storagePatternConfig = {
},
maxIncrementalSuffixAttempts: {
doc: 'How many incremental suffixes to try when a storage key is already taken (e.g. file_1.txt, file_2.txt, ...). Set to 0 to skip incremental suffixes entirely.',
- schema: z.coerce.number().int().nonnegative(),
+ schema: coercedPositiveIntegerSchema,
default: 9, // This allows for a total of 10 attempts (the initial key + 9 incremental suffixes)
env: 'DOCUMENT_STORAGE_PATTERN_MAX_INCREMENTAL_SUFFIX_ATTEMPTS',
},
@@ -24,17 +24,7 @@ export const storagePatternConfig = {
},
storageKeyPattern: {
doc: 'The pattern to use for generating storage keys. This can include expressions enclosed in double curly braces (e.g. {{document.name}}) that will be evaluated at runtime.',
- schema: z
- .string()
- .superRefine((storageKeyPattern, ctx) => {
- const result = isStoragePatternValid({ storageKeyPattern });
- if (!result.isValid) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: result.error.message,
- });
- }
- }),
+ schema: storagePatternSchema,
default: '{{organization.id}}/{{document.name}}',
env: 'DOCUMENT_STORAGE_KEY_PATTERN',
},
diff --git a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.schemas.test.ts b/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.schemas.test.ts
new file mode 100644
index 00000000..0a8fc540
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.schemas.test.ts
@@ -0,0 +1,16 @@
+import * as v from 'valibot';
+import { describe, expect, test } from 'vitest';
+import { storagePatternSchema } from './storage-pattern.schemas';
+
+describe('storage-pattern schemas', () => {
+ describe('storagePatternSchema', () => {
+ test('ensure the storage pattern is valid, it throws if the pattern contains invalid expressions or transformers', () => {
+ expect(v.parse(storagePatternSchema, '{{document.id}}')).toBe('{{document.id}}');
+ expect(v.parse(storagePatternSchema, '{{document.name | lowercase}}')).toBe('{{document.name | lowercase}}');
+ expect(v.parse(storagePatternSchema, 'documents/{{document.id}}')).toBe('documents/{{document.id}}');
+
+ expect(() => v.parse(storagePatternSchema, '{{document}}')).toThrow('Invalid storage pattern: Unknown expression: document');
+ expect(() => v.parse(storagePatternSchema, '{{document.name | unknownFilter}}')).toThrow('Invalid storage pattern: Unknown transformer: unknownFilter');
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.schemas.ts b/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.schemas.ts
new file mode 100644
index 00000000..11609234
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.schemas.ts
@@ -0,0 +1,17 @@
+import * as v from 'valibot';
+import { isStoragePatternValid } from './storage-pattern.usecases';
+
+export const storagePatternSchema = v.pipe(
+ v.string(),
+ v.rawCheck(({ dataset, addIssue }) => {
+ if (dataset.typed) {
+ const result = isStoragePatternValid({ storageKeyPattern: dataset.value });
+
+ if (!result.isValid) {
+ addIssue({
+ message: `Invalid storage pattern: ${result.error.message}`,
+ });
+ }
+ }
+ }),
+);
diff --git a/apps/papra-server/src/modules/emails/drivers/logger/logger.email-driver.config.ts b/apps/papra-server/src/modules/emails/drivers/logger/logger.email-driver.config.ts
index 6dde39fe..47110188 100644
--- a/apps/papra-server/src/modules/emails/drivers/logger/logger.email-driver.config.ts
+++ b/apps/papra-server/src/modules/emails/drivers/logger/logger.email-driver.config.ts
@@ -1,10 +1,10 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import * as v from 'valibot';
export const loggerEmailDriverConfig = {
level: {
doc: 'When using the logger email driver, the level to log emails at',
- schema: z.enum(['info', 'debug', 'warn', 'error']),
+ schema: v.picklist(['info', 'debug', 'warn', 'error']),
default: 'info',
env: 'LOGGER_EMAIL_DRIVER_LOG_LEVEL',
},
diff --git a/apps/papra-server/src/modules/emails/drivers/resend/resend.email-driver.config.ts b/apps/papra-server/src/modules/emails/drivers/resend/resend.email-driver.config.ts
index b7ebc55c..fa6ebbbc 100644
--- a/apps/papra-server/src/modules/emails/drivers/resend/resend.email-driver.config.ts
+++ b/apps/papra-server/src/modules/emails/drivers/resend/resend.email-driver.config.ts
@@ -1,10 +1,10 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import * as v from 'valibot';
export const resendEmailDriverConfig = {
resendApiKey: {
doc: 'The API key for the Resend email service',
- schema: z.string(),
+ schema: v.string(),
default: '',
env: 'RESEND_API_KEY',
},
diff --git a/apps/papra-server/src/modules/emails/drivers/smtp/smtp.email-driver.config.ts b/apps/papra-server/src/modules/emails/drivers/smtp/smtp.email-driver.config.ts
index 3525ea5b..e3012110 100644
--- a/apps/papra-server/src/modules/emails/drivers/smtp/smtp.email-driver.config.ts
+++ b/apps/papra-server/src/modules/emails/drivers/smtp/smtp.email-driver.config.ts
@@ -1,30 +1,30 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import * as v from 'valibot';
import { booleanishSchema } from '../../../config/config.schemas';
-import { parseJson } from '../../../intake-emails/intake-emails.schemas';
+import { coercedNumberSchema } from '../../../shared/schemas/number.schemas';
export const smtpEmailDriverConfig = {
host: {
doc: 'The host of the SMTP server',
- schema: z.string().optional(),
+ schema: v.optional(v.string()),
default: '',
env: 'SMTP_HOST',
},
port: {
doc: 'The port of the SMTP server',
- schema: z.coerce.number(),
+ schema: coercedNumberSchema,
default: 587,
env: 'SMTP_PORT',
},
user: {
doc: 'The user of the SMTP server',
- schema: z.string().optional(),
+ schema: v.optional(v.string()),
default: undefined,
env: 'SMTP_USER',
},
password: {
doc: 'The password of the SMTP server',
- schema: z.string().optional(),
+ schema: v.optional(v.string()),
default: undefined,
env: 'SMTP_PASSWORD',
},
@@ -36,7 +36,10 @@ export const smtpEmailDriverConfig = {
},
rawConfig: {
doc: 'The raw configuration for the nodemailer SMTP client in JSON format for advanced use cases. If set, this will override all other config options. See https://nodemailer.com/smtp/ for more details.',
- schema: z.string().transform(parseJson).optional(),
+ schema: v.optional(v.pipe(
+ v.string(),
+ v.parseJson(),
+ )),
default: undefined,
env: 'SMTP_JSON_CONFIG',
},
diff --git a/apps/papra-server/src/modules/emails/emails.config.ts b/apps/papra-server/src/modules/emails/emails.config.ts
index 13d5cdd5..42fe1924 100644
--- a/apps/papra-server/src/modules/emails/emails.config.ts
+++ b/apps/papra-server/src/modules/emails/emails.config.ts
@@ -1,5 +1,5 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import * as v from 'valibot';
import { emailDriverFactoryNames } from './drivers/email-driver';
import { LOGGER_EMAIL_DRIVER_NAME } from './drivers/logger/logger.email-driver';
import { loggerEmailDriverConfig } from './drivers/logger/logger.email-driver.config';
@@ -9,13 +9,13 @@ import { smtpEmailDriverConfig } from './drivers/smtp/smtp.email-driver.config';
export const emailsConfig = {
fromEmail: {
doc: 'The email address to send emails from',
- schema: z.string(),
+ schema: v.string(),
default: 'Papra <[email protected]>',
env: 'EMAILS_FROM_ADDRESS',
},
driverName: {
doc: `The driver to use when sending emails, value can be one of: ${emailDriverFactoryNames.map(x => `\`${x}\``).join(', ')}. Using \`logger\` will not send anything but log them instead`,
- schema: z.enum(emailDriverFactoryNames as [string, ...string[]]),
+ schema: v.picklist(emailDriverFactoryNames),
default: LOGGER_EMAIL_DRIVER_NAME,
env: 'EMAILS_DRIVER',
},
diff --git a/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.config.ts b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.config.ts
index b1f207eb..d6b4e2b9 100644
--- a/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.config.ts
+++ b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.config.ts
@@ -1,8 +1,8 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import * as v from 'valibot';
import { booleanishSchema } from '../config/config.schemas';
+import { coercedStrictlyPositiveIntegerSchema } from '../shared/schemas/number.schemas';
import { IN_MS } from '../shared/units';
-import { isString } from '../shared/utils';
import { defaultIgnoredPatterns } from './ingestion-folders.constants';
export const ingestionFolderConfig = {
@@ -14,7 +14,7 @@ export const ingestionFolderConfig = {
},
folderRootPath: {
doc: 'The root directory in which ingestion folders for each organization are stored',
- schema: z.string(),
+ schema: v.string(),
default: './ingestion',
env: 'INGESTION_FOLDER_ROOT_PATH',
},
@@ -27,43 +27,47 @@ export const ingestionFolderConfig = {
},
pollingInterval: {
doc: 'When polling is used, this is the interval at which the watcher checks for changes in the ingestion folder (in milliseconds)',
- schema: z.coerce.number().int().positive(),
+ schema: coercedStrictlyPositiveIntegerSchema,
default: 2 * IN_MS.SECOND,
env: 'INGESTION_FOLDER_WATCHER_POLLING_INTERVAL_MS',
},
},
processingConcurrency: {
doc: 'The number of files that can be processed concurrently by the server. Increasing this can improve processing speed, but it will also increase CPU and memory usage.',
- schema: z.coerce.number().int().positive().min(1),
+ schema: coercedStrictlyPositiveIntegerSchema,
default: 1,
env: 'INGESTION_FOLDER_PROCESSING_CONCURRENCY',
},
errorFolder: {
doc: 'The folder to move the file when the ingestion fails, the path is relative to the organization ingestion folder (<ingestion root>/<organization id>)',
- schema: z.string(),
+ schema: v.string(),
default: './ingestion-error',
env: 'INGESTION_FOLDER_ERROR_FOLDER_PATH',
},
postProcessing: {
strategy: {
doc: 'The action done on the file after it has been ingested',
- schema: z.enum(['delete', 'move']),
+ schema: v.picklist(['delete', 'move']),
default: 'delete',
env: 'INGESTION_FOLDER_POST_PROCESSING_STRATEGY',
},
moveToFolderPath: {
doc: 'The folder to move the file when the post-processing strategy is "move", the path is relative to the organization ingestion folder (<ingestion root>/<organization id>)',
- schema: z.string(),
+ schema: v.string(),
default: './ingestion-done',
env: 'INGESTION_FOLDER_POST_PROCESSING_MOVE_FOLDER_PATH',
},
},
ignoredPatterns: {
doc: `Comma separated list of patterns to ignore when watching the ingestion folder. Note that if you update this variable, it'll override the default patterns, not merge them. Regarding the format and syntax, please refer to the [picomatch documentation](https://github.com/micromatch/picomatch/blob/bf6a33bd3db990edfbfd20b3b160eed926cd07dd/README.md#globbing-features)`,
- schema: z.union([
- z.string(),
- z.array(z.string()),
- ]).transform(value => (isString(value) ? value.split(',') : value)),
+
+ schema: v.union([
+ v.pipe(
+ v.string(),
+ v.transform(value => value.split(',')),
+ ),
+ v.array(v.string()),
+ ]),
default: defaultIgnoredPatterns,
env: 'INGESTION_FOLDER_IGNORED_PATTERNS',
},
diff --git a/apps/papra-server/src/modules/intake-emails/drivers/catch-all/catch-all.intake-email-driver.config.ts b/apps/papra-server/src/modules/intake-emails/drivers/catch-all/catch-all.intake-email-driver.config.ts
index 2a47b598..3181205c 100644
--- a/apps/papra-server/src/modules/intake-emails/drivers/catch-all/catch-all.intake-email-driver.config.ts
+++ b/apps/papra-server/src/modules/intake-emails/drivers/catch-all/catch-all.intake-email-driver.config.ts
@@ -1,11 +1,11 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import * as v from 'valibot';
export const catchAllIntakeEmailDriverConfig = {
domain: {
doc: 'The domain to use when generating email addresses for intake emails when using the `catch-all` driver',
- schema: z.string(),
+ schema: v.string(),
default: 'papra.local',
env: 'INTAKE_EMAILS_CATCH_ALL_DOMAIN',
},
diff --git a/apps/papra-server/src/modules/intake-emails/drivers/owlrelay/owlrelay.intake-email-driver.config.ts b/apps/papra-server/src/modules/intake-emails/drivers/owlrelay/owlrelay.intake-email-driver.config.ts
index 0f731467..01e974f6 100644
--- a/apps/papra-server/src/modules/intake-emails/drivers/owlrelay/owlrelay.intake-email-driver.config.ts
+++ b/apps/papra-server/src/modules/intake-emails/drivers/owlrelay/owlrelay.intake-email-driver.config.ts
@@ -1,23 +1,23 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import * as v from 'valibot';
export const owlrelayIntakeEmailDriverConfig = {
owlrelayApiKey: {
doc: 'The API key used to interact with OwlRelay for the intake emails',
- schema: z.string(),
+ schema: v.string(),
default: 'change-me',
env: 'OWLRELAY_API_KEY',
},
webhookUrl: {
doc: 'The webhook URL to use when generating email addresses for intake emails with OwlRelay, if not provided, the webhook will be inferred from the server URL',
- schema: z.string().optional(),
+ schema: v.optional(v.string()),
default: undefined,
env: 'OWLRELAY_WEBHOOK_URL',
},
domain: {
doc: 'The domain to use when generating email addresses for intake emails with OwlRelay, if not provided, the OwlRelay will use their default domain',
- schema: z.string().optional(), // TODO: check valid hostname
+ schema: v.optional(v.string()), // TODO: check valid hostname
default: undefined,
env: 'OWLRELAY_DOMAIN',
},
diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.config.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.config.ts
index 0216170d..d47e726d 100644
--- a/apps/papra-server/src/modules/intake-emails/intake-emails.config.ts
+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.config.ts
@@ -1,5 +1,5 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import * as v from 'valibot';
import { booleanishSchema } from '../config/config.schemas';
import { CATCH_ALL_INTAKE_EMAIL_DRIVER_NAME } from './drivers/catch-all/catch-all.intake-email-driver';
import { catchAllIntakeEmailDriverConfig } from './drivers/catch-all/catch-all.intake-email-driver.config';
@@ -16,13 +16,13 @@ export const intakeEmailsConfig = {
},
webhookSecret: {
doc: 'The secret to use when verifying webhooks, should be a random string between 16 and 128 characters',
- schema: z.string().min(16).max(128),
+ schema: v.pipe(v.string(), v.minLength(16), v.maxLength(128)),
default: 'please-change-me',
env: 'INTAKE_EMAILS_WEBHOOK_SECRET',
},
driver: {
doc: `The driver to use when generating email addresses for intake emails, value can be one of: ${Object.keys(intakeEmailDrivers).map(x => `\`${x}\``).join(', ')}.`,
- schema: z.enum(Object.keys(intakeEmailDrivers) as [string, ...string[]]),
+ schema: v.picklist(Object.keys(intakeEmailDrivers)),
default: CATCH_ALL_INTAKE_EMAIL_DRIVER_NAME,
env: 'INTAKE_EMAILS_DRIVER',
},
diff --git a/apps/papra-server/src/modules/intake-emails/username-drivers/intake-email-username.config.ts b/apps/papra-server/src/modules/intake-emails/username-drivers/intake-email-username.config.ts
index 86f786d0..97d9924d 100644
--- a/apps/papra-server/src/modules/intake-emails/username-drivers/intake-email-username.config.ts
+++ b/apps/papra-server/src/modules/intake-emails/username-drivers/intake-email-username.config.ts
@@ -1,5 +1,5 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import * as v from 'valibot';
import { intakeEmailUsernameDrivers } from './intake-email-username.drivers';
import { patternIntakeEmailDriverConfig } from './pattern/pattern.intake-email-username-driver.config';
import { RANDOM_INTAKE_EMAIL_ADDRESSES_DRIVER_NAME } from './random/random.intake-email-username-driver';
@@ -7,7 +7,7 @@ import { RANDOM_INTAKE_EMAIL_ADDRESSES_DRIVER_NAME } from './random/random.intak
export const intakeEmailUsernameConfig = {
driver: {
doc: `The driver to use when generating email addresses for intake emails, value can be one of: ${Object.keys(intakeEmailUsernameDrivers).map(x => `\`${x}\``).join(', ')}`,
- schema: z.enum(Object.keys(intakeEmailUsernameDrivers) as [string, ...string[]]),
+ schema: v.picklist(Object.keys(intakeEmailUsernameDrivers)),
default: RANDOM_INTAKE_EMAIL_ADDRESSES_DRIVER_NAME,
env: 'INTAKE_EMAILS_USERNAME_DRIVER',
},
diff --git a/apps/papra-server/src/modules/intake-emails/username-drivers/pattern/pattern.intake-email-username-driver.config.ts b/apps/papra-server/src/modules/intake-emails/username-drivers/pattern/pattern.intake-email-username-driver.config.ts
index 6d419700..cc0dd00c 100644
--- a/apps/papra-server/src/modules/intake-emails/username-drivers/pattern/pattern.intake-email-username-driver.config.ts
+++ b/apps/papra-server/src/modules/intake-emails/username-drivers/pattern/pattern.intake-email-username-driver.config.ts
@@ -1,6 +1,6 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import * as v from 'valibot';
import { PATTERNS_PLACEHOLDERS } from './pattern.intake-email-username-driver.constants';
export const PATTERN_INTAKE_EMAIL_ADDRESSES_DRIVER_NAME = 'pattern';
@@ -8,7 +8,7 @@ export const PATTERN_INTAKE_EMAIL_ADDRESSES_DRIVER_NAME = 'pattern';
export const patternIntakeEmailDriverConfig = {
pattern: {
doc: `The pattern to use when generating email addresses usernames (before the @) for intake emails. Available placeholders are: ${Object.values(PATTERNS_PLACEHOLDERS).join(', ')}. Note: the resulting username will be slugified to remove special characters and spaces.`,
- schema: z.string(),
+ schema: v.string(),
default: `${PATTERNS_PLACEHOLDERS.USER_NAME}-${PATTERNS_PLACEHOLDERS.RANDOM_DIGITS}`,
env: 'INTAKE_EMAILS_USERNAME_DRIVER_PATTERN',
},
diff --git a/apps/papra-server/src/modules/organizations/organizations.config.ts b/apps/papra-server/src/modules/organizations/organizations.config.ts
index fa96faf2..2b27402f 100644
--- a/apps/papra-server/src/modules/organizations/organizations.config.ts
+++ b/apps/papra-server/src/modules/organizations/organizations.config.ts
@@ -1,28 +1,28 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import { coercedStrictlyPositiveIntegerSchema } from '../shared/schemas/number.schemas';
export const organizationsConfig = {
maxOrganizationCount: {
doc: 'The maximum number of organizations a standard user can have',
- schema: z.coerce.number().int().positive(),
+ schema: coercedStrictlyPositiveIntegerSchema,
default: 10,
env: 'MAX_ORGANIZATION_COUNT_PER_USER',
},
invitationExpirationDelayDays: {
doc: 'The number of days an invitation to an organization will be valid',
- schema: z.coerce.number().int().positive(),
+ schema: coercedStrictlyPositiveIntegerSchema,
default: 7,
env: 'ORGANIZATION_INVITATION_EXPIRATION_DELAY_DAYS',
},
maxUserInvitationsPerDay: {
doc: 'The maximum number of invitations a user can send per day',
- schema: z.coerce.number().int().positive(),
+ schema: coercedStrictlyPositiveIntegerSchema,
default: 30,
env: 'MAX_USER_ORGANIZATIONS_INVITATIONS_PER_DAY',
},
deletedOrganizationsPurgeDaysDelay: {
doc: 'The number of days before a soft-deleted organization is permanently purged',
- schema: z.coerce.number().int().positive(),
+ schema: coercedStrictlyPositiveIntegerSchema,
default: 30,
env: 'ORGANIZATIONS_DELETED_PURGE_DAYS_DELAY',
},
diff --git a/apps/papra-server/src/modules/plans/plans.config.ts b/apps/papra-server/src/modules/plans/plans.config.ts
index cb66883e..bd90af97 100644
--- a/apps/papra-server/src/modules/plans/plans.config.ts
+++ b/apps/papra-server/src/modules/plans/plans.config.ts
@@ -1,5 +1,5 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import * as v from 'valibot';
import { booleanishSchema } from '../config/config.schemas';
export const organizationPlansConfig = {
@@ -11,25 +11,25 @@ export const organizationPlansConfig = {
},
plusPlanMonthlyPriceId: {
doc: 'The monthly price id of the plus plan (useless for self-hosting)',
- schema: z.string(),
+ schema: v.string(),
default: 'change-me',
env: 'PLANS_PLUS_PLAN_MONTHLY_PRICE_ID',
},
plusPlanAnnualPriceId: {
doc: 'The annual price id of the plus plan (useless for self-hosting)',
- schema: z.string(),
+ schema: v.string(),
default: 'change-me',
env: 'PLANS_PLUS_PLAN_ANNUAL_PRICE_ID',
},
proPlanMonthlyPriceId: {
doc: 'The monthly price id of the pro plan (useless for self-hosting)',
- schema: z.string(),
+ schema: v.string(),
default: 'change-me',
env: 'PLANS_PRO_PLAN_MONTHLY_PRICE_ID',
},
proPlanAnnualPriceId: {
doc: 'The annual price id of the pro plan (useless for self-hosting)',
- schema: z.string(),
+ schema: v.string(),
default: 'change-me',
env: 'PLANS_PRO_PLAN_ANNUAL_PRICE_ID',
},
diff --git a/apps/papra-server/src/modules/shared/schemas/number.schemas.test.ts b/apps/papra-server/src/modules/shared/schemas/number.schemas.test.ts
new file mode 100644
index 00000000..aa618176
--- /dev/null
+++ b/apps/papra-server/src/modules/shared/schemas/number.schemas.test.ts
@@ -0,0 +1,15 @@
+import * as v from 'valibot';
+import { describe, expect, test } from 'vitest';
+import { coercedNumberSchema } from './number.schemas';
+
+describe('number schemas', () => {
+ describe('coerceNumberSchema', () => {
+ test('validates and coerces a string to a number', () => {
+ expect(v.parse(coercedNumberSchema, '42')).toBe(42);
+ expect(v.parse(coercedNumberSchema, 42)).toBe(42);
+
+ expect(() => v.parse(coercedNumberSchema, 'not-a-number')).toThrow();
+ expect(() => v.parse(coercedNumberSchema, [])).toThrow();
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/shared/schemas/number.schemas.ts b/apps/papra-server/src/modules/shared/schemas/number.schemas.ts
new file mode 100644
index 00000000..d0237c4b
--- /dev/null
+++ b/apps/papra-server/src/modules/shared/schemas/number.schemas.ts
@@ -0,0 +1,38 @@
+import * as v from 'valibot';
+
+export const integerSchema = v.pipe(
+ v.number(),
+ v.integer(),
+);
+
+export const positiveIntegerSchema = v.pipe(
+ v.number(),
+ v.integer(),
+ v.minValue(0),
+);
+
+export const coercedNumberSchema = v.union([
+ v.number(),
+ v.pipe(v.string(), v.toNumber()),
+]);
+
+export const coercedIntegerSchema = v.union([
+ integerSchema,
+ v.pipe(v.string(), v.toNumber(), integerSchema),
+]);
+
+export const coercedPositiveIntegerSchema = v.union([
+ positiveIntegerSchema,
+ v.pipe(v.string(), v.toNumber(), positiveIntegerSchema),
+]);
+
+export const strictlyPositiveIntegerSchema = v.pipe(
+ v.number(),
+ v.integer(),
+ v.minValue(1),
+);
+
+export const coercedStrictlyPositiveIntegerSchema = v.union([
+ strictlyPositiveIntegerSchema,
+ v.pipe(v.string(), v.toNumber(), strictlyPositiveIntegerSchema),
+]);
diff --git a/apps/papra-server/src/modules/subscriptions/subscriptions.config.ts b/apps/papra-server/src/modules/subscriptions/subscriptions.config.ts
index 9f8725b7..5d575f9e 100644
--- a/apps/papra-server/src/modules/subscriptions/subscriptions.config.ts
+++ b/apps/papra-server/src/modules/subscriptions/subscriptions.config.ts
@@ -1,22 +1,22 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import * as v from 'valibot';
export const subscriptionsConfig = {
stripeApiSecretKey: {
doc: 'The API secret key for the Stripe (useless for self-hosting)',
- schema: z.string(),
+ schema: v.string(),
default: 'change-me',
env: 'STRIPE_API_SECRET_KEY',
},
stripeWebhookSecret: {
doc: 'The secret for the Stripe webhook (useless for self-hosting)',
- schema: z.string(),
+ schema: v.string(),
default: 'change-me',
env: 'STRIPE_WEBHOOK_SECRET',
},
globalCouponId: {
doc: 'The Stripe coupon ID to apply globally for launch promotions',
- schema: z.string().optional(),
+ schema: v.optional(v.string()),
default: undefined,
env: 'GLOBAL_COUPON_ID',
},
diff --git a/apps/papra-server/src/modules/tags/tags.config.ts b/apps/papra-server/src/modules/tags/tags.config.ts
index d3cefdf6..7c2ef46a 100644
--- a/apps/papra-server/src/modules/tags/tags.config.ts
+++ b/apps/papra-server/src/modules/tags/tags.config.ts
@@ -1,10 +1,10 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
+import { coercedStrictlyPositiveIntegerSchema } from '../shared/schemas/number.schemas';
export const tagsConfig = {
maxTagsPerOrganization: {
doc: 'The maximum number of tags an organization can have',
- schema: z.coerce.number().int().positive(),
+ schema: coercedStrictlyPositiveIntegerSchema,
default: 200,
env: 'MAX_TAGS_PER_ORGANIZATION',
},
diff --git a/apps/papra-server/src/modules/tasks/drivers/tasks-driver.constants.ts b/apps/papra-server/src/modules/tasks/drivers/tasks-driver.constants.ts
index f965a445..f82efbcf 100644
--- a/apps/papra-server/src/modules/tasks/drivers/tasks-driver.constants.ts
+++ b/apps/papra-server/src/modules/tasks/drivers/tasks-driver.constants.ts
@@ -3,6 +3,6 @@ export const TASKS_DRIVER_NAMES = {
libsql: 'libsql',
} as const;
-export const tasksDriverNames = Object.keys(TASKS_DRIVER_NAMES);
+export const tasksDriverNames = Object.keys(TASKS_DRIVER_NAMES) as (keyof typeof TASKS_DRIVER_NAMES)[];
export type TasksDriverName = keyof typeof TASKS_DRIVER_NAMES;
diff --git a/apps/papra-server/src/modules/tasks/tasks.config.ts b/apps/papra-server/src/modules/tasks/tasks.config.ts
index 7f2a939f..e3018acd 100644
--- a/apps/papra-server/src/modules/tasks/tasks.config.ts
+++ b/apps/papra-server/src/modules/tasks/tasks.config.ts
@@ -1,7 +1,7 @@
import type { ConfigDefinition } from 'figue';
-import type { TasksDriverName } from './drivers/tasks-driver.constants';
-import { z } from 'zod';
-import { booleanishSchema } from '../config/config.schemas';
+import * as v from 'valibot';
+import { booleanishSchema, urlSchema } from '../config/config.schemas';
+import { coercedPositiveIntegerSchema } from '../shared/schemas/number.schemas';
import { IN_MS } from '../shared/units';
import { tasksDriverNames } from './drivers/tasks-driver.constants';
@@ -9,7 +9,7 @@ export const tasksConfig = {
persistence: {
driverName: {
doc: `The driver to use for the tasks persistence, values can be one of: ${tasksDriverNames.map(x => `\`${x}\``).join(', ')}. Using the memory driver is enough when running a single instance of the server.`,
- schema: z.enum(tasksDriverNames as [TasksDriverName, ...TasksDriverName[]]),
+ schema: v.picklist(tasksDriverNames),
default: 'memory',
env: 'TASKS_PERSISTENCE_DRIVER',
},
@@ -17,13 +17,13 @@ export const tasksConfig = {
libSql: {
url: {
doc: 'The URL of the LibSQL database, can be either a file-protocol url with a local path or a remote LibSQL database URL',
- schema: z.string().url(),
+ schema: urlSchema,
default: 'file:./tasks-db.sqlite',
env: 'TASKS_PERSISTENCE_DRIVERS_LIBSQL_URL',
},
authToken: {
doc: 'The auth token for the LibSQL database',
- schema: z.string().optional(),
+ schema: v.optional(v.string()),
default: undefined,
env: 'TASKS_PERSISTENCE_DRIVERS_LIBSQL_AUTH_TOKEN',
},
@@ -35,7 +35,7 @@ export const tasksConfig = {
},
pollIntervalMs: {
doc: 'The interval at which the task persistence driver polls for new tasks',
- schema: z.coerce.number().int().positive(),
+ schema: coercedPositiveIntegerSchema,
default: 1 * IN_MS.SECOND,
env: 'TASKS_PERSISTENCE_DRIVERS_LIBSQL_POLL_INTERVAL_MS',
},
@@ -45,14 +45,14 @@ export const tasksConfig = {
worker: {
id: {
doc: 'The id of the task worker, used to identify the worker in the Cadence cluster in case of multiple workers, should be unique per instance',
- schema: z.string().optional(),
+ schema: v.optional(v.string()),
env: ['TASKS_WORKER_ID', 'DYNO', 'RENDER_SERVICE_ID', 'FLY_MACHINE_ID'],
},
},
hardDeleteExpiredDocuments: {
cron: {
doc: 'The cron schedule for the task to hard delete expired "soft deleted" documents',
- schema: z.string(),
+ schema: v.string(),
default: '0 0 * * *',
env: 'DOCUMENTS_HARD_DELETE_EXPIRED_DOCUMENTS_CRON',
},
@@ -66,7 +66,7 @@ export const tasksConfig = {
expireInvitations: {
cron: {
doc: 'The cron schedule for the task to expire invitations',
- schema: z.string(),
+ schema: v.string(),
default: '0 0 * * *',
env: 'ORGANIZATIONS_EXPIRE_INVITATIONS_CRON',
},
@@ -80,7 +80,7 @@ export const tasksConfig = {
purgeExpiredOrganizations: {
cron: {
doc: 'The cron schedule for the task to purge expired soft-deleted organizations',
- schema: z.string(),
+ schema: v.string(),
default: '0 1 * * *',
env: 'ORGANIZATIONS_PURGE_EXPIRED_ORGANIZATIONS_CRON',
},
diff --git a/apps/papra-server/src/modules/tracking/tracking.config.ts b/apps/papra-server/src/modules/tracking/tracking.config.ts
index 4d0bbbe6..14f0f903 100644
--- a/apps/papra-server/src/modules/tracking/tracking.config.ts
+++ b/apps/papra-server/src/modules/tracking/tracking.config.ts
@@ -1,6 +1,6 @@
import type { ConfigDefinition } from 'figue';
-import { z } from 'zod';
-import { booleanishSchema } from '../config/config.schemas';
+import * as v from 'valibot';
+import { booleanishSchema, urlSchema } from '../config/config.schemas';
export const trackingConfig = {
posthog: {
@@ -12,13 +12,13 @@ export const trackingConfig = {
},
apiKey: {
doc: 'The API key for PostHog',
- schema: z.string(),
+ schema: v.string(),
default: 'set-me',
env: 'POSTHOG_API_KEY',
},
host: {
doc: 'The host for PostHog',
- schema: z.string().url(),
+ schema: urlSchema,
default: 'https://eu.i.posthog.com',
env: 'POSTHOG_HOST',
},
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 94106d1c..dc3683fb 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -566,6 +566,9 @@ importers:
tsx:
specifier: 'catalog:'
version: 4.20.6
+ valibot:
+ specifier: 'catalog:'
+ version: 1.3.1([email protected])
zod:
specifier: ^3.25.67
version: 3.25.76
@@ -13792,17 +13795,6 @@ snapshots:
nanostores: 1.0.1
zod: 4.1.12
- dependencies:
- '@better-auth/utils': 0.3.0
- '@better-fetch/fetch': 1.1.18
- '@standard-schema/spec': 1.0.0
- better-call: 1.1.5([email protected])
- jose: 6.1.0
- kysely: 0.28.8
- nanostores: 1.0.1
- zod: 4.1.12
-
dependencies:
@@ -13816,9 +13808,9 @@ snapshots:
expo-network: 8.0.8([email protected])([email protected])
dependencies:
'@better-auth/utils': 0.3.0
'@better-fetch/fetch': 1.1.18
@@ -18533,13 +18525,13 @@ snapshots:
dependencies:
'@better-auth/utils': 0.3.0
'@better-fetch/fetch': 1.1.18
'@noble/ciphers': 2.0.1
'@noble/hashes': 2.0.1
- better-call: 1.1.5([email protected])
+ better-call: 1.1.5([email protected])
defu: 6.1.4
jose: 6.1.0
kysely: 0.28.8