Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(intake-emails): added intake emails (#103)

Corentin THOMASSET274fb7d72e1a
diff --git a/README.md b/README.md
index 88a3aeff..8be5365a 100644
--- a/README.md
+++ b/README.md
@@ -49,10 +49,10 @@ A live demo of the platform is available at [demo.papra.cc](https://demo.papra.c
- **Open Source**: The project is open-source and free to use.
- **Self-hosting**: Host your own instance of Papra using Docker or other methods.
- **Tags**: Organize your documents with tags.
+- **Email ingestion**: Send/forward emails to a generated address to automatically import documents.
- *Coming soon:* **Tagging Rules**: Automatically tag documents based on custom rules.
- *Coming soon:* **Content extraction**: Automatically extract text from images or scanned documents for search.
- *Coming soon:* **i18n**: Support for multiple languages.
-- *Coming soon:* **Email ingestion**: Forward emails to automatically import documents.
- *Coming soon:* **SDK and API**: Build your own applications on top of Papra.
- *Coming soon:* **CLI**: Manage your documents from the command line.
- *Coming soon:* **Document sharing**: Share documents with others.
diff --git a/apps/papra-client/src/modules/config/config.ts b/apps/papra-client/src/modules/config/config.ts
index 1545ce4c..99be0398 100644
--- a/apps/papra-client/src/modules/config/config.ts
+++ b/apps/papra-client/src/modules/config/config.ts
@@ -25,6 +25,10 @@ export const buildTimeConfig = {
domain: import.meta.env.VITE_PLAUSIBLE_DOMAIN,
apiHost: import.meta.env.VITE_PLAUSIBLE_API_HOST,
},
+ intakeEmails: {
+ isEnabled: import.meta.env.VITE_INTAKE_EMAILS_IS_ENABLED === 'true',
+ emailGenerationDomain: import.meta.env.VITE_INTAKE_EMAILS_EMAIL_GENERATION_DOMAIN,
+ },
} as const;
export type Config = typeof buildTimeConfig;
diff --git a/apps/papra-client/src/modules/intake-emails/intake-emails.models.ts b/apps/papra-client/src/modules/intake-emails/intake-emails.models.ts
new file mode 100644
index 00000000..17d8d5f7
--- /dev/null
+++ b/apps/papra-client/src/modules/intake-emails/intake-emails.models.ts
@@ -0,0 +1,3 @@
+export function formatIntakeEmail({ domain, username }: { domain: string; username: string }) {
+ return `${username}@${domain}`;
+}
diff --git a/apps/papra-client/src/modules/intake-emails/intake-emails.services.ts b/apps/papra-client/src/modules/intake-emails/intake-emails.services.ts
new file mode 100644
index 00000000..e8eed55e
--- /dev/null
+++ b/apps/papra-client/src/modules/intake-emails/intake-emails.services.ts
@@ -0,0 +1,57 @@
+import type { IntakeEmail } from './intake-emails.types';
+import { apiClient } from '../shared/http/api-client';
+import { coerceDates } from '../shared/http/http-client.models';
+
+export async function fetchIntakeEmails({ organizationId }: { organizationId: string }) {
+ const { intakeEmails } = await apiClient<{ intakeEmails: IntakeEmail[] }>({
+ path: `/api/organizations/${organizationId}/intake-emails`,
+ method: 'GET',
+ });
+
+ return {
+ intakeEmails: intakeEmails.map(coerceDates),
+ };
+}
+
+export async function createIntakeEmail({ organizationId }: { organizationId: string }) {
+ const { intakeEmail } = await apiClient<{ intakeEmail: IntakeEmail }>({
+ path: `/api/organizations/${organizationId}/intake-emails`,
+ method: 'POST',
+ });
+
+ return {
+ intakeEmail: coerceDates(intakeEmail),
+ };
+}
+
+export async function deleteIntakeEmail({ organizationId, intakeEmailId }: { organizationId: string; intakeEmailId: string }) {
+ await apiClient({
+ path: `/api/organizations/${organizationId}/intake-emails/${intakeEmailId}`,
+ method: 'DELETE',
+ });
+}
+
+export async function updateIntakeEmail({
+ organizationId,
+ intakeEmailId,
+ isEnabled,
+ allowedOrigins,
+}: {
+ organizationId: string;
+ intakeEmailId: string;
+ isEnabled?: boolean;
+ allowedOrigins?: string[];
+}) {
+ const { intakeEmail } = await apiClient<{ intakeEmail: IntakeEmail }>({
+ path: `/api/organizations/${organizationId}/intake-emails/${intakeEmailId}`,
+ method: 'PUT',
+ body: {
+ isEnabled,
+ allowedOrigins,
+ },
+ });
+
+ return {
+ intakeEmail: coerceDates(intakeEmail),
+ };
+}
diff --git a/apps/papra-client/src/modules/intake-emails/intake-emails.types.ts b/apps/papra-client/src/modules/intake-emails/intake-emails.types.ts
new file mode 100644
index 00000000..b21562ca
--- /dev/null
+++ b/apps/papra-client/src/modules/intake-emails/intake-emails.types.ts
@@ -0,0 +1,9 @@
+export type IntakeEmail = {
+ id: string;
+ organizationId: string;
+ isEnabled: boolean;
+ allowedOrigins: string[];
+
+ createdAt: Date;
+ updatedAt: Date | undefined;
+};
diff --git a/apps/papra-client/src/modules/intake-emails/pages/intake-emails.page.tsx b/apps/papra-client/src/modules/intake-emails/pages/intake-emails.page.tsx
new file mode 100644
index 00000000..c9b3ceef
--- /dev/null
+++ b/apps/papra-client/src/modules/intake-emails/pages/intake-emails.page.tsx
@@ -0,0 +1,339 @@
+import type { DialogTriggerProps } from '@kobalte/core/dialog';
+import type { IntakeEmail } from '../intake-emails.types';
+import { useConfig } from '@/modules/config/config.provider';
+import { useConfirmModal } from '@/modules/shared/confirm';
+import { createForm } from '@/modules/shared/form/form';
+import { queryClient } from '@/modules/shared/query/query-client';
+import { cn } from '@/modules/shared/style/cn';
+import { Alert, AlertDescription } from '@/modules/ui/components/alert';
+import { Button } from '@/modules/ui/components/button';
+import { Card } from '@/modules/ui/components/card';
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/modules/ui/components/dialog';
+import { EmptyState } from '@/modules/ui/components/empty';
+import { createToast } from '@/modules/ui/components/sonner';
+import { TextField, TextFieldLabel, TextFieldRoot } from '@/modules/ui/components/textfield';
+import { useParams } from '@solidjs/router';
+import { createQuery } from '@tanstack/solid-query';
+import { type Component, For, type JSX, Show, Suspense } from 'solid-js';
+import { createSignal } from 'solid-js';
+import * as v from 'valibot';
+import { formatIntakeEmail } from '../intake-emails.models';
+import { createIntakeEmail, deleteIntakeEmail, fetchIntakeEmails, updateIntakeEmail } from '../intake-emails.services';
+
+const AllowedOriginsDialog: Component<{ children: (props: DialogTriggerProps) => JSX.Element; intakeEmails: IntakeEmail }> = (props) => {
+ const { config } = useConfig();
+ const [getAllowedOrigins, setAllowedOrigins] = createSignal([...props.intakeEmails.allowedOrigins]);
+
+ const update = async () => {
+ await updateIntakeEmail({
+ organizationId: props.intakeEmails.organizationId,
+ intakeEmailId: props.intakeEmails.id,
+ allowedOrigins: getAllowedOrigins(),
+ });
+ };
+
+ const getIntakeAddress = () => formatIntakeEmail({
+ domain: config.intakeEmails.emailGenerationDomain,
+ username: props.intakeEmails.id,
+ });
+
+ const deleteAllowedOrigin = async ({ origin }: { origin: string }) => {
+ setAllowedOrigins(origins => origins.filter(o => o !== origin));
+ await update();
+ };
+
+ const { form, Form, Field } = createForm({
+ schema: v.object({
+ email: v.pipe(
+ v.string(),
+ v.trim(),
+ v.email('Please enter a valid email address'),
+ ),
+ }),
+ onSubmit: async ({ email }) => {
+ if (getAllowedOrigins().includes(email)) {
+ throw new Error('This email is already in the allowed origins for this intake email');
+ }
+
+ setAllowedOrigins(origins => [...origins, email]);
+ await update();
+ },
+ });
+
+ async function invalidateQuery() {
+ await queryClient.invalidateQueries({
+ queryKey: ['organizations', props.intakeEmails.organizationId, 'intake-emails'],
+ });
+ }
+
+ return (
+ <Dialog onOpenChange={isOpen => !isOpen && invalidateQuery()}>
+ <DialogTrigger as={props.children} />
+
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Allowed origins</DialogTitle>
+ <DialogDescription>
+ Only emails sent to
+ {' '}
+ <span class="font-medium text-primary">{getIntakeAddress()}</span>
+ {' '}
+ from these origins will be processed. If no origins are specified, all emails will be discarded.
+ </DialogDescription>
+ </DialogHeader>
+
+ <Form>
+ <Field name="email">
+ {(field, inputProps) => (
+ <TextFieldRoot class="flex flex-col gap-1 mb-4 mt-4">
+ <TextFieldLabel for="email">Add allowed origin email</TextFieldLabel>
+
+ <div class="flex items-center gap-2">
+ <TextField type="email" id="email" placeholder="Eg. [email protected]" {...inputProps} autoFocus value={field.value} aria-invalid={Boolean(field.error)} />
+ <Button type="submit">
+ <div class="i-tabler-plus size-4 mr-2" />
+ Add
+ </Button>
+ </div>
+
+ <div class="text-red-500 text-sm mt-4">{form.response.message}</div>
+ {field.error && <div class="text-red-500 text-sm">{field.error }</div>}
+ </TextFieldRoot>
+ )}
+ </Field>
+ </Form>
+
+ <div class="flex flex-col gap-2">
+ <For each={getAllowedOrigins()}>
+ {origin => (
+ <div class="flex items-center gap-2 justify-between border rounded-lg p-2">
+ <div class="flex items-center gap-2">
+ <div class="bg-muted size-9 rounded-lg flex items-center justify-center">
+ <div class="i-tabler-mail size-5 text-primary" />
+ </div>
+ <div class="font-medium text-sm">
+ {origin}
+ </div>
+ </div>
+ <Button
+ variant="outline"
+ aria-label="Delete allowed origin"
+ size="icon"
+ class="text-red"
+ onClick={() => deleteAllowedOrigin({ origin })}
+ >
+ <div class="i-tabler-trash size-4" />
+ </Button>
+ </div>
+ )}
+ </For>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+export const IntakeEmailsPage: Component = () => {
+ const { config } = useConfig();
+
+ if (!config.intakeEmails.isEnabled) {
+ return (
+ <Card class="p-6">
+ <h2 class="text-base font-bold">Intake Emails</h2>
+ <p class="text-muted-foreground mt-1">
+ Intake emails are disabled on this instance. Please contact your administrator to enable them.
+ </p>
+ </Card>
+ );
+ }
+
+ const params = useParams();
+ const { confirm } = useConfirmModal();
+
+ const query = createQuery(() => ({
+ queryKey: ['organizations', params.organizationId, 'intake-emails'],
+ queryFn: () => fetchIntakeEmails({ organizationId: params.organizationId }),
+ }));
+
+ const createEmail = async () => {
+ await createIntakeEmail({ organizationId: params.organizationId });
+ await query.refetch();
+
+ createToast({
+ message: 'Intake email created',
+ type: 'success',
+ });
+ };
+
+ const deleteEmail = async ({ intakeEmailId }: { intakeEmailId: string }) => {
+ const confirmed = await confirm({
+ title: 'Delete intake email?',
+ message: 'Are you sure you want to delete this intake email? This action cannot be undone.',
+ cancelButton: {
+ text: 'Cancel',
+ },
+ confirmButton: {
+ text: 'Delete intake email',
+ variant: 'destructive',
+ },
+ });
+
+ if (!confirmed) {
+ return;
+ }
+
+ await deleteIntakeEmail({ organizationId: params.organizationId, intakeEmailId });
+ await query.refetch();
+
+ createToast({
+ message: 'Intake email deleted',
+ type: 'success',
+ });
+ };
+
+ const updateEmail = async ({ intakeEmailId, isEnabled }: { intakeEmailId: string; isEnabled: boolean }) => {
+ await updateIntakeEmail({ organizationId: params.organizationId, intakeEmailId, isEnabled });
+ await query.refetch();
+
+ createToast({
+ message: `Intake email ${isEnabled ? 'enabled' : 'disabled'}`,
+ type: 'success',
+ });
+ };
+
+ return (
+ <Card class="p-6">
+
+ <h2 class="text-base font-bold">Intake Emails</h2>
+
+ <p class="text-muted-foreground mt-1">
+ Intake emails address are used to automatically ingest emails into Papra. Just forward emails to the intake email address and their attachments will be added to your organization's documents.
+ </p>
+
+ <Alert variant="default" class="mt-4 flex items-center gap-4 xl:gap-4 text-muted-foreground">
+ <div class="i-tabler-info-circle size-10 xl:size-8 text-primary flex-shrink-0 " />
+
+ <AlertDescription>
+ Only enabled intake emails from allowed origins will be processed. You can enable or disable an intake email at any time.
+ </AlertDescription>
+
+ </Alert>
+
+ <Suspense>
+ <Show when={query.data?.intakeEmails}>
+ {intakeEmails => (
+ <Show
+ when={intakeEmails().length > 0}
+ fallback={(
+ <div class="mt-4 py-8 border-2 border-dashed rounded-lg text-center">
+ <EmptyState
+ title="No intake emails"
+ description="Generate an intake address to easily ingest emails attachments."
+ class="pt-0"
+ icon="i-tabler-mail"
+ cta={(
+ <Button variant="secondary" onClick={createEmail}>
+ <div class="i-tabler-plus size-4 mr-2" />
+ Generate intake email
+ </Button>
+ )}
+ />
+ </div>
+ )}
+ >
+ <div class="mt-4 mb-4 flex items-center justify-between">
+ <div class="text-muted-foreground">
+ {`${intakeEmails().length} intake email${intakeEmails().length > 1 ? 's' : ''} for this organization`}
+ </div>
+
+ <Button onClick={createEmail}>
+ <div class="i-tabler-plus size-4 mr-2" />
+ New intake email
+ </Button>
+ </div>
+
+ <div class="flex flex-col gap-2">
+ {intakeEmails().map(intakeEmail => (
+ <div class="flex items-center justify-between border rounded-lg p-4">
+ <div class="flex items-center gap-4">
+ <div class="bg-muted size-9 rounded-lg flex items-center justify-center">
+ <div class={cn('i-tabler-mail size-5', intakeEmail.isEnabled ? 'text-primary' : 'text-muted-foreground')} />
+ </div>
+
+ <div>
+ <div class="font-medium">
+ {formatIntakeEmail({
+ domain: config.intakeEmails.emailGenerationDomain,
+ username: intakeEmail.id,
+ })}
+
+ <Show when={!intakeEmail.isEnabled}>
+ <span class="text-muted-foreground text-xs ml-2">(Disabled)</span>
+ </Show>
+
+ </div>
+
+ <Show
+ when={intakeEmail.allowedOrigins.length > 0}
+ fallback={(
+ <div class="text-xs text-warning flex items-center gap-1.5">
+ <div class="i-tabler-alert-triangle size-3.75" />
+ No allowed email origins
+ </div>
+ )}
+ >
+ <div class="text-xs text-muted-foreground flex items-center gap-2">
+ {`Allowed from ${intakeEmail.allowedOrigins.length} address${intakeEmail.allowedOrigins.length > 1 ? 'es' : ''}`}
+ </div>
+
+ </Show>
+ </div>
+ </div>
+
+ <div class="flex items-center gap-2">
+ <Button
+ variant="outline"
+ onClick={() => updateEmail({ intakeEmailId: intakeEmail.id, isEnabled: !intakeEmail.isEnabled })}
+ >
+ <div class="i-tabler-power size-4 mr-2" />
+ {intakeEmail.isEnabled ? 'Disable' : 'Enable'}
+ </Button>
+
+ <AllowedOriginsDialog intakeEmails={intakeEmail}>
+ {(props: DialogTriggerProps) => (
+ <Button
+ variant="outline"
+ aria-label="Edit intake email"
+ {...props}
+ class="flex items-center gap-2 leading-none"
+ >
+ <div class="i-tabler-edit size-4" />
+ Manage origins addresses
+ </Button>
+ )}
+ </AllowedOriginsDialog>
+
+ <Button
+ variant="outline"
+ onClick={() => deleteEmail({ intakeEmailId: intakeEmail.id })}
+ aria-label="Delete intake email"
+ class="text-red"
+ >
+ <div class="i-tabler-trash size-4 mr-2" />
+
+ Delete
+ </Button>
+ </div>
+ </div>
+ ))}
+
+ </div>
+
+ </Show>
+
+ )}
+ </Show>
+ </Suspense>
+ </Card>
+ );
+};
diff --git a/apps/papra-client/src/modules/ui/layouts/integrations.layout.tsx b/apps/papra-client/src/modules/ui/layouts/integrations.layout.tsx
new file mode 100644
index 00000000..bb60907e
--- /dev/null
+++ b/apps/papra-client/src/modules/ui/layouts/integrations.layout.tsx
@@ -0,0 +1,33 @@
+import type { ParentComponent } from 'solid-js';
+import { A, useParams } from '@solidjs/router';
+import { Button } from '../components/button';
+
+export const IntegrationsLayout: ParentComponent = (props) => {
+ const params = useParams();
+
+ return (
+ <div class="p-6 mt-4 pb-32 mx-auto max-w-5xl">
+ <div class="border-b mb-6">
+ <h1 class="text-xl font-bold ">
+ Integrations
+ </h1>
+
+ <p class="text-muted-foreground mt-1">
+ Manage your organization's integrations
+ </p>
+
+ <div class="flex gap-2 mt-4">
+ <Button as={A} href={`/organizations/${params.organizationId}/intake-emails`} variant="ghost" activeClass="border-b border-primary text-foreground!" class="text-muted-foreground rounded-b-none">
+ Intake Emails
+ </Button>
+
+ <Button as={A} href={`/organizations/${params.organizationId}/api-keys`} variant="ghost" activeClass="border-b border-primary text-foreground!" class="text-muted-foreground rounded-b-none">
+ API Keys
+ </Button>
+ </div>
+ </div>
+
+ {props.children}
+ </div>
+ );
+};
diff --git a/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx b/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx
index d8e300a8..3da7404d 100644
--- a/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx
+++ b/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx
@@ -39,7 +39,7 @@ const OrganizationLayoutSideNav: Component = () => {
{
label: 'Integrations',
icon: 'i-tabler-link',
- href: `/organizations/${params.organizationId}/integrations`,
+ href: `/organizations/${params.organizationId}/intake-emails`,
},
];
diff --git a/apps/papra-client/src/routes.tsx b/apps/papra-client/src/routes.tsx
index bb7306df..32987b1f 100644
--- a/apps/papra-client/src/routes.tsx
+++ b/apps/papra-client/src/routes.tsx
@@ -10,6 +10,7 @@ import { ResetPasswordPage } from './modules/auth/pages/reset-password.page';
import { DeletedDocumentsPage } from './modules/documents/pages/deleted-documents.page';
import { DocumentPage } from './modules/documents/pages/document.page';
import { DocumentsPage } from './modules/documents/pages/documents.page';
+import { IntakeEmailsPage } from './modules/intake-emails/pages/intake-emails.page';
import { fetchOrganizations } from './modules/organizations/organizations.services';
import { CreateFirstOrganizationPage } from './modules/organizations/pages/create-first-organization.page';
import { CreateOrganizationPage } from './modules/organizations/pages/create-organization.page';
@@ -18,6 +19,7 @@ import { OrganizationsPage } from './modules/organizations/pages/organizations.p
import { ComingSoonPage } from './modules/shared/pages/coming-soon.page';
import { NotFoundPage } from './modules/shared/pages/not-found.page';
import { TagsPage } from './modules/tags/pages/tags.page';
+import { IntegrationsLayout } from './modules/ui/layouts/integrations.layout';
import { OrganizationLayout } from './modules/ui/layouts/organization.layout';
import { CurrentUserProvider, useCurrentUser } from './modules/users/composables/useCurrentUser';
import { UserSettingsPage } from './modules/users/pages/user-settings.page';
@@ -109,8 +111,18 @@ export const routes: RouteDefinition[] = [
component: TagsPage,
},
{
- path: '/integrations',
- component: ComingSoonPage,
+ path: '/',
+ component: IntegrationsLayout,
+ children: [
+ {
+ path: '/intake-emails',
+ component: IntakeEmailsPage,
+ },
+ {
+ path: '/api-keys',
+ component: ComingSoonPage,
+ },
+ ],
},
],
},
diff --git a/apps/papra-server/migrations/0003_intake-emails.sql b/apps/papra-server/migrations/0003_intake-emails.sql
new file mode 100644
index 00000000..a5d59cbe
--- /dev/null
+++ b/apps/papra-server/migrations/0003_intake-emails.sql
@@ -0,0 +1,9 @@
+CREATE TABLE `intake_emails` (
+ `id` text PRIMARY KEY NOT NULL,
+ `created_at` integer NOT NULL,
+ `updated_at` integer NOT NULL,
+ `organization_id` text NOT NULL,
+ `allowed_origins` text DEFAULT '[]' NOT NULL,
+ `is_enabled` integer DEFAULT true NOT NULL,
+ FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE cascade ON DELETE cascade
+);
diff --git a/apps/papra-server/migrations/meta/0003_snapshot.json b/apps/papra-server/migrations/meta/0003_snapshot.json
new file mode 100644
index 00000000..0b787494
--- /dev/null
+++ b/apps/papra-server/migrations/meta/0003_snapshot.json
@@ -0,0 +1,903 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "7347bf3b-241a-46c0-9c6c-843be2d46547",
+ "prevId": "461b726b-6e58-4a08-81bc-324027e568c5",
+ "tables": {
+ "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
+ },
+ "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": "''"
+ }
+ },
+ "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
+ }
+ },
+ "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_users": {
+ "name": "organization_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
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'member'"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "organization_users_user_id_users_id_fk": {
+ "name": "organization_users_user_id_users_id_fk",
+ "tableFrom": "organization_users",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "organization_users_organization_id_organizations_id_fk": {
+ "name": "organization_users_organization_id_organizations_id_fk",
+ "tableFrom": "organization_users",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_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
+ }
+ },
+ "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
+ }
+ },
+ "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": {}
+ },
+ "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
+ }
+ },
+ "indexes": {},
+ "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"
+ }
+ },
+ "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": {},
+ "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
+ },
+ "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": {},
+ "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": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
diff --git a/apps/papra-server/migrations/meta/_journal.json b/apps/papra-server/migrations/meta/_journal.json
index 1a4e7296..f1b7b4b9 100644
--- a/apps/papra-server/migrations/meta/_journal.json
+++ b/apps/papra-server/migrations/meta/_journal.json
@@ -22,6 +22,13 @@
"when": 1737369265792,
"tag": "0002_tags",
"breakpoints": true
+ },
+ {
+ "idx": 3,
+ "version": "6",
+ "when": 1737665080672,
+ "tag": "0003_intake-emails",
+ "breakpoints": true
}
]
}
diff --git a/apps/papra-server/package.json b/apps/papra-server/package.json
index 2674b635..8f0341c3 100644
--- a/apps/papra-server/package.json
+++ b/apps/papra-server/package.json
@@ -30,6 +30,7 @@
"@aws-sdk/client-s3": "^3.722.0",
"@aws-sdk/lib-storage": "^3.722.0",
"@corentinth/chisels": "^1.1.0",
+ "@corentinth/friendly-ids": "^0.0.1",
"@hono/node-server": "^1.13.7",
"@hono/oauth-providers": "^0.6.2",
"@libsql/client": "^0.14.0",
diff --git a/apps/papra-server/src/modules/app/database/database.test-utils.ts b/apps/papra-server/src/modules/app/database/database.test-utils.ts
index 3e8df82b..4bb46412 100644
--- a/apps/papra-server/src/modules/app/database/database.test-utils.ts
+++ b/apps/papra-server/src/modules/app/database/database.test-utils.ts
@@ -1,6 +1,7 @@
import type { Database } from './database.types';
import { migrate } from 'drizzle-orm/libsql/migrator';
import { documentsTable } from '../../documents/documents.table';
+import { intakeEmailsTable } from '../../intake-emails/intake-emails.tables';
import { organizationsTable, organizationUsersTable } from '../../organizations/organizations.table';
import { documentsTagsTable, tagsTable } from '../../tags/tags.table';
import { usersTable } from '../../users/users.table';
@@ -28,6 +29,7 @@ async function seedDatabase({
documents,
tags,
documentsTags,
+ intakeEmails,
}: {
db: Database;
users?: typeof usersTable.$inferInsert[];
@@ -36,6 +38,7 @@ async function seedDatabase({
documents?: typeof documentsTable.$inferInsert[];
tags?: typeof tagsTable.$inferInsert[];
documentsTags?: typeof documentsTagsTable.$inferInsert[];
+ intakeEmails?: typeof intakeEmailsTable.$inferInsert[];
}) {
await Promise.all([
users && db.insert(usersTable).values(users).execute(),
@@ -44,5 +47,6 @@ async function seedDatabase({
documents && db.insert(documentsTable).values(documents).execute(),
tags && db.insert(tagsTable).values(tags).execute(),
documentsTags && db.insert(documentsTagsTable).values(documentsTags).execute(),
+ intakeEmails && db.insert(intakeEmailsTable).values(intakeEmails).execute(),
]);
}
diff --git a/apps/papra-server/src/modules/app/server.routes.ts b/apps/papra-server/src/modules/app/server.routes.ts
index bf172c05..bab972b8 100644
--- a/apps/papra-server/src/modules/app/server.routes.ts
+++ b/apps/papra-server/src/modules/app/server.routes.ts
@@ -1,6 +1,7 @@
import type { ServerInstance } from './server.types';
import { registerConfigPublicRoutes } from '../config/config.routes';
import { registerDocumentsPrivateRoutes } from '../documents/documents.routes';
+import { registerIntakeEmailsPrivateRoutes, registerIntakeEmailsPublicRoutes } from '../intake-emails/intake-emails.routes';
import { registerOrganizationsPrivateRoutes } from '../organizations/organizations.routes';
import { registerTagsRoutes } from '../tags/tags.routes';
import { registerUsersPrivateRoutes } from '../users/users.routes';
@@ -19,6 +20,7 @@ export function registerRoutes({ app }: { app: ServerInstance }) {
function registerPublicRoutes({ app }: { app: ServerInstance }) {
registerConfigPublicRoutes({ app });
registerHealthCheckRoutes({ app });
+ registerIntakeEmailsPublicRoutes({ app });
}
function registerPrivateRoutes({ app }: { app: ServerInstance }) {
@@ -36,4 +38,5 @@ function registerPrivateRoutes({ app }: { app: ServerInstance }) {
registerOrganizationsPrivateRoutes({ app });
registerDocumentsPrivateRoutes({ app });
registerTagsRoutes({ app });
+ registerIntakeEmailsPrivateRoutes({ app });
}
diff --git a/apps/papra-server/src/modules/config/config.models.test.ts b/apps/papra-server/src/modules/config/config.models.test.ts
index d7dc875f..b07b47e7 100644
--- a/apps/papra-server/src/modules/config/config.models.test.ts
+++ b/apps/papra-server/src/modules/config/config.models.test.ts
@@ -10,6 +10,8 @@ describe('config models', () => {
- auth.isRegistrationEnabled Whether registration is enabled
- auth.providers.*.isEnabled Wether a oauth provider is enabled
- documents.deletedExpirationDelayInDays The delay in days before a deleted document is permanently deleted
+ - intakeEmails.isEnabled Whether intake emails are enabled
+ - intakeEmails.emailGenerationDomain The domain to use when generating email addresses for intake emails
Any other config should not be exposed.`, () => {
const config = {
@@ -31,6 +33,10 @@ describe('config models', () => {
documents: {
deletedDocumentsRetentionDays: 30,
},
+ intakeEmails: {
+ isEnabled: true,
+ emailGenerationDomain: 'papra.email',
+ },
} as unknown as Config;
expect(getPublicConfig({ config })).to.eql({
@@ -51,6 +57,10 @@ describe('config models', () => {
documents: {
deletedDocumentsRetentionDays: 30,
},
+ intakeEmails: {
+ isEnabled: true,
+ emailGenerationDomain: 'papra.email',
+ },
},
});
});
diff --git a/apps/papra-server/src/modules/config/config.models.ts b/apps/papra-server/src/modules/config/config.models.ts
index 8330d17e..33caa2f5 100644
--- a/apps/papra-server/src/modules/config/config.models.ts
+++ b/apps/papra-server/src/modules/config/config.models.ts
@@ -21,6 +21,8 @@ export function getPublicConfig({ config }: { config: Config }) {
'auth.providers.github.isEnabled',
'auth.providers.google.isEnabled',
'documents.deletedDocumentsRetentionDays',
+ 'intakeEmails.isEnabled',
+ 'intakeEmails.emailGenerationDomain',
]);
return {
diff --git a/apps/papra-server/src/modules/config/config.ts b/apps/papra-server/src/modules/config/config.ts
index fac5ee20..7c7c525c 100644
--- a/apps/papra-server/src/modules/config/config.ts
+++ b/apps/papra-server/src/modules/config/config.ts
@@ -5,6 +5,7 @@ import { defineConfig } from 'figue';
import { z } from 'zod';
import { authConfig } from '../app/auth/auth.config';
import { documentsConfig } from '../documents/documents.config';
+import { intakeEmailsConfig } from '../intake-emails/intake-emails.config';
import { createLogger } from '../shared/logger/logger';
import { tasksConfig } from '../tasks/tasks.config';
import { documentStorageConfig } from './fragments/document-storage.config';
@@ -88,6 +89,7 @@ export const configDefinition = {
documentsStorage: documentStorageConfig,
auth: authConfig,
tasks: tasksConfig,
+ intakeEmails: intakeEmailsConfig,
} as const satisfies ConfigDefinition;
const logger = createLogger({ namespace: 'config' });
diff --git a/apps/papra-server/src/modules/documents/documents.usecases.ts b/apps/papra-server/src/modules/documents/documents.usecases.ts
index ee78b273..6726b024 100644
--- a/apps/papra-server/src/modules/documents/documents.usecases.ts
+++ b/apps/papra-server/src/modules/documents/documents.usecases.ts
@@ -31,7 +31,7 @@ export async function createDocument({
generateDocumentId = generateDocumentIdImpl,
}: {
file: File;
- userId: string;
+ userId?: string;
organizationId: string;
documentsRepository: DocumentsRepository;
documentsStorageService: DocumentStorageService;
diff --git a/apps/papra-server/src/modules/intake-emails/e2e/ingest-intake-emails.e2e.test.ts b/apps/papra-server/src/modules/intake-emails/e2e/ingest-intake-emails.e2e.test.ts
new file mode 100644
index 00000000..980417fb
--- /dev/null
+++ b/apps/papra-server/src/modules/intake-emails/e2e/ingest-intake-emails.e2e.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, test } from 'vitest';
+import { createInMemoryDatabase } from '../../app/database/database.test-utils';
+import { createServer } from '../../app/server';
+import { overrideConfig } from '../../config/config.test-utils';
+
+function buildBody({ attachments = [], from, to }: { attachments?: File[]; from: { address: string; name: string }; to: { address: string; name: string }[] }) {
+ const formData = new FormData();
+ formData.append('meta', JSON.stringify({ from, to }));
+ attachments.forEach((attachment) => {
+ formData.append('attachments[]', attachment);
+ });
+
+ return formData;
+}
+
+describe('intake-emails e2e', () => {
+ describe('ingest an intake email', () => {
+ test('when intake email ingestion is disabled, a 403 is returned', async () => {
+ const { db } = await createInMemoryDatabase();
+ const { app } = createServer({
+ db,
+ config: overrideConfig({
+ intakeEmails: {
+ isEnabled: false,
+ },
+ }),
+ });
+
+ const response = await app.request('/api/intake-emails/ingest', {
+ method: 'POST',
+ headers: {
+ Authorization: 'Bearer invalid-token',
+ },
+ body: buildBody({
+ from: { address: '[email protected]', name: 'Foo' },
+ to: [{ address: '[email protected]', name: 'Bar' }],
+ }),
+ });
+
+ expect(response.status).to.eql(403);
+ expect(await response.json()).to.eql({
+ error: {
+ code: 'intake_emails.disabled',
+ message: 'Intake emails are disabled',
+ },
+ });
+ });
+
+ describe('when ingesting an email, the request must have an bearer authorization header with the token specified in the config', async () => {
+ test('when the header is missing or invalid, a 401 is returned', async () => {
+ const { db } = await createInMemoryDatabase();
+ const { app } = createServer({
+ db,
+ config: overrideConfig({
+ intakeEmails: {
+ isEnabled: true,
+ webhookSecret: 'super-secret',
+ },
+ }),
+ });
+
+ const response = await app.request('/api/intake-emails/ingest', {
+ method: 'POST',
+ headers: {
+ Authorization: 'Bearer invalid-token',
+ },
+ body: buildBody({
+ from: { address: '[email protected]', name: 'Foo' },
+ to: [{ address: '[email protected]', name: 'Bar' }],
+ }),
+ });
+
+ expect(response.status).to.eql(401);
+ expect(await response.json()).to.eql({
+ error: {
+ code: 'auth.unauthorized',
+ message: 'Unauthorized',
+ },
+ });
+ });
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.config.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.config.ts
new file mode 100644
index 00000000..32f262c7
--- /dev/null
+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.config.ts
@@ -0,0 +1,28 @@
+import type { ConfigDefinition } from 'figue';
+import { z } from 'zod';
+
+export const intakeEmailsConfig = {
+ isEnabled: {
+ doc: 'Whether intake emails are enabled',
+ schema: z
+ .string()
+ .trim()
+ .toLowerCase()
+ .transform(x => x === 'true')
+ .pipe(z.boolean()),
+ default: 'false',
+ env: 'INTAKE_EMAILS_IS_ENABLED',
+ },
+ emailGenerationDomain: {
+ doc: 'The domain to use when generating email addresses for intake emails',
+ schema: z.string(),
+ default: 'papra.email',
+ env: 'INTAKE_EMAILS_EMAIL_GENERATION_DOMAIN',
+ },
+ webhookSecret: {
+ doc: 'The secret to use when verifying webhooks',
+ schema: z.string(),
+ default: 'change-me',
+ env: 'INTAKE_EMAILS_WEBHOOK_SECRET',
+ },
+} as const satisfies ConfigDefinition;
diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.models.test.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.models.test.ts
new file mode 100644
index 00000000..5e091cfb
--- /dev/null
+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.models.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, test } from 'vitest';
+import { getEmailUsername, getIsFromAllowedOrigin, getIsIntakeEmailWebhookSecretValid } from './intake-emails.models';
+
+describe('intake-emails models', () => {
+ describe('getIsIntakeEmailWebhookSecretValid', () => {
+ test('the authorization header from the email intake webhook should be a bearer token with the api secret', () => {
+ expect(
+ getIsIntakeEmailWebhookSecretValid({
+ secret: 'foo',
+ authorizationHeader: 'Bearer foo',
+ }),
+ ).to.eql(true);
+
+ expect(
+ getIsIntakeEmailWebhookSecretValid({
+ secret: 'foo',
+ authorizationHeader: 'Bearer bar',
+ }),
+ ).to.eql(false);
+
+ expect(
+ getIsIntakeEmailWebhookSecretValid({
+ secret: 'foo',
+ authorizationHeader: 'Bearer ',
+ }),
+ ).to.eql(false);
+
+ expect(
+ getIsIntakeEmailWebhookSecretValid({
+ secret: 'foo',
+ authorizationHeader: undefined,
+ }),
+ ).to.eql(false);
+ });
+ });
+
+ describe('getEmailUsername', () => {
+ test('the username is the whole part of the email address before the @', () => {
+ expect(getEmailUsername({ email: '[email protected]' })).to.eql({ username: 'foo' });
+ expect(getEmailUsername({ email: '[email protected]' })).to.eql({ username: 'foo+bar' });
+ expect(getEmailUsername({ email: undefined })).to.eql({ username: undefined });
+ });
+ });
+
+ describe('getIsFromAllowedOrigin', () => {
+ test('an origin is allowed if it is in the list of the intake email allowed origins email address', () => {
+ expect(
+ getIsFromAllowedOrigin({
+ origin: '[email protected]',
+ allowedOrigins: ['[email protected]', '[email protected]'],
+ }),
+ ).to.eql(true);
+
+ expect(
+ getIsFromAllowedOrigin({
+ origin: '[email protected]',
+ allowedOrigins: ['[email protected]'],
+ }),
+ ).to.eql(false);
+ });
+
+ test('email addresses are case insensitive', () => {
+ expect(
+ getIsFromAllowedOrigin({
+ origin: '[email protected]',
+ allowedOrigins: ['[email protected]'],
+ }),
+ ).to.eql(true);
+ });
+
+ test('if no allowed origins are provided, the origin is not allowed', () => {
+ expect(
+ getIsFromAllowedOrigin({
+ origin: '[email protected]',
+ allowedOrigins: [],
+ }),
+ ).to.eql(false);
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.models.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.models.ts
new file mode 100644
index 00000000..6bbe780e
--- /dev/null
+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.models.ts
@@ -0,0 +1,31 @@
+export function getIsIntakeEmailWebhookSecretValid({
+ secret,
+ authorizationHeader,
+}: {
+ secret: string;
+ authorizationHeader: string | undefined;
+}) {
+ return authorizationHeader === `Bearer ${secret}`;
+}
+
+export function getEmailUsername({ email }: { email: string | undefined }) {
+ if (!email) {
+ return { username: undefined };
+ }
+
+ return {
+ username: email.split('@')[0],
+ };
+}
+
+export function getIsFromAllowedOrigin({
+ origin,
+ allowedOrigins,
+}: {
+ origin: string;
+ allowedOrigins: string[];
+}) {
+ return allowedOrigins
+ .map(allowedOrigin => allowedOrigin.toLowerCase())
+ .includes(origin.toLowerCase());
+}
diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.repository.test.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.repository.test.ts
new file mode 100644
index 00000000..0f3895b4
--- /dev/null
+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.repository.test.ts
@@ -0,0 +1,69 @@
+import { omit } from 'lodash-es';
+import { describe, expect, test } from 'vitest';
+import { createInMemoryDatabase } from '../app/database/database.test-utils';
+import { createIntakeEmailsRepository } from './intake-emails.repository';
+
+describe('intake-emails repository', () => {
+ describe('crud operations on intake-emails', () => {
+ test('an intake-email can be created, retrieved, and updated', async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],
+ });
+
+ const intakeEmailsRepository = createIntakeEmailsRepository({ db });
+
+ const { intakeEmail } = await intakeEmailsRepository.createIntakeEmail({
+ organizationId: 'organization-1',
+ });
+
+ expect(
+ omit(intakeEmail, ['id', 'createdAt', 'updatedAt']),
+ ).to.eql({
+ organizationId: 'organization-1',
+ isEnabled: true,
+ allowedOrigins: [],
+ });
+
+ const { intakeEmail: updatedIntakeEmail } = await intakeEmailsRepository.updateIntakeEmail({
+ intakeEmailId: intakeEmail.id,
+ organizationId: 'organization-1',
+ isEnabled: false,
+ allowedOrigins: ['[email protected]'],
+ });
+
+ expect(
+ omit(updatedIntakeEmail, ['id', 'createdAt', 'updatedAt']),
+ ).to.eql({
+ organizationId: 'organization-1',
+ isEnabled: false,
+ allowedOrigins: ['[email protected]'],
+ });
+
+ const { intakeEmail: retrievedIntakeEmail } = await intakeEmailsRepository.getIntakeEmail({
+ intakeEmailId: intakeEmail.id,
+ });
+
+ expect(
+ omit(retrievedIntakeEmail, ['id', 'createdAt', 'updatedAt']),
+ ).to.eql({
+ organizationId: 'organization-1',
+ isEnabled: false,
+ allowedOrigins: ['[email protected]'],
+ });
+
+ const { intakeEmails: orgIntakeEmails } = await intakeEmailsRepository.getOrganizationIntakeEmails({
+ organizationId: 'organization-1',
+ });
+
+ expect(orgIntakeEmails).to.eql([retrievedIntakeEmail]);
+
+ await intakeEmailsRepository.deleteIntakeEmail({ intakeEmailId: intakeEmail.id, organizationId: 'organization-1' });
+
+ const { intakeEmails: orgIntakeEmailsAfterDelete } = await intakeEmailsRepository.getOrganizationIntakeEmails({
+ organizationId: 'organization-1',
+ });
+
+ expect(orgIntakeEmailsAfterDelete).to.eql([]);
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.repository.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.repository.ts
new file mode 100644
index 00000000..9646bee7
--- /dev/null
+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.repository.ts
@@ -0,0 +1,79 @@
+import type { Database } from '../app/database/database.types';
+import { injectArguments } from '@corentinth/chisels';
+import { and, eq } from 'drizzle-orm';
+import { omitUndefined } from '../shared/utils';
+import { intakeEmailsTable } from './intake-emails.tables';
+
+export type IntakeEmailsRepository = ReturnType<typeof createIntakeEmailsRepository>;
+
+export function createIntakeEmailsRepository({ db }: { db: Database }) {
+ return injectArguments(
+ {
+ createIntakeEmail,
+ updateIntakeEmail,
+ getIntakeEmail,
+ getOrganizationIntakeEmails,
+ deleteIntakeEmail,
+ },
+ { db },
+ );
+}
+
+async function createIntakeEmail({ organizationId, db }: { organizationId: string; db: Database }) {
+ const [intakeEmail] = await db.insert(intakeEmailsTable).values({ organizationId }).returning();
+
+ return { intakeEmail };
+}
+
+async function updateIntakeEmail({ intakeEmailId, organizationId, isEnabled, allowedOrigins, db }: { intakeEmailId: string; organizationId: string; isEnabled?: boolean; allowedOrigins?: string[]; db: Database }) {
+ const [intakeEmail] = await db
+ .update(intakeEmailsTable)
+ .set(
+ omitUndefined({
+ isEnabled,
+ allowedOrigins,
+ }),
+ )
+ .where(
+ and(
+ eq(intakeEmailsTable.id, intakeEmailId),
+ eq(intakeEmailsTable.organizationId, organizationId),
+ ),
+ )
+ .returning();
+
+ return { intakeEmail };
+}
+
+async function getIntakeEmail({ intakeEmailId, db }: { intakeEmailId: string; db: Database }) {
+ const [intakeEmail] = await db
+ .select()
+ .from(intakeEmailsTable)
+ .where(
+ eq(intakeEmailsTable.id, intakeEmailId),
+ );
+
+ return { intakeEmail };
+}
+
+async function getOrganizationIntakeEmails({ organizationId, db }: { organizationId: string; db: Database }) {
+ const intakeEmails = await db
+ .select()
+ .from(intakeEmailsTable)
+ .where(
+ eq(intakeEmailsTable.organizationId, organizationId),
+ );
+
+ return { intakeEmails };
+}
+
+async function deleteIntakeEmail({ intakeEmailId, organizationId, db }: { intakeEmailId: string; organizationId: string; db: Database }) {
+ await db
+ .delete(intakeEmailsTable)
+ .where(
+ and(
+ eq(intakeEmailsTable.id, intakeEmailId),
+ eq(intakeEmailsTable.organizationId, organizationId),
+ ),
+ );
+}
diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.routes.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.routes.ts
new file mode 100644
index 00000000..30887dd1
--- /dev/null
+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.routes.ts
@@ -0,0 +1,187 @@
+import type { ServerInstance } from '../app/server.types';
+import { z } from 'zod';
+import { createUnauthorizedError } from '../app/auth/auth.errors';
+import { getUser } from '../app/auth/auth.models';
+import { getDb } from '../app/database/database.models';
+import { getConfig } from '../config/config.models';
+import { createDocumentsRepository } from '../documents/documents.repository';
+import { createDocumentStorageService } from '../documents/storage/documents.storage.services';
+import { organizationIdRegex } from '../organizations/organizations.constants';
+import { createOrganizationsRepository } from '../organizations/organizations.repository';
+import { ensureUserIsInOrganization } from '../organizations/organizations.usecases';
+import { createError } from '../shared/errors/errors';
+import { getAuthorizationHeader } from '../shared/headers/headers.models';
+import { createLogger } from '../shared/logger/logger';
+import { validateFormData, validateJsonBody, validateParams } from '../shared/validation/validation';
+import { getIsIntakeEmailWebhookSecretValid } from './intake-emails.models';
+import { createIntakeEmailsRepository } from './intake-emails.repository';
+import { intakeEmailsIngestionMetaSchema, parseJson } from './intake-emails.schemas';
+import { processIntakeEmailIngestion } from './intake-emails.usecases';
+
+const logger = createLogger({ namespace: 'intake-emails.routes' });
+
+export function registerIntakeEmailsPrivateRoutes({ app }: { app: ServerInstance }) {
+ setupGetOrganizationIntakeEmailsRoute({ app });
+ setupCreateIntakeEmailRoute({ app });
+ setupDeleteIntakeEmailRoute({ app });
+ setupUpdateIntakeEmailRoute({ app });
+}
+
+export function registerIntakeEmailsPublicRoutes({ app }: { app: ServerInstance }) {
+ setupIngestIntakeEmailRoute({ app });
+}
+
+export function setupGetOrganizationIntakeEmailsRoute({ app }: { app: ServerInstance }) {
+ app.get(
+ '/api/organizations/:organizationId/intake-emails',
+ validateParams(z.object({
+ organizationId: z.string().regex(organizationIdRegex),
+ })),
+ async (context) => {
+ const { userId } = getUser({ context });
+ const { organizationId } = context.req.valid('param');
+ const { db } = getDb({ context });
+
+ const organizationsRepository = createOrganizationsRepository({ db });
+ const intakeEmailsRepository = createIntakeEmailsRepository({ db });
+
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ const { intakeEmails } = await intakeEmailsRepository.getOrganizationIntakeEmails({ organizationId });
+
+ return context.json({ intakeEmails });
+ },
+ );
+}
+
+export function setupCreateIntakeEmailRoute({ app }: { app: ServerInstance }) {
+ app.post(
+ '/api/organizations/:organizationId/intake-emails',
+ validateParams(z.object({
+ organizationId: z.string().regex(organizationIdRegex),
+ })),
+ async (context) => {
+ const { userId } = getUser({ context });
+ const { organizationId } = context.req.valid('param');
+ const { db } = getDb({ context });
+
+ const organizationsRepository = createOrganizationsRepository({ db });
+ const intakeEmailsRepository = createIntakeEmailsRepository({ db });
+
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ const { intakeEmail } = await intakeEmailsRepository.createIntakeEmail({ organizationId });
+
+ return context.json({ intakeEmail });
+ },
+ );
+}
+
+export function setupDeleteIntakeEmailRoute({ app }: { app: ServerInstance }) {
+ app.delete(
+ '/api/organizations/:organizationId/intake-emails/:intakeEmailId',
+ validateParams(z.object({
+ organizationId: z.string().regex(organizationIdRegex),
+ intakeEmailId: z.string(),
+ })),
+ async (context) => {
+ const { userId } = getUser({ context });
+ const { organizationId, intakeEmailId } = context.req.valid('param');
+ const { db } = getDb({ context });
+
+ const organizationsRepository = createOrganizationsRepository({ db });
+ const intakeEmailsRepository = createIntakeEmailsRepository({ db });
+
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ await intakeEmailsRepository.deleteIntakeEmail({ intakeEmailId, organizationId });
+
+ return context.body(null, 204);
+ },
+ );
+}
+
+export function setupUpdateIntakeEmailRoute({ app }: { app: ServerInstance }) {
+ app.put(
+ '/api/organizations/:organizationId/intake-emails/:intakeEmailId',
+ validateParams(z.object({
+ organizationId: z.string().regex(organizationIdRegex),
+ intakeEmailId: z.string(),
+ })),
+ validateJsonBody(z.object({
+ isEnabled: z.boolean().optional(),
+ allowedOrigins: z.array(z.string().email().toLowerCase()).optional(),
+ })),
+ async (context) => {
+ const { userId } = getUser({ context });
+ const { db } = getDb({ context });
+ const { organizationId, intakeEmailId } = context.req.valid('param');
+ const { isEnabled, allowedOrigins } = context.req.valid('json');
+
+ const organizationsRepository = createOrganizationsRepository({ db });
+ const intakeEmailsRepository = createIntakeEmailsRepository({ db });
+
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ const { intakeEmail } = await intakeEmailsRepository.updateIntakeEmail({
+ intakeEmailId,
+ organizationId,
+ isEnabled,
+ allowedOrigins,
+ });
+
+ return context.json({ intakeEmail });
+ },
+ );
+}
+
+export function setupIngestIntakeEmailRoute({ app }: { app: ServerInstance }) {
+ app.post(
+ '/api/intake-emails/ingest',
+ validateFormData(z.object({
+ // meta is a JSON string, but it can also be parsed as an object in case of multipart/form-data json section
+ 'meta': z.string().transform(parseJson).pipe(intakeEmailsIngestionMetaSchema),
+ 'attachments[]': z.array(z.instanceof(File)).min(1, 'At least one attachment is required').optional(),
+ }), { allowAdditionalFields: true }),
+ async (context) => {
+ const { db } = getDb({ context });
+ const { config } = getConfig({ context });
+ const { meta, 'attachments[]': attachments = [] } = context.req.valid('form');
+ const { authorizationHeader } = getAuthorizationHeader({ context });
+
+ if (!config.intakeEmails.isEnabled) {
+ throw createError({
+ message: 'Intake emails are disabled',
+ code: 'intake_emails.disabled',
+ statusCode: 403,
+ });
+ }
+
+ const isIntakeEmailWebhookSecretValid = getIsIntakeEmailWebhookSecretValid({
+ authorizationHeader,
+ secret: config.intakeEmails.webhookSecret,
+ });
+
+ if (!isIntakeEmailWebhookSecretValid) {
+ logger.error('Invalid webhook secret');
+
+ throw createUnauthorizedError();
+ }
+
+ const intakeEmailsRepository = createIntakeEmailsRepository({ db });
+ const documentsRepository = createDocumentsRepository({ db });
+ const documentsStorageService = await createDocumentStorageService({ config });
+
+ await processIntakeEmailIngestion({
+ fromAddress: meta.from.address,
+ recipientsAddresses: meta.to.map(({ address }) => address),
+ attachments,
+ intakeEmailsRepository,
+ documentsRepository,
+ documentsStorageService,
+ });
+
+ return context.body(null, 202);
+ },
+ );
+}
diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.schemas.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.schemas.ts
new file mode 100644
index 00000000..44a9f395
--- /dev/null
+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.schemas.ts
@@ -0,0 +1,24 @@
+import { z } from 'zod';
+
+const emailInfoSchema = z.object({
+ address: z.string().email(),
+ name: z.string().optional(),
+});
+
+export const intakeEmailsIngestionMetaSchema = z.object({
+ from: emailInfoSchema,
+ to: z.array(emailInfoSchema),
+ // cc: z.array(emailInfoSchema).optional(),
+ // subject: z.string(),
+ // text: z.string().optional(),
+ // html: z.string().optional(),
+});
+
+export function parseJson(content: string, ctx: z.RefinementCtx) {
+ try {
+ return JSON.parse(content);
+ } catch (_error) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Invalid json' });
+ return z.never;
+ }
+}
diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.tables.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.tables.ts
new file mode 100644
index 00000000..0e3a0268
--- /dev/null
+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.tables.ts
@@ -0,0 +1,13 @@
+import { generateId as generateHumanReadableId } from '@corentinth/friendly-ids';
+import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
+import { organizationsTable } from '../organizations/organizations.table';
+import { createPrimaryKeyField, createTimestampColumns } from '../shared/db/columns.helpers';
+
+export const intakeEmailsTable = sqliteTable('intake_emails', {
+ ...createPrimaryKeyField({ idGenerator: generateHumanReadableId }),
+ ...createTimestampColumns(),
+
+ organizationId: text('organization_id').notNull().references(() => organizationsTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),
+ allowedOrigins: text('allowed_origins', { mode: 'json' }).notNull().$type<string[]>().default([]),
+ isEnabled: integer('is_enabled', { mode: 'boolean' }).notNull().default(true),
+});
diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts
new file mode 100644
index 00000000..9cd245e1
--- /dev/null
+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts
@@ -0,0 +1,161 @@
+import type { Config } from '../config/config.types';
+import { pick } from 'lodash-es';
+import { describe, expect, test } from 'vitest';
+import { createInMemoryDatabase } from '../app/database/database.test-utils';
+import { createDocumentsRepository } from '../documents/documents.repository';
+import { documentsTable } from '../documents/documents.table';
+import { createDocumentStorageService } from '../documents/storage/documents.storage.services';
+import { createTestLogger } from '../shared/logger/logger.test-utils';
+import { createIntakeEmailsRepository } from './intake-emails.repository';
+import { ingestEmailForRecipient, processIntakeEmailIngestion } from './intake-emails.usecases';
+
+describe('intake-emails usecases', () => {
+ describe('ingestEmailForRecipient', () => {
+ describe('when a email is forwarded to papra api, we look for the recipient in the intake emails repository and create a papra document for each attachment', () => {
+ test(`when an intake email is is configured, enabled and match the recipient, and the sender is allowed, a document is created for each attachment`, async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org-1', name: 'Organization 1' }],
+ intakeEmails: [{ id: 'ie-1', organizationId: 'org-1', allowedOrigins: ['[email protected]'] }],
+ });
+
+ const intakeEmailsRepository = createIntakeEmailsRepository({ db });
+ const documentsRepository = createDocumentsRepository({ db });
+ const documentsStorageService = await createDocumentStorageService({ config: { documentsStorage: { driver: 'in-memory' } } as Config });
+
+ await ingestEmailForRecipient({
+ fromAddress: '[email protected]',
+ recipientAddress: '[email protected]',
+ attachments: [
+ new File(['content1'], 'file1.txt', { type: 'text/plain' }),
+ new File(['content2'], 'file2.txt', { type: 'text/plain' }),
+ ],
+ intakeEmailsRepository,
+ documentsRepository,
+ documentsStorageService,
+ });
+
+ const documents = await db.select().from(documentsTable);
+
+ expect(
+ documents.map(doc => pick(doc, ['organizationId', 'name', 'mimeType', 'originalName', 'content'])),
+ ).to.eql([
+ { organizationId: 'org-1', name: 'file1.txt', mimeType: 'text/plain', originalName: 'file1.txt', content: 'content1' },
+ { organizationId: 'org-1', name: 'file2.txt', mimeType: 'text/plain', originalName: 'file2.txt', content: 'content2' },
+ ]);
+ });
+
+ test(`when the intake email is disabled, nothing happens, only a log is emitted`, async () => {
+ const { getLoggerArgs, logger } = createTestLogger();
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org-1', name: 'Organization 1' }],
+ intakeEmails: [{ id: 'ie-1', organizationId: 'org-1', isEnabled: false }],
+ });
+
+ const intakeEmailsRepository = createIntakeEmailsRepository({ db });
+ const documentsRepository = createDocumentsRepository({ db });
+ const documentsStorageService = await createDocumentStorageService({ config: { documentsStorage: { driver: 'in-memory' } } as Config });
+
+ await ingestEmailForRecipient({
+ fromAddress: '[email protected]',
+ recipientAddress: '[email protected]',
+ attachments: [new File(['content'], 'file.txt', { type: 'text/plain' })],
+ intakeEmailsRepository,
+ documentsRepository,
+ documentsStorageService,
+ logger,
+ });
+
+ expect(getLoggerArgs()).to.eql({ info: [['Intake email is disabled']] });
+ expect(await db.select().from(documentsTable)).to.eql([]);
+ });
+
+ test('when no intake email is found for the recipient, nothing happens, only a log is emitted', async () => {
+ const { getLoggerArgs, logger } = createTestLogger();
+ const { db } = await createInMemoryDatabase();
+
+ const intakeEmailsRepository = createIntakeEmailsRepository({ db });
+ const documentsRepository = createDocumentsRepository({ db });
+ const documentsStorageService = await createDocumentStorageService({ config: { documentsStorage: { driver: 'in-memory' } } as Config });
+
+ await ingestEmailForRecipient({
+ fromAddress: '[email protected]',
+ recipientAddress: '[email protected]',
+ attachments: [new File(['content'], 'file.txt', { type: 'text/plain' })],
+ intakeEmailsRepository,
+ documentsRepository,
+ documentsStorageService,
+ logger,
+ });
+
+ expect(getLoggerArgs()).to.eql({ info: [['Intake email not found']] });
+ expect(await db.select().from(documentsTable)).to.eql([]);
+ });
+
+ test(`in order to be processed, the emitter of the email must be allowed for the intake email
+ it should be registered in the intake email allowed origins
+ if not, an error is logged and no document is created`, async () => {
+ const { getLoggerArgs, logger } = createTestLogger();
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org-1', name: 'Organization 1' }],
+ intakeEmails: [{ id: 'ie-1', organizationId: 'org-1', allowedOrigins: ['[email protected]'] }],
+ });
+
+ const intakeEmailsRepository = createIntakeEmailsRepository({ db });
+ const documentsRepository = createDocumentsRepository({ db });
+ const documentsStorageService = await createDocumentStorageService({ config: { documentsStorage: { driver: 'in-memory' } } as Config });
+
+ await ingestEmailForRecipient({
+ fromAddress: '[email protected]',
+ recipientAddress: '[email protected]',
+ attachments: [new File(['content'], 'file.txt', { type: 'text/plain' })],
+ intakeEmailsRepository,
+ documentsRepository,
+ documentsStorageService,
+ logger,
+ });
+
+ expect(getLoggerArgs()).to.eql({ warn: [[{ fromAddress: '[email protected]' }, 'Origin not allowed']] });
+ expect(await db.select().from(documentsTable)).to.eql([]);
+ });
+ });
+ });
+
+ describe('processIntakeEmailIngestion', () => {
+ test(`when an email is send to multiple intake emails from different organization, the attachments are processed for each of them`, async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [
+ { id: 'org-1', name: 'Organization 1' },
+ { id: 'org-2', name: 'Organization 2' },
+ ],
+ intakeEmails: [
+ { id: 'ie-1', organizationId: 'org-1', allowedOrigins: ['[email protected]'] },
+ { id: 'ie-2', organizationId: 'org-2', allowedOrigins: ['[email protected]'] },
+ ],
+ });
+
+ const intakeEmailsRepository = createIntakeEmailsRepository({ db });
+ const documentsRepository = createDocumentsRepository({ db });
+ const documentsStorageService = await createDocumentStorageService({ config: { documentsStorage: { driver: 'in-memory' } } as Config });
+
+ await processIntakeEmailIngestion({
+ fromAddress: '[email protected]',
+ recipientsAddresses: ['[email protected]', '[email protected]'],
+ attachments: [
+ new File(['content1'], 'file1.txt', { type: 'text/plain' }),
+ ],
+ intakeEmailsRepository,
+ documentsRepository,
+ documentsStorageService,
+ });
+
+ const documents = await db.select().from(documentsTable);
+
+ expect(
+ documents.map(doc => pick(doc, ['organizationId', 'name', 'mimeType', 'originalName', 'content'])),
+ ).to.eql([
+ { organizationId: 'org-1', name: 'file1.txt', mimeType: 'text/plain', originalName: 'file1.txt', content: 'content1' },
+ { organizationId: 'org-2', name: 'file1.txt', mimeType: 'text/plain', originalName: 'file1.txt', content: 'content1' },
+ ]);
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.ts
new file mode 100644
index 00000000..b0f622f0
--- /dev/null
+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.ts
@@ -0,0 +1,105 @@
+import type { DocumentsRepository } from '../documents/documents.repository';
+import type { DocumentStorageService } from '../documents/storage/documents.storage.services';
+import type { Logger } from '../shared/logger/logger.types';
+import type { IntakeEmailsRepository } from './intake-emails.repository';
+import { safely } from '@corentinth/chisels';
+import { createDocument } from '../documents/documents.usecases';
+import { addLogContext, createLogger } from '../shared/logger/logger';
+import { getEmailUsername, getIsFromAllowedOrigin } from './intake-emails.models';
+
+export function processIntakeEmailIngestion({
+ fromAddress,
+ recipientsAddresses,
+ attachments,
+ intakeEmailsRepository,
+ documentsRepository,
+ documentsStorageService,
+}: {
+ fromAddress: string;
+ recipientsAddresses: string[];
+ attachments: File[];
+ intakeEmailsRepository: IntakeEmailsRepository;
+ documentsRepository: DocumentsRepository;
+ documentsStorageService: DocumentStorageService;
+}) {
+ return Promise.all(
+ recipientsAddresses.map(recipientAddress => safely(
+ ingestEmailForRecipient({
+ fromAddress,
+ recipientAddress,
+ attachments,
+ intakeEmailsRepository,
+ documentsRepository,
+ documentsStorageService,
+ }),
+ )),
+ );
+}
+
+export async function ingestEmailForRecipient({
+ fromAddress,
+ recipientAddress,
+ attachments,
+ intakeEmailsRepository,
+ documentsRepository,
+ documentsStorageService,
+ logger = createLogger({ namespace: 'intake-emails.ingest' }),
+}: {
+ fromAddress: string;
+ recipientAddress: string;
+ attachments: File[];
+ intakeEmailsRepository: IntakeEmailsRepository;
+ documentsRepository: DocumentsRepository;
+ documentsStorageService: DocumentStorageService;
+ logger?: Logger;
+}) {
+ const { username } = getEmailUsername({ email: recipientAddress });
+
+ if (!username) {
+ logger.warn('Invalid recipient address, no username found');
+
+ return;
+ }
+
+ const { intakeEmail } = await intakeEmailsRepository.getIntakeEmail({ intakeEmailId: username });
+
+ if (!intakeEmail) {
+ logger.info('Intake email not found');
+
+ return;
+ }
+
+ addLogContext({ intakeEmailId: intakeEmail.id });
+
+ if (!intakeEmail.isEnabled) {
+ logger.info('Intake email is disabled');
+
+ return;
+ }
+
+ const isFromAllowedOrigin = getIsFromAllowedOrigin({
+ origin: fromAddress,
+ allowedOrigins: intakeEmail.allowedOrigins,
+ });
+
+ if (!isFromAllowedOrigin) {
+ logger.warn({ fromAddress }, 'Origin not allowed');
+
+ return;
+ }
+
+ await Promise.all(attachments.map(async (file) => {
+ const [result, error] = await safely(createDocument({
+ file,
+ organizationId: intakeEmail.organizationId,
+ documentsStorageService,
+ documentsRepository,
+ }));
+
+ if (error) {
+ logger.error({ error }, 'Failed to create document for intake email ingestion');
+ } else {
+ logger.info({ documentId: result.document.id }, 'Document created for intake email ingestion');
+ }
+ }));
+}
diff --git a/apps/papra-server/src/modules/shared/validation/validation.ts b/apps/papra-server/src/modules/shared/validation/validation.ts
index fcb298c2..2e3458fe 100644
--- a/apps/papra-server/src/modules/shared/validation/validation.ts
+++ b/apps/papra-server/src/modules/shared/validation/validation.ts
@@ -14,10 +14,10 @@ function formatValidationError({ error }: { error: z.ZodError }) {
}
function buildValidator<Target extends keyof ValidationTargets>({ target, error }: { target: Target; error: { message: string; code: string } }) {
- return <Schema extends z.ZodTypeAny>(schema: Schema) => {
+ return <Schema extends z.ZodTypeAny>(schema: Schema, { allowAdditionalFields = false }: { allowAdditionalFields?: boolean } = {}) => {
return validator(target, (value, context) => {
// @ts-expect-error try to enforce strict mode
- const refinedSchema = schema.strict?.() ?? schema;
+ const refinedSchema = allowAdditionalFields ? schema : (schema.strict?.() ?? schema);
const result = refinedSchema.safeParse(value);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e09da029..e00e0b08 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -214,6 +214,9 @@ importers:
'@corentinth/chisels':
specifier: ^1.1.0
version: 1.1.0
+ '@corentinth/friendly-ids':
+ specifier: ^0.0.1
+ version: 0.0.1
'@hono/node-server':
specifier: ^1.13.7
version: 1.13.7([email protected])
@@ -658,6 +661,9 @@ packages:
'@corentinth/[email protected]':
resolution: {integrity: sha512-l4qG6uXLKFWilt1Mnt5btCoCaIGVLiPOk95V6W3BPPJ9LE558tlet2EnU3z1gfSO7kqRTgkqLdcwwlzI9mMRNQ==}
+ '@corentinth/[email protected]':
+ resolution: {integrity: sha512-NtOr6rEjsSp9bKUNkB0eAH04cFoXpiN9PmPLI0xEGq32g/qXlqp9vWHzr2Cc+Op8rHDjStuJxdWlD9iXTW7onA==}
+
resolution: {integrity: sha512-Ox2kYyxy7NoXdKWdHeDEjZxClwzO4SKM8plAaVwmAJPxHMqA0rLOoAsa+hBDwRLpctf+ZRnAd/ykguuJidnaTA==}
peerDependencies:
@@ -711,9 +717,11 @@ packages:
'@esbuild-kit/[email protected]':
resolution: {integrity: sha512-sPRAnw9CdSsRmEtnsl2WXWdyquogVpB3yZ3dgwJfe8zrOzTsV7cJvmwrKVa+0ma5BoiGJ+BoqkMvawbayKUsqQ==}
+ deprecated: 'Merged into tsx: https://tsx.is'
'@esbuild-kit/[email protected]':
resolution: {integrity: sha512-FxEMIkJKnodyA1OaCUoEvbYRkoZlLZ4d/eXFu9Fh8CbBBgP5EmZxrfTRyN0qpXZ4vOvqnE5YdRdcrmUUXuU+dA==}
+ deprecated: 'Merged into tsx: https://tsx.is'
'@esbuild/[email protected]':
resolution: {integrity: sha512-bmoCYyWdEL3wDQIVbcyzRyeKLgk2WtWLTWz1ZIAZF/EGbNOwSA6ew3PftJ1PqMiOOGu0OyFMzG53L0zqIpPeNA==}
@@ -2807,6 +2815,7 @@ packages:
resolution: {integrity: sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==}
engines: {node: '>=10'}
+ deprecated: This package is no longer supported.
resolution: {integrity: sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==}
@@ -3836,6 +3845,7 @@ packages:
resolution: {integrity: sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==}
engines: {node: '>=10'}
+ deprecated: This package is no longer supported.
resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}
@@ -3880,6 +3890,7 @@ packages:
resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==}
+ deprecated: Glob versions prior to v9 are no longer supported
resolution: {integrity: sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==}
@@ -4067,6 +4078,7 @@ packages:
resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==}
+ deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
@@ -4288,6 +4300,7 @@ packages:
resolution: {integrity: sha512-T9eIRCs6b0J1SHKYIvD8+KCJMcWZ900iZyxdnSCdqxN12Z1ijzT+jY5nrk72Jw4B0HGzms2NgpryArlJqvc3Lw==}
+ cpu: [x64, arm64, wasm32]
os: [darwin, linux, win32]
@@ -4709,6 +4722,7 @@ packages:
resolution: {integrity: sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==}
+ deprecated: This package is no longer supported.
resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==}
@@ -5125,6 +5139,7 @@ packages:
resolution: {integrity: sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==}
+ deprecated: Rimraf versions prior to v4 are no longer supported
hasBin: true
@@ -6922,6 +6937,8 @@ snapshots:
dependencies:
lodash-es: 4.17.21
+ '@corentinth/[email protected]': {}
+
dependencies:
'@floating-ui/dom': 1.6.13