Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(documents): add share by link (#1130)

Corentin Thomasset4fc4f686bd62
diff --git a/.changeset/cold-terms-pick.md b/.changeset/cold-terms-pick.md
new file mode 100644
index 00000000..5ebeda06
--- /dev/null
+++ b/.changeset/cold-terms-pick.md
@@ -0,0 +1,5 @@
+---
+"@papra/app": patch
+---
+
+Laid out the base for the rate limit system.
diff --git a/.changeset/few-mugs-change.md b/.changeset/few-mugs-change.md
new file mode 100644
index 00000000..f6fbee51
--- /dev/null
+++ b/.changeset/few-mugs-change.md
@@ -0,0 +1,5 @@
+---
+"@papra/app": minor
+---
+
+Added document sharing by link: generate a public link to share a document with anyone, without requiring a Papra account. Links can optionally be password-protected and given an expiration date, can be disabled/re-enabled, and are all manageable from a new organization-level "Share links" page.
diff --git a/apps/papra-client/src/index.tsx b/apps/papra-client/src/index.tsx
index 5120cd12..b4129c86 100644
--- a/apps/papra-client/src/index.tsx
+++ b/apps/papra-client/src/index.tsx
@@ -8,6 +8,7 @@ import { render } from 'solid-js/web';
import { CommandPaletteProvider } from './modules/command-palette/command-palette.provider';
import { isDemoMode } from './modules/config/config';
import { ConfigProvider } from './modules/config/config.provider';
+import { ShareDocumentDialogProvider } from './modules/document-share-links/components/share-document-dialog.component';
import { RenameDocumentDialogProvider } from './modules/documents/components/rename-document-button.component';
import { I18nProvider } from './modules/i18n/i18n.provider';
import { AboutDialogProvider } from './modules/shared/components/about-dialog';
@@ -42,9 +43,11 @@ render(
<ConfigProvider>
<AboutDialogProvider>
<RenameDocumentDialogProvider>
- <div class="min-h-screen font-sans text-sm font-400">
- {props.children}
- </div>
+ <ShareDocumentDialogProvider>
+ <div class="min-h-screen font-sans text-sm font-400">
+ {props.children}
+ </div>
+ </ShareDocumentDialogProvider>
</RenameDocumentDialogProvider>
{DemoIndicator && <DemoIndicator />}
</AboutDialogProvider>
diff --git a/apps/papra-client/src/locales/en.dictionary.ts b/apps/papra-client/src/locales/en.dictionary.ts
index 5909f2d2..4b5f1b73 100644
--- a/apps/papra-client/src/locales/en.dictionary.ts
+++ b/apps/papra-client/src/locales/en.dictionary.ts
@@ -527,6 +527,82 @@ export const translations = {
'documents.pdf-viewer.thumbnails.page-alt': 'Page {{ page }}',
+ // Document share links
+ 'document-share-links.share-action': 'Share',
+ 'document-share-links.copy': 'Copy link',
+ 'document-share-links.copied': 'Link copied to clipboard',
+ 'document-share-links.copy-error': 'Failed to copy the link',
+ 'document-share-links.enabled': 'Share link enabled',
+ 'document-share-links.disabled': 'Share link disabled',
+ 'document-share-links.deleted': 'Share link deleted',
+ 'document-share-links.password-protected': 'Password protected',
+ 'document-share-links.no-password': 'No password',
+ 'document-share-links.never-expires': 'Never expires',
+ 'document-share-links.expires-on': 'Expires on {{ date }}',
+ 'document-share-links.list.title': 'Share links',
+ 'document-share-links.list.description': 'Manage share links for "{{ name }}".',
+ 'document-share-links.list.create-new': 'Create new link',
+ 'document-share-links.create.title': 'Create a share link',
+ 'document-share-links.create.description': 'Create a new share link for this document.',
+ 'document-share-links.create.password.toggle': 'Require a password',
+ 'document-share-links.create.password.hint': 'Optional, recipients will have to enter it before accessing.',
+ 'document-share-links.create.password.placeholder': 'Enter or generate a password',
+ 'document-share-links.create.password.generate': 'Generate',
+ 'document-share-links.create.expiration.toggle': 'Set an expiration date',
+ 'document-share-links.create.expiration.hint': 'Optional, the link will auto-expire after this date.',
+ 'document-share-links.create.expiration.24h': '24 hours',
+ 'document-share-links.create.expiration.7d': '7 days',
+ 'document-share-links.create.expiration.30d': '30 days',
+ 'document-share-links.create.expiration.custom': 'Custom',
+ 'document-share-links.create.expiration.pick-date': 'Pick a date',
+ 'document-share-links.create.cancel': 'Cancel',
+ 'document-share-links.create.submit': 'Create link',
+ 'document-share-links.create.error': 'Failed to create the share link',
+ 'document-share-links.created.title': 'Share link created',
+ 'document-share-links.created.description': 'Your share link is ready — copy it and share it.',
+ 'document-share-links.created.done': 'Done',
+ 'document-share-links.actions.menu': 'Actions',
+ 'document-share-links.actions.open-document': 'Open document',
+ 'document-share-links.actions.enable': 'Enable link',
+ 'document-share-links.actions.disable': 'Disable link',
+ 'document-share-links.actions.stop-sharing': 'Stop sharing',
+ 'document-share-links.delete.confirm.title': 'Delete share link',
+ 'document-share-links.delete.confirm.message': 'Anyone with this link will immediately lose access. This cannot be undone.',
+ 'document-share-links.delete.confirm.confirm-button': 'Delete link',
+ 'document-share-links.delete.confirm.cancel-button': 'Cancel',
+ 'document-share-links.management.title': 'Share links',
+ 'document-share-links.management.description': 'Manage every share link created in this organization.',
+ 'document-share-links.management.empty.title': 'No share links',
+ 'document-share-links.management.empty.description': 'Share links created for documents in this organization will appear here.',
+ 'document-share-links.management.table.document': 'Document',
+ 'document-share-links.management.table.link': 'Link',
+ 'document-share-links.management.table.status': 'Status',
+ 'document-share-links.management.table.security': 'Security',
+ 'document-share-links.management.table.expiry': 'Expiry',
+ 'document-share-links.management.table.last-accessed': 'Last accessed',
+ 'document-share-links.management.table.actions': 'Actions',
+ 'document-share-links.management.status.expired': 'Expired',
+ 'document-share-links.management.status.enabled': 'Enabled',
+ 'document-share-links.management.status.disabled': 'Disabled',
+ 'document-share-links.management.status.trashed': 'Document in trash',
+ 'document-share-links.management.status.trashed-hint': 'The shared document is in the trash, so this link is inactive until the document is restored.',
+ 'document-share-links.management.security.password': 'Password',
+ 'document-share-links.management.security.public': 'Public',
+ 'document-share-links.management.never': 'Never',
+ 'document-share-links.public.download': 'Download',
+ 'document-share-links.public.download-error': 'Failed to download the file',
+ 'document-share-links.public.password.title': 'Password required',
+ 'document-share-links.public.password.description': 'This document is protected. Enter the password to access it.',
+ 'document-share-links.public.password.label': 'Password',
+ 'document-share-links.public.password.placeholder': 'Enter the password',
+ 'document-share-links.public.password.submit': 'Unlock',
+ 'document-share-links.public.password.invalid': 'Incorrect password',
+ 'document-share-links.public.password.too-many-attempts': 'Too many attempts. Please try again later.',
+ 'document-share-links.public.gone.title': 'Link unavailable',
+ 'document-share-links.public.gone.description': 'This share link has expired or has been disabled.',
+ 'document-share-links.public.not-found.title': 'Link not found',
+ 'document-share-links.public.not-found.description': 'This share link does not exist.',
+
'trash.delete-all.button': 'Delete all',
'trash.delete-all.confirm.title': 'Permanently delete all documents?',
'trash.delete-all.confirm.description': 'Are you sure you want to permanently delete all documents from the trash? This action cannot be undone.',
@@ -789,6 +865,7 @@ export const translations = {
'layout.menu.tags': 'Tags',
'layout.menu.custom-properties': 'Custom Properties',
'layout.menu.tagging-rules': 'Tagging rules',
+ 'layout.menu.share-links': 'Share links',
'layout.menu.deleted-documents': 'Deleted documents',
'layout.menu.organization-settings': 'Settings',
'layout.menu.api-keys': 'API keys',
diff --git a/apps/papra-client/src/modules/document-share-links/components/share-document-dialog-create-view.component.tsx b/apps/papra-client/src/modules/document-share-links/components/share-document-dialog-create-view.component.tsx
new file mode 100644
index 00000000..4e5d5fdb
--- /dev/null
+++ b/apps/papra-client/src/modules/document-share-links/components/share-document-dialog-create-view.component.tsx
@@ -0,0 +1,185 @@
+import type { Component } from 'solid-js';
+import Calendar from '@corvu/calendar';
+import { useMutation } from '@tanstack/solid-query';
+import { createSignal, For, Show } from 'solid-js';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { useI18nApiErrors } from '@/modules/shared/http/composables/i18n-api-errors';
+import { Button } from '@/modules/ui/components/button';
+import { CalendarGrid } from '@/modules/ui/components/calendar';
+import { CalendarMonthYearHeader } from '@/modules/ui/components/calendar-month-year-header';
+import { DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/modules/ui/components/dialog';
+import { Popover, PopoverContent, PopoverTrigger } from '@/modules/ui/components/popover';
+import { createToast } from '@/modules/ui/components/sonner';
+import { Switch, SwitchControl, SwitchDescription, SwitchLabel, SwitchThumb } from '@/modules/ui/components/switch';
+import { TextField, TextFieldRoot } from '@/modules/ui/components/textfield';
+import { invalidateShareLinksQueries, useCopyShareLink } from '../document-share-links.composables';
+import { generateShareLinkPassword } from '../document-share-links.models';
+import { createShareLink } from '../document-share-links.services';
+
+type ExpirationPreset = '24h' | '7d' | '30d' | 'custom';
+
+export const ShareDocumentDialogCreateView: Component<{
+ document: { id: string; organizationId: string; name: string };
+ onCancel: () => void;
+ onCreated: (args: { url: string }) => void;
+}> = (props) => {
+ const { t, formatDate } = useI18n();
+ const { copyShareLink } = useCopyShareLink();
+ const { getErrorMessage } = useI18nApiErrors();
+
+ const [getIsPasswordEnabled, setIsPasswordEnabled] = createSignal(false);
+ const [getPassword, setPassword] = createSignal('');
+ const [getIsExpirationEnabled, setIsExpirationEnabled] = createSignal(false);
+ const [getExpirationPreset, setExpirationPreset] = createSignal<ExpirationPreset>('7d');
+ const [getCustomDate, setCustomDate] = createSignal<Date | null>(null);
+
+ function computeExpiresAt(): Date | null {
+ if (!getIsExpirationEnabled()) {
+ return null;
+ }
+
+ const preset = getExpirationPreset();
+
+ if (preset === 'custom') {
+ const date = getCustomDate();
+
+ if (!date) {
+ return null;
+ }
+
+ // Expire at the end of the chosen day.
+ const day = `${date.getFullYear()}-${`${date.getMonth() + 1}`.padStart(2, '0')}-${`${date.getDate()}`.padStart(2, '0')}`;
+ return new Date(`${day}T23:59:59`);
+ }
+
+ const days = preset === '24h' ? 1 : preset === '7d' ? 7 : 30;
+ const date = new Date();
+ date.setDate(date.getDate() + days);
+ return date;
+ }
+
+ const canSubmit = () => {
+ if (getIsPasswordEnabled() && getPassword().trim() === '') {
+ return false;
+ }
+
+ if (getIsExpirationEnabled() && getExpirationPreset() === 'custom' && !getCustomDate()) {
+ return false;
+ }
+
+ return true;
+ };
+
+ const createMutation = useMutation(() => ({
+ mutationFn: () => createShareLink({
+ organizationId: props.document.organizationId,
+ documentId: props.document.id,
+ expiresAt: computeExpiresAt(),
+ password: getIsPasswordEnabled() && getPassword() !== '' ? getPassword() : undefined,
+ }),
+ onSuccess: async ({ shareLink }) => {
+ await invalidateShareLinksQueries({ organizationId: props.document.organizationId });
+ await copyShareLink({ url: shareLink.url });
+ props.onCreated({ url: shareLink.url });
+ },
+ onError: (error) => {
+ createToast({ type: 'error', message: getErrorMessage({ error, defaultMessage: t('document-share-links.create.error') }) });
+ },
+ }));
+
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle>{t('document-share-links.create.title')}</DialogTitle>
+ <DialogDescription>{t('document-share-links.create.description')}</DialogDescription>
+ </DialogHeader>
+
+ <div class="flex flex-col">
+ <div class="flex flex-col gap-3 py-4 border-t">
+ <Switch class="flex items-center justify-between gap-4" checked={getIsPasswordEnabled()} onChange={setIsPasswordEnabled}>
+ <div class="flex flex-col gap-0.5">
+ <SwitchLabel class="text-sm font-medium">{t('document-share-links.create.password.toggle')}</SwitchLabel>
+ <SwitchDescription class="text-xs text-muted-foreground">{t('document-share-links.create.password.hint')}</SwitchDescription>
+ </div>
+ <SwitchControl>
+ <SwitchThumb />
+ </SwitchControl>
+ </Switch>
+
+ <Show when={getIsPasswordEnabled()}>
+ <div class="flex items-center gap-2">
+ <TextFieldRoot class="flex-1">
+ <TextField type="text" autocomplete="off" placeholder={t('document-share-links.create.password.placeholder')} value={getPassword()} onInput={e => setPassword(e.currentTarget.value)} />
+ </TextFieldRoot>
+ <Button type="button" variant="outline" onClick={() => setPassword(generateShareLinkPassword())}>
+ <div class="i-tabler-refresh size-4 mr-2" />
+ {t('document-share-links.create.password.generate')}
+ </Button>
+ </div>
+ </Show>
+ </div>
+
+ <div class="flex flex-col gap-3 py-4 border-t">
+ <Switch class="flex items-center justify-between gap-4" checked={getIsExpirationEnabled()} onChange={setIsExpirationEnabled}>
+ <div class="flex flex-col gap-0.5">
+ <SwitchLabel class="text-sm font-medium">{t('document-share-links.create.expiration.toggle')}</SwitchLabel>
+ <SwitchDescription class="text-xs text-muted-foreground">{t('document-share-links.create.expiration.hint')}</SwitchDescription>
+ </div>
+ <SwitchControl>
+ <SwitchThumb />
+ </SwitchControl>
+ </Switch>
+
+ <Show when={getIsExpirationEnabled()}>
+ <div class="flex flex-wrap items-center gap-2">
+ <For each={['24h', '7d', '30d', 'custom'] as const}>
+ {preset => (
+ <Button
+ type="button"
+ size="sm"
+ variant={getExpirationPreset() === preset ? 'default' : 'outline'}
+ onClick={() => setExpirationPreset(preset)}
+ >
+ {t(`document-share-links.create.expiration.${preset}`)}
+ </Button>
+ )}
+ </For>
+ </div>
+
+ <Show when={getExpirationPreset() === 'custom'}>
+ <Popover>
+ <PopoverTrigger as={Button} variant="outline" class="self-start">
+ <div class="i-tabler-calendar size-4 mr-2" />
+ <Show when={getCustomDate()} fallback={t('document-share-links.create.expiration.pick-date')}>
+ {getDate => formatDate(getDate(), { dateStyle: 'medium' })}
+ </Show>
+ </PopoverTrigger>
+ <PopoverContent class="w-auto p-3">
+ <Calendar mode="single" value={getCustomDate()} onValueChange={setCustomDate} fixedWeeks>
+ {() => (
+ <div class="flex flex-col gap-2">
+ <CalendarMonthYearHeader />
+ <CalendarGrid />
+ </div>
+ )}
+ </Calendar>
+ </PopoverContent>
+ </Popover>
+ </Show>
+ </Show>
+ </div>
+ </div>
+
+ <DialogFooter>
+ <div class="flex gap-2 justify-end flex-col-reverse sm:flex-row">
+ <Button variant="secondary" onClick={props.onCancel} disabled={createMutation.isPending}>
+ {t('document-share-links.create.cancel')}
+ </Button>
+ <Button onClick={() => createMutation.mutate()} disabled={!canSubmit() || createMutation.isPending} isLoading={createMutation.isPending}>
+ {t('document-share-links.create.submit')}
+ </Button>
+ </div>
+ </DialogFooter>
+ </>
+ );
+};
diff --git a/apps/papra-client/src/modules/document-share-links/components/share-document-dialog-created-view.component.tsx b/apps/papra-client/src/modules/document-share-links/components/share-document-dialog-created-view.component.tsx
new file mode 100644
index 00000000..c909b543
--- /dev/null
+++ b/apps/papra-client/src/modules/document-share-links/components/share-document-dialog-created-view.component.tsx
@@ -0,0 +1,39 @@
+import type { Component } from 'solid-js';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { useCopy } from '@/modules/shared/utils/copy';
+import { Button } from '@/modules/ui/components/button';
+import { DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/modules/ui/components/dialog';
+
+export const ShareDocumentDialogCreatedView: Component<{
+ url: string;
+ onDone: () => void;
+}> = (props) => {
+ const { t } = useI18n();
+ const { copy, getIsJustCopied } = useCopy();
+
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle>{t('document-share-links.created.title')}</DialogTitle>
+ <DialogDescription>{t('document-share-links.created.description')}</DialogDescription>
+ </DialogHeader>
+
+ <div class="flex items-center gap-2 border rounded-md p-3 min-w-0">
+ <span class="flex-1 truncate text-sm font-mono min-w-0">{props.url}</span>
+ <Button type="button" variant="outline" size="sm" onClick={() => copy({ text: props.url })}>
+ <div
+ class="size-4 mr-2"
+ classList={{ 'i-tabler-check text-green': getIsJustCopied(), 'i-tabler-copy': !getIsJustCopied() }}
+ />
+ {t('document-share-links.copy')}
+ </Button>
+ </div>
+
+ <DialogFooter>
+ <Button onClick={props.onDone}>
+ {t('document-share-links.created.done')}
+ </Button>
+ </DialogFooter>
+ </>
+ );
+};
diff --git a/apps/papra-client/src/modules/document-share-links/components/share-document-dialog-list-view.component.tsx b/apps/papra-client/src/modules/document-share-links/components/share-document-dialog-list-view.component.tsx
new file mode 100644
index 00000000..910e01c4
--- /dev/null
+++ b/apps/papra-client/src/modules/document-share-links/components/share-document-dialog-list-view.component.tsx
@@ -0,0 +1,37 @@
+import type { Component } from 'solid-js';
+import type { ShareLink } from '../document-share-links.types';
+import { For } from 'solid-js';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { Button } from '@/modules/ui/components/button';
+import { DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/modules/ui/components/dialog';
+import { ShareLinkRow } from './share-link-row.component';
+
+export const ShareDocumentDialogListView: Component<{
+ shareLinks: ShareLink[];
+ documentName: string;
+ onCreateNew: () => void;
+}> = (props) => {
+ const { t } = useI18n();
+
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle>{t('document-share-links.list.title')}</DialogTitle>
+ <DialogDescription>{t('document-share-links.list.description', { name: props.documentName })}</DialogDescription>
+ </DialogHeader>
+
+ <div class="flex flex-col gap-2 max-h-72 overflow-y-auto min-w-0">
+ <For each={props.shareLinks}>
+ {shareLink => <ShareLinkRow shareLink={shareLink} />}
+ </For>
+ </div>
+
+ <DialogFooter>
+ <Button onClick={props.onCreateNew}>
+ <div class="i-tabler-plus size-4 mr-2" />
+ {t('document-share-links.list.create-new')}
+ </Button>
+ </DialogFooter>
+ </>
+ );
+};
diff --git a/apps/papra-client/src/modules/document-share-links/components/share-document-dialog.component.tsx b/apps/papra-client/src/modules/document-share-links/components/share-document-dialog.component.tsx
new file mode 100644
index 00000000..d896ca1b
--- /dev/null
+++ b/apps/papra-client/src/modules/document-share-links/components/share-document-dialog.component.tsx
@@ -0,0 +1,140 @@
+import type { Component, ParentComponent } from 'solid-js';
+import { useQuery } from '@tanstack/solid-query';
+import { createContext, createEffect, createSignal, on, Show, useContext } from 'solid-js';
+import { Dialog, DialogContent } from '@/modules/ui/components/dialog';
+import { fetchDocumentShareLinks } from '../document-share-links.services';
+import { ShareDocumentDialogCreateView } from './share-document-dialog-create-view.component';
+import { ShareDocumentDialogCreatedView } from './share-document-dialog-created-view.component';
+import { ShareDocumentDialogListView } from './share-document-dialog-list-view.component';
+
+type DialogView = 'loading' | 'list' | 'create' | 'created';
+
+export const ShareDocumentDialog: Component<{
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ document: { id: string; organizationId: string; name: string };
+}> = (props) => {
+ const [getView, setView] = createSignal<DialogView>('loading');
+
+ // Created-state link to display.
+ const [getCreatedUrl, setCreatedUrl] = createSignal('');
+
+ const shareLinksQuery = useQuery(() => ({
+ queryKey: ['organizations', props.document.organizationId, 'share-links', 'document', props.document.id],
+ queryFn: () => fetchDocumentShareLinks({ organizationId: props.document.organizationId, documentId: props.document.id }),
+ enabled: props.open,
+ }));
+
+ const hasExistingLinks = () => (shareLinksQuery.data?.shareLinks.length ?? 0) > 0;
+
+ // Reset everything each time the dialog opens.
+ createEffect(on(() => props.open, (open) => {
+ if (open) {
+ setCreatedUrl('');
+ setView('loading');
+ }
+ }));
+
+ // Once the links have loaded, decide the initial view: the list when links exist, otherwise the create form.
+ createEffect(() => {
+ if (props.open && getView() === 'loading' && shareLinksQuery.isSuccess) {
+ setView(hasExistingLinks() ? 'list' : 'create');
+ }
+ });
+
+ const goToCreate = () => {
+ setView('create');
+ };
+
+ const handleCancelCreate = () => {
+ // Came from the list (existing links) → go back to it; otherwise close the dialog.
+ if (hasExistingLinks()) {
+ setView('list');
+ return;
+ }
+
+ props.onOpenChange(false);
+ };
+
+ return (
+ <Dialog open={props.open} onOpenChange={props.onOpenChange}>
+ <DialogContent class="sm:max-w-[540px]">
+ <Show when={getView() === 'loading'}>
+ <div class="flex items-center justify-center py-10">
+ <div class="i-tabler-loader-2 size-6 animate-spin text-muted-foreground" />
+ </div>
+ </Show>
+
+ <Show when={getView() === 'list'}>
+ <ShareDocumentDialogListView
+ shareLinks={shareLinksQuery.data?.shareLinks ?? []}
+ documentName={props.document.name}
+ onCreateNew={goToCreate}
+ />
+ </Show>
+
+ <Show when={getView() === 'create'}>
+ <ShareDocumentDialogCreateView
+ document={props.document}
+ onCancel={handleCancelCreate}
+ onCreated={({ url }) => {
+ setCreatedUrl(url);
+ setView('created');
+ }}
+ />
+ </Show>
+
+ <Show when={getView() === 'created'}>
+ <ShareDocumentDialogCreatedView
+ url={getCreatedUrl()}
+ onDone={() => props.onOpenChange(false)}
+ />
+ </Show>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+const context = createContext<{
+ openShareDialog: (args: { documentId: string; organizationId: string; documentName: string }) => void;
+}>();
+
+export function useShareDocumentDialog() {
+ const shareDialogContext = useContext(context);
+
+ if (!shareDialogContext) {
+ throw new Error('useShareDocumentDialog must be used within a ShareDocumentDialogProvider');
+ }
+
+ return shareDialogContext;
+}
+
+export const ShareDocumentDialogProvider: ParentComponent = (props) => {
+ const [getIsOpen, setIsOpen] = createSignal(false);
+ const [getDocumentId, setDocumentId] = createSignal<string | undefined>(undefined);
+ const [getOrganizationId, setOrganizationId] = createSignal<string | undefined>(undefined);
+ const [getDocumentName, setDocumentName] = createSignal<string | undefined>(undefined);
+
+ return (
+ <context.Provider
+ value={{
+ openShareDialog: ({ documentId, organizationId, documentName }) => {
+ setDocumentId(documentId);
+ setOrganizationId(organizationId);
+ setDocumentName(documentName);
+ setIsOpen(true);
+ },
+ }}
+ >
+ <Show when={getDocumentId() && getOrganizationId()}>
+ <ShareDocumentDialog
+ open={getIsOpen()}
+ onOpenChange={setIsOpen}
+ document={{ id: getDocumentId() ?? '', organizationId: getOrganizationId() ?? '', name: getDocumentName() ?? '' }}
+ />
+ </Show>
+
+ {props.children}
+ </context.Provider>
+ );
+};
diff --git a/apps/papra-client/src/modules/document-share-links/components/share-link-actions.component.tsx b/apps/papra-client/src/modules/document-share-links/components/share-link-actions.component.tsx
new file mode 100644
index 00000000..0f81e424
--- /dev/null
+++ b/apps/papra-client/src/modules/document-share-links/components/share-link-actions.component.tsx
@@ -0,0 +1,60 @@
+import type { DropdownMenuSubTriggerProps } from '@kobalte/core/dropdown-menu';
+import type { Component } from 'solid-js';
+import type { ShareLink } from '../document-share-links.types';
+import { A } from '@solidjs/router';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { Button } from '@/modules/ui/components/button';
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/modules/ui/components/dropdown-menu';
+import { useCopyShareLink, useDeleteShareLink, useToggleShareLink } from '../document-share-links.composables';
+
+export const ShareLinkActions: Component<{ shareLink: ShareLink; withGoToDocument?: boolean }> = (props) => {
+ const { t } = useI18n();
+ const { copyShareLink } = useCopyShareLink();
+ const { toggleShareLink } = useToggleShareLink();
+ const { deleteShareLink } = useDeleteShareLink();
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ as={(triggerProps: DropdownMenuSubTriggerProps) => (
+ <Button variant="ghost" size="icon" aria-label={t('document-share-links.actions.menu')} {...triggerProps}>
+ <div class="i-tabler-dots-vertical size-4" />
+ </Button>
+ )}
+ />
+ <DropdownMenuContent class="w-48">
+ {(props.withGoToDocument ?? true) && (
+ <DropdownMenuItem
+ class="cursor-pointer"
+ as={A}
+ href={`/organizations/${props.shareLink.organizationId}/documents/${props.shareLink.documentId}`}
+ >
+ <div class="i-tabler-file-text size-4 mr-2" />
+ <span>{t('document-share-links.actions.open-document')}</span>
+ </DropdownMenuItem>
+ )}
+
+ <DropdownMenuItem class="cursor-pointer" onClick={() => copyShareLink({ url: props.shareLink.url })}>
+ <div class="i-tabler-copy size-4 mr-2" />
+ <span>{t('document-share-links.copy')}</span>
+ </DropdownMenuItem>
+
+ <DropdownMenuItem
+ class="cursor-pointer"
+ onClick={() => toggleShareLink({ organizationId: props.shareLink.organizationId, shareLinkId: props.shareLink.id, isEnabled: !props.shareLink.isEnabled })}
+ >
+ <div class={`${props.shareLink.isEnabled ? 'i-tabler-eye-off' : 'i-tabler-eye'} size-4 mr-2`} />
+ <span>{props.shareLink.isEnabled ? t('document-share-links.actions.disable') : t('document-share-links.actions.enable')}</span>
+ </DropdownMenuItem>
+
+ <DropdownMenuItem
+ class="cursor-pointer text-red"
+ onClick={() => deleteShareLink({ organizationId: props.shareLink.organizationId, shareLinkId: props.shareLink.id })}
+ >
+ <div class="i-tabler-trash size-4 mr-2" />
+ <span>{t('document-share-links.actions.stop-sharing')}</span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+};
diff --git a/apps/papra-client/src/modules/document-share-links/components/share-link-row.component.tsx b/apps/papra-client/src/modules/document-share-links/components/share-link-row.component.tsx
new file mode 100644
index 00000000..360323f5
--- /dev/null
+++ b/apps/papra-client/src/modules/document-share-links/components/share-link-row.component.tsx
@@ -0,0 +1,42 @@
+import type { Component } from 'solid-js';
+import type { ShareLink } from '../document-share-links.types';
+import { Show } from 'solid-js';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { useCopy } from '@/modules/shared/utils/copy';
+import { ShareLinkActions } from './share-link-actions.component';
+import { ShareLinkStatus } from './share-link-status.component';
+
+export const ShareLinkRow: Component<{ shareLink: ShareLink }> = (props) => {
+ const { t, formatDate } = useI18n();
+ const { copy, getIsJustCopied } = useCopy();
+
+ return (
+ <div class="flex items-center gap-2 border rounded-md p-3">
+ <div class="flex-1 min-w-0">
+ <button
+ type="button"
+ class="group flex items-center gap-2 min-w-0 max-w-full cursor-pointer text-left text-muted-foreground transition hover:text-foreground"
+ onClick={() => copy({ text: props.shareLink.url })}
+ title={t('document-share-links.copy')}
+ >
+ <span class="truncate text-sm font-mono min-w-0">{props.shareLink.url}</span>
+ <div
+ class="size-4 flex-shrink-0 opacity-0 transition group-hover:opacity-100"
+ classList={{ 'i-tabler-check text-green opacity-100': getIsJustCopied(), 'i-tabler-copy': !getIsJustCopied() }}
+ />
+ </button>
+ <div class="flex items-center gap-2 text-xs text-muted-foreground mt-1">
+ <ShareLinkStatus shareLink={props.shareLink} />
+
+ <span>{props.shareLink.isPasswordProtected ? t('document-share-links.password-protected') : t('document-share-links.no-password')}</span>
+ <span>-</span>
+ <Show when={props.shareLink.expiresAt} fallback={t('document-share-links.never-expires')}>
+ {getExpiresAt => t('document-share-links.expires-on', { date: formatDate(getExpiresAt()) })}
+ </Show>
+ </div>
+ </div>
+
+ <ShareLinkActions shareLink={props.shareLink} withGoToDocument={false} />
+ </div>
+ );
+};
diff --git a/apps/papra-client/src/modules/document-share-links/components/share-link-status.component.tsx b/apps/papra-client/src/modules/document-share-links/components/share-link-status.component.tsx
new file mode 100644
index 00000000..b7fddf2d
--- /dev/null
+++ b/apps/papra-client/src/modules/document-share-links/components/share-link-status.component.tsx
@@ -0,0 +1,61 @@
+import type { Component } from 'solid-js';
+import type { ShareLink } from '../document-share-links.types';
+import { Match, Switch } from 'solid-js';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+
+type ShareLinkStatusType = 'trashed' | 'expired' | 'enabled' | 'disabled';
+type ShareLinkStatusProps = {
+ shareLink: ShareLink;
+} | {
+ status: ShareLinkStatusType;
+};
+
+export function getShareLinkStatus({ shareLink }: { shareLink: ShareLink }): ShareLinkStatusType {
+ // A trashed document makes the link unusable (410) regardless of its own enabled/expiry state.
+ if (shareLink.isDocumentDeleted) {
+ return 'trashed';
+ }
+
+ if (shareLink.expiresAt && new Date(shareLink.expiresAt) < new Date()) {
+ return 'expired';
+ }
+
+ return shareLink.isEnabled ? 'enabled' : 'disabled';
+}
+
+export const ShareLinkStatus: Component<ShareLinkStatusProps> = (props) => {
+ const { t } = useI18n();
+ const getStatus = () => 'shareLink' in props ? getShareLinkStatus({ shareLink: props.shareLink }) : props.status;
+
+ return (
+ <Switch>
+ <Match when={getStatus() === 'trashed'}>
+ <span
+ class="rounded-full bg-red/10 text-red px-2 py-0.5 text-xs font-medium border border-red/20 inline-flex items-center gap-2 lh-tight"
+ title={t('document-share-links.management.status.trashed-hint')}
+ >
+ <div class="i-tabler-trash size-3" />
+ {t('document-share-links.management.status.trashed')}
+ </span>
+ </Match>
+ <Match when={getStatus() === 'expired'}>
+ <span class="rounded-full bg-warning/10 text-warning px-2 py-0.5 text-xs font-medium border border-warning/20 inline-flex items-center gap-2 lh-tight">
+ <div class="size-1 bg-current rounded-full" />
+ {t('document-share-links.management.status.expired')}
+ </span>
+ </Match>
+ <Match when={getStatus() === 'enabled'}>
+ <span class="rounded-full bg-primary/10 text-primary px-2 py-0.5 text-xs font-medium border border-primary/20 inline-flex items-center gap-2 lh-tight">
+ <div class="size-1 bg-current rounded-full" />
+ {t('document-share-links.management.status.enabled')}
+ </span>
+ </Match>
+ <Match when={getStatus() === 'disabled'}>
+ <span class="rounded-full bg-muted text-muted-foreground px-2 py-0.5 text-xs font-medium border border-muted-foreground/20 inline-flex items-center gap-2 lh-tight">
+ <div class="size-1 bg-current rounded-full" />
+ {t('document-share-links.management.status.disabled')}
+ </span>
+ </Match>
+ </Switch>
+ );
+};
diff --git a/apps/papra-client/src/modules/document-share-links/document-share-links.composables.tsx b/apps/papra-client/src/modules/document-share-links/document-share-links.composables.tsx
new file mode 100644
index 00000000..fc2172b6
--- /dev/null
+++ b/apps/papra-client/src/modules/document-share-links/document-share-links.composables.tsx
@@ -0,0 +1,62 @@
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { useConfirmModal } from '../shared/confirm';
+import { queryClient } from '../shared/query/query-client';
+import { createToast } from '../ui/components/sonner';
+import { deleteShareLink, updateShareLink } from './document-share-links.services';
+
+export function invalidateShareLinksQueries({ organizationId }: { organizationId: string }) {
+ return queryClient.invalidateQueries({ queryKey: ['organizations', organizationId, 'share-links'] });
+}
+
+export function useCopyShareLink() {
+ const { t } = useI18n();
+
+ return {
+ async copyShareLink({ url }: { url: string }) {
+ try {
+ await navigator.clipboard.writeText(url);
+ createToast({ type: 'success', message: t('document-share-links.copied') });
+ } catch {
+ createToast({ type: 'error', message: t('document-share-links.copy-error') });
+ }
+ },
+ };
+}
+
+export function useToggleShareLink() {
+ const { t } = useI18n();
+
+ return {
+ async toggleShareLink({ organizationId, shareLinkId, isEnabled }: { organizationId: string; shareLinkId: string; isEnabled: boolean }) {
+ await updateShareLink({ organizationId, shareLinkId, isEnabled });
+ await invalidateShareLinksQueries({ organizationId });
+ createToast({ type: 'success', message: isEnabled ? t('document-share-links.enabled') : t('document-share-links.disabled') });
+ },
+ };
+}
+
+export function useDeleteShareLink() {
+ const { confirm } = useConfirmModal();
+ const { t } = useI18n();
+
+ return {
+ async deleteShareLink({ organizationId, shareLinkId }: { organizationId: string; shareLinkId: string }): Promise<{ hasDeleted: boolean }> {
+ const isConfirmed = await confirm({
+ title: t('document-share-links.delete.confirm.title'),
+ message: t('document-share-links.delete.confirm.message'),
+ confirmButton: { text: t('document-share-links.delete.confirm.confirm-button'), variant: 'destructive' },
+ cancelButton: { text: t('document-share-links.delete.confirm.cancel-button') },
+ });
+
+ if (!isConfirmed) {
+ return { hasDeleted: false };
+ }
+
+ await deleteShareLink({ organizationId, shareLinkId });
+ await invalidateShareLinksQueries({ organizationId });
+ createToast({ type: 'success', message: t('document-share-links.deleted') });
+
+ return { hasDeleted: true };
+ },
+ };
+}
diff --git a/apps/papra-client/src/modules/document-share-links/document-share-links.models.ts b/apps/papra-client/src/modules/document-share-links/document-share-links.models.ts
new file mode 100644
index 00000000..860960e1
--- /dev/null
+++ b/apps/papra-client/src/modules/document-share-links/document-share-links.models.ts
@@ -0,0 +1,8 @@
+const PASSWORD_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
+
+export function generateShareLinkPassword({ length = 12 }: { length?: number } = {}) {
+ const values = crypto.getRandomValues(new Uint32Array(length));
+
+ // Modulo bias but negligible for our use case
+ return Array.from(values, value => PASSWORD_ALPHABET[value % PASSWORD_ALPHABET.length]).join('');
+}
diff --git a/apps/papra-client/src/modules/document-share-links/document-share-links.services.ts b/apps/papra-client/src/modules/document-share-links/document-share-links.services.ts
new file mode 100644
index 00000000..6794c482
--- /dev/null
+++ b/apps/papra-client/src/modules/document-share-links/document-share-links.services.ts
@@ -0,0 +1,142 @@
+import type { PublicSharedDocument, ShareLink } from './document-share-links.types';
+import { buildTimeConfig } from '@/modules/config/config';
+import { apiClient } from '../shared/http/api-client';
+import { httpClient } from '../shared/http/http-client';
+
+// Wire shape returned by the server: dates are ISO strings (or null).
+type ShareLinkDto = {
+ id: string;
+ documentId: string;
+ organizationId: string;
+ token: string;
+ url: string;
+ isPasswordProtected: boolean;
+ isEnabled: boolean;
+ expiresAt: string | null;
+ lastAccessedAt: string | null;
+ createdAt: string | null;
+ updatedAt: string | null;
+ documentName?: string;
+ isDocumentDeleted?: boolean;
+};
+
+function toShareLink(dto: ShareLinkDto): ShareLink {
+ const toDate = (value: string | null) => (value ? new Date(value) : undefined);
+
+ return {
+ ...dto,
+ expiresAt: toDate(dto.expiresAt),
+ lastAccessedAt: toDate(dto.lastAccessedAt),
+ createdAt: toDate(dto.createdAt),
+ updatedAt: toDate(dto.updatedAt),
+ };
+}
+
+export async function createShareLink({
+ organizationId,
+ documentId,
+ expiresAt,
+ password,
+}: {
+ organizationId: string;
+ documentId: string;
+ expiresAt?: Date | null;
+ password?: string;
+}) {
+ const { shareLink } = await apiClient<{ shareLink: ShareLinkDto }>({
+ method: 'POST',
+ path: `/api/organizations/${organizationId}/documents/${documentId}/share-links`,
+ body: { expiresAt: expiresAt ?? null, password },
+ });
+
+ return { shareLink: toShareLink(shareLink) };
+}
+
+export async function fetchDocumentShareLinks({ organizationId, documentId }: { organizationId: string; documentId: string }) {
+ const { shareLinks } = await apiClient<{ shareLinks: ShareLinkDto[] }>({
+ method: 'GET',
+ path: `/api/organizations/${organizationId}/documents/${documentId}/share-links`,
+ });
+
+ return { shareLinks: shareLinks.map(toShareLink) };
+}
+
+export async function fetchOrganizationShareLinks({ organizationId }: { organizationId: string }) {
+ const { shareLinks } = await apiClient<{ shareLinks: ShareLinkDto[] }>({
+ method: 'GET',
+ path: `/api/organizations/${organizationId}/share-links`,
+ });
+
+ return { shareLinks: shareLinks.map(toShareLink) };
+}
+
+export async function updateShareLink({
+ organizationId,
+ shareLinkId,
+ expiresAt,
+ password,
+ isEnabled,
+}: {
+ organizationId: string;
+ shareLinkId: string;
+ expiresAt?: Date | null;
+ password?: string | null;
+ isEnabled?: boolean;
+}) {
+ const { shareLink } = await apiClient<{ shareLink: ShareLinkDto }>({
+ method: 'PATCH',
+ path: `/api/organizations/${organizationId}/share-links/${shareLinkId}`,
+ body: { expiresAt, password, isEnabled },
+ });
+
+ return { shareLink: toShareLink(shareLink) };
+}
+
+export async function deleteShareLink({ organizationId, shareLinkId }: { organizationId: string; shareLinkId: string }) {
+ await apiClient({
+ method: 'DELETE',
+ path: `/api/organizations/${organizationId}/share-links/${shareLinkId}`,
+ });
+}
+
+// - Public endpoints
+// These intentionally use the lower-level `httpClient` instead of `apiClient`: `apiClient` redirects to /login on any 401,
+// but the public share flow uses 401 to signal "password required", which must be handled in-page.
+
+function getAuthorizationHeaders({ accessToken }: { accessToken?: string }): Record<string, string> {
+ return accessToken === undefined ? {} : { Authorization: `Bearer ${accessToken}` };
+}
+
+export async function fetchSharedDocument({ token, accessToken }: { token: string; accessToken?: string }) {
+ const { document } = await httpClient<{ document: PublicSharedDocument }>({
+ method: 'GET',
+ baseUrl: buildTimeConfig.baseApiUrl,
+ url: `/api/share-links/${token}/document`,
+ headers: getAuthorizationHeaders({ accessToken }),
+ });
+
+ return { document };
+}
+
+export async function verifySharePassword({ token, password }: { token: string; password: string }) {
+ const { accessToken } = await httpClient<{ accessToken: string }>({
+ method: 'POST',
+ baseUrl: buildTimeConfig.baseApiUrl,
+ url: `/api/share-links/${token}/verify`,
+ body: { password },
+ });
+
+ return { accessToken };
+}
+
+export async function fetchSharedDocumentFile({ token, accessToken }: { token: string; accessToken?: string }) {
+ const blob = await httpClient<Blob, 'blob'>({
+ method: 'GET',
+ baseUrl: buildTimeConfig.baseApiUrl,
+ url: `/api/share-links/${token}/document/file`,
+ responseType: 'blob',
+ headers: getAuthorizationHeaders({ accessToken }),
+ });
+
+ return { blob };
+}
diff --git a/apps/papra-client/src/modules/document-share-links/document-share-links.types.ts b/apps/papra-client/src/modules/document-share-links/document-share-links.types.ts
new file mode 100644
index 00000000..c2cdb56e
--- /dev/null
+++ b/apps/papra-client/src/modules/document-share-links/document-share-links.types.ts
@@ -0,0 +1,24 @@
+export type ShareLink = {
+ id: string;
+ documentId: string;
+ organizationId: string;
+ token: string;
+ url: string;
+ isPasswordProtected: boolean;
+ isEnabled: boolean;
+ expiresAt: Date | undefined;
+ lastAccessedAt: Date | undefined;
+ createdAt: Date | undefined;
+ updatedAt: Date | undefined;
+ // Only present on the organization-wide listing (joined from the document).
+ documentName?: string;
+ // Only present on the organization-wide listing: true when the backing document is in the trash,
+ // which makes the link return 410 until the document is restored.
+ isDocumentDeleted?: boolean;
+};
+
+export type PublicSharedDocument = {
+ name: string;
+ size: number;
+ mimeType: string;
+};
diff --git a/apps/papra-client/src/modules/document-share-links/pages/organization-share-links.page.tsx b/apps/papra-client/src/modules/document-share-links/pages/organization-share-links.page.tsx
new file mode 100644
index 00000000..d372ee23
--- /dev/null
+++ b/apps/papra-client/src/modules/document-share-links/pages/organization-share-links.page.tsx
@@ -0,0 +1,226 @@
+import type { Component } from 'solid-js';
+import { A, useParams } from '@solidjs/router';
+import { useQuery } from '@tanstack/solid-query';
+import { createSolidTable, flexRender, getCoreRowModel, getSortedRowModel } from '@tanstack/solid-table';
+import { For, Show, Suspense } from 'solid-js';
+import { RelativeTime } from '@/modules/i18n/components/RelativeTime';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { useCopy } from '@/modules/shared/utils/copy';
+import { Button } from '@/modules/ui/components/button';
+import { EmptyState } from '@/modules/ui/components/empty';
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/modules/ui/components/table';
+import { ShareLinkActions } from '../components/share-link-actions.component';
+import { getShareLinkStatus, ShareLinkStatus } from '../components/share-link-status.component';
+import { fetchOrganizationShareLinks } from '../document-share-links.services';
+
+const CopyLink: Component<{ url: string }> = (props) => {
+ const { copy, getIsJustCopied } = useCopy();
+
+ return (
+ <Button class="group gap-1 cursor-pointer bg-transparent! px-0 text-muted-foreground transition max-w-150px" variant="ghost" onClick={() => copy({ text: props.url })}>
+ <span class="truncate max-w-full group-hover:text-foreground transition" title={props.url}>
+ {new URL(props.url).pathname}
+
+ </span>
+
+ {getIsJustCopied()
+ ? (
+ <div class="i-tabler-check size-4 opacity-0 group-hover:opacity-100 transition text-green flex-shrink-0" />
+ )
+ : (
+ <div class="i-tabler-copy size-4 opacity-0 group-hover:opacity-100 transition flex-shrink-0" />
+ )}
+
+ </Button>
+ );
+};
+
+export const OrganizationShareLinksPage: Component = () => {
+ const params = useParams();
+ const { t } = useI18n();
+
+ const query = useQuery(() => ({
+ queryKey: ['organizations', params.organizationId, 'share-links'],
+ queryFn: () => fetchOrganizationShareLinks({ organizationId: params.organizationId }),
+ }));
+
+ const table = createSolidTable({
+ get data() {
+ return query.data?.shareLinks ?? [];
+ },
+ columns: [
+ {
+ header: () => t('document-share-links.management.table.document'),
+ accessorKey: 'documentName',
+ sortingFn: 'alphanumeric',
+ cell: data => (
+ <div class="max-w-xs flex items-center gap-2">
+ <A
+ href={`/organizations/${data.row.original.organizationId}/documents/${data.row.original.documentId}`}
+ class="font-medium truncate min-w-0 hover:underline"
+ title={data.row.original.documentName}
+ >
+ {data.row.original.documentName}
+ </A>
+ </div>
+ ),
+ },
+ {
+ header: () => t('document-share-links.management.table.link'),
+ accessorKey: 'token',
+ sortingFn: 'alphanumeric',
+ cell: data => (
+ <CopyLink url={data.row.original.url} />
+ ),
+ },
+ {
+ id: 'status',
+ header: () => t('document-share-links.management.table.status'),
+ accessorFn: shareLink => getShareLinkStatus({ shareLink }),
+ sortingFn: 'alphanumeric',
+ cell: data => (
+ <ShareLinkStatus status={data.getValue()} />
+ ),
+ },
+ {
+ header: () => t('document-share-links.management.table.security'),
+ accessorKey: 'isPasswordProtected',
+ sortingFn: 'basic',
+ cell: data => (
+ data.getValue<boolean>()
+ ? (
+ <div class="inline-flex items-center gap-1 ">
+ <div class="i-tabler-lock size-4" />
+ {t('document-share-links.management.security.password')}
+ </div>
+ )
+ : (
+ <div class="inline-flex items-center gap-1 text-muted-foreground">
+ <div class="i-tabler-lock-open size-4" />
+ {t('document-share-links.management.security.public')}
+ </div>
+ )
+ ),
+ },
+ {
+ header: () => t('document-share-links.management.table.expiry'),
+ accessorKey: 'expiresAt',
+ sortingFn: 'datetime',
+ cell: data => (
+ <Show
+ when={data.getValue<Date | undefined>()}
+ fallback={<span class="text-muted-foreground">{t('document-share-links.management.never')}</span>}
+ >
+ {getExpiresAt => <RelativeTime date={getExpiresAt()} />}
+ </Show>
+ ),
+ },
+ {
+ header: () => t('document-share-links.management.table.last-accessed'),
+ accessorKey: 'lastAccessedAt',
+ sortingFn: 'datetime',
+ cell: data => (
+ <Show
+ when={data.getValue<Date | undefined>()}
+ fallback={<span class="text-muted-foreground">{t('document-share-links.management.never')}</span>}
+ >
+ {getLastAccessedAt => <RelativeTime date={getLastAccessedAt()} />}
+ </Show>
+ ),
+ },
+ {
+ id: 'actions',
+ header: () => <div class="text-right">{t('document-share-links.management.table.actions')}</div>,
+ enableSorting: false,
+ cell: data => (
+ <div class="text-right">
+ <ShareLinkActions shareLink={data.row.original} />
+ </div>
+ ),
+ },
+ ],
+ initialState: {
+ sorting: [{ id: 'documentName', desc: false }],
+ },
+ getCoreRowModel: getCoreRowModel(),
+ getSortedRowModel: getSortedRowModel(),
+ });
+
+ return (
+ <div class="p-6 mt-4 pb-32 ">
+ <Suspense>
+ <Show when={query.data?.shareLinks}>
+ {getShareLinks => (
+ <Show
+ when={getShareLinks().length > 0}
+ fallback={(
+ <EmptyState
+ title={t('document-share-links.management.empty.title')}
+ icon="i-tabler-share"
+ description={t('document-share-links.management.empty.description')}
+ />
+ )}
+ >
+ <div class="pb-6">
+ <h2 class="text-xl font-bold">{t('document-share-links.management.title')}</h2>
+ <p class="text-muted-foreground mt-1">{t('document-share-links.management.description')}</p>
+ </div>
+
+ <Table>
+ <TableHeader>
+ <For each={table.getHeaderGroups()}>
+ {headerGroup => (
+ <TableRow>
+ <For each={headerGroup.headers}>
+ {header => (
+ <TableHead>
+ <Show
+ when={header.column.getCanSort()}
+ fallback={flexRender(header.column.columnDef.header, header.getContext())}
+ >
+ <button
+ class="flex items-center gap-1 cursor-pointer select-none"
+ onClick={header.column.getToggleSortingHandler()}
+ >
+ {flexRender(header.column.columnDef.header, header.getContext())}
+ <Show when={header.column.getIsSorted() === 'asc'}>
+ <div class="i-tabler-arrow-down size-3.5" />
+ </Show>
+ <Show when={header.column.getIsSorted() === 'desc'}>
+ <div class="i-tabler-arrow-up size-3.5" />
+ </Show>
+ <Show when={!header.column.getIsSorted()}>
+ <div class="i-tabler-arrows-sort size-3.5 opacity-40" />
+ </Show>
+ </button>
+ </Show>
+ </TableHead>
+ )}
+ </For>
+ </TableRow>
+ )}
+ </For>
+ </TableHeader>
+ <TableBody>
+ <For each={table.getRowModel().rows}>
+ {row => (
+ <TableRow>
+ <For each={row.getVisibleCells()}>
+ {cell => (
+ <TableCell>
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </TableCell>
+ )}
+ </For>
+ </TableRow>
+ )}
+ </For>
+ </TableBody>
+ </Table>
+ </Show>
+ )}
+ </Show>
+ </Suspense>
+ </div>
+ );
+};
diff --git a/apps/papra-client/src/modules/document-share-links/pages/shared-document.page.tsx b/apps/papra-client/src/modules/document-share-links/pages/shared-document.page.tsx
new file mode 100644
index 00000000..985298d9
--- /dev/null
+++ b/apps/papra-client/src/modules/document-share-links/pages/shared-document.page.tsx
@@ -0,0 +1,232 @@
+import type { Component } from 'solid-js';
+import { formatBytes } from '@corentinth/chisels';
+import { A, useParams } from '@solidjs/router';
+import { useMutation, useQuery } from '@tanstack/solid-query';
+import { createSignal, Match, Show, Switch } from 'solid-js';
+import { DocumentBlobPreview } from '@/modules/documents/components/document-preview.component';
+import { getDocumentIcon } from '@/modules/documents/document.models';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { useAboutDialog } from '@/modules/shared/components/about-dialog';
+import { downloadFile } from '@/modules/shared/files/download';
+import { isHttpErrorWithStatusCode } from '@/modules/shared/http/http-errors';
+import { cn } from '@/modules/shared/style/cn';
+import { ThemeSwitcher } from '@/modules/theme/theme-switcher.component';
+import { Button } from '@/modules/ui/components/button';
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger } from '@/modules/ui/components/dropdown-menu';
+import { createToast } from '@/modules/ui/components/sonner';
+import { TextField, TextFieldLabel, TextFieldRoot } from '@/modules/ui/components/textfield';
+import { LanguageSwitcher } from '@/modules/ui/layouts/sidenav.layout';
+import { fetchSharedDocument, fetchSharedDocumentFile, verifySharePassword } from '../document-share-links.services';
+
+function isPreviewable(mimeType: string) {
+ return mimeType.startsWith('image/') || mimeType === 'application/pdf';
+}
+
+const PasswordGate: Component<{ token: string; onUnlocked: (args: { accessToken: string }) => void }> = (props) => {
+ const { t } = useI18n();
+ const [getPassword, setPassword] = createSignal('');
+
+ const verifyMutation = useMutation(() => ({
+ mutationFn: () => verifySharePassword({ token: props.token, password: getPassword() }),
+ onSuccess: ({ accessToken }) => props.onUnlocked({ accessToken }),
+ onError: (error) => {
+ const message = isHttpErrorWithStatusCode({ error, statusCode: 429 })
+ ? t('document-share-links.public.password.too-many-attempts')
+ : t('document-share-links.public.password.invalid');
+
+ createToast({ type: 'error', message });
+ },
+ }));
+
+ return (
+ <div class="flex flex-col gap-4 max-w-lg mx-auto my-6 md:my-24 px-6">
+ <div class="flex flex-col items-center gap-2 text-center">
+ <div class="i-tabler-lock size-8 text-muted-foreground" />
+ <h1 class="text-lg font-semibold">{t('document-share-links.public.password.title')}</h1>
+ <p class="text-sm text-muted-foreground">{t('document-share-links.public.password.description')}</p>
+ </div>
+
+ <form
+ class="flex flex-col gap-3"
+ onSubmit={(e) => {
+ e.preventDefault();
+ verifyMutation.mutate();
+ }}
+ >
+ <TextFieldRoot class="flex flex-col gap-1">
+ <TextFieldLabel class="sr-only" for="share-password">{t('document-share-links.public.password.label')}</TextFieldLabel>
+ <TextField type="password" id="share-password" autofocus autocomplete="current-password" placeholder={t('document-share-links.public.password.placeholder')} value={getPassword()} onInput={e => setPassword(e.currentTarget.value)} />
+ </TextFieldRoot>
+
+ <Button type="submit" isLoading={verifyMutation.isPending} disabled={getPassword() === ''}>
+ {t('document-share-links.public.password.submit')}
+ </Button>
+ </form>
+ </div>
+ );
+};
+
+const SharedDocumentCard: Component<{ token: string; accessToken: string | undefined; document: { name: string; size: number; mimeType: string } }> = (props) => {
+ const { t } = useI18n();
+
+ const downloadMutation = useMutation(() => ({
+ mutationFn: () => fetchSharedDocumentFile({ token: props.token, accessToken: props.accessToken }),
+ onSuccess: ({ blob }) => {
+ const url = URL.createObjectURL(blob);
+ downloadFile({ url, fileName: props.document.name });
+ URL.revokeObjectURL(url);
+ },
+ onError: () => createToast({ type: 'error', message: t('document-share-links.public.download-error') }),
+ }));
+
+ const previewQuery = useQuery(() => ({
+ queryKey: ['share-link', props.token, 'file', props.accessToken],
+ queryFn: () => fetchSharedDocumentFile({ token: props.token, accessToken: props.accessToken }),
+ enabled: isPreviewable(props.document.mimeType),
+ retry: false,
+ refetchOnWindowFocus: false,
+ }));
+
+ return (
+ <div>
+ <div class="flex flex-col md:flex-row items-center gap-2 md:gap-4 max-w-5xl px-6 w-full mx-auto py-12 border-b">
+
+ <div class="bg-muted flex items-center justify-center size-12 rounded-lg shrink-0">
+ <div
+ class={cn(
+ getDocumentIcon({ document: props.document }),
+ 'size-7 text-primary',
+ )}
+ />
+ </div>
+
+ <div class="text-center md:text-left">
+ <h1 class="text-xl font-semibold break-all">{props.document.name}</h1>
+ <p class="text-sm text-muted-foreground">
+ {formatBytes({ bytes: props.document.size, base: 1000 })}
+ </p>
+ </div>
+
+ <div class="md:ml-auto">
+ <Button onClick={() => downloadMutation.mutate()} isLoading={downloadMutation.isPending}>
+ <div class="i-tabler-download size-4 mr-2" />
+ {t('document-share-links.public.download')}
+ </Button>
+ </div>
+ </div>
+
+ <div class="p-6 flex justify-center max-w-5xl mx-auto w-full">
+ <Show
+ when={previewQuery.data?.blob}
+ >
+ {getBlob => (
+ <div class="rounded-md overflow-hidden w-full min-h-1200px">
+ <DocumentBlobPreview blob={getBlob()} mimeType={props.document.mimeType} />
+ </div>
+ )}
+ </Show>
+ </div>
+
+ </div>
+ );
+};
+
+const StatusMessage: Component<{ icon: string; title: string; description: string }> = props => (
+ <div class="flex flex-col items-center gap-2 text-center mt-12 px-6">
+ <div class={`${props.icon} size-8 text-muted-foreground`} />
+ <h1 class="text-lg font-semibold">{props.title}</h1>
+ <p class="text-sm text-muted-foreground">{props.description}</p>
+ </div>
+);
+
+export const SharedDocumentPage: Component = () => {
+ const { t } = useI18n();
+ const params = useParams();
+ const [getAccessToken, setAccessToken] = createSignal<string | undefined>(undefined);
+ const aboutDialog = useAboutDialog();
+
+ const documentQuery = useQuery(() => ({
+ queryKey: ['share-link', params.token, getAccessToken()],
+ queryFn: () => fetchSharedDocument({ token: params.token, accessToken: getAccessToken() }),
+ retry: false,
+ }));
+
+ return (
+ <div>
+
+ <div class="border-b">
+ <div class="px-6 py-4 flex items-center justify-between gap-2 max-w-5xl mx-auto">
+ <A href="/" class="group text-base text-muted-foreground flex gap-2 font-semibold hover:text-foreground transition">
+ <div class="i-tabler-file-text size-6 text-primary transform rotate-12deg group-hover:rotate-25deg transition" />
+
+ Papra
+ </A>
+
+ <div class="flex gap-2">
+ <DropdownMenu>
+ <DropdownMenuTrigger as={Button} variant="outline" aria-label="User menu" size="icon">
+ <div class="i-tabler-dots size-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent class="min-w-48">
+
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger class="flex items-center gap-2 cursor-pointer">
+ <div class="i-tabler-language size-4 text-muted-foreground" />
+ {t('user-menu.language')}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent class="min-w-48">
+ <LanguageSwitcher />
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger class="flex items-center gap-2 cursor-pointer">
+ <div class="i-tabler-sun-moon size-4 text-muted-foreground" />
+ {t('user-menu.theme')}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent class="min-w-48">
+ <ThemeSwitcher />
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+
+ <DropdownMenuItem
+ onClick={() => aboutDialog.open()}
+ class="flex items-center gap-2 cursor-pointer"
+ >
+ <div class="i-tabler-info-circle size-4 text-muted-foreground" />
+ {t('user-menu.about')}
+ </DropdownMenuItem>
+
+ </DropdownMenuContent>
+ </DropdownMenu>
+
+ </div>
+ </div>
+ </div>
+
+ <Switch>
+ <Match when={documentQuery.isPending}>
+ <div class="flex justify-center py-8">
+ <div class="i-tabler-loader-2 size-6 animate-spin text-muted-foreground" />
+ </div>
+ </Match>
+
+ <Match when={documentQuery.isSuccess}>
+ <SharedDocumentCard token={params.token} accessToken={getAccessToken()} document={documentQuery.data!.document} />
+ </Match>
+
+ <Match when={documentQuery.isError && isHttpErrorWithStatusCode({ error: documentQuery.error, statusCode: 401 })}>
+ <PasswordGate token={params.token} onUnlocked={({ accessToken }) => setAccessToken(accessToken)} />
+ </Match>
+
+ <Match when={documentQuery.isError && isHttpErrorWithStatusCode({ error: documentQuery.error, statusCode: 410 })}>
+ <StatusMessage icon="i-tabler-link-off" title={t('document-share-links.public.gone.title')} description={t('document-share-links.public.gone.description')} />
+ </Match>
+
+ <Match when={documentQuery.isError}>
+ <StatusMessage icon="i-tabler-file-off" title={t('document-share-links.public.not-found.title')} description={t('document-share-links.public.not-found.description')} />
+ </Match>
+ </Switch>
+ </div>
+ );
+};
diff --git a/apps/papra-client/src/modules/documents/components/document-management-dropdown.component.tsx b/apps/papra-client/src/modules/documents/components/document-management-dropdown.component.tsx
index 3df9ad4a..f3f6c861 100644
--- a/apps/papra-client/src/modules/documents/components/document-management-dropdown.component.tsx
+++ b/apps/papra-client/src/modules/documents/components/document-management-dropdown.component.tsx
@@ -3,6 +3,7 @@ import type { Component } from 'solid-js';
import type { Document } from '../documents.types';
import { A } from '@solidjs/router';
import { Show } from 'solid-js';
+import { useShareDocumentDialog } from '@/modules/document-share-links/components/share-document-dialog.component';
import { useI18n } from '@/modules/i18n/i18n.provider';
import { Button } from '@/modules/ui/components/button';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger } from '@/modules/ui/components/dropdown-menu';
@@ -15,6 +16,7 @@ export const DocumentManagementDropdown: Component<{ document: Document }> = (pr
const { deleteDocument } = useDeleteDocument();
const { downloadDocument } = useDownloadDocument();
const { openRenameDialog } = useRenameDocumentDialog();
+ const { openShareDialog } = useShareDocumentDialog();
const { t } = useI18n();
const deleteDoc = () => deleteDocument({
@@ -68,6 +70,18 @@ export const DocumentManagementDropdown: Component<{ document: Document }> = (pr
<span>{t('documents.actions.download.title')}</span>
</DropdownMenuItem>
+ <DropdownMenuItem
+ class="cursor-pointer"
+ onClick={() => openShareDialog({
+ documentId: props.document.id,
+ organizationId: props.document.organizationId,
+ documentName: props.document.name,
+ })}
+ >
+ <div class="i-tabler-share size-4 mr-2" />
+ <span>{t('document-share-links.share-action')}</span>
+ </DropdownMenuItem>
+
<DropdownMenuItem
class="cursor-pointer"
onClick={() => openRenameDialog({
diff --git a/apps/papra-client/src/modules/documents/components/document-preview.component.tsx b/apps/papra-client/src/modules/documents/components/document-preview.component.tsx
index faa47c3b..6cadec0e 100644
--- a/apps/papra-client/src/modules/documents/components/document-preview.component.tsx
+++ b/apps/papra-client/src/modules/documents/components/document-preview.component.tsx
@@ -1,7 +1,7 @@
import type { Component } from 'solid-js';
import type { Document } from '../documents.types';
import { useQuery } from '@tanstack/solid-query';
-import { createResource, lazy, Match, Suspense, Switch } from 'solid-js';
+import { createMemo, createResource, lazy, Match, onCleanup, Show, Suspense, Switch } from 'solid-js';
import { useI18n } from '@/modules/i18n/i18n.provider';
import { Card } from '@/modules/ui/components/card';
import { fetchDocumentFile } from '../documents.services';
@@ -110,20 +110,31 @@ const TextFromBlob: Component<{ blob: Blob }> = (props) => {
);
};
-export const DocumentPreview: Component<{ document: Document }> = (props) => {
- const getIsImage = () => imageMimeType.includes(props.document.mimeType);
- const getIsPdf = () => pdfMimeType.includes(props.document.mimeType);
- const getIsTxtLike = () => txtLikeMimeType.includes(props.document.mimeType) || props.document.mimeType.startsWith('text/');
+export const DocumentBlobPreview: Component<{ blob: Blob; mimeType: string }> = (props) => {
+ const getIsImage = () => imageMimeType.includes(props.mimeType);
+ const getIsPdf = () => pdfMimeType.includes(props.mimeType);
+ const getIsTxtLike = () => txtLikeMimeType.includes(props.mimeType) || props.mimeType.startsWith('text/');
const { t } = useI18n();
- const query = useQuery(() => ({
- queryKey: ['organizations', props.document.organizationId, 'documents', props.document.id, 'file'],
- queryFn: () => fetchDocumentFile({ documentId: props.document.id, organizationId: props.document.organizationId }),
- }));
+ const getObjectUrl = createMemo<string | undefined>((prev) => {
+ if (prev) {
+ // Revoke the previous object URL to avoid memory leaks
+ URL.revokeObjectURL(prev);
+ }
+
+ return getIsImage() || getIsPdf() ? URL.createObjectURL(props.blob) : undefined;
+ });
+
+ onCleanup(() => {
+ const url = getObjectUrl();
+ if (url) {
+ URL.revokeObjectURL(url);
+ }
+ });
// Create a resource to check if octet-stream blob is text-safe
const [isOctetStreamTextSafe] = createResource(
- () => query.data && props.document.mimeType === 'application/octet-stream' ? query.data : null,
+ () => props.blob && props.mimeType === 'application/octet-stream' ? props.blob : null,
async (blob) => {
if (!blob) {
return false;
@@ -133,38 +144,51 @@ export const DocumentPreview: Component<{ document: Document }> = (props) => {
);
return (
- <Suspense>
- <Switch>
- <Match when={getIsImage() && query.data}>
- <div>
- <img src={URL.createObjectURL(query.data!)} class="w-full h-full object-contain" />
- </div>
- </Match>
-
- <Match when={getIsPdf() && query.data}>
- <PdfViewer url={URL.createObjectURL(query.data!)} />
- </Match>
-
- <Match when={getIsTxtLike() && query.data}>
- <TextFromBlob blob={query.data!} />
- </Match>
-
- <Match when={props.document.mimeType === 'application/octet-stream' && query.data && isOctetStreamTextSafe()}>
- <TextFromBlob blob={query.data!} />
- </Match>
-
- <Match when={props.document.mimeType === 'application/octet-stream' && query.data && !isOctetStreamTextSafe()}>
- <Card class="px-6 py-12 text-center text-sm text-muted-foreground">
- <p>{t('documents.preview.binary-file')}</p>
- </Card>
- </Match>
-
- <Match when={query.data}>
- <Card class="px-6 py-12 text-center text-sm text-muted-foreground">
- <p>{t('documents.preview.unknown-file-type')}</p>
- </Card>
- </Match>
- </Switch>
- </Suspense>
+ <Switch>
+ <Match when={getIsImage()}>
+ <div>
+ <img src={getObjectUrl()} class="w-full h-full object-contain" />
+ </div>
+ </Match>
+
+ <Match when={getIsPdf()}>
+ <PdfViewer url={getObjectUrl()!} />
+ </Match>
+
+ <Match when={getIsTxtLike()}>
+ <TextFromBlob blob={props.blob} />
+ </Match>
+
+ <Match when={props.mimeType === 'application/octet-stream' && isOctetStreamTextSafe()}>
+ <TextFromBlob blob={props.blob} />
+ </Match>
+
+ <Match when={props.mimeType === 'application/octet-stream' && !isOctetStreamTextSafe()}>
+ <Card class="px-6 py-12 text-center text-sm text-muted-foreground">
+ <p>{t('documents.preview.binary-file')}</p>
+ </Card>
+ </Match>
+
+ <Match when={true}>
+ <Card class="px-6 py-12 text-center text-sm text-muted-foreground">
+ <p>{t('documents.preview.unknown-file-type')}</p>
+ </Card>
+ </Match>
+ </Switch>
+ );
+};
+
+export const DocumentPreview: Component<{ document: Document }> = (props) => {
+ const query = useQuery(() => ({
+ queryKey: ['organizations', props.document.organizationId, 'documents', props.document.id, 'file'],
+ queryFn: () => fetchDocumentFile({ documentId: props.document.id, organizationId: props.document.organizationId }),
+ }));
+
+ return (
+ <Show when={query.data}>
+ {getBlob => (
+ <DocumentBlobPreview blob={getBlob()} mimeType={props.document.mimeType} />
+ )}
+ </Show>
);
};
diff --git a/apps/papra-client/src/modules/documents/pages/document.page.tsx b/apps/papra-client/src/modules/documents/pages/document.page.tsx
index ad0e6ba9..bc8d081a 100644
--- a/apps/papra-client/src/modules/documents/pages/document.page.tsx
+++ b/apps/papra-client/src/modules/documents/pages/document.page.tsx
@@ -8,6 +8,7 @@ import { createEffect, createSignal, For, Match, Show, Suspense, Switch } from '
import { useConfig } from '@/modules/config/config.provider';
import { DocumentCustomPropertiesPanel } from '@/modules/custom-properties/components/document-custom-properties-panel.component';
import { fetchCustomPropertyDefinitions } from '@/modules/custom-properties/custom-properties.services';
+import { useShareDocumentDialog } from '@/modules/document-share-links/components/share-document-dialog.component';
import { RelativeTime } from '@/modules/i18n/components/RelativeTime';
import { useI18n } from '@/modules/i18n/i18n.provider';
import { DocumentTagsList } from '@/modules/tags/components/tag-list.component';
@@ -131,6 +132,7 @@ export const DocumentPage: Component = () => {
const navigate = useNavigate();
const { config } = useConfig();
const { openRenameDialog } = useRenameDocumentDialog();
+ const { openShareDialog } = useShareDocumentDialog();
const getInitialTab = (): Tab => {
const tab = searchParams.tab;
@@ -235,6 +237,19 @@ export const DocumentPage: Component = () => {
<DocumentOpenWithDropdown document={getDocument()} organizationId={params.organizationId} />
+ <Button
+ onClick={() => openShareDialog({
+ documentId: getDocument().id,
+ organizationId: params.organizationId,
+ documentName: getDocument().name,
+ })}
+ variant="outline"
+ size="sm"
+ >
+ <div class="i-tabler-share size-4 mr-2" />
+ {t('document-share-links.share-action')}
+ </Button>
+
{getDocument().isDeleted
? (
<Button
diff --git a/apps/papra-client/src/modules/i18n/locales.test.ts b/apps/papra-client/src/modules/i18n/locales.test.ts
index c7ad916d..456d2e93 100644
--- a/apps/papra-client/src/modules/i18n/locales.test.ts
+++ b/apps/papra-client/src/modules/i18n/locales.test.ts
@@ -59,6 +59,7 @@ describe('locales', () => {
/^activity\.document\.[a-z0-9:]+$/, // activity.document.created
/^organizations\.invitations\.status\.[a-z0-9:]+$/, // organizations.invitations.status.pending
/^socials\.[a-z0-9]+$/, // socials.bluesky
+ /^document-share-links\.create\.expiration\.[a-z0-9]+$/, // document-share-links.create.expiration.24h
];
const keys = new Set(
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 ba234838..753e791e 100644
--- a/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx
+++ b/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx
@@ -99,6 +99,11 @@ const OrganizationLayoutSideNav: Component = () => {
icon: 'i-tabler-list-check',
href: `/organizations/${params.organizationId}/tagging-rules`,
},
+ {
+ label: t('layout.menu.share-links'),
+ icon: 'i-tabler-share',
+ href: `/organizations/${params.organizationId}/share-links`,
+ },
{
label: t('layout.menu.members'),
icon: 'i-tabler-users',
diff --git a/apps/papra-client/src/routes.tsx b/apps/papra-client/src/routes.tsx
index acd8444d..66fa839f 100644
--- a/apps/papra-client/src/routes.tsx
+++ b/apps/papra-client/src/routes.tsx
@@ -16,6 +16,8 @@ import { ResetPasswordPage } from './modules/auth/pages/reset-password.page';
import { CreateCustomPropertyPage } from './modules/custom-properties/pages/create-custom-property.page';
import { CustomPropertiesPage } from './modules/custom-properties/pages/custom-properties-list.page';
import { UpdateCustomPropertyPage } from './modules/custom-properties/pages/update-custom-property.page';
+import { OrganizationShareLinksPage } from './modules/document-share-links/pages/organization-share-links.page';
+import { SharedDocumentPage } from './modules/document-share-links/pages/shared-document.page';
import { DeletedDocumentsPage } from './modules/documents/pages/deleted-documents.page';
import { DocumentPdfViewerPage } from './modules/documents/pages/document-pdf-viewer.page';
import { DocumentPage } from './modules/documents/pages/document.page';
@@ -162,6 +164,10 @@ export const routes: RouteDefinition[] = [
path: '/tagging-rules',
component: TaggingRulesPage,
},
+ {
+ path: '/share-links',
+ component: OrganizationShareLinksPage,
+ },
{
path: '/tagging-rules/create',
component: CreateTaggingRulePage,
@@ -292,6 +298,11 @@ export const routes: RouteDefinition[] = [
path: '/about',
component: AboutPage,
},
+ {
+ // Public document share page — accessible to anyone (logged in or not), no auth guard.
+ path: '/share/:token',
+ component: SharedDocumentPage,
+ },
{
path: '*404',
component: NotFoundPage,
diff --git a/apps/papra-server/src/migrations/list/0021-document-share-links.migration.ts b/apps/papra-server/src/migrations/list/0021-document-share-links.migration.ts
new file mode 100644
index 00000000..495bf7e5
--- /dev/null
+++ b/apps/papra-server/src/migrations/list/0021-document-share-links.migration.ts
@@ -0,0 +1,33 @@
+import type { Migration } from '../migrations.types';
+import { sql } from 'drizzle-orm';
+
+export const documentShareLinksMigration = {
+ name: 'document-share-links',
+
+ up: async ({ db }) => {
+ await db.batch([
+ db.run(sql`CREATE TABLE IF NOT EXISTS "document_share_links" (
+ "id" text PRIMARY KEY NOT NULL,
+ "created_at" integer NOT NULL,
+ "updated_at" integer NOT NULL,
+ "organization_id" text NOT NULL,
+ "document_id" text NOT NULL,
+ "created_by" text,
+ "token" text NOT NULL,
+ "expires_at" integer,
+ "password_hash" text,
+ "is_enabled" integer DEFAULT true NOT NULL,
+ "last_accessed_at" integer,
+ FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade,
+ FOREIGN KEY ("document_id") REFERENCES "documents"("id") ON UPDATE cascade ON DELETE cascade,
+ FOREIGN KEY ("created_by") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null
+ )`),
+ db.run(sql`CREATE UNIQUE INDEX IF NOT EXISTS "document_share_links_token_unique" ON "document_share_links" ("token")`),
+ db.run(sql`CREATE INDEX IF NOT EXISTS "document_share_links_organization_id_document_id_index" ON "document_share_links" ("organization_id", "document_id")`),
+ ]);
+ },
+
+ down: async ({ db }) => {
+ await db.run(sql`DROP TABLE IF EXISTS "document_share_links"`);
+ },
+} satisfies Migration;
diff --git a/apps/papra-server/src/migrations/migrations.registry.test.ts b/apps/papra-server/src/migrations/migrations.registry.test.ts
index 0296b1d4..bf4f6328 100644
--- a/apps/papra-server/src/migrations/migrations.registry.test.ts
+++ b/apps/papra-server/src/migrations/migrations.registry.test.ts
@@ -83,6 +83,8 @@ describe('migrations registry', () => {
CREATE INDEX "document_custom_property_values_definition_text_index" ON "document_custom_property_values" ("property_definition_id", "text_value");
CREATE INDEX "document_custom_property_values_definition_user_id_index" ON "document_custom_property_values" ("property_definition_id", "user_id");
CREATE INDEX "document_custom_property_values_document_id_index" ON "document_custom_property_values" ("document_id", "property_definition_id");
+ CREATE INDEX "document_share_links_organization_id_document_id_index" ON "document_share_links" ("organization_id", "document_id");
+ CREATE UNIQUE INDEX "document_share_links_token_unique" ON "document_share_links" ("token");
CREATE INDEX documents_file_encryption_kek_version_index ON documents (file_encryption_kek_version);
CREATE INDEX documents_organization_id_document_date_index ON documents(organization_id, document_date);
CREATE INDEX "documents_organization_id_is_deleted_created_at_index" ON "documents" ("organization_id","is_deleted","created_at");
@@ -114,6 +116,7 @@ describe('migrations registry', () => {
CREATE TABLE "custom_property_select_options" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "property_definition_id" text NOT NULL REFERENCES "custom_property_definitions"("id") ON DELETE CASCADE ON UPDATE CASCADE, "name" text NOT NULL, "key" text NOT NULL, "display_order" integer NOT NULL DEFAULT 0 );
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 "document_custom_property_values" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "document_id" text NOT NULL REFERENCES "documents"("id") ON DELETE CASCADE ON UPDATE CASCADE, "property_definition_id" text NOT NULL REFERENCES "custom_property_definitions"("id") ON DELETE CASCADE ON UPDATE CASCADE, "text_value" text, "number_value" real, "date_value" integer, "boolean_value" integer, "select_option_id" text REFERENCES "custom_property_select_options"("id") ON DELETE CASCADE ON UPDATE CASCADE, "user_id" text REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE, "related_document_id" text REFERENCES "documents"("id") ON DELETE CASCADE ON UPDATE CASCADE );
+ CREATE TABLE "document_share_links" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "organization_id" text NOT NULL, "document_id" text NOT NULL, "created_by" text, "token" text NOT NULL, "expires_at" integer, "password_hash" text, "is_enabled" integer DEFAULT true NOT NULL, "last_accessed_at" integer, FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("document_id") REFERENCES "documents"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("created_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, document_date INTEGER, 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( document_id, organization_id, name, content, prefix='2 3 4' );
CREATE TABLE 'documents_fts_config'(k PRIMARY KEY, v) WITHOUT ROWID;
diff --git a/apps/papra-server/src/migrations/migrations.registry.ts b/apps/papra-server/src/migrations/migrations.registry.ts
index 68866669..946f2505 100644
--- a/apps/papra-server/src/migrations/migrations.registry.ts
+++ b/apps/papra-server/src/migrations/migrations.registry.ts
@@ -20,6 +20,7 @@ import { documentsDateMigration } from './list/0017-documents-date.migration';
import { customPropertiesMigration } from './list/0018-custom-properties.migration';
import { twoFactorVerifiedMigration } from './list/0019-two-factor-verified.migration';
import { kvStoreMigration } from './list/0020-kv-store.migration';
+import { documentShareLinksMigration } from './list/0021-document-share-links.migration';
export const migrations: Migration[] = [
initialSchemaSetupMigration,
@@ -42,4 +43,5 @@ export const migrations: Migration[] = [
customPropertiesMigration,
twoFactorVerifiedMigration,
kvStoreMigration,
+ documentShareLinksMigration,
];
diff --git a/apps/papra-server/src/modules/api-keys/api-keys.middlewares.ts b/apps/papra-server/src/modules/api-keys/api-keys.middlewares.ts
index 886765b0..8651e3ef 100644
--- a/apps/papra-server/src/modules/api-keys/api-keys.middlewares.ts
+++ b/apps/papra-server/src/modules/api-keys/api-keys.middlewares.ts
@@ -33,8 +33,10 @@ export function createApiKeyMiddleware({ db }: { db: Database }) {
throw createUnauthorizedError();
}
+ // The token isn't an API key (e.g. a share-link access token JWT). Leave it for
+ // downstream handlers; protected routes still enforce auth via requireAuthentication.
if (!looksLikeAnApiKey(token)) {
- throw createUnauthorizedError();
+ return next();
}
const { apiKey } = await getApiKey({ token, apiKeyRepository });
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 dfe8d409..a04e1496 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
@@ -5,6 +5,7 @@ import { runMigrations } from '../../../migrations/migrations.usecases';
import { apiKeyOrganizationsTable, apiKeysTable } from '../../api-keys/api-keys.tables';
import { customPropertyDefinitionsTable, documentCustomPropertyValuesTable } from '../../custom-properties/custom-properties.table';
import { customPropertySelectOptionsTable } from '../../custom-properties/options/custom-properties-options.table';
+import { documentShareLinksTable } from '../../document-share-links/document-share-links.table';
import { documentsTable } from '../../documents/documents.table';
import { intakeEmailsTable } from '../../intake-emails/intake-emails.tables';
import { organizationInvitationsTable, organizationMembersTable, organizationsTable } from '../../organizations/organizations.table';
@@ -43,6 +44,7 @@ const seedTables = {
customPropertySelectOptions: customPropertySelectOptionsTable,
documentCustomPropertyValues: documentCustomPropertyValuesTable,
documents: documentsTable,
+ documentShareLinks: documentShareLinksTable,
documentsTags: documentsTagsTable,
intakeEmails: intakeEmailsTable,
organizationInvitations: organizationInvitationsTable,
diff --git a/apps/papra-server/src/modules/app/middlewares/errors.middleware.ts b/apps/papra-server/src/modules/app/middlewares/errors.middleware.ts
index 11929872..71b169b4 100644
--- a/apps/papra-server/src/modules/app/middlewares/errors.middleware.ts
+++ b/apps/papra-server/src/modules/app/middlewares/errors.middleware.ts
@@ -8,6 +8,10 @@ export function registerErrorMiddleware({ app }: { app: ServerInstance }) {
app.onError((error, context) => {
logger.error({ error }, error.message ?? 'An error occurred');
+ // For some status code browsers may tend to cache error responses and not play new requests
+ // Happened with document share links and 410 responses when disabling/re-enabling share links
+ context.header('Cache-Control', 'no-store');
+
if (isCustomError(error) && !error.isInternal) {
return context.json(
formatPublicErrorPayload(error),
diff --git a/apps/papra-server/src/modules/app/rate-limit/rate-limit.config.constants.ts b/apps/papra-server/src/modules/app/rate-limit/rate-limit.config.constants.ts
new file mode 100644
index 00000000..16d8f989
--- /dev/null
+++ b/apps/papra-server/src/modules/app/rate-limit/rate-limit.config.constants.ts
@@ -0,0 +1,9 @@
+export const DURATION_UNIT_IN_MS: Record<string, number> = {
+ s: 1000,
+ m: 60 * 1000,
+ h: 60 * 60 * 1000,
+};
+
+export const RATE_LIMIT_CONFIG_REGEX = new RegExp(`^(\\d+)\\/(\\d*)([${Object.keys(DURATION_UNIT_IN_MS).join('')}])$`, 'i');
+
+export const RATE_LIMIT_CONFIG_FORMAT_DOC = 'Expected formats matching /^\\d+\\/\\d*[smh]$/, like "10/h", "10/2h", "2/5m", etc. For example "10/h" means 10 hits per hour, "10/2h" means 10 hits per 2 hours, "2/5m" means 2 hits per 5 minutes, etc. Units can be seconds (s), minutes (m) or hours (h).';
diff --git a/apps/papra-server/src/modules/app/rate-limit/rate-limit.config.models.test.ts b/apps/papra-server/src/modules/app/rate-limit/rate-limit.config.models.test.ts
new file mode 100644
index 00000000..0be71dc4
--- /dev/null
+++ b/apps/papra-server/src/modules/app/rate-limit/rate-limit.config.models.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, test } from 'vitest';
+import { parseRateLimitConfig } from './rate-limit.config.models';
+
+describe('rate-limit.config.models', () => {
+ describe('parseRateLimitConfig', () => {
+ test('parses rate limit config, like "10/2h", "2/5m", into a maxHits and window in Temporal.Duration', () => {
+ expect(parseRateLimitConfig('10/2h')).to.eql({ maxHits: 10, window: Temporal.Duration.from({ hours: 2 }) });
+ expect(parseRateLimitConfig('2/50m')).to.eql({ maxHits: 2, window: Temporal.Duration.from({ minutes: 50 }) });
+ });
+
+ test('the duration value is optional and defaults to 1, so "10/h" is equivalent to "10/1h"', () => {
+ expect(parseRateLimitConfig('10/h')).to.eql({ maxHits: 10, window: Temporal.Duration.from({ hours: 1 }) });
+ });
+
+ test('window unit are case-insensitive, so "10/2H" is equivalent to "10/2h"', () => {
+ expect(parseRateLimitConfig('10/2H')).to.eql({ maxHits: 10, window: Temporal.Duration.from({ hours: 2 }) });
+ });
+
+ test('trims whitespace around the config string', () => {
+ expect(parseRateLimitConfig(' 10/2h ')).to.eql({ maxHits: 10, window: Temporal.Duration.from({ hours: 2 }) });
+ });
+
+ test('units can be seconds (s), minutes (m) or hours (h)', () => {
+ expect(parseRateLimitConfig('10/30s')).to.eql({ maxHits: 10, window: Temporal.Duration.from({ seconds: 30 }) });
+ expect(parseRateLimitConfig('10/15m')).to.eql({ maxHits: 10, window: Temporal.Duration.from({ minutes: 15 }) });
+ expect(parseRateLimitConfig('10/1h')).to.eql({ maxHits: 10, window: Temporal.Duration.from({ hours: 1 }) });
+ });
+
+ test('throws if the format is invalid', () => {
+ expect(() => parseRateLimitConfig('invalid')).to.throw('Invalid rate limit format: "invalid". Expected formats like "10/h", "10/2h", "2/5m", etc.');
+ expect(() => parseRateLimitConfig('10x2h')).to.throw('Invalid rate limit format: "10x2h". Expected formats like "10/h", "10/2h", "2/5m", etc.');
+ expect(() => parseRateLimitConfig('10/')).to.throw('Invalid rate limit format: "10/". Expected formats like "10/h", "10/2h", "2/5m", etc.');
+ expect(() => parseRateLimitConfig('/2h')).to.throw('Invalid rate limit format: "/2h". Expected formats like "10/h", "10/2h", "2/5m", etc.');
+ expect(() => parseRateLimitConfig('10/2x')).to.throw('Invalid rate limit format: "10/2x". Expected formats like "10/h", "10/2h", "2/5m", etc.');
+ expect(() => parseRateLimitConfig('')).to.throw('Invalid rate limit format: "". Expected formats like "10/h", "10/2h", "2/5m", etc.');
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/app/rate-limit/rate-limit.config.models.ts b/apps/papra-server/src/modules/app/rate-limit/rate-limit.config.models.ts
new file mode 100644
index 00000000..b5e09afd
--- /dev/null
+++ b/apps/papra-server/src/modules/app/rate-limit/rate-limit.config.models.ts
@@ -0,0 +1,40 @@
+import { isNil } from '../../shared/utils';
+import { DURATION_UNIT_IN_MS, RATE_LIMIT_CONFIG_REGEX } from './rate-limit.config.constants';
+
+export function parseRateLimitConfig(rateLimitConfig: string) {
+ const match = rateLimitConfig.trim().match(RATE_LIMIT_CONFIG_REGEX);
+
+ const makeInvalidFormatError = () => new Error(`Invalid rate limit format: "${rateLimitConfig}". Expected formats like "10/h", "10/2h", "2/5m", etc.`);
+
+ if (!match) {
+ throw makeInvalidFormatError();
+ }
+
+ const [, maxHitsStr, durationValueStr, durationUnit] = match;
+
+ if (isNil(maxHitsStr) || isNil(durationValueStr) || isNil(durationUnit)) {
+ // Shouldn't be possible due to regex, but for type safety
+ throw makeInvalidFormatError();
+ }
+
+ const maxHits = Number.parseInt(maxHitsStr, 10);
+ const durationValue = durationValueStr === '' ? 1 : Number.parseInt(durationValueStr, 10);
+
+ if (Number.isNaN(maxHits) || Number.isNaN(durationValue)) {
+ throw makeInvalidFormatError();
+ }
+
+ const durationUnitInMs = DURATION_UNIT_IN_MS[durationUnit.toLowerCase()];
+
+ if (isNil(durationUnitInMs)) {
+ // Shouldn't be possible due to regex, but for type safety
+ throw makeInvalidFormatError();
+ }
+
+ const durationInMs = durationValue * durationUnitInMs;
+
+ return {
+ maxHits,
+ window: Temporal.Duration.from({ milliseconds: durationInMs }),
+ };
+}
diff --git a/apps/papra-server/src/modules/app/rate-limit/rate-limit.config.schemas.test.ts b/apps/papra-server/src/modules/app/rate-limit/rate-limit.config.schemas.test.ts
new file mode 100644
index 00000000..04373010
--- /dev/null
+++ b/apps/papra-server/src/modules/app/rate-limit/rate-limit.config.schemas.test.ts
@@ -0,0 +1,23 @@
+import * as v from 'valibot';
+import { describe, expect, test } from 'vitest';
+import { rateLimitConfigSchema } from './rate-limit.config.schemas';
+
+describe('rate-limit.config.schemas', () => {
+ describe('rateLimitConfigSchema', () => {
+ test('validates and transforms rate limit config strings into objects with maxHits and window properties', () => {
+ // Advanced format testing in ./rate-limit.config.models.test.ts
+ expect(v.parse(rateLimitConfigSchema, '10/2h')).to.eql({ maxHits: 10, window: Temporal.Duration.from({ hours: 2 }) });
+ expect(v.parse(rateLimitConfigSchema, '2/50m')).to.eql({ maxHits: 2, window: Temporal.Duration.from({ minutes: 50 }) });
+ expect(v.parse(rateLimitConfigSchema, '2/m')).to.eql({ maxHits: 2, window: Temporal.Duration.from({ minutes: 1 }) });
+ expect(v.parse(rateLimitConfigSchema, ' 2/m ')).to.eql({ maxHits: 2, window: Temporal.Duration.from({ minutes: 1 }) });
+ });
+
+ test('invalid format are rejected', () => {
+ expect(() => v.parse(rateLimitConfigSchema, 'invalid')).to.throw();
+ expect(() => v.parse(rateLimitConfigSchema, '10x2h')).to.throw();
+ expect(() => v.parse(rateLimitConfigSchema, '10/')).to.throw();
+ expect(() => v.parse(rateLimitConfigSchema, '/2h')).to.throw();
+ expect(() => v.parse(rateLimitConfigSchema, '10/2x')).to.throw();
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/app/rate-limit/rate-limit.config.schemas.ts b/apps/papra-server/src/modules/app/rate-limit/rate-limit.config.schemas.ts
new file mode 100644
index 00000000..eaba93cd
--- /dev/null
+++ b/apps/papra-server/src/modules/app/rate-limit/rate-limit.config.schemas.ts
@@ -0,0 +1,7 @@
+import * as v from 'valibot';
+import { parseRateLimitConfig } from './rate-limit.config.models';
+
+export const rateLimitConfigSchema = v.pipe(
+ v.string(),
+ v.transform(parseRateLimitConfig),
+);
diff --git a/apps/papra-server/src/modules/app/rate-limit/rate-limit.errors.ts b/apps/papra-server/src/modules/app/rate-limit/rate-limit.errors.ts
new file mode 100644
index 00000000..bc18e45d
--- /dev/null
+++ b/apps/papra-server/src/modules/app/rate-limit/rate-limit.errors.ts
@@ -0,0 +1,7 @@
+import { createErrorFactory } from '../../shared/errors/errors';
+
+export const createTooManyRequestsError = createErrorFactory({
+ message: 'Too many requests',
+ code: 'server.too_many_requests',
+ statusCode: 429,
+});
diff --git a/apps/papra-server/src/modules/app/rate-limit/rate-limit.kv-store.ts b/apps/papra-server/src/modules/app/rate-limit/rate-limit.kv-store.ts
new file mode 100644
index 00000000..4dc923d1
--- /dev/null
+++ b/apps/papra-server/src/modules/app/rate-limit/rate-limit.kv-store.ts
@@ -0,0 +1,16 @@
+import type { KvStore } from '../../kv-store/kv-store.types';
+import type { RateLimitKvStore } from './rate-limit.types';
+import * as v from 'valibot';
+import { positiveIntegerSchema } from '../../shared/schemas/number.schemas';
+
+const rateLimitKvStoreEntrySchema = v.object({
+ hitCount: positiveIntegerSchema,
+ resetAtEpochMs: positiveIntegerSchema,
+});
+
+export function scopeKvStoreForRateLimit({ kvStore }: { kvStore: KvStore }): RateLimitKvStore {
+ return kvStore.defineScope({
+ prefix: 'rate-limit',
+ schema: rateLimitKvStoreEntrySchema,
+ });
+}
diff --git a/apps/papra-server/src/modules/app/rate-limit/rate-limit.types.ts b/apps/papra-server/src/modules/app/rate-limit/rate-limit.types.ts
new file mode 100644
index 00000000..b70851c7
--- /dev/null
+++ b/apps/papra-server/src/modules/app/rate-limit/rate-limit.types.ts
@@ -0,0 +1,6 @@
+import type { KvStoreScope } from '../../kv-store/kv-store.types';
+
+export type RateLimitKvStore = KvStoreScope<{
+ hitCount: number;
+ resetAtEpochMs: number;
+}>;
diff --git a/apps/papra-server/src/modules/app/rate-limit/rate-limit.usecases.test.ts b/apps/papra-server/src/modules/app/rate-limit/rate-limit.usecases.test.ts
new file mode 100644
index 00000000..5b1e403d
--- /dev/null
+++ b/apps/papra-server/src/modules/app/rate-limit/rate-limit.usecases.test.ts
@@ -0,0 +1,100 @@
+import type { RateLimitKvStore } from './rate-limit.types';
+import * as v from 'valibot';
+import { describe, expect, test } from 'vitest';
+import { createInMemoryKvStoreDriver } from '../../kv-store/drivers/in-memory/in-memory.kv-store-driver';
+import { createKvStore } from '../../kv-store/kv-store';
+import { createTestClock } from '../../shared/clock/clock.test-utils';
+import { createTooManyRequestsError } from './rate-limit.errors';
+import { checkRateLimit, getRateLimit } from './rate-limit.usecases';
+
+function setup() {
+ const { clock } = createTestClock();
+ const driver = createInMemoryKvStoreDriver({ clock });
+ const kvStore = createKvStore({ driver });
+
+ const scope: RateLimitKvStore = kvStore.defineScope({
+ prefix: 'rate-limit',
+ schema: v.object({ hitCount: v.number(), resetAtEpochMs: v.number() }),
+ });
+
+ return { clock, kvStore: scope };
+}
+
+describe('rate-limit usecases', () => {
+ describe('getRateLimit', () => {
+ test('allows hits up to maxHits within the window, then flags the limit as exceeded', async () => {
+ const { clock, kvStore } = setup();
+ const config = { maxHits: 3, window: { minutes: 1 }, key: 'user-1' };
+
+ expect(await getRateLimit({ ...config, kvStore, clock })).toMatchObject({ hasExceededLimit: false, hitCount: 1, hitsRemaining: 2 });
+ expect(await getRateLimit({ ...config, kvStore, clock })).toMatchObject({ hasExceededLimit: false, hitCount: 2, hitsRemaining: 1 });
+ expect(await getRateLimit({ ...config, kvStore, clock })).toMatchObject({ hasExceededLimit: false, hitCount: 3, hitsRemaining: 0 });
+
+ // The 4th hit exceeds maxHits: the limit is flagged and the counter is not incremented further.
+ expect(await getRateLimit({ ...config, kvStore, clock })).toMatchObject({ hasExceededLimit: true, hitCount: 3, hitsRemaining: 0 });
+ });
+
+ test('exposes the window reset instant for response headers and keeps it fixed across hits', async () => {
+ const { clock, kvStore } = setup();
+ const config = { maxHits: 3, window: { minutes: 1 }, key: 'user-1' };
+
+ // First hit at t=0 opens a window that resets one minute later.
+ const expectedResetAt = clock.now().add({ minutes: 1 });
+ const first = await getRateLimit({ ...config, kvStore, clock });
+ expect(first.resetAt.equals(expectedResetAt)).to.eql(true);
+
+ // Subsequent hits report the same reset instant rather than sliding it forward.
+ clock.advanceBy({ seconds: 30 });
+ const second = await getRateLimit({ ...config, kvStore, clock });
+ expect(second.resetAt.equals(expectedResetAt)).to.eql(true);
+ });
+
+ test('the window is fixed and does not slide forward as hits accumulate', async () => {
+ const { clock, kvStore } = setup();
+ const config = { maxHits: 2, window: { minutes: 1 }, key: 'user-1' };
+
+ expect(await getRateLimit({ ...config, kvStore, clock })).toMatchObject({ hasExceededLimit: false });
+
+ clock.advanceBy({ seconds: 50 });
+ expect(await getRateLimit({ ...config, kvStore, clock })).toMatchObject({ hasExceededLimit: false });
+ expect(await getRateLimit({ ...config, kvStore, clock })).toMatchObject({ hasExceededLimit: true });
+
+ // Past the original reset instant the entry has expired, so the counter starts fresh.
+ clock.advanceBy({ seconds: 11 });
+ expect(await getRateLimit({ ...config, kvStore, clock })).toMatchObject({ hasExceededLimit: false, hitCount: 1 });
+ });
+
+ test('counts are tracked independently per key', async () => {
+ const { clock, kvStore } = setup();
+ const config = { maxHits: 1, window: { minutes: 1 } };
+
+ expect(await getRateLimit({ ...config, key: 'user-1', kvStore, clock })).toMatchObject({ hasExceededLimit: false });
+ expect(await getRateLimit({ ...config, key: 'user-1', kvStore, clock })).toMatchObject({ hasExceededLimit: true });
+
+ // A different key is unaffected by user-1 reaching its limit.
+ expect(await getRateLimit({ ...config, key: 'user-2', kvStore, clock })).toMatchObject({ hasExceededLimit: false, hitCount: 1 });
+ });
+
+ test('the counter resets once the window has fully elapsed', async () => {
+ const { clock, kvStore } = setup();
+ const config = { maxHits: 1, window: { minutes: 1 }, key: 'user-1' };
+
+ expect(await getRateLimit({ ...config, kvStore, clock })).toMatchObject({ hasExceededLimit: false });
+ expect(await getRateLimit({ ...config, kvStore, clock })).toMatchObject({ hasExceededLimit: true });
+
+ clock.advanceBy({ minutes: 1 });
+
+ expect(await getRateLimit({ ...config, kvStore, clock })).toMatchObject({ hasExceededLimit: false, hitCount: 1 });
+ });
+ });
+
+ describe('checkRateLimit', () => {
+ test('throws an error if the limit has been exceeded', async () => {
+ const { clock, kvStore } = setup();
+ const config = { maxHits: 1, window: { minutes: 1 }, key: 'user-1', kvStore, clock };
+
+ await checkRateLimit(config);
+ await expect(checkRateLimit(config)).rejects.toThrow(createTooManyRequestsError());
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/app/rate-limit/rate-limit.usecases.ts b/apps/papra-server/src/modules/app/rate-limit/rate-limit.usecases.ts
new file mode 100644
index 00000000..a6fd33df
--- /dev/null
+++ b/apps/papra-server/src/modules/app/rate-limit/rate-limit.usecases.ts
@@ -0,0 +1,70 @@
+import type { Clock } from '../../shared/clock/clock.types';
+import type { RateLimitKvStore } from './rate-limit.types';
+import { systemClock } from '../../shared/clock/clock';
+import { createTooManyRequestsError } from './rate-limit.errors';
+
+type RateLimitResult = {
+ hasExceededLimit: boolean;
+ hitCount: number;
+ hitsRemaining: number;
+ resetAt: Temporal.Instant;
+};
+
+export async function getRateLimit({
+ maxHits,
+ window,
+ key,
+ kvStore,
+ clock = systemClock,
+}: {
+ maxHits: number;
+ window: Temporal.DurationLike;
+ key: string;
+ kvStore: RateLimitKvStore;
+ clock?: Clock;
+}): Promise<RateLimitResult> {
+ const now = clock.now();
+
+ const entry = await kvStore.get(key);
+
+ if (!entry) {
+ const resetAt = now.add(window);
+ await kvStore.set(key, { hitCount: 1, resetAtEpochMs: resetAt.epochMilliseconds }, { expiresAt: resetAt });
+ return {
+ hasExceededLimit: false,
+ hitCount: 1,
+ hitsRemaining: maxHits - 1,
+ resetAt,
+ };
+ }
+
+ // The kv store filters out expired entries on read, so an existing entry is always within its window.
+ if (entry.hitCount >= maxHits) {
+ return {
+ hasExceededLimit: true,
+ hitCount: entry.hitCount,
+ hitsRemaining: 0,
+ resetAt: Temporal.Instant.fromEpochMilliseconds(entry.resetAtEpochMs),
+ };
+ }
+
+ // Keep the original reset instant so the window stays fixed instead of sliding forward on each hit.
+ const resetAt = Temporal.Instant.fromEpochMilliseconds(entry.resetAtEpochMs);
+ const hitCount = entry.hitCount + 1;
+ await kvStore.set(key, { hitCount, resetAtEpochMs: entry.resetAtEpochMs }, { expiresAt: resetAt });
+
+ return {
+ hasExceededLimit: false,
+ hitCount,
+ hitsRemaining: maxHits - hitCount,
+ resetAt,
+ };
+}
+
+export async function checkRateLimit(args: Parameters<typeof getRateLimit>[0]) {
+ const result = await getRateLimit(args);
+
+ if (result.hasExceededLimit) {
+ throw createTooManyRequestsError();
+ }
+}
diff --git a/apps/papra-server/src/modules/app/server.routes.test.ts b/apps/papra-server/src/modules/app/server.routes.test.ts
index 99c7b8e7..42e32391 100644
--- a/apps/papra-server/src/modules/app/server.routes.test.ts
+++ b/apps/papra-server/src/modules/app/server.routes.test.ts
@@ -1,6 +1,7 @@
import { inspectRoutes } from 'hono/dev';
import { describe, expect, test } from 'vitest';
import { overrideConfig } from '../config/config.test-utils';
+import { SHARE_LINK_TOKEN_LENGTH } from '../document-share-links/document-share-links.constants';
import { createInMemoryDatabase } from './database/database.test-utils';
import { createServer } from './server';
import { createTestServerDependencies } from './server.test-utils';
@@ -18,7 +19,9 @@ function setValidParams(path: string) {
.replaceAll(':memberId', 'org_mem_999999999999999999999999')
.replaceAll(':invitationId', 'inv_101010101010101010101010')
.replaceAll(':propertyDefinitionId', 'cpd_111111111111111111111111')
- .replaceAll(':optionId', 'cpso_222222222222222222222222');
+ .replaceAll(':optionId', 'cpso_222222222222222222222222')
+ .replaceAll(':shareLinkId', 'dsl_333333333333333333333333')
+ .replaceAll(':shareLinkToken', 't'.repeat(SHARE_LINK_TOKEN_LENGTH));
// throw if there are any remaining params
if (newPath.match(/:\w+/g)) {
@@ -43,6 +46,11 @@ describe('server routes', () => {
// Stripe stuff
'POST /api/stripe/webhook',
+
+ // Document share link access
+ 'GET /api/share-links/:shareLinkToken/document',
+ 'POST /api/share-links/:shareLinkToken/verify',
+ 'GET /api/share-links/:shareLinkToken/document/file',
];
// Excluding auth routes that are managed by better-auth
diff --git a/apps/papra-server/src/modules/app/server.routes.ts b/apps/papra-server/src/modules/app/server.routes.ts
index 66143a7c..e10f45ed 100644
--- a/apps/papra-server/src/modules/app/server.routes.ts
+++ b/apps/papra-server/src/modules/app/server.routes.ts
@@ -3,6 +3,7 @@ import { registerAdminRoutes } from '../admin/admin.routes';
import { registerApiKeysRoutes } from '../api-keys/api-keys.routes';
import { registerConfigRoutes } from '../config/config.routes';
import { registerCustomPropertiesRoutes } from '../custom-properties/custom-properties.routes';
+import { registerDocumentShareLinksRoutes } from '../document-share-links/document-share-links.routes';
import { registerDocumentActivityRoutes } from '../documents/document-activity/document-activity.routes';
import { registerDocumentsBatchRoutes } from '../documents/documents-batch/documents-batch.routes';
import { registerDocumentsRoutes } from '../documents/documents.routes';
@@ -34,5 +35,6 @@ export function registerRoutes(context: RouteDefinitionContext) {
registerInvitationsRoutes(context);
registerDocumentActivityRoutes(context);
registerCustomPropertiesRoutes(context);
+ registerDocumentShareLinksRoutes(context);
registerAdminRoutes(context);
}
diff --git a/apps/papra-server/src/modules/config/config.ts b/apps/papra-server/src/modules/config/config.ts
index 4caf78aa..86530d20 100644
--- a/apps/papra-server/src/modules/config/config.ts
+++ b/apps/papra-server/src/modules/config/config.ts
@@ -8,6 +8,7 @@ import { authConfig } from '../app/auth/auth.config';
import { ensureAuthSecretIsNotDefaultInProduction } from '../app/auth/auth.config.models';
import { databaseConfig } from '../app/database/database.config';
import { customPropertiesConfig } from '../custom-properties/custom-properties.config';
+import { documentShareLinksConfig } from '../document-share-links/document-share-links.config';
import { documentSearchConfig } from '../documents/document-search/document-search.config';
import { documentsConfig } from '../documents/documents.config';
import { documentStorageConfig } from '../documents/storage/document-storage.config';
@@ -158,6 +159,7 @@ export const configDefinition = {
subscriptions: subscriptionsConfig,
tags: tagsConfig,
customProperties: customPropertiesConfig,
+ documentShareLinks: documentShareLinksConfig,
tracking: trackingConfig,
webhooks: webhookConfig,
kvStore: kvStoreConfig,
diff --git a/apps/papra-server/src/modules/document-share-links/document-share-links.access-token.ts b/apps/papra-server/src/modules/document-share-links/document-share-links.access-token.ts
new file mode 100644
index 00000000..18af7c19
--- /dev/null
+++ b/apps/papra-server/src/modules/document-share-links/document-share-links.access-token.ts
@@ -0,0 +1,82 @@
+import type { Clock } from '../shared/clock/clock.types';
+import { sign, verify } from 'hono/jwt';
+import { JwtTokenInvalid, JwtTokenSignatureMismatched } from 'hono/utils/jwt/types';
+import { systemClock } from '../shared/clock/clock';
+import { deriveKeyWithHkdf } from '../shared/crypto/key-derivation';
+
+const ACCESS_TOKEN_HKDF_INFO = 'document-share-link-access-token';
+const ACCESS_TOKEN_ALGORITHM = 'HS256';
+
+// Derive a dedicated signing key from the auth secret so share-link tokens can't be reused for anything else.
+// The current password hash is folded into the derivation so that rotating (or removing) the share link
+// password changes the signing key, invalidating every previously issued token via a signature mismatch.
+function getSigningKey({ authSecret, passwordHash }: { authSecret: string; passwordHash: string }) {
+ return deriveKeyWithHkdf({ key: authSecret, info: `${ACCESS_TOKEN_HKDF_INFO}:${passwordHash}` });
+}
+
+export async function issueShareLinkAccessToken({
+ shareLinkId,
+ passwordHash,
+ authSecret,
+ ttlMinutes,
+ clock = systemClock,
+}: {
+ shareLinkId: string;
+ passwordHash: string;
+ authSecret: string;
+ ttlMinutes: number;
+ clock?: Clock;
+}): Promise<{ accessToken: string }> {
+ const nowSeconds = Math.floor(clock.now().epochMilliseconds / 1000);
+
+ const accessToken = await sign(
+ {
+ shareLinkId,
+ exp: nowSeconds + ttlMinutes * 60,
+ iat: nowSeconds,
+ },
+ getSigningKey({ authSecret, passwordHash }),
+ ACCESS_TOKEN_ALGORITHM,
+ );
+
+ return { accessToken };
+}
+
+// Returns whether the token is a valid, unexpired access token for the given share link.
+// Expiry is checked against the injected clock rather than hono's internal wall-clock check, so it stays deterministic in tests.
+export async function isShareLinkAccessTokenValid({
+ accessToken,
+ shareLinkId,
+ passwordHash,
+ authSecret,
+ clock = systemClock,
+}: {
+ accessToken: string | undefined;
+ shareLinkId: string;
+ passwordHash: string;
+ authSecret: string;
+ clock?: Clock;
+}): Promise<{ isValid: boolean }> {
+ if (accessToken === undefined || accessToken === '') {
+ return { isValid: false };
+ }
+
+ try {
+ const payload = await verify(accessToken, getSigningKey({ authSecret, passwordHash }), { alg: ACCESS_TOKEN_ALGORITHM, exp: false, iat: false, nbf: false });
+
+ if (payload.shareLinkId !== shareLinkId) {
+ return { isValid: false };
+ }
+
+ const nowSeconds = Math.floor(clock.now().epochMilliseconds / 1000);
+ const isExpired = typeof payload.exp === 'number' && payload.exp <= nowSeconds;
+
+ return { isValid: !isExpired };
+ } catch (error) {
+ if (error instanceof JwtTokenInvalid || error instanceof JwtTokenSignatureMismatched) {
+ return { isValid: false };
+ }
+
+ throw error;
+ }
+}
diff --git a/apps/papra-server/src/modules/document-share-links/document-share-links.config.ts b/apps/papra-server/src/modules/document-share-links/document-share-links.config.ts
new file mode 100644
index 00000000..ff459c10
--- /dev/null
+++ b/apps/papra-server/src/modules/document-share-links/document-share-links.config.ts
@@ -0,0 +1,45 @@
+import type { ConfigDefinition } from 'figue';
+import * as v from 'valibot';
+import { RATE_LIMIT_CONFIG_FORMAT_DOC } from '../app/rate-limit/rate-limit.config.constants';
+import { rateLimitConfigSchema } from '../app/rate-limit/rate-limit.config.schemas';
+import { urlSchema } from '../config/config.schemas';
+import { coercedStrictlyPositiveIntegerSchema } from '../shared/schemas/number.schemas';
+
+export const documentShareLinksConfig = {
+ shareLinkBaseUrl: {
+ doc: 'The base URL used to generate share links, if not specified it\'ll use the application `APP_BASE_URL` and the `CLIENT_BASE_URL` as fallback.',
+ schema: v.optional(urlSchema),
+ env: 'DOCUMENT_SHARE_LINKS_BASE_URL',
+ default: undefined,
+ },
+ maxLinksPerDocument: {
+ doc: 'The maximum number of share links a single document can have at the same time.',
+ schema: coercedStrictlyPositiveIntegerSchema,
+ default: 10,
+ env: 'DOCUMENT_SHARE_LINKS_MAX_LINKS_PER_DOCUMENT',
+ },
+ accessTokenTtlMinutes: {
+ doc: 'The lifetime, in minutes, of the access token issued after a successful share-link password verification.',
+ schema: coercedStrictlyPositiveIntegerSchema,
+ default: 15,
+ env: 'DOCUMENT_SHARE_LINKS_ACCESS_TOKEN_TTL_MINUTES',
+ },
+ passwordVerificationRateLimit: {
+ doc: `The rate limit applied to share link password verification attempts, to prevent brute-force attacks, globally scoped. ${RATE_LIMIT_CONFIG_FORMAT_DOC}`,
+ schema: rateLimitConfigSchema,
+ default: '30/1h',
+ env: 'DOCUMENT_SHARE_LINKS_PASSWORD_VERIFICATION_RATE_LIMIT',
+ },
+ documentAccessRateLimit: {
+ doc: `The rate limit applied to document access through share links, globally scoped. ${RATE_LIMIT_CONFIG_FORMAT_DOC}`,
+ schema: rateLimitConfigSchema,
+ default: '3600/1h',
+ env: 'DOCUMENT_SHARE_LINKS_DOCUMENT_ACCESS_RATE_LIMIT',
+ },
+ fileAccessRateLimit: {
+ doc: `The rate limit applied to file access through share links, globally scoped. ${RATE_LIMIT_CONFIG_FORMAT_DOC}`,
+ schema: rateLimitConfigSchema,
+ default: '600/1h',
+ env: 'DOCUMENT_SHARE_LINKS_FILE_ACCESS_RATE_LIMIT',
+ },
+} as const satisfies ConfigDefinition;
diff --git a/apps/papra-server/src/modules/document-share-links/document-share-links.constants.ts b/apps/papra-server/src/modules/document-share-links/document-share-links.constants.ts
new file mode 100644
index 00000000..9777bb4c
--- /dev/null
+++ b/apps/papra-server/src/modules/document-share-links/document-share-links.constants.ts
@@ -0,0 +1,9 @@
+import { createPrefixedIdRegex } from '../shared/random/ids';
+
+export const SHARE_LINK_ID_PREFIX = 'dsl';
+export const SHARE_LINK_ID_REGEX = createPrefixedIdRegex({ prefix: SHARE_LINK_ID_PREFIX });
+
+export const SHARE_LINK_TOKEN_LENGTH = 64;
+export const SHARE_LINK_TOKEN_REGEX = new RegExp(`^[a-z0-9]{${SHARE_LINK_TOKEN_LENGTH}}$`, 'i');
+
+export const SHARE_LINK_LAST_ACCESSED_TOUCH_DELAY_SECONDS = 60;
diff --git a/apps/papra-server/src/modules/document-share-links/document-share-links.errors.ts b/apps/papra-server/src/modules/document-share-links/document-share-links.errors.ts
new file mode 100644
index 00000000..5998ff47
--- /dev/null
+++ b/apps/papra-server/src/modules/document-share-links/document-share-links.errors.ts
@@ -0,0 +1,38 @@
+import { createErrorFactory } from '../shared/errors/errors';
+
+export const createShareLinkNotFoundError = createErrorFactory({
+ message: 'Share link not found.',
+ code: 'share_link.not_found',
+ statusCode: 404,
+});
+
+// 410 Gone: the link exists but is no longer usable (expired or disabled).
+export const createShareLinkGoneError = createErrorFactory({
+ message: 'Share link is no longer available.',
+ code: 'share_link.gone',
+ statusCode: 410,
+});
+
+export const createShareLinkPasswordRequiredError = createErrorFactory({
+ message: 'A valid access token is required to access this share link.',
+ code: 'share_link.password_required',
+ statusCode: 401,
+});
+
+export const createShareLinkInvalidPasswordError = createErrorFactory({
+ message: 'Invalid password.',
+ code: 'share_link.invalid_password',
+ statusCode: 401,
+});
+
+export const createShareLinkNotPasswordProtectedError = createErrorFactory({
+ message: 'This share link is not password protected.',
+ code: 'share_link.not_password_protected',
+ statusCode: 400,
+});
+
+export const createShareLinkLimitReachedError = createErrorFactory({
+ message: 'This document has reached the maximum number of share links.',
+ code: 'share_link.limit_reached',
+ statusCode: 409,
+});
diff --git a/apps/papra-server/src/modules/document-share-links/document-share-links.models.test.ts b/apps/papra-server/src/modules/document-share-links/document-share-links.models.test.ts
new file mode 100644
index 00000000..b0cde228
--- /dev/null
+++ b/apps/papra-server/src/modules/document-share-links/document-share-links.models.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, test } from 'vitest';
+import { createTestClock } from '../shared/clock/clock.test-utils';
+import { shouldTouchShareLinkLastAccessedAt } from './document-share-links.models';
+
+describe('document-share-links.models', () => {
+ describe('shouldTouchShareLinkLastAccessedAt', () => {
+ const { clock } = createTestClock({ now: '2026-05-12T12:00:00Z' });
+
+ test('update a link lastAccessedAt only if the last access was more than 1min ago', () => {
+ expect(shouldTouchShareLinkLastAccessedAt({ lastAccessedAt: Temporal.Instant.from('2026-05-12T11:58:00Z'), clock })).to.eql(true);
+ expect(shouldTouchShareLinkLastAccessedAt({ lastAccessedAt: Temporal.Instant.from('2026-05-12T11:59:00Z'), clock })).to.eql(false);
+ expect(shouldTouchShareLinkLastAccessedAt({ lastAccessedAt: Temporal.Instant.from('2026-05-12T11:59:01Z'), clock })).to.eql(false);
+
+ expect(shouldTouchShareLinkLastAccessedAt({ lastAccessedAt: null, clock })).to.eql(true);
+ expect(shouldTouchShareLinkLastAccessedAt({ lastAccessedAt: undefined, clock })).to.eql(true);
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/document-share-links/document-share-links.models.ts b/apps/papra-server/src/modules/document-share-links/document-share-links.models.ts
new file mode 100644
index 00000000..80636183
--- /dev/null
+++ b/apps/papra-server/src/modules/document-share-links/document-share-links.models.ts
@@ -0,0 +1,67 @@
+import type { Config } from '../config/config.types';
+import type { Clock } from '../shared/clock/clock.types';
+import type { DbSelectableShareLink } from './document-share-links.types';
+import { buildUrl } from '@corentinth/chisels';
+import { getClientBaseUrl } from '../config/config.models';
+import { omit } from '../shared/objects';
+import { generateId } from '../shared/random/ids';
+import { generateRandomString } from '../shared/random/random.services';
+import { isNil } from '../shared/utils';
+import { SHARE_LINK_ID_PREFIX, SHARE_LINK_LAST_ACCESSED_TOUCH_DELAY_SECONDS, SHARE_LINK_TOKEN_LENGTH } from './document-share-links.constants';
+
+export function generateShareLinkId() {
+ return generateId({ prefix: SHARE_LINK_ID_PREFIX });
+}
+
+export function generateShareToken() {
+ return { token: generateRandomString({ length: SHARE_LINK_TOKEN_LENGTH }) };
+}
+
+export function getShareLinkBaseUrl({ config }: { config: Config }) {
+ const { shareLinkBaseUrl } = config.documentShareLinks;
+
+ if (!isNil(shareLinkBaseUrl)) {
+ return { shareLinkBaseUrl };
+ }
+
+ const { clientBaseUrl } = getClientBaseUrl({ config });
+
+ return { shareLinkBaseUrl: clientBaseUrl };
+}
+
+export function buildShareLinkUrl({ token, config }: { token: string; config: Config }) {
+ const { shareLinkBaseUrl } = getShareLinkBaseUrl({ config });
+
+ return { url: buildUrl({ baseUrl: shareLinkBaseUrl, path: `/share/${token}` }) };
+}
+
+export function formatShareLinkForApi({ shareLink, config }: { shareLink: DbSelectableShareLink; config: Config }) {
+ const { url } = buildShareLinkUrl({ token: shareLink.token, config });
+
+ return {
+ ...omit(shareLink, ['passwordHash']),
+ isPasswordProtected: !isNil(shareLink.passwordHash),
+ url,
+ };
+}
+
+export function formatShareLinksForApi({ shareLinks, config }: { shareLinks: DbSelectableShareLink[]; config: Config }) {
+ return shareLinks.map(shareLink => formatShareLinkForApi({ shareLink, config }));
+}
+
+// Public-facing document details, exposing only what an anonymous visitor is allowed to see.
+export function formatPublicSharedDocument({ document }: { document: { name: string; originalSize: number; mimeType: string } }) {
+ return {
+ name: document.name,
+ size: document.originalSize,
+ mimeType: document.mimeType,
+ };
+}
+
+export function shouldTouchShareLinkLastAccessedAt({ lastAccessedAt, clock }: { lastAccessedAt: null | undefined | Temporal.Instant; clock: Clock }) {
+ if (isNil(lastAccessedAt)) {
+ return true;
+ }
+
+ return clock.now().since(lastAccessedAt).total('second') > SHARE_LINK_LAST_ACCESSED_TOUCH_DELAY_SECONDS;
+}
diff --git a/apps/papra-server/src/modules/document-share-links/document-share-links.password.test.ts b/apps/papra-server/src/modules/document-share-links/document-share-links.password.test.ts
new file mode 100644
index 00000000..730985b4
--- /dev/null
+++ b/apps/papra-server/src/modules/document-share-links/document-share-links.password.test.ts
@@ -0,0 +1,37 @@
+import { Buffer } from 'node:buffer';
+import { describe, expect, test } from 'vitest';
+import { hashPassword, verifyPassword } from './document-share-links.password';
+
+describe('document-share-links.password', () => {
+ describe('hash/verify password', () => {
+ test('an hashed password can be verified', async () => {
+ const password = 'my secret password';
+
+ const { passwordHash } = await hashPassword({ password });
+ const { isValid } = await verifyPassword({ password, passwordHash });
+
+ expect(isValid).toBe(true);
+ });
+
+ test('an incorrect password fails verification', async () => {
+ const { passwordHash } = await hashPassword({ password: 'my secret password' });
+ const { isValid } = await verifyPassword({ password: 'not the right password', passwordHash });
+
+ expect(isValid).toBe(false);
+ });
+
+ test('a malformed hash fails verification', async () => {
+ expect(await verifyPassword({ password: 'any password', passwordHash: 'this-is-not-a-valid-hash' })).to.eql({ isValid: false });
+ });
+
+ test('a tampered hash fails verification', async () => {
+ const { passwordHash } = await hashPassword({ password: 'my secret password' });
+
+ expect(await verifyPassword({ password: 'my secret password', passwordHash: passwordHash.replace(/^./, 'X') })).to.eql({ isValid: false });
+ });
+
+ test('regression test, ensure Buffer can base64 decode unpadded string, as the PHC spec requires', () => {
+ expect(Buffer.from('MQ==', 'base64')).toEqual(Buffer.from('MQ', 'base64'));
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/document-share-links/document-share-links.password.ts b/apps/papra-server/src/modules/document-share-links/document-share-links.password.ts
new file mode 100644
index 00000000..54736c65
--- /dev/null
+++ b/apps/papra-server/src/modules/document-share-links/document-share-links.password.ts
@@ -0,0 +1,71 @@
+import type { ScryptOptions } from 'node:crypto';
+import { Buffer } from 'node:buffer';
+import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto';
+
+async function scryptAsync({ password, salt, keyLength, options = {}}: { password: string; salt: Buffer; keyLength: number; options?: ScryptOptions }): Promise<Buffer> {
+ return new Promise((resolve, reject) => {
+ scrypt(password, salt, keyLength, options, (err, derivedKey) => {
+ if (err) {
+ reject(err);
+ } else {
+ resolve(derivedKey);
+ }
+ });
+ });
+}
+
+const SCRYPT_PREFIX = 'scrypt';
+const SALT_LENGTH_BYTES = 16;
+const KEY_LENGTH_BYTES = 64;
+const SCRYPT_PARAMS = {
+ logN: 14, // Cost. For link password hashing, 2^14 cost is enough
+ r: 8, // Block size
+ p: 1, // Parallelization
+};
+
+export async function hashPassword({ password }: { password: string }): Promise<{ passwordHash: string }> {
+ const salt = randomBytes(SALT_LENGTH_BYTES);
+ const options = {
+ n: 2 ** SCRYPT_PARAMS.logN,
+ r: SCRYPT_PARAMS.r,
+ p: SCRYPT_PARAMS.p,
+ };
+
+ const derivedKey = await scryptAsync({ password, salt, options, keyLength: KEY_LENGTH_BYTES });
+ const saltBase64 = salt.toString('base64').replace(/=+$/, ''); // Remove padding to comply with the PHC format (Buffer.from can handle unpadded base64)
+ const hashBase64 = derivedKey.toString('base64').replace(/=+$/, '');
+
+ return {
+ passwordHash: `$${SCRYPT_PREFIX}$ln=${SCRYPT_PARAMS.logN},r=${SCRYPT_PARAMS.r},p=${SCRYPT_PARAMS.p}$${saltBase64}$${hashBase64}`,
+ };
+}
+
+export async function verifyPassword({ password, passwordHash }: { password: string; passwordHash: string }): Promise<{ isValid: boolean }> {
+ const [prefix, paramsPart, saltBase64 = '', hashBase64 = ''] = passwordHash.split('$').slice(1);
+
+ if (prefix !== SCRYPT_PREFIX) {
+ return { isValid: false };
+ }
+
+ const paramsMatch = paramsPart?.match(/ln=(\d+),r=(\d+),p=(\d+)/);
+ if (!paramsMatch) {
+ return { isValid: false };
+ }
+
+ const logN = Number.parseInt(paramsMatch[1] ?? '', 10);
+ const r = Number.parseInt(paramsMatch[2] ?? '', 10);
+ const p = Number.parseInt(paramsMatch[3] ?? '', 10);
+
+ if (Number.isNaN(logN) || Number.isNaN(r) || Number.isNaN(p)) {
+ return { isValid: false };
+ }
+
+ const options = { n: 2 ** logN, r, p };
+
+ const salt = Buffer.from(saltBase64, 'base64');
+ const expectedHash = Buffer.from(hashBase64, 'base64');
+
+ const derivedKey = await scryptAsync({ password, salt, options, keyLength: expectedHash.length });
+
+ return { isValid: derivedKey.length === expectedHash.length && timingSafeEqual(derivedKey, expectedHash) };
+}
diff --git a/apps/papra-server/src/modules/document-share-links/document-share-links.repository.ts b/apps/papra-server/src/modules/document-share-links/document-share-links.repository.ts
new file mode 100644
index 00000000..eb4aa88d
--- /dev/null
+++ b/apps/papra-server/src/modules/document-share-links/document-share-links.repository.ts
@@ -0,0 +1,166 @@
+import type { Database } from '../app/database/database.types';
+import type { DbInsertableShareLink } from './document-share-links.types';
+import { injectArguments } from '@corentinth/chisels';
+import { and, count, desc, eq, getTableColumns } from 'drizzle-orm';
+import { documentsTable } from '../documents/documents.table';
+import { createError } from '../shared/errors/errors';
+import { omitUndefined } from '../shared/objects';
+import { isNil } from '../shared/utils';
+import { createShareLinkNotFoundError } from './document-share-links.errors';
+import { documentShareLinksTable } from './document-share-links.table';
+
+export type ShareLinksRepository = ReturnType<typeof createShareLinksRepository>;
+
+export function createShareLinksRepository({ db }: { db: Database }) {
+ return injectArguments(
+ {
+ createShareLink,
+ getShareLinkByToken,
+ getShareLinkById,
+ getDocumentShareLinks,
+ getOrganizationShareLinks,
+ countDocumentShareLinks,
+ updateShareLink,
+ deleteShareLink,
+ touchLastAccessedAt,
+ },
+ { db },
+ );
+}
+
+async function createShareLink({ db, ...shareLinkToInsert }: { db: Database } & DbInsertableShareLink) {
+ const [shareLink] = await db.insert(documentShareLinksTable).values(shareLinkToInsert).returning();
+
+ if (isNil(shareLink)) {
+ // shouldn't happen because of the returning, but for type safety
+
+ throw createError({
+ message: 'Error while creating share link',
+ code: 'share_link.save_error',
+ statusCode: 500,
+ isInternal: true,
+ });
+ }
+
+ return { shareLink };
+}
+
+async function getShareLinkByToken({ token, db }: { token: string; db: Database }) {
+ const [shareLink] = await db
+ .select()
+ .from(documentShareLinksTable)
+ .where(eq(documentShareLinksTable.token, token));
+
+ return { shareLink };
+}
+
+async function getShareLinkById({ shareLinkId, organizationId, db }: { shareLinkId: string; organizationId: string; db: Database }) {
+ const [shareLink] = await db
+ .select()
+ .from(documentShareLinksTable)
+ .where(
+ and(
+ eq(documentShareLinksTable.id, shareLinkId),
+ eq(documentShareLinksTable.organizationId, organizationId),
+ ),
+ );
+
+ return { shareLink };
+}
+
+async function getDocumentShareLinks({ documentId, organizationId, db }: { documentId: string; organizationId: string; db: Database }) {
+ const shareLinks = await db
+ .select()
+ .from(documentShareLinksTable)
+ .where(
+ and(
+ eq(documentShareLinksTable.documentId, documentId),
+ eq(documentShareLinksTable.organizationId, organizationId),
+ ),
+ )
+ .orderBy(desc(documentShareLinksTable.createdAt));
+
+ return { shareLinks };
+}
+
+async function getOrganizationShareLinks({ organizationId, db }: { organizationId: string; db: Database }) {
+ // Joins the document name (and trashed state) so the management UI can display it without a second round-trip.
+ const shareLinks = await db
+ .select({ ...getTableColumns(documentShareLinksTable), documentName: documentsTable.name, isDocumentDeleted: documentsTable.isDeleted })
+ .from(documentShareLinksTable)
+ .innerJoin(documentsTable, eq(documentShareLinksTable.documentId, documentsTable.id))
+ .where(eq(documentShareLinksTable.organizationId, organizationId))
+ .orderBy(desc(documentShareLinksTable.createdAt));
+
+ return { shareLinks };
+}
+
+async function countDocumentShareLinks({ documentId, organizationId, db }: { documentId: string; organizationId: string; db: Database }) {
+ const [record] = await db
+ .select({ shareLinksCount: count(documentShareLinksTable.id) })
+ .from(documentShareLinksTable)
+ .where(
+ and(
+ eq(documentShareLinksTable.documentId, documentId),
+ eq(documentShareLinksTable.organizationId, organizationId),
+ ),
+ );
+
+ return { shareLinksCount: record?.shareLinksCount ?? 0 };
+}
+
+async function updateShareLink({
+ shareLinkId,
+ organizationId,
+ expiresAt,
+ passwordHash,
+ isEnabled,
+ db,
+}: {
+ shareLinkId: string;
+ organizationId: string;
+ expiresAt?: Date | null;
+ passwordHash?: string | null;
+ isEnabled?: boolean;
+ db: Database;
+}) {
+ const [shareLink] = await db
+ .update(documentShareLinksTable)
+ .set({ ...omitUndefined({ expiresAt, passwordHash, isEnabled }), updatedAt: new Date() })
+ .where(
+ and(
+ eq(documentShareLinksTable.id, shareLinkId),
+ eq(documentShareLinksTable.organizationId, organizationId),
+ ),
+ )
+ .returning();
+
+ if (isNil(shareLink)) {
+ throw createShareLinkNotFoundError();
+ }
+
+ return { shareLink };
+}
+
+async function deleteShareLink({ shareLinkId, organizationId, db }: { shareLinkId: string; organizationId: string; db: Database }) {
+ const deleted = await db
+ .delete(documentShareLinksTable)
+ .where(
+ and(
+ eq(documentShareLinksTable.id, shareLinkId),
+ eq(documentShareLinksTable.organizationId, organizationId),
+ ),
+ )
+ .returning({ id: documentShareLinksTable.id });
+
+ if (deleted.length === 0) {
+ throw createShareLinkNotFoundError();
+ }
+}
+
+async function touchLastAccessedAt({ shareLinkId, lastAccessedAt, db }: { shareLinkId: string; lastAccessedAt: Date; db: Database }) {
+ await db
+ .update(documentShareLinksTable)
+ .set({ lastAccessedAt })
+ .where(eq(documentShareLinksTable.id, shareLinkId));
+}
diff --git a/apps/papra-server/src/modules/document-share-links/document-share-links.routes.ts b/apps/papra-server/src/modules/document-share-links/document-share-links.routes.ts
new file mode 100644
index 00000000..f9994a71
--- /dev/null
+++ b/apps/papra-server/src/modules/document-share-links/document-share-links.routes.ts
@@ -0,0 +1,268 @@
+import type { Context, RouteDefinitionContext } from '../app/server.types';
+import { Readable } from 'node:stream';
+import * as v from 'valibot';
+import { requireAuthentication } from '../app/auth/auth.middleware';
+import { getUser } from '../app/auth/auth.models';
+import { scopeKvStoreForRateLimit } from '../app/rate-limit/rate-limit.kv-store';
+import { checkRateLimit } from '../app/rate-limit/rate-limit.usecases';
+import { createDocumentsRepository } from '../documents/documents.repository';
+import { documentIdSchema } from '../documents/documents.schemas';
+import { getDocumentOrThrow } from '../documents/documents.usecases';
+import { joinKeyParts } from '../kv-store/kv-store.models';
+import { organizationIdSchema } from '../organizations/organization.schemas';
+import { createOrganizationsRepository } from '../organizations/organizations.repository';
+import { ensureUserIsInOrganization } from '../organizations/organizations.usecases';
+import { validateJsonBody, validateParams } from '../shared/validation/validation';
+import { formatPublicSharedDocument, formatShareLinkForApi, formatShareLinksForApi } from './document-share-links.models';
+import { createShareLinksRepository } from './document-share-links.repository';
+import { createShareLinkBodySchema, shareLinkIdSchema, shareLinkTokenSchema, updateShareLinkBodySchema, verifySharePasswordBodySchema } from './document-share-links.schemas';
+import {
+ createShareLink,
+ ensureShareLinkAccessGranted,
+ getSharedDocument,
+ getShareLinkDocumentOrThrow,
+ resolveUsableShareLinkByToken,
+ touchShareLinkLastAccessedAt,
+ updateShareLink,
+ verifySharePassword,
+} from './document-share-links.usecases';
+
+export function registerDocumentShareLinksRoutes(context: RouteDefinitionContext) {
+ // Organization-scoped management endpoints (authenticated)
+ setupCreateShareLinkRoute(context);
+ setupGetDocumentShareLinksRoute(context);
+ setupGetOrganizationShareLinksRoute(context);
+ setupUpdateShareLinkRoute(context);
+ setupDeleteShareLinkRoute(context);
+
+ // Public endpoints (no authentication)
+ setupGetSharedDocumentRoute(context);
+ setupVerifySharePasswordRoute(context);
+ setupGetSharedDocumentFileRoute(context);
+}
+
+function getAccessToken({ context }: { context: Context }) {
+ const authorization = context.req.header('Authorization');
+
+ if (authorization !== undefined && authorization.startsWith('Bearer ')) {
+ return { accessToken: authorization.slice('Bearer '.length) };
+ }
+
+ return { accessToken: undefined };
+}
+
+function setupCreateShareLinkRoute({ app, db, config }: RouteDefinitionContext) {
+ app.post(
+ '/api/organizations/:organizationId/documents/:documentId/share-links',
+ requireAuthentication({ apiKeyPermissions: ['documents:update'] }),
+ validateParams(v.strictObject({ organizationId: organizationIdSchema, documentId: documentIdSchema })),
+ validateJsonBody(createShareLinkBodySchema),
+ async (context) => {
+ const { userId } = getUser({ context });
+ const { organizationId, documentId } = context.req.valid('param');
+ const { expiresAt, password } = context.req.valid('json');
+
+ const organizationsRepository = createOrganizationsRepository({ db });
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ const shareLinksRepository = createShareLinksRepository({ db });
+ const documentsRepository = createDocumentsRepository({ db });
+
+ const { shareLink } = await createShareLink({
+ organizationId,
+ documentId,
+ expiresAt,
+ password,
+ userId,
+ shareLinksRepository,
+ documentsRepository,
+ config,
+ });
+
+ return context.json({ shareLink: formatShareLinkForApi({ shareLink, config }) }, 201);
+ },
+ );
+}
+
+function setupGetDocumentShareLinksRoute({ app, db, config }: RouteDefinitionContext) {
+ app.get(
+ '/api/organizations/:organizationId/documents/:documentId/share-links',
+ requireAuthentication({ apiKeyPermissions: ['documents:read'] }),
+ validateParams(v.strictObject({ organizationId: organizationIdSchema, documentId: documentIdSchema })),
+ async (context) => {
+ const { userId } = getUser({ context });
+ const { organizationId, documentId } = context.req.valid('param');
+
+ const organizationsRepository = createOrganizationsRepository({ db });
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ const documentsRepository = createDocumentsRepository({ db });
+ await getDocumentOrThrow({ documentId, organizationId, documentsRepository });
+
+ const shareLinksRepository = createShareLinksRepository({ db });
+ const { shareLinks } = await shareLinksRepository.getDocumentShareLinks({ documentId, organizationId });
+
+ return context.json({ shareLinks: formatShareLinksForApi({ shareLinks, config }) });
+ },
+ );
+}
+
+function setupGetOrganizationShareLinksRoute({ app, db, config }: RouteDefinitionContext) {
+ app.get(
+ '/api/organizations/:organizationId/share-links',
+ requireAuthentication({ apiKeyPermissions: ['documents:read'] }),
+ validateParams(v.strictObject({ organizationId: organizationIdSchema })),
+ async (context) => {
+ const { userId } = getUser({ context });
+ const { organizationId } = context.req.valid('param');
+
+ const organizationsRepository = createOrganizationsRepository({ db });
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ const shareLinksRepository = createShareLinksRepository({ db });
+ const { shareLinks } = await shareLinksRepository.getOrganizationShareLinks({ organizationId });
+
+ return context.json({ shareLinks: formatShareLinksForApi({ shareLinks, config }) });
+ },
+ );
+}
+
+function setupUpdateShareLinkRoute({ app, db, config }: RouteDefinitionContext) {
+ app.patch(
+ '/api/organizations/:organizationId/share-links/:shareLinkId',
+ requireAuthentication({ apiKeyPermissions: ['documents:update'] }),
+ validateParams(v.strictObject({ organizationId: organizationIdSchema, shareLinkId: shareLinkIdSchema })),
+ validateJsonBody(updateShareLinkBodySchema),
+ async (context) => {
+ const { userId } = getUser({ context });
+ const { organizationId, shareLinkId } = context.req.valid('param');
+ const { expiresAt, password, isEnabled } = context.req.valid('json');
+
+ const organizationsRepository = createOrganizationsRepository({ db });
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ const shareLinksRepository = createShareLinksRepository({ db });
+ const { shareLink } = await updateShareLink({ shareLinkId, organizationId, expiresAt, password, isEnabled, shareLinksRepository });
+
+ return context.json({ shareLink: formatShareLinkForApi({ shareLink, config }) });
+ },
+ );
+}
+
+function setupDeleteShareLinkRoute({ app, db }: RouteDefinitionContext) {
+ app.delete(
+ '/api/organizations/:organizationId/share-links/:shareLinkId',
+ requireAuthentication({ apiKeyPermissions: ['documents:update'] }),
+ validateParams(v.strictObject({ organizationId: organizationIdSchema, shareLinkId: shareLinkIdSchema })),
+ async (context) => {
+ const { userId } = getUser({ context });
+ const { organizationId, shareLinkId } = context.req.valid('param');
+
+ const organizationsRepository = createOrganizationsRepository({ db });
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ const shareLinksRepository = createShareLinksRepository({ db });
+ await shareLinksRepository.deleteShareLink({ shareLinkId, organizationId });
+
+ return context.body(null, 204);
+ },
+ );
+}
+
+function setupGetSharedDocumentRoute({ app, db, config, kvStore }: RouteDefinitionContext) {
+ app.get(
+ '/api/share-links/:shareLinkToken/document',
+ validateParams(v.strictObject({ shareLinkToken: shareLinkTokenSchema })),
+ async (context) => {
+ const { shareLinkToken } = context.req.valid('param');
+ const { accessToken } = getAccessToken({ context });
+
+ await checkRateLimit({
+ ...config.documentShareLinks.documentAccessRateLimit,
+ key: joinKeyParts(['public-share-link-document-access', shareLinkToken]),
+ kvStore: scopeKvStoreForRateLimit({ kvStore }),
+ });
+
+ const shareLinksRepository = createShareLinksRepository({ db });
+ const documentsRepository = createDocumentsRepository({ db });
+
+ const { document } = await getSharedDocument({ shareLinkToken, accessToken, shareLinksRepository, documentsRepository, config });
+
+ return context.json({ document: formatPublicSharedDocument({ document }) });
+ },
+ );
+}
+
+function setupVerifySharePasswordRoute({ app, db, config, kvStore }: RouteDefinitionContext) {
+ app.post(
+ '/api/share-links/:shareLinkToken/verify',
+ validateParams(v.strictObject({ shareLinkToken: shareLinkTokenSchema })),
+ validateJsonBody(verifySharePasswordBodySchema),
+ async (context) => {
+ const { shareLinkToken } = context.req.valid('param');
+ const { password } = context.req.valid('json');
+
+ // Strong rate limit per token to prevent distributed brute-force
+ await checkRateLimit({
+ ...config.documentShareLinks.passwordVerificationRateLimit,
+ key: joinKeyParts(['public-share-link-password-verification', shareLinkToken]),
+ kvStore: scopeKvStoreForRateLimit({ kvStore }),
+ });
+
+ const shareLinksRepository = createShareLinksRepository({ db });
+ const { accessToken } = await verifySharePassword({ shareLinkToken, password, shareLinksRepository, config });
+
+ return context.json({ accessToken });
+ },
+ );
+}
+
+function setupGetSharedDocumentFileRoute({ app, db, config, documentsStorageService, kvStore }: RouteDefinitionContext) {
+ app.get(
+ '/api/share-links/:shareLinkToken/document/file',
+ validateParams(v.strictObject({ shareLinkToken: shareLinkTokenSchema })),
+ async (context) => {
+ const { shareLinkToken } = context.req.valid('param');
+ const { accessToken } = getAccessToken({ context });
+
+ // Prevent abuse of the share system as a file host.
+ await checkRateLimit({
+ ...config.documentShareLinks.fileAccessRateLimit,
+ key: joinKeyParts(['public-share-link-file-access', shareLinkToken]),
+ kvStore: scopeKvStoreForRateLimit({ kvStore }),
+ });
+
+ const shareLinksRepository = createShareLinksRepository({ db });
+ const { shareLink } = await resolveUsableShareLinkByToken({ shareLinkToken, shareLinksRepository });
+
+ await ensureShareLinkAccessGranted({ shareLink, accessToken, config });
+
+ const documentsRepository = createDocumentsRepository({ db });
+ const { document } = await getShareLinkDocumentOrThrow({ shareLink, documentsRepository });
+
+ const { fileStream } = await documentsStorageService.getFileStream({
+ storageKey: document.originalStorageKey,
+ fileEncryptionAlgorithm: document.fileEncryptionAlgorithm,
+ fileEncryptionKekVersion: document.fileEncryptionKekVersion,
+ fileEncryptionKeyWrapped: document.fileEncryptionKeyWrapped,
+ });
+
+ await touchShareLinkLastAccessedAt({ shareLink, shareLinksRepository });
+
+ return context.body(
+ Readable.toWeb(fileStream),
+ 200,
+ {
+ // Serve as an opaque attachment to prevent the browser from rendering potentially dangerous files.
+ 'Content-Type': 'application/octet-stream',
+ 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(document.name)}`,
+ 'Content-Length': String(document.originalSize),
+ 'X-Content-Type-Options': 'nosniff',
+ 'X-Frame-Options': 'DENY',
+ 'X-Robots-Tag': 'noindex, nofollow',
+ 'Referrer-Policy': 'no-referrer',
+ },
+ );
+ },
+ );
+}
diff --git a/apps/papra-server/src/modules/document-share-links/document-share-links.schemas.ts b/apps/papra-server/src/modules/document-share-links/document-share-links.schemas.ts
new file mode 100644
index 00000000..256ee4c4
--- /dev/null
+++ b/apps/papra-server/src/modules/document-share-links/document-share-links.schemas.ts
@@ -0,0 +1,29 @@
+import * as v from 'valibot';
+import { createRegexSchema } from '../shared/schemas/string.schemas';
+import { SHARE_LINK_ID_REGEX, SHARE_LINK_TOKEN_REGEX } from './document-share-links.constants';
+
+export const shareLinkIdSchema = createRegexSchema(SHARE_LINK_ID_REGEX);
+export const shareLinkTokenSchema = createRegexSchema(SHARE_LINK_TOKEN_REGEX);
+
+const shareLinkPasswordSchema = v.pipe(v.string(), v.minLength(1), v.maxLength(256));
+
+export const createShareLinkBodySchema = v.strictObject({
+ expiresAt: v.optional(v.nullable(v.pipe(v.string(), v.isoTimestamp(), v.toDate()))),
+ password: v.optional(shareLinkPasswordSchema),
+});
+
+export const updateShareLinkBodySchema = v.pipe(
+ v.strictObject({
+ expiresAt: v.optional(v.nullable(v.pipe(v.string(), v.isoTimestamp(), v.toDate()))),
+ password: v.optional(v.nullable(shareLinkPasswordSchema)),
+ isEnabled: v.optional(v.boolean()),
+ }),
+ v.check(
+ data => data.expiresAt !== undefined || data.password !== undefined || data.isEnabled !== undefined,
+ 'At least one of \'expiresAt\', \'password\', or \'isEnabled\' must be provided',
+ ),
+);
+
+export const verifySharePasswordBodySchema = v.strictObject({
+ password: shareLinkPasswordSchema,
+});
diff --git a/apps/papra-server/src/modules/document-share-links/document-share-links.table.ts b/apps/papra-server/src/modules/document-share-links/document-share-links.table.ts
new file mode 100644
index 00000000..28effa5b
--- /dev/null
+++ b/apps/papra-server/src/modules/document-share-links/document-share-links.table.ts
@@ -0,0 +1,26 @@
+import { index, integer, sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core';
+import { documentsTable } from '../documents/documents.table';
+import { organizationsTable } from '../organizations/organizations.table';
+import { createPrimaryKeyField, createTimestampColumns } from '../shared/db/columns.helpers';
+import { usersTable } from '../users/users.table';
+import { generateShareLinkId } from './document-share-links.models';
+
+export const documentShareLinksTable = sqliteTable('document_share_links', {
+ ...createPrimaryKeyField({ idGenerator: generateShareLinkId }),
+ ...createTimestampColumns(),
+
+ organizationId: text('organization_id').notNull().references(() => organizationsTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),
+ documentId: text('document_id').notNull().references(() => documentsTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),
+ createdBy: text('created_by').references(() => usersTable.id, { onDelete: 'set null', onUpdate: 'cascade' }),
+
+ token: text('token').notNull(),
+ expiresAt: integer('expires_at', { mode: 'timestamp_ms' }),
+ passwordHash: text('password_hash'),
+ isEnabled: integer('is_enabled', { mode: 'boolean' }).notNull().default(true),
+ lastAccessedAt: integer('last_accessed_at', { mode: 'timestamp_ms' }),
+}, table => [
+ // Public lookup by token must be fast and tokens must be globally unique
+ uniqueIndex('document_share_links_token_unique').on(table.token),
+ // To list/manage share links for a given document within an organization
+ index('document_share_links_organization_id_document_id_index').on(table.organizationId, table.documentId),
+]);
diff --git a/apps/papra-server/src/modules/document-share-links/document-share-links.types.ts b/apps/papra-server/src/modules/document-share-links/document-share-links.types.ts
new file mode 100644
index 00000000..b9bddf2e
--- /dev/null
+++ b/apps/papra-server/src/modules/document-share-links/document-share-links.types.ts
@@ -0,0 +1,7 @@
+import type { Expand } from '@corentinth/chisels';
+import type { documentShareLinksTable } from './document-share-links.table';
+
+export type DbInsertableShareLink = Expand<typeof documentShareLinksTable.$inferInsert>;
+export type DbSelectableShareLink = Expand<typeof documentShareLinksTable.$inferSelect>;
+
+export type ShareLink = DbSelectableShareLink;
diff --git a/apps/papra-server/src/modules/document-share-links/document-share-links.usecases.test.ts b/apps/papra-server/src/modules/document-share-links/document-share-links.usecases.test.ts
new file mode 100644
index 00000000..986c8015
--- /dev/null
+++ b/apps/papra-server/src/modules/document-share-links/document-share-links.usecases.test.ts
@@ -0,0 +1,225 @@
+import { describe, expect, test } from 'vitest';
+import { createInMemoryDatabase } from '../app/database/database.test-utils';
+import { overrideConfig } from '../config/config.test-utils';
+import { createDocumentsRepository } from '../documents/documents.repository';
+import { createTestClock } from '../shared/clock/clock.test-utils';
+import { issueShareLinkAccessToken } from './document-share-links.access-token';
+import { createShareLinksRepository } from './document-share-links.repository';
+import { documentShareLinksTable } from './document-share-links.table';
+import {
+ createShareLink,
+ ensureShareLinkAccessGranted,
+ getSharedDocument,
+ resolveUsableShareLinkByToken,
+ updateShareLink,
+ verifySharePassword,
+} from './document-share-links.usecases';
+
+const config = overrideConfig({ auth: { secret: 'test-secret-that-is-at-least-32-chars-long' } });
+
+async function setup({ now = '2026-05-12T00:00:00Z' }: { now?: string } = {}) {
+ const { clock } = createTestClock({ now });
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'user_1', email: '[email protected]' }],
+ organizations: [{ id: 'org_1', name: 'Org 1' }],
+ documents: [{
+ id: 'doc_1',
+ organizationId: 'org_1',
+ name: 'invoice.pdf',
+ originalName: 'invoice.pdf',
+ originalSize: 1024,
+ originalStorageKey: 'org_1/originals/doc_1.pdf',
+ originalSha256Hash: 'hash_1',
+ mimeType: 'application/pdf',
+ }],
+ });
+
+ const shareLinksRepository = createShareLinksRepository({ db });
+ const documentsRepository = createDocumentsRepository({ db });
+
+ return { clock, db, shareLinksRepository, documentsRepository };
+}
+
+describe('document-share-links usecases', () => {
+ describe('createShareLink', () => {
+ test('stores the provided expiration date and a 64-char token', async () => {
+ const { shareLinksRepository, documentsRepository } = await setup({ now: '2026-05-12T00:00:00Z' });
+
+ const { shareLink } = await createShareLink({
+ organizationId: 'org_1',
+ documentId: 'doc_1',
+ expiresAt: new Date('2026-05-19T00:00:00Z'),
+ userId: 'user_1',
+ shareLinksRepository,
+ documentsRepository,
+ config,
+ });
+
+ expect(shareLink.expiresAt).to.eql(new Date('2026-05-19T00:00:00Z'));
+ expect(shareLink.passwordHash).to.eql(null);
+ expect(shareLink.token).to.have.length(64);
+ });
+
+ test('an omitted/null expiration creates a link that never expires', async () => {
+ const { shareLinksRepository, documentsRepository } = await setup();
+
+ const { shareLink } = await createShareLink({
+ organizationId: 'org_1',
+ documentId: 'doc_1',
+ expiresAt: null,
+ userId: 'user_1',
+ shareLinksRepository,
+ documentsRepository,
+ config,
+ });
+
+ expect(shareLink.expiresAt).to.eql(null);
+ });
+
+ test('the password is hashed and never stored in plain text', async () => {
+ const { shareLinksRepository, documentsRepository } = await setup();
+
+ const { shareLink } = await createShareLink({
+ organizationId: 'org_1',
+ documentId: 'doc_1',
+ password: 'hunter2',
+ userId: 'user_1',
+ shareLinksRepository,
+ documentsRepository,
+ config,
+ });
+
+ expect(shareLink.passwordHash).to.be.a('string');
+ expect(shareLink.passwordHash).not.to.include('hunter2');
+ expect(shareLink.passwordHash!.startsWith('$scrypt$')).to.eql(true);
+ });
+
+ test('throws when the document does not exist in the organization', async () => {
+ const { shareLinksRepository, documentsRepository } = await setup();
+
+ await expect(
+ createShareLink({ organizationId: 'org_1', documentId: 'doc_unknown', userId: 'user_1', shareLinksRepository, documentsRepository, config }),
+ ).rejects.toThrowError('Document not found.');
+ });
+
+ test('enforces the maximum number of share links per document', async () => {
+ const limitedConfig = overrideConfig({ auth: { secret: config.auth.secret }, documentShareLinks: { maxLinksPerDocument: 2 } });
+ const { shareLinksRepository, documentsRepository } = await setup();
+
+ const create = async () => createShareLink({ organizationId: 'org_1', documentId: 'doc_1', userId: 'user_1', shareLinksRepository, documentsRepository, config: limitedConfig });
+
+ await create();
+ await create();
+
+ await expect(create()).rejects.toThrowError('maximum number of share links');
+ });
+ });
+
+ describe('resolveUsableShareLinkByToken', () => {
+ test('throws 404 when the token is unknown', async () => {
+ const { clock, shareLinksRepository } = await setup();
+
+ await expect(resolveUsableShareLinkByToken({ shareLinkToken: 'unknown', shareLinksRepository, clock })).rejects.toThrowError('Share link not found.');
+ });
+
+ test('throws 410 when the link is disabled', async () => {
+ const { clock, db, shareLinksRepository } = await setup();
+ await db.insert(documentShareLinksTable).values({ id: 'dsl_1', organizationId: 'org_1', documentId: 'doc_1', token: 't'.repeat(64), isEnabled: false });
+
+ await expect(resolveUsableShareLinkByToken({ shareLinkToken: 't'.repeat(64), shareLinksRepository, clock })).rejects.toThrowError('no longer available');
+ });
+
+ test('throws 410 when the link is expired', async () => {
+ const { clock, db, shareLinksRepository } = await setup({ now: '2026-05-20T00:00:00Z' });
+ await db.insert(documentShareLinksTable).values({ id: 'dsl_1', organizationId: 'org_1', documentId: 'doc_1', token: 't'.repeat(64), expiresAt: new Date('2026-05-19T00:00:00Z') });
+
+ await expect(resolveUsableShareLinkByToken({ shareLinkToken: 't'.repeat(64), shareLinksRepository, clock })).rejects.toThrowError('no longer available');
+ });
+ });
+
+ describe('verifySharePassword + ensureShareLinkAccessGranted', () => {
+ test('a correct password yields an access token that grants access to the document', async () => {
+ const { clock, shareLinksRepository, documentsRepository } = await setup();
+
+ const { shareLink } = await createShareLink({ organizationId: 'org_1', documentId: 'doc_1', password: 'hunter2', userId: 'user_1', shareLinksRepository, documentsRepository, config });
+
+ const { accessToken } = await verifySharePassword({ shareLinkToken: shareLink.token, password: 'hunter2', shareLinksRepository, config, clock });
+
+ // Granting access with the freshly issued token resolves without throwing.
+ await ensureShareLinkAccessGranted({ shareLink, accessToken, config, clock });
+ });
+
+ test('an incorrect password is rejected', async () => {
+ const { clock, shareLinksRepository, documentsRepository } = await setup();
+ const { shareLink } = await createShareLink({ organizationId: 'org_1', documentId: 'doc_1', password: 'hunter2', userId: 'user_1', shareLinksRepository, documentsRepository, config });
+
+ await expect(verifySharePassword({ shareLinkToken: shareLink.token, password: 'wrong', shareLinksRepository, config, clock })).rejects.toThrowError('Invalid password.');
+ });
+
+ test('verifying a password on a non-protected link throws', async () => {
+ const { clock, shareLinksRepository, documentsRepository } = await setup();
+ const { shareLink } = await createShareLink({ organizationId: 'org_1', documentId: 'doc_1', userId: 'user_1', shareLinksRepository, documentsRepository, config });
+
+ await expect(verifySharePassword({ shareLinkToken: shareLink.token, password: 'whatever', shareLinksRepository, config, clock })).rejects.toThrowError('not password protected');
+ });
+
+ test('access is denied without a token on a protected link', async () => {
+ const { clock, shareLinksRepository, documentsRepository } = await setup();
+ const { shareLink } = await createShareLink({ organizationId: 'org_1', documentId: 'doc_1', password: 'hunter2', userId: 'user_1', shareLinksRepository, documentsRepository, config });
+
+ await expect(ensureShareLinkAccessGranted({ shareLink, accessToken: undefined, config, clock })).rejects.toThrowError('valid access token is required');
+ });
+
+ test('an expired access token is rejected', async () => {
+ const { clock, shareLinksRepository, documentsRepository } = await setup();
+ const { shareLink } = await createShareLink({ organizationId: 'org_1', documentId: 'doc_1', password: 'hunter2', userId: 'user_1', shareLinksRepository, documentsRepository, config });
+
+ const { accessToken } = await issueShareLinkAccessToken({ shareLinkId: shareLink.id, passwordHash: shareLink.passwordHash!, authSecret: config.auth.secret, ttlMinutes: 15, clock });
+
+ // Move past the token TTL.
+ clock.advanceBy({ minutes: 16 });
+
+ await expect(ensureShareLinkAccessGranted({ shareLink, accessToken, config, clock })).rejects.toThrowError('valid access token is required');
+ });
+
+ test('rotating the password invalidates previously issued access tokens', async () => {
+ const { clock, shareLinksRepository, documentsRepository } = await setup();
+ const { shareLink } = await createShareLink({ organizationId: 'org_1', documentId: 'doc_1', password: 'hunter2', userId: 'user_1', shareLinksRepository, documentsRepository, config });
+
+ const { accessToken } = await verifySharePassword({ shareLinkToken: shareLink.token, password: 'hunter2', shareLinksRepository, config, clock });
+
+ // Token is valid against the current password.
+ await ensureShareLinkAccessGranted({ shareLink, accessToken, config, clock });
+
+ const { shareLink: rotated } = await updateShareLink({ shareLinkId: shareLink.id, organizationId: 'org_1', password: 'new-password', shareLinksRepository });
+
+ // The same token no longer grants access once the password changed.
+ await expect(ensureShareLinkAccessGranted({ shareLink: rotated, accessToken, config, clock })).rejects.toThrowError('valid access token is required');
+ });
+ });
+
+ describe('getSharedDocument', () => {
+ test('returns the document for a non-protected, usable link and records the access time', async () => {
+ const { clock, shareLinksRepository, documentsRepository } = await setup();
+ const { shareLink } = await createShareLink({ organizationId: 'org_1', documentId: 'doc_1', userId: 'user_1', shareLinksRepository, documentsRepository, config });
+
+ const { document } = await getSharedDocument({ shareLinkToken: shareLink.token, accessToken: undefined, shareLinksRepository, documentsRepository, config, clock });
+
+ expect(document.id).to.eql('doc_1');
+
+ const { shareLink: refreshed } = await shareLinksRepository.getShareLinkById({ shareLinkId: shareLink.id, organizationId: 'org_1' });
+ expect(refreshed?.lastAccessedAt).to.eql(new Date('2026-05-12T00:00:00Z'));
+ });
+ });
+
+ describe('updateShareLink', () => {
+ test('setting password to null removes protection', async () => {
+ const { shareLinksRepository, documentsRepository } = await setup();
+ const { shareLink } = await createShareLink({ organizationId: 'org_1', documentId: 'doc_1', password: 'hunter2', userId: 'user_1', shareLinksRepository, documentsRepository, config });
+
+ const { shareLink: updated } = await updateShareLink({ shareLinkId: shareLink.id, organizationId: 'org_1', password: null, shareLinksRepository });
+
+ expect(updated.passwordHash).to.eql(null);
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/document-share-links/document-share-links.usecases.ts b/apps/papra-server/src/modules/document-share-links/document-share-links.usecases.ts
new file mode 100644
index 00000000..ca4385dd
--- /dev/null
+++ b/apps/papra-server/src/modules/document-share-links/document-share-links.usecases.ts
@@ -0,0 +1,251 @@
+import type { Config } from '../config/config.types';
+import type { DocumentsRepository } from '../documents/documents.repository';
+import type { Clock } from '../shared/clock/clock.types';
+import type { ShareLinksRepository } from './document-share-links.repository';
+import type { DbSelectableShareLink } from './document-share-links.types';
+import { getDocumentOrThrow } from '../documents/documents.usecases';
+import { systemClock } from '../shared/clock/clock';
+import { isNil } from '../shared/utils';
+import { isShareLinkAccessTokenValid, issueShareLinkAccessToken } from './document-share-links.access-token';
+import {
+ createShareLinkGoneError,
+ createShareLinkInvalidPasswordError,
+ createShareLinkLimitReachedError,
+ createShareLinkNotFoundError,
+ createShareLinkNotPasswordProtectedError,
+ createShareLinkPasswordRequiredError,
+} from './document-share-links.errors';
+import { generateShareToken, shouldTouchShareLinkLastAccessedAt } from './document-share-links.models';
+import { hashPassword, verifyPassword } from './document-share-links.password';
+
+function isShareLinkExpired({ shareLink, clock }: { shareLink: DbSelectableShareLink; clock: Clock }) {
+ if (isNil(shareLink.expiresAt)) {
+ return false;
+ }
+
+ return shareLink.expiresAt.getTime() <= clock.now().epochMilliseconds;
+}
+
+async function resolvePasswordHash({ password}: { password: string | undefined | null }) {
+ if (password === undefined) {
+ return { passwordHash: undefined };
+ }
+
+ // null explicitly removes the password in updates
+ if (password === null) {
+ return { passwordHash: null };
+ }
+
+ const { passwordHash } = await hashPassword({ password });
+ return { passwordHash };
+}
+
+export async function createShareLink({
+ organizationId,
+ documentId,
+ expiresAt,
+ password,
+ userId,
+ shareLinksRepository,
+ documentsRepository,
+ config,
+}: {
+ organizationId: string;
+ documentId: string;
+ expiresAt?: Date | null;
+ password?: string;
+ userId: string;
+ shareLinksRepository: ShareLinksRepository;
+ documentsRepository: DocumentsRepository;
+ config: Config;
+}) {
+ // Ensures the document exists in the organization before exposing it through a share link.
+ await getDocumentOrThrow({ documentId, organizationId, documentsRepository });
+
+ const { shareLinksCount } = await shareLinksRepository.countDocumentShareLinks({ documentId, organizationId });
+
+ if (shareLinksCount >= config.documentShareLinks.maxLinksPerDocument) {
+ throw createShareLinkLimitReachedError();
+ }
+
+ const { token } = generateShareToken();
+ const { passwordHash } = await resolvePasswordHash({ password });
+
+ const { shareLink } = await shareLinksRepository.createShareLink({
+ organizationId,
+ documentId,
+ token,
+ expiresAt,
+ passwordHash,
+ createdBy: userId,
+ });
+
+ return { shareLink };
+}
+
+export async function updateShareLink({
+ shareLinkId,
+ organizationId,
+ expiresAt,
+ password,
+ isEnabled,
+ shareLinksRepository,
+}: {
+ shareLinkId: string;
+ organizationId: string;
+ expiresAt?: Date | null;
+ password?: string | null;
+ isEnabled?: boolean;
+ shareLinksRepository: ShareLinksRepository;
+}) {
+ const { passwordHash } = await resolvePasswordHash({ password });
+
+ const { shareLink } = await shareLinksRepository.updateShareLink({
+ shareLinkId,
+ organizationId,
+ expiresAt,
+ passwordHash,
+ isEnabled,
+ });
+
+ return { shareLink };
+}
+
+// Resolves the document backing a share link for public access. A trashed (soft-deleted)
+// document is treated as gone (410): the link is not removed on trash so it resumes on restore,
+// but public access must stop immediately.
+export async function getShareLinkDocumentOrThrow({
+ shareLink,
+ documentsRepository,
+}: {
+ shareLink: DbSelectableShareLink;
+ documentsRepository: DocumentsRepository;
+}) {
+ const { document } = await getDocumentOrThrow({ documentId: shareLink.documentId, organizationId: shareLink.organizationId, documentsRepository });
+
+ if (document.isDeleted) {
+ throw createShareLinkGoneError();
+ }
+
+ return { document };
+}
+
+// Resolves a share link by its public token, throwing 404 if unknown and 410 if disabled/expired.
+export async function resolveUsableShareLinkByToken({
+ shareLinkToken,
+ shareLinksRepository,
+ clock = systemClock,
+}: {
+ shareLinkToken: string;
+ shareLinksRepository: ShareLinksRepository;
+ clock?: Clock;
+}) {
+ const { shareLink } = await shareLinksRepository.getShareLinkByToken({ token: shareLinkToken });
+
+ if (!shareLink) {
+ throw createShareLinkNotFoundError();
+ }
+
+ if (!shareLink.isEnabled || isShareLinkExpired({ shareLink, clock })) {
+ throw createShareLinkGoneError();
+ }
+
+ return { shareLink };
+}
+
+// Throws 401 when the link is password protected and no valid access token was provided.
+export async function ensureShareLinkAccessGranted({
+ shareLink,
+ accessToken,
+ config,
+ clock = systemClock,
+}: {
+ shareLink: DbSelectableShareLink;
+ accessToken: string | undefined;
+ config: Config;
+ clock?: Clock;
+}) {
+ if (isNil(shareLink.passwordHash)) {
+ // Link is not password protected
+ return;
+ }
+
+ const { isValid } = await isShareLinkAccessTokenValid({ accessToken, shareLinkId: shareLink.id, passwordHash: shareLink.passwordHash, authSecret: config.auth.secret, clock });
+
+ if (!isValid) {
+ throw createShareLinkPasswordRequiredError();
+ }
+}
+
+export async function verifySharePassword({
+ shareLinkToken,
+ password,
+ shareLinksRepository,
+ config,
+ clock = systemClock,
+}: {
+ shareLinkToken: string;
+ password: string;
+ shareLinksRepository: ShareLinksRepository;
+ config: Config;
+ clock?: Clock;
+}) {
+ const { shareLink } = await resolveUsableShareLinkByToken({ shareLinkToken, shareLinksRepository, clock });
+
+ if (shareLink.passwordHash === null) {
+ throw createShareLinkNotPasswordProtectedError();
+ }
+
+ const { isValid } = await verifyPassword({ password, passwordHash: shareLink.passwordHash });
+
+ if (!isValid) {
+ throw createShareLinkInvalidPasswordError();
+ }
+
+ const { accessToken } = await issueShareLinkAccessToken({
+ shareLinkId: shareLink.id,
+ passwordHash: shareLink.passwordHash,
+ authSecret: config.auth.secret,
+ ttlMinutes: config.documentShareLinks.accessTokenTtlMinutes,
+ clock,
+ });
+
+ return { accessToken };
+}
+
+export async function touchShareLinkLastAccessedAt({
+ shareLink,
+ shareLinksRepository,
+ clock = systemClock,
+}: { shareLink: DbSelectableShareLink; shareLinksRepository: ShareLinksRepository; clock?: Clock }) {
+ if (shouldTouchShareLinkLastAccessedAt({ lastAccessedAt: shareLink.lastAccessedAt?.toTemporalInstant(), clock })) {
+ await shareLinksRepository.touchLastAccessedAt({ shareLinkId: shareLink.id, lastAccessedAt: new Date(clock.now().epochMilliseconds) });
+ }
+}
+
+// Resolves a share link for public document access: validates usability, enforces password, returns the document.
+export async function getSharedDocument({
+ shareLinkToken,
+ accessToken,
+ shareLinksRepository,
+ documentsRepository,
+ config,
+ clock = systemClock,
+}: {
+ shareLinkToken: string;
+ accessToken: string | undefined;
+ shareLinksRepository: ShareLinksRepository;
+ documentsRepository: DocumentsRepository;
+ config: Config;
+ clock?: Clock;
+}) {
+ const { shareLink } = await resolveUsableShareLinkByToken({ shareLinkToken, shareLinksRepository, clock });
+
+ await ensureShareLinkAccessGranted({ shareLink, accessToken, config, clock });
+
+ const { document } = await getShareLinkDocumentOrThrow({ shareLink, documentsRepository });
+
+ await touchShareLinkLastAccessedAt({ shareLink, shareLinksRepository, clock });
+
+ return { shareLink, document };
+}
diff --git a/apps/papra-server/src/modules/document-share-links/e2e/shared-document-access.e2e.test.ts b/apps/papra-server/src/modules/document-share-links/e2e/shared-document-access.e2e.test.ts
new file mode 100644
index 00000000..5e5c57b6
--- /dev/null
+++ b/apps/papra-server/src/modules/document-share-links/e2e/shared-document-access.e2e.test.ts
@@ -0,0 +1,202 @@
+import { describe, expect, test } from 'vitest';
+import { createInMemoryDatabase } from '../../app/database/database.test-utils';
+import { createServer } from '../../app/server';
+import { createTestServerDependencies } from '../../app/server.test-utils';
+import { overrideConfig } from '../../config/config.test-utils';
+import { createInMemoryDocumentStorageServices } from '../../documents/storage/documents.storage.services.test-utils';
+import { ORGANIZATION_ROLES } from '../../organizations/organizations.constants';
+import { createReadableStream } from '../../shared/streams/readable-stream';
+
+const config = overrideConfig({
+ env: 'test',
+ auth: { secret: 'test-secret-that-is-at-least-32-chars-long' },
+ documentsStorage: { driver: 'in-memory' },
+});
+
+async function createTestApp() {
+ const document = {
+ id: 'doc_333333333333333333333333',
+ name: 'invoice.pdf',
+ storageKey: 'org_222222222222222222222222/originals/doc_333333333333333333333333.pdf',
+ mimeType: 'application/pdf',
+ };
+
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'usr_111111111111111111111111', email: '[email protected]' }],
+ organizations: [{ id: 'org_222222222222222222222222', name: 'Org 1' }],
+ organizationMembers: [{ organizationId: 'org_222222222222222222222222', userId: 'usr_111111111111111111111111', role: ORGANIZATION_ROLES.OWNER }],
+ documents: [{
+ id: document.id,
+ organizationId: 'org_222222222222222222222222',
+ name: document.name,
+ originalName: document.name,
+ originalSize: 1024,
+ originalStorageKey: document.storageKey,
+ originalSha256Hash: 'hash_1',
+ mimeType: document.mimeType,
+ }],
+ });
+
+ const documentsStorageService = createInMemoryDocumentStorageServices();
+
+ await documentsStorageService.saveFile({
+ fileName: document.name,
+ storageKey: document.storageKey,
+ mimeType: document.mimeType,
+ fileStream: createReadableStream({ content: 'File content.' }),
+ });
+
+ const { app } = createServer(createTestServerDependencies({ db, config, documentsStorageService }));
+
+ return { app };
+}
+
+describe('shared document access e2e', () => {
+ test('a password-protected document can be accessed with the access token issued after password verification', async () => {
+ const { app } = await createTestApp();
+
+ const createResponse = await app.request(
+ '/api/organizations/org_222222222222222222222222/documents/doc_333333333333333333333333/share-links',
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ password: 'hunter2' }),
+ },
+ { loggedInUserId: 'usr_111111111111111111111111' },
+ );
+
+ expect(createResponse.status).toBe(201);
+ const { shareLink } = await createResponse.json() as { shareLink: { token: string } };
+
+ // Without an access token, the protected document is gated behind a 401.
+ const unauthenticatedDocumentResponse = await app.request(`/api/share-links/${shareLink.token}/document`);
+ expect(unauthenticatedDocumentResponse.status).toBe(401);
+ expect(await unauthenticatedDocumentResponse.json()).toMatchObject({ error: { code: 'share_link.password_required' } });
+
+ const unauthenticatedFileResponse = await app.request(`/api/share-links/${shareLink.token}/document/file`);
+ expect(unauthenticatedFileResponse.status).toBe(401);
+
+ // Verifying the password yields a short-lived access token.
+ const verifyResponse = await app.request(`/api/share-links/${shareLink.token}/verify`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ password: 'hunter2' }),
+ });
+
+ expect(verifyResponse.status).toBe(200);
+ const { accessToken } = await verifyResponse.json() as { accessToken: string };
+ expect(accessToken).toEqual(expect.any(String));
+
+ // The access token, sent as a Bearer header, must grant access to the document.
+ const authenticatedResponse = await app.request(`/api/share-links/${shareLink.token}/document`, {
+ headers: { Authorization: `Bearer ${accessToken}` },
+ });
+
+ expect(authenticatedResponse.status).toBe(200);
+ expect(await authenticatedResponse.json()).toEqual({
+ document: { name: 'invoice.pdf', size: 1024, mimeType: 'application/pdf' },
+ });
+
+ const authenticatedFileResponse = await app.request(`/api/share-links/${shareLink.token}/document/file`, {
+ headers: { Authorization: `Bearer ${accessToken}` },
+ });
+
+ expect(authenticatedFileResponse.status).toBe(200);
+ expect(await authenticatedFileResponse.text()).toBe('File content.');
+ });
+
+ test('a passwordless document can be accessed without any access token', async () => {
+ const { app } = await createTestApp();
+
+ const createResponse = await app.request(
+ '/api/organizations/org_222222222222222222222222/documents/doc_333333333333333333333333/share-links',
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({}),
+ },
+ { loggedInUserId: 'usr_111111111111111111111111' },
+ );
+
+ expect(createResponse.status).toBe(201);
+ const { shareLink } = await createResponse.json() as { shareLink: { token: string } };
+
+ // No password gate: the document is reachable straight away.
+ const documentResponse = await app.request(`/api/share-links/${shareLink.token}/document`);
+
+ expect(documentResponse.status).toBe(200);
+ expect(await documentResponse.json()).toEqual({
+ document: { name: 'invoice.pdf', size: 1024, mimeType: 'application/pdf' },
+ });
+
+ const fileResponse = await app.request(`/api/share-links/${shareLink.token}/document/file`);
+
+ expect(fileResponse.status).toBe(200);
+ expect(await fileResponse.text()).toBe('File content.');
+
+ // Verifying a password against a passwordless link is a client error.
+ const verifyResponse = await app.request(`/api/share-links/${shareLink.token}/verify`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ password: 'hunter2' }),
+ });
+
+ expect(verifyResponse.status).toBe(400);
+ expect(await verifyResponse.json()).toMatchObject({ error: { code: 'share_link.not_password_protected' } });
+ });
+
+ test('a trashed document is no longer reachable through its share link, and access resumes once it is restored', async () => {
+ const { app } = await createTestApp();
+
+ const createResponse = await app.request(
+ '/api/organizations/org_222222222222222222222222/documents/doc_333333333333333333333333/share-links',
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({}),
+ },
+ { loggedInUserId: 'usr_111111111111111111111111' },
+ );
+
+ expect(createResponse.status).toBe(201);
+ const { shareLink } = await createResponse.json() as { shareLink: { token: string } };
+
+ // Sanity check: the link works while the document is live.
+ expect((await app.request(`/api/share-links/${shareLink.token}/document`)).status).toBe(200);
+
+ // Trash (soft-delete) the document.
+ const trashResponse = await app.request(
+ '/api/organizations/org_222222222222222222222222/documents/doc_333333333333333333333333',
+ { method: 'DELETE' },
+ { loggedInUserId: 'usr_111111111111111111111111' },
+ );
+ expect(trashResponse.status).toBe(200);
+
+ // Public access to both the metadata and the file must stop with a 410 Gone.
+ const trashedDocumentResponse = await app.request(`/api/share-links/${shareLink.token}/document`);
+ expect(trashedDocumentResponse.status).toBe(410);
+ expect(await trashedDocumentResponse.json()).toMatchObject({ error: { code: 'share_link.gone' } });
+
+ const trashedFileResponse = await app.request(`/api/share-links/${shareLink.token}/document/file`);
+ expect(trashedFileResponse.status).toBe(410);
+ expect(await trashedFileResponse.json()).toMatchObject({ error: { code: 'share_link.gone' } });
+
+ // Restoring the document brings the same link back to life.
+ const restoreResponse = await app.request(
+ '/api/organizations/org_222222222222222222222222/documents/doc_333333333333333333333333/restore',
+ { method: 'POST' },
+ { loggedInUserId: 'usr_111111111111111111111111' },
+ );
+ expect(restoreResponse.status).toBe(204);
+
+ const restoredDocumentResponse = await app.request(`/api/share-links/${shareLink.token}/document`);
+ expect(restoredDocumentResponse.status).toBe(200);
+ expect(await restoredDocumentResponse.json()).toEqual({
+ document: { name: 'invoice.pdf', size: 1024, mimeType: 'application/pdf' },
+ });
+
+ const restoredFileResponse = await app.request(`/api/share-links/${shareLink.token}/document/file`);
+ expect(restoredFileResponse.status).toBe(200);
+ expect(await restoredFileResponse.text()).toBe('File content.');
+ });
+});