Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

refactor(server): migrate admin endpoint validation from zod to valibot (#1033)

Corentin Thomasset5d55e41c3be6
diff --git a/.changeset/proud-things-rest.md b/.changeset/proud-things-rest.md
new file mode 100644
index 00000000..f49d5442
--- /dev/null
+++ b/.changeset/proud-things-rest.md
@@ -0,0 +1,5 @@
+---
+"@papra/app": patch
+---
+
+Changed the server endpoint validation library from `zod` to `valibot`, and improved some validation schemas in the process.
diff --git a/apps/papra-server/src/modules/admin/organizations/organizations.routes.ts b/apps/papra-server/src/modules/admin/organizations/organizations.routes.ts
index d90eb721..530c04e1 100644
--- a/apps/papra-server/src/modules/admin/organizations/organizations.routes.ts
+++ b/apps/papra-server/src/modules/admin/organizations/organizations.routes.ts
@@ -1,12 +1,13 @@
import type { RouteDefinitionContext } from '../../app/server.types';
-import { z } from 'zod';
+import * as v from 'valibot';
import { createRoleMiddleware, requireAuthentication } from '../../app/auth/auth.middleware';
import { createIntakeEmailsRepository } from '../../intake-emails/intake-emails.repository';
-import { organizationIdSchema } from '../../organizations/organization.schemas.legacy';
+import { organizationIdSchema } from '../../organizations/organization.schemas';
import { createOrganizationNotFoundError } from '../../organizations/organizations.errors';
import { createOrganizationsRepository } from '../../organizations/organizations.repository';
import { PERMISSIONS } from '../../roles/roles.constants';
-import { legacyValidateParams, legacyValidateQuery } from '../../shared/validation/validation.legacy';
+import { createQueryPaginationSchemaKeys } from '../../shared/schemas/pagination.schemas';
+import { validateParams, validateQuery } from '../../shared/validation/validation';
import { createWebhookRepository } from '../../webhooks/webhooks.repository';
export function registerOrganizationManagementRoutes(context: RouteDefinitionContext) {
@@ -27,11 +28,10 @@ function registerListOrganizationsRoute({ app, db }: RouteDefinitionContext) {
requirePermissions({
requiredPermissions: [PERMISSIONS.VIEW_USERS],
}),
- legacyValidateQuery(
- z.object({
- search: z.string().optional(),
- pageIndex: z.coerce.number().min(0).int().optional().default(0),
- pageSize: z.coerce.number().min(1).max(100).int().optional().default(25),
+ validateQuery(
+ v.strictObject({
+ search: v.optional(v.string()),
+ ...createQueryPaginationSchemaKeys(),
}),
),
async (context) => {
@@ -64,7 +64,7 @@ function registerGetOrganizationBasicInfoRoute({ app, db }: RouteDefinitionConte
requirePermissions({
requiredPermissions: [PERMISSIONS.VIEW_USERS],
}),
- legacyValidateParams(z.object({
+ validateParams(v.strictObject({
organizationId: organizationIdSchema,
})),
async (context) => {
@@ -92,7 +92,7 @@ function registerGetOrganizationMembersRoute({ app, db }: RouteDefinitionContext
requirePermissions({
requiredPermissions: [PERMISSIONS.VIEW_USERS],
}),
- legacyValidateParams(z.object({
+ validateParams(v.strictObject({
organizationId: organizationIdSchema,
})),
async (context) => {
@@ -122,7 +122,7 @@ function registerGetOrganizationIntakeEmailsRoute({ app, db }: RouteDefinitionCo
requirePermissions({
requiredPermissions: [PERMISSIONS.VIEW_USERS],
}),
- legacyValidateParams(z.object({
+ validateParams(v.strictObject({
organizationId: organizationIdSchema,
})),
async (context) => {
@@ -153,7 +153,7 @@ function registerGetOrganizationWebhooksRoute({ app, db }: RouteDefinitionContex
requirePermissions({
requiredPermissions: [PERMISSIONS.VIEW_USERS],
}),
- legacyValidateParams(z.object({
+ validateParams(v.strictObject({
organizationId: organizationIdSchema,
})),
async (context) => {
@@ -184,7 +184,7 @@ function registerGetOrganizationStatsRoute({ app, db }: RouteDefinitionContext)
requirePermissions({
requiredPermissions: [PERMISSIONS.VIEW_USERS],
}),
- legacyValidateParams(z.object({
+ validateParams(v.strictObject({
organizationId: organizationIdSchema,
})),
async (context) => {
diff --git a/apps/papra-server/src/modules/admin/users/users.routes.ts b/apps/papra-server/src/modules/admin/users/users.routes.ts
index 952f58ac..e62fa575 100644
--- a/apps/papra-server/src/modules/admin/users/users.routes.ts
+++ b/apps/papra-server/src/modules/admin/users/users.routes.ts
@@ -1,12 +1,13 @@
import type { RouteDefinitionContext } from '../../app/server.types';
-import { z } from 'zod';
+import * as v from 'valibot';
import { createRoleMiddleware, requireAuthentication } from '../../app/auth/auth.middleware';
import { createOrganizationsRepository } from '../../organizations/organizations.repository';
import { PERMISSIONS } from '../../roles/roles.constants';
import { createRolesRepository } from '../../roles/roles.repository';
-import { legacyValidateParams, legacyValidateQuery } from '../../shared/validation/validation.legacy';
+import { createQueryPaginationSchemaKeys } from '../../shared/schemas/pagination.schemas';
+import { validateParams, validateQuery } from '../../shared/validation/validation';
import { createUsersRepository } from '../../users/users.repository';
-import { userIdSchema } from '../../users/users.schemas.legacy';
+import { userIdSchema } from '../../users/users.schemas';
export function registerUserManagementRoutes(context: RouteDefinitionContext) {
registerListUsersRoute(context);
@@ -22,11 +23,10 @@ function registerListUsersRoute({ app, db }: RouteDefinitionContext) {
requirePermissions({
requiredPermissions: [PERMISSIONS.VIEW_USERS],
}),
- legacyValidateQuery(
- z.object({
- search: z.string().optional(),
- pageIndex: z.coerce.number().min(0).int().optional().default(0),
- pageSize: z.coerce.number().min(1).max(100).int().optional().default(25),
+ validateQuery(
+ v.strictObject({
+ search: v.optional(v.string()),
+ ...createQueryPaginationSchemaKeys(),
}),
),
async (context) => {
@@ -59,7 +59,7 @@ function registerGetUserDetailRoute({ app, db }: RouteDefinitionContext) {
requirePermissions({
requiredPermissions: [PERMISSIONS.VIEW_USERS],
}),
- legacyValidateParams(z.object({
+ validateParams(v.strictObject({
userId: userIdSchema,
})),
async (context) => {
diff --git a/apps/papra-server/src/modules/organizations/organization.schemas.ts b/apps/papra-server/src/modules/organizations/organization.schemas.ts
new file mode 100644
index 00000000..197a5bcd
--- /dev/null
+++ b/apps/papra-server/src/modules/organizations/organization.schemas.ts
@@ -0,0 +1,6 @@
+import { createRegexSchema } from '../shared/schemas/string.schemas';
+import { ORGANIZATION_ID_REGEX, ORGANIZATION_INVITATION_ID_REGEX, ORGANIZATION_MEMBER_ID_REGEX } from './organizations.constants';
+
+export const organizationIdSchema = createRegexSchema(ORGANIZATION_ID_REGEX);
+export const memberIdSchema = createRegexSchema(ORGANIZATION_MEMBER_ID_REGEX);
+export const invitationIdSchema = createRegexSchema(ORGANIZATION_INVITATION_ID_REGEX);
diff --git a/apps/papra-server/src/modules/shared/schemas/pagination.schemas.test.ts b/apps/papra-server/src/modules/shared/schemas/pagination.schemas.test.ts
new file mode 100644
index 00000000..e4cd8c0c
--- /dev/null
+++ b/apps/papra-server/src/modules/shared/schemas/pagination.schemas.test.ts
@@ -0,0 +1,107 @@
+import * as v from 'valibot';
+import { describe, expect, test } from 'vitest';
+import { createQueryPaginationSchemaKeys } from './pagination.schemas';
+
+describe('pagination.schemas', () => {
+ describe('createQueryPaginationSchemaKeys', () => {
+ describe('start-time guards on options', () => {
+ test('it throws if defaultPageSize is less than 1', () => {
+ expect(() => createQueryPaginationSchemaKeys({ defaultPageSize: 0 })).toThrow('defaultPageSize must be at least 1');
+ expect(() => createQueryPaginationSchemaKeys({ defaultPageSize: -1 })).toThrow('defaultPageSize must be at least 1');
+ });
+
+ test('it throws if maxPageSize is less than 1', () => {
+ expect(() => createQueryPaginationSchemaKeys({ maxPageSize: 0 })).toThrow('maxPageSize must be at least 1');
+ expect(() => createQueryPaginationSchemaKeys({ maxPageSize: -1 })).toThrow('maxPageSize must be at least 1');
+ });
+
+ test('it throws if defaultPageSize is greater than maxPageSize', () => {
+ expect(() => createQueryPaginationSchemaKeys({ defaultPageSize: 50, maxPageSize: 10 })).toThrow('defaultPageSize cannot be greater than maxPageSize');
+ });
+
+ test('it does not throw when defaultPageSize equals maxPageSize', () => {
+ expect(() => createQueryPaginationSchemaKeys({ defaultPageSize: 10, maxPageSize: 10 })).not.toThrow();
+ });
+ });
+
+ describe('validate and coerce string query params about pagination', () => {
+ test('a page index should be an integer string greater or equal to 0, defaulting to 0 if not provided', () => {
+ const { pageIndex } = createQueryPaginationSchemaKeys();
+
+ expect(v.parse(pageIndex, '0')).toBe(0);
+ expect(v.parse(pageIndex, '1')).toBe(1);
+ expect(v.parse(pageIndex, '1205')).toBe(1205);
+ expect(v.parse(pageIndex, String(Number.MAX_SAFE_INTEGER))).toBe(Number.MAX_SAFE_INTEGER);
+
+ expect(v.parse(pageIndex, undefined)).toBe(0);
+
+ expect(() => v.parse(pageIndex, '-1')).toThrow();
+ expect(() => v.parse(pageIndex, '1.5')).toThrow();
+ expect(() => v.parse(pageIndex, 1)).toThrow();
+ expect(() => v.parse(pageIndex, 'abc')).toThrow();
+ expect(() => v.parse(pageIndex, Number.NaN)).toThrow();
+ expect(() => v.parse(pageIndex, String(Number.MAX_SAFE_INTEGER + 1))).toThrow();
+ });
+
+ test('a page size should be an integer string between 1 and maxPageSize (100 by default), defaulting to defaultPageSize (25 by default) if not provided', () => {
+ const { pageSize } = createQueryPaginationSchemaKeys();
+
+ expect(v.parse(pageSize, '1')).toBe(1);
+ expect(v.parse(pageSize, '25')).toBe(25);
+ expect(v.parse(pageSize, '100')).toBe(100);
+
+ expect(v.parse(pageSize, undefined)).toBe(25);
+
+ expect(() => v.parse(pageSize, '0')).toThrow();
+ expect(() => v.parse(pageSize, '101')).toThrow();
+ expect(() => v.parse(pageSize, '-1')).toThrow();
+ expect(() => v.parse(pageSize, '1.5')).toThrow();
+ expect(() => v.parse(pageSize, 1)).toThrow();
+ expect(() => v.parse(pageSize, 'abc')).toThrow();
+ expect(() => v.parse(pageSize, Number.NaN)).toThrow();
+ });
+
+ test('it should be possible to customize maxPageSize and defaultPageSize', () => {
+ const { pageSize } = createQueryPaginationSchemaKeys({ maxPageSize: 50, defaultPageSize: 10 });
+
+ expect(v.parse(pageSize, '1')).toBe(1);
+ expect(v.parse(pageSize, '10')).toBe(10);
+ expect(v.parse(pageSize, '50')).toBe(50);
+
+ expect(v.parse(pageSize, undefined)).toBe(10);
+
+ expect(() => v.parse(pageSize, '0')).toThrow();
+ expect(() => v.parse(pageSize, '51')).toThrow();
+ });
+
+ test('it\'s possible to build an object schema with the pagination keys and validate an object with them', () => {
+ expect(
+ v.parse(
+ v.strictObject(createQueryPaginationSchemaKeys()),
+ { pageIndex: '2', pageSize: '30' },
+ ),
+ ).toEqual(
+ { pageIndex: 2, pageSize: 30 },
+ );
+
+ expect(
+ v.parse(
+ v.strictObject(createQueryPaginationSchemaKeys()),
+ {},
+ ),
+ ).toEqual(
+ { pageIndex: 0, pageSize: 25 },
+ );
+
+ expect(
+ v.parse(
+ v.strictObject({ ...createQueryPaginationSchemaKeys() }),
+ {},
+ ),
+ ).toEqual(
+ { pageIndex: 0, pageSize: 25 },
+ );
+ });
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/shared/schemas/pagination.schemas.ts b/apps/papra-server/src/modules/shared/schemas/pagination.schemas.ts
new file mode 100644
index 00000000..c8cd808b
--- /dev/null
+++ b/apps/papra-server/src/modules/shared/schemas/pagination.schemas.ts
@@ -0,0 +1,20 @@
+import * as v from 'valibot';
+
+export function createQueryPaginationSchemaKeys({ maxPageSize = 100, defaultPageSize = 25 }: { maxPageSize?: number; defaultPageSize?: number } = {}) {
+ if (defaultPageSize < 1) {
+ throw new Error('defaultPageSize must be at least 1');
+ }
+
+ if (maxPageSize < 1) {
+ throw new Error('maxPageSize must be at least 1');
+ }
+
+ if (defaultPageSize > maxPageSize) {
+ throw new Error('defaultPageSize cannot be greater than maxPageSize');
+ }
+
+ return {
+ pageIndex: v.optional(v.pipe(v.string(), v.toNumber(), v.safeInteger(), v.minValue(0)), '0'),
+ pageSize: v.optional(v.pipe(v.string(), v.toNumber(), v.safeInteger(), v.minValue(1), v.maxValue(maxPageSize)), String(defaultPageSize)),
+ };
+}
diff --git a/apps/papra-server/src/modules/shared/schemas/string.schemas.ts b/apps/papra-server/src/modules/shared/schemas/string.schemas.ts
new file mode 100644
index 00000000..4a1acf77
--- /dev/null
+++ b/apps/papra-server/src/modules/shared/schemas/string.schemas.ts
@@ -0,0 +1,5 @@
+import * as v from 'valibot';
+
+export function createRegexSchema(regex: RegExp, errorMessage?: string) {
+ return v.pipe(v.string(), v.regex(regex, errorMessage));
+}
diff --git a/apps/papra-server/src/modules/users/users.schemas.ts b/apps/papra-server/src/modules/users/users.schemas.ts
new file mode 100644
index 00000000..790cbfa1
--- /dev/null
+++ b/apps/papra-server/src/modules/users/users.schemas.ts
@@ -0,0 +1,4 @@
+import { createRegexSchema } from '../shared/schemas/string.schemas';
+import { USER_ID_REGEX } from './users.constants';
+
+export const userIdSchema = createRegexSchema(USER_ID_REGEX);