Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(storage): add document storage key pattern (#921)

Corentin Thomasset6be6beae9056
diff --git a/.changeset/lemon-houses-guess.md b/.changeset/lemon-houses-guess.md
new file mode 100644
index 00000000..63bb90a5
--- /dev/null
+++ b/.changeset/lemon-houses-guess.md
@@ -0,0 +1,5 @@
+---
+"@papra/app": patch
+---
+
+Added the possibility to customize the document storage path
\ No newline at end of file
diff --git a/apps/papra-server/package.json b/apps/papra-server/package.json
index 4872aef9..c09aab75 100644
--- a/apps/papra-server/package.json
+++ b/apps/papra-server/package.json
@@ -67,6 +67,7 @@
"drizzle-orm": "^0.38.4",
"figue": "catalog:",
"file-type": "^21.3.0",
+ "filenamify": "^7.0.1",
"hono": "^4.10.7",
"lodash-es": "^4.17.21",
"mime-types": "^3.0.1",
diff --git a/apps/papra-server/src/modules/api-keys/api-keys.services.ts b/apps/papra-server/src/modules/api-keys/api-keys.services.ts
index 419d34de..abc9d8a1 100644
--- a/apps/papra-server/src/modules/api-keys/api-keys.services.ts
+++ b/apps/papra-server/src/modules/api-keys/api-keys.services.ts
@@ -1,8 +1,8 @@
-import { generateToken } from '../shared/random/random.services';
+import { generateRandomString } from '../shared/random/random.services';
import { API_KEY_PREFIX, API_KEY_TOKEN_LENGTH } from './api-keys.constants';
export function generateApiToken() {
- const { token } = generateToken({ length: API_KEY_TOKEN_LENGTH });
+ const token = generateRandomString({ length: API_KEY_TOKEN_LENGTH });
return { token: `${API_KEY_PREFIX}_${token}` };
}
diff --git a/apps/papra-server/src/modules/documents/documents.models.test.ts b/apps/papra-server/src/modules/documents/documents.models.test.ts
index f4760fef..20dab2ee 100644
--- a/apps/papra-server/src/modules/documents/documents.models.test.ts
+++ b/apps/papra-server/src/modules/documents/documents.models.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'vitest';
-import { buildOriginalDocumentKey, formatDocumentForApi, isDocumentSizeLimitEnabled, joinStorageKeyParts } from './documents.models';
+import { buildOriginalDocumentKey, ensureSafeFileName, formatDocumentForApi, isDocumentSizeLimitEnabled, joinStorageKeyParts } from './documents.models';
describe('documents models', () => {
describe('joinStorageKeyParts', () => {
@@ -98,4 +98,74 @@ describe('documents models', () => {
});
});
});
+
+ describe('ensureSafeFileName', () => {
+ test('replaces characters that are not allowed in file names with an underscore', () => {
+ expect(ensureSafeFileName('file.txt')).to.eql('file.txt');
+ expect(ensureSafeFileName('fi/le.txt')).to.eql('fi_le.txt');
+ expect(ensureSafeFileName('fi\\le.txt')).to.eql('fi_le.txt');
+ expect(ensureSafeFileName('fi:le.txt')).to.eql('fi_le.txt');
+ expect(ensureSafeFileName('fi*le.txt')).to.eql('fi_le.txt');
+ expect(ensureSafeFileName('fi?le.txt')).to.eql('fi_le.txt');
+ expect(ensureSafeFileName('fi"le.txt')).to.eql('fi_le.txt');
+ expect(ensureSafeFileName('fi<le.txt')).to.eql('fi_le.txt');
+ expect(ensureSafeFileName('fi>le.txt')).to.eql('fi_le.txt');
+ expect(ensureSafeFileName('fi|le.txt')).to.eql('fi_le.txt');
+ });
+
+ test('leading spaces are preserved as they are valid in file names, but trailing spaces are removed', () => {
+ expect(ensureSafeFileName(' file.txt')).to.eql(' file.txt');
+ expect(ensureSafeFileName('file.txt ')).to.eql('file.txt');
+ expect(ensureSafeFileName(' file.txt ')).to.eql(' file.txt');
+ });
+
+ test('leading dots are preserved as they are valid in file names, but trailing dots are removed', () => {
+ expect(ensureSafeFileName('.file.txt')).to.eql('.file.txt');
+ expect(ensureSafeFileName('..file.txt')).to.eql('..file.txt');
+ expect(ensureSafeFileName('file.txt.')).to.eql('file.txt');
+ expect(ensureSafeFileName('.file.txt.')).to.eql('.file.txt');
+ });
+
+ test('reserved file names on Windows are suffixed with an underscore', () => {
+ const reservedFileNames = [
+ 'con',
+ 'prn',
+ 'aux',
+ 'nul',
+ ...Array.from({ length: 9 }, (_, i) => `com${i + 1}`),
+ ...Array.from({ length: 9 }, (_, i) => `lpt${i + 1}`),
+ ];
+
+ for (const reservedFileName of reservedFileNames) {
+ const lower = reservedFileName;
+ const upper = reservedFileName.toUpperCase();
+ const title = upper[0] + lower.slice(1);
+
+ expect(ensureSafeFileName(lower)).to.eql(`${lower}_`);
+ expect(ensureSafeFileName(upper)).to.eql(`${upper}_`);
+ expect(ensureSafeFileName(title)).to.eql(`${title}_`);
+
+ // Ok with extensions
+ expect(ensureSafeFileName(`${lower}.txt`)).to.eql(`${lower}.txt`);
+ expect(ensureSafeFileName(`${upper}.txt`)).to.eql(`${upper}.txt`);
+ expect(ensureSafeFileName(`${title}.txt`)).to.eql(`${title}.txt`);
+ }
+ });
+
+ test('path separators are replaced with underscores to prevent directory traversal', () => {
+ expect(ensureSafeFileName('../file.txt')).to.eql('_file.txt');
+ expect(ensureSafeFileName('..\\file.txt')).to.eql('_file.txt');
+ expect(ensureSafeFileName('..//file.txt')).to.eql('_file.txt');
+ expect(ensureSafeFileName('..\\\\file.txt')).to.eql('_file.txt');
+ expect(ensureSafeFileName('/foo/bar/file.txt')).to.eql('_foo_bar_file.txt');
+ });
+
+ test('edge cases', () => {
+ expect(ensureSafeFileName('')).to.eql('_');
+ expect(ensureSafeFileName('../')).to.eql('_');
+ expect(ensureSafeFileName('../..')).to.eql('_');
+ expect(ensureSafeFileName(' ')).to.eql('_');
+ expect(ensureSafeFileName('...')).to.eql('_');
+ });
+ });
});
diff --git a/apps/papra-server/src/modules/documents/documents.models.ts b/apps/papra-server/src/modules/documents/documents.models.ts
index b80ac102..3f6a998a 100644
--- a/apps/papra-server/src/modules/documents/documents.models.ts
+++ b/apps/papra-server/src/modules/documents/documents.models.ts
@@ -1,5 +1,6 @@
import type { PartialBy } from '@corentinth/chisels';
import type { DbSelectableDocument } from './documents.types';
+import filenamify from 'filenamify';
import { omit } from 'lodash-es';
import { getExtension } from '../shared/files/file-names';
import { generateId } from '../shared/random/ids';
@@ -45,3 +46,7 @@ export function formatDocumentForApi<T extends PartialBy<DbSelectableDocument, '
export function formatDocumentsForApi<T extends PartialBy<DbSelectableDocument, 'content'>>({ documents }: { documents: T[] }) {
return documents.map(document => formatDocumentForApi({ document }));
}
+
+export function ensureSafeFileName(fileName: string) {
+ return filenamify(fileName, { replacement: '_' });
+}
diff --git a/apps/papra-server/src/modules/documents/documents.usecases.ts b/apps/papra-server/src/modules/documents/documents.usecases.ts
index 61fc672c..d48de24d 100644
--- a/apps/papra-server/src/modules/documents/documents.usecases.ts
+++ b/apps/papra-server/src/modules/documents/documents.usecases.ts
@@ -14,6 +14,7 @@ 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 { PassThrough } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { safely } from '@corentinth/chisels';
@@ -33,9 +34,10 @@ import { createTagsRepository } from '../tags/tags.repository';
import { createWebhookRepository } from '../webhooks/webhook.repository';
import { createDocumentActivityRepository } from './document-activity/document-activity.repository';
import { createDocumentAlreadyExistsError, createDocumentNotDeletedError, createDocumentNotFoundError, createDocumentSizeTooLargeError } from './documents.errors';
-import { buildOriginalDocumentKey, generateDocumentId as generateDocumentIdImpl } from './documents.models';
+import { generateDocumentId as generateDocumentIdImpl } from './documents.models';
import { createDocumentsRepository } from './documents.repository';
import { extractDocumentText } from './documents.services';
+import { createStorageKey } from './storage/document-storage.usecases';
type DocumentStorageContext = {
storageKey: string;
@@ -49,6 +51,7 @@ export async function createDocument({
organizationId,
ocrLanguages = [],
isContentExtractionEnabled = true,
+ storagePatternConfig,
documentsRepository,
documentsStorageService,
generateDocumentId = generateDocumentIdImpl,
@@ -69,6 +72,7 @@ export async function createDocument({
organizationId: string;
ocrLanguages?: string[];
isContentExtractionEnabled?: boolean;
+ storagePatternConfig: StoragePatternConfig;
documentsRepository: DocumentsRepository;
documentsStorageService: DocumentStorageService;
generateDocumentId?: () => string;
@@ -85,7 +89,13 @@ export async function createDocument({
const { availableDocumentStorageBytes, maxFileSize } = await getOrganizationStorageLimits({ organizationId, plansRepository, subscriptionsRepository, documentsRepository });
const documentId = generateDocumentId();
- const { originalDocumentStorageKey } = buildOriginalDocumentKey({ documentId, organizationId, fileName });
+ const { storageKey } = await createStorageKey({
+ documentId,
+ documentName: fileName,
+ organizationId,
+ documentsStorageService,
+ storagePatternConfig,
+ });
const { tap: hashStream, getHash } = createSha256HashTransformer();
@@ -117,7 +127,7 @@ export async function createDocument({
const [encryptionMetadata] = await Promise.all([
documentsStorageService.saveFile({
fileStream: outputStream,
- storageKey: originalDocumentStorageKey,
+ storageKey,
mimeType,
fileName,
}),
@@ -136,7 +146,7 @@ export async function createDocument({
fileName,
organizationId,
documentsRepository,
- newDocumentStorageKey: originalDocumentStorageKey,
+ newDocumentStorageKey: storageKey,
tagsRepository,
taggingRulesRepository,
webhookRepository,
@@ -145,7 +155,7 @@ export async function createDocument({
logger,
})
: await createNewDocument({
- newFileStorageContext: { storageKey: originalDocumentStorageKey, ...encryptionMetadata },
+ newFileStorageContext: { storageKey, ...encryptionMetadata },
fileName,
size,
mimeType,
@@ -197,6 +207,7 @@ export function createDocumentCreationUsecase({
webhookRepository: initialDeps.webhookRepository ?? createWebhookRepository({ db }),
documentActivityRepository: initialDeps.documentActivityRepository ?? createDocumentActivityRepository({ db }),
+ storagePatternConfig: initialDeps.storagePatternConfig ?? config.documentsStorage.pattern,
ocrLanguages: initialDeps.ocrLanguages ?? config.documents.ocrLanguages,
isContentExtractionEnabled: initialDeps.isContentExtractionEnabled ?? config.documents.isContentExtractionEnabled,
generateDocumentId: initialDeps.generateDocumentId,
diff --git a/apps/papra-server/src/modules/documents/storage/document-storage.config.ts b/apps/papra-server/src/modules/documents/storage/document-storage.config.ts
index 30eeeba9..adc0a88a 100644
--- a/apps/papra-server/src/modules/documents/storage/document-storage.config.ts
+++ b/apps/papra-server/src/modules/documents/storage/document-storage.config.ts
@@ -6,6 +6,7 @@ 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';
export const documentStorageConfig = {
maxUploadSize: {
@@ -95,4 +96,5 @@ export const documentStorageConfig = {
},
},
encryption: documentEncryptionConfig,
+ pattern: storagePatternConfig,
} as const satisfies ConfigDefinition;
diff --git a/apps/papra-server/src/modules/documents/storage/document-storage.errors.ts b/apps/papra-server/src/modules/documents/storage/document-storage.errors.ts
index 5bef09ce..3c1e5fc7 100644
--- a/apps/papra-server/src/modules/documents/storage/document-storage.errors.ts
+++ b/apps/papra-server/src/modules/documents/storage/document-storage.errors.ts
@@ -11,3 +11,10 @@ export const createFileAlreadyExistsInStorageError = createErrorFactory({
code: 'documents.storage.file_already_exists',
statusCode: 409,
});
+
+export const createUnableToFindAvailableStorageKeyError = createErrorFactory({
+ message: 'Unable to find available storage key',
+ code: 'documents.storage.unable_to_find_available_storage_key',
+ statusCode: 500,
+ isInternal: true,
+});
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
new file mode 100644
index 00000000..d6a2e03f
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/document-storage.models.test.ts
@@ -0,0 +1,36 @@
+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.models.ts b/apps/papra-server/src/modules/documents/storage/document-storage.models.ts
new file mode 100644
index 00000000..3487d76a
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/document-storage.models.ts
@@ -0,0 +1,16 @@
+export function addSuffixToFileName({ storageKey, suffix }: { storageKey: string; suffix: string | number }) {
+ const lastSlashIndex = storageKey.lastIndexOf('/');
+ const dir = lastSlashIndex === -1 ? '' : storageKey.slice(0, lastSlashIndex + 1);
+ const fileName = lastSlashIndex === -1 ? storageKey : storageKey.slice(lastSlashIndex + 1);
+
+ const dotIndex = fileName.lastIndexOf('.');
+ if (dotIndex === -1) {
+ return `${dir}${fileName}_${suffix}`;
+ }
+
+ if (dotIndex === 0) {
+ return `${dir}${fileName}_${suffix}`;
+ }
+
+ return `${dir}${fileName.slice(0, dotIndex)}_${suffix}${fileName.slice(dotIndex)}`;
+}
diff --git a/apps/papra-server/src/modules/documents/storage/document-storage.usecases.test.ts b/apps/papra-server/src/modules/documents/storage/document-storage.usecases.test.ts
new file mode 100644
index 00000000..8a114482
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/document-storage.usecases.test.ts
@@ -0,0 +1,112 @@
+import { describe, expect, test } from 'vitest';
+import { createUnableToFindAvailableStorageKeyError } from './document-storage.errors';
+import { ensureStorageKeyIsAvailable } from './document-storage.usecases';
+
+describe('document-storage usecases', () => {
+ describe('ensureStorageKeyIsAvailable', () => {
+ test('when a given storage key is not already taken, the storage key is returned as is', async () => {
+ expect(
+ await ensureStorageKeyIsAvailable({
+ initialStorageKey: 'path/to/file.txt',
+ maxIncrementalSuffixAttempts: 3,
+ enableRandomSuffixFallback: false,
+ documentsStorageService: {
+ fileExists: async () => false,
+ },
+ }),
+ ).to.eql({ storageKey: 'path/to/file.txt' });
+ });
+
+ test('when the storage key is already taken, add incremental suffixes until an available storage key is found', async () => {
+ expect(
+ await ensureStorageKeyIsAvailable({
+ initialStorageKey: 'path/to/file.txt',
+ maxIncrementalSuffixAttempts: 3,
+ enableRandomSuffixFallback: false,
+ documentsStorageService: {
+ fileExists: async ({ storageKey }) => ['path/to/file.txt', 'path/to/file_1.txt'].includes(storageKey),
+ },
+ }),
+ ).to.eql({ storageKey: 'path/to/file_2.txt' });
+ });
+
+ test('when all incremental suffixes are taken and random suffix fallback is enabled, add a random suffix to find an available storage key', async () => {
+ expect(
+ await ensureStorageKeyIsAvailable({
+ initialStorageKey: 'path/to/file.txt',
+ maxIncrementalSuffixAttempts: 3,
+ enableRandomSuffixFallback: true,
+ generateRandomSuffix: () => 'random',
+ documentsStorageService: {
+ fileExists: async ({ storageKey }) => storageKey !== 'path/to/file_random.txt',
+ },
+ }),
+ ).to.eql({ storageKey: 'path/to/file_random.txt' });
+ });
+
+ test('when all incremental suffixes are taken and random suffix fallback is disabled, throw an error', async () => {
+ const pathsSet = new Set<string>([]);
+
+ const args = {
+ initialStorageKey: 'path/to/file.txt',
+ maxIncrementalSuffixAttempts: 3,
+ enableRandomSuffixFallback: false,
+ documentsStorageService: {
+ fileExists: async ({ storageKey }) => {
+ if (pathsSet.has(storageKey)) {
+ return true;
+ }
+ pathsSet.add(storageKey);
+ return false;
+ },
+ },
+ } as Parameters<typeof ensureStorageKeyIsAvailable>[0];
+
+ expect(await ensureStorageKeyIsAvailable(args)).to.eql({ storageKey: 'path/to/file.txt' });
+ expect(await ensureStorageKeyIsAvailable(args)).to.eql({ storageKey: 'path/to/file_1.txt' });
+ expect(await ensureStorageKeyIsAvailable(args)).to.eql({ storageKey: 'path/to/file_2.txt' });
+ expect(await ensureStorageKeyIsAvailable(args)).to.eql({ storageKey: 'path/to/file_3.txt' });
+ await expect(ensureStorageKeyIsAvailable(args)).rejects.toThrow(createUnableToFindAvailableStorageKeyError());
+ });
+
+ test('if even the random suffix fallback is taken, throw an error', async () => {
+ await expect(
+ ensureStorageKeyIsAvailable({
+ initialStorageKey: 'path/to/file.txt',
+ maxIncrementalSuffixAttempts: 3,
+ enableRandomSuffixFallback: true,
+ generateRandomSuffix: () => 'random',
+ documentsStorageService: {
+ fileExists: async () => true,
+ },
+ }),
+ ).rejects.toThrow(createUnableToFindAvailableStorageKeyError());
+ });
+
+ describe('the incremental suffix behavior can be disabled by setting a maximum number of incremental suffix attempts of 0', () => {
+ test('the initial storage key is returned as is if it is available, but an error is thrown if it is taken and random suffix fallback is disabled', async () => {
+ expect(
+ await ensureStorageKeyIsAvailable({
+ initialStorageKey: 'path/to/file.txt',
+ maxIncrementalSuffixAttempts: 0,
+ enableRandomSuffixFallback: false,
+ documentsStorageService: {
+ fileExists: async () => false,
+ },
+ }),
+ ).to.eql({ storageKey: 'path/to/file.txt' });
+
+ await expect(
+ ensureStorageKeyIsAvailable({
+ initialStorageKey: 'path/to/file.txt',
+ maxIncrementalSuffixAttempts: 0,
+ enableRandomSuffixFallback: false,
+ documentsStorageService: {
+ fileExists: async () => true,
+ },
+ }),
+ ).rejects.toThrow(createUnableToFindAvailableStorageKeyError());
+ });
+ });
+ });
+});
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
new file mode 100644
index 00000000..d56931b8
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/document-storage.usecases.ts
@@ -0,0 +1,102 @@
+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,
+ now = new Date(),
+ documentsStorageService,
+}: {
+ storagePatternConfig: StoragePatternConfig;
+ documentId: string;
+ documentName: string;
+ organizationId: string;
+ now?: Date;
+ documentsStorageService: Pick<DocumentStorageService, 'fileExists'>;
+}) {
+ 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,
+ });
+
+ return { storageKey };
+}
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
new file mode 100644
index 00000000..d40a6d24
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.config.ts
@@ -0,0 +1,45 @@
+import type { AppConfigDefinition } from '../../../config/config.types';
+import { z } from 'zod';
+import { booleanishSchema } from '../../../config/config.schemas';
+import { isStoragePatternValid } from './storage-pattern.usecases';
+
+export const storagePatternConfig = {
+ useLegacyStorageKeyDefinitionSystem: {
+ doc: 'Whether to use the legacy storage key definition system, which generates storage keys in the format: {{organization.id}}/originals/{{document.id}}. When set to true, no storage key pattern will be used, nor will the incremental suffix or random suffix fallback mechanisms be enabled, as the storage key will be generated using the legacy system.',
+ schema: booleanishSchema,
+ default: true,
+ env: 'DOCUMENT_STORAGE_USE_LEGACY_STORAGE_KEY_DEFINITION_SYSTEM',
+ showInDocumentation: false, // TODO: enable when released
+ },
+ maxIncrementalSuffixAttempts: {
+ doc: 'How many incremental suffixes to try when a storage key is already taken (e.g. file_1.txt, file_2.txt, ...). Set to 0 to skip incremental suffixes entirely.',
+ schema: z.coerce.number().int().nonnegative(),
+ default: 9, // This allows for a total of 10 attempts (the initial key + 9 incremental suffixes)
+ env: 'DOCUMENT_STORAGE_PATTERN_MAX_INCREMENTAL_SUFFIX_ATTEMPTS',
+ showInDocumentation: false, // TODO: enable when released
+ },
+ enableRandomSuffixFallback: {
+ doc: 'Whether to enable a fallback mechanism that adds a random alphanumeric 8-character suffix to the storage key if all incremental suffix attempts are exhausted.',
+ schema: booleanishSchema,
+ default: true,
+ env: 'DOCUMENT_STORAGE_PATTERN_ENABLE_RANDOM_SUFFIX_FALLBACK',
+ showInDocumentation: false, // TODO: enable when released
+ },
+ storageKeyPattern: {
+ doc: 'The pattern to use for generating storage keys. This can include expressions enclosed in double curly braces (e.g. {{document.name}}) that will be evaluated at runtime.',
+ schema: z
+ .string()
+ .superRefine((storageKeyPattern, ctx) => {
+ const result = isStoragePatternValid({ storageKeyPattern });
+ if (!result.isValid) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: result.error.message,
+ });
+ }
+ }),
+ default: '{{organization.id}}/{{document.name}}',
+ env: 'DOCUMENT_STORAGE_KEY_PATTERN',
+ showInDocumentation: false, // TODO: enable when released
+ },
+} as const satisfies AppConfigDefinition;
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
new file mode 100644
index 00000000..0fa7f72e
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.constants.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, test } from 'vitest';
+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', () => {
+ describe('dummy document id', () => {
+ test('a valid, hard-coded document id for document storage pattern validation', () => {
+ expect(DUMMY_DOCUMENT_ID).to.match(DOCUMENT_ID_REGEX);
+ });
+ });
+
+ describe('dummy organization id', () => {
+ test('a valid, hard-coded organization id for document storage pattern validation', () => {
+ expect(DUMMY_ORGANIZATION_ID).to.match(ORGANIZATION_ID_REGEX);
+ });
+ });
+});
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
new file mode 100644
index 00000000..016d9a3e
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.constants.ts
@@ -0,0 +1,2 @@
+export const DUMMY_DOCUMENT_ID = 'doc_000000000000000000000000';
+export const DUMMY_ORGANIZATION_ID = 'org_000000000000000000000000';
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
new file mode 100644
index 00000000..391420df
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.definitions.ts
@@ -0,0 +1,58 @@
+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';
+
+export const expressionsDefinitions: Record<string, (context: StoragePatternInterpolationContext) => string> = {
+ 'document.id': context => context.documentId,
+ 'document.name': context => ensureSafeFileName(context.documentName),
+ 'organization.id': context => context.organizationId,
+ 'currentDate': context => context.now.toISOString(),
+ 'random': () => generateRandomString({ length: 8 }),
+ ...[
+ 'yyyy',
+ 'MM',
+ 'dd',
+ 'HH',
+ 'mm',
+ 'ss',
+ 'SSS',
+ ].reduce((acc, token) => ({
+ ...acc,
+ [`currentDate.${token}`]: (context: StoragePatternInterpolationContext) => formatDate(context.now, `{${token}}`),
+ }), {}),
+};
+
+export const expressionTransformers: Record<string, StoragePatternExpressionTransformer> = {
+ uppercase: ({ value }) => String(value).toUpperCase(),
+ lowercase: ({ value }) => String(value).toLowerCase(),
+ formatDate: ({ value, args }) => {
+ if (!(value instanceof Date || typeof value === 'string' || typeof value === 'number')) {
+ throw new TypeError(`Value must be a date or a date-ish string, got: ${String(value)}`);
+ }
+
+ const date = new Date(value);
+
+ if (!isValidDate(date)) {
+ throw new Error(`Invalid date value: ${String(value)}`);
+ }
+
+ const format = args?.[0] ?? '{yyyy}-{MM}-{dd}';
+
+ return formatDate(date, format);
+ },
+
+ padStart: ({ value, args }) => {
+ const targetLength = Number.parseInt(args?.[0] ?? '0', 10);
+ const padString = args?.[1] ?? ' ';
+
+ return String(value).padStart(targetLength, padString);
+ },
+
+ padEnd: ({ value, args }) => {
+ const targetLength = Number.parseInt(args?.[0] ?? '0', 10);
+ const padString = args?.[1] ?? ' ';
+
+ return String(value).padEnd(targetLength, padString);
+ },
+};
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
new file mode 100644
index 00000000..b6e35e79
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.models.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, test } from 'vitest';
+import { tokenizeStringArguments } from './storage-pattern.models';
+
+describe('storage-pattern models', () => {
+ describe('tokenizeStringArguments', () => {
+ test('given a string of space-separated arguments, split them into an array', () => {
+ expect(tokenizeStringArguments({ argumentsString: 'arg1 arg2 arg3' })).to.eql(['arg1', 'arg2', 'arg3']);
+ expect(tokenizeStringArguments({ argumentsString: 'arg1' })).to.eql(['arg1']);
+ });
+
+ test('arguments can be wrapped in quotes to include spaces', () => {
+ expect(tokenizeStringArguments({ argumentsString: 'arg1 "arg 2 with spaces" arg3' })).to.eql(['arg1', 'arg 2 with spaces', 'arg3']);
+ expect(tokenizeStringArguments({ argumentsString: '"arg with spaces"' })).to.eql(['arg with spaces']);
+ expect(tokenizeStringArguments({ argumentsString: '"arg" "with spaces"' })).to.eql(['arg', 'with spaces']);
+ expect(tokenizeStringArguments({ argumentsString: '"arg""with spaces"' })).to.eql(['arg', 'with spaces']);
+ });
+
+ test('quotes can be escaped with a backslash', () => {
+ expect(tokenizeStringArguments({ argumentsString: 'arg1 "arg with \\"escaped quotes\\"" arg3' })).to.eql(['arg1', 'arg with "escaped quotes"', 'arg3']);
+ expect(tokenizeStringArguments({ argumentsString: '"arg with \\"escaped quotes\\""' })).to.eql(['arg with "escaped quotes"']);
+ expect(tokenizeStringArguments({ argumentsString: '\\"' })).to.eql(['"']);
+ expect(tokenizeStringArguments({ argumentsString: '\\"arg' })).to.eql(['"arg']);
+ });
+
+ test('empty or undefined argument string returns an empty array', () => {
+ expect(tokenizeStringArguments({ argumentsString: '' })).to.eql([]);
+ expect(tokenizeStringArguments({ argumentsString: undefined })).to.eql([]);
+ });
+
+ test('multiple spaces between arguments are ignored', () => {
+ expect(tokenizeStringArguments({ argumentsString: 'arg1 arg2 arg3' })).to.eql(['arg1', 'arg2', 'arg3']);
+ expect(tokenizeStringArguments({ argumentsString: ' arg1 arg2 arg3 ' })).to.eql(['arg1', 'arg2', 'arg3']);
+ });
+ });
+});
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
new file mode 100644
index 00000000..86b09e56
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.models.ts
@@ -0,0 +1,51 @@
+import { isNilOrEmptyString } from '../../../shared/utils';
+
+export function tokenizeStringArguments({ argumentsString }: { argumentsString: string | undefined }): string[] {
+ if (isNilOrEmptyString(argumentsString)) {
+ return [];
+ }
+
+ const args: string[] = [];
+ let current = '';
+ let inQuotes = false;
+ let i = 0;
+
+ while (i < argumentsString.length) {
+ const char = argumentsString[i];
+
+ // Escaped quotes
+ if (char === '\\' && i + 1 < argumentsString.length && argumentsString[i + 1] === '"') {
+ current += '"';
+ i += 2;
+ continue;
+ }
+
+ if (char === '"') {
+ if (!inQuotes && current.length > 0) {
+ args.push(current);
+ current = '';
+ }
+ inQuotes = !inQuotes;
+ i++;
+ continue;
+ }
+
+ if (char === ' ' && !inQuotes) {
+ if (current.length > 0) {
+ args.push(current);
+ current = '';
+ }
+ i++;
+ continue;
+ }
+
+ current += char;
+ i++;
+ }
+
+ if (current.length > 0) {
+ args.push(current);
+ }
+
+ return args;
+}
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
new file mode 100644
index 00000000..24fe2175
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.types.ts
@@ -0,0 +1,12 @@
+import type { Config } from '../../../config/config.types';
+
+export type StoragePatternInterpolationContext = {
+ documentId: string;
+ documentName: string;
+ organizationId: string;
+ now: Date;
+};
+
+export type StoragePatternExpressionTransformer = (args: { value: unknown; args?: string[] }) => string;
+
+export type StoragePatternConfig = Config['documentsStorage']['pattern'];
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
new file mode 100644
index 00000000..b29e13ac
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.usecases.test.ts
@@ -0,0 +1,120 @@
+import type { StoragePatternInterpolationContext } from './storage-pattern.types';
+import { describe, expect, test } from 'vitest';
+import { buildStorageKey, isStoragePatternValid } from './storage-pattern.usecases';
+
+describe('storage-pattern usecases', () => {
+ describe('buildStorageKey', () => {
+ const context: StoragePatternInterpolationContext = {
+ documentId: 'doc_012345678901234567890123',
+ documentName: 'My Document.pdf',
+ organizationId: 'org_012345678901234567890123',
+ now: new Date('2025-05-15T12:34:56.789Z'),
+ };
+
+ describe('given a storage key pattern, returns a function that can interpolate it with a context', () => {
+ const patterns = [
+ {
+ label: 'simple pattern with no transformers',
+ storageKeyPattern: '{{organization.id}}/{{document.name}}',
+ expected: 'org_012345678901234567890123/My Document.pdf',
+ },
+ {
+ label: 'patterns can have spaces around expressions',
+ storageKeyPattern: '{{ organization.id }}/{{document.name }}',
+ expected: 'org_012345678901234567890123/My Document.pdf',
+ },
+ {
+ label: 'pattern with a transformer',
+ storageKeyPattern: '{{organization.id}}/{{document.name | uppercase}}',
+ expected: 'org_012345678901234567890123/MY DOCUMENT.PDF',
+ },
+ {
+ label: 'transformers can have spaces around them',
+ storageKeyPattern: '{{organization.id}}/{{document.name | uppercase }}',
+ expected: 'org_012345678901234567890123/MY DOCUMENT.PDF',
+ },
+ {
+ label: 'transformers can have arguments',
+ storageKeyPattern: '{{ currentDate | formatDate {yyyy} }}',
+ expected: '2025',
+ },
+ {
+ label: 'transformers can end with curly braces if they have arguments',
+ storageKeyPattern: '{{currentDate | formatDate {yyyy}-{MM}-{dd}}}',
+ expected: '2025-05-15',
+ },
+ {
+ label: 'transformers arguments can use quotes for spaces',
+ storageKeyPattern: '{{currentDate | formatDate "{yyyy} {MM} {dd}"}}',
+ expected: '2025 05 15',
+ },
+ {
+ label: 'transformers arguments can have escaped quotes',
+ storageKeyPattern: '{{currentDate | formatDate "{yyyy} \\"{MM}\\" {dd}"}}',
+ expected: '2025 "05" 15',
+ },
+ {
+ label: 'transformers can have multiple arguments',
+ storageKeyPattern: '{{document.id | padStart 30 0}}',
+ expected: '00doc_012345678901234567890123',
+ },
+ {
+ label: 'transformers multiple arguments can be quoted',
+ storageKeyPattern: '{{document.id | padStart "40" "hello \\"world\\""}}',
+ expected: 'hello "worlddoc_012345678901234567890123',
+ },
+ {
+ label: 'unclosed quotes are accepted and considered part of the argument',
+ storageKeyPattern: '{{currentDate | formatDate "{yyyy} {MM} {dd}}}',
+ expected: '2025 05 15',
+ },
+ ];
+
+ for (const { label, storageKeyPattern, expected: storageKey } of patterns) {
+ test(label, () => {
+ expect(
+ buildStorageKey({ storageKeyPattern, ...context }),
+ ).to.eql(
+ { storageKey },
+ );
+ });
+ }
+ });
+
+ test('unrecognized expressions throw an error', () => {
+ expect(
+ () => buildStorageKey({ storageKeyPattern: '{{unknown.expression}}/{{document.name}}', ...context }),
+ ).to.throw('Unknown expression: unknown.expression');
+ });
+
+ test('unrecognized transformers throw an error', () => {
+ expect(
+ () => buildStorageKey({ storageKeyPattern: '{{document.name | unknownTransformer}}', ...context }),
+ ).to.throw('Unknown transformer: unknownTransformer');
+ });
+
+ test('transformers without arguments called with arguments are ok', () => {
+ expect(
+ buildStorageKey({ storageKeyPattern: '{{document.name | uppercase "unexpected argument"}}', ...context }),
+ ).to.eql({ storageKey: 'MY DOCUMENT.PDF' });
+ });
+ });
+
+ describe('isStoragePatternValid', () => {
+ test('a pattern is invalid if it contains an unrecognized expression', () => {
+ expect(isStoragePatternValid({ storageKeyPattern: '{{unknown.expression}}/{{document.name}}' })).to.eql({ isValid: false, error: new Error('Unknown expression: unknown.expression') });
+ });
+
+ test('a pattern is invalid if it contains an unrecognized transformer', () => {
+ expect(isStoragePatternValid({ storageKeyPattern: '{{document.name | unknownTransformer}}' })).to.eql({ isValid: false, error: new Error('Unknown transformer: unknownTransformer') });
+ });
+
+ test('a pattern is valid if it only contains recognized expressions and transformers', () => {
+ expect(isStoragePatternValid({ storageKeyPattern: '{{organization.id}}/{{document.name | uppercase}}' })).to.eql({ isValid: true });
+ });
+
+ test('a pattern is invalid if it ends with a slash', () => {
+ expect(isStoragePatternValid({ storageKeyPattern: '{{organization.id}}/{{document.name}}/' })).to.eql({ isValid: false, error: new Error('Pattern cannot end with a slash') });
+ });
+ });
+});
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
new file mode 100644
index 00000000..8332718e
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/patterns/storage-pattern.usecases.ts
@@ -0,0 +1,88 @@
+import type { StoragePatternInterpolationContext } from './storage-pattern.types';
+import { castError } from '@corentinth/chisels';
+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';
+
+export function buildStorageKey({ storageKeyPattern, ...context }: { storageKeyPattern: string } & StoragePatternInterpolationContext) {
+ const storageKey = storageKeyPattern.replace(/\{\{(.*?)\}\}(?!\})/g, (_match, rawExpression) => {
+ if (isNil(rawExpression) || typeof rawExpression !== 'string') {
+ throw new Error('Expression cannot be empty');
+ }
+
+ const [expression, ...transformerParts] = rawExpression.split('|').map(part => part.trim());
+
+ if (isNilOrEmptyString(expression)) {
+ throw new Error('Expression cannot be empty');
+ }
+
+ const expressionExists = expression in expressionsDefinitions;
+
+ if (!expressionExists) {
+ throw new Error(`Unknown expression: ${expression}`);
+ }
+
+ const expressionBuilder = expressionsDefinitions[expression];
+
+ if (!expressionBuilder) {
+ // This should never happen because of the check above, but for type safety
+ throw new Error(`No builder found for expression: ${expression}`);
+ }
+
+ const baseValue = expressionBuilder(context);
+
+ if (transformerParts.length === 0) {
+ return String(baseValue);
+ }
+
+ return transformerParts.reduce((value, transformerPart) => {
+ const [transformerRawName, ...transformerArgsParts] = transformerPart.split(' ');
+
+ const transformerName = transformerRawName?.trim();
+ const argumentsString = transformerArgsParts.join(' ').trim();
+
+ const transformer = expressionTransformers[transformerName as keyof typeof expressionTransformers];
+
+ if (!transformer) {
+ throw new Error(`Unknown transformer: ${transformerName}`);
+ }
+
+ const transformerArguments = tokenizeStringArguments({ argumentsString });
+
+ return transformer({ value, args: transformerArguments });
+ }, baseValue);
+ });
+
+ return { storageKey };
+}
+
+export function isStoragePatternValid({ storageKeyPattern }: { storageKeyPattern: string }): { isValid: true } | { isValid: false; error: Error } {
+ const endsWithSlash = storageKeyPattern.endsWith('/');
+
+ if (endsWithSlash) {
+ return {
+ isValid: false,
+ error: new Error('Pattern cannot end with a slash'),
+ };
+ }
+
+ try {
+ buildStorageKey({
+ storageKeyPattern,
+ documentId: DUMMY_DOCUMENT_ID,
+ documentName: 'my-document.pdf',
+ organizationId: DUMMY_ORGANIZATION_ID,
+ now: new Date(),
+ });
+
+ return {
+ isValid: true,
+ };
+ } catch (error) {
+ return {
+ isValid: false,
+ error: castError(error),
+ };
+ }
+}
diff --git a/apps/papra-server/src/modules/organizations/organizations.models.ts b/apps/papra-server/src/modules/organizations/organizations.models.ts
index 6cb399d1..51588b2c 100644
--- a/apps/papra-server/src/modules/organizations/organizations.models.ts
+++ b/apps/papra-server/src/modules/organizations/organizations.models.ts
@@ -1,5 +1,6 @@
import type { OrganizationRole } from './organizations.types';
-import { ORGANIZATION_ROLES } from './organizations.constants';
+import { generateId } from '../shared/random/ids';
+import { ORGANIZATION_ID_PREFIX, ORGANIZATION_ROLES } from './organizations.constants';
export function canUserRemoveMemberFromOrganization({
userRole,
@@ -18,3 +19,7 @@ export function canUserRemoveMemberFromOrganization({
return true;
}
+
+export function generateOrganizationId() {
+ return generateId({ prefix: ORGANIZATION_ID_PREFIX });
+}
diff --git a/apps/papra-server/src/modules/organizations/organizations.table.ts b/apps/papra-server/src/modules/organizations/organizations.table.ts
index 5234e8d5..cc8ce7f2 100644
--- a/apps/papra-server/src/modules/organizations/organizations.table.ts
+++ b/apps/papra-server/src/modules/organizations/organizations.table.ts
@@ -3,10 +3,11 @@ import type { OrganizationInvitationStatus, OrganizationRole } from './organizat
import { index, integer, sqliteTable, text, unique } from 'drizzle-orm/sqlite-core';
import { createPrimaryKeyField, createTimestampColumns } from '../shared/db/columns.helpers';
import { usersTable } from '../users/users.table';
-import { ORGANIZATION_ID_PREFIX, ORGANIZATION_INVITATION_ID_PREFIX, ORGANIZATION_INVITATION_STATUS, ORGANIZATION_INVITATION_STATUS_LIST, ORGANIZATION_MEMBER_ID_PREFIX, ORGANIZATION_ROLES_LIST } from './organizations.constants';
+import { ORGANIZATION_INVITATION_ID_PREFIX, ORGANIZATION_INVITATION_STATUS, ORGANIZATION_INVITATION_STATUS_LIST, ORGANIZATION_MEMBER_ID_PREFIX, ORGANIZATION_ROLES_LIST } from './organizations.constants';
+import { generateOrganizationId } from './organizations.models';
export const organizationsTable = sqliteTable('organizations', {
- ...createPrimaryKeyField({ prefix: ORGANIZATION_ID_PREFIX }),
+ ...createPrimaryKeyField({ idGenerator: generateOrganizationId }),
...createTimestampColumns(),
name: text('name').notNull(),
diff --git a/apps/papra-server/src/modules/shared/date.format.bench.ts b/apps/papra-server/src/modules/shared/date.format.bench.ts
new file mode 100644
index 00000000..7adf88e1
--- /dev/null
+++ b/apps/papra-server/src/modules/shared/date.format.bench.ts
@@ -0,0 +1,66 @@
+import { bench, describe } from 'vitest';
+
+function formatWithSwitch(date: Date, exp: string): string {
+ return exp.replace(/\\?\{.*?\}/g, (key) => {
+ if (key.startsWith('\\')) {
+ return key.slice(1);
+ }
+
+ switch (key) {
+ case '{yyyy}':
+ return `${date.getFullYear()}`;
+ case '{yy}':
+ return `${date.getFullYear()}`.slice(-2);
+ case '{MM}':
+ return `${(date.getMonth() + 1)}`.padStart(2, '0');
+ case '{dd}':
+ return `${date.getDate()}`.padStart(2, '0');
+ case '{HH}':
+ return `${date.getHours()}`.padStart(2, '0');
+ case '{mm}':
+ return `${date.getMinutes()}`.padStart(2, '0');
+ case '{ss}':
+ return `${date.getSeconds()}`.padStart(2, '0');
+ case '{SSS}':
+ return `${date.getMilliseconds()}`.padStart(3, '0');
+ default:
+ return '';
+ }
+ });
+}
+
+const formatters: Record<string, (date: Date) => string> = {
+ '{yyyy}': date => `${date.getFullYear()}`,
+ '{yy}': date => `${date.getFullYear()}`.slice(-2),
+ '{MM}': date => `${(date.getMonth() + 1)}`.padStart(2, '0'),
+ '{dd}': date => `${date.getDate()}`.padStart(2, '0'),
+ '{HH}': date => `${date.getHours()}`.padStart(2, '0'),
+ '{mm}': date => `${date.getMinutes()}`.padStart(2, '0'),
+ '{ss}': date => `${date.getSeconds()}`.padStart(2, '0'),
+ '{SSS}': date => `${date.getMilliseconds()}`.padStart(3, '0'),
+};
+
+export function formatWithLut(date: Date, exp: string): string {
+ return exp.replace(/\\?\{.*?\}/g, (key) => {
+ if (key.startsWith('\\')) {
+ return key.slice(1);
+ }
+
+ return formatters[key]?.(date) ?? '';
+ });
+}
+
+describe.skip('date formatting', () => {
+ const date = new Date();
+ const exp = '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}.{SSS}';
+
+ bench('formatWithLut', () => {
+ const result = formatWithLut(date, exp);
+ void result;
+ });
+
+ bench('formatWithSwitch', () => {
+ const result = formatWithSwitch(date, exp);
+ void result;
+ });
+});
diff --git a/apps/papra-server/src/modules/shared/date.test.ts b/apps/papra-server/src/modules/shared/date.test.ts
index 4cac13d9..42d0386c 100644
--- a/apps/papra-server/src/modules/shared/date.test.ts
+++ b/apps/papra-server/src/modules/shared/date.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'vitest';
-import { addDays, isValidDate, startOfDay, subDays } from './date';
+import { addDays, formatDate, isValidDate, startOfDay, subDays } from './date';
describe('date', () => {
describe('isValidDate', () => {
@@ -89,4 +89,18 @@ describe('date', () => {
expect(startOfDay(new Date('2024-05-15T10:30:45'))).to.eql(new Date('2024-05-15T00:00:00'));
});
});
+
+ describe('formatDate', () => {
+ test('formats date according to a given expression', () => {
+ const date = new Date('2024-05-15T10:30:45.123Z');
+ expect(formatDate(date, '{yyyy}-{MM}-{dd}')).toBe('2024-05-15');
+ expect(formatDate(date, '{HH}:{mm}:{ss}')).toBe('10:30:45');
+ expect(formatDate(date, '{yyyy}/{MM}/{dd} {HH}:{mm}:{ss}.{SSS}')).toBe('2024/05/15 10:30:45.123');
+ expect(formatDate(date, 'Today is {dd}/{MM}/{yyyy}')).toBe('Today is 15/05/2024');
+ expect(formatDate(date, 'Escaped \\{yyyy} should be literal')).toBe('Escaped {yyyy} should be literal');
+ expect(formatDate(date, '{timestamp}')).toBe('1715769045123');
+ expect(formatDate(date, '{unix}')).toBe('1715769045');
+ expect(formatDate(date, '{iso}')).toBe('2024-05-15T10:30:45.123Z');
+ });
+ });
});
diff --git a/apps/papra-server/src/modules/shared/date.ts b/apps/papra-server/src/modules/shared/date.ts
index ba7dad2b..7b2d0a31 100644
--- a/apps/papra-server/src/modules/shared/date.ts
+++ b/apps/papra-server/src/modules/shared/date.ts
@@ -17,3 +17,30 @@ export function startOfDay(date: Date): Date {
result.setHours(0, 0, 0, 0);
return result;
}
+
+export function formatDate(date: Date, expression: string): string {
+ return expression
+ .replace(
+ /\\?\{.*?\}/g,
+ (key) => {
+ if (key.startsWith('\\')) {
+ return key.slice(1);
+ }
+
+ switch (key) {
+ case '{yyyy}': return `${date.getFullYear()}`;
+ case '{yy}': return `${date.getFullYear()}`.slice(-2);
+ case '{MM}': return `${(date.getMonth() + 1)}`.padStart(2, '0');
+ case '{dd}': return `${date.getDate()}`.padStart(2, '0');
+ case '{HH}': return `${date.getHours()}`.padStart(2, '0');
+ case '{mm}': return `${date.getMinutes()}`.padStart(2, '0');
+ case '{ss}': return `${date.getSeconds()}`.padStart(2, '0');
+ case '{SSS}': return `${date.getMilliseconds()}`.padStart(3, '0');
+ case '{timestamp}': return `${date.getTime()}`;
+ case '{unix}': return `${Math.floor(date.getTime() / 1000)}`;
+ case '{iso}': return date.toISOString();
+ default: return '';
+ }
+ },
+ );
+}
diff --git a/apps/papra-server/src/modules/shared/random/random.services.test.ts b/apps/papra-server/src/modules/shared/random/random.services.test.ts
index cce6eec7..48963ae4 100644
--- a/apps/papra-server/src/modules/shared/random/random.services.test.ts
+++ b/apps/papra-server/src/modules/shared/random/random.services.test.ts
@@ -1,17 +1,15 @@
import { describe, expect, test } from 'vitest';
-import { generateToken } from './random.services';
+import { generateRandomString } from './random.services';
describe('random', () => {
- describe('generateToken', () => {
- test('create random token of 32 characters by default', () => {
- const { token } = generateToken();
-
- expect(token.length).toBe(32);
+ describe('generateRandomString', () => {
+ test('create random string of 32 characters by default', () => {
+ expect(generateRandomString().length).toBe(32);
});
test('the length can be customized', () => {
- expect(generateToken({ length: 64 }).token.length).toBe(64);
- expect(generateToken({ length: 31 }).token.length).toBe(31);
+ expect(generateRandomString({ length: 64 }).length).toBe(64);
+ expect(generateRandomString({ length: 31 }).length).toBe(31);
});
});
});
diff --git a/apps/papra-server/src/modules/shared/random/random.services.ts b/apps/papra-server/src/modules/shared/random/random.services.ts
index 5454ad34..42a0f311 100644
--- a/apps/papra-server/src/modules/shared/random/random.services.ts
+++ b/apps/papra-server/src/modules/shared/random/random.services.ts
@@ -3,8 +3,6 @@ import { customAlphabet } from 'nanoid';
const corpus = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const nanoid = customAlphabet(corpus);
-export function generateToken({ length = 32 }: { length?: number } = {}) {
- const token = nanoid(length);
-
- return { token };
+export function generateRandomString({ length = 32 }: { length?: number } = {}) {
+ return nanoid(length);
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index db46014d..cff7e999 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -515,6 +515,9 @@ importers:
file-type:
specifier: ^21.3.0
version: 21.3.0
+ filenamify:
+ specifier: ^7.0.1
+ version: 7.0.1
hono:
specifier: ^4.10.7
version: 4.10.7
@@ -7608,6 +7611,14 @@ packages:
resolution: {integrity: sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==}
+ resolution: {integrity: sha512-9ZT504KxEQDamsOogZImAWGEN24R1uFAxU3ZS4AZqn2ooidmN68Olh7n4/RcA4lLatZztjA0ZSuxeLHVoCc8JA==}
+ engines: {node: '>=20'}
+
+ resolution: {integrity: sha512-9b4rfnaX2MkJCgp27wypV6DAMvj4WMOSgJ+TdcpJIO84Dql+Cv6iJjdG4XDTLubOWkfNiBv3joO59sau/TXw+Q==}
+ engines: {node: '>=20'}
+
resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==}
engines: {node: '>=8'}
@@ -20518,6 +20529,12 @@ snapshots:
dependencies:
minimatch: 5.1.6
+
+ dependencies:
+ filename-reserved-regex: 4.0.0
+
dependencies:
to-regex-range: 5.0.1