Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

refactor(papra-server): reorganize storage module to be document-agnostic (#1449)

Corentin Thomasseta8628cdbab21
diff --git a/apps/papra-server/src/modules/app/server.test-utils.ts b/apps/papra-server/src/modules/app/server.test-utils.ts
index e7b136ee..a02ebc40 100644
--- a/apps/papra-server/src/modules/app/server.test-utils.ts
+++ b/apps/papra-server/src/modules/app/server.test-utils.ts
@@ -2,7 +2,7 @@ import type { GlobalDependencies } from './server.types';
import { overrideConfig } from '../config/config.test-utils';
import { createDocumentSearchServices } from '../documents/document-search/document-search.registry';
-import { createDocumentStorageService } from '../documents/storage/documents.storage.services';
+import { createStorageService } from '../storage/storage.services';
import { createEmailsServices } from '../emails/emails.services';
import { createInMemoryKvStoreDriver } from '../kv-store/drivers/in-memory/in-memory.kv-store-driver';
import { createKvStore } from '../kv-store/kv-store';
@@ -33,7 +33,13 @@ export function createTestServerDependencies(
const documentsStorageService =
overrides.documentsStorageService ??
- createDocumentStorageService({ documentStorageConfig: config.documentsStorage });
+ createStorageService({
+ storageConfig: config.documentsStorage,
+ encryptionOptions: {
+ isEncryptionEnabled: config.documentsStorage.encryption.isEncryptionEnabled,
+ keyEncryptionKeys: config.documentsStorage.encryption.documentKeyEncryptionKeys,
+ },
+ });
const taskServices = overrides.taskServices ?? createInMemoryTaskServices();
const trackingServices = overrides.trackingServices ?? createDummyTrackingServices();
const eventServices = overrides.eventServices ?? createEventServices();
diff --git a/apps/papra-server/src/modules/app/server.types.ts b/apps/papra-server/src/modules/app/server.types.ts
index 16f8eb8b..4302659c 100644
--- a/apps/papra-server/src/modules/app/server.types.ts
+++ b/apps/papra-server/src/modules/app/server.types.ts
@@ -2,7 +2,7 @@ import type { Context as BaseContext, Hono } from 'hono';
import type { ApiKey } from '../api-keys/api-keys.types';
import type { Config } from '../config/config.types';
import type { DocumentSearchServices } from '../documents/document-search/document-search.types';
-import type { DocumentStorageService } from '../documents/storage/documents.storage.services';
+import type { StorageService } from '../storage/storage.services';
import type { EmailsServices } from '../emails/emails.services';
import type { KvStore } from '../kv-store/kv-store.types';
import type { SubscriptionsServices } from '../subscriptions/subscriptions.services';
@@ -38,7 +38,7 @@ export type GlobalDependencies = {
subscriptionsServices: SubscriptionsServices;
trackingServices: TrackingServices;
taskServices: TaskServices;
- documentsStorageService: DocumentStorageService;
+ documentsStorageService: StorageService;
documentSearchServices: DocumentSearchServices;
eventServices: EventServices;
shutdownServices: ShutdownServices;
diff --git a/apps/papra-server/src/modules/config/config.ts b/apps/papra-server/src/modules/config/config.ts
index 312c24f7..482b8d28 100644
--- a/apps/papra-server/src/modules/config/config.ts
+++ b/apps/papra-server/src/modules/config/config.ts
@@ -11,7 +11,10 @@ import { customPropertiesConfig } from '../custom-properties/custom-properties.c
import { documentShareLinksConfig } from '../document-share-links/document-share-links.config';
import { documentSearchConfig } from '../documents/document-search/document-search.config';
import { documentsConfig } from '../documents/documents.config';
-import { documentStorageConfig } from '../documents/storage/document-storage.config';
+import { documentEncryptionConfig } from '../documents/document-encryption.config';
+import { documentMaxUploadSizeConfig } from '../documents/document-storage.config';
+import { storagePatternConfig as documentStoragePatternConfig } from '../documents/storage-patterns/storage-pattern.config';
+import { createStorageConfig } from '../storage/storage.config';
import { emailsConfig } from '../emails/emails.config';
import { ingestionFolderConfig } from '../ingestion-folders/ingestion-folders.config';
import { intakeEmailsConfig } from '../intake-emails/intake-emails.config';
@@ -42,6 +45,16 @@ import { aiConfig } from '../ai/ai.config';
import { autoTaggingConfig } from '../auto-tagging/auto-tagging.config';
import { documentContentExtractionConfig } from '../documents/content-extraction/content-extraction.config';
+const documentsStorageConfig = {
+ ...createStorageConfig({
+ envPrefix: 'DOCUMENT_STORAGE',
+ defaultFilesystemRoot: './local-documents',
+ }),
+ maxUploadSize: documentMaxUploadSizeConfig,
+ encryption: documentEncryptionConfig,
+ pattern: documentStoragePatternConfig,
+};
+
export const configDefinition = {
env: {
doc: 'The application environment.',
@@ -159,7 +172,7 @@ export const configDefinition = {
database: databaseConfig,
documents: documentsConfig,
- documentsStorage: documentStorageConfig,
+ documentsStorage: documentsStorageConfig,
documentContentExtraction: documentContentExtractionConfig,
documentSearch: documentSearchConfig,
auth: authConfig,
diff --git a/apps/papra-server/src/modules/document-share-links/e2e/shared-document-access.e2e.test.ts b/apps/papra-server/src/modules/document-share-links/e2e/shared-document-access.e2e.test.ts
index fab15286..883993fe 100644
--- a/apps/papra-server/src/modules/document-share-links/e2e/shared-document-access.e2e.test.ts
+++ b/apps/papra-server/src/modules/document-share-links/e2e/shared-document-access.e2e.test.ts
@@ -3,7 +3,7 @@ import { createInMemoryDatabase } from '../../app/database/database.test-utils';
import { createServer } from '../../app/server';
import { createTestServerDependencies } from '../../app/server.test-utils';
import { overrideConfig } from '../../config/config.test-utils';
-import { createInMemoryDocumentStorageServices } from '../../documents/storage/documents.storage.services.test-utils';
+import { createInMemoryStorageService } from '../../storage/storage.test-utils';
import { ORGANIZATION_ROLES } from '../../organizations/organizations.constants';
import { createReadableStream } from '../../shared/streams/readable-stream';
@@ -45,7 +45,7 @@ async function createTestApp() {
],
});
- const documentsStorageService = createInMemoryDocumentStorageServices();
+ const documentsStorageService = createInMemoryStorageService();
await documentsStorageService.saveFile({
fileName: document.name,
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.config.ts b/apps/papra-server/src/modules/documents/document-encryption.config.ts
similarity index 82%
rename from apps/papra-server/src/modules/documents/storage/encryption/document-encryption.config.ts
rename to apps/papra-server/src/modules/documents/document-encryption.config.ts
index c09a67bf..7fcc73f6 100644
--- a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.config.ts
+++ b/apps/papra-server/src/modules/documents/document-encryption.config.ts
@@ -1,6 +1,6 @@
import type { ConfigDefinition } from 'figue';
-import { booleanishSchema } from '../../../config/config.schemas';
-import { coercedDocumentKeyEncryptionKeysListSchema } from './document-encryption.schemas';
+import { booleanishSchema } from '../config/config.schemas';
+import { coercedStorageKeyEncryptionKeysListSchema } from '../storage/encryption/storage-encryption.schemas';
export const documentEncryptionConfig = {
isEncryptionEnabled: {
@@ -20,7 +20,7 @@ Formats:
- Versions must be unique and can be any alphabetically sortable string
- The order of the version:key pair is not important
`.trim(),
- schema: coercedDocumentKeyEncryptionKeysListSchema,
+ schema: coercedStorageKeyEncryptionKeysListSchema,
default: undefined,
env: 'DOCUMENT_STORAGE_DOCUMENT_KEY_ENCRYPTION_KEYS',
},
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.usecases.test.ts b/apps/papra-server/src/modules/documents/document-encryption.usecases.test.ts
similarity index 80%
rename from apps/papra-server/src/modules/documents/storage/encryption/document-encryption.usecases.test.ts
rename to apps/papra-server/src/modules/documents/document-encryption.usecases.test.ts
index c480288e..20b6bff9 100644
--- a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.usecases.test.ts
+++ b/apps/papra-server/src/modules/documents/document-encryption.usecases.test.ts
@@ -1,14 +1,14 @@
-import type { TaskServices } from '../../../tasks/tasks.services';
+import type { TaskServices } from '../tasks/tasks.services';
import { Buffer } from 'node:buffer';
import { Readable } from 'node:stream';
import { describe, expect, test } from 'vitest';
-import { createInMemoryDatabase } from '../../../app/database/database.test-utils';
-import { createTestEventServices } from '../../../app/events/events.test-utils';
-import { overrideConfig } from '../../../config/config.test-utils';
-import { documentsTable } from '../../documents.table';
-import { createDocumentCreationUsecase } from '../../documents.usecases';
-import { createDocumentStorageServiceFromDriver } from '../documents.storage.services';
-import { inMemoryStorageDriverFactory } from '../drivers/memory/memory.storage-driver';
+import { createInMemoryDatabase } from '../app/database/database.test-utils';
+import { createTestEventServices } from '../app/events/events.test-utils';
+import { overrideConfig } from '../config/config.test-utils';
+import { documentsTable } from './documents.table';
+import { createDocumentCreationUsecase } from './documents.usecases';
+import { createStorageServiceFromDriver } from '../storage/storage.services';
+import { inMemoryStorageDriverFactory } from '../storage/drivers/memory/memory.storage-driver';
import { encryptAllUnencryptedDocuments } from './document-encryption.usecases';
export const noopTaskServices = {
@@ -28,11 +28,11 @@ describe('document-encryption usecases', () => {
db,
config: overrideConfig(),
taskServices: noopTaskServices,
- documentsStorageService: createDocumentStorageServiceFromDriver({
+ documentsStorageService: createStorageServiceFromDriver({
storageDriver,
- encryptionConfig: {
+ encryptionOptions: {
isEncryptionEnabled: false,
- documentKeyEncryptionKeys: [],
+ keyEncryptionKeys: [],
},
}),
eventServices: createTestEventServices(),
@@ -52,11 +52,11 @@ describe('document-encryption usecases', () => {
fileStream: Readable.from(Buffer.from('Hello, world! - 2')),
});
- const documentStorageServiceWithEncryption = createDocumentStorageServiceFromDriver({
+ const documentStorageServiceWithEncryption = createStorageServiceFromDriver({
storageDriver,
- encryptionConfig: {
+ encryptionOptions: {
isEncryptionEnabled: true,
- documentKeyEncryptionKeys: [
+ keyEncryptionKeys: [
{
key: Buffer.from('64/4Ep2f/3ylsg9wIUeeZ7oIFPCyM6IaPjoLrhQCBSo=', 'base64'),
version: '1',
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.usecases.ts b/apps/papra-server/src/modules/documents/document-encryption.usecases.ts
similarity index 84%
rename from apps/papra-server/src/modules/documents/storage/encryption/document-encryption.usecases.ts
rename to apps/papra-server/src/modules/documents/document-encryption.usecases.ts
index 011394ed..a389fe05 100644
--- a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.usecases.ts
+++ b/apps/papra-server/src/modules/documents/document-encryption.usecases.ts
@@ -1,9 +1,9 @@
import type { Logger } from '@crowlog/logger';
-import type { Database } from '../../../app/database/database.types';
-import type { DocumentStorageService } from '../documents.storage.services';
+import type { Database } from '../app/database/database.types';
+import type { StorageService } from '../storage/drivers/drivers.models';
import { eq, isNull } from 'drizzle-orm';
-import { createLogger } from '../../../shared/logger/logger';
-import { documentsTable } from '../../documents.table';
+import { createLogger } from '../shared/logger/logger';
+import { documentsTable } from './documents.table';
export async function encryptAllUnencryptedDocuments({
db,
@@ -13,7 +13,7 @@ export async function encryptAllUnencryptedDocuments({
}: {
db: Database;
logger?: Logger;
- documentStorageService: DocumentStorageService;
+ documentStorageService: StorageService;
deleteUnencryptedAfterEncryption?: boolean;
}) {
const documents = await db
diff --git a/apps/papra-server/src/modules/documents/document-storage.config.ts b/apps/papra-server/src/modules/documents/document-storage.config.ts
new file mode 100644
index 00000000..c61e4c4f
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/document-storage.config.ts
@@ -0,0 +1,9 @@
+import { coercedPositiveIntegerSchema } from '../shared/schemas/number.schemas';
+import { IN_BYTES } from '../shared/units';
+
+export const documentMaxUploadSizeConfig = {
+ doc: 'The maximum size in bytes for an uploaded file. Set to 0 to disable the limit and allow uploading documents of any size.',
+ schema: coercedPositiveIntegerSchema,
+ default: 25 * IN_BYTES.MEGABYTE,
+ env: 'DOCUMENT_STORAGE_MAX_UPLOAD_SIZE',
+} as const;
diff --git a/apps/papra-server/src/modules/documents/document-storage.usecases.test.ts b/apps/papra-server/src/modules/documents/document-storage.usecases.test.ts
new file mode 100644
index 00000000..e4e081ce
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/document-storage.usecases.test.ts
@@ -0,0 +1,78 @@
+import type { StoragePatternConfig } from './storage-patterns/storage-pattern.types';
+import { createNoopLogger } from '@crowlog/logger';
+import { describe, expect, test, vi } from 'vitest';
+import { createDocumentStorageKey } from './document-storage.usecases';
+
+const baseStoragePatternConfig = {
+ useLegacyStorageKeyDefinitionSystem: false,
+ storageKeyPattern: '{{organization.id}}/{{document.name}}',
+ enableRandomSuffixFallback: true,
+ maxIncrementalSuffixAttempts: 9,
+} satisfies StoragePatternConfig;
+
+const documentContext = {
+ documentId: 'doc_1',
+ documentName: 'invoice.pdf',
+ organizationId: 'org_1',
+ now: new Date('2026-01-01T00:00:00.000Z'),
+};
+
+describe('document-storage usecases', () => {
+ describe('createDocumentStorageKey', () => {
+ test('uses the legacy document key without checking for collisions', async () => {
+ const fileExists = vi.fn(async () => false);
+
+ await expect(
+ createDocumentStorageKey({
+ ...documentContext,
+ storagePatternConfig: {
+ ...baseStoragePatternConfig,
+ useLegacyStorageKeyDefinitionSystem: true,
+ },
+ documentsStorageService: { fileExists },
+ logger: createNoopLogger(),
+ }),
+ ).resolves.toEqual({ storageKey: 'org_1/originals/doc_1.pdf' });
+ expect(fileExists).not.toHaveBeenCalled();
+ });
+
+ test('interpolates the document pattern and resolves collisions with incremental suffixes', async () => {
+ const fileExists = vi.fn(
+ async ({ storageKey }: { storageKey: string }) => storageKey === 'org_1/invoice.pdf',
+ );
+
+ await expect(
+ createDocumentStorageKey({
+ ...documentContext,
+ storagePatternConfig: baseStoragePatternConfig,
+ documentsStorageService: { fileExists },
+ logger: createNoopLogger(),
+ }),
+ ).resolves.toEqual({ storageKey: 'org_1/invoice_1.pdf' });
+ expect(fileExists).toHaveBeenNthCalledWith(1, { storageKey: 'org_1/invoice.pdf' });
+ expect(fileExists).toHaveBeenNthCalledWith(2, { storageKey: 'org_1/invoice_1.pdf' });
+ });
+
+ test('uses the random suffix fallback after incremental attempts are exhausted', async () => {
+ const fileExists = vi
+ .fn<({ storageKey }: { storageKey: string }) => Promise<boolean>>()
+ .mockResolvedValueOnce(true)
+ .mockResolvedValueOnce(false);
+
+ const result = await createDocumentStorageKey({
+ ...documentContext,
+ storagePatternConfig: {
+ ...baseStoragePatternConfig,
+ maxIncrementalSuffixAttempts: 0,
+ },
+ documentsStorageService: { fileExists },
+ logger: createNoopLogger(),
+ });
+
+ expect(result.storageKey).toMatch(/^org_1\/invoice_[A-Za-z0-9]{8}\.pdf$/);
+ expect(fileExists).toHaveBeenCalledTimes(2);
+ expect(fileExists).toHaveBeenNthCalledWith(1, { storageKey: 'org_1/invoice.pdf' });
+ expect(fileExists).toHaveBeenNthCalledWith(2, { storageKey: result.storageKey });
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/documents/document-storage.usecases.ts b/apps/papra-server/src/modules/documents/document-storage.usecases.ts
new file mode 100644
index 00000000..f21bf0a1
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/document-storage.usecases.ts
@@ -0,0 +1,57 @@
+import type { Logger } from '../shared/logger/logger';
+import type { StorageService } from '../storage/drivers/drivers.models';
+import type { StoragePatternConfig } from './storage-patterns/storage-pattern.types';
+import { buildOriginalDocumentKey } from './documents.models';
+import { buildStorageKey } from './storage-patterns/storage-pattern.usecases';
+import { ensureStorageKeyIsAvailable } from '../storage/storage.usecases';
+
+export async function createDocumentStorageKey({
+ storagePatternConfig,
+ documentId,
+ documentName,
+ organizationId,
+ documentsStorageService,
+ logger,
+ now = new Date(),
+}: {
+ storagePatternConfig: StoragePatternConfig;
+ documentId: string;
+ documentName: string;
+ organizationId: string;
+ documentsStorageService: Pick<StorageService, 'fileExists'>;
+ logger?: Logger;
+ now?: Date;
+}) {
+ const {
+ useLegacyStorageKeyDefinitionSystem,
+ storageKeyPattern,
+ enableRandomSuffixFallback,
+ maxIncrementalSuffixAttempts,
+ } = storagePatternConfig;
+
+ if (useLegacyStorageKeyDefinitionSystem) {
+ const { originalDocumentStorageKey } = buildOriginalDocumentKey({
+ documentId,
+ fileName: documentName,
+ organizationId,
+ });
+
+ return { storageKey: originalDocumentStorageKey };
+ }
+
+ const { storageKey: initialStorageKey } = buildStorageKey({
+ storageKeyPattern,
+ documentId,
+ documentName,
+ organizationId,
+ now,
+ });
+
+ return ensureStorageKeyIsAvailable({
+ initialStorageKey,
+ maxIncrementalSuffixAttempts,
+ enableRandomSuffixFallback,
+ storageService: documentsStorageService,
+ logger,
+ });
+}
diff --git a/apps/papra-server/src/modules/documents/documents.usecases.test.ts b/apps/papra-server/src/modules/documents/documents.usecases.test.ts
index cd1d82e7..49733eef 100644
--- a/apps/papra-server/src/modules/documents/documents.usecases.test.ts
+++ b/apps/papra-server/src/modules/documents/documents.usecases.test.ts
@@ -1,5 +1,5 @@
import type { PlansRepository } from '../plans/plans.repository';
-import type { DocumentStorageService } from './storage/documents.storage.services';
+import type { StorageService } from '../storage/storage.services';
import { describe, expect, test } from 'vitest';
import { createInMemoryDatabase } from '../app/database/database.test-utils';
import { createTestEventServices } from '../app/events/events.test-utils';
@@ -30,8 +30,8 @@ import {
trashDocument,
updateDocument,
} from './documents.usecases';
-import { createDocumentStorageService } from './storage/documents.storage.services';
-import { createInMemoryDocumentStorageServices } from './storage/documents.storage.services.test-utils';
+import { createStorageService } from '../storage/storage.services';
+import { createInMemoryStorageService } from '../storage/storage.test-utils';
describe('documents usecases', () => {
describe('createDocument', () => {
@@ -49,8 +49,12 @@ describe('documents usecases', () => {
organizationPlans: { isFreePlanUnlimited: true },
documentsStorage: { driver: 'in-memory' },
});
- const documentsStorageService = createDocumentStorageService({
- documentStorageConfig: config.documentsStorage,
+ const documentsStorageService = createStorageService({
+ storageConfig: config.documentsStorage,
+ encryptionOptions: {
+ isEncryptionEnabled: config.documentsStorage.encryption.isEncryptionEnabled,
+ keyEncryptionKeys: config.documentsStorage.encryption.documentKeyEncryptionKeys,
+ },
});
const createDocument = createDocumentCreationUsecase({
@@ -116,8 +120,12 @@ describe('documents usecases', () => {
documentsStorage: { driver: 'in-memory' },
});
- const documentsStorageService = createDocumentStorageService({
- documentStorageConfig: config.documentsStorage,
+ const documentsStorageService = createStorageService({
+ storageConfig: config.documentsStorage,
+ encryptionOptions: {
+ isEncryptionEnabled: config.documentsStorage.encryption.isEncryptionEnabled,
+ keyEncryptionKeys: config.documentsStorage.encryption.documentKeyEncryptionKeys,
+ },
});
let documentIdIndex = 1;
@@ -260,7 +268,7 @@ describe('documents usecases', () => {
db,
config,
taskServices,
- documentsStorageService: createInMemoryDocumentStorageServices(),
+ documentsStorageService: createInMemoryStorageService(),
eventServices: createTestEventServices(),
});
@@ -313,7 +321,7 @@ describe('documents usecases', () => {
documentsStorage: { driver: 'in-memory' },
});
const documentsRepository = createDocumentsRepository({ db });
- const inMemoryDocumentsStorageService = createInMemoryDocumentStorageServices();
+ const inMemoryDocumentsStorageService = createInMemoryStorageService();
const createDocument = createDocumentCreationUsecase({
db,
@@ -392,8 +400,12 @@ describe('documents usecases', () => {
});
const documentsRepository = createDocumentsRepository({ db });
- const documentsStorageService = createDocumentStorageService({
- documentStorageConfig: config.documentsStorage,
+ const documentsStorageService = createStorageService({
+ storageConfig: config.documentsStorage,
+ encryptionOptions: {
+ isEncryptionEnabled: config.documentsStorage.encryption.isEncryptionEnabled,
+ keyEncryptionKeys: config.documentsStorage.encryption.documentKeyEncryptionKeys,
+ },
});
const createDocument = createDocumentCreationUsecase({
@@ -443,7 +455,7 @@ describe('documents usecases', () => {
],
});
- const inMemoryDocumentsStorageService = createInMemoryDocumentStorageServices();
+ const inMemoryDocumentsStorageService = createInMemoryStorageService();
const plansRepository = {
getOrganizationPlanById: async (_args) => ({
@@ -498,7 +510,7 @@ describe('documents usecases', () => {
const { promise, resolve } = Promise.withResolvers();
- const inMemoryDocumentsStorageService = createInMemoryDocumentStorageServices();
+ const inMemoryDocumentsStorageService = createInMemoryStorageService();
const documentsStorageService = {
...inMemoryDocumentsStorageService,
saveFile: async (args) => {
@@ -511,7 +523,7 @@ describe('documents usecases', () => {
return inMemoryDocumentsStorageService.saveFile(args);
},
- } as DocumentStorageService;
+ } as StorageService;
const plansRepository = {
getOrganizationPlanById: async (_args) => ({
@@ -574,7 +586,7 @@ describe('documents usecases', () => {
],
});
- const inMemoryDocumentsStorageService = createInMemoryDocumentStorageServices();
+ const inMemoryDocumentsStorageService = createInMemoryStorageService();
const plansRepository = {
getOrganizationPlanById: async (_args) => ({
@@ -634,7 +646,7 @@ describe('documents usecases', () => {
db,
config,
generateDocumentId: () => `doc_${documentIdIndex++}`,
- documentsStorageService: createInMemoryDocumentStorageServices(),
+ documentsStorageService: createInMemoryStorageService(),
taskServices,
eventServices,
});
@@ -681,8 +693,12 @@ describe('documents usecases', () => {
});
const documentsRepository = createDocumentsRepository({ db });
- const documentsStorageService = createDocumentStorageService({
- documentStorageConfig: config.documentsStorage,
+ const documentsStorageService = createStorageService({
+ storageConfig: config.documentsStorage,
+ encryptionOptions: {
+ isEncryptionEnabled: config.documentsStorage.encryption.isEncryptionEnabled,
+ keyEncryptionKeys: config.documentsStorage.encryption.documentKeyEncryptionKeys,
+ },
});
const taggingRulesRepository = createTaggingRulesRepository({ db });
const tagsRepository = createTagsRepository({ db });
@@ -742,8 +758,12 @@ describe('documents usecases', () => {
});
const documentsRepository = createDocumentsRepository({ db });
- const documentsStorageService = createDocumentStorageService({
- documentStorageConfig: config.documentsStorage,
+ const documentsStorageService = createStorageService({
+ storageConfig: config.documentsStorage,
+ encryptionOptions: {
+ isEncryptionEnabled: config.documentsStorage.encryption.isEncryptionEnabled,
+ keyEncryptionKeys: config.documentsStorage.encryption.documentKeyEncryptionKeys,
+ },
});
const taggingRulesRepository = createTaggingRulesRepository({ db });
const tagsRepository = createTagsRepository({ db });
diff --git a/apps/papra-server/src/modules/documents/documents.usecases.ts b/apps/papra-server/src/modules/documents/documents.usecases.ts
index 08b636dc..3e57d258 100644
--- a/apps/papra-server/src/modules/documents/documents.usecases.ts
+++ b/apps/papra-server/src/modules/documents/documents.usecases.ts
@@ -14,9 +14,9 @@ import type { TagsRepository } from '../tags/tags.repository';
import type { TaskServices } from '../tasks/tasks.services';
import type { DocumentsRepository } from './documents.repository';
import type { Document } from './documents.types';
-import type { DocumentStorageService } from './storage/documents.storage.services';
-import type { EncryptionContext } from './storage/drivers/drivers.models';
-import type { StoragePatternConfig } from './storage/patterns/storage-pattern.types';
+import type { StorageService } from '../storage/storage.services';
+import type { EncryptionContext } from '../storage/drivers/drivers.models';
+import type { StoragePatternConfig } from './storage-patterns/storage-pattern.types';
import { PassThrough } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { safely } from '@corentinth/chisels';
@@ -48,7 +48,7 @@ import {
generateDocumentId as generateDocumentIdImpl,
} from './documents.models';
import { createDocumentsRepository } from './documents.repository';
-import { createStorageKey } from './storage/document-storage.usecases';
+import { createDocumentStorageKey } from './document-storage.usecases';
import type { ExtractDocumentTextUsecase } from './content-extraction/content-extraction.usecases';
type DocumentStorageContext = {
@@ -86,7 +86,7 @@ export async function createDocument({
isContentExtractionEnabled?: boolean;
storagePatternConfig: StoragePatternConfig;
documentsRepository: DocumentsRepository;
- documentsStorageService: DocumentStorageService;
+ documentsStorageService: StorageService;
generateDocumentId?: () => string;
plansRepository: PlansRepository;
subscriptionsRepository: SubscriptionsRepository;
@@ -108,7 +108,7 @@ export async function createDocument({
});
const documentId = generateDocumentId();
- const { storageKey } = await createStorageKey({
+ const { storageKey } = await createDocumentStorageKey({
documentId,
documentName: fileName,
organizationId,
@@ -216,7 +216,7 @@ export function createDocumentCreationUsecase({
}: {
db: Database;
taskServices: TaskServices;
- documentsStorageService: DocumentStorageService;
+ documentsStorageService: StorageService;
eventServices: EventServices;
config: Config;
} & Partial<DocumentUsecaseDependencies>) {
@@ -272,7 +272,7 @@ async function handleExistingDocument({
tagsRepository: TagsRepository;
taggingRulesRepository: TaggingRulesRepository;
eventServices: EventServices;
- documentsStorageService: DocumentStorageService;
+ documentsStorageService: StorageService;
newDocumentStorageKey: string;
logger: Logger;
}) {
@@ -336,7 +336,7 @@ async function createNewDocument({
organizationId: string;
documentId: string;
documentsRepository: DocumentsRepository;
- documentsStorageService: DocumentStorageService;
+ documentsStorageService: StorageService;
plansRepository: PlansRepository;
subscriptionsRepository: SubscriptionsRepository;
planEntitlementsRepository: PlanEntitlementsRepository;
@@ -449,7 +449,7 @@ export async function hardDeleteDocument({
}: {
document: Pick<Document, 'id' | 'originalStorageKey' | 'organizationId'>;
documentsRepository: DocumentsRepository;
- documentsStorageService: DocumentStorageService;
+ documentsStorageService: StorageService;
eventServices: EventServices;
}) {
await Promise.all([
@@ -472,7 +472,7 @@ export async function deleteExpiredDocuments({
logger = createLogger({ namespace: 'documents:deleteExpiredDocuments' }),
}: {
documentsRepository: DocumentsRepository;
- documentsStorageService: DocumentStorageService;
+ documentsStorageService: StorageService;
eventServices: EventServices;
config: Config;
now?: Date;
@@ -519,7 +519,7 @@ export async function deleteTrashDocument({
documentId: string;
organizationId: string;
documentsRepository: DocumentsRepository;
- documentsStorageService: DocumentStorageService;
+ documentsStorageService: StorageService;
eventServices: EventServices;
}) {
const { document } = await documentsRepository.getDocumentById({ documentId, organizationId });
@@ -548,7 +548,7 @@ export async function deleteAllTrashDocuments({
}: {
organizationId: string;
documentsRepository: DocumentsRepository;
- documentsStorageService: DocumentStorageService;
+ documentsStorageService: StorageService;
eventServices: EventServices;
}) {
const { documents } = await documentsRepository.getAllOrganizationTrashDocuments({
@@ -586,7 +586,7 @@ export async function extractAndSaveDocumentFileContent({
documentId: string;
organizationId: string;
documentsRepository: DocumentsRepository;
- documentsStorageService: DocumentStorageService;
+ documentsStorageService: StorageService;
taggingRulesRepository: TaggingRulesRepository;
tagsRepository: TagsRepository;
eventServices: EventServices;
diff --git a/apps/papra-server/src/modules/documents/e2e/upload-documents.e2e.test.ts b/apps/papra-server/src/modules/documents/e2e/upload-documents.e2e.test.ts
index dd8e164b..24132cb0 100644
--- a/apps/papra-server/src/modules/documents/e2e/upload-documents.e2e.test.ts
+++ b/apps/papra-server/src/modules/documents/e2e/upload-documents.e2e.test.ts
@@ -7,7 +7,7 @@ import { overrideConfig } from '../../config/config.test-utils';
import { ORGANIZATION_ROLES } from '../../organizations/organizations.constants';
import { PLAN_IDS } from '../../plans/plans.constants';
import { documentsTable } from '../documents.table';
-import { createInMemoryDocumentStorageServices } from '../storage/documents.storage.services.test-utils';
+import { createInMemoryStorageService } from '../../storage/storage.test-utils';
describe('documents e2e', () => {
describe('document upload', () => {
@@ -102,7 +102,7 @@ describe('documents e2e', () => {
],
});
- const documentsStorageService = createInMemoryDocumentStorageServices();
+ const documentsStorageService = createInMemoryStorageService();
const { app } = createServer(
createTestServerDependencies({
diff --git a/apps/papra-server/src/modules/documents/events/activity-log.document-created.test.ts b/apps/papra-server/src/modules/documents/events/activity-log.document-created.test.ts
index b7b3c5cf..3b721ff7 100644
--- a/apps/papra-server/src/modules/documents/events/activity-log.document-created.test.ts
+++ b/apps/papra-server/src/modules/documents/events/activity-log.document-created.test.ts
@@ -10,7 +10,7 @@ import { createReadableStream } from '../../shared/streams/readable-stream';
import { createInMemoryTaskServices } from '../../tasks/tasks.test-utils';
import { documentActivityLogTable } from '../document-activity/document-activity.table';
import { createDocumentCreationUsecase } from '../documents.usecases';
-import { createInMemoryDocumentStorageServices } from '../storage/documents.storage.services.test-utils';
+import { createInMemoryStorageService } from '../../storage/storage.test-utils';
import { registerInsertActivityLogOnDocumentCreatedHandler } from './activity-log.document-created';
describe('activity-log document-created', () => {
@@ -36,7 +36,7 @@ describe('activity-log document-created', () => {
db,
config,
generateDocumentId: createDeterministicIdGenerator({ prefix: 'doc' }),
- documentsStorageService: createInMemoryDocumentStorageServices(),
+ documentsStorageService: createInMemoryStorageService(),
taskServices,
eventServices,
});
diff --git a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.config.ts b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.config.ts
similarity index 88%
rename from apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.config.ts
rename to apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.config.ts
index b195c29d..e06085f8 100644
--- a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.config.ts
+++ b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.config.ts
@@ -1,6 +1,6 @@
-import type { AppConfigDefinition } from '../../../config/config.types';
-import { booleanishSchema } from '../../../config/config.schemas';
-import { coercedPositiveIntegerSchema } from '../../../shared/schemas/number.schemas';
+import type { AppConfigDefinition } from '../../config/config.types';
+import { booleanishSchema } from '../../config/config.schemas';
+import { coercedPositiveIntegerSchema } from '../../shared/schemas/number.schemas';
import { storagePatternSchema } from './storage-pattern.schemas';
export const storagePatternConfig = {
diff --git a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.constants.test.ts b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.constants.test.ts
similarity index 80%
rename from apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.constants.test.ts
rename to apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.constants.test.ts
index 0fa7f72e..f4797d44 100644
--- a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.constants.test.ts
+++ b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.constants.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'vitest';
-import { ORGANIZATION_ID_REGEX } from '../../../organizations/organizations.constants';
-import { DOCUMENT_ID_REGEX } from '../../documents.constants';
+import { ORGANIZATION_ID_REGEX } from '../../organizations/organizations.constants';
+import { DOCUMENT_ID_REGEX } from '../documents.constants';
import { DUMMY_DOCUMENT_ID, DUMMY_ORGANIZATION_ID } from './storage-pattern.constants';
describe('storage-pattern constants', () => {
diff --git a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.constants.ts b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.constants.ts
similarity index 100%
rename from apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.constants.ts
rename to apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.constants.ts
diff --git a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.definitions.ts b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.definitions.ts
similarity index 90%
rename from apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.definitions.ts
rename to apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.definitions.ts
index 26b2f4e8..9a03302d 100644
--- a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.definitions.ts
+++ b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.definitions.ts
@@ -2,9 +2,9 @@ import type {
StoragePatternExpressionTransformer,
StoragePatternInterpolationContext,
} from './storage-pattern.types';
-import { formatDate, isValidDate } from '../../../shared/date';
-import { generateRandomString } from '../../../shared/random/random.services';
-import { ensureSafeFileName } from '../../documents.models';
+import { formatDate, isValidDate } from '../../shared/date';
+import { generateRandomString } from '../../shared/random/random.services';
+import { ensureSafeFileName } from '../documents.models';
export const expressionsDefinitions: Record<
string,
diff --git a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.models.test.ts b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.models.test.ts
similarity index 100%
rename from apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.models.test.ts
rename to apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.models.test.ts
diff --git a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.models.ts b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.models.ts
similarity index 94%
rename from apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.models.ts
rename to apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.models.ts
index 236f04b1..835704a2 100644
--- a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.models.ts
+++ b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.models.ts
@@ -1,4 +1,4 @@
-import { isNilOrEmptyString } from '../../../shared/utils';
+import { isNilOrEmptyString } from '../../shared/utils';
export function tokenizeStringArguments({
argumentsString,
diff --git a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.schemas.test.ts b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.schemas.test.ts
similarity index 100%
rename from apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.schemas.test.ts
rename to apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.schemas.test.ts
diff --git a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.schemas.ts b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.schemas.ts
similarity index 100%
rename from apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.schemas.ts
rename to apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.schemas.ts
diff --git a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.types.ts b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.types.ts
similarity index 84%
rename from apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.types.ts
rename to apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.types.ts
index bdf4556a..6ac749b1 100644
--- a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.types.ts
+++ b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.types.ts
@@ -1,4 +1,4 @@
-import type { Config } from '../../../config/config.types';
+import type { Config } from '../../config/config.types';
export type StoragePatternInterpolationContext = {
documentId: string;
diff --git a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.usecases.test.ts b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.usecases.test.ts
similarity index 100%
rename from apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.usecases.test.ts
rename to apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.usecases.test.ts
diff --git a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.usecases.ts b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.usecases.ts
similarity index 97%
rename from apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.usecases.ts
rename to apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.usecases.ts
index 1d7cea8d..75b13556 100644
--- a/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.usecases.ts
+++ b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.usecases.ts
@@ -1,6 +1,6 @@
import type { StoragePatternInterpolationContext } from './storage-pattern.types';
import { castError } from '@corentinth/chisels';
-import { isNil, isNilOrEmptyString } from '../../../shared/utils';
+import { isNil, isNilOrEmptyString } from '../../shared/utils';
import { DUMMY_DOCUMENT_ID, DUMMY_ORGANIZATION_ID } from './storage-pattern.constants';
import { expressionsDefinitions, expressionTransformers } from './storage-pattern.definitions';
import { tokenizeStringArguments } from './storage-pattern.models';
diff --git a/apps/papra-server/src/modules/documents/storage/document-storage.config.ts b/apps/papra-server/src/modules/documents/storage/document-storage.config.ts
deleted file mode 100644
index 3a0084b1..00000000
--- a/apps/papra-server/src/modules/documents/storage/document-storage.config.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-import type { ConfigDefinition } from 'figue';
-import * as v from 'valibot';
-import { booleanishSchema } from '../../config/config.schemas';
-import { coercedPositiveIntegerSchema } from '../../shared/schemas/number.schemas';
-import { IN_BYTES } from '../../shared/units';
-import { AZ_BLOB_STORAGE_DRIVER_NAME } from './drivers/az-blob/az-blob.storage-driver';
-import { FS_STORAGE_DRIVER_NAME } from './drivers/fs/fs.storage-driver';
-import { IN_MEMORY_STORAGE_DRIVER_NAME } from './drivers/memory/memory.storage-driver';
-import { S3_STORAGE_DRIVER_NAME } from './drivers/s3/s3.storage-driver';
-import { documentEncryptionConfig } from './encryption/document-encryption.config';
-import { storagePatternConfig } from './patterns/storage-pattern.config';
-
-const driverNames = [
- FS_STORAGE_DRIVER_NAME,
- S3_STORAGE_DRIVER_NAME,
- IN_MEMORY_STORAGE_DRIVER_NAME,
- AZ_BLOB_STORAGE_DRIVER_NAME,
-] as const;
-
-export const documentStorageConfig = {
- maxUploadSize: {
- doc: 'The maximum size in bytes for an uploaded file. Set to 0 to disable the limit and allow uploading documents of any size.',
- schema: coercedPositiveIntegerSchema,
- default: 25 * IN_BYTES.MEGABYTE,
- env: 'DOCUMENT_STORAGE_MAX_UPLOAD_SIZE',
- },
- driver: {
- doc: `The driver to use for document storage, values can be one of: ${driverNames.map((x) => `\`${x}\``).join(', ')}`,
- schema: v.picklist(driverNames),
- default: FS_STORAGE_DRIVER_NAME,
- env: 'DOCUMENT_STORAGE_DRIVER',
- },
- drivers: {
- filesystem: {
- root: {
- doc: 'The root directory to store documents in (default as "./app-data/documents" when using docker)',
- schema: v.string(),
- default: './local-documents',
- env: 'DOCUMENT_STORAGE_FILESYSTEM_ROOT',
- },
- },
- s3: {
- accessKeyId: {
- doc: 'The AWS access key ID for S3',
- schema: v.string(),
- default: '',
- env: 'DOCUMENT_STORAGE_S3_ACCESS_KEY_ID',
- },
- secretAccessKey: {
- doc: 'The AWS secret access key for S3',
- schema: v.string(),
- default: '',
- env: 'DOCUMENT_STORAGE_S3_SECRET_ACCESS_KEY',
- },
- bucketName: {
- doc: 'The S3 bucket name',
- schema: v.string(),
- default: '',
- env: 'DOCUMENT_STORAGE_S3_BUCKET_NAME',
- },
- region: {
- doc: 'The AWS region for S3',
- schema: v.string(),
- default: 'auto',
- env: 'DOCUMENT_STORAGE_S3_REGION',
- },
- endpoint: {
- doc: 'The S3 endpoint',
- schema: v.optional(v.string()),
- default: undefined,
- env: 'DOCUMENT_STORAGE_S3_ENDPOINT',
- },
- forcePathStyle: {
- doc: 'Whether to force path style URLs for S3',
- schema: booleanishSchema,
- default: false,
- env: 'DOCUMENT_STORAGE_S3_FORCE_PATH_STYLE',
- },
- },
- azureBlob: {
- connectionString: {
- doc: 'The Azure Blob Storage connection string, if provided, the other account name, account key and container name will be ignored',
- schema: v.optional(v.string()),
- default: undefined,
- env: 'DOCUMENT_STORAGE_AZURE_BLOB_CONNECTION_STRING',
- },
- accountName: {
- doc: 'The Azure Blob Storage account name',
- schema: v.string(),
- default: '',
- env: 'DOCUMENT_STORAGE_AZURE_BLOB_ACCOUNT_NAME',
- },
- accountKey: {
- doc: 'The Azure Blob Storage account key',
- schema: v.string(),
- default: '',
- env: 'DOCUMENT_STORAGE_AZURE_BLOB_ACCOUNT_KEY',
- },
- containerName: {
- doc: 'The Azure Blob Storage container name',
- schema: v.string(),
- default: '',
- env: 'DOCUMENT_STORAGE_AZURE_BLOB_CONTAINER_NAME',
- },
- },
- },
- encryption: documentEncryptionConfig,
- pattern: storagePatternConfig,
-} as const satisfies ConfigDefinition;
diff --git a/apps/papra-server/src/modules/documents/storage/document-storage.models.test.ts b/apps/papra-server/src/modules/documents/storage/document-storage.models.test.ts
deleted file mode 100644
index e2422191..00000000
--- a/apps/papra-server/src/modules/documents/storage/document-storage.models.test.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { describe, expect, test } from 'vitest';
-import { addSuffixToFileName } from './document-storage.models';
-
-describe('document-storage models', () => {
- describe('addSuffixToFileName', () => {
- test('given a storage key and a suffix, add the suffix before the file extension', () => {
- expect(addSuffixToFileName({ storageKey: 'file.txt', suffix: '1' })).to.eql('file_1.txt');
- expect(addSuffixToFileName({ storageKey: 'archive.tar.gz', suffix: 'backup' })).to.eql(
- 'archive.tar_backup.gz',
- );
- });
-
- test('if there is no file extension, add the suffix at the end of the storage key', () => {
- expect(addSuffixToFileName({ storageKey: 'file', suffix: '2' })).to.eql('file_2');
- expect(addSuffixToFileName({ storageKey: 'archive', suffix: 'backup' })).to.eql(
- 'archive_backup',
- );
- });
-
- test('the suffix can be either a string or a number', () => {
- expect(addSuffixToFileName({ storageKey: 'file.txt', suffix: 2 })).to.eql('file_2.txt');
- expect(addSuffixToFileName({ storageKey: 'file.txt', suffix: '2' })).to.eql('file_2.txt');
- });
-
- test('filenames starting with a dot (e.g. .env) are supported', () => {
- expect(addSuffixToFileName({ storageKey: '.env', suffix: 'backup' })).to.eql('.env_backup');
- expect(addSuffixToFileName({ storageKey: '.env.local', suffix: 'backup' })).to.eql(
- '.env_backup.local',
- );
- });
-
- test('the storage key path can contain directories, the suffix should be added to the file name only', () => {
- expect(addSuffixToFileName({ storageKey: 'path/to/file.txt', suffix: '1' })).to.eql(
- 'path/to/file_1.txt',
- );
- expect(
- addSuffixToFileName({ storageKey: 'path/dir.with.dots/file.txt', suffix: '2' }),
- ).to.eql('path/dir.with.dots/file_2.txt');
- });
-
- test('if the storage key ends with a dot, the suffix should be added before the dot', () => {
- expect(addSuffixToFileName({ storageKey: 'file.', suffix: '1' })).to.eql('file_1.');
- expect(addSuffixToFileName({ storageKey: 'archive.', suffix: 'backup' })).to.eql(
- 'archive_backup.',
- );
- });
- });
-});
diff --git a/apps/papra-server/src/modules/documents/storage/document-storage.usecases.ts b/apps/papra-server/src/modules/documents/storage/document-storage.usecases.ts
deleted file mode 100644
index db26efc1..00000000
--- a/apps/papra-server/src/modules/documents/storage/document-storage.usecases.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import type { Logger } from '../../shared/logger/logger';
-import type { DocumentStorageService } from './documents.storage.services';
-import type { StoragePatternConfig } from './patterns/storage-pattern.types';
-import { createLogger } from '../../shared/logger/logger';
-import { generateRandomString } from '../../shared/random/random.services';
-import { buildOriginalDocumentKey } from '../documents.models';
-import { createUnableToFindAvailableStorageKeyError } from './document-storage.errors';
-import { addSuffixToFileName } from './document-storage.models';
-import { buildStorageKey } from './patterns/storage-pattern.usecases';
-
-export async function ensureStorageKeyIsAvailable({
- initialStorageKey,
- maxIncrementalSuffixAttempts,
- enableRandomSuffixFallback,
-
- generateRandomSuffix = () => generateRandomString({ length: 8 }),
- documentsStorageService,
- logger = createLogger({ namespace: 'ensureStorageKeyIsAvailable' }),
-}: {
- initialStorageKey: string;
- maxIncrementalSuffixAttempts: number;
- enableRandomSuffixFallback: boolean;
-
- generateRandomSuffix?: () => string;
- documentsStorageService: Pick<DocumentStorageService, 'fileExists'>;
- logger?: Logger;
-}): Promise<{ storageKey: string }> {
- let proposedStorageKey = initialStorageKey;
- let counter = 0;
-
- const logMeta = { initialStorageKey, maxIncrementalSuffixAttempts, enableRandomSuffixFallback };
-
- while (counter <= maxIncrementalSuffixAttempts) {
- const exists = await documentsStorageService.fileExists({ storageKey: proposedStorageKey });
-
- if (!exists) {
- return { storageKey: proposedStorageKey };
- }
-
- logger.warn({ ...logMeta, proposedStorageKey, counter }, 'Storage key is already taken');
-
- proposedStorageKey = addSuffixToFileName({
- storageKey: initialStorageKey,
- suffix: counter + 1,
- }); // Suffixes start at 1
- counter++;
- }
-
- if (enableRandomSuffixFallback) {
- const randomSuffix = generateRandomSuffix();
- proposedStorageKey = addSuffixToFileName({
- storageKey: initialStorageKey,
- suffix: randomSuffix,
- });
-
- logger.warn({ ...logMeta, proposedStorageKey, randomSuffix }, 'Falling back to random suffix');
-
- const exists = await documentsStorageService.fileExists({ storageKey: proposedStorageKey });
-
- if (!exists) {
- return { storageKey: proposedStorageKey };
- }
- }
-
- logger.error({ ...logMeta }, 'Unable to find available storage key after all attempts');
-
- throw createUnableToFindAvailableStorageKeyError();
-}
-
-export async function createStorageKey({
- storagePatternConfig,
- documentId,
- documentName,
- organizationId,
- documentsStorageService,
- logger,
- now = new Date(),
-}: {
- storagePatternConfig: StoragePatternConfig;
- documentId: string;
- documentName: string;
- organizationId: string;
- documentsStorageService: Pick<DocumentStorageService, 'fileExists'>;
- logger?: Logger;
- now?: Date;
-}) {
- const {
- useLegacyStorageKeyDefinitionSystem,
- storageKeyPattern,
- enableRandomSuffixFallback,
- maxIncrementalSuffixAttempts,
- } = storagePatternConfig;
-
- if (useLegacyStorageKeyDefinitionSystem) {
- const { originalDocumentStorageKey } = buildOriginalDocumentKey({
- documentId,
- fileName: documentName,
- organizationId,
- });
-
- return { storageKey: originalDocumentStorageKey };
- }
-
- const { storageKey: initialStorageKey } = buildStorageKey({
- storageKeyPattern,
- documentId,
- documentName,
- organizationId,
- now,
- });
-
- const { storageKey } = await ensureStorageKeyIsAvailable({
- initialStorageKey,
- maxIncrementalSuffixAttempts,
- enableRandomSuffixFallback,
- documentsStorageService,
- logger,
- });
-
- return { storageKey };
-}
diff --git a/apps/papra-server/src/modules/documents/storage/documents.storage.services.ts b/apps/papra-server/src/modules/documents/storage/documents.storage.services.ts
deleted file mode 100644
index b0fc43a9..00000000
--- a/apps/papra-server/src/modules/documents/storage/documents.storage.services.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import type { Config } from '../../config/config.types';
-import type { DocumentStorageConfig } from './documents.storage.types';
-import type {
- StorageDriver,
- StorageDriverFactory,
- StorageServices,
-} from './drivers/drivers.models';
-import { createError } from '../../shared/errors/errors';
-import { isNil } from '../../shared/utils';
-import {
- AZ_BLOB_STORAGE_DRIVER_NAME,
- azBlobStorageDriverFactory,
-} from './drivers/az-blob/az-blob.storage-driver';
-import { FS_STORAGE_DRIVER_NAME, fsStorageDriverFactory } from './drivers/fs/fs.storage-driver';
-import {
- IN_MEMORY_STORAGE_DRIVER_NAME,
- inMemoryStorageDriverFactory,
-} from './drivers/memory/memory.storage-driver';
-import { S3_STORAGE_DRIVER_NAME, s3StorageDriverFactory } from './drivers/s3/s3.storage-driver';
-import { wrapWithEncryptionLayer } from './encryption/document-encryption.services';
-
-const storageDriverFactories = {
- [FS_STORAGE_DRIVER_NAME]: fsStorageDriverFactory,
- [S3_STORAGE_DRIVER_NAME]: s3StorageDriverFactory,
- [IN_MEMORY_STORAGE_DRIVER_NAME]: inMemoryStorageDriverFactory,
- [AZ_BLOB_STORAGE_DRIVER_NAME]: azBlobStorageDriverFactory,
-};
-
-export type DocumentStorageService = Awaited<ReturnType<typeof createDocumentStorageService>>;
-
-export function createDocumentStorageService({
- documentStorageConfig,
-}: {
- documentStorageConfig: DocumentStorageConfig;
-}): StorageServices {
- const storageDriverName = documentStorageConfig.driver;
-
- const storageDriverFactory: StorageDriverFactory | undefined =
- storageDriverFactories[storageDriverName];
-
- if (isNil(storageDriverFactory)) {
- throw createError({
- message: `Unknown storage driver: ${storageDriverName}`,
- code: 'storage_driver.unknown_driver',
- isInternal: true,
- statusCode: 500,
- });
- }
-
- const storageDriver = storageDriverFactory({ documentStorageConfig });
-
- return createDocumentStorageServiceFromDriver({
- storageDriver,
- encryptionConfig: documentStorageConfig.encryption,
- });
-}
-
-export function createDocumentStorageServiceFromDriver({
- storageDriver,
- encryptionConfig,
-}: {
- storageDriver: StorageDriver;
- encryptionConfig: Config['documentsStorage']['encryption'];
-}): StorageServices {
- return wrapWithEncryptionLayer({ storageDriver, encryptionConfig });
-}
diff --git a/apps/papra-server/src/modules/documents/storage/documents.storage.types.ts b/apps/papra-server/src/modules/documents/storage/documents.storage.types.ts
deleted file mode 100644
index 7c2902b0..00000000
--- a/apps/papra-server/src/modules/documents/storage/documents.storage.types.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import type { Config } from '../../config/config.types';
-
-export type DocumentStorageConfig = Config['documentsStorage'];
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.models.test.ts b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.models.test.ts
deleted file mode 100644
index 9e92f41c..00000000
--- a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.models.test.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { Buffer } from 'node:buffer';
-import { describe, expect, test } from 'vitest';
-import { getKekByVersion, getMostRecentDocumentKek } from './document-encryption.models';
-import {
- createDocumentKekNotFoundError,
- createDocumentKekRequiredError,
-} from './document-encryptions.errors';
-
-describe('document-encryption models', () => {
- describe('getMostRecentDocumentKek', () => {
- test('given an array of document KEKs, the key with the highest version is returned', () => {
- const documentKeyEncryptionKeys = [
- { version: '1', key: Buffer.from('key1') },
- { version: '3', key: Buffer.from('key3') },
- { version: '2', key: Buffer.from('key2') },
- ];
-
- expect(getMostRecentDocumentKek({ documentKeyEncryptionKeys })).to.eql({
- version: '3',
- key: Buffer.from('key3'),
- });
- });
-
- test('when no KEK is found, an error is thrown', () => {
- expect(() => getMostRecentDocumentKek({ documentKeyEncryptionKeys: undefined })).toThrow(
- createDocumentKekRequiredError(),
- );
- expect(() => getMostRecentDocumentKek({ documentKeyEncryptionKeys: [] })).toThrow(
- createDocumentKekRequiredError(),
- );
- });
- });
-
- describe('getKekByVersion', () => {
- test('given a version, the KEK with the matching version is returned', () => {
- const documentKeyEncryptionKeys = [
- { version: '1', key: Buffer.from('key1') },
- { version: '3', key: Buffer.from('key3') },
- { version: '2', key: Buffer.from('key2') },
- ];
-
- expect(getKekByVersion({ documentKeyEncryptionKeys, version: '2' })).to.eql({
- version: '2',
- key: Buffer.from('key2'),
- });
- });
-
- test('when no KEK is found, an error is thrown', () => {
- expect(() => getKekByVersion({ documentKeyEncryptionKeys: [], version: '2' })).toThrow(
- createDocumentKekNotFoundError(),
- );
- expect(() => getKekByVersion({ documentKeyEncryptionKeys: undefined, version: '2' })).toThrow(
- createDocumentKekNotFoundError(),
- );
- });
- });
-});
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.models.test.ts b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.models.test.ts
deleted file mode 100644
index 9c983fce..00000000
--- a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.models.test.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { describe, expect, test } from 'vitest';
-import { areDocumentKeyEncryptionKeysUnique } from './document-encryption.schemas.models';
-
-describe('document-encryption schemas models', () => {
- describe('areDocumentKeyEncryptionKeysUnique', () => {
- test('same versions should return false, different versions should return true', () => {
- expect(
- areDocumentKeyEncryptionKeysUnique([{ version: '1' }, { version: '2' }, { version: '3' }]),
- ).toBe(true);
-
- expect(
- areDocumentKeyEncryptionKeysUnique([{ version: '1' }, { version: '2' }, { version: '1' }]),
- ).toBe(false);
-
- expect(areDocumentKeyEncryptionKeysUnique([])).toBe(true);
- expect(areDocumentKeyEncryptionKeysUnique([{ version: '1' }])).toBe(true);
- });
- });
-});
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.models.ts b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.models.ts
deleted file mode 100644
index 9d656e75..00000000
--- a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.models.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export function areDocumentKeyEncryptionKeysUnique(keys: { version: string }[]) {
- return keys.length === new Set(keys.map((k) => k.version)).size;
-}
diff --git a/apps/papra-server/src/modules/documents/tasks/extract-document-file-content.task.ts b/apps/papra-server/src/modules/documents/tasks/extract-document-file-content.task.ts
index cd820300..63a5db25 100644
--- a/apps/papra-server/src/modules/documents/tasks/extract-document-file-content.task.ts
+++ b/apps/papra-server/src/modules/documents/tasks/extract-document-file-content.task.ts
@@ -1,7 +1,7 @@
import type { Database } from '../../app/database/database.types';
import type { EventServices } from '../../app/events/events.services';
import type { TaskServices } from '../../tasks/tasks.services';
-import type { DocumentStorageService } from '../storage/documents.storage.services';
+import type { StorageService } from '../../storage/storage.services';
import { createTaggingRulesRepository } from '../../tagging-rules/tagging-rules.repository';
import { createTagsRepository } from '../../tags/tags.repository';
import { createDocumentsRepository } from '../documents.repository';
@@ -18,7 +18,7 @@ export async function registerExtractDocumentFileContentTask({
}: {
taskServices: TaskServices;
db: Database;
- documentsStorageService: DocumentStorageService;
+ documentsStorageService: StorageService;
eventServices: EventServices;
config: Config;
}) {
diff --git a/apps/papra-server/src/modules/documents/tasks/hard-delete-expired-documents.task.ts b/apps/papra-server/src/modules/documents/tasks/hard-delete-expired-documents.task.ts
index b161a20d..24129bc9 100644
--- a/apps/papra-server/src/modules/documents/tasks/hard-delete-expired-documents.task.ts
+++ b/apps/papra-server/src/modules/documents/tasks/hard-delete-expired-documents.task.ts
@@ -2,7 +2,7 @@ import type { Database } from '../../app/database/database.types';
import type { EventServices } from '../../app/events/events.services';
import type { Config } from '../../config/config.types';
import type { TaskServices } from '../../tasks/tasks.services';
-import type { DocumentStorageService } from '../storage/documents.storage.services';
+import type { StorageService } from '../../storage/storage.services';
import { createLogger } from '../../shared/logger/logger';
import { createDocumentsRepository } from '../documents.repository';
import { deleteExpiredDocuments } from '../documents.usecases';
@@ -19,7 +19,7 @@ export async function registerHardDeleteExpiredDocumentsTask({
taskServices: TaskServices;
db: Database;
config: Config;
- documentsStorageService: DocumentStorageService;
+ documentsStorageService: StorageService;
eventServices: EventServices;
}) {
const taskName = 'hard-delete-expired-documents';
diff --git a/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.usecases.test.ts b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.usecases.test.ts
index fa21f67c..c5204631 100644
--- a/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.usecases.test.ts
+++ b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.usecases.test.ts
@@ -5,7 +5,7 @@ import { createTestEventServices } from '../app/events/events.test-utils';
import { overrideConfig } from '../config/config.test-utils';
import { documentsTable } from '../documents/documents.table';
import { createDocumentCreationUsecase } from '../documents/documents.usecases';
-import { createInMemoryDocumentStorageServices } from '../documents/storage/documents.storage.services.test-utils';
+import { createInMemoryStorageService } from '../storage/storage.test-utils';
import { createOrganizationsRepository } from '../organizations/organizations.repository';
import { createInMemoryFsServices } from '../shared/fs/fs.in-memory';
import { createTestLogger } from '../shared/logger/logger.test-utils';
@@ -38,7 +38,7 @@ describe('ingestion-folders usecases', () => {
},
});
- const documentsStorageService = createInMemoryDocumentStorageServices();
+ const documentsStorageService = createInMemoryStorageService();
let documentIdIndex = 1;
const generateDocumentId = () => `doc_${documentIdIndex++}`;
@@ -147,7 +147,7 @@ describe('ingestion-folders usecases', () => {
},
});
- const documentsStorageService = createInMemoryDocumentStorageServices();
+ const documentsStorageService = createInMemoryStorageService();
let documentIdIndex = 1;
const generateDocumentId = () => `doc_${documentIdIndex++}`;
@@ -257,7 +257,7 @@ describe('ingestion-folders usecases', () => {
},
});
- const documentsStorageService = createInMemoryDocumentStorageServices();
+ const documentsStorageService = createInMemoryStorageService();
let documentIdIndex = 1;
const generateDocumentId = () => `doc_${documentIdIndex++}`;
@@ -342,7 +342,7 @@ describe('ingestion-folders usecases', () => {
},
});
- const documentsStorageService = createInMemoryDocumentStorageServices();
+ const documentsStorageService = createInMemoryStorageService();
let documentIdIndex = 1;
const generateDocumentId = () => `doc_${documentIdIndex++}`;
@@ -489,7 +489,7 @@ describe('ingestion-folders usecases', () => {
});
const organizationsRepository = createOrganizationsRepository({ db });
- const documentsStorageService = createInMemoryDocumentStorageServices();
+ const documentsStorageService = createInMemoryStorageService();
let documentIdIndex = 1;
const generateDocumentId = () => `doc_${documentIdIndex++}`;
diff --git a/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.usecases.ts b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.usecases.ts
index 32f8abed..042db295 100644
--- a/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.usecases.ts
+++ b/apps/papra-server/src/modules/ingestion-folders/ingestion-folders.usecases.ts
@@ -3,7 +3,7 @@ import type { Database } from '../app/database/database.types';
import type { EventServices } from '../app/events/events.services';
import type { Config } from '../config/config.types';
import type { CreateDocumentUsecase } from '../documents/documents.usecases';
-import type { DocumentStorageService } from '../documents/storage/documents.storage.services';
+import type { StorageService } from '../storage/storage.services';
import type { OrganizationsRepository } from '../organizations/organizations.repository';
import type { FsServices } from '../shared/fs/fs.services';
import type { Logger } from '../shared/logger/logger';
@@ -44,7 +44,7 @@ export function createIngestionFolderWatcher({
logger?: Logger;
db: Database;
taskServices: TaskServices;
- documentsStorageService: DocumentStorageService;
+ documentsStorageService: StorageService;
eventServices: EventServices;
}) {
const {
diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts
index d3c13d63..3c8d09c6 100644
--- a/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts
+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts
@@ -7,7 +7,7 @@ import { createTestEventServices } from '../app/events/events.test-utils';
import { overrideConfig } from '../config/config.test-utils';
import { documentsTable } from '../documents/documents.table';
import { createDocumentCreationUsecase } from '../documents/documents.usecases';
-import { createInMemoryDocumentStorageServices } from '../documents/storage/documents.storage.services.test-utils';
+import { createInMemoryStorageService } from '../storage/storage.test-utils';
import { createPlanEntitlementsRepository } from '../plan-entitlements/plan-entitlements.repository';
import { createPlanEntitlementDefinitionRegistry } from '../plan-entitlements/plan-entitlements.registry';
import { PLAN_IDS } from '../plans/plans.constants';
@@ -45,7 +45,7 @@ describe('intake-emails usecases', () => {
const createDocument = createDocumentCreationUsecase({
db,
taskServices,
- documentsStorageService: createInMemoryDocumentStorageServices(),
+ documentsStorageService: createInMemoryStorageService(),
config: overrideConfig({
organizationPlans: { isFreePlanUnlimited: true },
}),
@@ -105,7 +105,7 @@ describe('intake-emails usecases', () => {
const createDocument = createDocumentCreationUsecase({
db,
taskServices,
- documentsStorageService: createInMemoryDocumentStorageServices(),
+ documentsStorageService: createInMemoryStorageService(),
config: overrideConfig({
organizationPlans: { isFreePlanUnlimited: true },
}),
@@ -139,7 +139,7 @@ describe('intake-emails usecases', () => {
const createDocument = createDocumentCreationUsecase({
db,
taskServices,
- documentsStorageService: createInMemoryDocumentStorageServices(),
+ documentsStorageService: createInMemoryStorageService(),
config: overrideConfig({
organizationPlans: { isFreePlanUnlimited: true },
}),
@@ -190,7 +190,7 @@ describe('intake-emails usecases', () => {
const createDocument = createDocumentCreationUsecase({
db,
taskServices,
- documentsStorageService: createInMemoryDocumentStorageServices(),
+ documentsStorageService: createInMemoryStorageService(),
config: overrideConfig({
organizationPlans: { isFreePlanUnlimited: true },
}),
@@ -250,7 +250,7 @@ describe('intake-emails usecases', () => {
const createDocument = createDocumentCreationUsecase({
db,
taskServices,
- documentsStorageService: createInMemoryDocumentStorageServices(),
+ documentsStorageService: createInMemoryStorageService(),
config: overrideConfig({
organizationPlans: { isFreePlanUnlimited: true },
}),
diff --git a/apps/papra-server/src/modules/organizations/organizations.usecases.test.ts b/apps/papra-server/src/modules/organizations/organizations.usecases.test.ts
index cfe894e9..8d181f53 100644
--- a/apps/papra-server/src/modules/organizations/organizations.usecases.test.ts
+++ b/apps/papra-server/src/modules/organizations/organizations.usecases.test.ts
@@ -1,4 +1,4 @@
-import type { DocumentStorageService } from '../documents/storage/documents.storage.services';
+import type { StorageService } from '../storage/storage.services';
import type { EmailsServices } from '../emails/emails.services';
import type { PlansRepository } from '../plans/plans.repository';
import type { SubscriptionsServices } from '../subscriptions/subscriptions.services';
@@ -1390,7 +1390,7 @@ describe('organizations usecases', () => {
deleteFile: async ({ storageKey }: { storageKey: string }) => {
deletedFiles.push(storageKey);
},
- } as DocumentStorageService;
+ } as StorageService;
await purgeExpiredSoftDeletedOrganization({
organizationId: 'organization-1',
@@ -1506,7 +1506,7 @@ describe('organizations usecases', () => {
}
deletedFiles.push(storageKey);
},
- } as DocumentStorageService;
+ } as StorageService;
await purgeExpiredSoftDeletedOrganization({
organizationId: 'organization-1',
@@ -1563,7 +1563,7 @@ describe('organizations usecases', () => {
deleteFile: async ({ storageKey }: { storageKey: string }) => {
deletedFiles.push(storageKey);
},
- } as DocumentStorageService;
+ } as StorageService;
await purgeExpiredSoftDeletedOrganization({
organizationId: 'organization-1',
@@ -1614,7 +1614,7 @@ describe('organizations usecases', () => {
deleteFile: async ({ storageKey }: { storageKey: string }) => {
deletedFiles.push(storageKey);
},
- } as DocumentStorageService;
+ } as StorageService;
await purgeExpiredSoftDeletedOrganization({
organizationId: 'organization-1',
@@ -1706,7 +1706,7 @@ describe('organizations usecases', () => {
deleteFile: async ({ storageKey }: { storageKey: string }) => {
deletedFiles.push(storageKey);
},
- } as DocumentStorageService;
+ } as StorageService;
const { purgedOrganizationCount } = await purgeExpiredSoftDeletedOrganizations({
organizationsRepository,
@@ -1793,7 +1793,7 @@ describe('organizations usecases', () => {
}
deletedFiles.push(storageKey);
},
- } as DocumentStorageService;
+ } as StorageService;
const { purgedOrganizationCount } = await purgeExpiredSoftDeletedOrganizations({
organizationsRepository,
@@ -1848,7 +1848,7 @@ describe('organizations usecases', () => {
deleteFile: async ({ storageKey }: { storageKey: string }) => {
deletedFiles.push(storageKey);
},
- } as DocumentStorageService;
+ } as StorageService;
const { purgedOrganizationCount } = await purgeExpiredSoftDeletedOrganizations({
organizationsRepository,
diff --git a/apps/papra-server/src/modules/organizations/organizations.usecases.ts b/apps/papra-server/src/modules/organizations/organizations.usecases.ts
index 2cdefadc..4bc7c631 100644
--- a/apps/papra-server/src/modules/organizations/organizations.usecases.ts
+++ b/apps/papra-server/src/modules/organizations/organizations.usecases.ts
@@ -1,6 +1,6 @@
import type { Config } from '../config/config.types';
import type { DocumentsRepository } from '../documents/documents.repository';
-import type { DocumentStorageService } from '../documents/storage/documents.storage.services';
+import type { StorageService } from '../storage/storage.services';
import type { EmailsServices } from '../emails/emails.services';
import type { PlanEntitlementsRepository } from '../plan-entitlements/plan-entitlements.repository';
import type { PlanEntitlementDefinitionRegistry } from '../plan-entitlements/plan-entitlements.registry';
@@ -653,7 +653,7 @@ export async function purgeExpiredSoftDeletedOrganization({
organizationId: string;
documentsRepository: DocumentsRepository;
organizationsRepository: OrganizationsRepository;
- documentsStorageService: DocumentStorageService;
+ documentsStorageService: StorageService;
logger?: Logger;
batchSize?: number;
}) {
@@ -706,7 +706,7 @@ export async function purgeExpiredSoftDeletedOrganizations({
}: {
organizationsRepository: OrganizationsRepository;
documentsRepository: DocumentsRepository;
- documentsStorageService: DocumentStorageService;
+ documentsStorageService: StorageService;
logger?: Logger;
now?: Date;
}) {
diff --git a/apps/papra-server/src/modules/organizations/tasks/purge-expired-organizations.task.ts b/apps/papra-server/src/modules/organizations/tasks/purge-expired-organizations.task.ts
index 31d2fbd3..644d029d 100644
--- a/apps/papra-server/src/modules/organizations/tasks/purge-expired-organizations.task.ts
+++ b/apps/papra-server/src/modules/organizations/tasks/purge-expired-organizations.task.ts
@@ -1,6 +1,6 @@
import type { Database } from '../../app/database/database.types';
import type { Config } from '../../config/config.types';
-import type { DocumentStorageService } from '../../documents/storage/documents.storage.services';
+import type { StorageService } from '../../storage/storage.services';
import type { TaskServices } from '../../tasks/tasks.services';
import { createDocumentsRepository } from '../../documents/documents.repository';
import { createLogger } from '../../shared/logger/logger';
@@ -18,7 +18,7 @@ export async function registerPurgeExpiredOrganizationsTask({
taskServices: TaskServices;
db: Database;
config: Config;
- documentsStorageService: DocumentStorageService;
+ documentsStorageService: StorageService;
}) {
const taskName = 'purge-expired-organizations';
const { cron, runOnStartup } = config.tasks.purgeExpiredOrganizations;
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/az-blob/az-blob.models.ts b/apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.models.ts
similarity index 100%
rename from apps/papra-server/src/modules/documents/storage/drivers/az-blob/az-blob.models.ts
rename to apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.models.ts
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/az-blob/az-blob.storage-driver.int.test.ts b/apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.storage-driver.int.test.ts
similarity index 74%
rename from apps/papra-server/src/modules/documents/storage/drivers/az-blob/az-blob.storage-driver.int.test.ts
rename to apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.storage-driver.int.test.ts
index c1492e01..63ceb38b 100644
--- a/apps/papra-server/src/modules/documents/storage/drivers/az-blob/az-blob.storage-driver.int.test.ts
+++ b/apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.storage-driver.int.test.ts
@@ -1,7 +1,6 @@
-import type { DocumentStorageConfig } from '../../documents.storage.types';
import { AzuriteContainer } from '@testcontainers/azurite';
import { describe } from 'vitest';
-import { TEST_CONTAINER_IMAGES } from '../../../../../../test/containers/images';
+import { TEST_CONTAINER_IMAGES } from '../../../../../test/containers/images';
import { runDriverTestSuites } from '../drivers.test-suite';
import { azBlobStorageDriverFactory } from './az-blob.storage-driver';
@@ -16,9 +15,10 @@ describe('az-blob storage-driver', () => {
const connectionString = azuriteContainer.getConnectionString();
const driver = azBlobStorageDriverFactory({
- documentStorageConfig: {
- drivers: { azureBlob: { connectionString, containerName: 'test-container' } },
- } as DocumentStorageConfig,
+ connectionString,
+ containerName: 'test-container',
+ accountName: '',
+ accountKey: '',
});
const client = driver.getClient();
await client.createContainer('test-container');
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/az-blob/az-blob.storage-driver.ts b/apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.storage-driver.ts
similarity index 86%
rename from apps/papra-server/src/modules/documents/storage/drivers/az-blob/az-blob.storage-driver.ts
rename to apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.storage-driver.ts
index 6915bf73..a56e0f9a 100644
--- a/apps/papra-server/src/modules/documents/storage/drivers/az-blob/az-blob.storage-driver.ts
+++ b/apps/papra-server/src/modules/storage/drivers/az-blob/az-blob.storage-driver.ts
@@ -1,20 +1,23 @@
import type { Readable } from 'node:stream';
+import type { AzureBlobStorageDriverOptions } from '../../storage.types';
+import type { StorageDriver } from '../drivers.models';
import { BlobServiceClient, StorageSharedKeyCredential } from '@azure/storage-blob';
import { safely } from '@corentinth/chisels';
import {
createFileAlreadyExistsInStorageError,
createFileNotFoundError,
-} from '../../document-storage.errors';
-import { defineStorageDriver } from '../drivers.models';
+} from '../../storage.errors';
import { isAzureBlobAlreadyExistsError, isAzureBlobNotFoundError } from './az-blob.models';
export const AZ_BLOB_STORAGE_DRIVER_NAME = 'azure-blob' as const;
-export const azBlobStorageDriverFactory = defineStorageDriver(({ documentStorageConfig }) => {
- const { accountName, accountKey, containerName, connectionString } =
- documentStorageConfig.drivers.azureBlob;
-
+export const azBlobStorageDriverFactory = ({
+ accountName,
+ accountKey,
+ containerName,
+ connectionString,
+}: AzureBlobStorageDriverOptions) => {
const blobServiceClient =
connectionString !== undefined
? BlobServiceClient.fromConnectionString(connectionString)
@@ -81,5 +84,5 @@ export const azBlobStorageDriverFactory = defineStorageDriver(({ documentStorage
return true;
},
- };
-});
+ } satisfies StorageDriver & { getClient: () => BlobServiceClient };
+};
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/drivers.models.ts b/apps/papra-server/src/modules/storage/drivers/drivers.models.ts
similarity index 70%
rename from apps/papra-server/src/modules/documents/storage/drivers/drivers.models.ts
rename to apps/papra-server/src/modules/storage/drivers/drivers.models.ts
index afeb372f..0380d783 100644
--- a/apps/papra-server/src/modules/documents/storage/drivers/drivers.models.ts
+++ b/apps/papra-server/src/modules/storage/drivers/drivers.models.ts
@@ -1,6 +1,5 @@
import type { Readable } from 'node:stream';
-import type { ExtendNamedArguments, ExtendReturnPromise } from '../../../shared/types';
-import type { DocumentStorageConfig } from '../documents.storage.types';
+import type { ExtendNamedArguments, ExtendReturnPromise } from '../../shared/types';
export type StorageDriver = {
name: string;
@@ -16,7 +15,6 @@ export type StorageDriver = {
}>;
deleteFile: (args: { storageKey: string }) => Promise<void>;
-
fileExists: (args: { storageKey: string }) => Promise<boolean>;
};
@@ -26,18 +24,11 @@ export type EncryptionContext = {
fileEncryptionKekVersion?: string | null | undefined;
};
-// Same as the driver but with the encryption context added in the args
-export type StorageServices = {
+export type StorageService = {
saveFile: ExtendReturnPromise<StorageDriver['saveFile'], EncryptionContext>;
getFileStream: ExtendNamedArguments<StorageDriver['getFileStream'], EncryptionContext>;
deleteFile: StorageDriver['deleteFile'];
fileExists: StorageDriver['fileExists'];
};
-export type StorageDriverFactory = (args: {
- documentStorageConfig: DocumentStorageConfig;
-}) => StorageDriver;
-
-export function defineStorageDriver<T extends StorageDriverFactory>(factory: T) {
- return factory;
-}
+export type StorageDriverFactory<TOptions = undefined> = (options: TOptions) => StorageDriver;
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/drivers.test-suite.ts b/apps/papra-server/src/modules/storage/drivers/drivers.test-suite.ts
similarity index 92%
rename from apps/papra-server/src/modules/documents/storage/drivers/drivers.test-suite.ts
rename to apps/papra-server/src/modules/storage/drivers/drivers.test-suite.ts
index 2c200571..22b39ab5 100644
--- a/apps/papra-server/src/modules/documents/storage/drivers/drivers.test-suite.ts
+++ b/apps/papra-server/src/modules/storage/drivers/drivers.test-suite.ts
@@ -1,4 +1,4 @@
-import type { StorageDriver, StorageServices } from './drivers.models';
+import type { StorageDriver, StorageService } from './drivers.models';
import { Buffer } from 'node:buffer';
import { randomBytes, randomUUID } from 'node:crypto';
import { describe, expect, test } from 'vitest';
@@ -6,13 +6,10 @@ import {
collectReadableStreamToBuffer,
collectReadableStreamToString,
createReadableStream,
-} from '../../../shared/streams/readable-stream';
-import {
- createFileAlreadyExistsInStorageError,
- createFileNotFoundError,
-} from '../document-storage.errors';
-import { wrapWithEncryptionLayer } from '../encryption/document-encryption.services';
-import { IN_BYTES } from '../../../shared/units';
+} from '../../shared/streams/readable-stream';
+import { createFileAlreadyExistsInStorageError, createFileNotFoundError } from '../storage.errors';
+import { wrapWithEncryptionLayer } from '../encryption/storage-encryption.services';
+import { IN_BYTES } from '../../shared/units';
import { MULTIPART_MIN_PART_SIZE_IN_BYTES } from './s3/s3.storage-driver';
export function runDriverTestSuites({
@@ -40,7 +37,7 @@ export function runDriverTestSuites({
await driver.saveFile(args);
return {};
},
- } as StorageServices,
+ } as StorageService,
[Symbol.asyncDispose]: dispose,
};
},
@@ -53,9 +50,9 @@ export function runDriverTestSuites({
return {
storageServices: wrapWithEncryptionLayer({
storageDriver: driver,
- encryptionConfig: {
+ encryptionOptions: {
isEncryptionEnabled: true,
- documentKeyEncryptionKeys: [
+ keyEncryptionKeys: [
{
version: '1',
key: Buffer.from(
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/fs/fixtures/text-file.txt b/apps/papra-server/src/modules/storage/drivers/fs/fixtures/text-file.txt
similarity index 100%
rename from apps/papra-server/src/modules/documents/storage/drivers/fs/fixtures/text-file.txt
rename to apps/papra-server/src/modules/storage/drivers/fs/fixtures/text-file.txt
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.int.test.ts b/apps/papra-server/src/modules/storage/drivers/fs/fs.storage-driver.int.test.ts
similarity index 73%
rename from apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.int.test.ts
rename to apps/papra-server/src/modules/storage/drivers/fs/fs.storage-driver.int.test.ts
index fcdfbc34..d79da0cd 100644
--- a/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.int.test.ts
+++ b/apps/papra-server/src/modules/storage/drivers/fs/fs.storage-driver.int.test.ts
@@ -1,13 +1,12 @@
-import type { DocumentStorageConfig } from '../../documents.storage.types';
import fs from 'node:fs';
import path from 'node:path';
import { describe, expect, test } from 'vitest';
-import { createDisposableTmpDirectory } from '../../../../shared/fs/fs.test-utils';
-import { createReadableStream } from '../../../../shared/streams/readable-stream';
+import { createDisposableTmpDirectory } from '../../../shared/fs/fs.test-utils';
+import { createReadableStream } from '../../../shared/streams/readable-stream';
import {
createFileAlreadyExistsInStorageError,
createFileNotFoundError,
-} from '../../document-storage.errors';
+} from '../../storage.errors';
import { runDriverTestSuites } from '../drivers.test-suite';
import { fsStorageDriverFactory } from './fs.storage-driver';
@@ -18,11 +17,7 @@ describe('storage driver', () => {
const { tmpDirectoryPath, removeTmpDirectory } = await createDisposableTmpDirectory();
return {
- driver: fsStorageDriverFactory({
- documentStorageConfig: {
- drivers: { filesystem: { root: tmpDirectoryPath } },
- } as DocumentStorageConfig,
- }),
+ driver: fsStorageDriverFactory({ root: tmpDirectoryPath }),
[Symbol.asyncDispose]: async () => {
await removeTmpDirectory();
},
@@ -35,11 +30,7 @@ describe('storage driver', () => {
await using tmpDirectory = await createDisposableTmpDirectory();
const { tmpDirectoryPath } = tmpDirectory;
- const fsStorageDriver = fsStorageDriverFactory({
- documentStorageConfig: {
- drivers: { filesystem: { root: tmpDirectoryPath } },
- } as DocumentStorageConfig,
- });
+ const fsStorageDriver = fsStorageDriverFactory({ root: tmpDirectoryPath });
const storageKey = 'org_1/text-file.txt';
await fsStorageDriver.saveFile({
@@ -63,11 +54,7 @@ describe('storage driver', () => {
await using tmpDirectory = await createDisposableTmpDirectory();
const { tmpDirectoryPath } = tmpDirectory;
- const fsStorageDriver = fsStorageDriverFactory({
- documentStorageConfig: {
- drivers: { filesystem: { root: tmpDirectoryPath } },
- } as DocumentStorageConfig,
- });
+ const fsStorageDriver = fsStorageDriverFactory({ root: tmpDirectoryPath });
await fsStorageDriver.saveFile({
fileStream: createReadableStream({ content: 'lorem ipsum' }),
@@ -92,11 +79,7 @@ describe('storage driver', () => {
await using tmpDirectory = await createDisposableTmpDirectory();
const { tmpDirectoryPath } = tmpDirectory;
- const fsStorageDriver = fsStorageDriverFactory({
- documentStorageConfig: {
- drivers: { filesystem: { root: tmpDirectoryPath } },
- } as DocumentStorageConfig,
- });
+ const fsStorageDriver = fsStorageDriverFactory({ root: tmpDirectoryPath });
await fsStorageDriver.saveFile({
fileStream: createReadableStream({ content: 'lorem ipsum' }),
@@ -121,11 +104,7 @@ describe('storage driver', () => {
await using tmpDirectory = await createDisposableTmpDirectory();
const { tmpDirectoryPath } = tmpDirectory;
- const fsStorageDriver = fsStorageDriverFactory({
- documentStorageConfig: {
- drivers: { filesystem: { root: tmpDirectoryPath } },
- } as DocumentStorageConfig,
- });
+ const fsStorageDriver = fsStorageDriverFactory({ root: tmpDirectoryPath });
await expect(
fsStorageDriver.getFileStream({ storageKey: 'org_1/text-file.txt' }),
@@ -138,11 +117,7 @@ describe('storage driver', () => {
await using tmpDirectory = await createDisposableTmpDirectory();
const { tmpDirectoryPath } = tmpDirectory;
- const fsStorageDriver = fsStorageDriverFactory({
- documentStorageConfig: {
- drivers: { filesystem: { root: tmpDirectoryPath } },
- } as DocumentStorageConfig,
- });
+ const fsStorageDriver = fsStorageDriverFactory({ root: tmpDirectoryPath });
await fsStorageDriver.saveFile({
fileStream: createReadableStream({ content: 'lorem ipsum' }),
@@ -173,11 +148,7 @@ describe('storage driver', () => {
await using tmpDirectory = await createDisposableTmpDirectory();
const { tmpDirectoryPath } = tmpDirectory;
- const fsStorageDriver = fsStorageDriverFactory({
- documentStorageConfig: {
- drivers: { filesystem: { root: tmpDirectoryPath } },
- } as DocumentStorageConfig,
- });
+ const fsStorageDriver = fsStorageDriverFactory({ root: tmpDirectoryPath });
await expect(
fsStorageDriver.deleteFile({ storageKey: 'org_1/text-file.txt' }),
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.models.test.ts b/apps/papra-server/src/modules/storage/drivers/fs/fs.storage-driver.models.test.ts
similarity index 100%
rename from apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.models.test.ts
rename to apps/papra-server/src/modules/storage/drivers/fs/fs.storage-driver.models.test.ts
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.models.ts b/apps/papra-server/src/modules/storage/drivers/fs/fs.storage-driver.models.ts
similarity index 78%
rename from apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.models.ts
rename to apps/papra-server/src/modules/storage/drivers/fs/fs.storage-driver.models.ts
index f11c1837..7a199aa8 100644
--- a/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.models.ts
+++ b/apps/papra-server/src/modules/storage/drivers/fs/fs.storage-driver.models.ts
@@ -1,4 +1,4 @@
-import { isNil } from '../../../../shared/utils';
+import { isNil } from '../../../shared/utils';
export function isFileNotFoundError({ error }: { error?: unknown }): boolean {
return !isNil(error) && typeof error === 'object' && 'code' in error && error.code === 'ENOENT';
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.ts b/apps/papra-server/src/modules/storage/drivers/fs/fs.storage-driver.ts
similarity index 84%
rename from apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.ts
rename to apps/papra-server/src/modules/storage/drivers/fs/fs.storage-driver.ts
index 143880ea..3166eb14 100644
--- a/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.ts
+++ b/apps/papra-server/src/modules/storage/drivers/fs/fs.storage-driver.ts
@@ -1,24 +1,19 @@
+import type { FilesystemStorageDriverOptions } from '../../storage.types';
+import type { StorageDriver } from '../drivers.models';
import fs from 'node:fs';
import { dirname, join } from 'node:path';
import { safely } from '@corentinth/chisels';
-import { isFileAlreadyExistsError } from '../../../../shared/fs/fs.models';
-import {
- checkFileExists,
- deleteFile,
- ensureDirectoryExists,
-} from '../../../../shared/fs/fs.services';
+import { isFileAlreadyExistsError } from '../../../shared/fs/fs.models';
+import { checkFileExists, deleteFile, ensureDirectoryExists } from '../../../shared/fs/fs.services';
import {
createFileAlreadyExistsInStorageError,
createFileNotFoundError,
-} from '../../document-storage.errors';
-import { defineStorageDriver } from '../drivers.models';
+} from '../../storage.errors';
import { isFileNotFoundError } from './fs.storage-driver.models';
export const FS_STORAGE_DRIVER_NAME = 'filesystem' as const;
-export const fsStorageDriverFactory = defineStorageDriver(({ documentStorageConfig }) => {
- const { root } = documentStorageConfig.drivers.filesystem;
-
+export const fsStorageDriverFactory = ({ root }: FilesystemStorageDriverOptions) => {
const getStoragePath = ({ storageKey }: { storageKey: string }) => ({
storagePath: join(root, storageKey),
});
@@ -89,5 +84,5 @@ export const fsStorageDriverFactory = defineStorageDriver(({ documentStorageConf
return exists;
},
- };
-});
+ } satisfies StorageDriver;
+};
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/memory/memory.storage-driver.int.test.ts b/apps/papra-server/src/modules/storage/drivers/memory/memory.storage-driver.int.test.ts
similarity index 95%
rename from apps/papra-server/src/modules/documents/storage/drivers/memory/memory.storage-driver.int.test.ts
rename to apps/papra-server/src/modules/storage/drivers/memory/memory.storage-driver.int.test.ts
index d6e6939c..3d12e4a9 100644
--- a/apps/papra-server/src/modules/documents/storage/drivers/memory/memory.storage-driver.int.test.ts
+++ b/apps/papra-server/src/modules/storage/drivers/memory/memory.storage-driver.int.test.ts
@@ -3,8 +3,8 @@ import { describe, expect, test } from 'vitest';
import {
createReadableStream,
fileToReadableStream,
-} from '../../../../shared/streams/readable-stream';
-import { createFileNotFoundError } from '../../document-storage.errors';
+} from '../../../shared/streams/readable-stream';
+import { createFileNotFoundError } from '../../storage.errors';
import { runDriverTestSuites } from '../drivers.test-suite';
import { inMemoryStorageDriverFactory } from './memory.storage-driver';
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/memory/memory.storage-driver.ts b/apps/papra-server/src/modules/storage/drivers/memory/memory.storage-driver.ts
similarity index 84%
rename from apps/papra-server/src/modules/documents/storage/drivers/memory/memory.storage-driver.ts
rename to apps/papra-server/src/modules/storage/drivers/memory/memory.storage-driver.ts
index 1b906bea..abedc1a3 100644
--- a/apps/papra-server/src/modules/documents/storage/drivers/memory/memory.storage-driver.ts
+++ b/apps/papra-server/src/modules/storage/drivers/memory/memory.storage-driver.ts
@@ -1,17 +1,17 @@
import type { Buffer } from 'node:buffer';
+import type { StorageDriver } from '../drivers.models';
import {
collectReadableStreamToBuffer,
createReadableStream,
-} from '../../../../shared/streams/readable-stream';
+} from '../../../shared/streams/readable-stream';
import {
createFileAlreadyExistsInStorageError,
createFileNotFoundError,
-} from '../../document-storage.errors';
-import { defineStorageDriver } from '../drivers.models';
+} from '../../storage.errors';
export const IN_MEMORY_STORAGE_DRIVER_NAME = 'in-memory' as const;
-export const inMemoryStorageDriverFactory = defineStorageDriver(() => {
+export const inMemoryStorageDriverFactory = () => {
const storage: Map<string, { content: Buffer; mimeType: string; fileName: string }> = new Map();
const fileExists = ({ storageKey }: { storageKey: string }) => storage.has(storageKey);
@@ -52,5 +52,5 @@ export const inMemoryStorageDriverFactory = defineStorageDriver(() => {
fileExists: async ({ storageKey }) => fileExists({ storageKey }),
_getStorage: () => storage,
- };
-});
+ } satisfies StorageDriver & { _getStorage: () => typeof storage };
+};
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/s3/integrations-tests/b2.storage-driver.int.test.ts b/apps/papra-server/src/modules/storage/drivers/s3/integrations-tests/b2.storage-driver.int.test.ts
similarity index 64%
rename from apps/papra-server/src/modules/documents/storage/drivers/s3/integrations-tests/b2.storage-driver.int.test.ts
rename to apps/papra-server/src/modules/storage/drivers/s3/integrations-tests/b2.storage-driver.int.test.ts
index 432e295c..fb40c17d 100644
--- a/apps/papra-server/src/modules/documents/storage/drivers/s3/integrations-tests/b2.storage-driver.int.test.ts
+++ b/apps/papra-server/src/modules/storage/drivers/s3/integrations-tests/b2.storage-driver.int.test.ts
@@ -1,4 +1,3 @@
-import type { DocumentStorageConfig } from '../../../documents.storage.types';
import { describe } from 'vitest';
import { runDriverTestSuites } from '../../drivers.test-suite';
import { s3StorageDriverFactory } from '../s3.storage-driver';
@@ -14,18 +13,12 @@ describe('s3 storage-driver', () => {
timeout: 40_000,
createDriver: async () => {
const driver = s3StorageDriverFactory({
- documentStorageConfig: {
- drivers: {
- s3: {
- accessKeyId,
- secretAccessKey,
- bucketName,
- region: 'auto',
- endpoint,
- forcePathStyle: true,
- },
- },
- } as DocumentStorageConfig,
+ accessKeyId: accessKeyId!,
+ secretAccessKey: secretAccessKey!,
+ bucketName: bucketName!,
+ region: 'auto',
+ endpoint,
+ forcePathStyle: true,
});
return {
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/s3/integrations-tests/r2.storage-driver.int.test.ts b/apps/papra-server/src/modules/storage/drivers/s3/integrations-tests/r2.storage-driver.int.test.ts
similarity index 64%
rename from apps/papra-server/src/modules/documents/storage/drivers/s3/integrations-tests/r2.storage-driver.int.test.ts
rename to apps/papra-server/src/modules/storage/drivers/s3/integrations-tests/r2.storage-driver.int.test.ts
index fd7133be..44dfe782 100644
--- a/apps/papra-server/src/modules/documents/storage/drivers/s3/integrations-tests/r2.storage-driver.int.test.ts
+++ b/apps/papra-server/src/modules/storage/drivers/s3/integrations-tests/r2.storage-driver.int.test.ts
@@ -1,4 +1,3 @@
-import type { DocumentStorageConfig } from '../../../documents.storage.types';
import { describe } from 'vitest';
import { runDriverTestSuites } from '../../drivers.test-suite';
import { s3StorageDriverFactory } from '../s3.storage-driver';
@@ -14,18 +13,12 @@ describe('s3 storage-driver', () => {
timeout: 40_000,
createDriver: async () => {
const driver = s3StorageDriverFactory({
- documentStorageConfig: {
- drivers: {
- s3: {
- accessKeyId,
- secretAccessKey,
- bucketName,
- region: 'auto',
- endpoint,
- forcePathStyle: true,
- },
- },
- } as DocumentStorageConfig,
+ accessKeyId: accessKeyId!,
+ secretAccessKey: secretAccessKey!,
+ bucketName: bucketName!,
+ region: 'auto',
+ endpoint,
+ forcePathStyle: true,
});
return {
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/s3/s3.storage-driver.int.test.ts b/apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.int.test.ts
similarity index 60%
rename from apps/papra-server/src/modules/documents/storage/drivers/s3/s3.storage-driver.int.test.ts
rename to apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.int.test.ts
index 4ca5ff89..3ee1b7ee 100644
--- a/apps/papra-server/src/modules/documents/storage/drivers/s3/s3.storage-driver.int.test.ts
+++ b/apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.int.test.ts
@@ -1,7 +1,6 @@
-import type { DocumentStorageConfig } from '../../documents.storage.types';
import { LocalstackContainer } from '@testcontainers/localstack';
import { describe } from 'vitest';
-import { TEST_CONTAINER_IMAGES } from '../../../../../../test/containers/images';
+import { TEST_CONTAINER_IMAGES } from '../../../../../test/containers/images';
import { runDriverTestSuites } from '../drivers.test-suite';
import { s3StorageDriverFactory } from './s3.storage-driver';
@@ -16,18 +15,12 @@ describe('s3 storage-driver', () => {
TEST_CONTAINER_IMAGES.LOCALSTACK,
).start();
const driver = s3StorageDriverFactory({
- documentStorageConfig: {
- drivers: {
- s3: {
- accessKeyId: 'test',
- secretAccessKey: 'test',
- bucketName: 'test-bucket',
- region: 'eu-central-1',
- endpoint: localstackContainer.getConnectionUri(),
- forcePathStyle: true,
- },
- },
- } as DocumentStorageConfig,
+ accessKeyId: 'test',
+ secretAccessKey: 'test',
+ bucketName: 'test-bucket',
+ region: 'eu-central-1',
+ endpoint: localstackContainer.getConnectionUri(),
+ forcePathStyle: true,
});
await driver.getClient().createBucket();
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/s3/s3.storage-driver.models.test.ts b/apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.models.test.ts
similarity index 99%
rename from apps/papra-server/src/modules/documents/storage/drivers/s3/s3.storage-driver.models.test.ts
rename to apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.models.test.ts
index 72c7b9a2..81020131 100644
--- a/apps/papra-server/src/modules/documents/storage/drivers/s3/s3.storage-driver.models.test.ts
+++ b/apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.models.test.ts
@@ -4,7 +4,7 @@ import { describe, expect, test } from 'vitest';
import {
collectReadableStreamToString,
createReadableStream,
-} from '../../../../shared/streams/readable-stream';
+} from '../../../shared/streams/readable-stream';
import { bufferStreamUpToThreshold, buildEndpointUrl } from './s3.storage-driver.models';
function streamFromChunks(chunks: string[]) {
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/s3/s3.storage-driver.models.ts b/apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.models.ts
similarity index 100%
rename from apps/papra-server/src/modules/documents/storage/drivers/s3/s3.storage-driver.models.ts
rename to apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.models.ts
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/s3/s3.storage-driver.ts b/apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.ts
similarity index 82%
rename from apps/papra-server/src/modules/documents/storage/drivers/s3/s3.storage-driver.ts
rename to apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.ts
index 21ad5f57..beff13f3 100644
--- a/apps/papra-server/src/modules/documents/storage/drivers/s3/s3.storage-driver.ts
+++ b/apps/papra-server/src/modules/storage/drivers/s3/s3.storage-driver.ts
@@ -1,21 +1,26 @@
+import type { S3StorageDriverOptions } from '../../storage.types';
+import type { StorageDriver } from '../drivers.models';
import { Readable } from 'node:stream';
import { S3mini } from 's3mini';
import {
createFileAlreadyExistsInStorageError,
createFileNotFoundError,
-} from '../../document-storage.errors';
-import { defineStorageDriver } from '../drivers.models';
+} from '../../storage.errors';
import { bufferStreamUpToThreshold, buildEndpointUrl } from './s3.storage-driver.models';
-import { IN_BYTES } from '../../../../shared/units';
+import { IN_BYTES } from '../../../shared/units';
export const S3_STORAGE_DRIVER_NAME = 's3' as const;
export const MULTIPART_MIN_PART_SIZE_IN_BYTES = 8 * IN_BYTES.MEGABYTE;
-export const s3StorageDriverFactory = defineStorageDriver(({ documentStorageConfig }) => {
- const { accessKeyId, secretAccessKey, bucketName, region, endpoint, forcePathStyle } =
- documentStorageConfig.drivers.s3;
-
+export const s3StorageDriverFactory = ({
+ accessKeyId,
+ secretAccessKey,
+ bucketName,
+ region,
+ endpoint,
+ forcePathStyle,
+}: S3StorageDriverOptions) => {
const client = new S3mini({
accessKeyId,
secretAccessKey,
@@ -67,5 +72,5 @@ export const s3StorageDriverFactory = defineStorageDriver(({ documentStorageConf
await client.deleteObject(storageKey);
},
fileExists,
- };
-});
+ } satisfies StorageDriver & { getClient: () => S3mini };
+};
diff --git a/apps/papra-server/src/modules/storage/drivers/storage-drivers.registry.ts b/apps/papra-server/src/modules/storage/drivers/storage-drivers.registry.ts
new file mode 100644
index 00000000..a669453c
--- /dev/null
+++ b/apps/papra-server/src/modules/storage/drivers/storage-drivers.registry.ts
@@ -0,0 +1,57 @@
+import type { StorageDriverFactory } from './drivers.models';
+import type {
+ AzureBlobStorageDriverOptions,
+ FilesystemStorageDriverOptions,
+ S3StorageDriverOptions,
+} from '../storage.types';
+import { createError } from '../../shared/errors/errors';
+import { isNil } from '../../shared/utils';
+import {
+ AZ_BLOB_STORAGE_DRIVER_NAME,
+ azBlobStorageDriverFactory,
+} from './az-blob/az-blob.storage-driver';
+import { FS_STORAGE_DRIVER_NAME, fsStorageDriverFactory } from './fs/fs.storage-driver';
+import {
+ IN_MEMORY_STORAGE_DRIVER_NAME,
+ inMemoryStorageDriverFactory,
+} from './memory/memory.storage-driver';
+import { S3_STORAGE_DRIVER_NAME, s3StorageDriverFactory } from './s3/s3.storage-driver';
+
+export const storageDriverFactories = {
+ [FS_STORAGE_DRIVER_NAME]: fsStorageDriverFactory,
+ [S3_STORAGE_DRIVER_NAME]: s3StorageDriverFactory,
+ [IN_MEMORY_STORAGE_DRIVER_NAME]: inMemoryStorageDriverFactory,
+ [AZ_BLOB_STORAGE_DRIVER_NAME]: azBlobStorageDriverFactory,
+};
+
+export const storageDriverNames = Object.keys(
+ storageDriverFactories,
+) as (keyof typeof storageDriverFactories)[];
+
+export type StorageDriverName = keyof typeof storageDriverFactories;
+
+export type StorageDriverOptionsByName = {
+ [FS_STORAGE_DRIVER_NAME]: FilesystemStorageDriverOptions;
+ [S3_STORAGE_DRIVER_NAME]: S3StorageDriverOptions;
+ [IN_MEMORY_STORAGE_DRIVER_NAME]: undefined;
+ [AZ_BLOB_STORAGE_DRIVER_NAME]: AzureBlobStorageDriverOptions;
+};
+
+export function getStorageDriverFactory<TName extends StorageDriverName>({
+ driverName,
+}: {
+ driverName: TName;
+}): StorageDriverFactory<StorageDriverOptionsByName[TName]> {
+ const factory = storageDriverFactories[driverName];
+
+ if (isNil(factory)) {
+ throw createError({
+ message: `Unknown storage driver: ${driverName}`,
+ code: 'storage_driver.unknown_driver',
+ isInternal: true,
+ statusCode: 500,
+ });
+ }
+
+ return factory as StorageDriverFactory<StorageDriverOptionsByName[TName]>;
+}
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.constants.ts b/apps/papra-server/src/modules/storage/encryption/storage-encryption.constants.ts
similarity index 100%
rename from apps/papra-server/src/modules/documents/storage/encryption/document-encryption.constants.ts
rename to apps/papra-server/src/modules/storage/encryption/storage-encryption.constants.ts
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryptions.errors.ts b/apps/papra-server/src/modules/storage/encryption/storage-encryption.errors.ts
similarity index 73%
rename from apps/papra-server/src/modules/documents/storage/encryption/document-encryptions.errors.ts
rename to apps/papra-server/src/modules/storage/encryption/storage-encryption.errors.ts
index 6b7cff5e..7f8dc405 100644
--- a/apps/papra-server/src/modules/documents/storage/encryption/document-encryptions.errors.ts
+++ b/apps/papra-server/src/modules/storage/encryption/storage-encryption.errors.ts
@@ -1,6 +1,6 @@
-import { createErrorFactory } from '../../../shared/errors/errors';
+import { createErrorFactory } from '../../shared/errors/errors';
-export const createDocumentKekRequiredError = createErrorFactory({
+export const createKekRequiredError = createErrorFactory({
message: 'Document key encryption keys are required',
code: 'storage_driver.document_key_encryption_keys_required',
isInternal: true,
@@ -14,7 +14,7 @@ export const createUnsupportedEncryptionAlgorithmError = createErrorFactory({
statusCode: 500,
});
-export const createDocumentKekNotFoundError = createErrorFactory({
+export const createKekNotFoundError = createErrorFactory({
message: 'Document key encryption key not found',
code: 'storage_driver.document_key_encryption_key_not_found',
isInternal: true,
diff --git a/apps/papra-server/src/modules/storage/encryption/storage-encryption.models.test.ts b/apps/papra-server/src/modules/storage/encryption/storage-encryption.models.test.ts
new file mode 100644
index 00000000..03624c8b
--- /dev/null
+++ b/apps/papra-server/src/modules/storage/encryption/storage-encryption.models.test.ts
@@ -0,0 +1,52 @@
+import { Buffer } from 'node:buffer';
+import { describe, expect, test } from 'vitest';
+import { getKekByVersion, getMostRecentKek } from './storage-encryption.models';
+import { createKekNotFoundError, createKekRequiredError } from './storage-encryption.errors';
+
+describe('storage-encryption models', () => {
+ describe('getMostRecentKek', () => {
+ test('given an array of document KEKs, the key with the highest version is returned', () => {
+ const keyEncryptionKeys = [
+ { version: '1', key: Buffer.from('key1') },
+ { version: '3', key: Buffer.from('key3') },
+ { version: '2', key: Buffer.from('key2') },
+ ];
+
+ expect(getMostRecentKek({ keyEncryptionKeys })).to.eql({
+ version: '3',
+ key: Buffer.from('key3'),
+ });
+ });
+
+ test('when no KEK is found, an error is thrown', () => {
+ expect(() => getMostRecentKek({ keyEncryptionKeys: undefined })).toThrow(
+ createKekRequiredError(),
+ );
+ expect(() => getMostRecentKek({ keyEncryptionKeys: [] })).toThrow(createKekRequiredError());
+ });
+ });
+
+ describe('getKekByVersion', () => {
+ test('given a version, the KEK with the matching version is returned', () => {
+ const keyEncryptionKeys = [
+ { version: '1', key: Buffer.from('key1') },
+ { version: '3', key: Buffer.from('key3') },
+ { version: '2', key: Buffer.from('key2') },
+ ];
+
+ expect(getKekByVersion({ keyEncryptionKeys, version: '2' })).to.eql({
+ version: '2',
+ key: Buffer.from('key2'),
+ });
+ });
+
+ test('when no KEK is found, an error is thrown', () => {
+ expect(() => getKekByVersion({ keyEncryptionKeys: [], version: '2' })).toThrow(
+ createKekNotFoundError(),
+ );
+ expect(() => getKekByVersion({ keyEncryptionKeys: undefined, version: '2' })).toThrow(
+ createKekNotFoundError(),
+ );
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.models.ts b/apps/papra-server/src/modules/storage/encryption/storage-encryption.models.ts
similarity index 56%
rename from apps/papra-server/src/modules/documents/storage/encryption/document-encryption.models.ts
rename to apps/papra-server/src/modules/storage/encryption/storage-encryption.models.ts
index 1279c555..7881117d 100644
--- a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.models.ts
+++ b/apps/papra-server/src/modules/storage/encryption/storage-encryption.models.ts
@@ -1,45 +1,38 @@
+import type { StorageKeyEncryptionKey } from '../storage.types';
import { Buffer } from 'node:buffer';
import crypto from 'node:crypto';
-import { decrypt, encrypt } from '../../../shared/crypto/encryption';
-import { createError } from '../../../shared/errors/errors';
-import { isNil } from '../../../shared/utils';
-import { WRAPPED_ENCRYPTION_KEY_ENCODING } from './document-encryption.constants';
-import {
- createDocumentKekNotFoundError,
- createDocumentKekRequiredError,
-} from './document-encryptions.errors';
+import { decrypt, encrypt } from '../../shared/crypto/encryption';
+import { createError } from '../../shared/errors/errors';
+import { isNil } from '../../shared/utils';
+import { WRAPPED_ENCRYPTION_KEY_ENCODING } from './storage-encryption.constants';
+import { createKekNotFoundError, createKekRequiredError } from './storage-encryption.errors';
-type DocumentKeyEncryptionKey = {
- version: string;
- key: Buffer;
-};
-
-export function getMostRecentDocumentKek({
- documentKeyEncryptionKeys = [],
+export function getMostRecentKek({
+ keyEncryptionKeys = [],
}: {
- documentKeyEncryptionKeys?: DocumentKeyEncryptionKey[];
-}): DocumentKeyEncryptionKey {
- const sortedKeys = documentKeyEncryptionKeys.sort((a, b) => a.version.localeCompare(b.version));
+ keyEncryptionKeys?: StorageKeyEncryptionKey[];
+}): StorageKeyEncryptionKey {
+ const sortedKeys = keyEncryptionKeys.sort((a, b) => a.version.localeCompare(b.version));
const mostRecentKey = sortedKeys[sortedKeys.length - 1];
if (isNil(mostRecentKey)) {
- throw createDocumentKekRequiredError();
+ throw createKekRequiredError();
}
return mostRecentKey;
}
export function getKekByVersion({
- documentKeyEncryptionKeys = [],
+ keyEncryptionKeys = [],
version,
}: {
- documentKeyEncryptionKeys?: DocumentKeyEncryptionKey[];
+ keyEncryptionKeys?: StorageKeyEncryptionKey[];
version: string;
-}): DocumentKeyEncryptionKey {
- const kek = documentKeyEncryptionKeys.find((kek) => kek.version === version);
+}): StorageKeyEncryptionKey {
+ const kek = keyEncryptionKeys.find((kek) => kek.version === version);
if (isNil(kek)) {
- throw createDocumentKekNotFoundError();
+ throw createKekNotFoundError();
}
return kek;
@@ -54,7 +47,7 @@ export function wrapEncryptionKey({
kek,
}: {
encryptionKey: Buffer;
- kek: DocumentKeyEncryptionKey;
+ kek: StorageKeyEncryptionKey;
}): string {
try {
return encrypt({ key: kek.key, value: encryptionKey }).toString(
@@ -76,7 +69,7 @@ export function unwrapEncryptionKey({
kek,
}: {
wrappedEncryptionKey: string;
- kek: DocumentKeyEncryptionKey;
+ kek: StorageKeyEncryptionKey;
}): Buffer {
try {
return decrypt({
diff --git a/apps/papra-server/src/modules/storage/encryption/storage-encryption.schemas.models.test.ts b/apps/papra-server/src/modules/storage/encryption/storage-encryption.schemas.models.test.ts
new file mode 100644
index 00000000..130e74d6
--- /dev/null
+++ b/apps/papra-server/src/modules/storage/encryption/storage-encryption.schemas.models.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, test } from 'vitest';
+import { areStorageKeyEncryptionKeysUnique } from './storage-encryption.schemas.models';
+
+describe('storage-encryption schemas models', () => {
+ describe('areStorageKeyEncryptionKeysUnique', () => {
+ test('same versions should return false, different versions should return true', () => {
+ expect(
+ areStorageKeyEncryptionKeysUnique([{ version: '1' }, { version: '2' }, { version: '3' }]),
+ ).toBe(true);
+
+ expect(
+ areStorageKeyEncryptionKeysUnique([{ version: '1' }, { version: '2' }, { version: '1' }]),
+ ).toBe(false);
+
+ expect(areStorageKeyEncryptionKeysUnique([])).toBe(true);
+ expect(areStorageKeyEncryptionKeysUnique([{ version: '1' }])).toBe(true);
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/storage/encryption/storage-encryption.schemas.models.ts b/apps/papra-server/src/modules/storage/encryption/storage-encryption.schemas.models.ts
new file mode 100644
index 00000000..0a5b3689
--- /dev/null
+++ b/apps/papra-server/src/modules/storage/encryption/storage-encryption.schemas.models.ts
@@ -0,0 +1,3 @@
+export function areStorageKeyEncryptionKeysUnique(keys: { version: string }[]) {
+ return keys.length === new Set(keys.map((k) => k.version)).size;
+}
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.test.ts b/apps/papra-server/src/modules/storage/encryption/storage-encryption.schemas.test.ts
similarity index 78%
rename from apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.test.ts
rename to apps/papra-server/src/modules/storage/encryption/storage-encryption.schemas.test.ts
index c3c115e2..0e4d0c7d 100644
--- a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.test.ts
+++ b/apps/papra-server/src/modules/storage/encryption/storage-encryption.schemas.test.ts
@@ -2,14 +2,14 @@ import { Buffer } from 'node:buffer';
import * as v from 'valibot';
import { describe, expect, test } from 'vitest';
-import { coercedDocumentKeyEncryptionKeysListSchema } from './document-encryption.schemas';
+import { coercedStorageKeyEncryptionKeysListSchema } from './storage-encryption.schemas';
-describe('document-encryption schemas', () => {
- describe('documentKeyEncryptionKeysSchema', () => {
+describe('storage-encryption schemas', () => {
+ describe('storageKeyEncryptionKeysSchema', () => {
test('the user can provide a comma separated list of 32 bytes long hex strings env variable', () => {
expect(
v.parse(
- coercedDocumentKeyEncryptionKeysListSchema,
+ coercedStorageKeyEncryptionKeysListSchema,
'1:0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c,2:abdc13ff846337ef514a62d7d2cd2aa3b517d957ab7c825b8de0c7678f17a843',
),
).to.eql([
@@ -33,7 +33,7 @@ describe('document-encryption schemas', () => {
test('versions should be unique', () => {
expect(() =>
v.parse(
- coercedDocumentKeyEncryptionKeysListSchema,
+ coercedStorageKeyEncryptionKeysListSchema,
'1:0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c,1:abdc13ff846337ef514a62d7d2cd2aa3b517d957ab7c825b8de0c7678f17a843',
),
).toThrow('The keys must have unique versions');
@@ -42,7 +42,7 @@ describe('document-encryption schemas', () => {
test('the user can provide a single 32 bytes long hex string env variable', () => {
expect(
v.parse(
- coercedDocumentKeyEncryptionKeysListSchema,
+ coercedStorageKeyEncryptionKeysListSchema,
'0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c',
),
).to.eql([
@@ -59,7 +59,7 @@ describe('document-encryption schemas', () => {
test('the user can provide a single versioned 32 bytes long hex string env variable', () => {
expect(
v.parse(
- coercedDocumentKeyEncryptionKeysListSchema,
+ coercedStorageKeyEncryptionKeysListSchema,
'42:0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c',
),
).to.eql([
@@ -74,15 +74,15 @@ describe('document-encryption schemas', () => {
});
test('no keys provided should not raise an error', () => {
- expect(v.parse(coercedDocumentKeyEncryptionKeysListSchema, undefined)).to.eql(undefined);
+ expect(v.parse(coercedStorageKeyEncryptionKeysListSchema, undefined)).to.eql(undefined);
});
test('keys should be 32 bytes long hex strings', () => {
- expect(() => v.parse(coercedDocumentKeyEncryptionKeysListSchema, '0deba553')).to.throw();
+ expect(() => v.parse(coercedStorageKeyEncryptionKeysListSchema, '0deba553')).to.throw();
expect(() =>
v.parse(
- coercedDocumentKeyEncryptionKeysListSchema,
+ coercedStorageKeyEncryptionKeysListSchema,
// 33 bytes long hex string
'0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c8',
),
@@ -90,7 +90,7 @@ describe('document-encryption schemas', () => {
expect(() =>
v.parse(
- coercedDocumentKeyEncryptionKeysListSchema,
+ coercedStorageKeyEncryptionKeysListSchema,
// 32 bytes long but not a hex string
'Zdeba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c',
),
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.ts b/apps/papra-server/src/modules/storage/encryption/storage-encryption.schemas.ts
similarity index 68%
rename from apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.ts
rename to apps/papra-server/src/modules/storage/encryption/storage-encryption.schemas.ts
index 04afa78d..c59c89bd 100644
--- a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.ts
+++ b/apps/papra-server/src/modules/storage/encryption/storage-encryption.schemas.ts
@@ -1,15 +1,15 @@
import { Buffer } from 'node:buffer';
import * as v from 'valibot';
-import { areDocumentKeyEncryptionKeysUnique } from './document-encryption.schemas.models';
+import { areStorageKeyEncryptionKeysUnique } from './storage-encryption.schemas.models';
-const documentKeyEncryptionKeySchema = v.object({
+const storageKeyEncryptionKeySchema = v.object({
version: v.string(),
key: v.pipe(v.instance(Buffer), v.length(32)),
});
-const documentKeyEncryptionKeyListSchema = v.pipe(
- v.array(documentKeyEncryptionKeySchema),
- v.check((keys) => areDocumentKeyEncryptionKeysUnique(keys), 'The keys must have unique versions'),
+const storageKeyEncryptionKeyListSchema = v.pipe(
+ v.array(storageKeyEncryptionKeySchema),
+ v.check((keys) => areStorageKeyEncryptionKeysUnique(keys), 'The keys must have unique versions'),
);
const versionedHexKeySchema = v.pipe(
@@ -34,16 +34,16 @@ const versionedHexKeySchema = v.pipe(
})),
);
-export const coercedDocumentKeyEncryptionKeysListSchema = v.optional(
+export const coercedStorageKeyEncryptionKeysListSchema = v.optional(
v.union(
[
- documentKeyEncryptionKeyListSchema,
+ storageKeyEncryptionKeyListSchema,
v.pipe(
v.string(),
v.transform((value) => value.split(',').map((part) => part.trim())),
v.array(versionedHexKeySchema),
v.check(
- (keys) => areDocumentKeyEncryptionKeysUnique(keys),
+ (keys) => areStorageKeyEncryptionKeysUnique(keys),
'The keys must have unique versions',
),
),
diff --git a/apps/papra-server/src/modules/storage/encryption/storage-encryption.services.test.ts b/apps/papra-server/src/modules/storage/encryption/storage-encryption.services.test.ts
new file mode 100644
index 00000000..6de4c322
--- /dev/null
+++ b/apps/papra-server/src/modules/storage/encryption/storage-encryption.services.test.ts
@@ -0,0 +1,75 @@
+import { Buffer } from 'node:buffer';
+import { describe, expect, test } from 'vitest';
+import {
+ collectReadableStreamToString,
+ createReadableStream,
+} from '../../shared/streams/readable-stream';
+import { inMemoryStorageDriverFactory } from '../drivers/memory/memory.storage-driver';
+import { createUnsupportedEncryptionAlgorithmError } from './storage-encryption.errors';
+import { wrapWithEncryptionLayer } from './storage-encryption.services';
+
+const firstKek = { version: '1', key: Buffer.alloc(32, 1) };
+const secondKek = { version: '2', key: Buffer.alloc(32, 2) };
+
+describe('storage-encryption services', () => {
+ test('decrypts a file with the KEK version stored in its encryption context', async () => {
+ const storageDriver = inMemoryStorageDriverFactory();
+ const writer = wrapWithEncryptionLayer({
+ storageDriver,
+ encryptionOptions: {
+ isEncryptionEnabled: true,
+ keyEncryptionKeys: [firstKek],
+ },
+ });
+ const encryptionContext = await writer.saveFile({
+ fileStream: createReadableStream({ content: 'encrypted content' }),
+ fileName: 'test.txt',
+ mimeType: 'text/plain',
+ storageKey: 'test.txt',
+ });
+
+ expect(encryptionContext.fileEncryptionKekVersion).toBe(firstKek.version);
+
+ const reader = wrapWithEncryptionLayer({
+ storageDriver,
+ encryptionOptions: {
+ isEncryptionEnabled: true,
+ keyEncryptionKeys: [firstKek, secondKek],
+ },
+ });
+ const { fileStream } = await reader.getFileStream({
+ storageKey: 'test.txt',
+ ...encryptionContext,
+ });
+
+ await expect(collectReadableStreamToString({ stream: fileStream })).resolves.toBe(
+ 'encrypted content',
+ );
+ });
+
+ test('rejects unsupported encryption algorithms', async () => {
+ const storageDriver = inMemoryStorageDriverFactory();
+ await storageDriver.saveFile({
+ fileStream: createReadableStream({ content: 'stored content' }),
+ fileName: 'test.txt',
+ mimeType: 'text/plain',
+ storageKey: 'test.txt',
+ });
+ const storageService = wrapWithEncryptionLayer({
+ storageDriver,
+ encryptionOptions: {
+ isEncryptionEnabled: false,
+ keyEncryptionKeys: [],
+ },
+ });
+
+ await expect(
+ storageService.getFileStream({
+ storageKey: 'test.txt',
+ fileEncryptionKeyWrapped: 'wrapped-key',
+ fileEncryptionKekVersion: firstKek.version,
+ fileEncryptionAlgorithm: 'unsupported',
+ }),
+ ).rejects.toThrow(createUnsupportedEncryptionAlgorithmError());
+ });
+});
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.services.ts b/apps/papra-server/src/modules/storage/encryption/storage-encryption.services.ts
similarity index 59%
rename from apps/papra-server/src/modules/documents/storage/encryption/document-encryption.services.ts
rename to apps/papra-server/src/modules/storage/encryption/storage-encryption.services.ts
index 1d86eedd..4f66b74e 100644
--- a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.services.ts
+++ b/apps/papra-server/src/modules/storage/encryption/storage-encryption.services.ts
@@ -1,28 +1,25 @@
-import type { Config } from '../../../config/config.types';
-import type { StorageDriver, StorageServices } from '../drivers/drivers.models';
-import {
- createDecryptTransformer,
- createEncryptTransformer,
-} from '../../../shared/crypto/encryption';
-import { isNil } from '../../../shared/utils';
-import { ENCRYPTION_ALGORITHMS } from './document-encryption.constants';
+import type { StorageDriver, StorageService } from '../drivers/drivers.models';
+import type { StorageEncryptionOptions } from '../storage.types';
+import { createDecryptTransformer, createEncryptTransformer } from '../../shared/crypto/encryption';
+import { isNil } from '../../shared/utils';
+import { ENCRYPTION_ALGORITHMS } from './storage-encryption.constants';
import {
createNewEncryptionKey,
getKekByVersion,
- getMostRecentDocumentKek,
+ getMostRecentKek,
unwrapEncryptionKey,
wrapEncryptionKey,
-} from './document-encryption.models';
-import { createUnsupportedEncryptionAlgorithmError } from './document-encryptions.errors';
+} from './storage-encryption.models';
+import { createUnsupportedEncryptionAlgorithmError } from './storage-encryption.errors';
export function wrapWithEncryptionLayer({
storageDriver,
- encryptionConfig,
+ encryptionOptions,
}: {
storageDriver: StorageDriver;
- encryptionConfig: Config['documentsStorage']['encryption'];
-}): StorageServices {
- const { isEncryptionEnabled, documentKeyEncryptionKeys } = encryptionConfig;
+ encryptionOptions: StorageEncryptionOptions;
+}): StorageService {
+ const { isEncryptionEnabled, keyEncryptionKeys } = encryptionOptions;
return {
...storageDriver,
@@ -31,12 +28,10 @@ export function wrapWithEncryptionLayer({
if (!isEncryptionEnabled) {
await storageDriver.saveFile(driverArgs);
- return {}; // No encryption metadata to return
+ return {};
}
- // Create a random 32 bytes encryption key
const encryptionKey = createNewEncryptionKey();
-
const encryptedFileStream = createEncryptTransformer({ key: encryptionKey });
await storageDriver.saveFile({
@@ -44,8 +39,7 @@ export function wrapWithEncryptionLayer({
...rest,
});
- // In order to store the encryption key, we encrypt it with the most recent KEK from the config
- const kek = getMostRecentDocumentKek({ documentKeyEncryptionKeys });
+ const kek = getMostRecentKek({ keyEncryptionKeys });
return {
fileEncryptionKeyWrapped: wrapEncryptionKey({ encryptionKey, kek }),
@@ -66,7 +60,6 @@ export function wrapWithEncryptionLayer({
isNil(fileEncryptionKekVersion) ||
isNil(fileEncryptionAlgorithm)
) {
- // If the file is not encrypted, we return the file stream as is
return { fileStream };
}
@@ -74,8 +67,7 @@ export function wrapWithEncryptionLayer({
throw createUnsupportedEncryptionAlgorithmError();
}
- const kek = getKekByVersion({ documentKeyEncryptionKeys, version: fileEncryptionKekVersion });
-
+ const kek = getKekByVersion({ keyEncryptionKeys, version: fileEncryptionKekVersion });
const encryptionKey = unwrapEncryptionKey({
wrappedEncryptionKey: fileEncryptionKeyWrapped,
kek,
diff --git a/apps/papra-server/src/modules/storage/storage.config.test.ts b/apps/papra-server/src/modules/storage/storage.config.test.ts
new file mode 100644
index 00000000..18a551f6
--- /dev/null
+++ b/apps/papra-server/src/modules/storage/storage.config.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, test } from 'vitest';
+import { createStorageConfig } from './storage.config';
+
+describe('createStorageConfig', () => {
+ test('creates independent definitions for different prefixes and filesystem defaults', () => {
+ const documents = createStorageConfig({
+ envPrefix: 'DOCUMENT_STORAGE',
+ defaultFilesystemRoot: './local-documents',
+ });
+ const artifacts = createStorageConfig({
+ envPrefix: 'TEST_ARTIFACT_STORAGE',
+ defaultFilesystemRoot: './local-artifacts',
+ });
+
+ const getEnvironmentVariableNames = (definition: ReturnType<typeof createStorageConfig>) => [
+ definition.driver.env,
+ definition.drivers.filesystem.root.env,
+ ...Object.values(definition.drivers.s3).map(({ env }) => env),
+ ...Object.values(definition.drivers.azureBlob).map(({ env }) => env),
+ ];
+
+ expect(getEnvironmentVariableNames(documents)).toEqual([
+ 'DOCUMENT_STORAGE_DRIVER',
+ 'DOCUMENT_STORAGE_FILESYSTEM_ROOT',
+ 'DOCUMENT_STORAGE_S3_ACCESS_KEY_ID',
+ 'DOCUMENT_STORAGE_S3_SECRET_ACCESS_KEY',
+ 'DOCUMENT_STORAGE_S3_BUCKET_NAME',
+ 'DOCUMENT_STORAGE_S3_REGION',
+ 'DOCUMENT_STORAGE_S3_ENDPOINT',
+ 'DOCUMENT_STORAGE_S3_FORCE_PATH_STYLE',
+ 'DOCUMENT_STORAGE_AZURE_BLOB_CONNECTION_STRING',
+ 'DOCUMENT_STORAGE_AZURE_BLOB_ACCOUNT_NAME',
+ 'DOCUMENT_STORAGE_AZURE_BLOB_ACCOUNT_KEY',
+ 'DOCUMENT_STORAGE_AZURE_BLOB_CONTAINER_NAME',
+ ]);
+ expect(getEnvironmentVariableNames(artifacts)).toEqual([
+ 'TEST_ARTIFACT_STORAGE_DRIVER',
+ 'TEST_ARTIFACT_STORAGE_FILESYSTEM_ROOT',
+ 'TEST_ARTIFACT_STORAGE_S3_ACCESS_KEY_ID',
+ 'TEST_ARTIFACT_STORAGE_S3_SECRET_ACCESS_KEY',
+ 'TEST_ARTIFACT_STORAGE_S3_BUCKET_NAME',
+ 'TEST_ARTIFACT_STORAGE_S3_REGION',
+ 'TEST_ARTIFACT_STORAGE_S3_ENDPOINT',
+ 'TEST_ARTIFACT_STORAGE_S3_FORCE_PATH_STYLE',
+ 'TEST_ARTIFACT_STORAGE_AZURE_BLOB_CONNECTION_STRING',
+ 'TEST_ARTIFACT_STORAGE_AZURE_BLOB_ACCOUNT_NAME',
+ 'TEST_ARTIFACT_STORAGE_AZURE_BLOB_ACCOUNT_KEY',
+ 'TEST_ARTIFACT_STORAGE_AZURE_BLOB_CONTAINER_NAME',
+ ]);
+
+ expect(documents.drivers.filesystem.root.default).toBe('./local-documents');
+ expect(artifacts.drivers.filesystem.root.default).toBe('./local-artifacts');
+ expect(documents).not.toBe(artifacts);
+ expect(documents.drivers).not.toBe(artifacts.drivers);
+ });
+});
diff --git a/apps/papra-server/src/modules/storage/storage.config.ts b/apps/papra-server/src/modules/storage/storage.config.ts
new file mode 100644
index 00000000..e542fecc
--- /dev/null
+++ b/apps/papra-server/src/modules/storage/storage.config.ts
@@ -0,0 +1,96 @@
+import type { ConfigDefinition } from 'figue';
+import * as v from 'valibot';
+import { booleanishSchema } from '../config/config.schemas';
+import { storageDriverNames } from './drivers/storage-drivers.registry';
+import { FS_STORAGE_DRIVER_NAME } from './drivers/fs/fs.storage-driver';
+
+export function createStorageConfig({
+ envPrefix,
+ defaultFilesystemRoot,
+}: {
+ envPrefix: string;
+ defaultFilesystemRoot: string;
+}) {
+ return {
+ driver: {
+ doc: `The driver to use for storage, values can be one of: ${storageDriverNames.map((name) => `\`${name}\``).join(', ')}`,
+ schema: v.picklist(storageDriverNames),
+ default: FS_STORAGE_DRIVER_NAME,
+ env: `${envPrefix}_DRIVER`,
+ },
+ drivers: {
+ filesystem: {
+ root: {
+ doc: 'The root directory in which files are stored',
+ schema: v.string(),
+ default: defaultFilesystemRoot,
+ env: `${envPrefix}_FILESYSTEM_ROOT`,
+ },
+ },
+ s3: {
+ accessKeyId: {
+ doc: 'The AWS access key ID for S3',
+ schema: v.string(),
+ default: '',
+ env: `${envPrefix}_S3_ACCESS_KEY_ID`,
+ },
+ secretAccessKey: {
+ doc: 'The AWS secret access key for S3',
+ schema: v.string(),
+ default: '',
+ env: `${envPrefix}_S3_SECRET_ACCESS_KEY`,
+ },
+ bucketName: {
+ doc: 'The S3 bucket name',
+ schema: v.string(),
+ default: '',
+ env: `${envPrefix}_S3_BUCKET_NAME`,
+ },
+ region: {
+ doc: 'The AWS region for S3',
+ schema: v.string(),
+ default: 'auto',
+ env: `${envPrefix}_S3_REGION`,
+ },
+ endpoint: {
+ doc: 'The S3 endpoint',
+ schema: v.optional(v.string()),
+ default: undefined,
+ env: `${envPrefix}_S3_ENDPOINT`,
+ },
+ forcePathStyle: {
+ doc: 'Whether to force path style URLs for S3',
+ schema: booleanishSchema,
+ default: false,
+ env: `${envPrefix}_S3_FORCE_PATH_STYLE`,
+ },
+ },
+ azureBlob: {
+ connectionString: {
+ doc: 'The Azure Blob Storage connection string; when set, account credentials are ignored',
+ schema: v.optional(v.string()),
+ default: undefined,
+ env: `${envPrefix}_AZURE_BLOB_CONNECTION_STRING`,
+ },
+ accountName: {
+ doc: 'The Azure Blob Storage account name',
+ schema: v.string(),
+ default: '',
+ env: `${envPrefix}_AZURE_BLOB_ACCOUNT_NAME`,
+ },
+ accountKey: {
+ doc: 'The Azure Blob Storage account key',
+ schema: v.string(),
+ default: '',
+ env: `${envPrefix}_AZURE_BLOB_ACCOUNT_KEY`,
+ },
+ containerName: {
+ doc: 'The Azure Blob Storage container name',
+ schema: v.string(),
+ default: '',
+ env: `${envPrefix}_AZURE_BLOB_CONTAINER_NAME`,
+ },
+ },
+ },
+ } as const satisfies ConfigDefinition;
+}
diff --git a/apps/papra-server/src/modules/documents/storage/document-storage.errors.ts b/apps/papra-server/src/modules/storage/storage.errors.ts
similarity index 89%
rename from apps/papra-server/src/modules/documents/storage/document-storage.errors.ts
rename to apps/papra-server/src/modules/storage/storage.errors.ts
index 3c1e5fc7..35ebc877 100644
--- a/apps/papra-server/src/modules/documents/storage/document-storage.errors.ts
+++ b/apps/papra-server/src/modules/storage/storage.errors.ts
@@ -1,4 +1,4 @@
-import { createErrorFactory } from '../../shared/errors/errors';
+import { createErrorFactory } from '../shared/errors/errors';
export const createFileNotFoundError = createErrorFactory({
message: 'File not found',
diff --git a/apps/papra-server/src/modules/storage/storage.models.test.ts b/apps/papra-server/src/modules/storage/storage.models.test.ts
new file mode 100644
index 00000000..2206ecc4
--- /dev/null
+++ b/apps/papra-server/src/modules/storage/storage.models.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, test } from 'vitest';
+import { addSuffixToStorageKey } from './storage.models';
+
+describe('storage models', () => {
+ describe('addSuffixToStorageKey', () => {
+ test('given a storage key and a suffix, add the suffix before the file extension', () => {
+ expect(addSuffixToStorageKey({ storageKey: 'file.txt', suffix: '1' })).to.eql('file_1.txt');
+ expect(addSuffixToStorageKey({ storageKey: 'archive.tar.gz', suffix: 'backup' })).to.eql(
+ 'archive.tar_backup.gz',
+ );
+ });
+
+ test('if there is no file extension, add the suffix at the end of the storage key', () => {
+ expect(addSuffixToStorageKey({ storageKey: 'file', suffix: '2' })).to.eql('file_2');
+ expect(addSuffixToStorageKey({ storageKey: 'archive', suffix: 'backup' })).to.eql(
+ 'archive_backup',
+ );
+ });
+
+ test('the suffix can be either a string or a number', () => {
+ expect(addSuffixToStorageKey({ storageKey: 'file.txt', suffix: 2 })).to.eql('file_2.txt');
+ expect(addSuffixToStorageKey({ storageKey: 'file.txt', suffix: '2' })).to.eql('file_2.txt');
+ });
+
+ test('filenames starting with a dot (e.g. .env) are supported', () => {
+ expect(addSuffixToStorageKey({ storageKey: '.env', suffix: 'backup' })).to.eql('.env_backup');
+ expect(addSuffixToStorageKey({ storageKey: '.env.local', suffix: 'backup' })).to.eql(
+ '.env_backup.local',
+ );
+ });
+
+ test('the storage key path can contain directories, the suffix should be added to the file name only', () => {
+ expect(addSuffixToStorageKey({ storageKey: 'path/to/file.txt', suffix: '1' })).to.eql(
+ 'path/to/file_1.txt',
+ );
+ expect(
+ addSuffixToStorageKey({ storageKey: 'path/dir.with.dots/file.txt', suffix: '2' }),
+ ).to.eql('path/dir.with.dots/file_2.txt');
+ });
+
+ test('if the storage key ends with a dot, the suffix should be added before the dot', () => {
+ expect(addSuffixToStorageKey({ storageKey: 'file.', suffix: '1' })).to.eql('file_1.');
+ expect(addSuffixToStorageKey({ storageKey: 'archive.', suffix: 'backup' })).to.eql(
+ 'archive_backup.',
+ );
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/documents/storage/document-storage.models.ts b/apps/papra-server/src/modules/storage/storage.models.ts
similarity index 93%
rename from apps/papra-server/src/modules/documents/storage/document-storage.models.ts
rename to apps/papra-server/src/modules/storage/storage.models.ts
index 5e37b634..50f3b3e1 100644
--- a/apps/papra-server/src/modules/documents/storage/document-storage.models.ts
+++ b/apps/papra-server/src/modules/storage/storage.models.ts
@@ -1,4 +1,4 @@
-export function addSuffixToFileName({
+export function addSuffixToStorageKey({
storageKey,
suffix,
}: {
diff --git a/apps/papra-server/src/modules/storage/storage.services.ts b/apps/papra-server/src/modules/storage/storage.services.ts
new file mode 100644
index 00000000..35c8b806
--- /dev/null
+++ b/apps/papra-server/src/modules/storage/storage.services.ts
@@ -0,0 +1,58 @@
+import type { StorageDriver, StorageDriverFactory, StorageService } from './drivers/drivers.models';
+import type {
+ StorageConfig,
+ StorageDriverOptions,
+ StorageEncryptionOptions,
+} from './storage.types';
+import { AZ_BLOB_STORAGE_DRIVER_NAME } from './drivers/az-blob/az-blob.storage-driver';
+import { FS_STORAGE_DRIVER_NAME } from './drivers/fs/fs.storage-driver';
+import { IN_MEMORY_STORAGE_DRIVER_NAME } from './drivers/memory/memory.storage-driver';
+import { S3_STORAGE_DRIVER_NAME } from './drivers/s3/s3.storage-driver';
+import type {
+ StorageDriverName,
+ StorageDriverOptionsByName,
+} from './drivers/storage-drivers.registry';
+import { getStorageDriverFactory } from './drivers/storage-drivers.registry';
+import { wrapWithEncryptionLayer } from './encryption/storage-encryption.services';
+
+export type { StorageService } from './drivers/drivers.models';
+
+type StorageDriverOptionsResolvers = {
+ [TName in StorageDriverName]: (storageConfig: StorageConfig) => StorageDriverOptionsByName[TName];
+};
+
+const storageDriverOptionsResolvers = {
+ [FS_STORAGE_DRIVER_NAME]: (storageConfig) => storageConfig.drivers.filesystem,
+ [S3_STORAGE_DRIVER_NAME]: (storageConfig) => storageConfig.drivers.s3,
+ [IN_MEMORY_STORAGE_DRIVER_NAME]: () => undefined,
+ [AZ_BLOB_STORAGE_DRIVER_NAME]: (storageConfig) => storageConfig.drivers.azureBlob,
+} satisfies StorageDriverOptionsResolvers;
+
+export function createStorageService({
+ storageConfig,
+ encryptionOptions,
+}: {
+ storageConfig: StorageConfig;
+ encryptionOptions: StorageEncryptionOptions;
+}): StorageService {
+ const { driver: driverName } = storageConfig;
+ const storageDriverFactory = getStorageDriverFactory({
+ driverName,
+ }) as StorageDriverFactory<StorageDriverOptions>;
+
+ const resolveDriverOptions = storageDriverOptionsResolvers[driverName];
+ const driverOptions: StorageDriverOptions = resolveDriverOptions(storageConfig);
+ const storageDriver = storageDriverFactory(driverOptions);
+
+ return createStorageServiceFromDriver({ storageDriver, encryptionOptions });
+}
+
+export function createStorageServiceFromDriver({
+ storageDriver,
+ encryptionOptions,
+}: {
+ storageDriver: StorageDriver;
+ encryptionOptions: StorageEncryptionOptions;
+}): StorageService {
+ return wrapWithEncryptionLayer({ storageDriver, encryptionOptions });
+}
diff --git a/apps/papra-server/src/modules/documents/storage/documents.storage.services.test-utils.ts b/apps/papra-server/src/modules/storage/storage.test-utils.ts
similarity index 51%
rename from apps/papra-server/src/modules/documents/storage/documents.storage.services.test-utils.ts
rename to apps/papra-server/src/modules/storage/storage.test-utils.ts
index 3fc21cc7..6897c5cd 100644
--- a/apps/papra-server/src/modules/documents/storage/documents.storage.services.test-utils.ts
+++ b/apps/papra-server/src/modules/storage/storage.test-utils.ts
@@ -1,14 +1,14 @@
-import { createDocumentStorageServiceFromDriver } from './documents.storage.services';
import { inMemoryStorageDriverFactory } from './drivers/memory/memory.storage-driver';
+import { createStorageServiceFromDriver } from './storage.services';
-export function createInMemoryDocumentStorageServices() {
+export function createInMemoryStorageService() {
const driver = inMemoryStorageDriverFactory();
- const service = createDocumentStorageServiceFromDriver({
+ const service = createStorageServiceFromDriver({
storageDriver: driver,
- encryptionConfig: {
+ encryptionOptions: {
isEncryptionEnabled: false,
- documentKeyEncryptionKeys: [],
+ keyEncryptionKeys: [],
},
});
diff --git a/apps/papra-server/src/modules/storage/storage.types.ts b/apps/papra-server/src/modules/storage/storage.types.ts
new file mode 100644
index 00000000..04f1f2f5
--- /dev/null
+++ b/apps/papra-server/src/modules/storage/storage.types.ts
@@ -0,0 +1,47 @@
+import type { Buffer } from 'node:buffer';
+import type { StorageDriverName } from './drivers/storage-drivers.registry';
+
+export type FilesystemStorageDriverOptions = {
+ root: string;
+};
+
+export type S3StorageDriverOptions = {
+ accessKeyId: string;
+ secretAccessKey: string;
+ bucketName: string;
+ region: string;
+ endpoint?: string;
+ forcePathStyle: boolean;
+};
+
+export type AzureBlobStorageDriverOptions = {
+ connectionString?: string;
+ accountName: string;
+ accountKey: string;
+ containerName: string;
+};
+
+export type StorageDriverOptions =
+ | FilesystemStorageDriverOptions
+ | S3StorageDriverOptions
+ | AzureBlobStorageDriverOptions
+ | undefined;
+
+export type StorageConfig = {
+ driver: StorageDriverName;
+ drivers: {
+ filesystem: FilesystemStorageDriverOptions;
+ s3: S3StorageDriverOptions;
+ azureBlob: AzureBlobStorageDriverOptions;
+ };
+};
+
+export type StorageKeyEncryptionKey = {
+ version: string;
+ key: Buffer;
+};
+
+export type StorageEncryptionOptions = {
+ isEncryptionEnabled: boolean;
+ keyEncryptionKeys?: StorageKeyEncryptionKey[];
+};
diff --git a/apps/papra-server/src/modules/documents/storage/document-storage.usecases.test.ts b/apps/papra-server/src/modules/storage/storage.usecases.test.ts
similarity index 90%
rename from apps/papra-server/src/modules/documents/storage/document-storage.usecases.test.ts
rename to apps/papra-server/src/modules/storage/storage.usecases.test.ts
index c278df60..e6a8617b 100644
--- a/apps/papra-server/src/modules/documents/storage/document-storage.usecases.test.ts
+++ b/apps/papra-server/src/modules/storage/storage.usecases.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, test } from 'vitest';
-import { createUnableToFindAvailableStorageKeyError } from './document-storage.errors';
-import { ensureStorageKeyIsAvailable } from './document-storage.usecases';
+import { createUnableToFindAvailableStorageKeyError } from './storage.errors';
+import { ensureStorageKeyIsAvailable } from './storage.usecases';
-describe('document-storage usecases', () => {
+describe('storage usecases', () => {
describe('ensureStorageKeyIsAvailable', () => {
test('when a given storage key is not already taken, the storage key is returned as is', async () => {
expect(
@@ -10,7 +10,7 @@ describe('document-storage usecases', () => {
initialStorageKey: 'path/to/file.txt',
maxIncrementalSuffixAttempts: 3,
enableRandomSuffixFallback: false,
- documentsStorageService: {
+ storageService: {
fileExists: async () => false,
},
}),
@@ -23,7 +23,7 @@ describe('document-storage usecases', () => {
initialStorageKey: 'path/to/file.txt',
maxIncrementalSuffixAttempts: 3,
enableRandomSuffixFallback: false,
- documentsStorageService: {
+ storageService: {
fileExists: async ({ storageKey }) =>
['path/to/file.txt', 'path/to/file_1.txt'].includes(storageKey),
},
@@ -38,7 +38,7 @@ describe('document-storage usecases', () => {
maxIncrementalSuffixAttempts: 3,
enableRandomSuffixFallback: true,
generateRandomSuffix: () => 'random',
- documentsStorageService: {
+ storageService: {
fileExists: async ({ storageKey }) => storageKey !== 'path/to/file_random.txt',
},
}),
@@ -52,7 +52,7 @@ describe('document-storage usecases', () => {
initialStorageKey: 'path/to/file.txt',
maxIncrementalSuffixAttempts: 3,
enableRandomSuffixFallback: false,
- documentsStorageService: {
+ storageService: {
fileExists: async ({ storageKey }) => {
if (pathsSet.has(storageKey)) {
return true;
@@ -79,7 +79,7 @@ describe('document-storage usecases', () => {
maxIncrementalSuffixAttempts: 3,
enableRandomSuffixFallback: true,
generateRandomSuffix: () => 'random',
- documentsStorageService: {
+ storageService: {
fileExists: async () => true,
},
}),
@@ -93,7 +93,7 @@ describe('document-storage usecases', () => {
initialStorageKey: 'path/to/file.txt',
maxIncrementalSuffixAttempts: 0,
enableRandomSuffixFallback: false,
- documentsStorageService: {
+ storageService: {
fileExists: async () => false,
},
}),
@@ -104,7 +104,7 @@ describe('document-storage usecases', () => {
initialStorageKey: 'path/to/file.txt',
maxIncrementalSuffixAttempts: 0,
enableRandomSuffixFallback: false,
- documentsStorageService: {
+ storageService: {
fileExists: async () => true,
},
}),
diff --git a/apps/papra-server/src/modules/storage/storage.usecases.ts b/apps/papra-server/src/modules/storage/storage.usecases.ts
new file mode 100644
index 00000000..bf5de92d
--- /dev/null
+++ b/apps/papra-server/src/modules/storage/storage.usecases.ts
@@ -0,0 +1,62 @@
+import type { Logger } from '../shared/logger/logger';
+import type { StorageService } from './drivers/drivers.models';
+import { createLogger } from '../shared/logger/logger';
+import { generateRandomString } from '../shared/random/random.services';
+import { createUnableToFindAvailableStorageKeyError } from './storage.errors';
+import { addSuffixToStorageKey } from './storage.models';
+
+export async function ensureStorageKeyIsAvailable({
+ initialStorageKey,
+ maxIncrementalSuffixAttempts,
+ enableRandomSuffixFallback,
+ generateRandomSuffix = () => generateRandomString({ length: 8 }),
+ storageService,
+ logger = createLogger({ namespace: 'ensureStorageKeyIsAvailable' }),
+}: {
+ initialStorageKey: string;
+ maxIncrementalSuffixAttempts: number;
+ enableRandomSuffixFallback: boolean;
+ generateRandomSuffix?: () => string;
+ storageService: Pick<StorageService, 'fileExists'>;
+ logger?: Logger;
+}): Promise<{ storageKey: string }> {
+ let proposedStorageKey = initialStorageKey;
+ let counter = 0;
+
+ const logMeta = { initialStorageKey, maxIncrementalSuffixAttempts, enableRandomSuffixFallback };
+
+ while (counter <= maxIncrementalSuffixAttempts) {
+ const exists = await storageService.fileExists({ storageKey: proposedStorageKey });
+
+ if (!exists) {
+ return { storageKey: proposedStorageKey };
+ }
+
+ logger.warn({ ...logMeta, proposedStorageKey, counter }, 'Storage key is already taken');
+
+ proposedStorageKey = addSuffixToStorageKey({
+ storageKey: initialStorageKey,
+ suffix: counter + 1,
+ });
+ counter++;
+ }
+
+ if (enableRandomSuffixFallback) {
+ const randomSuffix = generateRandomSuffix();
+ proposedStorageKey = addSuffixToStorageKey({
+ storageKey: initialStorageKey,
+ suffix: randomSuffix,
+ });
+
+ logger.warn({ ...logMeta, proposedStorageKey, randomSuffix }, 'Falling back to random suffix');
+
+ const exists = await storageService.fileExists({ storageKey: proposedStorageKey });
+
+ if (!exists) {
+ return { storageKey: proposedStorageKey };
+ }
+ }
+
+ logger.error({ ...logMeta }, 'Unable to find available storage key after all attempts');
+ throw createUnableToFindAvailableStorageKeyError();
+}
diff --git a/apps/papra-server/src/scripts/encrypt-all-documents.script.ts b/apps/papra-server/src/scripts/encrypt-all-documents.script.ts
index a47e8ccb..1a8465ae 100644
--- a/apps/papra-server/src/scripts/encrypt-all-documents.script.ts
+++ b/apps/papra-server/src/scripts/encrypt-all-documents.script.ts
@@ -1,16 +1,20 @@
import process from 'node:process';
import { isNull } from 'drizzle-orm';
import { documentsTable } from '../modules/documents/documents.table';
-import { createDocumentStorageService } from '../modules/documents/storage/documents.storage.services';
-import { encryptAllUnencryptedDocuments } from '../modules/documents/storage/encryption/document-encryption.usecases';
+import { createStorageService } from '../modules/storage/storage.services';
+import { encryptAllUnencryptedDocuments } from '../modules/documents/document-encryption.usecases';
import { isNil } from '../modules/shared/utils';
import { runScriptWithDb } from './commons/run-script';
await runScriptWithDb(
{ scriptName: 'encrypt-all-documents' },
async ({ db, config, logger, isDryRun }) => {
- const documentStorageService = createDocumentStorageService({
- documentStorageConfig: config.documentsStorage,
+ const documentStorageService = createStorageService({
+ storageConfig: config.documentsStorage,
+ encryptionOptions: {
+ isEncryptionEnabled: config.documentsStorage.encryption.isEncryptionEnabled,
+ keyEncryptionKeys: config.documentsStorage.encryption.documentKeyEncryptionKeys,
+ },
});
if (!config.documentsStorage.encryption.isEncryptionEnabled) {
diff --git a/apps/papra-server/src/scripts/migrate-document-storage.script.ts b/apps/papra-server/src/scripts/migrate-document-storage.script.ts
index 4d1ecfba..72449740 100644
--- a/apps/papra-server/src/scripts/migrate-document-storage.script.ts
+++ b/apps/papra-server/src/scripts/migrate-document-storage.script.ts
@@ -9,8 +9,8 @@ import { count, eq } from 'drizzle-orm';
import { createIterator } from '../modules/app/database/database.usecases';
import { parseConfig } from '../modules/config/config';
import { documentsTable } from '../modules/documents/documents.table';
-import { createStorageKey } from '../modules/documents/storage/document-storage.usecases';
-import { createDocumentStorageService } from '../modules/documents/storage/documents.storage.services';
+import { createDocumentStorageKey } from '../modules/documents/document-storage.usecases';
+import { createStorageService } from '../modules/storage/storage.services';
import { ensureBooleanArg } from './commons/args.utils';
import { runScriptWithDb } from './commons/run-script';
@@ -35,11 +35,19 @@ export async function migrateDocumentStorage({
const { config: fromConfig } = await parseConfig({ env: { ...process.env, ...fromEnv } });
const { config: toConfig } = await parseConfig({ env: { ...process.env, ...toEnv } });
- const fromStorageService = createDocumentStorageService({
- documentStorageConfig: fromConfig.documentsStorage,
+ const fromStorageService = createStorageService({
+ storageConfig: fromConfig.documentsStorage,
+ encryptionOptions: {
+ isEncryptionEnabled: fromConfig.documentsStorage.encryption.isEncryptionEnabled,
+ keyEncryptionKeys: fromConfig.documentsStorage.encryption.documentKeyEncryptionKeys,
+ },
});
- const toStorageService = createDocumentStorageService({
- documentStorageConfig: toConfig.documentsStorage,
+ const toStorageService = createStorageService({
+ storageConfig: toConfig.documentsStorage,
+ encryptionOptions: {
+ isEncryptionEnabled: toConfig.documentsStorage.encryption.isEncryptionEnabled,
+ keyEncryptionKeys: toConfig.documentsStorage.encryption.documentKeyEncryptionKeys,
+ },
});
prompts?.intro('Document Storage Migration');
@@ -118,7 +126,7 @@ export async function migrateDocumentStorage({
fileEncryptionAlgorithm,
});
- const { storageKey: newStorageKey } = await createStorageKey({
+ const { storageKey: newStorageKey } = await createDocumentStorageKey({
storagePatternConfig: toConfig.documentsStorage.pattern,
documentId: id,
organizationId,
diff --git a/apps/papra-server/src/start.ts b/apps/papra-server/src/start.ts
index d41d973c..8a71a9f5 100644
--- a/apps/papra-server/src/start.ts
+++ b/apps/papra-server/src/start.ts
@@ -13,7 +13,7 @@ import { getProcessMode } from './modules/app/process.models';
import { createServer } from './modules/app/server';
import { parseConfig } from './modules/config/config';
import { createDocumentSearchServices } from './modules/documents/document-search/document-search.registry';
-import { createDocumentStorageService } from './modules/documents/storage/documents.storage.services';
+import { createStorageService } from './modules/storage/storage.services';
import { createEmailsServices } from './modules/emails/emails.services';
import { createIngestionFolderWatcher } from './modules/ingestion-folders/ingestion-folders.usecases';
import { buildKvStore } from './modules/kv-store/kv-store';
@@ -60,8 +60,12 @@ async function buildServices({ config }: { config: Config }): Promise<GlobalDepe
await ensureLocalDatabaseDirectoryExists({ config });
const { db } = setupDatabase({ ...config.database, shutdownServices });
- const documentsStorageService = createDocumentStorageService({
- documentStorageConfig: config.documentsStorage,
+ const documentsStorageService = createStorageService({
+ storageConfig: config.documentsStorage,
+ encryptionOptions: {
+ isEncryptionEnabled: config.documentsStorage.encryption.isEncryptionEnabled,
+ keyEncryptionKeys: config.documentsStorage.encryption.documentKeyEncryptionKeys,
+ },
});
const taskServices = createTaskServices({ config });
const trackingServices = createTrackingServices({ config, shutdownServices });