Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

refactor(api): typesafe route definition (#1556)

Corentin Thomassetb5763bb24f3a
diff --git a/.changeset/empty-sheep-swim.md b/.changeset/empty-sheep-swim.md
new file mode 100644
index 00000000..023933a7
--- /dev/null
+++ b/.changeset/empty-sheep-swim.md
@@ -0,0 +1,5 @@
+---
+'@papra/api-sdk': minor
+---
+
+Added auto-generated methods from the new api definition
diff --git a/.changeset/social-peas-prove.md b/.changeset/social-peas-prove.md
new file mode 100644
index 00000000..ff56c419
--- /dev/null
+++ b/.changeset/social-peas-prove.md
@@ -0,0 +1,5 @@
+---
+'@papra/app': patch
+---
+
+API breaking change: PUT /api/users/me now returns only id, email, name, createdAt, updatedAt, and twoFactorEnabled instead of the full user object.
diff --git a/apps/papra-server/README.md b/apps/papra-server/README.md
index 78277529..d735de4f 100644
--- a/apps/papra-server/README.md
+++ b/apps/papra-server/README.md
@@ -2,6 +2,8 @@
This is the server for [Papra](https://papra.app).
+For API changes, see the [API route migration guide](./src/modules/api/README.md).
+
## Development
To start the development server, run:
diff --git a/apps/papra-server/package.json b/apps/papra-server/package.json
index 3bc29127..1feac6fc 100644
--- a/apps/papra-server/package.json
+++ b/apps/papra-server/package.json
@@ -11,7 +11,8 @@
"./organizations/constants": "./src/modules/organizations/organizations.constants.ts",
"./customProperties/constants": "./src/modules/custom-properties/custom-properties.constants.ts",
"./apiKeys/constants": "./src/modules/api-keys/api-keys.constants.ts",
- "./plans/constants": "./src/modules/plans/plans.constants.ts"
+ "./plans/constants": "./src/modules/plans/plans.constants.ts",
+ "./api/contract": "./src/modules/api/api.contracts.registry.ts"
},
"scripts": {
"dev": "tsx watch --env-file-if-exists=.env src/index.ts | crowlog-pretty",
@@ -88,6 +89,7 @@
"picomatch": "^4.0.4",
"posthog-node": "^5.20.0",
"resend": "^4.6.0",
+ "rou3": "^0.12.0",
"s3mini": "^0.9.5",
"stripe": "^17.7.0",
"tsx": "catalog:",
diff --git a/apps/papra-server/src/modules/api-keys/api-keys.authentication.test.ts b/apps/papra-server/src/modules/api-keys/api-keys.authentication.test.ts
new file mode 100644
index 00000000..d4e79879
--- /dev/null
+++ b/apps/papra-server/src/modules/api-keys/api-keys.authentication.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, expectTypeOf, test } from 'vitest';
+import { buildGetApiKeyFromHeaders } from './api-keys.authentication';
+
+const token = `ppapi_${'a'.repeat(64)}`;
+
+describe('buildGetApiKeyFromHeaders', () => {
+ test('requests without an Authorization header do not look up API keys', async () => {
+ let lookupCalled = false;
+ const getApiKey = buildGetApiKeyFromHeaders({
+ lookupApiKeyByToken: async () => {
+ lookupCalled = true;
+ return null;
+ },
+ });
+
+ expect(await getApiKey({ headers: new Headers() })).toEqual(null);
+ expect(lookupCalled).toEqual(false);
+ });
+
+ test('other bearer tokens are left for downstream handlers without a lookup', async () => {
+ let lookupCalled = false;
+ const getApiKey = buildGetApiKeyFromHeaders({
+ lookupApiKeyByToken: async () => {
+ lookupCalled = true;
+ return null;
+ },
+ });
+
+ expect(
+ await getApiKey({ headers: new Headers({ Authorization: 'Bearer share.link.jwt' }) }),
+ ).toEqual(null);
+ expect(lookupCalled).toEqual(false);
+ });
+
+ test('API-key-shaped tokens are passed to the lookup and preserve its result type', async () => {
+ const apiKey = { apiKeyId: 'ak_123', userId: 'usr_123' };
+ const lookedUpTokens: string[] = [];
+ const getApiKey = buildGetApiKeyFromHeaders({
+ lookupApiKeyByToken: async ({ token }) => {
+ lookedUpTokens.push(token);
+ return apiKey;
+ },
+ });
+
+ const result = await getApiKey({ headers: new Headers({ authorization: `Bearer ${token}` }) });
+
+ expectTypeOf(result).toEqualTypeOf<typeof apiKey | null>();
+ expect(result).toEqual(apiKey);
+ expect(lookedUpTokens).toEqual([token]);
+ });
+
+ test('unknown or expired keys remain unauthenticated when the lookup returns null', async () => {
+ const getApiKey = buildGetApiKeyFromHeaders({ lookupApiKeyByToken: async () => null });
+
+ expect(await getApiKey({ headers: new Headers({ Authorization: `Bearer ${token}` }) })).toEqual(
+ null,
+ );
+ });
+
+ test('malformed Authorization headers are rejected before lookup', async () => {
+ let lookupCalled = false;
+ const getApiKey = buildGetApiKeyFromHeaders({
+ lookupApiKeyByToken: async () => {
+ lookupCalled = true;
+ return null;
+ },
+ });
+
+ await expect(
+ getApiKey({ headers: new Headers({ Authorization: `Bearer ${token} extra` }) }),
+ ).rejects.toMatchObject({
+ statusCode: 401,
+ code: 'auth.unauthorized',
+ });
+ expect(lookupCalled).toEqual(false);
+ });
+
+ test('non-Bearer authorization schemes are rejected before lookup', async () => {
+ let lookupCalled = false;
+ const getApiKey = buildGetApiKeyFromHeaders({
+ lookupApiKeyByToken: async () => {
+ lookupCalled = true;
+ return null;
+ },
+ });
+
+ await expect(
+ getApiKey({ headers: new Headers({ Authorization: `Basic ${token}` }) }),
+ ).rejects.toMatchObject({
+ statusCode: 401,
+ code: 'auth.unauthorized',
+ });
+ expect(lookupCalled).toEqual(false);
+ });
+
+ test('lookup failures propagate rather than masquerading as missing credentials', async () => {
+ const error = new Error('API-key storage unavailable');
+ const getApiKey = buildGetApiKeyFromHeaders({
+ lookupApiKeyByToken: async () => {
+ throw error;
+ },
+ });
+
+ await expect(
+ getApiKey({ headers: new Headers({ Authorization: `Bearer ${token}` }) }),
+ ).rejects.toEqual(error);
+ });
+});
diff --git a/apps/papra-server/src/modules/api-keys/api-keys.authentication.ts b/apps/papra-server/src/modules/api-keys/api-keys.authentication.ts
new file mode 100644
index 00000000..52f7ddfc
--- /dev/null
+++ b/apps/papra-server/src/modules/api-keys/api-keys.authentication.ts
@@ -0,0 +1,17 @@
+import { extractApiKeyToken } from './api-keys.models';
+
+export function buildGetApiKeyFromHeaders<Key>({
+ lookupApiKeyByToken,
+}: {
+ lookupApiKeyByToken: (args: { token: string }) => Promise<Key | null>;
+}) {
+ return async ({ headers }: { headers: Headers }): Promise<Key | null> => {
+ const token = extractApiKeyToken({ headers });
+
+ if (token === undefined) {
+ return null;
+ }
+
+ return lookupApiKeyByToken({ token });
+ };
+}
diff --git a/apps/papra-server/src/modules/api-keys/api-keys.middlewares.ts b/apps/papra-server/src/modules/api-keys/api-keys.middlewares.ts
index 8651e3ef..b36684d2 100644
--- a/apps/papra-server/src/modules/api-keys/api-keys.middlewares.ts
+++ b/apps/papra-server/src/modules/api-keys/api-keys.middlewares.ts
@@ -1,11 +1,8 @@
import type { Database } from '../app/database/database.types';
import type { Context } from '../app/server.types';
import { createMiddleware } from 'hono/factory';
-import { createUnauthorizedError } from '../app/auth/auth.errors';
-import { getAuthorizationHeader } from '../shared/headers/headers.models';
import { addLogContext } from '../shared/logger/logger';
-import { isNil } from '../shared/utils';
-import { looksLikeAnApiKey } from './api-keys.models';
+import { buildGetApiKeyFromHeaders } from './api-keys.authentication';
import { createApiKeysRepository } from './api-keys.repository';
import { getApiKey } from './api-keys.usecases';
@@ -13,33 +10,15 @@ import { getApiKey } from './api-keys.usecases';
// and set it on the context, no auth enforcement is done here
export function createApiKeyMiddleware({ db }: { db: Database }) {
const apiKeyRepository = createApiKeysRepository({ db });
+ const getApiKeyFromHeaders = buildGetApiKeyFromHeaders({
+ lookupApiKeyByToken: async ({ token }) => {
+ const { apiKey } = await getApiKey({ token, apiKeyRepository });
+ return apiKey ?? null;
+ },
+ });
return createMiddleware(async (context: Context, next) => {
- const { authorizationHeader } = getAuthorizationHeader({ context });
-
- if (isNil(authorizationHeader)) {
- return next();
- }
-
- const parts = authorizationHeader.split(' ');
-
- if (parts.length !== 2) {
- throw createUnauthorizedError();
- }
-
- const [maybeBearer, token] = parts;
-
- if (maybeBearer !== 'Bearer') {
- throw createUnauthorizedError();
- }
-
- // The token isn't an API key (e.g. a share-link access token JWT). Leave it for
- // downstream handlers; protected routes still enforce auth via requireAuthentication.
- if (!looksLikeAnApiKey(token)) {
- return next();
- }
-
- const { apiKey } = await getApiKey({ token, apiKeyRepository });
+ const apiKey = await getApiKeyFromHeaders({ headers: context.req.raw.headers });
if (apiKey) {
const userId = apiKey.userId;
diff --git a/apps/papra-server/src/modules/api-keys/api-keys.models.ts b/apps/papra-server/src/modules/api-keys/api-keys.models.ts
index 21ff6188..00a45a4a 100644
--- a/apps/papra-server/src/modules/api-keys/api-keys.models.ts
+++ b/apps/papra-server/src/modules/api-keys/api-keys.models.ts
@@ -1,3 +1,4 @@
+import { createUnauthorizedError } from '../app/auth/auth.errors';
import { sha256 } from '../shared/crypto/hash';
import { isNil } from '../shared/utils';
import { API_KEY_PREFIX, API_KEY_TOKEN_REGEX } from './api-keys.constants';
@@ -14,6 +15,24 @@ export function getApiKeyHash({ token }: { token: string }) {
};
}
+export function extractApiKeyToken({ headers }: { headers: Headers }): string | undefined {
+ const authorizationHeader = headers.get('Authorization');
+
+ if (authorizationHeader === null) {
+ return undefined;
+ }
+
+ const parts = authorizationHeader.split(' ');
+ const [scheme, token] = parts;
+
+ if (parts.length !== 2 || scheme !== 'Bearer') {
+ throw createUnauthorizedError();
+ }
+
+ // Other bearer tokens (such as share-link JWTs) belong to downstream handlers.
+ return looksLikeAnApiKey(token) ? token : undefined;
+}
+
// Positional argument as TS does not like named argument with type guards
export function looksLikeAnApiKey(token?: string | null): token is string {
if (isNil(token)) {
diff --git a/apps/papra-server/src/modules/api/README.md b/apps/papra-server/src/modules/api/README.md
new file mode 100644
index 00000000..6a09c6b0
--- /dev/null
+++ b/apps/papra-server/src/modules/api/README.md
@@ -0,0 +1,37 @@
+# API routes
+
+## New API definition system
+
+Starting october 2026 we use a new contract-based system to define our API routes.
+
+- it allows for auto generating a type-safe sdk for the api
+- it opens the door for auto generating openapi documentation
+- it removes the coupling with hono
+
+**Contracts**
+
+- define the HTTP interface: method, path, request and response schemas, and status codes
+- used by the server to validate and serialize requests and responses
+- used by the SDK to generate client methods and types
+- defined in `*.api.contracts.ts` files, colocated within their domain feature
+- registered in `api.contracts.registry.ts` to be exported by the SDK
+- examples: [users](../users/users.api.contracts.ts)
+- schemas for "inputs" (body, params, query, ...) can have transforms
+- schemas for "outputs" (response) must result in json serializable and not depend on transforms, output as input style
+- on the server, responses are not run through the schema at runtime, used only for type inference
+- contracts are exported by the server and imported by the SDK package and inlined at build time, no runtime dependency on the server
+- path parameter (aka params) are expected to not require encoding, only [a-zA-Z0-9_-], id style
+
+**Routes**
+
+- implement the business logic for a contract
+- defined in `*.api.routes.ts`
+- not to be confused with the legacy `*.routes.ts` files, having both help migrate incrementally
+- registered in `server.api.routes.ts`
+- examples: [users](../users/users.api.routes.ts)
+
+## Legacy API routes
+
+- defined in `*.routes.ts` files, colocated within their domain feature
+- they need to be migrated to the new system, but can coexist with the new routes during migration
+- migrating a route should be as-is, with no change in behavior, refining the contract is ok as long as it doesn't break the existing behavior
diff --git a/apps/papra-server/src/modules/api/api.authentication.test.ts b/apps/papra-server/src/modules/api/api.authentication.test.ts
new file mode 100644
index 00000000..a357a3cf
--- /dev/null
+++ b/apps/papra-server/src/modules/api/api.authentication.test.ts
@@ -0,0 +1,180 @@
+import type { ApiKeyPermissions } from '../api-keys/api-keys.types';
+import { describe, expect, test } from 'vitest';
+import { buildGetApiKeyFromHeaders } from '../api-keys/api-keys.authentication';
+import { wrapWithLoggerContext } from '../shared/logger/logger';
+import { buildResolveAuthenticationContext } from './api.authentication';
+
+const token = `ppapi_${'a'.repeat(64)}`;
+const apiKey = {
+ userId: 'usr_123',
+ apiKeyId: 'ak_123',
+ permissions: ['documents:read', 'tags:read'] satisfies ApiKeyPermissions[],
+};
+
+describe('buildResolveAuthenticationContext', () => {
+ test('session requests without an API-key token do not query API-key storage', async () => {
+ let lookupCalled = false;
+ const createResolver = buildResolveAuthenticationContext({
+ getSession: async ({ headers }) => {
+ expect(headers.get('Cookie')).toEqual('session=test');
+ return { userId: 'usr_session' };
+ },
+ getApiKey: buildGetApiKeyFromHeaders({
+ lookupApiKeyByToken: async () => {
+ lookupCalled = true;
+ return apiKey;
+ },
+ }),
+ });
+ const resolveContext = createResolver();
+ const request = new Request('https://papra.test', { headers: { Cookie: 'session=test' } });
+
+ const context = await wrapWithLoggerContext({}, async () => resolveContext({ request }));
+
+ expect(context).toEqual({ userId: 'usr_session', authType: 'session' });
+ expect(lookupCalled).toEqual(false);
+ });
+
+ test('a missing session on a session-only route is rejected without looking up an API key', async () => {
+ let lookupCalled = false;
+ const createResolver = buildResolveAuthenticationContext({
+ getSession: async () => null,
+ getApiKey: async () => {
+ lookupCalled = true;
+ return apiKey;
+ },
+ });
+ const resolveContext = createResolver();
+ const request = new Request('https://papra.test', {
+ headers: { Authorization: `Bearer ${token}` },
+ });
+
+ await expect(resolveContext({ request })).rejects.toMatchObject({
+ statusCode: 401,
+ code: 'auth.unauthorized',
+ });
+ expect(lookupCalled).toEqual(false);
+ });
+
+ test('simultaneous valid session and API-key credentials are rejected even for the same user', async () => {
+ const createResolver = buildResolveAuthenticationContext({
+ getSession: async () => ({ userId: apiKey.userId }),
+ getApiKey: buildGetApiKeyFromHeaders({ lookupApiKeyByToken: async () => apiKey }),
+ });
+ const request = new Request('https://papra.test', {
+ headers: { Authorization: `Bearer ${token}` },
+ });
+
+ await expect(createResolver()({ request })).rejects.toMatchObject({
+ statusCode: 401,
+ code: 'auth.unauthorized',
+ });
+ await expect(
+ createResolver({ apiKeyPermissions: ['documents:read'] })({ request }),
+ ).rejects.toMatchObject({
+ statusCode: 401,
+ code: 'auth.unauthorized',
+ });
+ });
+
+ test('an unrecognized or expired API key does not invalidate a valid session', async () => {
+ const lookedUpTokens: string[] = [];
+ const createResolver = buildResolveAuthenticationContext({
+ getSession: async () => ({ userId: 'usr_session' }),
+ getApiKey: buildGetApiKeyFromHeaders({
+ lookupApiKeyByToken: async ({ token }) => {
+ lookedUpTokens.push(token);
+ return null;
+ },
+ }),
+ });
+ const resolveContext = createResolver();
+ const request = new Request('https://papra.test', {
+ headers: { Authorization: `Bearer ${token}` },
+ });
+
+ const context = await wrapWithLoggerContext({}, async () => resolveContext({ request }));
+
+ expect(context).toEqual({ userId: 'usr_session', authType: 'session' });
+ expect(lookedUpTokens).toEqual([token]);
+ });
+
+ test('API keys with every required permission provide their owner and key identity', async () => {
+ const createResolver = buildResolveAuthenticationContext({
+ getSession: async () => null,
+ getApiKey: async ({ headers }) => {
+ expect(headers.get('Authorization')).toEqual(`Bearer ${token}`);
+ return apiKey;
+ },
+ });
+ const resolveContext = createResolver({ apiKeyPermissions: ['documents:read', 'tags:read'] });
+ const request = new Request('https://papra.test', {
+ headers: { Authorization: `Bearer ${token}` },
+ });
+
+ const context = await wrapWithLoggerContext({}, async () => resolveContext({ request }));
+
+ expect(context).toEqual({ userId: 'usr_123', apiKeyId: 'ak_123', authType: 'api-key' });
+ });
+
+ test('API keys missing any required permission are rejected', async () => {
+ const createResolver = buildResolveAuthenticationContext({
+ getSession: async () => null,
+ getApiKey: async () => apiKey,
+ });
+ const resolveContext = createResolver({
+ apiKeyPermissions: ['documents:read', 'documents:update'],
+ });
+
+ await expect(
+ resolveContext({ request: new Request('https://papra.test') }),
+ ).rejects.toMatchObject({
+ statusCode: 401,
+ code: 'auth.unauthorized',
+ });
+ });
+
+ test('an explicit empty permission list accepts valid API keys without permissions', async () => {
+ const createResolver = buildResolveAuthenticationContext({
+ getSession: async () => null,
+ getApiKey: async () => ({ ...apiKey, permissions: [] }),
+ });
+ const resolveContext = createResolver({ apiKeyPermissions: [] });
+
+ const context = await wrapWithLoggerContext({}, async () =>
+ resolveContext({ request: new Request('https://papra.test') }),
+ );
+
+ expect(context).toEqual({ userId: 'usr_123', apiKeyId: 'ak_123', authType: 'api-key' });
+ });
+
+ test('requests without valid credentials are rejected even when API keys are allowed', async () => {
+ const createResolver = buildResolveAuthenticationContext({
+ getSession: async () => null,
+ getApiKey: async () => null,
+ });
+ const resolveContext = createResolver({ apiKeyPermissions: [] });
+
+ await expect(
+ resolveContext({ request: new Request('https://papra.test') }),
+ ).rejects.toMatchObject({
+ statusCode: 401,
+ code: 'auth.unauthorized',
+ });
+ });
+
+ test('authentication lookup failures propagate instead of becoming unauthorized errors', async () => {
+ const error = new Error('API-key storage unavailable');
+ const createResolver = buildResolveAuthenticationContext({
+ getSession: async () => null,
+ getApiKey: async () => {
+ throw error;
+ },
+ });
+ const resolveContext = createResolver({ apiKeyPermissions: ['documents:read'] });
+
+ await expect(resolveContext({ request: new Request('https://papra.test') })).rejects.toEqual(
+ error,
+ );
+ });
+});
diff --git a/apps/papra-server/src/modules/api/api.authentication.ts b/apps/papra-server/src/modules/api/api.authentication.ts
new file mode 100644
index 00000000..1b4899ab
--- /dev/null
+++ b/apps/papra-server/src/modules/api/api.authentication.ts
@@ -0,0 +1,103 @@
+import { addLogContext } from '@crowlog/async-context-plugin';
+import type { ApiKeyPermissions } from '../api-keys/api-keys.types';
+import { createUnauthorizedError } from '../app/auth/auth.errors';
+import type { Database } from '../app/database/database.types';
+import { buildGetApiKeyFromHeaders } from '../api-keys/api-keys.authentication';
+import { getApiKey } from '../api-keys/api-keys.usecases';
+import { createApiKeysRepository } from '../api-keys/api-keys.repository';
+
+export function buildGetSession({
+ auth,
+}: {
+ auth: {
+ api: { getSession: (args: { headers: Headers }) => Promise<{ user: { id: string } } | null> };
+ };
+}) {
+ return async ({ headers }: { headers: Headers }): Promise<{ userId: string } | null> => {
+ const session = await auth.api.getSession({ headers });
+
+ return session ? { userId: session.user.id } : null;
+ };
+}
+
+export function buildGetApiKey({ db }: { db: Database }) {
+ const apiKeyRepository = createApiKeysRepository({ db });
+
+ return buildGetApiKeyFromHeaders({
+ lookupApiKeyByToken: async ({ token }) => {
+ const { apiKey } = await getApiKey({ token, apiKeyRepository });
+ return apiKey
+ ? { userId: apiKey.userId, permissions: apiKey.permissions, apiKeyId: apiKey.id }
+ : null;
+ },
+ });
+}
+
+export function buildResolveAuthenticationContext({
+ getSession,
+ getApiKey,
+}: {
+ getSession: (args: { headers: Headers }) => Promise<{ userId: string } | null>;
+ getApiKey: (args: {
+ headers: Headers;
+ }) => Promise<{ userId: string; permissions: ApiKeyPermissions[]; apiKeyId: string } | null>;
+}) {
+ return ({ apiKeyPermissions }: { apiKeyPermissions?: ApiKeyPermissions[] } = {}) =>
+ async ({
+ request,
+ }: {
+ request: Request;
+ }): Promise<
+ | { userId: string; authType: 'session' }
+ | { userId: string; apiKeyId: string; authType: 'api-key' }
+ > => {
+ const headers = request.headers;
+
+ const session = await getSession({ headers });
+
+ if (session) {
+ // Reject ambiguous credentials, even on session-only routes. The injected
+ // lookup must return null without querying storage when no API-key token is present.
+ if (await getApiKey({ headers })) {
+ throw createUnauthorizedError();
+ }
+
+ const context = {
+ userId: session.userId,
+ authType: 'session' as const,
+ };
+
+ addLogContext(context);
+ return context;
+ }
+
+ if (apiKeyPermissions === undefined) {
+ throw createUnauthorizedError();
+ }
+
+ const apiKey = await getApiKey({ headers });
+
+ if (!apiKey) {
+ throw createUnauthorizedError();
+ }
+
+ const hasAllPermissions = apiKeyPermissions.every((permission) =>
+ apiKey.permissions.includes(permission),
+ );
+
+ if (!hasAllPermissions) {
+ throw createUnauthorizedError();
+ }
+
+ const context = {
+ userId: apiKey.userId,
+ apiKeyId: apiKey.apiKeyId,
+ authType: 'api-key' as const,
+ };
+
+ addLogContext(context);
+ return context;
+ };
+}
+
+export type ResolveAuthenticationContext = ReturnType<typeof buildResolveAuthenticationContext>;
diff --git a/apps/papra-server/src/modules/api/api.contracts.registry.ts b/apps/papra-server/src/modules/api/api.contracts.registry.ts
new file mode 100644
index 00000000..0cc04334
--- /dev/null
+++ b/apps/papra-server/src/modules/api/api.contracts.registry.ts
@@ -0,0 +1,8 @@
+import { getCurrentUserContract, updateCurrentUserContract } from '../users/users.api.contracts';
+
+export type { ApiContract } from './api.contracts';
+
+export const apiContracts = {
+ getCurrentUser: getCurrentUserContract,
+ updateCurrentUser: updateCurrentUserContract,
+};
diff --git a/apps/papra-server/src/modules/api/api.contracts.ts b/apps/papra-server/src/modules/api/api.contracts.ts
new file mode 100644
index 00000000..cf26fd1d
--- /dev/null
+++ b/apps/papra-server/src/modules/api/api.contracts.ts
@@ -0,0 +1,41 @@
+import type { GenericSchema } from 'valibot';
+import type { ApiRequestBodySchemas } from './requests/requests.types';
+import type {
+ ApiResponseBodylessStatus,
+ ApiResponseContentType,
+} from './responses/responses.types';
+
+type ApiResponseDefinition = {
+ description: string;
+ content: Partial<Record<ApiResponseContentType, { schema: GenericSchema }>>;
+};
+
+type ApiBodylessResponseDefinition = {
+ description: string;
+ content: Record<string, never>;
+};
+
+export type ApiContract = {
+ path: string;
+ request?: {
+ query?: GenericSchema;
+ body?: ApiRequestBodySchemas;
+ params?: GenericSchema;
+ };
+} & (
+ | {
+ method: 'HEAD';
+ responses: Record<number, ApiBodylessResponseDefinition>;
+ }
+ | {
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE';
+ responses: Record<number, ApiResponseDefinition> &
+ Partial<Record<ApiResponseBodylessStatus, ApiBodylessResponseDefinition>>;
+ }
+);
+
+export function defineApiContract<const Contract extends ApiContract>(
+ contract: Contract,
+): Contract {
+ return contract;
+}
diff --git a/apps/papra-server/src/modules/api/api.request-handler.head.test.ts b/apps/papra-server/src/modules/api/api.request-handler.head.test.ts
new file mode 100644
index 00000000..ab3b42a7
--- /dev/null
+++ b/apps/papra-server/src/modules/api/api.request-handler.head.test.ts
@@ -0,0 +1,319 @@
+import * as v from 'valibot';
+import { describe, expect, test } from 'vitest';
+import { createUnauthorizedError } from '../app/auth/auth.errors';
+import { createError } from '../shared/errors/errors';
+import { createTestLogger } from '../shared/logger/logger.test-utils';
+import { defineApiContract } from './api.contracts';
+import { buildApiRequestHandler } from './api.request-handler';
+import { defineApiRoute } from './api.routes';
+
+const getDocumentRoute = defineApiRoute({
+ contract: defineApiContract({
+ method: 'GET',
+ path: '/api/documents/:documentId',
+ request: {
+ params: v.object({ documentId: v.pipe(v.string(), v.startsWith('doc_')) }),
+ query: v.object({ format: v.optional(v.literal('text')) }),
+ },
+ responses: {
+ 200: {
+ description: 'The document content.',
+ content: { 'text/plain': { schema: v.string() } },
+ },
+ 404: {
+ description: 'The document does not exist.',
+ content: { 'text/plain': { schema: v.string() } },
+ },
+ },
+ }),
+ handler: async () => ({
+ status: 200,
+ contentType: 'text/plain',
+ body: 'Hello',
+ headers: { 'Content-Length': '5', 'ETag': '"v1"', 'X-Route': 'get' },
+ }),
+});
+
+const headDocumentContract = defineApiContract({
+ ...getDocumentRoute.contract,
+ method: 'HEAD',
+ responses: {
+ 200: { description: 'The document metadata.', content: {} },
+ 404: { description: 'The document does not exist.', content: {} },
+ },
+});
+
+describe('HEAD request handling', () => {
+ test('explicit HEAD routes take precedence over GET without changing GET behavior', async () => {
+ const handleApiRequest = buildApiRequestHandler({
+ routes: [
+ getDocumentRoute,
+ defineApiRoute({
+ contract: headDocumentContract,
+ handler: async () => ({
+ status: 200,
+ headers: {
+ 'Content-Type': 'text/plain',
+ 'Content-Length': '5',
+ 'ETag': '"v1"',
+ 'X-Route': 'head',
+ },
+ }),
+ }),
+ ],
+ });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/documents/doc_123', { method: 'HEAD' }),
+ });
+ const getResponse = await handleApiRequest({
+ request: new Request('https://papra.test/api/documents/doc_123'),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(200);
+ expect(response.headers.get('X-Route')).toEqual('head');
+ expect(response.headers.get('Content-Type')).toEqual('text/plain');
+ expect(response.headers.get('Content-Length')).toEqual('5');
+ expect(response.headers.get('ETag')).toEqual('"v1"');
+ expect(response.body).toEqual(null);
+ expect(await response.text()).toEqual('');
+ expect.assert(getResponse);
+ expect(getResponse.status).toEqual(200);
+ expect(getResponse.headers.get('X-Route')).toEqual('get');
+ expect(await getResponse.text()).toEqual('Hello');
+ });
+
+ test('GET fallback validates inputs and passes the original HEAD request through context and handler', async () => {
+ const seenRequests: Request[] = [];
+ const handleApiRequest = buildApiRequestHandler({
+ routes: [
+ defineApiRoute({
+ contract: getDocumentRoute.contract,
+ resolveContext: ({ request }) => {
+ seenRequests.push(request);
+ return { method: request.method };
+ },
+ handler: async (input) => {
+ seenRequests.push(input.request);
+ expect(input.context).toEqual({ method: 'HEAD' });
+ expect(input.params).toEqual({ documentId: 'doc_123' });
+ expect(input.query).toEqual({ format: 'text' });
+ expect(input.body).toEqual(undefined);
+ return getDocumentRoute.handler({ ...input, context: undefined });
+ },
+ }),
+ ],
+ });
+ const request = new Request('https://papra.test/api/documents/doc_123?format=text', {
+ method: 'HEAD',
+ });
+
+ const response = await handleApiRequest({ request });
+
+ expect.assert(response);
+ expect(response.status).toEqual(200);
+ expect(response.headers.get('X-Route')).toEqual('get');
+ expect(response.headers.get('Content-Type')).toEqual('text/plain; charset=utf-8');
+ expect(response.headers.get('Content-Length')).toEqual('5');
+ expect(response.headers.get('ETag')).toEqual('"v1"');
+ expect(response.body).toEqual(null);
+ expect(await response.text()).toEqual('');
+ expect(seenRequests.map((seenRequest) => seenRequest === request)).toEqual([true, true]);
+ });
+
+ test('a matched HEAD route returning 404 does not retry GET or fall through', async () => {
+ const handleApiRequest = buildApiRequestHandler({
+ routes: [
+ getDocumentRoute,
+ defineApiRoute({
+ contract: headDocumentContract,
+ handler: async () => ({ status: 404, headers: { 'X-Route': 'head' } }),
+ }),
+ ],
+ });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/documents/doc_123', { method: 'HEAD' }),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(404);
+ expect(response.headers.get('X-Route')).toEqual('head');
+ expect(response.body).toEqual(null);
+ });
+
+ test('a matched GET fallback returning 404 stays final and loses its body', async () => {
+ const handleApiRequest = buildApiRequestHandler({
+ routes: [
+ defineApiRoute({
+ contract: getDocumentRoute.contract,
+ handler: async () => ({ status: 404, contentType: 'text/plain', body: 'Not found' }),
+ }),
+ ],
+ });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/documents/doc_123', { method: 'HEAD' }),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(404);
+ expect(response.headers.get('Content-Type')).toEqual('text/plain; charset=utf-8');
+ expect(response.body).toEqual(null);
+ });
+
+ test('invalid HEAD path parameters return a bodyless validation error', async () => {
+ const handleApiRequest = buildApiRequestHandler({ routes: [getDocumentRoute] });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/documents/invalid', { method: 'HEAD' }),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(400);
+ expect(response.headers.get('Cache-Control')).toEqual('no-store');
+ expect(response.body).toEqual(null);
+ });
+
+ test('invalid HEAD query parameters return a bodyless validation error', async () => {
+ const handleApiRequest = buildApiRequestHandler({ routes: [getDocumentRoute] });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/documents/doc_123?format=json', {
+ method: 'HEAD',
+ }),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(400);
+ expect(response.headers.get('Cache-Control')).toEqual('no-store');
+ expect(response.body).toEqual(null);
+ });
+
+ test('GET fallback body parsing failures return bodyless responses', async () => {
+ const handleApiRequest = buildApiRequestHandler({
+ routes: [
+ defineApiRoute({
+ contract: defineApiContract({
+ ...getDocumentRoute.contract,
+ request: { body: { 'application/json': v.object({ name: v.string() }) } },
+ }),
+ handler: async () => ({ status: 200, contentType: 'text/plain', body: 'Hello' }),
+ }),
+ ],
+ });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/documents/doc_123', { method: 'HEAD' }),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(415);
+ expect(response.headers.get('Cache-Control')).toEqual('no-store');
+ expect(response.body).toEqual(null);
+ });
+
+ test('HEAD authentication failures preserve their status and headers without a body', async () => {
+ const { logger } = createTestLogger();
+ const handleApiRequest = buildApiRequestHandler({
+ logger,
+ routes: [
+ defineApiRoute({
+ ...getDocumentRoute,
+ resolveContext: () => {
+ throw createUnauthorizedError();
+ },
+ }),
+ ],
+ });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/documents/invalid', { method: 'HEAD' }),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(401);
+ expect(response.headers.get('Content-Type')).toEqual('application/json');
+ expect(response.headers.get('Cache-Control')).toEqual('no-store');
+ expect(response.body).toEqual(null);
+ });
+
+ test('public HEAD handler errors preserve their status without a body', async () => {
+ const { logger } = createTestLogger();
+ const handleApiRequest = buildApiRequestHandler({
+ logger,
+ routes: [
+ defineApiRoute({
+ contract: getDocumentRoute.contract,
+ handler: async () => {
+ throw createError({ statusCode: 410, message: 'Gone', code: 'document.gone' });
+ },
+ }),
+ ],
+ });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/documents/doc_123', { method: 'HEAD' }),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(410);
+ expect(response.headers.get('Cache-Control')).toEqual('no-store');
+ expect(response.body).toEqual(null);
+ });
+
+ test('unexpected HEAD handler failures return a bodyless non-cacheable 500', async () => {
+ const { logger } = createTestLogger();
+ const handleApiRequest = buildApiRequestHandler({
+ logger,
+ routes: [
+ defineApiRoute({
+ contract: headDocumentContract,
+ handler: async () => {
+ throw new Error('Sensitive details');
+ },
+ }),
+ ],
+ });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/documents/doc_123', { method: 'HEAD' }),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(500);
+ expect(response.headers.get('Cache-Control')).toEqual('no-store');
+ expect(response.body).toEqual(null);
+ });
+
+ test('HEAD requests without a HEAD or GET match fall through without resolving context', async () => {
+ let contextResolved = false;
+ const handleApiRequest = buildApiRequestHandler({
+ routes: [
+ defineApiRoute({
+ contract: defineApiContract({
+ method: 'POST',
+ path: '/api/documents',
+ responses: { 204: { description: 'Created.', content: {} } },
+ }),
+ resolveContext: () => {
+ contextResolved = true;
+ },
+ handler: async () => ({ status: 204 }),
+ }),
+ ],
+ });
+
+ const unmatchedMethodResponse = await handleApiRequest({
+ request: new Request('https://papra.test/api/documents', { method: 'HEAD' }),
+ });
+ const unmatchedPathResponse = await handleApiRequest({
+ request: new Request('https://papra.test/api/missing', { method: 'HEAD' }),
+ });
+
+ expect(unmatchedMethodResponse).toEqual(undefined);
+ expect(unmatchedPathResponse).toEqual(undefined);
+ expect(contextResolved).toEqual(false);
+ });
+});
diff --git a/apps/papra-server/src/modules/api/api.request-handler.test.ts b/apps/papra-server/src/modules/api/api.request-handler.test.ts
new file mode 100644
index 00000000..c16f1f64
--- /dev/null
+++ b/apps/papra-server/src/modules/api/api.request-handler.test.ts
@@ -0,0 +1,545 @@
+import * as v from 'valibot';
+import { describe, expect, test } from 'vitest';
+import { createUnauthorizedError } from '../app/auth/auth.errors';
+import { createError } from '../shared/errors/errors';
+import { createTestLogger } from '../shared/logger/logger.test-utils';
+import { defineApiContract } from './api.contracts';
+import { buildApiRequestHandler } from './api.request-handler';
+import { defineApiRoute } from './api.routes';
+
+const echoRoute = defineApiRoute({
+ contract: defineApiContract({
+ method: 'POST',
+ path: '/api/users/:userId',
+ request: {
+ body: {
+ 'application/json': v.strictObject({ name: v.pipe(v.string(), v.trim()) }),
+ },
+ query: v.object({ limit: v.pipe(v.string(), v.transform(Number)) }),
+ params: v.object({ userId: v.pipe(v.string(), v.startsWith('usr_')) }),
+ },
+ responses: {
+ 201: {
+ description: 'Echoes the parsed request.',
+ content: {
+ 'application/json': {
+ schema: v.object({
+ body: v.object({ name: v.string() }),
+ query: v.object({ limit: v.number() }),
+ params: v.object({ userId: v.string() }),
+ method: v.string(),
+ }),
+ },
+ },
+ },
+ },
+ }),
+ handler: async ({ body, query, params, request }) => ({
+ status: 201,
+ contentType: 'application/json',
+ body: { body, query, params, method: request.method },
+ headers: { 'X-Request-Id': 'request-1' },
+ }),
+});
+
+describe('buildApiRequestHandler', () => {
+ test('matched routes receive parsed input and return serialized responses', async () => {
+ const handleApiRequest = buildApiRequestHandler({ routes: [echoRoute] });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/users/usr_123?limit=10', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json; charset=utf-8' },
+ body: JSON.stringify({ name: ' Alice ' }),
+ }),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(201);
+ expect(response.headers.get('Content-Type')).toEqual('application/json');
+ expect(response.headers.get('X-Request-Id')).toEqual('request-1');
+ expect(await response.json()).toEqual({
+ body: { name: 'Alice' },
+ query: { limit: 10 },
+ params: { userId: 'usr_123' },
+ method: 'POST',
+ });
+ });
+
+ test('context resolves once per request before validation and is passed to the handler', async () => {
+ const events: string[] = [];
+ const handleApiRequest = buildApiRequestHandler({
+ routes: [
+ echoRoute,
+ defineApiRoute({
+ contract: defineApiContract({
+ ...echoRoute.contract,
+ path: '/api/context/:userId',
+ request: {
+ params: v.pipe(
+ echoRoute.contract.request.params,
+ v.transform((params) => {
+ events.push('params');
+ return params;
+ }),
+ ),
+ query: v.pipe(
+ echoRoute.contract.request.query,
+ v.transform((query) => {
+ events.push('query');
+ return query;
+ }),
+ ),
+ body: {
+ 'application/json': v.pipe(
+ echoRoute.contract.request.body['application/json'],
+ v.transform((body) => {
+ events.push('body');
+ return body;
+ }),
+ ),
+ },
+ },
+ }),
+ resolveContext: async ({ request }) => {
+ events.push('resolve:start');
+ await Promise.resolve();
+ events.push('resolve:end');
+ return { requestId: request.headers.get('X-Request-Id') ?? 'unknown' };
+ },
+ handler: async ({ context, body, query, params, request }) => {
+ events.push('handler');
+ return {
+ status: 201,
+ contentType: 'application/json',
+ body: { body, query, params, method: request.method },
+ headers: { 'X-Request-Id': context.requestId },
+ };
+ },
+ }),
+ ],
+ });
+
+ const sendRequest = async (requestId: string) =>
+ handleApiRequest({
+ request: new Request('https://papra.test/api/context/usr_123?limit=10', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', 'X-Request-Id': requestId },
+ body: JSON.stringify({ name: ' Alice ' }),
+ }),
+ });
+
+ const firstResponse = await sendRequest('request-1');
+ const secondResponse = await sendRequest('request-2');
+
+ expect.assert(firstResponse);
+ expect.assert(secondResponse);
+ expect(firstResponse.status).toEqual(201);
+ expect(secondResponse.status).toEqual(201);
+ expect(firstResponse.headers.get('X-Request-Id')).toEqual('request-1');
+ expect(secondResponse.headers.get('X-Request-Id')).toEqual('request-2');
+ expect(await firstResponse.json()).toEqual({
+ body: { name: 'Alice' },
+ query: { limit: 10 },
+ params: { userId: 'usr_123' },
+ method: 'POST',
+ });
+ expect(events).toEqual([
+ 'resolve:start',
+ 'resolve:end',
+ 'params',
+ 'query',
+ 'body',
+ 'handler',
+ 'resolve:start',
+ 'resolve:end',
+ 'params',
+ 'query',
+ 'body',
+ 'handler',
+ ]);
+ });
+
+ test('synchronous context resolvers provide their return value to the handler', async () => {
+ const handleApiRequest = buildApiRequestHandler({
+ routes: [
+ defineApiRoute({
+ contract: defineApiContract({
+ method: 'GET',
+ path: '/api/context',
+ responses: {
+ 200: {
+ description: 'The resolved request path.',
+ content: { 'text/plain': { schema: v.string() } },
+ },
+ },
+ }),
+ resolveContext: ({ request }) => ({ path: new URL(request.url).pathname }),
+ handler: async ({ context }) => ({
+ status: 200,
+ contentType: 'text/plain',
+ body: context.path,
+ }),
+ }),
+ ],
+ });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/context'),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(200);
+ expect(await response.text()).toEqual('/api/context');
+ });
+
+ test('resolver failures stop validation and the handler without exposing internal details', async () => {
+ let handlerCalled = false;
+ const handleApiRequest = buildApiRequestHandler({
+ routes: [
+ defineApiRoute({
+ contract: echoRoute.contract,
+ resolveContext: async () => {
+ throw new Error('Sensitive resolver details');
+ },
+ handler: async () => {
+ handlerCalled = true;
+ throw new Error('The handler must not be called');
+ },
+ }),
+ ],
+ });
+ const request = new Request('https://papra.test/api/users/invalid', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: 'Invalid JSON',
+ });
+
+ const response = await handleApiRequest({ request });
+
+ expect.assert(response);
+ expect(response.status).toEqual(500);
+ expect(await response.json()).toEqual({
+ error: { message: 'Internal server error', code: 'api.internal-error' },
+ });
+ expect(handlerCalled).toEqual(false);
+ expect(request.bodyUsed).toEqual(false);
+ });
+
+ test('public resolver errors return their status before validation or handler execution', async () => {
+ let handlerCalled = false;
+ const handleApiRequest = buildApiRequestHandler({
+ routes: [
+ defineApiRoute({
+ contract: echoRoute.contract,
+ resolveContext: async () => {
+ throw createUnauthorizedError();
+ },
+ handler: async () => {
+ handlerCalled = true;
+ throw new Error('The handler must not be called');
+ },
+ }),
+ ],
+ });
+ const request = new Request('https://papra.test/api/users/invalid', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: 'Invalid JSON',
+ });
+
+ const response = await handleApiRequest({ request });
+
+ expect.assert(response);
+ expect(response.status).toEqual(401);
+ expect(response.headers.get('Cache-Control')).toEqual('no-store');
+ expect(await response.json()).toEqual({
+ error: { message: 'Unauthorized', code: 'auth.unauthorized' },
+ });
+ expect(handlerCalled).toEqual(false);
+ expect(request.bodyUsed).toEqual(false);
+ });
+
+ test('public handler errors preserve their status and public payload without being cached', async () => {
+ const handleApiRequest = buildApiRequestHandler({
+ routes: [
+ defineApiRoute({
+ contract: defineApiContract({ method: 'GET', path: '/api/error', responses: {} }),
+ handler: async () => {
+ throw createError({
+ statusCode: 410,
+ message: 'Resource no longer available',
+ code: 'resource.gone',
+ cause: new Error('Sensitive cause'),
+ });
+ },
+ }),
+ ],
+ });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/error'),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(410);
+ expect(response.headers.get('Content-Type')).toEqual('application/json');
+ expect(response.headers.get('Cache-Control')).toEqual('no-store');
+ expect(await response.json()).toEqual({
+ error: { message: 'Resource no longer available', code: 'resource.gone' },
+ });
+ });
+
+ test('internal custom errors are logged but return a sanitized non-cacheable 500', async () => {
+ const { logger, getLogs } = createTestLogger();
+ const error = createError({
+ statusCode: 503,
+ message: 'Sensitive internal details',
+ code: 'internal.sensitive',
+ isInternal: true,
+ });
+ const handleApiRequest = buildApiRequestHandler({
+ logger,
+ routes: [
+ defineApiRoute({
+ contract: defineApiContract({ method: 'GET', path: '/api/error', responses: {} }),
+ handler: async () => {
+ throw error;
+ },
+ }),
+ ],
+ });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/error'),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(500);
+ expect(response.headers.get('Cache-Control')).toEqual('no-store');
+ expect(await response.json()).toEqual({
+ error: { message: 'Internal server error', code: 'api.internal-error' },
+ });
+ expect(getLogs()).toMatchObject([
+ { level: 'error', message: error.message, data: { error: { message: error.message } } },
+ ]);
+ });
+
+ test('invalid request bodies return validation errors instead of reaching the handler', async () => {
+ const handleApiRequest = buildApiRequestHandler({ routes: [echoRoute] });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/users/usr_123?limit=10', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 123 }),
+ }),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(400);
+ expect(response.headers.get('Cache-Control')).toEqual('no-store');
+ expect(await response.json()).toMatchObject({
+ error: {
+ code: 'api.validation_error',
+ details: [{ path: 'name' }],
+ },
+ });
+ });
+
+ test('invalid path parameters return validation errors instead of reaching the handler', async () => {
+ const handleApiRequest = buildApiRequestHandler({ routes: [echoRoute] });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/users/invalid?limit=10', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'Alice' }),
+ }),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(400);
+ expect(await response.json()).toMatchObject({
+ error: { code: 'api.validation_error', details: [{ path: 'userId' }] },
+ });
+ });
+
+ test('path parameter transformations reach the handler alongside heterogeneous routes', async () => {
+ const handleApiRequest = buildApiRequestHandler({
+ routes: [
+ echoRoute,
+ defineApiRoute({
+ contract: defineApiContract({
+ method: 'GET',
+ path: '/api/pages/:page',
+ request: { params: v.object({ page: v.pipe(v.string(), v.transform(Number)) }) },
+ responses: {
+ 200: {
+ description: 'The next page.',
+ content: { 'application/json': { schema: v.object({ nextPage: v.number() }) } },
+ },
+ },
+ }),
+ handler: async ({ params }) => ({
+ status: 200,
+ contentType: 'application/json',
+ body: { nextPage: params.page + 1 },
+ }),
+ }),
+ ],
+ });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/pages/2'),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(200);
+ expect(await response.json()).toEqual({ nextPage: 3 });
+ });
+
+ test('absent schemas yield empty query and params objects and an undefined body', async () => {
+ const handleApiRequest = buildApiRequestHandler({
+ routes: [
+ defineApiRoute({
+ contract: defineApiContract({
+ method: 'POST',
+ path: '/api/ignored/:id',
+ responses: { 204: { description: 'No content.', content: {} } },
+ }),
+ handler: async ({ body, query, params, context }) => {
+ expect({ body, query, params, context }).toEqual({
+ body: undefined,
+ query: {},
+ params: {},
+ context: undefined,
+ });
+ return { status: 204 };
+ },
+ }),
+ ],
+ });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/ignored/123?limit=10', {
+ method: 'POST',
+ body: 'Ignored',
+ }),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(204);
+ expect(response.headers.get('Content-Type')).toEqual(null);
+ expect(await response.text()).toEqual('');
+ });
+
+ test('unmatched paths return undefined without resolving context or consuming the body', async () => {
+ let contextResolved = false;
+ const handleApiRequest = buildApiRequestHandler({
+ routes: [
+ defineApiRoute({
+ ...echoRoute,
+ resolveContext: () => {
+ contextResolved = true;
+ return undefined;
+ },
+ }),
+ ],
+ });
+
+ const request = new Request('https://papra.test/api/missing', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: 'Invalid JSON',
+ });
+
+ const response = await handleApiRequest({ request });
+
+ expect(response).toEqual(undefined);
+ expect(contextResolved).toEqual(false);
+ expect(request.bodyUsed).toEqual(false);
+ expect(await request.text()).toEqual('Invalid JSON');
+ });
+
+ test('unmatched methods return undefined even when the path matches', async () => {
+ const handleApiRequest = buildApiRequestHandler({ routes: [echoRoute] });
+ const request = new Request('https://papra.test/api/users/usr_123?limit=10', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'Alice' }),
+ });
+
+ const response = await handleApiRequest({ request });
+
+ expect(response).toEqual(undefined);
+ expect(request.bodyUsed).toEqual(false);
+ });
+
+ test('matched routes returning 404 produce a response instead of falling through', async () => {
+ const handleApiRequest = buildApiRequestHandler({
+ routes: [
+ defineApiRoute({
+ contract: defineApiContract({
+ method: 'GET',
+ path: '/api/missing-document',
+ responses: {
+ 404: {
+ description: 'The document does not exist.',
+ content: { 'text/plain': { schema: v.string() } },
+ },
+ },
+ }),
+ handler: async () => ({
+ status: 404,
+ contentType: 'text/plain',
+ body: 'Document not found',
+ }),
+ }),
+ ],
+ });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/missing-document'),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(404);
+ expect(await response.text()).toEqual('Document not found');
+ });
+
+ test('unexpected handler failures are logged and return a generic error without exposing internal details', async () => {
+ const { logger, getLogs } = createTestLogger();
+ const error = new Error('Sensitive internal details');
+ const handleApiRequest = buildApiRequestHandler({
+ logger,
+ routes: [
+ defineApiRoute({
+ contract: defineApiContract({
+ method: 'GET',
+ path: '/api/error',
+ responses: {},
+ }),
+ handler: async () => {
+ throw error;
+ },
+ }),
+ ],
+ });
+
+ const response = await handleApiRequest({
+ request: new Request('https://papra.test/api/error'),
+ });
+
+ expect.assert(response);
+ expect(response.status).toEqual(500);
+ expect(response.headers.get('Content-Type')).toEqual('application/json');
+ expect(response.headers.get('Cache-Control')).toEqual('no-store');
+ expect(await response.json()).toEqual({
+ error: { message: 'Internal server error', code: 'api.internal-error' },
+ });
+ expect(getLogs()).toMatchObject([
+ { level: 'error', message: error.message, data: { error: { message: error.message } } },
+ ]);
+ });
+});
diff --git a/apps/papra-server/src/modules/api/api.request-handler.ts b/apps/papra-server/src/modules/api/api.request-handler.ts
new file mode 100644
index 00000000..59e83332
--- /dev/null
+++ b/apps/papra-server/src/modules/api/api.request-handler.ts
@@ -0,0 +1,117 @@
+import type { ApiContract } from './api.contracts';
+import type { ApiContextResolver, ApiHandlerInput } from './api.routes';
+import type { ApiResponse } from './responses/responses.types';
+import { addRoute, createRouter, findRoute } from 'rou3';
+import { parseBody } from './requests/parsers/body.parser';
+import { parseParams } from './requests/parsers/params.parser';
+import { parseQuery } from './requests/parsers/query.parser';
+import { apiErrorResponse, internalServerErrorResponse } from './responses/responses';
+import { serializeApiResponse } from './responses/serialize/responses.serialize';
+import { isCustomError } from '../shared/errors/errors';
+import type { Logger } from '../shared/logger/logger';
+import { createLogger } from '../shared/logger/logger';
+
+// Heterogeneous routes erase their input types only inside the dispatcher. A handler
+// cannot be called until its own contract has validated the request.
+type RegisteredApiRoute = {
+ contract: ApiContract;
+ resolveContext?: ApiContextResolver;
+ handler: (input: never) => Promise<ApiResponse>;
+};
+
+export function buildApiRequestHandler({
+ routes,
+ logger = createLogger({ namespace: 'api' }),
+}: {
+ routes: RegisteredApiRoute[];
+ logger?: Logger;
+}) {
+ const router = createRouter<RegisteredApiRoute>();
+
+ for (const route of routes) {
+ addRoute(router, route.contract.method, route.contract.path, route);
+ }
+
+ const handleRequest = async ({
+ request,
+ }: {
+ request: Request;
+ }): Promise<Response | undefined> => {
+ const url = new URL(request.url);
+ const method = request.method.toUpperCase();
+ const routeMatch =
+ findRoute(router, method, url.pathname) ??
+ (method === 'HEAD' ? findRoute(router, 'GET', url.pathname) : undefined);
+
+ if (!routeMatch) {
+ // Let the caller handle unmatched requests without consuming their body.
+ return undefined;
+ }
+
+ try {
+ const {
+ data: { handler, contract, resolveContext },
+ params,
+ } = routeMatch;
+
+ const context = await resolveContext?.({ request });
+
+ const paramsResult = parseParams({ params, schema: contract.request?.params });
+
+ if (!paramsResult.success) {
+ return paramsResult.response;
+ }
+
+ const queryResult = parseQuery({ url, schema: contract.request?.query });
+
+ if (!queryResult.success) {
+ return queryResult.response;
+ }
+
+ const bodyResult = await parseBody({ request, bodySchemas: contract.request?.body });
+
+ if (!bodyResult.success) {
+ return bodyResult.response;
+ }
+
+ const validatedHandler = handler as (
+ input: ApiHandlerInput<ApiContract, unknown>,
+ ) => Promise<ApiResponse>;
+ const handlerResult = await validatedHandler({
+ body: bodyResult.body,
+ query: queryResult.query,
+ params: paramsResult.params,
+ request,
+ context,
+ });
+
+ return serializeApiResponse({
+ handlerResult,
+ responseDefinitions: contract.responses,
+ method: contract.method,
+ });
+ } catch (error) {
+ logger.error({ error }, error instanceof Error ? error.message : 'An error occurred');
+
+ if (isCustomError(error) && !error.isInternal) {
+ return apiErrorResponse({
+ status: error.statusCode,
+ message: error.message,
+ code: error.code,
+ });
+ }
+
+ return internalServerErrorResponse();
+ }
+ };
+
+ return async ({ request }: { request: Request }): Promise<Response | undefined> => {
+ const response = await handleRequest({ request });
+
+ if (request.method.toUpperCase() === 'HEAD' && response !== undefined) {
+ return new Response(null, response);
+ }
+
+ return response;
+ };
+}
diff --git a/apps/papra-server/src/modules/api/api.routes.test.ts b/apps/papra-server/src/modules/api/api.routes.test.ts
new file mode 100644
index 00000000..aa692b8a
--- /dev/null
+++ b/apps/papra-server/src/modules/api/api.routes.test.ts
@@ -0,0 +1,407 @@
+import type { ApiHandlerInput, ApiHandlerResult, ApiRoute } from './api.routes';
+import * as v from 'valibot';
+import { describe, expectTypeOf, test } from 'vitest';
+import { defineApiContract } from './api.contracts';
+import { defineApiRoute } from './api.routes';
+
+const wireDateSchema = v.pipe(
+ v.union([v.date(), v.string()]),
+ v.transform((value) => new Date(value).toISOString()),
+);
+
+const contract = defineApiContract({
+ method: 'POST',
+ path: '/api/items/:id',
+ request: {
+ params: v.object({ id: v.pipe(v.string(), v.transform(Number)) }),
+ query: v.object({ limit: v.optional(v.pipe(v.string(), v.transform(Number)), '10') }),
+ body: {
+ 'application/json': v.object({
+ name: v.string(),
+ count: v.pipe(v.string(), v.transform(Number)),
+ }),
+ },
+ },
+ responses: {
+ 200: {
+ description: 'An item or its name.',
+ content: {
+ 'application/json': {
+ schema: v.object({
+ name: v.string(),
+ createdAt: wireDateSchema,
+ tags: v.array(v.string()),
+ }),
+ },
+ 'text/plain': { schema: v.string() },
+ },
+ },
+ 400: {
+ description: 'An error.',
+ content: { 'application/json': { schema: v.object({ error: v.string() }) } },
+ },
+ 204: { description: 'No content.', content: {} },
+ 205: { description: 'Reset content.', content: {} },
+ 304: { description: 'Not modified.', content: {} },
+ },
+});
+
+describe('defineApiRoute types', () => {
+ test('handlers infer parsed request outputs and retain their contract', () => {
+ const route = defineApiRoute({
+ contract,
+ handler: async ({ body, query, params, request }) => {
+ expectTypeOf(body).toEqualTypeOf<{ name: string; count: number }>();
+ expectTypeOf(query).toEqualTypeOf<{ limit: number }>();
+ expectTypeOf(params).toEqualTypeOf<{ id: number }>();
+ expectTypeOf(request).toEqualTypeOf<Request>();
+
+ return {
+ status: 200,
+ contentType: 'application/json',
+ body: { name: body.name, createdAt: new Date().toISOString(), tags: ['item'] },
+ };
+ },
+ });
+
+ expectTypeOf(route).toEqualTypeOf<ApiRoute<typeof contract>>();
+ expectTypeOf(route.contract.method).toEqualTypeOf<'POST'>();
+ expectTypeOf(route.contract.path).toEqualTypeOf<'/api/items/:id'>();
+ expectTypeOf(route.contract.responses[200].content['application/json'].schema).toEqualTypeOf<
+ (typeof contract.responses)[200]['content']['application/json']['schema']
+ >();
+ });
+
+ test('missing schemas produce empty query and params objects and an undefined body, without inferring the path', () => {
+ defineApiRoute({
+ contract: defineApiContract({
+ method: 'GET',
+ path: '/api/items/:id',
+ responses: { 204: { description: 'No content.', content: {} } },
+ }),
+ handler: async ({ body, query, params, context }) => {
+ expectTypeOf(context).toEqualTypeOf<undefined>();
+ expectTypeOf(body).toEqualTypeOf<undefined>();
+ expectTypeOf(query).toEqualTypeOf<Record<string, never>>();
+ expectTypeOf(params).toEqualTypeOf<Record<string, never>>();
+ return { status: 204 };
+ },
+ });
+ });
+
+ test('async context resolvers infer a required handler context without changing request or response inference', () => {
+ const route = defineApiRoute({
+ contract,
+ resolveContext: async (input) => {
+ expectTypeOf(input).toEqualTypeOf<{ request: Request }>();
+ return { requestId: input.request.headers.get('X-Request-Id') ?? 'unknown' };
+ },
+ handler: async ({ context, body, params, query }) => {
+ expectTypeOf(context).toEqualTypeOf<{ requestId: string }>();
+ expectTypeOf(body).toEqualTypeOf<{ name: string; count: number }>();
+ expectTypeOf(params).toEqualTypeOf<{ id: number }>();
+ expectTypeOf(query).toEqualTypeOf<{ limit: number }>();
+ return { status: 200, contentType: 'text/plain', body: context.requestId };
+ },
+ });
+
+ expectTypeOf<Parameters<typeof route.handler>[0]['context']>().toEqualTypeOf<{
+ requestId: string;
+ }>();
+ });
+
+ test('reusable synchronous context resolvers retain their context type', () => {
+ const resolveContext = ({ request }: { request: Request }) => ({ url: new URL(request.url) });
+ const route = defineApiRoute({
+ contract,
+ resolveContext,
+ handler: async ({ context }) => {
+ expectTypeOf(context).toEqualTypeOf<{ url: URL }>();
+ return { status: 200, contentType: 'text/plain', body: context.url.pathname };
+ },
+ });
+
+ expectTypeOf(route).toEqualTypeOf<ApiRoute<typeof contract, typeof resolveContext>>();
+ expectTypeOf(route.resolveContext).toEqualTypeOf<typeof resolveContext>();
+ expectTypeOf<{ contract: typeof contract; handler: typeof route.handler }>().not.toMatchTypeOf<
+ typeof route
+ >();
+ });
+
+ test('a possibly absent resolver makes the handler context possibly undefined', () => {
+ function createRoute(resolveContext: (() => { requestId: string }) | undefined) {
+ return defineApiRoute({
+ contract,
+ resolveContext,
+ handler: async ({ context }) => {
+ expectTypeOf(context).toEqualTypeOf<{ requestId: string } | undefined>();
+ return { status: 200, contentType: 'text/plain', body: context?.requestId ?? 'unknown' };
+ },
+ });
+ }
+
+ createRoute(undefined);
+ createRoute(() => ({ requestId: 'request-1' }));
+ });
+
+ test('an optional resolver in route options preserves the possibility of an undefined context', () => {
+ function createRoute(options: { resolveContext?: () => { requestId: string } }) {
+ return defineApiRoute({
+ contract,
+ ...options,
+ handler: async ({ context }) => {
+ expectTypeOf(context).toEqualTypeOf<{ requestId: string } | undefined>();
+ return { status: 200, contentType: 'text/plain', body: context?.requestId ?? 'unknown' };
+ },
+ });
+ }
+
+ createRoute({});
+ createRoute({ resolveContext: () => ({ requestId: 'request-1' }) });
+ });
+
+ test('handlers cannot invent context fields or bypass response types when a resolver is present', () => {
+ const resolveContext = () => ({ requestId: 'request-1' });
+ const invalidContextHandler = async ({
+ context,
+ }: ApiHandlerInput<typeof contract, { requestId: string; extra: boolean }>) => ({
+ status: 200 as const,
+ contentType: 'text/plain' as const,
+ body: context.requestId,
+ });
+ const invalidResponseHandler = async ({
+ context,
+ }: ApiHandlerInput<typeof contract, { requestId: string }>) => ({
+ status: 201 as const,
+ contentType: 'text/plain' as const,
+ body: context.requestId,
+ });
+
+ // @ts-expect-error The resolver does not provide the extra context field.
+ defineApiRoute({ contract, resolveContext, handler: invalidContextHandler });
+ // @ts-expect-error Context resolution does not permit an undeclared response status.
+ defineApiRoute({ contract, resolveContext, handler: invalidResponseHandler });
+ });
+
+ test('multiple request content types produce a union of parsed body outputs', () => {
+ defineApiRoute({
+ contract: defineApiContract({
+ method: 'POST',
+ path: '/api/items',
+ request: {
+ body: {
+ 'application/json': v.object({ count: v.pipe(v.string(), v.transform(Number)) }),
+ 'text/plain': v.string(),
+ },
+ },
+ responses: { 204: { description: 'No content.', content: {} } },
+ }),
+ handler: async ({ body, query, params }) => {
+ expectTypeOf(body).toEqualTypeOf<{ count: number } | string>();
+ expectTypeOf(query).toEqualTypeOf<Record<string, never>>();
+ expectTypeOf(params).toEqualTypeOf<Record<string, never>>();
+ return { status: 204 };
+ },
+ });
+ });
+
+ test('response status and content type discriminate schema outputs, including bodyless statuses', () => {
+ expectTypeOf<ApiHandlerResult<typeof contract>>().toEqualTypeOf<
+ | {
+ status: 200;
+ contentType: 'application/json';
+ body: { name: string; createdAt: string; tags: string[] };
+ headers?: Record<string, string>;
+ }
+ | { status: 200; contentType: 'text/plain'; body: string; headers?: Record<string, string> }
+ | {
+ status: 400;
+ contentType: 'application/json';
+ body: { error: string };
+ headers?: Record<string, string>;
+ }
+ | { status: 204; contentType?: never; body?: never; headers?: Record<string, string> }
+ | { status: 205; contentType?: never; body?: never; headers?: Record<string, string> }
+ | { status: 304; contentType?: never; body?: never; headers?: Record<string, string> }
+ >();
+
+ defineApiRoute({
+ contract,
+ handler: async ({ body }) => {
+ if (body.count < 0) {
+ return { status: 400, contentType: 'application/json', body: { error: 'Invalid count' } };
+ }
+
+ if (body.count === 0) {
+ return { status: 204, headers: { 'X-Empty': 'true' } };
+ }
+
+ return { status: 200, contentType: 'text/plain', body: body.name };
+ },
+ });
+ });
+
+ test('handlers cannot widen the contract by returning an undeclared status or content type', () => {
+ defineApiRoute({
+ contract,
+ // @ts-expect-error Only statuses declared by the contract are allowed.
+ handler: async () => ({
+ status: 201,
+ contentType: 'application/json',
+ body: { error: 'Invalid' },
+ }),
+ });
+
+ defineApiRoute({
+ contract,
+ // @ts-expect-error This content type exists for 200, not 400.
+ handler: async () => ({ status: 400, contentType: 'text/plain', body: 'Invalid' }),
+ });
+
+ defineApiRoute({
+ contract,
+ // @ts-expect-error Undeclared content types cannot be returned.
+ handler: async () => ({ status: 200, contentType: 'text/html', body: 'Invalid' }),
+ });
+ });
+
+ test('response bodies must match the output schema for their status and content type', () => {
+ defineApiRoute({
+ contract,
+ // @ts-expect-error Schema input accepts Date, but handlers must return the string output.
+ handler: async () => ({
+ status: 200,
+ contentType: 'application/json',
+ body: { name: 'Item', createdAt: new Date(), tags: [] },
+ }),
+ });
+
+ defineApiRoute({
+ contract,
+ // @ts-expect-error This JSON body belongs to status 400, not 200.
+ handler: async () => ({
+ status: 200,
+ contentType: 'application/json',
+ body: { error: 'Invalid' },
+ }),
+ });
+
+ defineApiRoute({
+ contract,
+ // @ts-expect-error Plain text responses must use the declared string output.
+ handler: async () => ({ status: 200, contentType: 'text/plain', body: { name: 'Item' } }),
+ });
+ });
+
+ test('contentful responses require both a content type and a body', () => {
+ defineApiRoute({
+ contract,
+ // @ts-expect-error Content-Type cannot be omitted for a contentful response.
+ handler: async () => ({ status: 200, body: 'Item' }),
+ });
+
+ defineApiRoute({
+ contract,
+ // @ts-expect-error A body cannot be omitted for a contentful response.
+ handler: async () => ({ status: 200, contentType: 'text/plain' }),
+ });
+ });
+
+ test('bodyless statuses reject bodies and content types', () => {
+ defineApiRoute({
+ contract,
+ // @ts-expect-error Bodyless statuses cannot carry a body.
+ handler: async () => ({ status: 204, body: 'Item' }),
+ });
+
+ defineApiRoute({
+ contract,
+ // @ts-expect-error Bodyless statuses cannot specify a content type.
+ handler: async () => ({ status: 304, contentType: 'application/json' }),
+ });
+ });
+
+ test('bodyless statuses cannot declare response content in their contract', () => {
+ defineApiContract({
+ method: 'DELETE',
+ path: '/api/items/:id',
+ responses: {
+ 204: {
+ description: 'No content.',
+ content: {
+ // @ts-expect-error Bodyless statuses cannot declare a payload schema.
+ 'application/json': { schema: v.string() },
+ },
+ },
+ },
+ });
+ });
+
+ test('HEAD handlers return only status and headers regardless of status code', () => {
+ const headContract = defineApiContract({
+ method: 'HEAD',
+ path: '/api/items/:id',
+ responses: {
+ 200: { description: 'Item metadata.', content: {} },
+ 404: { description: 'Item not found.', content: {} },
+ },
+ });
+
+ expectTypeOf<ApiHandlerResult<typeof headContract>>().toEqualTypeOf<
+ | { status: 200; contentType?: never; body?: never; headers?: Record<string, string> }
+ | { status: 404; contentType?: never; body?: never; headers?: Record<string, string> }
+ >();
+
+ const route = defineApiRoute({
+ contract: headContract,
+ handler: async () => ({
+ status: 200,
+ headers: { 'Content-Type': 'application/json', 'Content-Length': '123' },
+ }),
+ });
+
+ expectTypeOf(route.contract.method).toEqualTypeOf<'HEAD'>();
+
+ defineApiRoute({
+ contract: headContract,
+ // @ts-expect-error HEAD responses cannot carry a body, even with a contentful status.
+ handler: async () => ({ status: 200, body: 'Item' }),
+ });
+
+ defineApiRoute({
+ contract: headContract,
+ // @ts-expect-error Representation metadata belongs in headers, not a body content type.
+ handler: async () => ({ status: 200, contentType: 'text/plain' }),
+ });
+
+ defineApiRoute({
+ contract: headContract,
+ // @ts-expect-error HEAD responses still require a declared status.
+ handler: async () => ({ status: 201 }),
+ });
+ });
+
+ test('HEAD contracts cannot declare response payload schemas', () => {
+ // @ts-expect-error All HEAD response statuses are bodyless.
+ defineApiContract({
+ method: 'HEAD',
+ path: '/api/items/:id',
+ responses: {
+ 200: {
+ description: 'Item metadata.',
+ content: { 'text/plain': { schema: v.string() } },
+ },
+ },
+ });
+ });
+
+ test('exported input types preserve request outputs', () => {
+ expectTypeOf<ApiHandlerInput<typeof contract>>().toEqualTypeOf<{
+ body: { name: string; count: number };
+ query: { limit: number };
+ params: { id: number };
+ request: Request;
+ context: undefined;
+ }>();
+ });
+});
diff --git a/apps/papra-server/src/modules/api/api.routes.ts b/apps/papra-server/src/modules/api/api.routes.ts
new file mode 100644
index 00000000..9f7f7d2d
--- /dev/null
+++ b/apps/papra-server/src/modules/api/api.routes.ts
@@ -0,0 +1,100 @@
+import type { Expand } from '@corentinth/chisels';
+import type { ApiContract } from './api.contracts';
+import type { ApiRequestBodyOutput, ApiRequestSchemaOutput } from './requests/requests.types';
+import type {
+ ApiResponseBodylessStatus,
+ ApiResponseContentType,
+} from './responses/responses.types';
+import type { GenericSchema, InferOutput } from 'valibot';
+
+type ApiRequestSchema<
+ Contract extends ApiContract,
+ Key extends keyof NonNullable<ApiContract['request']>,
+> = Key extends keyof NonNullable<Contract['request']>
+ ? NonNullable<Contract['request']>[Key]
+ : undefined;
+
+// Runs before validation and must leave the request body unread.
+export type ApiContextResolver = (input: { request: Request }) => unknown;
+
+export type ApiResolvedContext<Resolver> = Resolver extends ApiContextResolver
+ ? Awaited<ReturnType<Resolver>>
+ : undefined;
+
+export type ApiHandlerInput<Contract extends ApiContract, Context = undefined> = {
+ body: ApiRequestBodyOutput<ApiRequestSchema<Contract, 'body'>>;
+ query: ApiRequestSchemaOutput<ApiRequestSchema<Contract, 'query'>>;
+ params: ApiRequestSchemaOutput<ApiRequestSchema<Contract, 'params'>>;
+ request: Request;
+ context: Context;
+};
+
+type ApiResponseContentResult<Content, Status extends number> = {
+ [ContentType in keyof Content & ApiResponseContentType]: Content[ContentType] extends {
+ schema: infer Schema extends GenericSchema;
+ }
+ ? { status: Status; contentType: ContentType; body: InferOutput<Schema> }
+ : never;
+}[keyof Content & ApiResponseContentType];
+
+export type ApiHandlerResult<Contract extends ApiContract> = {
+ [Status in keyof Contract['responses'] & number]: Expand<
+ (Status extends (Contract['method'] extends 'HEAD' ? number : ApiResponseBodylessStatus)
+ ? { status: Status; contentType?: never; body?: never }
+ : ApiResponseContentResult<Contract['responses'][Status]['content'], Status>) & {
+ headers?: Record<string, string>;
+ }
+ >;
+}[keyof Contract['responses'] & number];
+
+export type ApiHandler<Contract extends ApiContract, Context = undefined> = (
+ input: ApiHandlerInput<Contract, Context>,
+) => Promise<ApiHandlerResult<Contract>>;
+
+export type ApiRoute<
+ Contract extends ApiContract,
+ Resolver extends ApiContextResolver | undefined = undefined,
+> = {
+ contract: Contract;
+ handler: ApiHandler<Contract, ApiResolvedContext<Resolver>>;
+} & (undefined extends Resolver ? { resolveContext?: Resolver } : { resolveContext: Resolver });
+
+// Infer the contract only from `contract`, not the handler or an enclosing route registry.
+// Infer status literals without requiring handlers to use `as const` on their results.
+// Separate present and optional resolvers so context is only optional when the hook is.
+export function defineApiRoute<
+ const Contract extends ApiContract,
+ const Status extends keyof Contract['responses'] & number,
+ Resolver extends ApiContextResolver | undefined,
+>(route: {
+ contract: Contract;
+ resolveContext: Resolver;
+ handler: (
+ input: NoInfer<ApiHandlerInput<Contract, ApiResolvedContext<Resolver>>>,
+ ) => Promise<NoInfer<ApiHandlerResult<Contract>> & { status: Status }>;
+}): NoInfer<ApiRoute<Contract, Resolver>>;
+export function defineApiRoute<
+ const Contract extends ApiContract,
+ const Status extends keyof Contract['responses'] & number,
+ Resolver extends ApiContextResolver | undefined = undefined,
+>(route: {
+ contract: Contract;
+ resolveContext?: Resolver;
+ handler: (
+ input: NoInfer<ApiHandlerInput<Contract, ApiResolvedContext<Resolver | undefined>>>,
+ ) => Promise<NoInfer<ApiHandlerResult<Contract>> & { status: Status }>;
+}): NoInfer<ApiRoute<Contract, Resolver | undefined>>;
+export function defineApiRoute<
+ Contract extends ApiContract,
+ Resolver extends ApiContextResolver | undefined,
+>({
+ contract,
+ resolveContext,
+ handler,
+}: {
+ contract: Contract;
+ resolveContext?: Resolver;
+ handler: ApiHandler<Contract, ApiResolvedContext<Resolver>>;
+}) {
+ return { contract, resolveContext, handler };
+}
diff --git a/apps/papra-server/src/modules/api/api.schemas.ts b/apps/papra-server/src/modules/api/api.schemas.ts
new file mode 100644
index 00000000..83572d90
--- /dev/null
+++ b/apps/papra-server/src/modules/api/api.schemas.ts
@@ -0,0 +1,3 @@
+import * as v from 'valibot';
+
+export const isoDateStringSchema = v.pipe(v.string(), v.isoTimestamp());
diff --git a/apps/papra-server/src/modules/api/requests/parsers/body.parser.test.ts b/apps/papra-server/src/modules/api/requests/parsers/body.parser.test.ts
new file mode 100644
index 00000000..6e594177
--- /dev/null
+++ b/apps/papra-server/src/modules/api/requests/parsers/body.parser.test.ts
@@ -0,0 +1,44 @@
+import * as v from 'valibot';
+import { describe, expect, expectTypeOf, test } from 'vitest';
+import { parseBody } from './body.parser';
+
+describe('parseBody', () => {
+ test('the parsed body is typed as the schema output, including transformations', async () => {
+ const result = await parseBody({
+ request: new Request('https://papra.test', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ count: '2' }),
+ }),
+ bodySchemas: {
+ 'application/json': v.object({ count: v.pipe(v.string(), v.transform(Number)) }),
+ },
+ });
+
+ expect.assert(result.success);
+ expectTypeOf(result.body).toEqualTypeOf<{ count: number }>();
+ expect(result.body).toEqual({ count: 2 });
+ });
+
+ test('multiple body schemas return the union of their outputs', async () => {
+ const result = await parseBody({
+ request: new Request('https://papra.test', { method: 'POST', body: ' Hello ' }),
+ bodySchemas: {
+ 'application/json': v.object({ count: v.number() }),
+ 'text/plain': v.pipe(v.string(), v.trim()),
+ },
+ });
+
+ expect.assert(result.success);
+ expectTypeOf(result.body).toEqualTypeOf<{ count: number } | string>();
+ expect(result.body).toEqual('Hello');
+ });
+
+ test('an absent body schema returns undefined', async () => {
+ const result = await parseBody({ request: new Request('https://papra.test') });
+
+ expect.assert(result.success);
+ expectTypeOf(result.body).toEqualTypeOf<undefined>();
+ expect(result.body).toEqual(undefined);
+ });
+});
diff --git a/apps/papra-server/src/modules/api/requests/parsers/body.parser.ts b/apps/papra-server/src/modules/api/requests/parsers/body.parser.ts
new file mode 100644
index 00000000..aeed8574
--- /dev/null
+++ b/apps/papra-server/src/modules/api/requests/parsers/body.parser.ts
@@ -0,0 +1,90 @@
+import type { GenericSchema } from 'valibot';
+import type { ApiRequestBodyOutput, ApiRequestBodySchemas } from '../requests.types';
+import type { ApiRequestBodyParser } from './body.parsers';
+import { safely } from '@corentinth/chisels';
+import * as v from 'valibot';
+import { apiErrorResponse, apiValidationErrorResponse } from '../../responses/responses';
+import { apiRequestBodyParsers } from './body.parsers';
+
+function unsupportedContentTypeResponse(): Response {
+ return apiErrorResponse({
+ status: 415,
+ message: 'Unsupported Content-Type',
+ code: 'api.unsupported-content-type',
+ });
+}
+
+export async function parseBody<
+ Schemas extends ApiRequestBodySchemas | undefined = undefined,
+>(args: {
+ request: Request;
+ bodySchemas?: Schemas;
+ parsers?: Record<string, ApiRequestBodyParser>;
+}): Promise<
+ { success: true; body: ApiRequestBodyOutput<Schemas> } | { success: false; response: Response }
+>;
+export async function parseBody({
+ request,
+ bodySchemas,
+ parsers = apiRequestBodyParsers,
+}: {
+ request: Request;
+ bodySchemas?: Record<string, GenericSchema>;
+ parsers?: Record<string, ApiRequestBodyParser>;
+}): Promise<{ success: true; body: unknown } | { success: false; response: Response }> {
+ if (!bodySchemas) {
+ return { success: true, body: undefined };
+ }
+
+ const contentType = request.headers.get('Content-Type')?.split(';', 1)[0]?.trim().toLowerCase();
+
+ if (!contentType) {
+ return {
+ success: false,
+ response: unsupportedContentTypeResponse(),
+ };
+ }
+
+ const schema = bodySchemas[contentType];
+ const parser = parsers[contentType];
+
+ if (!schema || !parser) {
+ return {
+ success: false,
+ response: unsupportedContentTypeResponse(),
+ };
+ }
+
+ const [body, parseError] = await safely(parser.parse(request));
+
+ if (parseError) {
+ return {
+ success: false,
+ response: apiValidationErrorResponse([
+ {
+ path: 'body',
+ message: parser.errorMessage,
+ },
+ ]),
+ };
+ }
+
+ const validationResult = v.safeParse(schema, body);
+
+ if (!validationResult.success) {
+ const details = validationResult.issues.map((issue) => ({
+ path: v.getDotPath(issue),
+ message: issue.message,
+ }));
+
+ return {
+ success: false,
+ response: apiValidationErrorResponse(details),
+ };
+ }
+
+ return {
+ success: true,
+ body: validationResult.output,
+ };
+}
diff --git a/apps/papra-server/src/modules/api/requests/parsers/body.parsers.ts b/apps/papra-server/src/modules/api/requests/parsers/body.parsers.ts
new file mode 100644
index 00000000..e9ce8fe3
--- /dev/null
+++ b/apps/papra-server/src/modules/api/requests/parsers/body.parsers.ts
@@ -0,0 +1,15 @@
+export type ApiRequestBodyParser = {
+ parse: (request: Request) => Promise<unknown>;
+ errorMessage: string;
+};
+
+export const apiRequestBodyParsers = {
+ 'application/json': {
+ parse: async (request: Request): Promise<unknown> => request.json(),
+ errorMessage: 'Invalid JSON body',
+ },
+ 'text/plain': {
+ parse: async (request: Request) => request.text(),
+ errorMessage: 'Invalid text body',
+ },
+} satisfies Record<string, ApiRequestBodyParser>;
diff --git a/apps/papra-server/src/modules/api/requests/parsers/params.parser.test.ts b/apps/papra-server/src/modules/api/requests/parsers/params.parser.test.ts
new file mode 100644
index 00000000..5845774e
--- /dev/null
+++ b/apps/papra-server/src/modules/api/requests/parsers/params.parser.test.ts
@@ -0,0 +1,42 @@
+import * as v from 'valibot';
+import { describe, expect, expectTypeOf, test } from 'vitest';
+import { parseParams } from './params.parser';
+
+describe('parseParams', () => {
+ test('validated path parameters are returned with schema transformations applied', () => {
+ const result = parseParams({
+ params: { page: '2' },
+ schema: v.object({ page: v.pipe(v.string(), v.transform(Number)) }),
+ });
+
+ expect.assert(result.success);
+ expectTypeOf(result.params).toEqualTypeOf<{ page: number }>();
+ expect(result).toEqual({ success: true, params: { page: 2 } });
+ });
+
+ test('an absent schema produces an empty params object', () => {
+ const result = parseParams({});
+
+ expect.assert(result.success);
+ expectTypeOf(result.params).toEqualTypeOf<Record<string, never>>();
+ expect(result).toEqual({ success: true, params: {} });
+ });
+
+ test('invalid path parameters produce a validation error response', async () => {
+ const result = parseParams({
+ params: { userId: '' },
+ schema: v.object({ userId: v.pipe(v.string(), v.minLength(1, 'User ID is required')) }),
+ });
+
+ expect.assert(!result.success);
+
+ expect(result.response.status).toEqual(400);
+ expect(await result.response.json()).toEqual({
+ error: {
+ message: 'Bad request',
+ code: 'api.validation_error',
+ details: [{ path: 'userId', message: 'User ID is required' }],
+ },
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/api/requests/parsers/params.parser.ts b/apps/papra-server/src/modules/api/requests/parsers/params.parser.ts
new file mode 100644
index 00000000..1719986e
--- /dev/null
+++ b/apps/papra-server/src/modules/api/requests/parsers/params.parser.ts
@@ -0,0 +1,38 @@
+import type { GenericSchema } from 'valibot';
+import type { ApiRequestSchemaOutput } from '../requests.types';
+import * as v from 'valibot';
+import { apiValidationErrorResponse } from '../../responses/responses';
+
+export function parseParams<Schema extends GenericSchema | undefined = undefined>(args: {
+ params?: Record<string, string>;
+ schema?: Schema;
+}):
+ | { success: true; params: ApiRequestSchemaOutput<Schema> }
+ | { success: false; response: Response };
+export function parseParams({
+ params,
+ schema,
+}: {
+ params?: Record<string, string>;
+ schema?: GenericSchema;
+}): { success: true; params: unknown } | { success: false; response: Response } {
+ if (!schema) {
+ return { success: true, params: {} };
+ }
+
+ const validationResult = v.safeParse(schema, params);
+
+ if (!validationResult.success) {
+ const details = validationResult.issues.map((issue) => ({
+ path: v.getDotPath(issue),
+ message: issue.message,
+ }));
+
+ return {
+ success: false,
+ response: apiValidationErrorResponse(details),
+ };
+ }
+
+ return { success: true, params: validationResult.output };
+}
diff --git a/apps/papra-server/src/modules/api/requests/parsers/query.parser.test.ts b/apps/papra-server/src/modules/api/requests/parsers/query.parser.test.ts
new file mode 100644
index 00000000..ec856907
--- /dev/null
+++ b/apps/papra-server/src/modules/api/requests/parsers/query.parser.test.ts
@@ -0,0 +1,27 @@
+import * as v from 'valibot';
+import { describe, expect, expectTypeOf, test } from 'vitest';
+import { parseQuery } from './query.parser';
+
+describe('parseQuery', () => {
+ test('query outputs preserve transformations and defaults in their values and types', () => {
+ const result = parseQuery({
+ url: new URL('https://papra.test?page=2'),
+ schema: v.object({
+ page: v.pipe(v.string(), v.transform(Number)),
+ limit: v.optional(v.pipe(v.string(), v.transform(Number)), '10'),
+ }),
+ });
+
+ expect.assert(result.success);
+ expectTypeOf(result.query).toEqualTypeOf<{ page: number; limit: number }>();
+ expect(result.query).toEqual({ page: 2, limit: 10 });
+ });
+
+ test('an absent schema produces an empty query object', () => {
+ const result = parseQuery({ url: new URL('https://papra.test?page=2') });
+
+ expect.assert(result.success);
+ expectTypeOf(result.query).toEqualTypeOf<Record<string, never>>();
+ expect(result.query).toEqual({});
+ });
+});
diff --git a/apps/papra-server/src/modules/api/requests/parsers/query.parser.ts b/apps/papra-server/src/modules/api/requests/parsers/query.parser.ts
new file mode 100644
index 00000000..12874132
--- /dev/null
+++ b/apps/papra-server/src/modules/api/requests/parsers/query.parser.ts
@@ -0,0 +1,40 @@
+import type { GenericSchema } from 'valibot';
+import type { ApiRequestSchemaOutput } from '../requests.types';
+import * as v from 'valibot';
+import { apiValidationErrorResponse } from '../../responses/responses';
+
+export function parseQuery<Schema extends GenericSchema | undefined = undefined>(args: {
+ url: URL;
+ schema?: Schema;
+}):
+ | { success: true; query: ApiRequestSchemaOutput<Schema> }
+ | { success: false; response: Response };
+export function parseQuery({
+ url,
+ schema,
+}: {
+ url: URL;
+ schema?: GenericSchema;
+}): { success: true; query: unknown } | { success: false; response: Response } {
+ if (!schema) {
+ return { success: true, query: {} };
+ }
+
+ const queryParams = Object.fromEntries(url.searchParams.entries());
+
+ const validationResult = v.safeParse(schema, queryParams);
+
+ if (!validationResult.success) {
+ const details = validationResult.issues.map((issue) => ({
+ path: v.getDotPath(issue),
+ message: issue.message,
+ }));
+
+ return {
+ success: false,
+ response: apiValidationErrorResponse(details),
+ };
+ }
+
+ return { success: true, query: validationResult.output };
+}
diff --git a/apps/papra-server/src/modules/api/requests/requests.types.ts b/apps/papra-server/src/modules/api/requests/requests.types.ts
new file mode 100644
index 00000000..5a31bb8e
--- /dev/null
+++ b/apps/papra-server/src/modules/api/requests/requests.types.ts
@@ -0,0 +1,15 @@
+import type { GenericSchema, InferOutput } from 'valibot';
+import type { apiRequestBodyParsers } from './parsers/body.parsers';
+
+export type ApiRequestContentType = keyof typeof apiRequestBodyParsers;
+
+export type ApiRequestBodySchemas = Partial<Record<ApiRequestContentType, GenericSchema>>;
+
+export type ApiRequestSchemaOutput<
+ Schema,
+ Fallback = Record<string, never>,
+> = Schema extends GenericSchema ? InferOutput<Schema> : Fallback;
+
+export type ApiRequestBodyOutput<Schemas> = Schemas extends ApiRequestBodySchemas
+ ? ApiRequestSchemaOutput<Schemas[keyof Schemas], never>
+ : undefined;
diff --git a/apps/papra-server/src/modules/api/responses/responses.ts b/apps/papra-server/src/modules/api/responses/responses.ts
new file mode 100644
index 00000000..4bf4d97f
--- /dev/null
+++ b/apps/papra-server/src/modules/api/responses/responses.ts
@@ -0,0 +1,52 @@
+export function jsonResponse(
+ body: unknown,
+ { status = 200, headers = {} }: { status?: number; headers?: Record<string, string> } = {},
+) {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...headers,
+ },
+ });
+}
+
+export function apiErrorResponse({
+ status,
+ message,
+ code,
+ ...rest
+}: {
+ status: number;
+ message: string;
+ code: string;
+ [key: string]: unknown;
+}) {
+ return jsonResponse(
+ {
+ error: {
+ message,
+ code,
+ ...rest,
+ },
+ },
+ { status, headers: { 'Cache-Control': 'no-store' } },
+ );
+}
+
+export function apiValidationErrorResponse(details: { path?: string | null; message: string }[]) {
+ return apiErrorResponse({
+ status: 400,
+ message: 'Bad request',
+ code: 'api.validation_error',
+ details,
+ });
+}
+
+export function internalServerErrorResponse() {
+ return apiErrorResponse({
+ status: 500,
+ message: 'Internal server error',
+ code: 'api.internal-error',
+ });
+}
diff --git a/apps/papra-server/src/modules/api/responses/responses.types.ts b/apps/papra-server/src/modules/api/responses/responses.types.ts
new file mode 100644
index 00000000..857cad60
--- /dev/null
+++ b/apps/papra-server/src/modules/api/responses/responses.types.ts
@@ -0,0 +1,12 @@
+import type { apiResponseBodySerializers } from './serialize/responses.serializers';
+
+export type ApiResponseContentType = keyof typeof apiResponseBodySerializers;
+
+export type ApiResponseBodylessStatus = 204 | 205 | 304;
+
+export type ApiResponse = {
+ status: number;
+ contentType?: string;
+ body?: unknown;
+ headers?: Record<string, string>;
+};
diff --git a/apps/papra-server/src/modules/api/responses/serialize/responses.serialize.test.ts b/apps/papra-server/src/modules/api/responses/serialize/responses.serialize.test.ts
new file mode 100644
index 00000000..0346bd99
--- /dev/null
+++ b/apps/papra-server/src/modules/api/responses/serialize/responses.serialize.test.ts
@@ -0,0 +1,140 @@
+import * as v from 'valibot';
+import { describe, expect, test } from 'vitest';
+import { serializeApiResponse } from './responses.serialize';
+
+describe('serializeApiResponse', () => {
+ test('bodyless responses preserve their status and headers', async () => {
+ const response = serializeApiResponse({
+ handlerResult: { status: 204, headers: { 'X-Request-Id': 'request-1' } },
+ responseDefinitions: { 204: { description: 'No content.', content: {} } },
+ });
+
+ expect(response.status).toEqual(204);
+ expect(response.headers.get('X-Request-Id')).toEqual('request-1');
+ expect(response.headers.get('Content-Type')).toEqual(null);
+ expect(await response.text()).toEqual('');
+ });
+
+ test('HEAD responses allow headers-only 200 responses with representation metadata', async () => {
+ const response = serializeApiResponse({
+ method: 'HEAD',
+ handlerResult: {
+ status: 200,
+ headers: { 'Content-Type': 'text/plain', 'Content-Length': '5', 'ETag': '"v1"' },
+ },
+ responseDefinitions: { 200: { description: 'Document metadata.', content: {} } },
+ });
+
+ expect(response.status).toEqual(200);
+ expect(response.headers.get('Content-Type')).toEqual('text/plain');
+ expect(response.headers.get('Content-Length')).toEqual('5');
+ expect(response.headers.get('ETag')).toEqual('"v1"');
+ expect(response.body).toEqual(null);
+ expect(await response.text()).toEqual('');
+ });
+
+ test('HEAD responses reject bodies and serializer content types', () => {
+ expect(() =>
+ serializeApiResponse({
+ method: 'HEAD',
+ handlerResult: { status: 200, body: 'Hello' },
+ responseDefinitions: { 200: { description: 'Document metadata.', content: {} } },
+ }),
+ ).toThrow('Bodyless responses cannot include a body or Content-Type');
+
+ expect(() =>
+ serializeApiResponse({
+ method: 'HEAD',
+ handlerResult: { status: 200, contentType: 'text/plain' },
+ responseDefinitions: { 200: { description: 'Document metadata.', content: {} } },
+ }),
+ ).toThrow('Bodyless responses cannot include a body or Content-Type');
+ });
+
+ test('plain text responses use their body serializer and content type', async () => {
+ const response = serializeApiResponse({
+ handlerResult: { status: 200, contentType: 'text/plain', body: 'Hello' },
+ responseDefinitions: {
+ 200: {
+ description: 'A greeting.',
+ content: { 'text/plain': { schema: v.string() } },
+ },
+ },
+ });
+
+ expect(response.status).toEqual(200);
+ expect(response.headers.get('Content-Type')).toEqual('text/plain; charset=utf-8');
+ expect(await response.text()).toEqual('Hello');
+ });
+
+ test('response schema transformations are not applied to wire-ready bodies', async () => {
+ const response = serializeApiResponse({
+ handlerResult: { status: 200, contentType: 'application/json', body: 'wire:value' },
+ responseDefinitions: {
+ 200: {
+ description: 'Already serialized output.',
+ content: {
+ 'application/json': {
+ schema: v.pipe(
+ v.string(),
+ v.transform((value) => `wire:${value}`),
+ ),
+ },
+ },
+ },
+ },
+ });
+
+ expect(await response.json()).toEqual('wire:value');
+ });
+
+ test('content types must be declared for the returned status even when a serializer exists', () => {
+ expect(() =>
+ serializeApiResponse({
+ handlerResult: { status: 200, contentType: 'text/plain', body: 'Hello' },
+ responseDefinitions: {
+ 200: {
+ description: 'A JSON greeting.',
+ content: { 'application/json': { schema: v.string() } },
+ },
+ },
+ }),
+ ).toThrow('Undeclared response Content-Type');
+ });
+
+ test('contentful responses cannot omit the content type', () => {
+ expect(() =>
+ serializeApiResponse({
+ handlerResult: { status: 200, body: 'Hello' },
+ responseDefinitions: {
+ 200: { description: 'A greeting.', content: { 'text/plain': { schema: v.string() } } },
+ },
+ }),
+ ).toThrow('Content-Type is required for non-empty responses');
+ });
+
+ test('bodyless responses cannot carry a body or content type', () => {
+ expect(() =>
+ serializeApiResponse({
+ handlerResult: { status: 204, body: 'Hello' },
+ responseDefinitions: { 204: { description: 'No content.', content: {} } },
+ }),
+ ).toThrow('Bodyless responses cannot include a body or Content-Type');
+
+ expect(() =>
+ serializeApiResponse({
+ handlerResult: { status: 304, contentType: 'application/json' },
+ responseDefinitions: { 304: { description: 'Not modified.', content: {} } },
+ }),
+ ).toThrow('Bodyless responses cannot include a body or Content-Type');
+ });
+
+ test('undeclared response statuses are rejected', () => {
+ expect(() =>
+ serializeApiResponse({
+ handlerResult: { status: 201, contentType: 'application/json', body: {} },
+ responseDefinitions: {},
+ }),
+ ).toThrow('Undeclared response status');
+ });
+});
diff --git a/apps/papra-server/src/modules/api/responses/serialize/responses.serialize.ts b/apps/papra-server/src/modules/api/responses/serialize/responses.serialize.ts
new file mode 100644
index 00000000..39a2a858
--- /dev/null
+++ b/apps/papra-server/src/modules/api/responses/serialize/responses.serialize.ts
@@ -0,0 +1,56 @@
+import type { ApiContract } from '../../api.contracts';
+import type { ApiResponse } from '../responses.types';
+import type { ApiResponseBodySerializer } from './responses.serializers';
+import { apiResponseBodySerializers } from './responses.serializers';
+
+export function serializeApiResponse({
+ handlerResult,
+ responseDefinitions,
+ method,
+ serializers = apiResponseBodySerializers,
+}: {
+ handlerResult: ApiResponse;
+ responseDefinitions: ApiContract['responses'];
+ method?: ApiContract['method'];
+ serializers?: Record<string, ApiResponseBodySerializer>;
+}): Response {
+ const { status, contentType, body, headers } = handlerResult;
+
+ const responseDefinition = responseDefinitions[status];
+
+ if (!responseDefinition) {
+ throw new Error('Undeclared response status');
+ }
+
+ if (method === 'HEAD' || [204, 205, 304].includes(status)) {
+ if (body !== undefined || contentType !== undefined) {
+ throw new Error('Bodyless responses cannot include a body or Content-Type');
+ }
+
+ return new Response(null, { status, headers });
+ }
+
+ if (!contentType) {
+ throw new Error('Content-Type is required for non-empty responses');
+ }
+
+ if (!Object.hasOwn(responseDefinition.content, contentType)) {
+ throw new Error('Undeclared response Content-Type');
+ }
+
+ const serializer = serializers[contentType];
+
+ if (!serializer) {
+ throw new Error(`No serializer found for Content-Type: ${contentType}`);
+ }
+
+ const serializedBody = serializer.serialize(body);
+
+ return new Response(serializedBody, {
+ status,
+ headers: {
+ 'Content-Type': serializer.contentType,
+ ...headers,
+ },
+ });
+}
diff --git a/apps/papra-server/src/modules/api/responses/serialize/responses.serializers.ts b/apps/papra-server/src/modules/api/responses/serialize/responses.serializers.ts
new file mode 100644
index 00000000..cd9e4f98
--- /dev/null
+++ b/apps/papra-server/src/modules/api/responses/serialize/responses.serializers.ts
@@ -0,0 +1,29 @@
+export type ApiResponseBodySerializer = {
+ contentType: string;
+ serialize: (body: unknown) => ConstructorParameters<typeof Response>[0];
+};
+
+export const apiResponseBodySerializers = {
+ 'application/json': {
+ contentType: 'application/json',
+ serialize: (body): string => {
+ const serialized = JSON.stringify(body);
+
+ if (serialized === undefined) {
+ throw new Error('Response body is not JSON serializable');
+ }
+
+ return serialized;
+ },
+ },
+ 'text/plain': {
+ contentType: 'text/plain; charset=utf-8',
+ serialize: (body): string => {
+ if (typeof body !== 'string') {
+ throw new Error('Plain text responses require a string body');
+ }
+
+ return body;
+ },
+ },
+} satisfies Record<string, ApiResponseBodySerializer>;
diff --git a/apps/papra-server/src/modules/app/server.api.routes.test.ts b/apps/papra-server/src/modules/app/server.api.routes.test.ts
new file mode 100644
index 00000000..531cc834
--- /dev/null
+++ b/apps/papra-server/src/modules/app/server.api.routes.test.ts
@@ -0,0 +1,167 @@
+import * as v from 'valibot';
+import { describe, expect, test } from 'vitest';
+import { createApiKeysRepository } from '../api-keys/api-keys.repository';
+import { createApiKey } from '../api-keys/api-keys.usecases';
+import { overrideConfig } from '../config/config.test-utils';
+import { PERMISSIONS_BY_ROLE } from '../roles/roles.constants';
+import { userRolesTable } from '../roles/roles.table';
+import { getCurrentUserContract } from '../users/users.api.contracts';
+import { createInMemoryDatabase } from './database/database.test-utils';
+import { createServer } from './server';
+import { createTestServerDependencies } from './server.test-utils';
+
+async function createAuthenticatedServer() {
+ const { db } = await createInMemoryDatabase();
+ const dependencies = createTestServerDependencies({
+ db,
+ config: overrideConfig({ auth: { firstUserAsAdmin: false } }),
+ });
+ const { app } = createServer(dependencies);
+ const {
+ headers,
+ response: { user },
+ } = await dependencies.auth.api.signUpEmail({
+ body: {
+ email: '[email protected]',
+ password: 'StrongPassword123!',
+ name: 'Alice',
+ },
+ returnHeaders: true,
+ });
+ const cookie = headers
+ .getSetCookie()
+ .map((cookie) => cookie.split(';')[0])
+ .join('; ');
+
+ return { app, db, user, headers: { Cookie: cookie } };
+}
+
+describe('contract API wiring', () => {
+ test('session cookies authenticate the current-user endpoint and return its wire contract', async () => {
+ const { app, db, user, headers } = await createAuthenticatedServer();
+ await db.insert(userRolesTable).values({ userId: user.id, role: 'admin' });
+
+ const response = await app.request('/api/users/me', { headers });
+ const body = await response.json();
+
+ expect(response.status).toEqual(200);
+ expect(response.headers.get('Content-Type')).toEqual('application/json');
+ expect(body).toEqual({
+ user: {
+ id: user.id,
+ email: '[email protected]',
+ name: 'Alice',
+ createdAt: user.createdAt.toISOString(),
+ updatedAt: user.updatedAt.toISOString(),
+ twoFactorEnabled: false,
+ permissions: PERMISSIONS_BY_ROLE.admin,
+ },
+ });
+ expect(
+ v.safeParse(getCurrentUserContract.responses[200].content['application/json'].schema, body)
+ .success,
+ ).toEqual(true);
+ });
+
+ test('HEAD requests reach migrated GET routes and return only their status and headers', async () => {
+ const { app, headers } = await createAuthenticatedServer();
+
+ const response = await app.request('/api/users/me', { method: 'HEAD', headers });
+
+ expect(response.status).toEqual(200);
+ expect(response.headers.get('Content-Type')).toEqual('application/json');
+ expect(response.body).toEqual(null);
+ expect(await response.text()).toEqual('');
+ });
+
+ test('HEAD requests to migrated routes still require authentication', async () => {
+ const { db } = await createInMemoryDatabase();
+ const { app } = createServer(createTestServerDependencies({ db }));
+
+ const response = await app.request('/api/users/me', { method: 'HEAD' });
+
+ expect(response.status).toEqual(401);
+ expect(response.headers.get('Cache-Control')).toEqual('no-store');
+ expect(response.body).toEqual(null);
+ });
+
+ test('unmatched HEAD requests continue to legacy GET routes', async () => {
+ const { db } = await createInMemoryDatabase();
+ const { app } = createServer(createTestServerDependencies({ db }));
+
+ const response = await app.request('/api/ping', { method: 'HEAD' });
+
+ expect(response.status).toEqual(200);
+ expect(response.headers.get('Content-Type')).toEqual('application/json');
+ expect(response.body).toEqual(null);
+ });
+
+ test('unknown HEAD paths reach the existing not-found handler without a body', async () => {
+ const { db } = await createInMemoryDatabase();
+ const { app } = createServer(createTestServerDependencies({ db }));
+
+ const response = await app.request('/api/missing', { method: 'HEAD' });
+
+ expect(response.status).toEqual(404);
+ expect(response.headers.get('Content-Type')).toEqual('application/json');
+ expect(response.body).toEqual(null);
+ });
+
+ test('the current-user endpoint rejects requests without credentials', async () => {
+ const { db } = await createInMemoryDatabase();
+ const { app } = createServer(createTestServerDependencies({ db }));
+
+ const response = await app.request('/api/users/me');
+
+ expect(response.status).toEqual(401);
+ expect(await response.json()).toEqual({
+ error: { message: 'Unauthorized', code: 'auth.unauthorized' },
+ });
+ });
+
+ test('the current-user endpoint does not accept an API key in place of a session', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'usr_alice', email: '[email protected]' }],
+ });
+ const { token } = await createApiKey({
+ apiKeyRepository: createApiKeysRepository({ db }),
+ name: 'Test key',
+ userId: 'usr_alice',
+ permissions: [],
+ organizationIds: [],
+ allOrganizations: true,
+ });
+ const { app } = createServer(createTestServerDependencies({ db }));
+
+ const response = await app.request('/api/users/me', {
+ headers: { Authorization: `Bearer ${token}` },
+ });
+
+ expect(response.status).toEqual(401);
+ expect(await response.json()).toEqual({
+ error: { message: 'Unauthorized', code: 'auth.unauthorized' },
+ });
+ });
+
+ test('unmigrated routes receive the session and unread request body', async () => {
+ const { app, headers } = await createAuthenticatedServer();
+
+ const response = await app.request('/api/organizations', {
+ method: 'POST',
+ headers: { ...headers, 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'Alice Organization' }),
+ });
+
+ expect(response.status).toEqual(200);
+ expect(await response.json()).toMatchObject({
+ organization: { name: 'Alice Organization' },
+ });
+
+ const organizationsResponse = await app.request('/api/organizations', { headers });
+
+ expect(organizationsResponse.status).toEqual(200);
+ expect(await organizationsResponse.json()).toMatchObject({
+ organizations: [{ name: 'Alice Organization' }],
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/app/server.api.routes.ts b/apps/papra-server/src/modules/app/server.api.routes.ts
new file mode 100644
index 00000000..8c8e76a7
--- /dev/null
+++ b/apps/papra-server/src/modules/app/server.api.routes.ts
@@ -0,0 +1,43 @@
+import type { ApiDependencies, RouteDefinitionContext } from './server.types';
+
+import { buildApiRequestHandler } from '../api/api.request-handler';
+import { buildUserApiRoutes } from '../users/users.api.routes';
+import {
+ buildGetApiKey,
+ buildGetSession,
+ buildResolveAuthenticationContext,
+} from '../api/api.authentication';
+
+function buildApiRoutes(deps: ApiDependencies) {
+ return [...buildUserApiRoutes(deps)];
+}
+
+export function registerApiRoutes({ app, ...deps }: RouteDefinitionContext) {
+ const { auth, db } = deps;
+
+ const resolveAuthenticationContext = buildResolveAuthenticationContext({
+ getSession: buildGetSession({ auth }),
+ getApiKey: buildGetApiKey({ db }),
+ });
+
+ const apiDeps = {
+ ...deps,
+ resolveAuthenticationContext,
+ };
+
+ const handleApiRequest = buildApiRequestHandler({
+ routes: buildApiRoutes(apiDeps),
+ });
+
+ app.use('/api/*', async (context, next) => {
+ const response = await handleApiRequest({
+ request: context.req.raw,
+ });
+
+ if (response !== undefined) {
+ return response;
+ }
+
+ await next();
+ });
+}
diff --git a/apps/papra-server/src/modules/app/server.routes.ts b/apps/papra-server/src/modules/app/server.routes.ts
index 585fb469..c71bb9cf 100644
--- a/apps/papra-server/src/modules/app/server.routes.ts
+++ b/apps/papra-server/src/modules/app/server.routes.ts
@@ -15,7 +15,6 @@ import { registerPlanEntitlementsRoutes } from '../plan-entitlements/plan-entitl
import { registerSubscriptionsRoutes } from '../subscriptions/subscriptions.routes';
import { registerTaggingRulesRoutes } from '../tagging-rules/tagging-rules.routes';
import { registerTagsRoutes } from '../tags/tags.routes';
-import { registerUsersRoutes } from '../users/users.routes';
import { registerWebhooksRoutes } from '../webhooks/webhooks.routes';
import { registerAuthRoutes } from './auth/auth.routes';
import { registerHealthCheckRoutes } from './health-check/health-check.routes';
@@ -27,7 +26,6 @@ export function registerRoutes(context: RouteDefinitionContext) {
registerHealthCheckRoutes(context);
registerIntakeEmailsRoutes(context);
registerSubscriptionsRoutes(context);
- registerUsersRoutes(context);
registerOrganizationsRoutes(context);
registerOrganizationSettingsRoutes(context);
registerDocumentsRoutes(context);
diff --git a/apps/papra-server/src/modules/app/server.ts b/apps/papra-server/src/modules/app/server.ts
index 858e26b4..d674f51f 100644
--- a/apps/papra-server/src/modules/app/server.ts
+++ b/apps/papra-server/src/modules/app/server.ts
@@ -9,6 +9,7 @@ import { registerErrorMiddleware } from './middlewares/errors.middleware';
import { createTimeoutMiddleware } from './middlewares/timeout.middleware';
import { registerRoutes } from './server.routes';
import { registerStaticAssetsRoutes } from './static-assets/static-assets.routes';
+import { registerApiRoutes } from './server.api.routes';
export function createServer(dependencies: GlobalDependencies) {
const { config, db, shutdownServices } = dependencies;
@@ -23,8 +24,9 @@ export function createServer(dependencies: GlobalDependencies) {
registerErrorMiddleware({ app });
registerStaticAssetsRoutes({ app, config });
- app.use(createApiKeyMiddleware({ db }));
+ registerApiRoutes({ app, ...dependencies });
+ app.use(createApiKeyMiddleware({ db }));
registerRoutes({ app, ...dependencies });
return {
diff --git a/apps/papra-server/src/modules/app/server.types.ts b/apps/papra-server/src/modules/app/server.types.ts
index 4302659c..e017c05f 100644
--- a/apps/papra-server/src/modules/app/server.types.ts
+++ b/apps/papra-server/src/modules/app/server.types.ts
@@ -16,6 +16,7 @@ import type { EventServices } from './events/events.services';
import type { ShutdownServices } from './graceful-shutdown/graceful-shutdown.services';
import type { PlanEntitlementDefinitionRegistry } from '../plan-entitlements/plan-entitlements.registry';
import type { AiServices } from '../ai/ai.services';
+import type { ResolveAuthenticationContext } from '../api/api.authentication';
export type ServerInstanceGenerics = {
Variables: {
@@ -49,3 +50,7 @@ export type GlobalDependencies = {
};
export type RouteDefinitionContext = { app: ServerInstance } & GlobalDependencies;
+
+export type ApiDependencies = GlobalDependencies & {
+ resolveAuthenticationContext: ResolveAuthenticationContext;
+};
diff --git a/apps/papra-server/src/modules/users/users.api.contracts.ts b/apps/papra-server/src/modules/users/users.api.contracts.ts
new file mode 100644
index 00000000..37122618
--- /dev/null
+++ b/apps/papra-server/src/modules/users/users.api.contracts.ts
@@ -0,0 +1,59 @@
+import { defineApiContract } from '../api/api.contracts';
+import * as v from 'valibot';
+import { isoDateStringSchema } from '../api/api.schemas';
+
+export const getCurrentUserContract = defineApiContract({
+ path: '/api/users/me',
+ method: 'GET',
+ responses: {
+ 200: {
+ description: "Returns the current authenticated user's information.",
+ content: {
+ 'application/json': {
+ schema: v.object({
+ user: v.object({
+ id: v.string(),
+ email: v.string(),
+ name: v.string(),
+ createdAt: isoDateStringSchema,
+ updatedAt: isoDateStringSchema,
+ twoFactorEnabled: v.boolean(),
+ permissions: v.array(v.string()),
+ }),
+ }),
+ },
+ },
+ },
+ },
+});
+
+export const updateCurrentUserContract = defineApiContract({
+ path: '/api/users/me',
+ method: 'PUT',
+ request: {
+ body: {
+ 'application/json': v.strictObject({
+ name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(50)),
+ }),
+ },
+ },
+ responses: {
+ 200: {
+ description: "Updates the current authenticated user's information.",
+ content: {
+ 'application/json': {
+ schema: v.object({
+ user: v.object({
+ id: v.string(),
+ email: v.string(),
+ name: v.string(),
+ createdAt: isoDateStringSchema,
+ updatedAt: isoDateStringSchema,
+ twoFactorEnabled: v.boolean(),
+ }),
+ }),
+ },
+ },
+ },
+ },
+});
diff --git a/apps/papra-server/src/modules/users/users.api.routes.ts b/apps/papra-server/src/modules/users/users.api.routes.ts
new file mode 100644
index 00000000..d9750f52
--- /dev/null
+++ b/apps/papra-server/src/modules/users/users.api.routes.ts
@@ -0,0 +1,75 @@
+import { defineApiRoute } from '../api/api.routes';
+import type { ApiDependencies } from '../app/server.types';
+import { getPermissionsForRoles } from '../roles/roles.methods';
+import { createRolesRepository } from '../roles/roles.repository';
+import { getCurrentUserContract, updateCurrentUserContract } from './users.api.contracts';
+import { createUsersNotFoundError } from './users.errors';
+import { createUsersRepository } from './users.repository';
+
+export function buildUserApiRoutes(deps: ApiDependencies) {
+ return [setupGetCurrentUserRoute(deps), setupUpdateCurrentUserRoute(deps)];
+}
+
+function setupUpdateCurrentUserRoute({ resolveAuthenticationContext, db }: ApiDependencies) {
+ return defineApiRoute({
+ contract: updateCurrentUserContract,
+ resolveContext: resolveAuthenticationContext(),
+ handler: async ({ context: { userId }, body: { name } }) => {
+ const usersRepository = createUsersRepository({ db });
+ const { user } = await usersRepository.updateUser({ userId, name });
+
+ if (!user) {
+ throw createUsersNotFoundError();
+ }
+
+ return {
+ status: 200,
+ contentType: 'application/json',
+ body: {
+ user: {
+ id: user.id,
+ email: user.email,
+ name: user.name ?? '',
+ createdAt: user.createdAt.toISOString(),
+ updatedAt: user.updatedAt.toISOString(),
+ twoFactorEnabled: user.twoFactorEnabled,
+ },
+ },
+ };
+ },
+ });
+}
+
+function setupGetCurrentUserRoute({ resolveAuthenticationContext, db }: ApiDependencies) {
+ return defineApiRoute({
+ contract: getCurrentUserContract,
+ resolveContext: resolveAuthenticationContext(),
+ handler: async ({ context: { userId } }) => {
+ const usersRepository = createUsersRepository({ db });
+ const rolesRepository = createRolesRepository({ db });
+
+ const [{ user }, { roles }] = await Promise.all([
+ usersRepository.getUserByIdOrThrow({ userId }),
+ rolesRepository.getUserRoles({ userId }),
+ ]);
+
+ const { permissions } = getPermissionsForRoles({ roles });
+
+ return {
+ status: 200,
+ contentType: 'application/json',
+ body: {
+ user: {
+ id: user.id,
+ email: user.email,
+ name: user.name ?? '',
+ createdAt: user.createdAt.toISOString(),
+ updatedAt: user.updatedAt.toISOString(),
+ twoFactorEnabled: user.twoFactorEnabled,
+ permissions,
+ },
+ },
+ };
+ },
+ });
+}
diff --git a/apps/papra-server/src/modules/users/users.routes.ts b/apps/papra-server/src/modules/users/users.routes.ts
deleted file mode 100644
index 539de455..00000000
--- a/apps/papra-server/src/modules/users/users.routes.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import type { RouteDefinitionContext } from '../app/server.types';
-import * as v from 'valibot';
-import { requireAuthentication } from '../app/auth/auth.middleware';
-import { getUser } from '../app/auth/auth.models';
-import { getPermissionsForRoles } from '../roles/roles.methods';
-import { createRolesRepository } from '../roles/roles.repository';
-import { pick } from '../shared/objects';
-import { validateJsonBody } from '../shared/validation/validation';
-import { createUsersRepository } from './users.repository';
-
-export function registerUsersRoutes(context: RouteDefinitionContext) {
- setupGetCurrentUserRoute(context);
- setupUpdateUserRoute(context);
-}
-
-function setupGetCurrentUserRoute({ app, db }: RouteDefinitionContext) {
- app.get('/api/users/me', requireAuthentication(), async (context) => {
- const { userId } = getUser({ context });
-
- const usersRepository = createUsersRepository({ db });
- const rolesRepository = createRolesRepository({ db });
-
- const [{ user }, { roles }] = await Promise.all([
- usersRepository.getUserByIdOrThrow({ userId }),
- rolesRepository.getUserRoles({ userId }),
- ]);
-
- const { permissions } = getPermissionsForRoles({ roles });
-
- return context.json({
- user: {
- ...pick(user, ['id', 'email', 'name', 'createdAt', 'updatedAt', 'twoFactorEnabled']),
-
- permissions,
- },
- });
- });
-}
-
-function setupUpdateUserRoute({ app, db }: RouteDefinitionContext) {
- app.put(
- '/api/users/me',
- requireAuthentication(),
- validateJsonBody(
- v.strictObject({
- name: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(50)),
- }),
- ),
- async (context) => {
- const { userId } = getUser({ context });
-
- const { name } = context.req.valid('json');
-
- const usersRepository = createUsersRepository({ db });
-
- const { user } = await usersRepository.updateUser({ userId, name });
-
- return context.json({ user });
- },
- );
-}
diff --git a/packages/api-sdk/README.md b/packages/api-sdk/README.md
index 7db6d8e3..efb8467b 100644
--- a/packages/api-sdk/README.md
+++ b/packages/api-sdk/README.md
@@ -5,7 +5,7 @@ This is a JS/TS SDK for the Papra API.
# Prerequisites
-To use the SDK, you need to have an API key. You can create one in your user settings (under /api-keys).
+For API-key-enabled endpoints, create an API key in your user settings (under /api-keys). Session-only endpoints, such as the current-user endpoints, require a signed-in session instead.
## Installation
@@ -47,6 +47,30 @@ const client = createClient({ apiKey, apiBaseUrl }).forOrganization('org_...');
await client.uploadDocument({ file });
```
+## Contract-based methods
+
+Methods are derived from the server's contract registry; adding a registry entry adds the corresponding SDK method on the next build. Migrated methods accept separate `params`, `query`, and `body` fields and return the successful response body.
+
+For current-user endpoints, use your existing session rather than an API key:
+
+```ts
+const client = createClient({
+ apiBaseUrl: 'https://papra.example',
+ credentials: 'include', // Send the browser's existing session cookie.
+});
+
+const { user } = await client.getCurrentUser();
+await client.updateCurrentUser({ body: { name: 'Alice' } });
+```
+
+For server-side calls, pass session cookies explicitly through `headers: { Cookie: sessionCookie }`. You can also supply a custom `fetch` implementation. The SDK does not sign users in or maintain a cookie jar.
+
+Contract-based methods currently support JSON request/response bodies and bodyless success responses. Path and query parameters support scalar values. Other content formats are rejected when building the client. Existing handwritten methods, including multipart uploads and `forOrganization`, remain available during migration; organization scoping currently applies only to these legacy methods.
+
+Request values use the schemas' input types and are sent without applying server-side transformations. Responses are validated with Valibot and returned as parsed schema outputs; current-user timestamps remain ISO strings.
+
+Contract-based methods throw `ApiHttpError` for unsuccessful HTTP responses (with `status` and `data`), and `ApiResponseError` for successful responses that violate their declared status, content type, or schema. Network errors propagate from the HTTP transport. Legacy methods retain their existing `ofetch` error behavior.
+
## License
This project is licensed under the AGPL-3.0 License - see the [LICENSE](./LICENSE) file for details.
diff --git a/packages/api-sdk/package.json b/packages/api-sdk/package.json
index f09bfe3c..4997805c 100644
--- a/packages/api-sdk/package.json
+++ b/packages/api-sdk/package.json
@@ -24,7 +24,7 @@
"dist"
],
"type": "module",
- "types": "./dist/index.d.ts",
+ "types": "./dist/index.d.mts",
"exports": {
".": "./dist/index.mjs",
"./package.json": "./package.json"
@@ -40,11 +40,16 @@
},
"dependencies": {
"@corentinth/chisels": "catalog:",
- "ofetch": "catalog:"
+ "ofetch": "catalog:",
+ "valibot": "catalog:"
},
"devDependencies": {
+ "@papra/app-server": "workspace:*",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
+ },
+ "inlinedDependencies": {
+ "@papra/app-server": "0.0.0"
}
}
diff --git a/packages/api-sdk/src/api-client.test.ts b/packages/api-sdk/src/api-client.test.ts
new file mode 100644
index 00000000..accdfa33
--- /dev/null
+++ b/packages/api-sdk/src/api-client.test.ts
@@ -0,0 +1,102 @@
+import type { Client } from './api-client';
+import { describe, expect, expectTypeOf, test } from 'vitest';
+import { createClient } from './api-client';
+
+const user = {
+ id: 'usr_alice',
+ email: '[email protected]',
+ name: 'Alice',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ twoFactorEnabled: false,
+};
+
+describe('createClient', () => {
+ test('registry methods use session credentials and custom headers without adding an API key', async () => {
+ const requests: Request[] = [];
+ const headers = new Headers({ 'Cookie': 'session=alice', 'X-Custom': 'value' });
+ const client = createClient({
+ apiBaseUrl: 'https://papra.example',
+ credentials: 'include',
+ headers,
+ fetch: async (input, init) => {
+ const request = new Request(input, init);
+ requests.push(request);
+ return Response.json({ user: { ...user, permissions: [] } });
+ },
+ });
+
+ expect(await client.getCurrentUser()).toEqual({ user: { ...user, permissions: [] } });
+ expect(requests[0]?.url).toEqual('https://papra.example/api/users/me');
+ expect(requests[0]?.method).toEqual('GET');
+ expect(requests[0]?.credentials).toEqual('include');
+ expect(requests[0]?.headers.get('Authorization')).toEqual(null);
+ expect(requests[0]?.headers.get('Cookie')).toEqual('session=alice');
+ expect(requests[0]?.headers.get('X-Custom')).toEqual('value');
+ expect(requests[0]?.headers.get('X-Papra-Source')).toMatch(/^papra-api-sdk-javascript\//);
+ expect(headers.has('X-Papra-Source')).toEqual(false);
+ });
+
+ test('the update method sends a JSON body and returns validated wire dates', async () => {
+ const requests: Request[] = [];
+ const client = createClient({
+ fetch: async (input, init) => {
+ requests.push(new Request(input, init));
+ return Response.json({ user: { ...user, name: 'Updated Alice' } });
+ },
+ });
+
+ const result = await client.updateCurrentUser({ body: { name: ' Updated Alice ' } });
+
+ expect(result).toEqual({ user: { ...user, name: 'Updated Alice' } });
+ expect(requests[0]?.url).toEqual('https://api.papra.app/api/users/me');
+ expect(requests[0]?.method).toEqual('PUT');
+ expect(await requests[0]?.json()).toEqual({ name: ' Updated Alice ' });
+ expectTypeOf(result.user.createdAt).toEqualTypeOf<string>();
+ expectTypeOf(result.user.updatedAt).toEqualTypeOf<string>();
+ expectTypeOf<Parameters<Client['updateCurrentUser']>[0]>().toMatchTypeOf<{
+ body: { name: string };
+ }>();
+ });
+
+ test('unmigrated methods retain API key authentication and organization scoping', async () => {
+ const requests: Request[] = [];
+ const client = createClient({
+ apiKey: 'ppapi_test',
+ fetch: async (input, init) => {
+ requests.push(new Request(input, init));
+ return Response.json({ tags: [] });
+ },
+ });
+
+ expect(await client.forOrganization('org_123').listTags()).toEqual({ tags: [] });
+ expect(requests[0]?.url).toEqual('https://api.papra.app/api/organizations/org_123/tags');
+ expect(requests[0]?.headers.get('Authorization')).toEqual('Bearer ppapi_test');
+ });
+
+ test('legacy document uploads remain multipart requests', async () => {
+ const requests: Request[] = [];
+ const client = createClient({
+ apiKey: 'ppapi_test',
+ fetch: async (input, init) => {
+ requests.push(new Request(input, init));
+ return Response.json({ document: { id: 'doc_123' } });
+ },
+ });
+
+ await client
+ .forOrganization('org_123')
+ .uploadDocument({ file: new File(['hello'], 'hello.txt', { type: 'text/plain' }) });
+
+ expect(requests[0]?.method).toEqual('POST');
+ expect(requests[0]?.headers.get('Content-Type')).toMatch(/^multipart\/form-data; boundary=/);
+ const form = await requests[0]?.formData();
+ const file = form?.get('file');
+ expect(file).toBeInstanceOf(File);
+ if (!(file instanceof File)) {
+ throw new Error('Expected the uploaded file');
+ }
+ expect(file.name).toEqual('hello.txt');
+ expect(await file.text()).toEqual('hello');
+ });
+});
diff --git a/packages/api-sdk/src/api-client.ts b/packages/api-sdk/src/api-client.ts
index fa9bbf98..1f151a5e 100644
--- a/packages/api-sdk/src/api-client.ts
+++ b/packages/api-sdk/src/api-client.ts
@@ -1,144 +1,20 @@
-import type { PapraDocument, PapraTag } from './api-client.types';
-import type { ApiClient } from './http-client';
-import { injectArguments } from '@corentinth/chisels';
+import type { HttpClientOptions } from './http-client';
+import { apiContracts } from '@papra/app-server/api/contract';
+import { createContractClient } from './contract-client';
import { createApiClient } from './http-client';
+import { createLegacyClient } from './legacy-client';
export const PAPRA_API_URL = 'https://api.papra.app';
export type Client = ReturnType<typeof createClient>;
-export function createClient({
- apiKey,
- apiBaseUrl = PAPRA_API_URL,
-}: {
- apiKey: string;
- apiBaseUrl?: string;
-}) {
- const { apiClient } = createApiClient({ apiKey, apiBaseUrl });
+export type ClientOptions = Omit<HttpClientOptions, 'apiBaseUrl'> & { apiBaseUrl?: string };
- const methods = injectArguments(
- {
- uploadDocument,
- trashDocumentsBatch,
- listOrganizations,
- listTags,
- createTag,
- addTagToDocument,
- getCurrentApiKey,
- },
- { apiClient },
- );
+export function createClient({ apiBaseUrl = PAPRA_API_URL, ...options }: ClientOptions = {}) {
+ const { apiClient } = createApiClient({ ...options, apiBaseUrl });
return {
- ...methods,
- forOrganization: (organizationId: string) => injectArguments(methods, { organizationId }),
+ ...createLegacyClient({ apiClient }),
+ ...createContractClient({ contracts: apiContracts, apiClient }),
};
}
-
-async function uploadDocument({
- file,
- organizationId,
- apiClient,
-}: {
- file: File;
- organizationId: string;
- apiClient: ApiClient;
-}) {
- const formData = new FormData();
- formData.append('file', file);
-
- return await apiClient<{ document: PapraDocument }>(
- `/api/organizations/${organizationId}/documents`,
- {
- method: 'POST',
- body: formData,
- },
- );
-}
-
-async function trashDocumentsBatch({
- organizationId,
- filter,
- apiClient,
-}: {
- organizationId: string;
- filter: { documentIds: string[] } | { query: string };
- apiClient: ApiClient;
-}) {
- return await apiClient<{ trashedDocumentIds: string[]; trashedCount: number }>(
- `/api/organizations/${organizationId}/documents/batch/trash`,
- {
- method: 'POST',
- body: { filter },
- },
- );
-}
-
-async function listOrganizations({ apiClient }: { apiClient: ApiClient }) {
- return await apiClient<{ organizations: { id: string; name: string }[] }>('/api/organizations', {
- method: 'GET',
- });
-}
-
-async function listTags({
- organizationId,
- apiClient,
-}: {
- organizationId: string;
- apiClient: ApiClient;
-}) {
- return await apiClient<{ tags: PapraTag[] }>(`/api/organizations/${organizationId}/tags`, {
- method: 'GET',
- });
-}
-
-async function createTag({
- organizationId,
- name,
- color,
- description,
- apiClient,
-}: {
- organizationId: string;
- name: string;
- color: string;
- description?: string;
- apiClient: ApiClient;
-}) {
- return await apiClient<{ tag: PapraTag }>(`/api/organizations/${organizationId}/tags`, {
- method: 'POST',
- body: { name, color, description },
- });
-}
-
-async function addTagToDocument({
- organizationId,
- documentId,
- tagId,
- apiClient,
-}: {
- organizationId: string;
- documentId: string;
- tagId: string;
- apiClient: ApiClient;
-}) {
- return await apiClient<void>(
- `/api/organizations/${organizationId}/documents/${documentId}/tags`,
- {
- method: 'POST',
- body: { tagId },
- },
- );
-}
-
-async function getCurrentApiKey({ apiClient }: { apiClient: ApiClient }) {
- return await apiClient<{
- apiKey: {
- id: string;
- name: string;
- permissions: string[];
- };
- }>('/api/api-keys/current', {
- method: 'GET',
- });
-}
diff --git a/packages/api-sdk/src/contract-client.errors.ts b/packages/api-sdk/src/contract-client.errors.ts
new file mode 100644
index 00000000..31283728
--- /dev/null
+++ b/packages/api-sdk/src/contract-client.errors.ts
@@ -0,0 +1,41 @@
+type ApiErrorContext = {
+ method: string;
+ path: string;
+ status: number;
+};
+
+export class ApiHttpError extends Error {
+ readonly method: string;
+ readonly path: string;
+ readonly status: number;
+ readonly data: unknown;
+
+ constructor({ method, path, status, data }: ApiErrorContext & { data: unknown }) {
+ super(`${method} ${path} failed with status ${status}`);
+ this.name = 'ApiHttpError';
+ this.method = method;
+ this.path = path;
+ this.status = status;
+ this.data = data;
+ }
+}
+
+export class ApiResponseError extends Error {
+ readonly method: string;
+ readonly path: string;
+ readonly status: number;
+
+ constructor({
+ method,
+ path,
+ status,
+ message,
+ cause,
+ }: ApiErrorContext & { message: string; cause?: unknown }) {
+ super(`${method} ${path}: ${message}`, { cause });
+ this.name = 'ApiResponseError';
+ this.method = method;
+ this.path = path;
+ this.status = status;
+ }
+}
diff --git a/packages/api-sdk/src/contract-client.test.ts b/packages/api-sdk/src/contract-client.test.ts
new file mode 100644
index 00000000..b2f9c872
--- /dev/null
+++ b/packages/api-sdk/src/contract-client.test.ts
@@ -0,0 +1,248 @@
+import type { ApiContract } from '@papra/app-server/api/contract';
+import * as v from 'valibot';
+import { describe, expect, test } from 'vitest';
+import { createContractClient } from './contract-client';
+import { ApiHttpError, ApiResponseError } from './contract-client.errors';
+import { createApiClient } from './http-client';
+
+const getItemContract = {
+ method: 'GET',
+ path: '/api/items',
+ responses: {
+ 200: {
+ description: 'An item.',
+ content: { 'application/json': { schema: v.object({ name: v.string() }) } },
+ },
+ },
+} as const satisfies ApiContract;
+
+function createTestClient<const Contract extends ApiContract>(
+ contract: Contract,
+ respond: (request: Request) => Response | Promise<Response>,
+) {
+ const requests: Request[] = [];
+ const { apiClient } = createApiClient({
+ apiBaseUrl: 'https://papra.example',
+ fetch: async (input, init) => {
+ const request = new Request(input, init);
+ requests.push(request);
+ return await respond(request);
+ },
+ });
+
+ return { client: createContractClient({ contracts: { call: contract }, apiClient }), requests };
+}
+
+describe('contract client', () => {
+ test('path and query values are encoded and request transformations are left to the server', async () => {
+ let transformations = 0;
+ const { client, requests } = createTestClient(
+ {
+ ...getItemContract,
+ method: 'POST',
+ path: '/api/items/:id',
+ request: {
+ params: v.object({ id: v.string() }),
+ query: v.object({ search: v.string(), page: v.optional(v.string()) }),
+ body: {
+ 'application/json': v.object({
+ count: v.pipe(
+ v.string(),
+ v.transform((value) => {
+ transformations++;
+ return Number(value) + 1;
+ }),
+ ),
+ }),
+ },
+ },
+ responses: {
+ 200: {
+ description: 'A parsed count.',
+ content: {
+ 'application/json': {
+ schema: v.object({ count: v.pipe(v.string(), v.transform(Number)) }),
+ },
+ },
+ },
+ },
+ },
+ () =>
+ Response.json(
+ { count: '3' },
+ { headers: { 'Content-Type': 'application/json; charset=utf-8' } },
+ ),
+ );
+
+ expect(
+ await client.call({
+ params: { id: 'a/b ?' },
+ query: { search: 'x&y', page: undefined },
+ body: { count: '2' },
+ }),
+ ).toEqual({ count: 3 });
+ expect(transformations).toEqual(0);
+ expect(requests).toHaveLength(1);
+ const [request] = requests;
+ expect(request?.url).toEqual('https://papra.example/api/items/a%2Fb%20%3F?search=x%26y');
+ expect(request?.method).toEqual('POST');
+ expect(request?.headers.get('Content-Type')).toEqual('application/json');
+ expect(request?.headers.get('Accept')).toEqual('application/json');
+ expect(await request?.json()).toEqual({ count: '2' });
+ });
+
+ test('JSON string bodies are serialized rather than sent as unquoted text', async () => {
+ const { client, requests } = createTestClient(
+ { ...getItemContract, method: 'PUT', request: { body: { 'application/json': v.string() } } },
+ () => Response.json({ name: 'Alice' }),
+ );
+
+ await client.call({ body: 'Alice' });
+
+ expect(await requests[0]?.text()).toEqual('"Alice"');
+ });
+
+ test('the actual success status selects its response schema', async () => {
+ const { client } = createTestClient(
+ {
+ ...getItemContract,
+ responses: {
+ ...getItemContract.responses,
+ 201: {
+ description: 'A created item.',
+ content: { 'application/json': { schema: v.object({ id: v.number() }) } },
+ },
+ },
+ },
+ () => Response.json({ id: 123 }, { status: 201 }),
+ );
+
+ expect(await client.call()).toEqual({ id: 123 });
+ });
+
+ test('bodyless successful responses return undefined without parsing JSON', async () => {
+ const { client } = createTestClient(
+ {
+ method: 'DELETE',
+ path: '/api/items',
+ responses: { 204: { description: 'Deleted.', content: {} } },
+ },
+ () => new Response(null, { status: 204 }),
+ );
+
+ expect(await client.call()).toEqual(undefined);
+ });
+
+ test('HTTP failures expose their status and JSON payload even when undeclared', async () => {
+ const data = { error: { code: 'auth.unauthorized', message: 'Unauthorized' } };
+ const { client } = createTestClient(getItemContract, () =>
+ Response.json(data, { status: 401 }),
+ );
+ const result = client.call();
+
+ await expect(result).rejects.toBeInstanceOf(ApiHttpError);
+ await expect(result).rejects.toMatchObject({
+ status: 401,
+ data,
+ method: 'GET',
+ path: '/api/items',
+ });
+ });
+
+ test('non-JSON HTTP failures retain their body and are not retried', async () => {
+ const { client, requests } = createTestClient(
+ getItemContract,
+ () => new Response('Bad gateway', { status: 502 }),
+ );
+ const result = client.call();
+
+ await expect(result).rejects.toBeInstanceOf(ApiHttpError);
+ await expect(result).rejects.toMatchObject({ status: 502, data: 'Bad gateway' });
+ expect(requests).toHaveLength(1);
+ });
+
+ test('a successful response with an invalid payload is a contract error, not an HTTP error', async () => {
+ const { client } = createTestClient(getItemContract, () => Response.json({ name: 123 }));
+ const result = client.call();
+
+ await expect(result).rejects.toBeInstanceOf(ApiResponseError);
+ await expect(result).rejects.toMatchObject({ status: 200, cause: { name: 'ValiError' } });
+ });
+
+ test('undeclared success statuses are rejected', async () => {
+ const { client } = createTestClient(getItemContract, () =>
+ Response.json({ name: 'Alice' }, { status: 201 }),
+ );
+
+ await expect(client.call()).rejects.toMatchObject({
+ name: 'ApiResponseError',
+ status: 201,
+ message: 'GET /api/items: Undeclared response status',
+ });
+ });
+
+ test('a JSON-looking response with an undeclared content type is rejected', async () => {
+ const { client } = createTestClient(
+ getItemContract,
+ () => new Response('{"name":"Alice"}', { headers: { 'Content-Type': 'text/plain' } }),
+ );
+
+ await expect(client.call()).rejects.toMatchObject({
+ name: 'ApiResponseError',
+ message: 'GET /api/items: Unexpected response Content-Type',
+ });
+ });
+
+ test('malformed JSON cannot satisfy even a string response schema', async () => {
+ const { client } = createTestClient(
+ {
+ ...getItemContract,
+ responses: {
+ 200: { description: 'A name.', content: { 'application/json': { schema: v.string() } } },
+ },
+ },
+ () => new Response('Alice', { headers: { 'Content-Type': 'application/json' } }),
+ );
+
+ await expect(client.call()).rejects.toBeInstanceOf(ApiResponseError);
+ });
+
+ test('unsupported request formats fail when building the client', () => {
+ expect(() =>
+ createTestClient(
+ { ...getItemContract, method: 'POST', request: { body: { 'text/plain': v.string() } } },
+ () => Response.json({ name: 'Alice' }),
+ ),
+ ).toThrow('only JSON request bodies are supported');
+ });
+
+ test('unsupported response formats fail when building the client', () => {
+ expect(() =>
+ createTestClient(
+ {
+ ...getItemContract,
+ responses: {
+ 200: { description: 'A name.', content: { 'text/plain': { schema: v.string() } } },
+ },
+ },
+ () => new Response('Alice'),
+ ),
+ ).toThrow('only JSON or bodyless responses are supported');
+ });
+
+ test('path traversal values are rejected before a request is made', async () => {
+ const { client, requests } = createTestClient(
+ {
+ ...getItemContract,
+ path: '/api/items/:id',
+ request: { params: v.object({ id: v.string() }) },
+ },
+ () => Response.json({ name: 'Alice' }),
+ );
+
+ await expect(client.call({ params: { id: '..' } })).rejects.toThrow(
+ 'Invalid path parameter: id',
+ );
+ expect(requests).toHaveLength(0);
+ });
+});
diff --git a/packages/api-sdk/src/contract-client.ts b/packages/api-sdk/src/contract-client.ts
new file mode 100644
index 00000000..f6718976
--- /dev/null
+++ b/packages/api-sdk/src/contract-client.ts
@@ -0,0 +1,158 @@
+import type { ApiContract } from '@papra/app-server/api/contract';
+import type { ContractClient } from './contract-client.types';
+import type { ApiClient } from './http-client';
+import * as v from 'valibot';
+import { ApiHttpError, ApiResponseError } from './contract-client.errors';
+
+type RequestInput = {
+ params?: Record<string, unknown>;
+ query?: Record<string, unknown>;
+ body?: unknown;
+};
+
+export function createContractClient<const Contracts extends Record<string, ApiContract>>({
+ contracts,
+ apiClient,
+}: {
+ contracts: Contracts;
+ apiClient: ApiClient;
+}): ContractClient<Contracts> {
+ const entries = Object.entries(contracts).map(([name, contract]) => {
+ assertSupportedContract(contract);
+
+ return [
+ name,
+ async (input: RequestInput = {}) => executeRequest({ contract, apiClient, input }),
+ ];
+ });
+
+ // Dynamic registry iteration erases the correlation between each name and its contract.
+ // Keep that assertion here; callers retain their contract's request and response types.
+ return Object.fromEntries(entries) as ContractClient<Contracts>;
+}
+
+function assertSupportedContract(contract: ApiContract) {
+ const bodyTypes = Object.keys(contract.request?.body ?? {});
+
+ if (contract.request?.body && (bodyTypes.length !== 1 || bodyTypes[0] !== 'application/json')) {
+ throw new TypeError(
+ `${contract.method} ${contract.path}: only JSON request bodies are supported`,
+ );
+ }
+
+ for (const [status, response] of Object.entries(contract.responses)) {
+ const contentTypes = Object.keys(response.content);
+ const isBodyless = ['204', '205', '304'].includes(status);
+
+ if (
+ isBodyless
+ ? contentTypes.length !== 0
+ : contentTypes.length !== 1 || contentTypes[0] !== 'application/json'
+ ) {
+ throw new TypeError(
+ `${contract.method} ${contract.path}: only JSON or bodyless responses are supported`,
+ );
+ }
+ }
+}
+
+function serializeValue(value: unknown): string {
+ if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') {
+ throw new TypeError('Path and query parameters must be strings, numbers, or booleans');
+ }
+
+ return String(value);
+}
+
+function buildRequestPath({ contract, input }: { contract: ApiContract; input: RequestInput }) {
+ const path = contract.path.replace(/:([A-Za-z0-9_]+)/g, (_, name: string) => {
+ const value = input.params?.[name];
+
+ if (value === undefined || value === null) {
+ throw new TypeError(`Missing path parameter: ${name}`);
+ }
+
+ const serialized = serializeValue(value);
+
+ if (serialized === '.' || serialized === '..') {
+ throw new TypeError(`Invalid path parameter: ${name}`);
+ }
+
+ return encodeURIComponent(serialized);
+ });
+ const query = new URLSearchParams();
+
+ for (const [key, value] of Object.entries(input.query ?? {})) {
+ if (value !== undefined && value !== null) {
+ query.set(key, serializeValue(value));
+ }
+ }
+
+ const search = query.toString();
+ return search ? `${path}?${search}` : path;
+}
+
+async function executeRequest({
+ contract,
+ apiClient,
+ input,
+}: {
+ contract: ApiContract;
+ apiClient: ApiClient;
+ input: RequestInput;
+}): Promise<unknown> {
+ const path = buildRequestPath({ contract, input });
+ const hasBody = contract.request?.body !== undefined;
+ const response = await apiClient.raw(path, {
+ method: contract.method,
+ headers: {
+ Accept: 'application/json',
+ ...(hasBody ? { 'Content-Type': 'application/json' } : {}),
+ },
+ body: hasBody ? JSON.stringify(input.body) : undefined,
+ // Read text so malformed JSON cannot be accepted by ofetch's permissive JSON parser.
+ responseType: 'text',
+ ignoreResponseError: true,
+ retry: 0,
+ });
+ const errorContext = { method: contract.method, path: contract.path, status: response.status };
+
+ if (!response.ok) {
+ let data: unknown = response._data;
+
+ try {
+ data = JSON.parse(response._data ?? '');
+ } catch {
+ // Proxies and older servers may return non-JSON error bodies.
+ }
+
+ throw new ApiHttpError({ ...errorContext, data });
+ }
+
+ const definition = contract.responses[response.status];
+
+ if (!definition) {
+ throw new ApiResponseError({ ...errorContext, message: 'Undeclared response status' });
+ }
+
+ if ([204, 205, 304].includes(response.status)) {
+ return undefined;
+ }
+
+ const contentType = response.headers.get('Content-Type')?.split(';', 1)[0]?.trim().toLowerCase();
+ const schema = definition.content['application/json']?.schema;
+
+ if (contentType !== 'application/json' || !schema) {
+ throw new ApiResponseError({ ...errorContext, message: 'Unexpected response Content-Type' });
+ }
+
+ try {
+ return v.parse(schema, JSON.parse(response._data ?? ''));
+ } catch (cause) {
+ throw new ApiResponseError({
+ ...errorContext,
+ message: 'Response does not match its contract',
+ cause,
+ });
+ }
+}
diff --git a/packages/api-sdk/src/contract-client.types.test.ts b/packages/api-sdk/src/contract-client.types.test.ts
new file mode 100644
index 00000000..0c10a66a
--- /dev/null
+++ b/packages/api-sdk/src/contract-client.types.test.ts
@@ -0,0 +1,121 @@
+import type { ApiContract } from '@papra/app-server/api/contract';
+import type {
+ ClientMethod,
+ ClientRequest,
+ ClientResponse,
+ ContractClient,
+} from './contract-client.types';
+import * as v from 'valibot';
+import { describe, expectTypeOf, test } from 'vitest';
+
+const contracts = {
+ getItem: {
+ method: 'GET',
+ path: '/api/items',
+ responses: {
+ 200: {
+ description: 'An item.',
+ content: { 'application/json': { schema: v.object({ name: v.string() }) } },
+ },
+ },
+ },
+ updateItem: {
+ method: 'PUT',
+ path: '/api/items/:id',
+ request: {
+ params: v.object({ id: v.pipe(v.string(), v.transform(Number)) }),
+ query: v.object({ page: v.optional(v.pipe(v.string(), v.transform(Number)), '1') }),
+ body: { 'application/json': v.object({ count: v.pipe(v.string(), v.transform(Number)) }) },
+ },
+ responses: {
+ 200: {
+ description: 'A count.',
+ content: {
+ 'application/json': {
+ schema: v.object({ count: v.pipe(v.string(), v.transform(Number)) }),
+ },
+ },
+ },
+ 201: {
+ description: 'An id.',
+ content: { 'application/json': { schema: v.object({ id: v.string() }) } },
+ },
+ 204: { description: 'No content.', content: {} },
+ 400: {
+ description: 'Invalid input.',
+ content: { 'application/json': { schema: v.object({ error: v.string() }) } },
+ },
+ },
+ },
+ searchItems: {
+ method: 'GET',
+ path: '/api/items/search',
+ request: { query: v.object({ search: v.string() }) },
+ responses: { 204: { description: 'No content.', content: {} } },
+ },
+} as const satisfies Record<string, ApiContract>;
+
+describe('contract client types', () => {
+ test('request types use schema inputs, before transformations and defaults', () => {
+ expectTypeOf<ClientRequest<typeof contracts.updateItem>>().toEqualTypeOf<
+ {
+ params: { id: string };
+ } & {
+ query?: { page?: string };
+ } & {
+ body: { count: string };
+ }
+ >();
+ });
+
+ test('response types contain parsed successful bodies, excluding HTTP errors', () => {
+ expectTypeOf<ClientResponse<typeof contracts.updateItem>>().toEqualTypeOf<
+ { count: number } | { id: string } | void
+ >();
+ expectTypeOf<ClientResponse<typeof contracts.searchItems>>().toEqualTypeOf<void>();
+ });
+
+ test('methods require only their declared inputs and preserve registry names', () => {
+ expectTypeOf<keyof ContractClient<typeof contracts>>().toEqualTypeOf<
+ 'getItem' | 'updateItem' | 'searchItems'
+ >();
+ expectTypeOf<ClientMethod<typeof contracts.getItem>>().toBeCallableWith();
+ expectTypeOf<ClientMethod<typeof contracts.updateItem>>().toBeCallableWith({
+ params: { id: '123' },
+ body: { count: '2' },
+ });
+ expectTypeOf<ClientMethod<typeof contracts.searchItems>>().toBeCallableWith({
+ query: { search: 'Alice' },
+ });
+
+ // Compile-only calls: invalid invocations must not issue real requests.
+ function checkInputs(client: ContractClient<typeof contracts>) {
+ // @ts-expect-error An update requires its body and path parameters.
+ void client.updateItem();
+ // @ts-expect-error Path parameters cannot be omitted.
+ void client.updateItem({ body: { count: '2' } });
+ // @ts-expect-error The body accepts the wire string, not the server's parsed number.
+ void client.updateItem({ params: { id: '123' }, body: { count: 2 } });
+ // @ts-expect-error This endpoint has no request body.
+ void client.getItem({ body: { name: 'Alice' } });
+ // @ts-expect-error A required query cannot be omitted.
+ void client.searchItems();
+ // @ts-expect-error Methods cannot override the contract's HTTP method.
+ void client.getItem({ method: 'POST' });
+ // @ts-expect-error Unknown registry methods are not exposed.
+ void client.deleteItem();
+ }
+
+ expectTypeOf(checkInputs).toBeFunction();
+ });
+
+ test('a query consisting only of optional fields allows a no-argument call', () => {
+ const contract = {
+ ...contracts.getItem,
+ request: { query: v.object({ limit: v.optional(v.string(), '10') }) },
+ };
+
+ expectTypeOf<ClientMethod<typeof contract>>().toBeCallableWith();
+ expectTypeOf<ClientMethod<typeof contract>>().toBeCallableWith({ query: { limit: '20' } });
+ });
+});
diff --git a/packages/api-sdk/src/contract-client.types.ts b/packages/api-sdk/src/contract-client.types.ts
new file mode 100644
index 00000000..0f7b9aa4
--- /dev/null
+++ b/packages/api-sdk/src/contract-client.types.ts
@@ -0,0 +1,63 @@
+import type { GenericSchema, InferInput, InferOutput } from 'valibot';
+
+type RequestSchema<Contract, Key extends string> = Contract extends { request: infer Request }
+ ? Key extends keyof Request
+ ? Request[Key]
+ : never
+ : never;
+
+type JsonBodySchema<Contract> =
+ RequestSchema<Contract, 'body'> extends infer Body
+ ? Body extends { 'application/json': infer Schema }
+ ? Schema
+ : never
+ : never;
+
+type RequestField<Key extends string, Schema, AllowEmpty extends boolean = false> = [
+ Schema,
+] extends [never]
+ ? { [K in Key]?: never }
+ : Schema extends GenericSchema
+ ? AllowEmpty extends true
+ ? {} extends InferInput<Schema>
+ ? { [K in Key]?: InferInput<Schema> }
+ : { [K in Key]: InferInput<Schema> }
+ : { [K in Key]: InferInput<Schema> }
+ : { [K in Key]?: never };
+
+// These are wire inputs, not the transformed values received by server handlers.
+export type ClientRequest<Contract> = RequestField<
+ 'params',
+ RequestSchema<Contract, 'params'>,
+ true
+> &
+ RequestField<'query', RequestSchema<Contract, 'query'>, true> &
+ RequestField<'body', JsonBodySchema<Contract>>;
+
+type Responses<Contract> = Contract extends { responses: infer Definitions } ? Definitions : never;
+
+type SuccessStatus<Contract> = {
+ [Status in keyof Responses<Contract> & number]: `${Status}` extends `2${string}` ? Status : never;
+}[keyof Responses<Contract> & number];
+
+type JsonResponse<Response> = Response extends {
+ content: { 'application/json': { schema: infer Schema extends GenericSchema } };
+}
+ ? InferOutput<Schema>
+ : never;
+
+export type ClientResponse<Contract> = {
+ [Status in SuccessStatus<Contract>]: Status extends 204 | 205
+ ? void
+ : JsonResponse<Responses<Contract>[Status]>;
+}[SuccessStatus<Contract>];
+
+export type ClientMethod<Contract> = (
+ ...args: {} extends ClientRequest<Contract>
+ ? [input?: ClientRequest<Contract>]
+ : [input: ClientRequest<Contract>]
+) => Promise<ClientResponse<Contract>>;
+
+export type ContractClient<Contracts> = {
+ [Name in keyof Contracts]: ClientMethod<Contracts[Name]>;
+};
diff --git a/packages/api-sdk/src/http-client.ts b/packages/api-sdk/src/http-client.ts
index 6a57a595..93435e46 100644
--- a/packages/api-sdk/src/http-client.ts
+++ b/packages/api-sdk/src/http-client.ts
@@ -4,16 +4,32 @@ import { version } from '../package.json';
export type ApiClient = $Fetch;
-export function createApiClient({ apiKey, apiBaseUrl }: { apiKey: string; apiBaseUrl: string }): {
- apiClient: ApiClient;
-} {
- const apiClient = ofetch.create({
- headers: {
- 'Authorization': `Bearer ${apiKey}`,
- 'X-Papra-Source': `papra-api-sdk-javascript/${version}`,
- },
- baseURL: apiBaseUrl,
- });
+export type HttpClientOptions = {
+ apiKey?: string;
+ apiBaseUrl: string;
+ headers?: HeadersInit;
+ credentials?: RequestCredentials;
+ fetch?: typeof globalThis.fetch;
+};
+
+export function createApiClient({
+ apiKey,
+ apiBaseUrl,
+ headers: customHeaders,
+ credentials,
+ fetch: fetchImplementation,
+}: HttpClientOptions): { apiClient: ApiClient } {
+ const headers = new Headers(customHeaders);
+ headers.set('X-Papra-Source', `papra-api-sdk-javascript/${version}`);
+
+ if (apiKey) {
+ headers.set('Authorization', `Bearer ${apiKey}`);
+ }
+
+ const apiClient = ofetch.create(
+ { headers, baseURL: apiBaseUrl, credentials },
+ { fetch: fetchImplementation },
+ );
return {
apiClient,
diff --git a/packages/api-sdk/src/index.ts b/packages/api-sdk/src/index.ts
index a3a9a5d8..3a8234dd 100644
--- a/packages/api-sdk/src/index.ts
+++ b/packages/api-sdk/src/index.ts
@@ -1,3 +1,4 @@
export { createClient, PAPRA_API_URL } from './api-client';
-export type { Client } from './api-client';
+export type { Client, ClientOptions } from './api-client';
+export { ApiHttpError, ApiResponseError } from './contract-client.errors';
diff --git a/packages/api-sdk/src/legacy-client.ts b/packages/api-sdk/src/legacy-client.ts
new file mode 100644
index 00000000..0f17269b
--- /dev/null
+++ b/packages/api-sdk/src/legacy-client.ts
@@ -0,0 +1,117 @@
+import type { PapraDocument, PapraTag } from './api-client.types';
+import type { ApiClient } from './http-client';
+import { injectArguments } from '@corentinth/chisels';
+
+// Retain the public SDK methods until their endpoints have contracts.
+export function createLegacyClient({ apiClient }: { apiClient: ApiClient }) {
+ const methods = injectArguments(
+ {
+ uploadDocument,
+ trashDocumentsBatch,
+ listOrganizations,
+ listTags,
+ createTag,
+ addTagToDocument,
+ getCurrentApiKey,
+ },
+ { apiClient },
+ );
+
+ return {
+ ...methods,
+ forOrganization: (organizationId: string) => injectArguments(methods, { organizationId }),
+ };
+}
+
+async function uploadDocument({
+ file,
+ organizationId,
+ apiClient,
+}: {
+ file: File;
+ organizationId: string;
+ apiClient: ApiClient;
+}) {
+ const formData = new FormData();
+ formData.append('file', file);
+
+ return await apiClient<{ document: PapraDocument }>(
+ `/api/organizations/${organizationId}/documents`,
+ { method: 'POST', body: formData },
+ );
+}
+
+async function trashDocumentsBatch({
+ organizationId,
+ filter,
+ apiClient,
+}: {
+ organizationId: string;
+ filter: { documentIds: string[] } | { query: string };
+ apiClient: ApiClient;
+}) {
+ return await apiClient<{ trashedDocumentIds: string[]; trashedCount: number }>(
+ `/api/organizations/${organizationId}/documents/batch/trash`,
+ { method: 'POST', body: { filter } },
+ );
+}
+
+async function listOrganizations({ apiClient }: { apiClient: ApiClient }) {
+ return await apiClient<{ organizations: { id: string; name: string }[] }>('/api/organizations', {
+ method: 'GET',
+ });
+}
+
+async function listTags({
+ organizationId,
+ apiClient,
+}: {
+ organizationId: string;
+ apiClient: ApiClient;
+}) {
+ return await apiClient<{ tags: PapraTag[] }>(`/api/organizations/${organizationId}/tags`, {
+ method: 'GET',
+ });
+}
+
+async function createTag({
+ organizationId,
+ name,
+ color,
+ description,
+ apiClient,
+}: {
+ organizationId: string;
+ name: string;
+ color: string;
+ description?: string;
+ apiClient: ApiClient;
+}) {
+ return await apiClient<{ tag: PapraTag }>(`/api/organizations/${organizationId}/tags`, {
+ method: 'POST',
+ body: { name, color, description },
+ });
+}
+
+async function addTagToDocument({
+ organizationId,
+ documentId,
+ tagId,
+ apiClient,
+}: {
+ organizationId: string;
+ documentId: string;
+ tagId: string;
+ apiClient: ApiClient;
+}) {
+ return await apiClient<void>(
+ `/api/organizations/${organizationId}/documents/${documentId}/tags`,
+ { method: 'POST', body: { tagId } },
+ );
+}
+
+async function getCurrentApiKey({ apiClient }: { apiClient: ApiClient }) {
+ return await apiClient<{
+ apiKey: { id: string; name: string; permissions: string[] };
+ }>('/api/api-keys/current', { method: 'GET' });
+}
diff --git a/packages/api-sdk/tsdown.config.ts b/packages/api-sdk/tsdown.config.ts
index 1feec394..745079b9 100644
--- a/packages/api-sdk/tsdown.config.ts
+++ b/packages/api-sdk/tsdown.config.ts
@@ -4,4 +4,7 @@ export default defineConfig({
entry: ['./src/index.ts'],
dts: true,
exports: true,
+ deps: {
+ alwaysBundle: ['@papra/app-server'],
+ },
});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index cd39fdbc..450ead03 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -720,6 +720,9 @@ importers:
resend:
specifier: ^4.6.0
+ rou3:
+ specifier: ^0.12.0
+ version: 0.12.0
s3mini:
specifier: ^0.9.5
version: 0.9.5
@@ -878,7 +881,13 @@ importers:
ofetch:
specifier: 'catalog:'
version: 1.4.1
+ valibot:
+ specifier: 'catalog:'
+ version: 1.4.2([email protected])
devDependencies:
+ '@papra/app-server':
+ specifier: workspace:*
tsdown:
specifier: 'catalog:'
@@ -9722,6 +9731,10 @@ packages:
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
+ resolution: {integrity: sha512-V2L6A3jA3RV/zI4pSXkV8OF3+8zPOfaYsb2bV9nTzxV/TXRYDtXgv+k0n1QnYrR0XuTkHfR63wU3Nov6hKCaAA==}
+ engines: {node: '>=20.19.0'}
+
resolution: {integrity: sha512-iFE4hLDuloSWcD7mjdCDhx2bKcIsYbtOTpfH5MHHLSKMOUyjqQXTeZVa289uuwEGEKFoE/BAPbhaU4B774nceg==}
@@ -12970,7 +12983,7 @@ snapshots:
nanostores: 1.3.0
zod: 4.5.4
dependencies:
'@better-auth/utils': 0.4.0
@@ -13003,29 +13016,29 @@ snapshots:
expo-network: 8.0.8([email protected])([email protected])
dependencies:
'@better-auth/utils': 0.4.0
optionalDependencies:
kysely: 0.28.17
dependencies:
'@better-auth/utils': 0.4.0
dependencies:
'@better-auth/utils': 0.4.0
dependencies:
'@better-auth/utils': 0.4.0
dependencies:
'@better-auth/utils': 0.4.0
@@ -15562,6 +15575,7 @@ snapshots:
picomatch: 4.0.7
posthog-node: 5.20.0
+ rou3: 0.12.0
s3mini: 0.9.5
stripe: 17.7.0
tsx: 4.21.0
@@ -18037,12 +18051,12 @@ snapshots:
dependencies:
- '@better-auth/memory-adapter': 1.6.11(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
- '@better-auth/mongo-adapter': 1.6.11(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
- '@better-auth/prisma-adapter': 1.6.11(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
- '@better-auth/telemetry': 1.6.11(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])
+ '@better-auth/kysely-adapter': 1.6.11(@better-auth/[email protected](@better-fetch/[email protected])([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected])
+ '@better-auth/memory-adapter': 1.6.11(@better-auth/[email protected](@better-fetch/[email protected])([email protected])([email protected])([email protected]))(@better-auth/[email protected])
+ '@better-auth/mongo-adapter': 1.6.11(@better-auth/[email protected](@better-fetch/[email protected])([email protected])([email protected])([email protected]))(@better-auth/[email protected])
+ '@better-auth/prisma-adapter': 1.6.11(@better-auth/[email protected](@better-fetch/[email protected])([email protected])([email protected])([email protected]))(@better-auth/[email protected])
+ '@better-auth/telemetry': 1.6.11(@better-auth/[email protected](@better-fetch/[email protected])([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])
'@better-auth/utils': 0.4.0
'@better-fetch/fetch': 1.1.21
'@noble/ciphers': 2.2.0
@@ -18059,7 +18073,7 @@ snapshots:
react: 19.1.0
react-dom: 19.1.0([email protected])
solid-js: 1.9.13
transitivePeerDependencies:
- '@cloudflare/workers-types'
- '@opentelemetry/api'
@@ -18067,12 +18081,12 @@ snapshots:
dependencies:
- '@better-auth/memory-adapter': 1.6.11(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
- '@better-auth/mongo-adapter': 1.6.11(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
- '@better-auth/prisma-adapter': 1.6.11(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
- '@better-auth/telemetry': 1.6.11(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])
+ '@better-auth/kysely-adapter': 1.6.11(@better-auth/[email protected](@better-fetch/[email protected])([email protected])([email protected])([email protected]))(@better-auth/[email protected])([email protected])
+ '@better-auth/memory-adapter': 1.6.11(@better-auth/[email protected](@better-fetch/[email protected])([email protected])([email protected])([email protected]))(@better-auth/[email protected])
+ '@better-auth/mongo-adapter': 1.6.11(@better-auth/[email protected](@better-fetch/[email protected])([email protected])([email protected])([email protected]))(@better-auth/[email protected])
+ '@better-auth/prisma-adapter': 1.6.11(@better-auth/[email protected](@better-fetch/[email protected])([email protected])([email protected])([email protected]))(@better-auth/[email protected])
+ '@better-auth/telemetry': 1.6.11(@better-auth/[email protected](@better-fetch/[email protected])([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])
'@better-auth/utils': 0.4.0
'@better-fetch/fetch': 1.1.21
'@noble/ciphers': 2.2.0
@@ -18089,7 +18103,7 @@ snapshots:
react: 19.2.7
react-dom: 19.2.7([email protected])
solid-js: 1.9.13
transitivePeerDependencies:
- '@cloudflare/workers-types'
- '@opentelemetry/api'
@@ -22844,6 +22858,8 @@ snapshots:
'@rolldown/binding-win32-arm64-msvc': 1.2.8
'@rolldown/binding-win32-x64-msvc': 1.2.8
+
@@ -24226,34 +24242,6 @@ snapshots:
transitivePeerDependencies:
- msw
- dependencies:
- '@vitest/expect': 4.1.11
- '@vitest/pretty-format': 4.1.11
- '@vitest/runner': 4.1.11
- '@vitest/snapshot': 4.1.11
- '@vitest/spy': 4.1.11
- '@vitest/utils': 4.1.11
- es-module-lexer: 2.1.0
- expect-type: 1.3.0
- magic-string: 0.30.21
- obug: 2.1.3
- pathe: 2.0.3
- picomatch: 4.0.4
- std-env: 4.1.0
- tinybench: 2.9.0
- tinyexec: 1.3.0
- tinyglobby: 0.2.17
- tinyrainbow: 3.1.0
- why-is-node-running: 2.3.0
- optionalDependencies:
- '@types/node': 26.0.1
- transitivePeerDependencies:
- - msw
- optional: true
-