Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(documents): implement document encryption (#480)

Corentin Thomasset0a03f42231f6
diff --git a/.changeset/rude-loops-lose.md b/.changeset/rude-loops-lose.md
new file mode 100644
index 00000000..53e60c9f
--- /dev/null
+++ b/.changeset/rude-loops-lose.md
@@ -0,0 +1,6 @@
+---
+"@papra/app-server": minor
+"@papra/docs": minor
+---
+
+Added documents encryption layer
diff --git a/apps/docs/src/assets/docs/encryption-schema-dark.png b/apps/docs/src/assets/docs/encryption-schema-dark.png
new file mode 100644
index 00000000..7c81ff15
Binary files /dev/null and b/apps/docs/src/assets/docs/encryption-schema-dark.png differ
diff --git a/apps/docs/src/assets/docs/encryption-schema-light.png b/apps/docs/src/assets/docs/encryption-schema-light.png
new file mode 100644
index 00000000..184d0c2f
Binary files /dev/null and b/apps/docs/src/assets/docs/encryption-schema-light.png differ
diff --git a/apps/docs/src/components/encryption-key-generator.astro b/apps/docs/src/components/encryption-key-generator.astro
new file mode 100644
index 00000000..4f06d4ee
--- /dev/null
+++ b/apps/docs/src/components/encryption-key-generator.astro
@@ -0,0 +1,154 @@
+---
+const iconSize = '20';
+const refreshIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="${iconSize}" height="${iconSize}" viewBox="0 0 24 24"><!-- Icon from Tabler Icons by Paweł Kuna - https://github.com/tabler/tabler-icons/blob/master/LICENSE --><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 11A8.1 8.1 0 0 0 4.5 9M4 5v4h4m-4 4a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4"/></svg>`;
+const copyIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="${iconSize}" height="${iconSize}" viewBox="0 0 24 24"><!-- Icon from Tabler Icons by Paweł Kuna - https://github.com/tabler/tabler-icons/blob/master/LICENSE --><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"><path d="M7 9.667A2.667 2.667 0 0 1 9.667 7h8.666A2.667 2.667 0 0 1 21 9.667v8.666A2.667 2.667 0 0 1 18.333 21H9.667A2.667 2.667 0 0 1 7 18.333z"/><path d="M4.012 16.737A2 2 0 0 1 3 15V5c0-1.1.9-2 2-2h10c.75 0 1.158.385 1.5 1"/></g></svg>`;
+const copiedIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="${iconSize}" height="${iconSize}" viewBox="0 0 24 24"><!-- Icon from Tabler Icons by Paweł Kuna - https://github.com/tabler/tabler-icons/blob/master/LICENSE --><path fill="currentColor" d="M18.333 6A3.667 3.667 0 0 1 22 9.667v8.666A3.667 3.667 0 0 1 18.333 22H9.667A3.667 3.667 0 0 1 6 18.333V9.667A3.667 3.667 0 0 1 9.667 6zM15 2c1.094 0 1.828.533 2.374 1.514a1 1 0 1 1-1.748.972C15.405 4.088 15.284 4 15 4H5c-.548 0-1 .452-1 1v9.998c0 .32.154.618.407.805l.1.065a1 1 0 1 1-.99 1.738A3 3 0 0 1 2 15V5c0-1.652 1.348-3 3-3zm1.293 9.293L13 14.585l-1.293-1.292a1 1 0 0 0-1.414 1.414l2 2a1 1 0 0 0 1.414 0l4-4a1 1 0 0 0-1.414-1.414"/></svg>`;
+---
+
+<div class="key-generator">
+ <div class="key-row">
+ <input type="text" class="key-input" readonly />
+ <button class="cbtn btn-refresh" title="Generate new key">
+ <span set:html={refreshIcon} aria-label="Refresh" />
+ </button>
+ <button class="cbtn btn-copy" title="Copy to clipboard">
+ <span set:html={copyIcon} aria-label="Copy" class="icon-copy" />
+ <span set:html={copiedIcon} aria-label="Copied" class="icon-copied hidden" />
+ </button>
+ </div>
+ <div class="info-text">
+ Generated locally in your browser - no network or server involved
+ </div>
+</div>
+
+<script>
+ function generateKey({ keyInputElement }: { keyInputElement: HTMLInputElement }) {
+ // Generate a 32-byte (256-bit) encryption key
+ const array = new Uint8Array(32);
+ crypto.getRandomValues(array);
+
+ // Convert to hex format
+ const key = Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
+ keyInputElement.value = key;
+ }
+
+ function copyToClipboard({ keyInputElement, copyButtonElement, iconCopyElement, iconCopiedElement }: { keyInputElement: HTMLInputElement; copyButtonElement: HTMLButtonElement; iconCopyElement: HTMLSpanElement; iconCopiedElement: HTMLSpanElement }) {
+ keyInputElement.select();
+ keyInputElement.setSelectionRange(0, 64); // For mobile devices
+
+ navigator.clipboard.writeText(keyInputElement.value).then(() => {
+ iconCopyElement.classList.add('hidden');
+ iconCopiedElement.classList.remove('hidden');
+ copyButtonElement.disabled = true;
+
+ setTimeout(() => {
+ iconCopyElement.classList.remove('hidden');
+ iconCopiedElement.classList.add('hidden');
+ copyButtonElement.disabled = false;
+ }, 1_000);
+ }).catch(() => {
+ // Fallback for older browsers
+ document.execCommand('copy');
+ });
+ }
+
+ const keyGenerators = document.querySelectorAll('.key-generator');
+
+ keyGenerators.forEach((keyGenerator) => {
+ const refreshButtonElement = keyGenerator.querySelector('.btn-refresh')!;
+ const copyButtonElement = keyGenerator.querySelector<HTMLButtonElement>('.btn-copy')!;
+ const keyInputElement = keyGenerator.querySelector<HTMLInputElement>('.key-input')!;
+ const iconCopyElement = keyGenerator.querySelector<HTMLSpanElement>('.icon-copy')!;
+ const iconCopiedElement = keyGenerator.querySelector<HTMLSpanElement>('.icon-copied')!;
+
+ generateKey({ keyInputElement });
+
+ refreshButtonElement.addEventListener('click', () => generateKey({ keyInputElement }));
+ copyButtonElement.addEventListener('click', () => copyToClipboard({ copyButtonElement, keyInputElement, iconCopyElement, iconCopiedElement }));
+ });
+</script>
+
+<style>
+ .key-generator {
+ /* background-color: var(--ec-frm-trmBg);
+ border-radius: var(--ec-brdRad);
+ border: 1px solid var(--ec-brdCol);
+ font-family: monospace;
+ max-width: 100%; */
+ }
+
+ .key-row {
+ display: flex;
+ align-items: center;
+ }
+
+ .key-input {
+ flex: 1;
+ background-color: var(--sl-color-black);
+ border: 1px solid var(--sl-color-gray-5);
+ border-radius: 4px 0 0 4px;
+ padding: 8px 12px;
+ font-family: var(--__sl-font-mono, monospace);
+ font-size: 14px;
+ color: var(--sl-color-gray-2);
+ min-width: 0; /* Allow input to shrink */
+ border-right: none;
+ }
+
+ .key-input:focus {
+ outline: none;
+ border-color: var(--ec-frm-inpBrd, #4a9eff);
+ box-shadow: 0 0 0 2px var(--ec-frm-inpBrd, #4a9eff)33;
+ }
+
+ .cbtn {
+ background-color: var(--ec-frm-btnBg);
+ border: 1px solid var(--ec-brdCol);
+ padding: 10px 12px;
+ cursor: pointer;
+ font-size: 16px;
+ transition: all 0.2s ease;
+ min-width: 44px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ margin-top: 0;
+ }
+
+ .cbtn.btn-copy {
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+ border-top-right-radius: 4px;
+ border-bottom-right-radius: 4px;
+ border-left: none;
+ }
+
+ .cbtn.btn-refresh {
+ border-radius: 0;
+ }
+
+ .cbtn:hover {
+ background-color: var(--sl-color-gray-6)!important;
+ }
+
+ .cbtn:disabled {
+ opacity: 0.6;
+ cursor: not-allowed;
+ transform: none;
+ }
+
+ .btn-refresh:hover:not(:disabled) {
+ background-color: var(--ec-frm-btnBgHover, #3a3a3a);
+ }
+
+ .btn-copy:hover:not(:disabled) {
+ background-color: var(--ec-frm-btnBgHover, #3a3a3a);
+ }
+
+ .info-text {
+ color: var(--ec-frm-txtSecondary, #888888);
+ font-style: italic;
+ margin-top: 0;
+ }
+
+</style>
diff --git a/apps/docs/src/content/docs/03-guides/05-setup-document-encryption.mdx b/apps/docs/src/content/docs/03-guides/05-setup-document-encryption.mdx
new file mode 100644
index 00000000..0f20e4b5
--- /dev/null
+++ b/apps/docs/src/content/docs/03-guides/05-setup-document-encryption.mdx
@@ -0,0 +1,448 @@
+---
+title: Setup Document Encryption
+description: Step-by-step guide to enable and configure document encryption in Papra for enhanced data security.
+slug: guides/document-encryption
+---
+import { Steps } from '@astrojs/starlight/components';
+import { Aside } from '@astrojs/starlight/components';
+import { Code } from '@astrojs/starlight/components';
+import { Tabs, TabItem } from '@astrojs/starlight/components';
+import EncryptionKeyGenerator from '../../../components/encryption-key-generator.astro';
+
+<Aside type="note">
+Document encryption is available in Papra v0.9.0 and above.
+</Aside>
+
+Document encryption in Papra provides end-to-end protection for your stored documents using industry-standard AES-256-GCM encryption. This guide will walk you through enabling encryption, understanding how it works, and managing encryption keys.
+
+## How Encryption Works
+
+Papra uses a two-layer encryption approach that provides both security and flexibility:
+
+### Key Encryption Architecture
+
+1. **Key Encryption Key (KEK)**: A master key that you provide, used to encrypt document-specific keys
+2. **Document Encryption Key (DEK)**: Unique per-document keys that actually encrypt your files
+3. **File Encryption**: Each document gets its own random 256-bit encryption key for maximum security
+
+<div class="dark:block hidden">
+![Key Encryption Architecture](../../../assets/docs/encryption-schema-light.png)
+</div>
+<div class="dark:hidden block">
+![Key Encryption Architecture](../../../assets/docs/encryption-schema-dark.png)
+</div>
+
+### Encryption Flow
+
+<Steps>
+
+1. **Document Upload**: When you upload a document, Papra generates a unique 256-bit encryption key (DEK)
+
+2. **File Encryption**: The document is encrypted using AES-256-GCM with the DEK
+
+3. **Key Wrapping**: The DEK is encrypted (wrapped) using your Key Encryption Key (KEK)
+
+4. **Storage**: The encrypted document and wrapped DEK are stored separately - the file in your storage backend, the wrapped key in the database along with the document metadata
+
+5. **Retrieval**: When accessing a document, Papra unwraps the DEK using your KEK, then decrypts the file stream
+
+</Steps>
+
+<Aside type="note">
+This architecture means that even if someone gains access to your file storage, they cannot decrypt documents without access to both your document records and your KEK, in other words, without your database and your environment variables.
+</Aside>
+
+## Quick Setup
+
+<Steps>
+
+1. **Generate an encryption key**
+
+ Generate a secure random 256-bit key in hex format, using this generator or OpenSSL command.
+
+ <Tabs>
+ <TabItem label="Key generator">
+ <EncryptionKeyGenerator />
+ </TabItem>
+
+ <TabItem label="OpenSSL command">
+ ```bash
+ openssl rand -hex 32
+ ```
+
+ This will output something like: `0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c`
+ </TabItem>
+
+ </Tabs>
+
+
+
+2. **Enable encryption in your configuration**
+
+ Add the following environment variables to your `.env` file or Docker configuration:
+
+ ```bash
+ DOCUMENT_STORAGE_ENCRYPTION_IS_ENABLED=true
+ DOCUMENT_STORAGE_DOCUMENT_KEY_ENCRYPTION_KEYS=<your-encryption-key>
+ ```
+
+3. **Restart Papra**
+
+ Restart your Papra instance to apply the encryption settings.
+
+</Steps>
+
+## Configuration Options
+
+### Environment Variables
+
+| Variable | Description | Required |
+|----------|-------------|----------|
+| `DOCUMENT_STORAGE_ENCRYPTION_IS_ENABLED` | Enable/disable document encryption | No |
+| `DOCUMENT_STORAGE_DOCUMENT_KEY_ENCRYPTION_KEYS` | Key encryption keys for document encryption | Yes (if encryption enabled) |
+
+### Key Formats
+
+<Tabs>
+ <TabItem label="Single Key">
+ For simple setups, provide a single 32-byte hex string:
+
+ ```bash
+ DOCUMENT_STORAGE_DOCUMENT_KEY_ENCRYPTION_KEYS=<your-encryption-key>
+ ```
+
+ This key will automatically be assigned version `1`.
+ </TabItem>
+
+ <TabItem label="Multiple Keys">
+ For key rotation and advanced setups, provide versioned keys:
+
+ ```bash
+ DOCUMENT_STORAGE_DOCUMENT_KEY_ENCRYPTION_KEYS=1:<your-encryption-key-1>,2:<your-encryption-key-2>
+ ```
+
+ - The highest version key encrypts new documents
+ - All keys can decrypt existing documents
+ - Versions can be any alphabetically sortable string
+ - Order in the list doesn't matter
+ </TabItem>
+</Tabs>
+
+## Docker Compose Setup
+
+Add encryption configuration to your Docker Compose file:
+
+<Tabs>
+ <TabItem label="Environment Variables">
+ ```yaml title="docker-compose.yml" ins={8-9}
+ services:
+ papra:
+ container_name: papra
+ image: ghcr.io/papra-hq/papra:latest
+ restart: unless-stopped
+ environment:
+ # ... other environment variables ...
+ - DOCUMENT_STORAGE_ENCRYPTION_IS_ENABLED=true
+ - DOCUMENT_STORAGE_DOCUMENT_KEY_ENCRYPTION_KEYS=<your-encryption-key>
+ volumes:
+ - ./app-data:/app/app-data
+ ports:
+ - "1221:1221"
+ ```
+ </TabItem>
+
+ <TabItem label="Config File">
+ ```yaml title="docker-compose.yml"
+ services:
+ papra:
+ container_name: papra
+ image: ghcr.io/papra-hq/papra:latest
+ restart: unless-stopped
+ volumes:
+ - ./app-data:/app/app-data
+ - ./papra.config.yaml:/app/app-data/papra.config.yaml
+ ports:
+ - "1221:1221"
+ ```
+
+ ```yaml title="./papra.config.yaml"
+ documentsStorage:
+ encryption:
+ isEncryptionEnabled: true
+ documentKeyEncryptionKeys: "<your-encryption-key>"
+ ```
+ </TabItem>
+</Tabs>
+
+## Key Management
+
+### Key Rotation
+
+Key rotation allows you to replace encryption keys without losing access to existing documents:
+
+<Steps>
+
+1. **Generate a new key**
+
+ ```bash
+ openssl rand -hex 32
+ ```
+
+2. **Add the new key with a higher version**
+
+ ```bash
+ DOCUMENT_STORAGE_DOCUMENT_KEY_ENCRYPTION_KEYS=1:old_key_here,2:new_key_here
+ ```
+
+3. **Restart Papra**
+
+ New documents will use the highest version key (version 2), while existing documents remain accessible with the old key.
+
+4. **Optional: Remove old keys**
+
+ Once you're confident all documents are using the new key, you can remove old keys. However, this will make any documents encrypted with old keys inaccessible.
+
+</Steps>
+
+<Aside type="caution">
+Never remove a key version if there are still documents encrypted with that key, unless you're certain you no longer need access to those documents.
+</Aside>
+
+### Key Security Best Practices
+
+1. **Store keys securely**: Use a secrets management system in production
+2. **Use different keys per environment**: Development, staging, and production should have separate keys
+3. **Backup your keys**: Loss of encryption keys means permanent loss of document access
+4. **Rotate keys periodically**: Consider rotating keys annually or after security incidents
+5. **Limit key access**: Only authorized personnel should have access to encryption keys
+
+### Docker Secrets Example
+
+For production environments, store your encryption keys securely using external secret management systems or secure file systems, and reference them via environment variables.
+
+## Compatibility and Migration
+
+### Enabling Encryption on Existing Instances
+
+When you enable encryption on a Papra instance that already has documents:
+
+- **Existing documents**: Remain unencrypted but accessible
+- **New documents**: Are encrypted using the current KEK
+- **Mixed storage**: Papra automatically handles both encrypted and unencrypted documents
+
+### Migrating Existing Documents to Encrypted Format
+
+If you want to encrypt all existing unencrypted documents after enabling encryption, Papra provides a maintenance command to handle this migration automatically.
+
+<Aside type="caution">
+It's advised to make a backup of your documents and database before running the migration.
+</Aside>
+
+<Steps>
+
+1. **Verify encryption is properly configured**
+
+ Ensure encryption is enabled and working for new documents before migrating existing ones:
+
+ ```bash
+ # Check that your configuration includes:
+ DOCUMENT_STORAGE_ENCRYPTION_IS_ENABLED=true
+ DOCUMENT_STORAGE_DOCUMENT_KEY_ENCRYPTION_KEYS=<your-key>
+ ```
+
+2. **Run dry-run to preview changes**
+
+ <Tabs>
+ <TabItem label="Docker Compose">
+ ```bash
+ # Run dry-run inside the Docker container
+ docker compose exec papra pnpm maintenance:encrypt-all-documents --dry-run
+ ```
+ </TabItem>
+
+ <TabItem label="Docker">
+ ```bash
+ # Run dry-run inside the Docker container
+ docker exec -it papra pnpm maintenance:encrypt-all-documents --dry-run
+ ```
+ </TabItem>
+
+ <TabItem label="Source Installation">
+ ```bash
+ # From your Papra server directory
+ pnpm maintenance:encrypt-all-documents --dry-run
+ ```
+ </TabItem>
+
+
+ </Tabs>
+
+ This will show you:
+ - How many documents will be encrypted
+ - Which documents will be affected
+ - No actual encryption will be performed
+
+4. **Run the migration**
+
+ <Tabs>
+ <TabItem label="Docker Compose">
+ ```bash
+ # Run migration inside the Docker container
+ docker compose exec papra pnpm maintenance:encrypt-all-documents
+ ```
+ </TabItem>
+
+ <TabItem label="Docker">
+ ```bash
+ # Run migration inside the Docker container
+ docker exec -it papra pnpm maintenance:encrypt-all-documents
+ ```
+ </TabItem>
+
+ <TabItem label="Source Installation">
+ ```bash
+ # From your Papra server directory
+ pnpm maintenance:encrypt-all-documents
+ ```
+ </TabItem>
+ </Tabs>
+
+ The command will:
+ - Find all unencrypted documents
+ - Encrypt each document using your configured KEK
+ - Update database records with encryption metadata
+ - Remove original unencrypted files from storage
+ - Provide progress logging throughout the process
+
+5. **Verify migration success**
+
+ After migration:
+ - Test document access through the Papra interface
+ - Check that storage files are now encrypted (should start with `PP01`)
+ - Verify all documents are accessible and downloadable
+
+</Steps>
+
+<Aside type="tip">
+**Migration Performance**
+
+- The migration processes documents sequentially to ensure reliability
+- Large document collections may take considerable time
+- Monitor disk space during migration (temporary storage overhead)
+- Consider running during maintenance windows for production systems
+</Aside>
+
+#### Troubleshooting Migration Issues
+
+**Migration fails with "Document encryption is not enabled"**
+- Verify `DOCUMENT_STORAGE_ENCRYPTION_IS_ENABLED=true` is set
+- Restart Papra after configuration changes
+
+**Migration fails with "Document encryption keys are not set"**
+- Ensure `DOCUMENT_STORAGE_DOCUMENT_KEY_ENCRYPTION_KEYS` contains valid keys
+- Verify key format is correct (64-character hex string)
+
+**Migration stops or fails partway**
+- Check available disk space
+- Review Papra logs for specific error messages
+- Restore from backup and retry after fixing the issue
+
+**Documents inaccessible after migration**
+- Verify encryption keys are still properly configured
+- Check that Papra can access your storage backend
+- Restore from backup if necessary
+
+### Disabling Encryption
+
+If you disable encryption:
+
+- **Encrypted documents**: Remain encrypted but are automatically decrypted when accessed (if KEK is still available)
+- **New documents**: Are stored unencrypted
+- **Data loss risk**: If you remove the KEK while encrypted documents exist, those documents become inaccessible
+
+<Aside type="caution">
+Disabling encryption doesn't automatically decrypt existing documents in storage. They remain encrypted and require the KEK for access.
+</Aside>
+
+### Storage Driver Compatibility
+
+The encryption layer sits between Papra and your chosen storage driver, providing consistent encryption regardless of where files are stored (S3, Azure Blob Storage, File System, etc.).
+
+## Technical Details
+
+### Encryption Algorithm
+
+- **Algorithm**: AES-256-GCM (Authenticated Encryption)
+- **Key size**: 256 bits (32 bytes)
+- **IV size**: 96 bits (12 bytes)
+- **Authentication tag**: 128 bits (16 bytes)
+
+### File Format
+
+Encrypted files use a custom format with a magic number for identification:
+
+```
+| Magic (4 bytes) | IV (12 bytes) | Encrypted Data | Auth Tag (16 bytes) |
+```
+
+- **Magic number**: `PP01` - identifies Papra encrypted files
+- **IV**: Initialization vector for GCM mode
+- **Encrypted Data**: The actual encrypted document content
+- **Auth Tag**: Authentication tag for integrity verification
+
+### Performance Considerations
+
+- **Streaming encryption**: Files are encrypted/decrypted in streams, minimizing memory usage
+- **No size overhead**: Minimal storage overhead (32 bytes per file for headers)
+- **CPU impact**: Modern processors handle AES encryption efficiently
+
+## Troubleshooting
+
+### Common Issues
+
+**"Document KEK required" error**
+- Ensure `DOCUMENT_STORAGE_DOCUMENT_KEY_ENCRYPTION_KEYS` is set
+- Verify the key format is correct (64 character hex string)
+
+**"Document KEK not found" error**
+- The document was encrypted with a key version that's no longer available
+- Add the missing key version back to your configuration
+
+**"Unsupported encryption algorithm" error**
+- The document uses an encryption algorithm not supported by this Papra version
+- This shouldn't occur in normal operation
+
+**Performance issues**
+- Consider your storage driver's performance characteristics
+- Encryption adds minimal overhead, but network/disk I/O remains the bottleneck
+
+### Verification
+
+To verify encryption is working:
+
+1. Upload a document after enabling encryption
+2. Check your storage backend - the file should not be readable as plain text
+3. The file should start with the magic number `PP01` if you examine it directly
+
+<Aside>
+You can find complete configuration options in the [configuration reference](/self-hosting/configuration). Look for variables prefixed with `DOCUMENT_STORAGE_ENCRYPTION_`.
+</Aside>
+
+## Security Considerations
+
+### Threat Model
+
+Document encryption in Papra protects against:
+
+- **Storage compromise**: If your file storage is breached, documents remain encrypted
+- **Database-only breach**: Without the KEK, wrapped DEKs cannot be unwrapped
+- **Configuration exposure**: If the KEK is exposed, the files remain encrypted as long as the DEK are not exposed
+
+### Limitations
+
+Encryption does not protect against:
+
+- **Application-level access**: Users with document access can view decrypted content
+- **Memory dumps**: Decrypted content exists temporarily in application memory
+- **Key and database compromise**: If KEKs are stolen, all DEKs can be decrypted if the database is compromised
+- **Full system compromise**: If the entire Papra instance is compromised, documents can be accessed
diff --git a/apps/docs/src/content/navigation.ts b/apps/docs/src/content/navigation.ts
index 687e09fa..4e1fc14b 100644
--- a/apps/docs/src/content/navigation.ts
+++ b/apps/docs/src/content/navigation.ts
@@ -35,6 +35,10 @@ export const sidebar = [
label: 'Setup Custom OAuth2 Providers',
slug: 'guides/setup-custom-oauth2-providers',
},
+ {
+ label: 'Document Encryption',
+ slug: 'guides/document-encryption',
+ },
],
},
{
diff --git a/apps/docs/uno.config.ts b/apps/docs/uno.config.ts
index e49fa22b..d7e99396 100644
--- a/apps/docs/uno.config.ts
+++ b/apps/docs/uno.config.ts
@@ -10,8 +10,8 @@ export default defineConfig({
presets: [
presetUno({
dark: {
- dark: '[data-kb-theme="dark"]',
- light: '[data-kb-theme="light"]',
+ dark: '[data-theme="dark"]',
+ light: '[data-theme="light"]',
},
prefix: '',
}),
diff --git a/apps/papra-server/package.json b/apps/papra-server/package.json
index 9ac3c736..56544664 100644
--- a/apps/papra-server/package.json
+++ b/apps/papra-server/package.json
@@ -34,7 +34,8 @@
"clean:all": "pnpm clean:db && pnpm clean:storage",
"dev:reset": "pnpm clean:all && pnpm migrate:up",
"script:send-intake-email": "tsx --env-file-if-exists=.env src/scripts/send-intake-email.script.ts | crowlog-pretty",
- "stripe:webhook": "stripe listen --forward-to localhost:1221/api/stripe/webhook"
+ "stripe:webhook": "stripe listen --forward-to localhost:1221/api/stripe/webhook",
+ "maintenance:encrypt-all-documents": "tsx --env-file-if-exists=.env src/scripts/encrypt-all-documents.script.ts"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.835.0",
diff --git a/apps/papra-server/src/migrations/list/0010-document-file-encryption.migration.ts b/apps/papra-server/src/migrations/list/0010-document-file-encryption.migration.ts
new file mode 100644
index 00000000..b0cd9762
--- /dev/null
+++ b/apps/papra-server/src/migrations/list/0010-document-file-encryption.migration.ts
@@ -0,0 +1,32 @@
+import type { BatchItem } from 'drizzle-orm/batch';
+import type { Migration } from '../migrations.types';
+import { sql } from 'drizzle-orm';
+
+export const documentFileEncryptionMigration = {
+ name: 'document-file-encryption',
+
+ up: async ({ db }) => {
+ // Check if columns already exist to handle reapplying migrations
+ const tableInfo = await db.run(sql`PRAGMA table_info(documents)`);
+ const existingColumns = tableInfo.rows.map(row => row.name);
+ const hasColumn = (columnName: string) => existingColumns.includes(columnName);
+
+ const statements = [
+ ...(!hasColumn('file_encryption_key_wrapped') ? [sql`ALTER TABLE documents ADD COLUMN file_encryption_key_wrapped TEXT`] : []),
+ ...(!hasColumn('file_encryption_kek_version') ? [sql`ALTER TABLE documents ADD COLUMN file_encryption_kek_version TEXT`] : []),
+ ...(!hasColumn('file_encryption_algorithm') ? [sql`ALTER TABLE documents ADD COLUMN file_encryption_algorithm TEXT`] : []),
+ sql`CREATE INDEX IF NOT EXISTS documents_file_encryption_kek_version_index ON documents (file_encryption_kek_version)`,
+ ];
+
+ await db.batch(statements.map(statement => db.run(statement) as BatchItem<'sqlite'>) as [BatchItem<'sqlite'>, ...BatchItem<'sqlite'>[]]);
+ },
+
+ down: async ({ db }) => {
+ await db.batch([
+ db.run(sql`DROP INDEX IF EXISTS documents_file_encryption_kek_version_index`),
+ db.run(sql`ALTER TABLE documents DROP COLUMN file_encryption_key_wrapped`),
+ db.run(sql`ALTER TABLE documents DROP COLUMN file_encryption_kek_version`),
+ db.run(sql`ALTER TABLE documents DROP COLUMN file_encryption_algorithm`),
+ ]);
+ },
+} satisfies Migration;
diff --git a/apps/papra-server/src/migrations/meta/0009_snapshot.json b/apps/papra-server/src/migrations/meta/0009_snapshot.json
new file mode 100644
index 00000000..30e611b7
--- /dev/null
+++ b/apps/papra-server/src/migrations/meta/0009_snapshot.json
@@ -0,0 +1,1998 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "6f0abb3a-800c-4968-a528-95f3f254c1ef",
+ "prevId": "7fb3b6cf-299a-430f-84be-9050d2ff9a65",
+ "tables": {
+ "document_activity_log": {
+ "name": "document_activity_log",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "document_id": {
+ "name": "document_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "event": {
+ "name": "event",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "event_data": {
+ "name": "event_data",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tag_id": {
+ "name": "tag_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "document_activity_log_document_id_documents_id_fk": {
+ "name": "document_activity_log_document_id_documents_id_fk",
+ "tableFrom": "document_activity_log",
+ "tableTo": "documents",
+ "columnsFrom": [
+ "document_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "document_activity_log_user_id_users_id_fk": {
+ "name": "document_activity_log_user_id_users_id_fk",
+ "tableFrom": "document_activity_log",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "cascade"
+ },
+ "document_activity_log_tag_id_tags_id_fk": {
+ "name": "document_activity_log_tag_id_tags_id_fk",
+ "tableFrom": "document_activity_log",
+ "tableTo": "tags",
+ "columnsFrom": [
+ "tag_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "documents": {
+ "name": "documents",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "deleted_by": {
+ "name": "deleted_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "original_name": {
+ "name": "original_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "original_size": {
+ "name": "original_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "original_storage_key": {
+ "name": "original_storage_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "original_sha256_hash": {
+ "name": "original_sha256_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "file_encryption_key_wrapped": {
+ "name": "file_encryption_key_wrapped",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "file_encryption_kek_version": {
+ "name": "file_encryption_kek_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "file_encryption_algorithm": {
+ "name": "file_encryption_algorithm",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "documents_organization_id_is_deleted_created_at_index": {
+ "name": "documents_organization_id_is_deleted_created_at_index",
+ "columns": [
+ "organization_id",
+ "is_deleted",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "documents_organization_id_is_deleted_index": {
+ "name": "documents_organization_id_is_deleted_index",
+ "columns": [
+ "organization_id",
+ "is_deleted"
+ ],
+ "isUnique": false
+ },
+ "documents_organization_id_original_sha256_hash_unique": {
+ "name": "documents_organization_id_original_sha256_hash_unique",
+ "columns": [
+ "organization_id",
+ "original_sha256_hash"
+ ],
+ "isUnique": true
+ },
+ "documents_original_sha256_hash_index": {
+ "name": "documents_original_sha256_hash_index",
+ "columns": [
+ "original_sha256_hash"
+ ],
+ "isUnique": false
+ },
+ "documents_organization_id_size_index": {
+ "name": "documents_organization_id_size_index",
+ "columns": [
+ "organization_id",
+ "original_size"
+ ],
+ "isUnique": false
+ },
+ "documents_file_encryption_kek_version_index": {
+ "name": "documents_file_encryption_kek_version_index",
+ "columns": [
+ "file_encryption_kek_version"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "documents_organization_id_organizations_id_fk": {
+ "name": "documents_organization_id_organizations_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "documents_created_by_users_id_fk": {
+ "name": "documents_created_by_users_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "cascade"
+ },
+ "documents_deleted_by_users_id_fk": {
+ "name": "documents_deleted_by_users_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "users",
+ "columnsFrom": [
+ "deleted_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "organization_invitations": {
+ "name": "organization_invitations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "inviter_id": {
+ "name": "inviter_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "organization_invitations_organization_email_unique": {
+ "name": "organization_invitations_organization_email_unique",
+ "columns": [
+ "organization_id",
+ "email"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "organization_invitations_organization_id_organizations_id_fk": {
+ "name": "organization_invitations_organization_id_organizations_id_fk",
+ "tableFrom": "organization_invitations",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "organization_invitations_inviter_id_users_id_fk": {
+ "name": "organization_invitations_inviter_id_users_id_fk",
+ "tableFrom": "organization_invitations",
+ "tableTo": "users",
+ "columnsFrom": [
+ "inviter_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "organization_members": {
+ "name": "organization_members",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "organization_members_user_organization_unique": {
+ "name": "organization_members_user_organization_unique",
+ "columns": [
+ "organization_id",
+ "user_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "organization_members_organization_id_organizations_id_fk": {
+ "name": "organization_members_organization_id_organizations_id_fk",
+ "tableFrom": "organization_members",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "organization_members_user_id_users_id_fk": {
+ "name": "organization_members_user_id_users_id_fk",
+ "tableFrom": "organization_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "organizations": {
+ "name": "organizations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "customer_id": {
+ "name": "customer_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user_roles": {
+ "name": "user_roles",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "user_roles_role_index": {
+ "name": "user_roles_role_index",
+ "columns": [
+ "role"
+ ],
+ "isUnique": false
+ },
+ "user_roles_user_id_role_unique_index": {
+ "name": "user_roles_user_id_role_unique_index",
+ "columns": [
+ "user_id",
+ "role"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "user_roles_user_id_users_id_fk": {
+ "name": "user_roles_user_id_users_id_fk",
+ "tableFrom": "user_roles",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "documents_tags": {
+ "name": "documents_tags",
+ "columns": {
+ "document_id": {
+ "name": "document_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tag_id": {
+ "name": "tag_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "documents_tags_document_id_documents_id_fk": {
+ "name": "documents_tags_document_id_documents_id_fk",
+ "tableFrom": "documents_tags",
+ "tableTo": "documents",
+ "columnsFrom": [
+ "document_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "documents_tags_tag_id_tags_id_fk": {
+ "name": "documents_tags_tag_id_tags_id_fk",
+ "tableFrom": "documents_tags",
+ "tableTo": "tags",
+ "columnsFrom": [
+ "tag_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {
+ "documents_tags_pkey": {
+ "columns": [
+ "document_id",
+ "tag_id"
+ ],
+ "name": "documents_tags_pkey"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tags": {
+ "name": "tags",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "tags_organization_id_name_unique": {
+ "name": "tags_organization_id_name_unique",
+ "columns": [
+ "organization_id",
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "tags_organization_id_organizations_id_fk": {
+ "name": "tags_organization_id_organizations_id_fk",
+ "tableFrom": "tags",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "users": {
+ "name": "users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email_verified": {
+ "name": "email_verified",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "max_organization_count": {
+ "name": "max_organization_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "users_email_unique": {
+ "name": "users_email_unique",
+ "columns": [
+ "email"
+ ],
+ "isUnique": true
+ },
+ "users_email_index": {
+ "name": "users_email_index",
+ "columns": [
+ "email"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "api_key_organizations": {
+ "name": "api_key_organizations",
+ "columns": {
+ "api_key_id": {
+ "name": "api_key_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_member_id": {
+ "name": "organization_member_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "api_key_organizations_api_key_id_api_keys_id_fk": {
+ "name": "api_key_organizations_api_key_id_api_keys_id_fk",
+ "tableFrom": "api_key_organizations",
+ "tableTo": "api_keys",
+ "columnsFrom": [
+ "api_key_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "api_key_organizations_organization_member_id_organization_members_id_fk": {
+ "name": "api_key_organizations_organization_member_id_organization_members_id_fk",
+ "tableFrom": "api_key_organizations",
+ "tableTo": "organization_members",
+ "columnsFrom": [
+ "organization_member_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "api_keys": {
+ "name": "api_keys",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "key_hash": {
+ "name": "key_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prefix": {
+ "name": "prefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "all_organizations": {
+ "name": "all_organizations",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ }
+ },
+ "indexes": {
+ "api_keys_key_hash_unique": {
+ "name": "api_keys_key_hash_unique",
+ "columns": [
+ "key_hash"
+ ],
+ "isUnique": true
+ },
+ "key_hash_index": {
+ "name": "key_hash_index",
+ "columns": [
+ "key_hash"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "api_keys_user_id_users_id_fk": {
+ "name": "api_keys_user_id_users_id_fk",
+ "tableFrom": "api_keys",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "auth_accounts": {
+ "name": "auth_accounts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token_expires_at": {
+ "name": "access_token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token_expires_at": {
+ "name": "refresh_token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "auth_accounts_user_id_users_id_fk": {
+ "name": "auth_accounts_user_id_users_id_fk",
+ "tableFrom": "auth_accounts",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "auth_sessions": {
+ "name": "auth_sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "active_organization_id": {
+ "name": "active_organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "auth_sessions_token_index": {
+ "name": "auth_sessions_token_index",
+ "columns": [
+ "token"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "auth_sessions_user_id_users_id_fk": {
+ "name": "auth_sessions_user_id_users_id_fk",
+ "tableFrom": "auth_sessions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "auth_sessions_active_organization_id_organizations_id_fk": {
+ "name": "auth_sessions_active_organization_id_organizations_id_fk",
+ "tableFrom": "auth_sessions",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "active_organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "auth_verifications": {
+ "name": "auth_verifications",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "auth_verifications_identifier_index": {
+ "name": "auth_verifications_identifier_index",
+ "columns": [
+ "identifier"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "intake_emails": {
+ "name": "intake_emails",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email_address": {
+ "name": "email_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "allowed_origins": {
+ "name": "allowed_origins",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "is_enabled": {
+ "name": "is_enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ }
+ },
+ "indexes": {
+ "intake_emails_email_address_unique": {
+ "name": "intake_emails_email_address_unique",
+ "columns": [
+ "email_address"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "intake_emails_organization_id_organizations_id_fk": {
+ "name": "intake_emails_organization_id_organizations_id_fk",
+ "tableFrom": "intake_emails",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "organization_subscriptions": {
+ "name": "organization_subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "customer_id": {
+ "name": "customer_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "plan_id": {
+ "name": "plan_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "seats_count": {
+ "name": "seats_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "current_period_end": {
+ "name": "current_period_end",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "current_period_start": {
+ "name": "current_period_start",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cancel_at_period_end": {
+ "name": "cancel_at_period_end",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "organization_subscriptions_organization_id_organizations_id_fk": {
+ "name": "organization_subscriptions_organization_id_organizations_id_fk",
+ "tableFrom": "organization_subscriptions",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tagging_rule_actions": {
+ "name": "tagging_rule_actions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tagging_rule_id": {
+ "name": "tagging_rule_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tag_id": {
+ "name": "tag_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "tagging_rule_actions_tagging_rule_id_tagging_rules_id_fk": {
+ "name": "tagging_rule_actions_tagging_rule_id_tagging_rules_id_fk",
+ "tableFrom": "tagging_rule_actions",
+ "tableTo": "tagging_rules",
+ "columnsFrom": [
+ "tagging_rule_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "tagging_rule_actions_tag_id_tags_id_fk": {
+ "name": "tagging_rule_actions_tag_id_tags_id_fk",
+ "tableFrom": "tagging_rule_actions",
+ "tableTo": "tags",
+ "columnsFrom": [
+ "tag_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tagging_rule_conditions": {
+ "name": "tagging_rule_conditions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tagging_rule_id": {
+ "name": "tagging_rule_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "field": {
+ "name": "field",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "operator": {
+ "name": "operator",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_case_sensitive": {
+ "name": "is_case_sensitive",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "tagging_rule_conditions_tagging_rule_id_tagging_rules_id_fk": {
+ "name": "tagging_rule_conditions_tagging_rule_id_tagging_rules_id_fk",
+ "tableFrom": "tagging_rule_conditions",
+ "tableTo": "tagging_rules",
+ "columnsFrom": [
+ "tagging_rule_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tagging_rules": {
+ "name": "tagging_rules",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "tagging_rules_organization_id_organizations_id_fk": {
+ "name": "tagging_rules_organization_id_organizations_id_fk",
+ "tableFrom": "tagging_rules",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "webhook_deliveries": {
+ "name": "webhook_deliveries",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "webhook_id": {
+ "name": "webhook_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "event_name": {
+ "name": "event_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "request_payload": {
+ "name": "request_payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "response_payload": {
+ "name": "response_payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "response_status": {
+ "name": "response_status",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "webhook_deliveries_webhook_id_webhooks_id_fk": {
+ "name": "webhook_deliveries_webhook_id_webhooks_id_fk",
+ "tableFrom": "webhook_deliveries",
+ "tableTo": "webhooks",
+ "columnsFrom": [
+ "webhook_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "webhook_events": {
+ "name": "webhook_events",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "webhook_id": {
+ "name": "webhook_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "event_name": {
+ "name": "event_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "webhook_events_webhook_id_event_name_unique": {
+ "name": "webhook_events_webhook_id_event_name_unique",
+ "columns": [
+ "webhook_id",
+ "event_name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "webhook_events_webhook_id_webhooks_id_fk": {
+ "name": "webhook_events_webhook_id_webhooks_id_fk",
+ "tableFrom": "webhook_events",
+ "tableTo": "webhooks",
+ "columnsFrom": [
+ "webhook_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "webhooks": {
+ "name": "webhooks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "secret": {
+ "name": "secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "webhooks_created_by_users_id_fk": {
+ "name": "webhooks_created_by_users_id_fk",
+ "tableFrom": "webhooks",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "cascade"
+ },
+ "webhooks_organization_id_organizations_id_fk": {
+ "name": "webhooks_organization_id_organizations_id_fk",
+ "tableFrom": "webhooks",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
diff --git a/apps/papra-server/src/migrations/meta/_journal.json b/apps/papra-server/src/migrations/meta/_journal.json
index 59d95ce3..80f6f14b 100644
--- a/apps/papra-server/src/migrations/meta/_journal.json
+++ b/apps/papra-server/src/migrations/meta/_journal.json
@@ -57,6 +57,20 @@
"when": 1754086182584,
"tag": "0007_document-activity-log-on-delete-set-null",
"breakpoints": true
+ },
+ {
+ "idx": 8,
+ "version": "6",
+ "when": 1756332437565,
+ "tag": "0008_document-file-encryption",
+ "breakpoints": true
+ },
+ {
+ "idx": 9,
+ "version": "6",
+ "when": 1756332955747,
+ "tag": "0009_document-file-encryption",
+ "breakpoints": true
}
]
}
diff --git a/apps/papra-server/src/migrations/migrations.registry.test.ts b/apps/papra-server/src/migrations/migrations.registry.test.ts
index 2f56f75b..a943ec45 100644
--- a/apps/papra-server/src/migrations/migrations.registry.test.ts
+++ b/apps/papra-server/src/migrations/migrations.registry.test.ts
@@ -71,6 +71,7 @@ describe('migrations registry', () => {
"CREATE UNIQUE INDEX "api_keys_key_hash_unique" ON "api_keys" ("key_hash");
CREATE INDEX "auth_sessions_token_index" ON "auth_sessions" ("token");
CREATE INDEX "auth_verifications_identifier_index" ON "auth_verifications" ("identifier");
+ CREATE INDEX documents_file_encryption_kek_version_index ON documents (file_encryption_kek_version);
CREATE INDEX "documents_organization_id_is_deleted_created_at_index" ON "documents" ("organization_id","is_deleted","created_at");
CREATE INDEX "documents_organization_id_is_deleted_index" ON "documents" ("organization_id","is_deleted");
CREATE UNIQUE INDEX "documents_organization_id_original_sha256_hash_unique" ON "documents" ("organization_id","original_sha256_hash");
@@ -94,7 +95,7 @@ describe('migrations registry', () => {
CREATE TABLE "auth_sessions" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "token" text NOT NULL, "user_id" text, "expires_at" integer NOT NULL, "ip_address" text, "user_agent" text, "active_organization_id" text, FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("active_organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE set null );
CREATE TABLE "auth_verifications" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "identifier" text NOT NULL, "value" text NOT NULL, "expires_at" integer NOT NULL );
CREATE TABLE "document_activity_log" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "document_id" text NOT NULL, "event" text NOT NULL, "event_data" text, "user_id" text, "tag_id" text, FOREIGN KEY ("document_id") REFERENCES "documents"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null, FOREIGN KEY ("tag_id") REFERENCES "tags"("id") ON UPDATE cascade ON DELETE set null );
- CREATE TABLE "documents" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "is_deleted" integer DEFAULT false NOT NULL, "deleted_at" integer, "organization_id" text NOT NULL, "created_by" text, "deleted_by" text, "original_name" text NOT NULL, "original_size" integer DEFAULT 0 NOT NULL, "original_storage_key" text NOT NULL, "original_sha256_hash" text NOT NULL, "name" text NOT NULL, "mime_type" text NOT NULL, "content" text DEFAULT '' NOT NULL, FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("created_by") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null, FOREIGN KEY ("deleted_by") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null );
+ CREATE TABLE "documents" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "is_deleted" integer DEFAULT false NOT NULL, "deleted_at" integer, "organization_id" text NOT NULL, "created_by" text, "deleted_by" text, "original_name" text NOT NULL, "original_size" integer DEFAULT 0 NOT NULL, "original_storage_key" text NOT NULL, "original_sha256_hash" text NOT NULL, "name" text NOT NULL, "mime_type" text NOT NULL, "content" text DEFAULT '' NOT NULL, file_encryption_key_wrapped TEXT, file_encryption_kek_version TEXT, file_encryption_algorithm TEXT, FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("created_by") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null, FOREIGN KEY ("deleted_by") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null );
CREATE VIRTUAL TABLE documents_fts USING fts5(id UNINDEXED, name, original_name, content, prefix='2 3 4');
CREATE TABLE 'documents_fts_config'(k PRIMARY KEY, v) WITHOUT ROWID;
CREATE TABLE 'documents_fts_content'(id INTEGER PRIMARY KEY, c0, c1, c2, c3);
diff --git a/apps/papra-server/src/migrations/migrations.registry.ts b/apps/papra-server/src/migrations/migrations.registry.ts
index 21ecf0f1..5665ad26 100644
--- a/apps/papra-server/src/migrations/migrations.registry.ts
+++ b/apps/papra-server/src/migrations/migrations.registry.ts
@@ -10,6 +10,8 @@ import { documentActivityLogMigration } from './list/0007-document-activity-log.
import { documentActivityLogOnDeleteSetNullMigration } from './list/0008-document-activity-log-on-delete-set-null.migration';
import { dropLegacyMigrationsMigration } from './list/0009-drop-legacy-migrations.migration';
+import { documentFileEncryptionMigration } from './list/0010-document-file-encryption.migration';
+
export const migrations: Migration[] = [
initialSchemaSetupMigration,
documentsFtsMigration,
@@ -20,4 +22,5 @@ export const migrations: Migration[] = [
documentActivityLogMigration,
documentActivityLogOnDeleteSetNullMigration,
dropLegacyMigrationsMigration,
+ documentFileEncryptionMigration,
];
diff --git a/apps/papra-server/src/modules/app/database/database.config.ts b/apps/papra-server/src/modules/app/database/database.config.ts
index 0e0303f3..1b40eb46 100644
--- a/apps/papra-server/src/modules/app/database/database.config.ts
+++ b/apps/papra-server/src/modules/app/database/database.config.ts
@@ -15,7 +15,7 @@ export const databaseConfig = {
env: 'DATABASE_AUTH_TOKEN',
},
encryptionKey: {
- doc: 'The encryption key for the database. If not provided, the database will not be encrypted. Use with caution as if lost, the data will be unrecoverable.',
+ doc: 'The encryption key for the database. If not provided, the database will not be encrypted at rest. Use with caution as if lost, the data will be unrecoverable.',
schema: z.string().optional(),
default: undefined,
env: 'DATABASE_ENCRYPTION_KEY',
diff --git a/apps/papra-server/src/modules/app/database/database.usecases.test.ts b/apps/papra-server/src/modules/app/database/database.usecases.test.ts
new file mode 100644
index 00000000..7c2af015
--- /dev/null
+++ b/apps/papra-server/src/modules/app/database/database.usecases.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, test } from 'vitest';
+import { usersTable } from '../../users/users.table';
+import { createInMemoryDatabase } from './database.test-utils';
+import { createIterator } from './database.usecases';
+
+const createUsers = ({ count }: { count: number }) => Array.from({ length: count }, (_, i) => ({ id: `usr_${i}`, email: `user-${i}@papra.dev` }));
+
+describe('database usecases', () => {
+ describe('createIterator', () => {
+ test('permit to iterate over a large collection of records', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: createUsers({ count: 10 }),
+ });
+
+ const query = db.select().from(usersTable).orderBy(usersTable.id).$dynamic();
+ const iterator = createIterator({ query });
+
+ const results: string[] = [];
+ for await (const record of iterator) {
+ results.push(record.id);
+ }
+
+ expect(results.length).to.eql(10);
+ expect(results).to.eql(['usr_0', 'usr_1', 'usr_2', 'usr_3', 'usr_4', 'usr_5', 'usr_6', 'usr_7', 'usr_8', 'usr_9']);
+ });
+
+ test('it works with Array.fromAsync', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: createUsers({ count: 10 }),
+ });
+
+ const query = db.select().from(usersTable).orderBy(usersTable.id).$dynamic();
+ const iterator = createIterator({ query });
+
+ const results = await Array.fromAsync(iterator);
+
+ expect(results.length).to.eql(10);
+ });
+
+ test('the amount of records per page is configurable', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: createUsers({ count: 10 }),
+ });
+
+ const query = db.select().from(usersTable).orderBy(usersTable.id).$dynamic();
+ const iterator = createIterator({ query, batchSize: 3 });
+
+ const results: string[] = [];
+ for await (const record of iterator) {
+ results.push(record.id);
+ }
+
+ expect(results.length).to.eql(10);
+ expect(results).to.eql(['usr_0', 'usr_1', 'usr_2', 'usr_3', 'usr_4', 'usr_5', 'usr_6', 'usr_7', 'usr_8', 'usr_9']);
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/app/database/database.usecases.ts b/apps/papra-server/src/modules/app/database/database.usecases.ts
new file mode 100644
index 00000000..2e4fb3ba
--- /dev/null
+++ b/apps/papra-server/src/modules/app/database/database.usecases.ts
@@ -0,0 +1,26 @@
+import type { SQLiteSelect } from 'drizzle-orm/sqlite-core';
+import type { ArrayElement } from '../../shared/types';
+
+export async function* createIterator<T extends SQLiteSelect>({
+ query,
+ batchSize = 100,
+}: { query: T; batchSize?: number }): AsyncGenerator<ArrayElement<T['_']['result']>> {
+ let offset = 0;
+
+ while (true) {
+ const results = await query.limit(batchSize).offset(offset);
+ if (results.length === 0) {
+ break;
+ }
+
+ for (const result of results) {
+ yield result as ArrayElement<T['_']['result']>;
+ }
+
+ if (results.length < batchSize) {
+ break;
+ }
+
+ offset += batchSize;
+ }
+}
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 6e21d5e3..f4760fef 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, isDocumentSizeLimitEnabled, joinStorageKeyParts } from './documents.models';
+import { buildOriginalDocumentKey, formatDocumentForApi, isDocumentSizeLimitEnabled, joinStorageKeyParts } from './documents.models';
describe('documents models', () => {
describe('joinStorageKeyParts', () => {
@@ -56,4 +56,46 @@ describe('documents models', () => {
expect(isDocumentSizeLimitEnabled({ maxUploadSize: 42 })).to.eql(true);
});
});
+
+ describe('formatDocumentForApi', () => {
+ test('formats a document from the database into a user facing document by omitting the storage key and encryption related fields', () => {
+ expect(formatDocumentForApi({
+ document: {
+ id: 'doc_1',
+ organizationId: 'org_1',
+ createdBy: 'user_1',
+ deletedAt: null,
+ deletedBy: null,
+ name: 'file.txt',
+ mimeType: 'text/plain',
+ originalName: 'file.txt',
+ originalSize: 100,
+ originalStorageKey: 'org_1/originals/doc_1.txt',
+ originalSha256Hash: '1234567890',
+ fileEncryptionAlgorithm: 'aes-256-gcm',
+ fileEncryptionKeyWrapped: '1234567890',
+ fileEncryptionKekVersion: '1.0',
+ content: 'Hello, world!',
+ isDeleted: false,
+ createdAt: new Date('2025-01-01'),
+ updatedAt: new Date('2025-01-01'),
+ },
+ })).to.eql({
+ content: 'Hello, world!',
+ createdAt: new Date('2025-01-01'),
+ createdBy: 'user_1',
+ deletedAt: null,
+ deletedBy: null,
+ id: 'doc_1',
+ isDeleted: false,
+ mimeType: 'text/plain',
+ name: 'file.txt',
+ organizationId: 'org_1',
+ originalName: 'file.txt',
+ originalSha256Hash: '1234567890',
+ originalSize: 100,
+ updatedAt: new Date('2025-01-01'),
+ });
+ });
+ });
});
diff --git a/apps/papra-server/src/modules/documents/documents.models.ts b/apps/papra-server/src/modules/documents/documents.models.ts
index 4210fb03..b80ac102 100644
--- a/apps/papra-server/src/modules/documents/documents.models.ts
+++ b/apps/papra-server/src/modules/documents/documents.models.ts
@@ -1,3 +1,6 @@
+import type { PartialBy } from '@corentinth/chisels';
+import type { DbSelectableDocument } from './documents.types';
+import { omit } from 'lodash-es';
import { getExtension } from '../shared/files/file-names';
import { generateId } from '../shared/random/ids';
import { isDefined } from '../shared/utils';
@@ -24,3 +27,21 @@ export function generateDocumentId() {
export function isDocumentSizeLimitEnabled({ maxUploadSize }: { maxUploadSize: number }) {
return maxUploadSize > 0;
}
+
+export function formatDocumentForApi<T extends PartialBy<DbSelectableDocument, 'content'>>({ document }: { document: T }) {
+ return {
+ ...omit(
+ document,
+ [
+ 'fileEncryptionAlgorithm',
+ 'fileEncryptionKeyWrapped',
+ 'fileEncryptionKekVersion',
+ 'originalStorageKey',
+ ],
+ ),
+ };
+}
+
+export function formatDocumentsForApi<T extends PartialBy<DbSelectableDocument, 'content'>>({ documents }: { documents: T[] }) {
+ return documents.map(document => formatDocumentForApi({ document }));
+}
diff --git a/apps/papra-server/src/modules/documents/documents.repository.ts b/apps/papra-server/src/modules/documents/documents.repository.ts
index d2bc5241..610d7fe2 100644
--- a/apps/papra-server/src/modules/documents/documents.repository.ts
+++ b/apps/papra-server/src/modules/documents/documents.repository.ts
@@ -379,5 +379,10 @@ async function updateDocument({ documentId, organizationId, name, content, db }:
)
.returning();
+ if (isNil(document)) {
+ // This should never happen, but for type safety
+ throw createDocumentNotFoundError();
+ }
+
return { document };
}
diff --git a/apps/papra-server/src/modules/documents/documents.routes.ts b/apps/papra-server/src/modules/documents/documents.routes.ts
index 576f57f4..cac7dd06 100644
--- a/apps/papra-server/src/modules/documents/documents.routes.ts
+++ b/apps/papra-server/src/modules/documents/documents.routes.ts
@@ -13,6 +13,7 @@ import { deferTriggerWebhooks } from '../webhooks/webhook.usecases';
import { createDocumentActivityRepository } from './document-activity/document-activity.repository';
import { deferRegisterDocumentActivityLog } from './document-activity/document-activity.usecases';
import { createDocumentIsNotDeletedError } from './documents.errors';
+import { formatDocumentForApi, formatDocumentsForApi } from './documents.models';
import { createDocumentsRepository } from './documents.repository';
import { documentIdSchema } from './documents.schemas';
import { createDocumentCreationUsecase, deleteAllTrashDocuments, deleteTrashDocument, ensureDocumentExists, getDocumentOrThrow } from './documents.usecases';
@@ -52,7 +53,7 @@ function setupCreateDocumentRoute({ app, ...deps }: RouteDefinitionContext) {
const { document } = await createDocument({ fileStream, fileName, mimeType, userId, organizationId });
- return context.json({ document });
+ return context.json({ document: formatDocumentForApi({ document }) });
},
);
}
@@ -94,7 +95,7 @@ function setupGetDocumentsRoute({ app, db }: RouteDefinitionContext) {
]);
return context.json({
- documents,
+ documents: formatDocumentsForApi({ documents }),
documentsCount,
});
},
@@ -134,7 +135,7 @@ function setupGetDeletedDocumentsRoute({ app, db }: RouteDefinitionContext) {
]);
return context.json({
- documents,
+ documents: formatDocumentsForApi({ documents }),
documentsCount,
});
},
@@ -162,7 +163,7 @@ function setupGetDocumentRoute({ app, db }: RouteDefinitionContext) {
const { document } = await getDocumentOrThrow({ documentId, organizationId, documentsRepository });
return context.json({
- document,
+ document: formatDocumentForApi({ document }),
});
},
);
@@ -271,7 +272,12 @@ function setupGetDocumentFileRoute({ app, db, documentsStorageService }: RouteDe
const { document } = await getDocumentOrThrow({ documentId, documentsRepository, organizationId });
- const { fileStream } = await documentsStorageService.getFileStream({ storageKey: document.originalStorageKey });
+ const { fileStream } = await documentsStorageService.getFileStream({
+ storageKey: document.originalStorageKey,
+ fileEncryptionAlgorithm: document.fileEncryptionAlgorithm,
+ fileEncryptionKekVersion: document.fileEncryptionKekVersion,
+ fileEncryptionKeyWrapped: document.fileEncryptionKeyWrapped,
+ });
return context.body(
Readable.toWeb(fileStream),
@@ -314,7 +320,7 @@ function setupSearchDocumentsRoute({ app, db }: RouteDefinitionContext) {
const { documents } = await documentsRepository.searchOrganizationDocuments({ organizationId, searchQuery, pageIndex, pageSize });
return context.json({
- documents,
+ documents: formatDocumentsForApi({ documents }),
});
},
);
@@ -450,7 +456,7 @@ function setupUpdateDocumentRoute({ app, db }: RouteDefinitionContext) {
},
});
- return context.json({ document });
+ return context.json({ document: formatDocumentForApi({ document }) });
},
);
}
diff --git a/apps/papra-server/src/modules/documents/documents.table.ts b/apps/papra-server/src/modules/documents/documents.table.ts
index d8032dcb..9c38895d 100644
--- a/apps/papra-server/src/modules/documents/documents.table.ts
+++ b/apps/papra-server/src/modules/documents/documents.table.ts
@@ -21,6 +21,10 @@ export const documentsTable = sqliteTable('documents', {
name: text('name').notNull(),
mimeType: text('mime_type').notNull(),
content: text('content').notNull().default(''),
+
+ fileEncryptionKeyWrapped: text('file_encryption_key_wrapped'), // The wrapped encryption key
+ fileEncryptionKekVersion: text('file_encryption_kek_version'), // The key encryption key version used to encrypt the file encryption key
+ fileEncryptionAlgorithm: text('file_encryption_algorithm'),
}, table => [
// To select paginated documents by organization
index('documents_organization_id_is_deleted_created_at_index').on(table.organizationId, table.isDeleted, table.createdAt),
@@ -32,4 +36,6 @@ export const documentsTable = sqliteTable('documents', {
index('documents_original_sha256_hash_index').on(table.originalSha256Hash),
// To sum the size of documents by organization
index('documents_organization_id_size_index').on(table.organizationId, table.originalSize),
+ // To list documents by file encryption KEK version
+ index('documents_file_encryption_kek_version_index').on(table.fileEncryptionKekVersion),
]);
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 64a5366e..913a6f77 100644
--- a/apps/papra-server/src/modules/documents/documents.usecases.test.ts
+++ b/apps/papra-server/src/modules/documents/documents.usecases.test.ts
@@ -250,6 +250,7 @@ describe('documents usecases', () => {
const config = overrideConfig({
organizationPlans: { isFreePlanUnlimited: true },
+ documentsStorage: { driver: 'in-memory' },
});
const documentsRepository = createDocumentsRepository({ db });
diff --git a/apps/papra-server/src/modules/documents/documents.usecases.ts b/apps/papra-server/src/modules/documents/documents.usecases.ts
index 83358212..be0a3f31 100644
--- a/apps/papra-server/src/modules/documents/documents.usecases.ts
+++ b/apps/papra-server/src/modules/documents/documents.usecases.ts
@@ -13,6 +13,7 @@ import type { DocumentActivityRepository } from './document-activity/document-ac
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 { safely } from '@corentinth/chisels';
import pLimit from 'p-limit';
import { createOrganizationDocumentStorageLimitReachedError } from '../organizations/organizations.errors';
@@ -22,7 +23,7 @@ import { createLogger } from '../shared/logger/logger';
import { createByteCounter } from '../shared/streams/byte-counter';
import { createSha256HashTransformer } from '../shared/streams/stream-hash';
import { collectStreamToFile } from '../shared/streams/stream.convertion';
-import { isDefined } from '../shared/utils';
+import { isDefined, isNil } from '../shared/utils';
import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';
import { createTaggingRulesRepository } from '../tagging-rules/tagging-rules.repository';
import { applyTaggingRules } from '../tagging-rules/tagging-rules.usecases';
@@ -37,6 +38,10 @@ import { buildOriginalDocumentKey, generateDocumentId as generateDocumentIdImpl
import { createDocumentsRepository } from './documents.repository';
import { extractDocumentText } from './documents.services';
+type DocumentStorageContext = {
+ storageKey: string;
+} & EncryptionContext;
+
export async function createDocument({
fileStream,
fileName,
@@ -101,7 +106,7 @@ export async function createDocument({
.pipe(byteCountStream);
// We optimistically save the file to leverage streaming, if the file already exists, we will delete it
- await documentsStorageService.saveFile({
+ const newFileStorageContext = await documentsStorageService.saveFile({
fileStream: outputStream,
storageKey: originalDocumentStorageKey,
mimeType,
@@ -120,14 +125,14 @@ export async function createDocument({
fileName,
organizationId,
documentsRepository,
- newDocumentStorageKey: originalDocumentStorageKey,
+ newDocumentStorageKey: newFileStorageContext.storageKey,
tagsRepository,
taggingRulesRepository,
documentsStorageService,
logger,
})
: await createNewDocument({
- newDocumentStorageKey: originalDocumentStorageKey,
+ newFileStorageContext,
fileName,
size,
mimeType,
@@ -259,7 +264,7 @@ async function createNewDocument({
subscriptionsRepository,
documentsRepository,
documentsStorageService,
- newDocumentStorageKey,
+ newFileStorageContext,
documentId,
trackingServices,
taskServices,
@@ -278,7 +283,7 @@ async function createNewDocument({
plansRepository: PlansRepository;
subscriptionsRepository: SubscriptionsRepository;
trackingServices: TrackingServices;
- newDocumentStorageKey: string;
+ newFileStorageContext: DocumentStorageContext;
taskServices: TaskServices;
ocrLanguages?: string[];
logger: Logger;
@@ -290,7 +295,7 @@ async function createNewDocument({
if (size > availableDocumentStorageBytes) {
logger.error({ size, availableDocumentStorageBytes }, 'Document size exceeds organization storage limit after being saved');
- await documentsStorageService.deleteFile({ storageKey: newDocumentStorageKey });
+ await documentsStorageService.deleteFile({ storageKey: newFileStorageContext.storageKey });
throw createOrganizationDocumentStorageLimitReachedError();
}
@@ -302,7 +307,10 @@ async function createNewDocument({
originalName: fileName,
createdBy: userId,
originalSize: size,
- originalStorageKey: newDocumentStorageKey,
+ originalStorageKey: newFileStorageContext.storageKey,
+ fileEncryptionAlgorithm: newFileStorageContext.fileEncryptionAlgorithm,
+ fileEncryptionKekVersion: newFileStorageContext.fileEncryptionKekVersion,
+ fileEncryptionKeyWrapped: newFileStorageContext.fileEncryptionKeyWrapped,
mimeType,
originalSha256Hash: hash,
}));
@@ -311,7 +319,7 @@ async function createNewDocument({
logger.error({ error }, 'Error while creating document');
// If the document is not saved, delete the file from the storage
- await documentsStorageService.deleteFile({ storageKey: newDocumentStorageKey });
+ await documentsStorageService.deleteFile({ storageKey: newFileStorageContext.storageKey });
logger.error({ error }, 'Stored document file deleted because of error');
@@ -479,7 +487,12 @@ export async function extractAndSaveDocumentFileContent({
throw createDocumentNotFoundError();
}
- const { fileStream } = await documentsStorageService.getFileStream({ storageKey: document.originalStorageKey });
+ const { fileStream } = await documentsStorageService.getFileStream({
+ storageKey: document.originalStorageKey,
+ fileEncryptionAlgorithm: document.fileEncryptionAlgorithm,
+ fileEncryptionKekVersion: document.fileEncryptionKekVersion,
+ fileEncryptionKeyWrapped: document.fileEncryptionKeyWrapped,
+ });
const { file } = await collectStreamToFile({ fileStream, fileName: document.name, mimeType: document.mimeType });
@@ -487,7 +500,7 @@ export async function extractAndSaveDocumentFileContent({
const { document: updatedDocument } = await documentsRepository.updateDocument({ documentId, organizationId, content: text });
- if (!updatedDocument) {
+ if (isNil(updatedDocument)) {
// This should never happen, but for type safety
throw createDocumentNotFoundError();
}
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 47e26f19..2d44b0ff 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
@@ -4,6 +4,7 @@ import { AZ_BLOB_STORAGE_DRIVER_NAME } from './drivers/az-blob/az-blob.storage-d
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';
export const documentStorageConfig = {
maxUploadSize: {
@@ -92,4 +93,5 @@ export const documentStorageConfig = {
},
},
},
+ encryption: documentEncryptionConfig,
} as const satisfies ConfigDefinition;
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
index b2e996f1..cb921e99 100644
--- a/apps/papra-server/src/modules/documents/storage/documents.storage.services.ts
+++ b/apps/papra-server/src/modules/documents/storage/documents.storage.services.ts
@@ -1,10 +1,12 @@
import type { Config } from '../../config/config.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,
@@ -15,10 +17,10 @@ const storageDriverFactories = {
export type DocumentStorageService = Awaited<ReturnType<typeof createDocumentStorageService>>;
-export function createDocumentStorageService({ config }: { config: Config }) {
+export function createDocumentStorageService({ config }: { config: Config }): StorageServices {
const storageDriverName = config.documentsStorage.driver;
- const storageDriverFactory = storageDriverFactories[storageDriverName];
+ const storageDriverFactory: StorageDriverFactory | undefined = storageDriverFactories[storageDriverName];
if (isNil(storageDriverFactory)) {
throw createError({
@@ -31,5 +33,18 @@ export function createDocumentStorageService({ config }: { config: Config }) {
const storageDriver = storageDriverFactory({ config });
- return storageDriver;
+ return createDocumentStorageServiceFromDriver({
+ storageDriver,
+ encryptionConfig: config.documentsStorage.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/drivers/drivers.models.ts b/apps/papra-server/src/modules/documents/storage/drivers/drivers.models.ts
index 841bb22e..b5dc6fa5 100644
--- a/apps/papra-server/src/modules/documents/storage/drivers/drivers.models.ts
+++ b/apps/papra-server/src/modules/documents/storage/drivers/drivers.models.ts
@@ -1,5 +1,6 @@
import type { Readable } from 'node:stream';
import type { Config } from '../../../config/config.types';
+import type { ExtendNamedArguments, ExtendReturnPromise } from '../../../shared/types';
export type StorageDriver = {
name: string;
@@ -17,6 +18,19 @@ export type StorageDriver = {
deleteFile: (args: { storageKey: string }) => Promise<void>;
};
+export type EncryptionContext = {
+ fileEncryptionKeyWrapped?: string | null | undefined;
+ fileEncryptionAlgorithm?: string | null | undefined;
+ fileEncryptionKekVersion?: string | null | undefined;
+};
+
+// Same as the driver but with the encryption context added in the args
+export type StorageServices = {
+ saveFile: ExtendReturnPromise<StorageDriver['saveFile'], EncryptionContext>;
+ getFileStream: ExtendNamedArguments<StorageDriver['getFileStream'], EncryptionContext>;
+ deleteFile: StorageDriver['deleteFile'];
+};
+
export type StorageDriverFactory = (args: { config: Config }) => StorageDriver;
export function defineStorageDriver<T extends StorageDriverFactory>(factory: T) {
diff --git a/apps/papra-server/src/modules/documents/storage/drivers/drivers.test-suite.ts b/apps/papra-server/src/modules/documents/storage/drivers/drivers.test-suite.ts
index fdcf0ca4..f0c332b2 100644
--- a/apps/papra-server/src/modules/documents/storage/drivers/drivers.test-suite.ts
+++ b/apps/papra-server/src/modules/documents/storage/drivers/drivers.test-suite.ts
@@ -1,33 +1,60 @@
-import type { StorageDriver } from './drivers.models';
+import type { StorageDriver, StorageServices } from './drivers.models';
+import { Buffer } from 'node:buffer';
import { describe, expect, test } from 'vitest';
import { collectReadableStreamToString, createReadableStream } from '../../../shared/streams/readable-stream';
import { createFileNotFoundError } from '../document-storage.errors';
+import { wrapWithEncryptionLayer } from '../encryption/document-encryption.services';
-export function runDriverTestSuites({ createDriver, timeout, retry }: { createDriver: () => Promise<{ driver: StorageDriver; [Symbol.asyncDispose]: () => Promise<void> }>; timeout?: number; retry?: number }) {
- describe('upload, download, delete', () => {
- test('the driver should support uploading, retrieving and deleting files', { timeout, retry }, async () => {
- await using resource = await createDriver();
+export function runDriverTestSuites({ createDriver: createDriverBase, timeout, retry }: { createDriver: () => Promise<{ driver: StorageDriver; [Symbol.asyncDispose]: () => Promise<void> }>; timeout?: number; retry?: number }) {
+ [
+ {
+ name: 'without encryption',
+ createStorageService: async () => {
+ const { driver, [Symbol.asyncDispose]: dispose } = await createDriverBase();
- const { driver } = resource;
+ return {
+ storageServices: driver as StorageServices,
+ [Symbol.asyncDispose]: dispose,
+ };
+ },
+ },
+ {
+ name: 'with encryption',
+ createStorageService: async () => {
+ const { driver, [Symbol.asyncDispose]: dispose } = await createDriverBase();
- // 1. Save the file
- await driver.saveFile({
- fileName: 'test.txt',
- mimeType: 'text/plain',
- storageKey: 'files/test.txt',
- fileStream: createReadableStream({ content: 'Hello, world!' }),
- });
+ return {
+ storageServices: wrapWithEncryptionLayer({ storageDriver: driver, encryptionConfig: { isEncryptionEnabled: true, documentKeyEncryptionKeys: [{ version: '1', key: Buffer.from('622b55bec85b3fca6fbad2d1c5ef1d67ed19b24eece069961cd430370735c2ff', 'hex') }] } }),
+ [Symbol.asyncDispose]: dispose,
+ };
+ },
+ },
+ ].forEach(({ createStorageService, name }) => {
+ describe(name, () => {
+ test('the driver should support uploading, retrieving and deleting files', { timeout, retry }, async () => {
+ await using resource = await createStorageService();
+
+ const { storageServices } = resource;
- // 2. Retrieve the file
- const { fileStream } = await driver.getFileStream({ storageKey: 'files/test.txt' });
- expect(await collectReadableStreamToString({ stream: fileStream })).to.eql('Hello, world!');
+ // 1. Save the file
+ const storageContext = await storageServices.saveFile({
+ fileName: 'test.txt',
+ mimeType: 'text/plain',
+ storageKey: 'files/test.txt',
+ fileStream: createReadableStream({ content: 'Hello, world!' }),
+ });
- // 3. Delete the file
- await driver.deleteFile({ storageKey: 'files/test.txt' });
- await expect(driver.getFileStream({ storageKey: 'files/test.txt' })).rejects.toThrow(createFileNotFoundError());
+ // 2. Retrieve the file
+ const { fileStream } = await storageServices.getFileStream({ ...storageContext, storageKey: 'files/test.txt' });
+ expect(await collectReadableStreamToString({ stream: fileStream })).to.eql('Hello, world!');
- // 4. Try to delete the file again
- await expect(driver.deleteFile({ storageKey: 'files/test.txt' })).rejects.toThrow(createFileNotFoundError());
+ // 3. Delete the file
+ await storageServices.deleteFile({ storageKey: 'files/test.txt' });
+ await expect(storageServices.getFileStream({ storageKey: 'files/test.txt' })).rejects.toThrow(createFileNotFoundError());
+
+ // 4. Try to delete the file again
+ await expect(storageServices.deleteFile({ storageKey: 'files/test.txt' })).rejects.toThrow(createFileNotFoundError());
+ });
});
});
}
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.config.ts b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.config.ts
new file mode 100644
index 00000000..1f02f6eb
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.config.ts
@@ -0,0 +1,28 @@
+import type { ConfigDefinition } from 'figue';
+import { booleanishSchema } from '../../../config/config.schemas';
+import { documentKeyEncryptionKeysSchema } from './document-encryption.schemas';
+
+export const documentEncryptionConfig = {
+ isEncryptionEnabled: {
+ doc: 'Whether to enable encryption for documents',
+ schema: booleanishSchema,
+ default: false,
+ env: 'DOCUMENT_STORAGE_ENCRYPTION_IS_ENABLED',
+ },
+ documentKeyEncryptionKeys: {
+ doc: `
+Key encryption keys (KEKs) used to encrypt the document encryption key (DEK), as 32-byte hex strings, you can generate one using the command \`openssl rand -hex 32\`.
+
+Formats:
+- Single key: \`0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c\` (will be assigned version \`1\`)
+- Multiple keys: \`1:<key1>,2:<key2>\`
+ - The key with the highest version will be used to encrypt new DEKs, others will be used to decrypt existing DEKs
+ - Versions must be unique and can be any alphabetically sortable string
+ - The order of the version:key pair is not important
+`.trim(),
+ schema: documentKeyEncryptionKeysSchema,
+ default: undefined,
+ env: 'DOCUMENT_STORAGE_DOCUMENT_KEY_ENCRYPTION_KEYS',
+ },
+
+} as const satisfies ConfigDefinition;
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.constants.ts b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.constants.ts
new file mode 100644
index 00000000..48f7b783
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.constants.ts
@@ -0,0 +1,5 @@
+export const ENCRYPTION_ALGORITHMS = {
+ AES_256_GCM: 'aes-256-gcm',
+} as const;
+
+export const WRAPPED_ENCRYPTION_KEY_ENCODING = 'base64';
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
new file mode 100644
index 00000000..38569afc
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.models.test.ts
@@ -0,0 +1,44 @@
+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.models.ts b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.models.ts
new file mode 100644
index 00000000..5f3d8cb5
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.models.ts
@@ -0,0 +1,65 @@
+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';
+
+type DocumentKeyEncryptionKey = {
+ version: string;
+ key: Buffer;
+};
+
+export function getMostRecentDocumentKek({ documentKeyEncryptionKeys = [] }: { documentKeyEncryptionKeys?: DocumentKeyEncryptionKey[] }): DocumentKeyEncryptionKey {
+ const sortedKeys = documentKeyEncryptionKeys.sort((a, b) => a.version.localeCompare(b.version));
+ const mostRecentKey = sortedKeys[sortedKeys.length - 1];
+
+ if (isNil(mostRecentKey)) {
+ throw createDocumentKekRequiredError();
+ }
+
+ return mostRecentKey;
+}
+
+export function getKekByVersion({ documentKeyEncryptionKeys = [], version }: { documentKeyEncryptionKeys?: DocumentKeyEncryptionKey[]; version: string }): DocumentKeyEncryptionKey {
+ const kek = documentKeyEncryptionKeys.find(kek => kek.version === version);
+
+ if (isNil(kek)) {
+ throw createDocumentKekNotFoundError();
+ }
+
+ return kek;
+}
+
+export function createNewEncryptionKey() {
+ return crypto.randomBytes(32);
+}
+
+export function wrapEncryptionKey({ encryptionKey, kek }: { encryptionKey: Buffer; kek: DocumentKeyEncryptionKey }): string {
+ try {
+ return encrypt({ key: kek.key, value: encryptionKey }).toString(WRAPPED_ENCRYPTION_KEY_ENCODING);
+ } catch (error) {
+ throw createError({
+ message: 'Unable to wrap encryption key',
+ code: 'storage_driver.encryption.unable_to_wrap_encryption_key',
+ statusCode: 500,
+ isInternal: true,
+ cause: error,
+ });
+ }
+}
+
+export function unwrapEncryptionKey({ wrappedEncryptionKey, kek }: { wrappedEncryptionKey: string; kek: DocumentKeyEncryptionKey }): Buffer {
+ try {
+ return decrypt({ encryptedValue: Buffer.from(wrappedEncryptionKey, WRAPPED_ENCRYPTION_KEY_ENCODING), key: kek.key });
+ } catch (error) {
+ throw createError({
+ message: 'Unable to unwrap encryption key, the key might be invalid',
+ code: 'storage_driver.encryption.unable_to_unwrap_encryption_key',
+ statusCode: 500,
+ isInternal: true,
+ cause: error,
+ });
+ }
+}
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.test.ts b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.test.ts
new file mode 100644
index 00000000..515a3112
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.test.ts
@@ -0,0 +1,38 @@
+import { Buffer } from 'node:buffer';
+import { describe, expect, test } from 'vitest';
+import { documentKeyEncryptionKeysSchema } from './document-encryption.schemas';
+
+describe('document-encryption schemas', () => {
+ describe('documentKeyEncryptionKeysSchema', () => {
+ test('the user can provide a comma separated list of 32 bytes long hex strings env variable', () => {
+ const env = '1:0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c,2:abdc13ff846337ef514a62d7d2cd2aa3b517d957ab7c825b8de0c7678f17a843';
+
+ expect(
+ documentKeyEncryptionKeysSchema.parse(env),
+ ).to.eql([
+ {
+ version: '1',
+ key: Buffer.from('0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c', 'hex'),
+ },
+ {
+ version: '2',
+ key: Buffer.from('abdc13ff846337ef514a62d7d2cd2aa3b517d957ab7c825b8de0c7678f17a843', 'hex'),
+ },
+ ]);
+ });
+
+ test('the user can provide a single 32 bytes long hex string env variable', () => {
+ const env = '0deba5534bd70548de92d1fd4ae37cf901cca3dc20589b7e022ddb680c98e50c';
+
+ expect(
+ documentKeyEncryptionKeysSchema.parse(env),
+ ).to.eql([{ version: '1', key: Buffer.from(env, 'hex') }]);
+ });
+
+ test('no keys provided should not raise an error', () => {
+ expect(
+ documentKeyEncryptionKeysSchema.parse(undefined),
+ ).to.eql(undefined);
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.ts b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.ts
new file mode 100644
index 00000000..d8b32e03
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.schemas.ts
@@ -0,0 +1,40 @@
+import { Buffer } from 'node:buffer';
+import { z } from 'zod';
+
+export const documentKeyEncryptionKeySchema = z.object({
+ version: z.string(),
+ key: z.instanceof(Buffer).refine(x => x.length === 32, { message: 'The key must be a 32 bytes long hex string' }),
+});
+
+const documentKeyEncryptionKeyArraySchema = z
+ .array(documentKeyEncryptionKeySchema)
+ .refine(x => x.length === new Set(x.map(x => x.version)).size, { message: 'The keys must have unique versions' });
+
+export const documentKeyEncryptionKeysSchema = z.union([
+ documentKeyEncryptionKeyArraySchema,
+ z.string().transform((x) => {
+ if (x.match(/^[0-9a-f]{64}$/i)) {
+ return [{
+ version: '1',
+ key: Buffer.from(x, 'hex'),
+ }];
+ }
+
+ const keys = x.split(',').map(x => x.trim().split(':')).map(([version, key]) => {
+ if (version === undefined || key === undefined) {
+ return undefined;
+ }
+
+ return {
+ version,
+ key: Buffer.from(key, 'hex'),
+ };
+ });
+
+ if (keys.length === 0) {
+ return undefined;
+ }
+
+ return keys;
+ }).pipe(documentKeyEncryptionKeyArraySchema),
+]).optional();
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.services.ts b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.services.ts
new file mode 100644
index 00000000..9a643fb2
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.services.ts
@@ -0,0 +1,62 @@
+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 { createNewEncryptionKey, getKekByVersion, getMostRecentDocumentKek, unwrapEncryptionKey, wrapEncryptionKey } from './document-encryption.models';
+import { createUnsupportedEncryptionAlgorithmError } from './document-encryptions.errors';
+
+export function wrapWithEncryptionLayer({ storageDriver, encryptionConfig }: { storageDriver: StorageDriver; encryptionConfig: Config['documentsStorage']['encryption'] }): StorageServices {
+ const { isEncryptionEnabled, documentKeyEncryptionKeys } = encryptionConfig;
+
+ return {
+ ...storageDriver,
+ saveFile: async (driverArgs) => {
+ const { fileStream, ...rest } = driverArgs;
+
+ if (!isEncryptionEnabled) {
+ return storageDriver.saveFile(driverArgs);
+ }
+
+ // Create a random 32 bytes encryption key
+ const encryptionKey = createNewEncryptionKey();
+
+ const encryptedFileStream = createEncryptTransformer({ key: encryptionKey });
+
+ const driverResult = await storageDriver.saveFile({
+ fileStream: fileStream.pipe(encryptedFileStream),
+ ...rest,
+ });
+
+ // In order to store the encryption key, we encrypt it with the most recent KEK from the config
+ const kek = getMostRecentDocumentKek({ documentKeyEncryptionKeys });
+
+ return {
+ ...driverResult,
+ fileEncryptionKeyWrapped: wrapEncryptionKey({ encryptionKey, kek }),
+ fileEncryptionAlgorithm: ENCRYPTION_ALGORITHMS.AES_256_GCM,
+ fileEncryptionKekVersion: kek.version,
+ };
+ },
+ getFileStream: async ({ fileEncryptionKeyWrapped, fileEncryptionKekVersion, fileEncryptionAlgorithm, ...driverArgs }) => {
+ const { fileStream } = await storageDriver.getFileStream(driverArgs);
+
+ if (isNil(fileEncryptionKeyWrapped) || isNil(fileEncryptionKekVersion) || isNil(fileEncryptionAlgorithm)) {
+ // If the file is not encrypted, we return the file stream as is
+ return { fileStream };
+ }
+
+ if (fileEncryptionAlgorithm !== ENCRYPTION_ALGORITHMS.AES_256_GCM) {
+ throw createUnsupportedEncryptionAlgorithmError();
+ }
+
+ const kek = getKekByVersion({ documentKeyEncryptionKeys, version: fileEncryptionKekVersion });
+
+ const encryptionKey = unwrapEncryptionKey({ wrappedEncryptionKey: fileEncryptionKeyWrapped, kek });
+
+ return {
+ fileStream: fileStream.pipe(createDecryptTransformer({ key: encryptionKey })),
+ };
+ },
+ };
+}
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.usecases.test.ts b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.usecases.test.ts
new file mode 100644
index 00000000..dfa0028e
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.usecases.test.ts
@@ -0,0 +1,104 @@
+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 { 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 { encryptAllUnencryptedDocuments } from './document-encryption.usecases';
+
+export const noopTaskServices = {
+ scheduleJob: async _args => Promise.resolve({ jobId: '1' }),
+} as TaskServices;
+
+describe('document-encryption usecases', () => {
+ describe('encryptAllUnencryptedDocuments', () => {
+ test('given a papra instance with some encrypted and some unencrypted documents, it should encrypt all unencrypted documents', async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org-1', name: 'Org 1' }],
+ });
+
+ const storageDriver = inMemoryStorageDriverFactory();
+
+ const createDocumentWithoutEncryption = await createDocumentCreationUsecase({
+ db,
+ config: overrideConfig(),
+ taskServices: noopTaskServices,
+ documentsStorageService: createDocumentStorageServiceFromDriver({
+ storageDriver,
+ encryptionConfig: {
+ isEncryptionEnabled: false,
+ documentKeyEncryptionKeys: [],
+ },
+ }),
+ });
+
+ const { document: document1 } = await createDocumentWithoutEncryption({
+ fileName: 'Doc 1.txt',
+ mimeType: 'text/plain',
+ organizationId: 'org-1',
+ fileStream: Readable.from(Buffer.from('Hello, world! - 1')),
+ });
+
+ const { document: document2 } = await createDocumentWithoutEncryption({
+ fileName: 'Doc 2.txt',
+ mimeType: 'text/plain',
+ organizationId: 'org-1',
+ fileStream: Readable.from(Buffer.from('Hello, world! - 2')),
+ });
+
+ const documentStorageServiceWithEncryption = createDocumentStorageServiceFromDriver({
+ storageDriver,
+ encryptionConfig: {
+ isEncryptionEnabled: true,
+ documentKeyEncryptionKeys: [{
+ key: Buffer.from('64/4Ep2f/3ylsg9wIUeeZ7oIFPCyM6IaPjoLrhQCBSo=', 'base64'),
+ version: '1',
+ }],
+ },
+ });
+
+ const createDocumentWithEncryption = await createDocumentCreationUsecase({
+ db,
+ documentsStorageService: documentStorageServiceWithEncryption,
+ config: overrideConfig(),
+ taskServices: noopTaskServices,
+ });
+
+ const { document: document3 } = await createDocumentWithEncryption({
+ fileName: 'Doc 3.txt',
+ mimeType: 'text/plain',
+ organizationId: 'org-1',
+ fileStream: Readable.from(Buffer.from('Hello, world! - 3')),
+ });
+
+ // Ensure document 1 and 2 are readable while document 3 is not
+ const storage = storageDriver._getStorage();
+
+ expect(storage.get(document1.originalStorageKey)?.content.toString('utf-8')).toEqual('Hello, world! - 1');
+ expect(storage.get(document2.originalStorageKey)?.content.toString('utf-8')).toEqual('Hello, world! - 2');
+ // Encrypted document should start with PP01
+ const encryptedDocument3 = storage.get(document3.originalStorageKey)?.content;
+ expect(encryptedDocument3?.subarray(0, 4).toString('utf-8')).toEqual('PP01');
+
+ await encryptAllUnencryptedDocuments({
+ db,
+ documentStorageService: documentStorageServiceWithEncryption,
+ });
+
+ // All documents should be encrypted
+
+ const [newDocument1, newDocument2, newDocument3] = await db.select().from(documentsTable).orderBy(documentsTable.createdAt);
+
+ expect(storage.get(newDocument1!.originalStorageKey)?.content.subarray(0, 4).toString('utf-8')).toEqual('PP01');
+ expect(storage.get(newDocument2!.originalStorageKey)?.content.subarray(0, 4).toString('utf-8')).toEqual('PP01');
+ expect(storage.get(newDocument3!.originalStorageKey)?.content.subarray(0, 4).toString('utf-8')).toEqual('PP01');
+
+ // The document 3 should have the same original storage key
+ expect(document3.originalStorageKey).to.eql(newDocument3!.originalStorageKey);
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.usecases.ts b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.usecases.ts
new file mode 100644
index 00000000..060a6b2e
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/encryption/document-encryption.usecases.ts
@@ -0,0 +1,48 @@
+import type { Logger } from '@crowlog/logger';
+import type { Database } from '../../../app/database/database.types';
+import type { DocumentStorageService } from '../documents.storage.services';
+import { eq, isNull } from 'drizzle-orm';
+import { createLogger } from '../../../shared/logger/logger';
+import { documentsTable } from '../../documents.table';
+
+export async function encryptAllUnencryptedDocuments({
+ db,
+ documentStorageService,
+ logger = createLogger({ namespace: 'encryptAllUnencryptedDocuments' }),
+ deleteUnencryptedAfterEncryption = true,
+}: {
+ db: Database;
+ logger?: Logger;
+ documentStorageService: DocumentStorageService;
+ deleteUnencryptedAfterEncryption?: boolean;
+}) {
+ const documents = await db
+ .select({ id: documentsTable.id, originalStorageKey: documentsTable.originalStorageKey, fileName: documentsTable.originalName, mimeType: documentsTable.mimeType })
+ .from(documentsTable)
+ .where(isNull(documentsTable.fileEncryptionKeyWrapped))
+ .orderBy(documentsTable.id);
+
+ logger.info(`Found ${documents.length} documents to encrypt`);
+
+ for (const { id, originalStorageKey, fileName, mimeType } of documents) {
+ logger.info(`Encrypting document ${id}`);
+
+ const { fileStream } = await documentStorageService.getFileStream({
+ storageKey: originalStorageKey,
+ fileEncryptionKeyWrapped: null,
+ fileEncryptionAlgorithm: null,
+ fileEncryptionKekVersion: null,
+ });
+ const newStorageKey = `${originalStorageKey}.enc`;
+ const { storageKey, ...encryptionFields } = await documentStorageService.saveFile({ fileStream, fileName, mimeType, storageKey: newStorageKey });
+
+ await db.update(documentsTable).set({
+ ...encryptionFields,
+ originalStorageKey: storageKey,
+ }).where(eq(documentsTable.id, id));
+
+ if (deleteUnencryptedAfterEncryption) {
+ await documentStorageService.deleteFile({ storageKey: originalStorageKey });
+ }
+ }
+}
diff --git a/apps/papra-server/src/modules/documents/storage/encryption/document-encryptions.errors.ts b/apps/papra-server/src/modules/documents/storage/encryption/document-encryptions.errors.ts
new file mode 100644
index 00000000..6b7cff5e
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/storage/encryption/document-encryptions.errors.ts
@@ -0,0 +1,22 @@
+import { createErrorFactory } from '../../../shared/errors/errors';
+
+export const createDocumentKekRequiredError = createErrorFactory({
+ message: 'Document key encryption keys are required',
+ code: 'storage_driver.document_key_encryption_keys_required',
+ isInternal: true,
+ statusCode: 500,
+});
+
+export const createUnsupportedEncryptionAlgorithmError = createErrorFactory({
+ message: 'Unsupported encryption algorithm',
+ code: 'storage_driver.unsupported_encryption_algorithm',
+ isInternal: true,
+ statusCode: 500,
+});
+
+export const createDocumentKekNotFoundError = createErrorFactory({
+ message: 'Document key encryption key not found',
+ code: 'storage_driver.document_key_encryption_key_not_found',
+ isInternal: true,
+ statusCode: 500,
+});
diff --git a/apps/papra-server/src/modules/shared/crypto/encryption.test.ts b/apps/papra-server/src/modules/shared/crypto/encryption.test.ts
new file mode 100644
index 00000000..634dd228
--- /dev/null
+++ b/apps/papra-server/src/modules/shared/crypto/encryption.test.ts
@@ -0,0 +1,95 @@
+import { Buffer } from 'node:buffer';
+import { Readable, Writable } from 'node:stream';
+import { pipeline } from 'node:stream/promises';
+import { describe, expect, test } from 'vitest';
+import { collectReadableStreamToString } from '../streams/readable-stream';
+import { createDecryptTransformer, createEncryptTransformer, decrypt, encrypt } from './encryption';
+
+describe('encryption', () => {
+ describe('encrypt / decrypt', () => {
+ test('an encrypted value can be decrypted with the same key', () => {
+ const key = Buffer.from('u+aFUIt/XEO5mhqB8tLVCiFyiFK/k7AxZD2TAvO0x0k=', 'base64');
+ const value = 'test';
+
+ const encryptedValue = encrypt({ key, value });
+ const decryptedValue = decrypt({ encryptedValue, key });
+
+ expect(decryptedValue.toString('utf8')).to.eql(value);
+ });
+ });
+
+ describe('encrypt / decrypt stream', () => {
+ test('an encrypted stream can be decrypted with the same key', async () => {
+ const key = Buffer.from('u+aFUIt/XEO5mhqB8tLVCiFyiFK/k7AxZD2TAvO0x0k=', 'base64');
+ const inputStream = new Readable({
+ read() {
+ this.push(Buffer.from('foo'));
+ this.push(Buffer.from('bar'));
+ this.push(null);
+ },
+ });
+
+ let output = '';
+ const outputStream = new Writable({
+ write(chunk: Buffer, encoding: string, callback: (error?: Error | null) => void) {
+ output += chunk.toString('utf8');
+ callback();
+ },
+ });
+
+ await pipeline(
+ inputStream,
+ createEncryptTransformer({ key }),
+ createDecryptTransformer({ key }),
+ outputStream,
+ );
+
+ expect(output).to.eql('foobar');
+ });
+ });
+
+ describe('decrypt stream', () => {
+ describe('the chunks can be of different sizes', () => {
+ const key = Buffer.from('u+aFUIt/XEO5mhqB8tLVCiFyiFK/k7AxZD2TAvO0x0k=', 'base64');
+ // Encrypted "foobar" with key above
+ const encryptedData = Buffer.from('UFAwMUAZw/UfMg5ysSJA53QuaBgdRg9LFNnKK5lV0/eCn6PD60o=', 'base64url');
+
+ // Some variations of the encrypted data
+ const variants: { name: string; data: Buffer[] }[] = [
+ {
+ name: 'whole encrypted data as a single chunk',
+ data: [encryptedData],
+ },
+ {
+ name: 'a chunk per byte',
+ data: Array.from(encryptedData).map(byte => Buffer.from([byte])),
+ },
+ {
+ name: '15 bytes (incomplete header), then the rest',
+ data: [encryptedData.subarray(0, 15), encryptedData.subarray(15)],
+ },
+ {
+ name: 'whole encrypted data, but last 10 bytes (incomplete tag), then the rest',
+ data: [encryptedData.subarray(0, encryptedData.length - 10), encryptedData.subarray(encryptedData.length - 10)],
+ },
+ ] as const;
+
+ for (const { name, data } of variants) {
+ test(name, async () => {
+ const stream = new Readable({
+ read() {
+ for (const chunk of data) {
+ this.push(chunk);
+ }
+ this.push(null);
+ },
+ }).pipe(createDecryptTransformer({ key }));
+
+ const decryptedData = await collectReadableStreamToString({ stream });
+
+ expect(decryptedData).to.eql('foobar');
+ });
+ }
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/shared/crypto/encryption.ts b/apps/papra-server/src/modules/shared/crypto/encryption.ts
new file mode 100644
index 00000000..44378f2e
--- /dev/null
+++ b/apps/papra-server/src/modules/shared/crypto/encryption.ts
@@ -0,0 +1,134 @@
+import type { BinaryLike, DecipherGCM } from 'node:crypto';
+import { Buffer } from 'node:buffer';
+import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
+import { Transform } from 'node:stream';
+import { castError } from '@corentinth/chisels';
+import { isNil } from '../utils';
+
+const ALGORITHM = 'aes-256-gcm';
+const IV_LENGTH = 12;
+const TAG_LENGTH = 16;
+
+export function encrypt({ key, value }: { key: BinaryLike; value: BinaryLike }) {
+ const iv = randomBytes(IV_LENGTH);
+ const cipher = createCipheriv(ALGORITHM, key, iv);
+ const encrypted = cipher.update(value);
+ cipher.final();
+ const tag = cipher.getAuthTag();
+
+ return Buffer.concat([iv, tag, encrypted]);
+}
+
+export function decrypt({ encryptedValue, key }: { encryptedValue: Buffer; key: BinaryLike }) {
+ const iv = encryptedValue.subarray(0, IV_LENGTH);
+ const tag = encryptedValue.subarray(IV_LENGTH, IV_LENGTH + TAG_LENGTH);
+ const encryptedBuffer = encryptedValue.subarray(IV_LENGTH + TAG_LENGTH);
+
+ const decipher = createDecipheriv(ALGORITHM, key, iv);
+ decipher.setAuthTag(tag);
+ const decrypted = decipher.update(encryptedBuffer);
+ decipher.final();
+ return decrypted;
+}
+
+// The magic number is used to identify the file format
+const MAGIC = Buffer.from('PP01');
+const HEADER_LENGTH = MAGIC.length + IV_LENGTH;
+
+// | MAGIC (4 bytes) | IV (12 bytes) | ... encrypted data ... | TAG (16 bytes) |
+
+export function createEncryptTransformer({ key, iv = randomBytes(IV_LENGTH) }: { key: BinaryLike; iv?: Buffer }) {
+ const cipher = createCipheriv(ALGORITHM, key, iv);
+ const header = Buffer.concat([MAGIC, iv]);
+
+ let headerWritten = false;
+
+ const transform = new Transform({
+ transform(chunk: Buffer, _encoding, callback: (error?: Error | null) => void) {
+ if (!headerWritten) {
+ this.push(header);
+ headerWritten = true;
+ }
+
+ try {
+ const encrypted = cipher.update(chunk);
+ this.push(encrypted);
+ callback();
+ } catch (error) {
+ callback(castError(error));
+ }
+ },
+ flush(callback: (error?: Error | null) => void) {
+ try {
+ const final = cipher.final();
+ if (final.length > 0) {
+ this.push(final);
+ }
+ this.push(cipher.getAuthTag());
+ callback();
+ } catch (error) {
+ callback(castError(error));
+ }
+ },
+ });
+
+ return transform;
+}
+
+export function createDecryptTransformer({ key }: { key: BinaryLike }) {
+ let header = Buffer.alloc(0);
+ let decipher: DecipherGCM;
+ let last16Bytes: Buffer = Buffer.alloc(0);
+
+ const transform = new Transform({
+ transform(chunk: Buffer, _encoding, callback: (error?: Error | null) => void) {
+ const chunkWithPreviousLast16Bytes = Buffer.concat([last16Bytes, chunk]);
+ const isThereAtLeast16Bytes = chunkWithPreviousLast16Bytes.length >= TAG_LENGTH;
+
+ let chunkWithoutLast16Bytes: Buffer = isThereAtLeast16Bytes ? chunkWithPreviousLast16Bytes.subarray(0, chunkWithPreviousLast16Bytes.length - TAG_LENGTH) : Buffer.alloc(0);
+ last16Bytes = isThereAtLeast16Bytes ? chunkWithPreviousLast16Bytes.subarray(chunkWithPreviousLast16Bytes.length - TAG_LENGTH) : chunkWithPreviousLast16Bytes;
+
+ if (header.length < HEADER_LENGTH) {
+ const headerChunk = chunkWithoutLast16Bytes.subarray(0, HEADER_LENGTH - header.length);
+ header = Buffer.concat([header, headerChunk]);
+ chunkWithoutLast16Bytes = chunkWithoutLast16Bytes.subarray(headerChunk.length);
+ }
+
+ if (header.length === HEADER_LENGTH && isNil(decipher)) {
+ const magic = header.subarray(0, MAGIC.length);
+
+ if (!magic.equals(MAGIC)) {
+ this.destroy(new Error('Invalid magic number'));
+ return;
+ }
+
+ const iv = header.subarray(MAGIC.length, MAGIC.length + IV_LENGTH);
+
+ decipher = createDecipheriv(ALGORITHM, key, iv);
+ }
+
+ if (decipher !== undefined && chunkWithoutLast16Bytes.length > 0) {
+ try {
+ const decrypted = decipher.update(chunkWithoutLast16Bytes);
+ this.push(decrypted);
+ callback();
+ } catch (error) {
+ callback(castError(error));
+ }
+ } else {
+ callback();
+ }
+ },
+ flush(callback: (error?: Error | null) => void) {
+ try {
+ decipher.setAuthTag(last16Bytes);
+ this.push(decipher.final());
+ callback();
+ } catch (error) {
+ callback(castError(error));
+ }
+ },
+ });
+
+ return transform;
+}
diff --git a/apps/papra-server/src/modules/shared/crypto/key-derivation.test.ts b/apps/papra-server/src/modules/shared/crypto/key-derivation.test.ts
new file mode 100644
index 00000000..b3e31b9f
--- /dev/null
+++ b/apps/papra-server/src/modules/shared/crypto/key-derivation.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, test } from 'vitest';
+import { deriveKeyWithHkdf } from './key-derivation';
+
+describe('key-derivation', () => {
+ describe('deriveKeyWithHkdf', () => {
+ test('deterministically derives a subkey from a key and an info', () => {
+ const key = 'my-key';
+ const info = 'papra/v1:my-info';
+
+ expect(deriveKeyWithHkdf({ key, info })).to.eql('MmKTujAu_3NZFKU8tB2SHW_lHiB_rjKMJd5lvx0ydTA');
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/shared/crypto/key-derivation.ts b/apps/papra-server/src/modules/shared/crypto/key-derivation.ts
new file mode 100644
index 00000000..5832451c
--- /dev/null
+++ b/apps/papra-server/src/modules/shared/crypto/key-derivation.ts
@@ -0,0 +1,18 @@
+import type { BinaryLike } from 'node:crypto';
+import { Buffer } from 'node:buffer';
+import { hkdfSync } from 'node:crypto';
+
+export function deriveKeyWithHkdf({
+ key,
+ info,
+ salt = Buffer.alloc(0),
+ outputKeyLength = 32,
+}: {
+ key: BinaryLike;
+ info: BinaryLike;
+ salt?: Buffer;
+ outputKeyLength?: number;
+}) {
+ const newKey = hkdfSync('sha256', key, salt, info, outputKeyLength);
+ return Buffer.from(newKey).toString('base64url');
+}
diff --git a/apps/papra-server/src/modules/shared/types.ts b/apps/papra-server/src/modules/shared/types.ts
index 5ae448c0..b96f2b28 100644
--- a/apps/papra-server/src/modules/shared/types.ts
+++ b/apps/papra-server/src/modules/shared/types.ts
@@ -1 +1,7 @@
export type NonEmptyArray<T> = [T, ...T[]];
+
+export type ExtendNamedArguments<Method, NewArgs extends Record<string, unknown>> = Method extends (args: infer Args) => infer Return ? (args: Args & NewArgs) => Return : never;
+export type ExtendReturn<Method, NewReturn extends Record<string, unknown>> = Method extends (args: infer Args) => infer Return ? (args: Args) => Return & NewReturn : never;
+export type ExtendReturnPromise<Method, NewReturn extends Record<string, unknown>> = Method extends (args: infer Args) => Promise<infer Return> ? (args: Args) => Promise<Return & NewReturn> : never;
+
+export type ArrayElement<ArrayType extends readonly unknown[]> = ArrayType extends readonly (infer ElementType)[] ? ElementType : never;
diff --git a/apps/papra-server/src/scripts/encrypt-all-documents.script.ts b/apps/papra-server/src/scripts/encrypt-all-documents.script.ts
new file mode 100644
index 00000000..7f128110
--- /dev/null
+++ b/apps/papra-server/src/scripts/encrypt-all-documents.script.ts
@@ -0,0 +1,54 @@
+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 { 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({ config });
+
+ if (!config.documentsStorage.encryption.isEncryptionEnabled) {
+ logger.error('Document encryption is not enabled, skipping');
+
+ process.exit(1);
+ }
+
+ if (isNil(config.documentsStorage.encryption.documentKeyEncryptionKeys)) {
+ logger.error('Document encryption keys are not set, skipping');
+
+ process.exit(1);
+ }
+
+ logger.info('Starting encryption of all unencrypted documents');
+
+ if (isDryRun) {
+ logger.info('[DRY RUN] No actual encryption will be performed');
+
+ // In dry run mode, just count the documents that would be encrypted
+ const documents = await db
+ .select({ id: documentsTable.id, originalName: documentsTable.originalName })
+ .from(documentsTable)
+ .where(isNull(documentsTable.fileEncryptionKeyWrapped));
+
+ logger.info({
+ count: documents.length,
+ documents: documents.map(d => ({ id: d.id, name: d.originalName })),
+ }, '[DRY RUN] Documents that would be encrypted');
+
+ return;
+ }
+
+ await encryptAllUnencryptedDocuments({
+ db,
+ documentStorageService,
+ logger,
+ deleteUnencryptedAfterEncryption: true,
+ });
+
+ logger.info('Document encryption completed successfully');
+ },
+);
diff --git a/packages/lecture/src/extractors.usecases.test.ts b/packages/lecture/src/extractors.usecases.test.ts
index 6c85bbea..22246712 100644
--- a/packages/lecture/src/extractors.usecases.test.ts
+++ b/packages/lecture/src/extractors.usecases.test.ts
@@ -45,7 +45,7 @@ describe('extractors usecases', () => {
const fixtureName = fixtureDir.split('/').filter(Boolean).pop();
// use test.concurrent to run the tests in parallel -> need to use the provided expect
- test(`fixture ${fixtureName}`, { timeout: 10_000, concurrent: true }, async ({ expect }) => {
+ test(`fixture ${fixtureName}`, { timeout: 20_000, concurrent: true }, async ({ expect }) => {
const fixtureFilesPaths = await glob(['*'], { cwd: fixtureDir, absolute: true });
const inputFilePath = fixtureFilesPaths.find(name => name.match(/\/\d{3}\.input\.\w+$/));