Skip to content

The Open Source DocuSign Alternative.

feat: persist signatures for authless embed signers (#3465)

Lucas Smith68b9d2093c35
diff --git a/apps/docs/content/docs/developers/embedding/iframe.mdx b/apps/docs/content/docs/developers/embedding/iframe.mdx
index 70077fcfc..63129c175 100644
--- a/apps/docs/content/docs/developers/embedding/iframe.mdx
+++ b/apps/docs/content/docs/developers/embedding/iframe.mdx
@@ -75,6 +75,28 @@ const buildEmbedSrc = (host: string, token: string) => {
A complete example can be found in the [Embeds repository](https://github.com/documenso/embeds/blob/main/packages/mitosis/src/sign-document.lite.tsx).
+#### Query parameters
+
+A small number of options are read **server side** and are therefore passed as regular query parameters rather than in the fragment.
+
+| Parameter | Applies to | Description |
+| --------- | ---------- | ----------- |
+| `clientUserId` | `/embed/sign/:token` | Opaque signer identifier used to prefill and persist the signer's signature across embeds. Platform Plan. See [Persisting Signatures](/docs/developers/embedding#persisting-signatures). |
+| `externalId` | `/embed/direct/:token` | Your reference ID, stored with the document created from the direct template. |
+
+```ts
+const src = new URL(`/embed/sign/${token}`, host);
+
+src.searchParams.set('clientUserId', 'usr_8f2c1b4e');
+
+return `${src.toString()}#${encodedOptions}`;
+```
+
+<Callout type="warn" title="Keep identifiers opaque">
+ Query parameters are part of the HTTP request and will appear in Documenso's request logs. Never put an email address
+ or other personally identifiable information in `clientUserId`; use an opaque ID instead.
+</Callout>
+
<Callout type="info" title="Why use the URL fragment?">
The fragment is **not sent to the server** as part of the HTTP request, but it is available to the embedded app in
the browser. This makes it a convenient way to pass client-side configuration without changing the base embed URL.
diff --git a/apps/docs/content/docs/developers/embedding/index.mdx b/apps/docs/content/docs/developers/embedding/index.mdx
index 0cf9a149e..cd5e44417 100644
--- a/apps/docs/content/docs/developers/embedding/index.mdx
+++ b/apps/docs/content/docs/developers/embedding/index.mdx
@@ -176,6 +176,7 @@ If you prefer not to use any SDK, you can embed signing using [Direct Links](/do
| `host` | `string` | Documenso instance URL. Defaults to `https://app.documenso.com`. |
| `name` | `string` | Pre-fill the signer's name. |
| `lockName` | `boolean` | Prevent the signer from changing their name. |
+| `clientUserId` | `string` | Opaque identifier for the signer used to persist their signature across embeds (Platform Plan). See [Persisting Signatures](#persisting-signatures). |
| `language` | `string` | Set the UI language. See [Supported Languages](https://github.com/documenso/documenso/tree/main/packages/lib/constants/locales.ts). |
| `onDocumentReady` | `function` | Called when the document is loaded and ready. |
| `onDocumentCompleted` | `function` | Called when signing is completed. |
@@ -183,6 +184,39 @@ If you prefer not to use any SDK, you can embed signing using [Direct Links](/do
---
+## Persisting Signatures
+
+<Callout type="info">
+ Persisted signatures are available on the [Platform Plan](https://documen.so/platform-cta-pricing) and above.
+</Callout>
+
+By default a signer in an embed has no account, so every document they sign starts with an empty signature pad. If the same person signs through your embeds repeatedly you can pass a `clientUserId` and Documenso will remember the signature they used and prefill it next time.
+
+```jsx
+<EmbedSignDocument
+ token="recipient-signing-token"
+ clientUserId="usr_8f2c1b4e"
+/>
+```
+
+How it works:
+
+- The persisted signature is scoped to your organisation, the recipient's email address and the `clientUserId` you pass. The same `clientUserId` with a different recipient email is treated as a different signer.
+- When the embed loads with a `clientUserId` and a matching signature exists, the signature pad is prefilled with it. The signer can still clear it and sign differently.
+- Whenever the signer updates their signature inside the embed, the new signature is stored in the background. Storage is best effort and never blocks signing.
+- Only the signature pad value is stored. It's never applied to a document on the signer's behalf.
+
+<Callout type="warn" title="Do not use personal information as the identifier">
+ `clientUserId` is sent as a URL query parameter and will appear in Documenso's request logs. Those logs are rotated
+ and deleted, but only after a significant retention period. Always pass an **opaque identifier** (for example your
+ internal user ID or a random token you store against the user) rather than an email address, name, phone number or
+ any other personally identifiable information. Documenso only ever stores a one-way hash of the identifier.
+</Callout>
+
+Writes to persisted signatures are rate limited per recipient and per IP address. If the limit is exceeded the update is skipped and the signer's current session is unaffected.
+
+---
+
## Event Callbacks
### onDocumentCompleted
diff --git a/apps/docs/content/docs/developers/embedding/sdks/react.mdx b/apps/docs/content/docs/developers/embedding/sdks/react.mdx
index 58ef0c5d4..d244746a2 100644
--- a/apps/docs/content/docs/developers/embedding/sdks/react.mdx
+++ b/apps/docs/content/docs/developers/embedding/sdks/react.mdx
@@ -57,6 +57,16 @@ const SigningPage = ({ token }: { token: string }) => {
};
```
+### Remembering a signer's signature (Platform Plan)
+
+Pass an opaque `clientUserId` to prefill and persist the signer's signature across your embeds. Never use an email
+address or other personal information here, it appears in request logs. See
+[Persisting Signatures](/docs/developers/embedding#persisting-signatures).
+
+```tsx
+<EmbedSignDocument token={token} clientUserId={user.id} />
+```
+
---
## Styling (Platform Plan)
diff --git a/apps/remix/app/components/embed/embed-document-fields.tsx b/apps/remix/app/components/embed/embed-document-fields.tsx
index d2b4ada91..67164c9b9 100644
--- a/apps/remix/app/components/embed/embed-document-fields.tsx
+++ b/apps/remix/app/components/embed/embed-document-fields.tsx
@@ -37,9 +37,16 @@ export type EmbedDocumentFieldsProps = {
> | null;
onSignField?: (value: TSignFieldWithTokenMutationSchema) => Promise<void> | void;
onUnsignField?: (value: TRemovedSignedFieldWithTokenMutationSchema) => Promise<void> | void;
+ onSignatureChanged?: (signature: string | null) => void;
};
-export const EmbedDocumentFields = ({ fields, metadata, onSignField, onUnsignField }: EmbedDocumentFieldsProps) => {
+export const EmbedDocumentFields = ({
+ fields,
+ metadata,
+ onSignField,
+ onUnsignField,
+ onSignatureChanged,
+}: EmbedDocumentFieldsProps) => {
return (
<ElementVisible target={PDF_VIEWER_PAGE_SELECTOR}>
{fields.map((field) =>
@@ -50,6 +57,7 @@ export const EmbedDocumentFields = ({ fields, metadata, onSignField, onUnsignFie
field={field}
onSignField={onSignField}
onUnsignField={onUnsignField}
+ onSignatureChanged={onSignatureChanged}
typedSignatureEnabled={metadata?.typedSignatureEnabled}
uploadSignatureEnabled={metadata?.uploadSignatureEnabled}
drawSignatureEnabled={metadata?.drawSignatureEnabled}
diff --git a/apps/remix/app/components/embed/embed-document-signing-page-v1.tsx b/apps/remix/app/components/embed/embed-document-signing-page-v1.tsx
index afd9a774f..8ec2a6feb 100644
--- a/apps/remix/app/components/embed/embed-document-signing-page-v1.tsx
+++ b/apps/remix/app/components/embed/embed-document-signing-page-v1.tsx
@@ -44,6 +44,7 @@ import { EmbedClientLoading } from './embed-client-loading';
import { EmbedDocumentCompleted } from './embed-document-completed';
import { EmbedDocumentFields } from './embed-document-fields';
import { EmbedDocumentRejected } from './embed-document-rejected';
+import { usePersistEmbedSignature } from './use-persist-embed-signature';
export type EmbedSignDocumentV1ClientPageProps = {
token: string;
@@ -59,6 +60,7 @@ export type EmbedSignDocumentV1ClientPageProps = {
hidePoweredBy?: boolean;
allowWhitelabelling?: boolean;
allRecipients?: RecipientWithFields[];
+ clientUserId?: string | null;
};
export const EmbedSignDocumentV1ClientPage = ({
@@ -75,6 +77,7 @@ export const EmbedSignDocumentV1ClientPage = ({
hidePoweredBy = false,
allowWhitelabelling = false,
allRecipients = [],
+ clientUserId = null,
}: EmbedSignDocumentV1ClientPageProps) => {
const { _ } = useLingui();
const { toast } = useToast();
@@ -82,6 +85,12 @@ export const EmbedSignDocumentV1ClientPage = ({
const { fullName, email, signature, setFullName, setEmail, setSignature } = useRequiredDocumentSigningContext();
+ const { persistSignature } = usePersistEmbedSignature({
+ token,
+ clientUserId,
+ initialSignature: signature,
+ });
+
const [hasFinishedInit, setHasFinishedInit] = useState(false);
const [hasDocumentLoaded, setHasDocumentLoaded] = useState(false);
const [hasCompletedDocument, setHasCompletedDocument] = useState(isCompleted);
@@ -544,7 +553,10 @@ export const EmbedSignDocumentV1ClientPage = ({
disableAnimation
fullName={fullName}
value={signature ?? ''}
- onChange={(v) => setSignature(v ?? '')}
+ onChange={(v) => {
+ setSignature(v ?? '');
+ persistSignature(v);
+ }}
typedSignatureEnabled={metadata?.typedSignatureEnabled}
uploadSignatureEnabled={metadata?.uploadSignatureEnabled}
drawSignatureEnabled={metadata?.drawSignatureEnabled}
@@ -586,7 +598,7 @@ export const EmbedSignDocumentV1ClientPage = ({
)}
{/* Fields */}
- <EmbedDocumentFields fields={fields} metadata={metadata} />
+ <EmbedDocumentFields fields={fields} metadata={metadata} onSignatureChanged={persistSignature} />
{/* Completed fields */}
<DocumentReadOnlyFields documentMeta={metadata || undefined} fields={completedFields} />
diff --git a/apps/remix/app/components/embed/embed-document-signing-page-v2.tsx b/apps/remix/app/components/embed/embed-document-signing-page-v2.tsx
index 8973a23df..0d31eaa0a 100644
--- a/apps/remix/app/components/embed/embed-document-signing-page-v2.tsx
+++ b/apps/remix/app/components/embed/embed-document-signing-page-v2.tsx
@@ -15,24 +15,33 @@ import { EmbedClientLoading } from './embed-client-loading';
import { EmbedDocumentCompleted } from './embed-document-completed';
import { EmbedDocumentRejected } from './embed-document-rejected';
import { EmbedSigningProvider } from './embed-signing-context';
+import { usePersistEmbedSignature } from './use-persist-embed-signature';
export type EmbedSignDocumentV2ClientPageProps = {
hidePoweredBy?: boolean;
allowWhitelabelling?: boolean;
+ clientUserId?: string | null;
};
export const EmbedSignDocumentV2ClientPage = ({
hidePoweredBy = false,
allowWhitelabelling = false,
+ clientUserId = null,
}: EmbedSignDocumentV2ClientPageProps) => {
const { _ } = useLingui();
const analytics = useAnalytics();
- const { envelope, recipient, envelopeData, setFullName, setEmail, fullName, email } =
+ const { envelope, recipient, envelopeData, setFullName, setEmail, fullName, email, signature } =
useRequiredEnvelopeSigningContext();
const { isCompleted, isRejected, recipientSignature } = envelopeData;
+ const { persistSignature } = usePersistEmbedSignature({
+ token: recipient.token,
+ clientUserId,
+ initialSignature: signature,
+ });
+
// !: Not used at the moment, may be removed in the future.
// const [hasDocumentLoaded, setHasDocumentLoaded] = useState(false);
const [hasFinishedInit, setHasFinishedInit] = useState(false);
@@ -266,6 +275,7 @@ export const EmbedSignDocumentV2ClientPage = ({
onDocumentReady={onDocumentReady}
onFieldSigned={onFieldSigned}
onFieldUnsigned={onFieldUnsigned}
+ onSignatureChanged={persistSignature}
>
<div className="embed--Root relative">
{!hasFinishedInit && <EmbedClientLoading />}
diff --git a/apps/remix/app/components/embed/embed-signing-context.tsx b/apps/remix/app/components/embed/embed-signing-context.tsx
index 0b4a3c848..898ddb008 100644
--- a/apps/remix/app/components/embed/embed-signing-context.tsx
+++ b/apps/remix/app/components/embed/embed-signing-context.tsx
@@ -18,6 +18,7 @@ export type EmbedSigningContextValue = {
onDocumentReady: () => void;
onFieldSigned: (data: { fieldId?: number; value?: string; isBase64?: boolean }) => void;
onFieldUnsigned: (data: { fieldId?: number }) => void;
+ onSignatureChanged: (signature: string | null) => void;
};
const EmbedSigningContext = createContext<EmbedSigningContextValue | null>(null);
@@ -53,6 +54,7 @@ export type EmbedSigningProviderProps = {
onDocumentReady: () => void;
onFieldSigned: (data: { fieldId?: number; value?: string; isBase64?: boolean }) => void;
onFieldUnsigned: (data: { fieldId?: number }) => void;
+ onSignatureChanged: (signature: string | null) => void;
children: React.ReactNode;
};
@@ -67,6 +69,7 @@ export const EmbedSigningProvider = ({
onDocumentReady,
onFieldSigned,
onFieldUnsigned,
+ onSignatureChanged,
children,
}: EmbedSigningProviderProps) => {
return (
@@ -83,6 +86,7 @@ export const EmbedSigningProvider = ({
onDocumentReady,
onFieldSigned,
onFieldUnsigned,
+ onSignatureChanged,
}}
>
{children}
diff --git a/apps/remix/app/components/embed/use-persist-embed-signature.ts b/apps/remix/app/components/embed/use-persist-embed-signature.ts
new file mode 100644
index 000000000..1ccbc7f7d
--- /dev/null
+++ b/apps/remix/app/components/embed/use-persist-embed-signature.ts
@@ -0,0 +1,48 @@
+import { DO_NOT_INVALIDATE_QUERY_ON_MUTATION } from '@documenso/lib/constants/trpc';
+import { trpc } from '@documenso/trpc/react';
+import { useCallback, useRef } from 'react';
+
+export type UsePersistEmbedSignatureOptions = {
+ token: string;
+ clientUserId: string | null | undefined;
+ initialSignature: string | null | undefined;
+};
+
+export const usePersistEmbedSignature = ({
+ token,
+ clientUserId,
+ initialSignature,
+}: UsePersistEmbedSignatureOptions) => {
+ const { mutate } = trpc.embeddingPresign.persistEmbedSignature.useMutation({
+ ...DO_NOT_INVALIDATE_QUERY_ON_MUTATION,
+ });
+
+ const lastPersistedSignature = useRef(initialSignature || null);
+
+ const persistSignature = useCallback(
+ (signature: string | null | undefined) => {
+ const nextSignature = signature || null;
+
+ if (!clientUserId || !nextSignature || nextSignature === lastPersistedSignature.current) {
+ return;
+ }
+
+ mutate(
+ {
+ token,
+ clientUserId,
+ signature: nextSignature,
+ },
+ {
+ onSuccess: () => {
+ lastPersistedSignature.current = nextSignature;
+ },
+ onError: () => null,
+ },
+ );
+ },
+ [token, clientUserId, mutate],
+ );
+
+ return { persistSignature };
+};
diff --git a/apps/remix/app/components/general/document-signing/document-signing-signature-field.tsx b/apps/remix/app/components/general/document-signing/document-signing-signature-field.tsx
index ecab0b1bc..4aef2195d 100644
--- a/apps/remix/app/components/general/document-signing/document-signing-signature-field.tsx
+++ b/apps/remix/app/components/general/document-signing/document-signing-signature-field.tsx
@@ -32,6 +32,7 @@ export type DocumentSigningSignatureFieldProps = {
field: FieldWithSignature;
onSignField?: (value: TSignFieldWithTokenMutationSchema) => Promise<void> | void;
onUnsignField?: (value: TRemovedSignedFieldWithTokenMutationSchema) => Promise<void> | void;
+ onSignatureChanged?: (signature: string | null) => void;
typedSignatureEnabled?: boolean;
uploadSignatureEnabled?: boolean;
drawSignatureEnabled?: boolean;
@@ -41,6 +42,7 @@ export const DocumentSigningSignatureField = ({
field,
onSignField,
onUnsignField,
+ onSignatureChanged,
typedSignatureEnabled,
uploadSignatureEnabled,
drawSignatureEnabled,
@@ -103,6 +105,7 @@ export const DocumentSigningSignatureField = ({
const onDialogSignClick = () => {
setShowSignatureModal(false);
setProvidedSignature(localSignature);
+ onSignatureChanged?.(localSignature);
if (!localSignature) {
return;
diff --git a/apps/remix/app/components/general/envelope-signing/envelope-signer-form.tsx b/apps/remix/app/components/general/envelope-signing/envelope-signer-form.tsx
index 010a89fa3..b188646d4 100644
--- a/apps/remix/app/components/general/envelope-signing/envelope-signer-form.tsx
+++ b/apps/remix/app/components/general/envelope-signing/envelope-signer-form.tsx
@@ -26,7 +26,7 @@ export default function EnvelopeSignerForm() {
setSelectedAssistantRecipientId,
} = useRequiredEnvelopeSigningContext();
- const { isNameLocked, isEmailLocked } = useEmbedSigningContext() || {};
+ const { isNameLocked, isEmailLocked, onSignatureChanged } = useEmbedSigningContext() || {};
const hasSignatureField = useMemo(() => {
return recipientFields.some((field) => isSignatureFieldType(field.type));
@@ -117,7 +117,10 @@ export default function EnvelopeSignerForm() {
disabled={isSubmitting}
fullName={fullName}
value={signature ?? ''}
- onChange={(v) => setSignature(v ?? '')}
+ onChange={(v) => {
+ setSignature(v ?? '');
+ onSignatureChanged?.(v ?? null);
+ }}
typedSignatureEnabled={envelope.documentMeta.typedSignatureEnabled}
uploadSignatureEnabled={envelope.documentMeta.uploadSignatureEnabled}
drawSignatureEnabled={envelope.documentMeta.drawSignatureEnabled}
diff --git a/apps/remix/app/components/general/envelope-signing/envelope-signer-page-renderer.tsx b/apps/remix/app/components/general/envelope-signing/envelope-signer-page-renderer.tsx
index 1c5c54ca0..4c76a5a46 100644
--- a/apps/remix/app/components/general/envelope-signing/envelope-signer-page-renderer.tsx
+++ b/apps/remix/app/components/general/envelope-signing/envelope-signer-page-renderer.tsx
@@ -88,7 +88,7 @@ export const EnvelopeSignerPageRenderer = ({ pageData }: { pageData: PageRenderD
const cachedRenderFields = useRef<Map<number, Field & { signature?: Signature | null }>>(new Map());
const prevShowPendingFieldTooltip = useRef(showPendingFieldTooltip);
- const { onFieldSigned, onFieldUnsigned } = useEmbedSigningContext() || {};
+ const { onFieldSigned, onFieldUnsigned, onSignatureChanged } = useEmbedSigningContext() || {};
const { stage, pageLayer, konvaContainer, unscaledViewport } = usePageRenderer(
({ stage, pageLayer }) => createPageCanvas(stage, pageLayer),
@@ -405,6 +405,7 @@ export const EnvelopeSignerPageRenderer = ({ pageData }: { pageData: PageRenderD
});
setSignature(payload.value);
+ onSignatureChanged?.(payload.value);
} else {
await signField(field.id, payload);
}
diff --git a/apps/remix/app/routes/embed+/_v0+/sign.$token.tsx b/apps/remix/app/routes/embed+/_v0+/sign.$token.tsx
index 36b44ffbe..2ba0a4593 100644
--- a/apps/remix/app/routes/embed+/_v0+/sign.$token.tsx
+++ b/apps/remix/app/routes/embed+/_v0+/sign.$token.tsx
@@ -6,6 +6,7 @@ import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { captureServerEvent } from '@documenso/lib/server-only/analytics/capture-server-event';
import { getDocumentAndSenderByToken } from '@documenso/lib/server-only/document/get-document-by-token';
import { viewedDocument } from '@documenso/lib/server-only/document/viewed-document';
+import { resolveEmbedSignature } from '@documenso/lib/server-only/embedding/resolve-embed-signature';
import { getEnvelopeForRecipientSigning } from '@documenso/lib/server-only/envelope/get-envelope-for-recipient-signing';
import { getEnvelopeRequiredAccessData } from '@documenso/lib/server-only/envelope/get-envelope-required-access-data';
import { getCompletedFieldsForToken } from '@documenso/lib/server-only/field/get-completed-fields-for-token';
@@ -38,6 +39,8 @@ import type { Route } from './+types/sign.$token';
async function handleV1Loader({ params, request }: Route.LoaderArgs) {
const { requestMetadata } = getOptionalLoaderContext();
+ const { searchParams } = new URL(request.url);
+
if (!params.token) {
throw new Response('Not found', { status: 404 });
}
@@ -148,6 +151,21 @@ async function handleV1Loader({ params, request }: Route.LoaderArgs) {
})
: [];
+ let clientUserId: string | null = null;
+ let persistedSignature: string | null = null;
+
+ if (!hasRecipientActioned) {
+ const resolved = await resolveEmbedSignature({
+ clientUserId: searchParams.get('clientUserId'),
+ teamId: document.teamId,
+ recipientEmail: recipient.email,
+ claimFlags: organisationClaim.flags,
+ });
+
+ clientUserId = resolved?.clientUserId ?? null;
+ persistedSignature = resolved?.persistedSignature ?? null;
+ }
+
fireAndForget(async () => {
const team = await prisma.team.findFirst({
where: {
@@ -184,12 +202,16 @@ async function handleV1Loader({ params, request }: Route.LoaderArgs) {
isRejected,
hidePoweredBy,
allowEmbedSigningWhitelabel,
+ clientUserId,
+ persistedSignature,
};
}
async function handleV2Loader({ params, request }: Route.LoaderArgs) {
const { requestMetadata } = getOptionalLoaderContext();
+ const { searchParams } = new URL(request.url);
+
if (!params.token) {
throw new Response('Not found', { status: 404 });
}
@@ -307,6 +329,21 @@ async function handleV2Loader({ params, request }: Route.LoaderArgs) {
await assertEmbedCscServiceSession({ request, token, envelope, isCompleted, isRejected });
+ let clientUserId: string | null = null;
+ let persistedSignature: string | null = null;
+
+ if (!isCompleted && !isRejected) {
+ const resolved = await resolveEmbedSignature({
+ clientUserId: searchParams.get('clientUserId'),
+ teamId: envelope.teamId,
+ recipientEmail: recipient.email,
+ claimFlags: organisationClaim.flags,
+ });
+
+ clientUserId = resolved?.clientUserId ?? null;
+ persistedSignature = resolved?.persistedSignature ?? null;
+ }
+
fireAndForget(async () => {
const team = await prisma.team.findFirst({
where: {
@@ -337,6 +374,8 @@ async function handleV2Loader({ params, request }: Route.LoaderArgs) {
envelopeForSigning,
hidePoweredBy,
allowEmbedSigningWhitelabel,
+ clientUserId,
+ persistedSignature,
};
}
@@ -423,13 +462,15 @@ const EmbedSignDocumentPageV1 = ({ data }: { data: Awaited<ReturnType<typeof han
isRejected,
hidePoweredBy,
allowEmbedSigningWhitelabel,
+ clientUserId,
+ persistedSignature,
} = data;
return (
<DocumentSigningProvider
email={recipient.email}
fullName={user?.email === recipient.email ? user?.name : recipient.name}
- signature={user?.email === recipient.email ? user?.signature : undefined}
+ signature={(user?.email === recipient.email ? user?.signature : undefined) || persistedSignature || undefined}
typedSignatureEnabled={document.documentMeta?.typedSignatureEnabled}
uploadSignatureEnabled={document.documentMeta?.uploadSignatureEnabled}
drawSignatureEnabled={document.documentMeta?.drawSignatureEnabled}
@@ -449,6 +490,7 @@ const EmbedSignDocumentPageV1 = ({ data }: { data: Awaited<ReturnType<typeof han
hidePoweredBy={hidePoweredBy}
allowWhitelabelling={allowEmbedSigningWhitelabel}
allRecipients={allRecipients}
+ clientUserId={clientUserId}
/>
</DocumentSigningAuthProvider>
</DocumentSigningProvider>
@@ -456,7 +498,15 @@ const EmbedSignDocumentPageV1 = ({ data }: { data: Awaited<ReturnType<typeof han
};
const EmbedSignDocumentPageV2 = ({ data }: { data: Awaited<ReturnType<typeof handleV2Loader>> }) => {
- const { token, user, envelopeForSigning, hidePoweredBy, allowEmbedSigningWhitelabel } = data;
+ const {
+ token,
+ user,
+ envelopeForSigning,
+ hidePoweredBy,
+ allowEmbedSigningWhitelabel,
+ clientUserId,
+ persistedSignature,
+ } = data;
const { envelope, recipient } = envelopeForSigning;
@@ -465,7 +515,7 @@ const EmbedSignDocumentPageV2 = ({ data }: { data: Awaited<ReturnType<typeof han
envelopeData={envelopeForSigning}
email={recipient.email}
fullName={user?.email === recipient.email ? user?.name : recipient.name}
- signature={user?.email === recipient.email ? user?.signature : undefined}
+ signature={(user?.email === recipient.email ? user?.signature : undefined) || persistedSignature || undefined}
>
<DocumentSigningAuthProvider documentAuthOptions={envelope.authOptions} recipient={recipient} user={user}>
<EnvelopeRenderProvider
@@ -477,6 +527,7 @@ const EmbedSignDocumentPageV2 = ({ data }: { data: Awaited<ReturnType<typeof han
<EmbedSignDocumentV2ClientPage
hidePoweredBy={hidePoweredBy}
allowWhitelabelling={allowEmbedSigningWhitelabel}
+ clientUserId={clientUserId}
/>
</EnvelopeRenderProvider>
</DocumentSigningAuthProvider>
diff --git a/packages/app-tests/e2e/api/trpc/embedding/persist-embed-signature.spec.ts b/packages/app-tests/e2e/api/trpc/embedding/persist-embed-signature.spec.ts
new file mode 100644
index 000000000..221de8217
--- /dev/null
+++ b/packages/app-tests/e2e/api/trpc/embedding/persist-embed-signature.spec.ts
@@ -0,0 +1,115 @@
+import { NEXT_PUBLIC_WEBAPP_URL } from '@documenso/lib/constants/app';
+import { EMBED_SIGNATURES_PER_RECIPIENT_LIMIT } from '@documenso/lib/server-only/embedding/upsert-embed-signature';
+import { prisma } from '@documenso/prisma';
+import { seedPendingDocumentWithFullFields } from '@documenso/prisma/seed/documents';
+import { seedUser } from '@documenso/prisma/seed/users';
+import type { Page } from '@playwright/test';
+import { expect, test } from '@playwright/test';
+import { FieldType, SigningStatus } from '@prisma/client';
+
+import { WEBAPP_ORIGIN_HEADERS } from '../../../fixtures/authentication';
+
+const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
+
+const callPersistEmbedSignature = async (
+ page: Page,
+ input: { token: string; clientUserId: string; signature: string },
+) => {
+ return await page.context().request.post(`${WEBAPP_BASE_URL}/api/trpc/embeddingPresign.persistEmbedSignature`, {
+ headers: { ...WEBAPP_ORIGIN_HEADERS, 'content-type': 'application/json' },
+ data: JSON.stringify({ json: input }),
+ });
+};
+
+const seedRecipient = async () => {
+ const { user: owner, team } = await seedUser();
+
+ const { recipients } = await seedPendingDocumentWithFullFields({
+ owner,
+ teamId: team.id,
+ recipients: ['[email protected]'],
+ fields: [FieldType.SIGNATURE],
+ updateDocumentOptions: { internalVersion: 2 },
+ });
+
+ return recipients[0];
+};
+
+test('[PERSIST_EMBED_SIGNATURE]: caps the number of rows a single recipient can create', async ({ page }) => {
+ const recipient = await seedRecipient();
+
+ for (let i = 0; i < EMBED_SIGNATURES_PER_RECIPIENT_LIMIT; i++) {
+ const response = await callPersistEmbedSignature(page, {
+ token: recipient.token,
+ clientUserId: `usr_${i}`,
+ signature: `Signer ${i}`,
+ });
+
+ expect(response.status()).toBe(200);
+ }
+
+ const overflow = await callPersistEmbedSignature(page, {
+ token: recipient.token,
+ clientUserId: 'usr_overflow',
+ signature: 'Overflow',
+ });
+
+ expect(overflow.ok()).toBe(false);
+
+ // Overwriting an existing identity is still allowed at the cap.
+ const overwrite = await callPersistEmbedSignature(page, {
+ token: recipient.token,
+ clientUserId: 'usr_0',
+ signature: 'Signer 0 updated',
+ });
+
+ expect(overwrite.status()).toBe(200);
+
+ expect(await prisma.embedSignature.count({ where: { recipientId: recipient.id } })).toBe(
+ EMBED_SIGNATURES_PER_RECIPIENT_LIMIT,
+ );
+});
+
+test('[PERSIST_EMBED_SIGNATURE]: rejects recipients that can no longer sign', async ({ page }) => {
+ const signedRecipient = await seedRecipient();
+ const expiredRecipient = await seedRecipient();
+
+ await prisma.recipient.update({
+ where: { id: signedRecipient.id },
+ data: { signingStatus: SigningStatus.SIGNED },
+ });
+
+ await prisma.recipient.update({
+ where: { id: expiredRecipient.id },
+ data: { expiresAt: new Date(Date.now() - 60_000) },
+ });
+
+ for (const recipient of [signedRecipient, expiredRecipient]) {
+ const response = await callPersistEmbedSignature(page, {
+ token: recipient.token,
+ clientUserId: 'usr_blocked',
+ signature: 'Blocked',
+ });
+
+ expect(response.status()).toBe(404);
+ }
+
+ expect(
+ await prisma.embedSignature.count({
+ where: { recipientId: { in: [signedRecipient.id, expiredRecipient.id] } },
+ }),
+ ).toBe(0);
+});
+
+test('[PERSIST_EMBED_SIGNATURE]: rejects a non-PNG payload behind the image prefix', async ({ page }) => {
+ const recipient = await seedRecipient();
+
+ const response = await callPersistEmbedSignature(page, {
+ token: recipient.token,
+ clientUserId: 'usr_blob',
+ signature: `data:image/png;base64,${'A'.repeat(4096)}`,
+ });
+
+ expect(response.status()).toBe(400);
+ expect(await prisma.embedSignature.count({ where: { recipientId: recipient.id } })).toBe(0);
+});
diff --git a/packages/app-tests/e2e/embed/embed-persisted-signature.spec.ts b/packages/app-tests/e2e/embed/embed-persisted-signature.spec.ts
new file mode 100644
index 000000000..93617eec5
--- /dev/null
+++ b/packages/app-tests/e2e/embed/embed-persisted-signature.spec.ts
@@ -0,0 +1,66 @@
+import { prisma } from '@documenso/prisma';
+import { seedPendingDocumentWithFullFields } from '@documenso/prisma/seed/documents';
+import { seedUser } from '@documenso/prisma/seed/users';
+import { expect, type Page, test } from '@playwright/test';
+import { FieldType } from '@prisma/client';
+
+const PDF_PAGE_SELECTOR = 'img[data-page-number]';
+
+const SIGNER_EMAIL = '[email protected]';
+const CLIENT_USER_ID = 'usr_8f2c1b4e';
+
+// Distinct from both the fixture default and the recipient name, which the
+// type pad falls back to, so a prefilled value can only have come from storage.
+const TYPED_SIGNATURE = 'Persisted Signer';
+
+test.describe.configure({ mode: 'parallel' });
+
+const openEmbed = async (page: Page, token: string) => {
+ await page.goto(`/embed/sign/${token}?clientUserId=${CLIENT_USER_ID}`);
+
+ await expect(page.locator(PDF_PAGE_SELECTOR).first()).toBeVisible({ timeout: 30_000 });
+};
+
+for (const internalVersion of [1, 2] as const) {
+ test(`[EMBED_PERSISTED_SIGNATURE]: persists the signature and prefills it on the next embed (v${internalVersion})`, async ({
+ page,
+ }) => {
+ const { user: owner, team } = await seedUser();
+
+ const seedDocument = async () => {
+ const { recipients } = await seedPendingDocumentWithFullFields({
+ owner,
+ teamId: team.id,
+ recipients: [SIGNER_EMAIL],
+ fields: [FieldType.SIGNATURE],
+ updateDocumentOptions: { internalVersion },
+ });
+
+ return recipients[0];
+ };
+
+ const firstRecipient = await seedDocument();
+
+ await openEmbed(page, firstRecipient.token);
+
+ await page.getByTestId('signature-pad-dialog-button').click();
+ await page.getByRole('tab', { name: 'Type' }).click();
+ await page.getByTestId('signature-pad-type-input').fill(TYPED_SIGNATURE);
+ await page.getByRole('button', { name: 'Next' }).click();
+
+ await expect
+ .poll(() => prisma.embedSignature.findFirst({ where: { recipientId: firstRecipient.id } }), {
+ timeout: 10_000,
+ })
+ .toMatchObject({ signature: TYPED_SIGNATURE });
+
+ const secondRecipient = await seedDocument();
+
+ await openEmbed(page, secondRecipient.token);
+
+ await page.getByTestId('signature-pad-dialog-button').click();
+ await page.getByRole('tab', { name: 'Type' }).click();
+
+ await expect(page.getByTestId('signature-pad-type-input')).toHaveValue(TYPED_SIGNATURE);
+ });
+}
diff --git a/packages/lib/constants/signatures.ts b/packages/lib/constants/signatures.ts
index 0e0090e4f..3e6885abf 100644
--- a/packages/lib/constants/signatures.ts
+++ b/packages/lib/constants/signatures.ts
@@ -1,4 +1,20 @@
export const SIGNATURE_CANVAS_DPI = 2;
export const SIGNATURE_MIN_COVERAGE_THRESHOLD = 0.01;
-export const isBase64Image = (value: string) => value.startsWith('data:image/png;base64,');
+const PNG_DATA_URL_PREFIX = 'data:image/png;base64,';
+
+// Base64 of the 8-byte PNG magic number.
+const PNG_BASE64_MAGIC = 'iVBORw0KGgo';
+
+export const isBase64Image = (value: string) => value.startsWith(PNG_DATA_URL_PREFIX);
+
+// Stricter than `isBase64Image`: also checks the payload is a real PNG.
+export const isPngSignatureDataUrl = (value: string) => {
+ if (!isBase64Image(value)) {
+ return false;
+ }
+
+ const payload = value.slice(PNG_DATA_URL_PREFIX.length);
+
+ return payload.startsWith(PNG_BASE64_MAGIC) && /^[A-Za-z0-9+/]+=*$/.test(payload);
+};
diff --git a/packages/lib/server-only/embedding/create-embed-signature-key.test.ts b/packages/lib/server-only/embedding/create-embed-signature-key.test.ts
new file mode 100644
index 000000000..ee92dc355
--- /dev/null
+++ b/packages/lib/server-only/embedding/create-embed-signature-key.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest';
+
+import { createEmbedSignatureKey } from './create-embed-signature-key';
+
+describe('createEmbedSignatureKey', () => {
+ const base = {
+ organisationId: 'org_123',
+ email: '[email protected]',
+ clientUserId: 'usr_8f2c1b4e',
+ };
+
+ it('returns a hex SHA-256 digest rather than the raw key', () => {
+ const key = createEmbedSignatureKey(base);
+
+ expect(key).toMatch(/^[a-f0-9]{64}$/);
+ expect(key).not.toContain(base.organisationId);
+ expect(key).not.toContain('example.com');
+ expect(key).not.toContain(base.clientUserId);
+ });
+
+ it('is stable for the same inputs', () => {
+ expect(createEmbedSignatureKey(base)).toBe(createEmbedSignatureKey({ ...base }));
+ });
+
+ it('normalises email case and surrounding whitespace', () => {
+ const key = createEmbedSignatureKey(base);
+
+ expect(createEmbedSignatureKey({ ...base, email: '[email protected]' })).toBe(key);
+ expect(createEmbedSignatureKey({ ...base, email: ' [email protected] ' })).toBe(key);
+ });
+
+ it('scopes the key to the organisation', () => {
+ expect(createEmbedSignatureKey({ ...base, organisationId: 'org_456' })).not.toBe(createEmbedSignatureKey(base));
+ });
+
+ it('scopes the key to the recipient email', () => {
+ expect(createEmbedSignatureKey({ ...base, email: '[email protected]' })).not.toBe(createEmbedSignatureKey(base));
+ });
+
+ it('treats the client user id as case sensitive and opaque', () => {
+ expect(createEmbedSignatureKey({ ...base, clientUserId: 'USR_8F2C1B4E' })).not.toBe(createEmbedSignatureKey(base));
+ });
+});
diff --git a/packages/lib/server-only/embedding/create-embed-signature-key.ts b/packages/lib/server-only/embedding/create-embed-signature-key.ts
new file mode 100644
index 000000000..3d37162e7
--- /dev/null
+++ b/packages/lib/server-only/embedding/create-embed-signature-key.ts
@@ -0,0 +1,15 @@
+import { createHash } from 'node:crypto';
+
+export type CreateEmbedSignatureKeyOptions = {
+ organisationId: string;
+ email: string;
+ clientUserId: string;
+};
+
+// Hashed so the stored row contains neither the recipient's email nor the
+// embedder's identifier.
+export const createEmbedSignatureKey = ({ organisationId, email, clientUserId }: CreateEmbedSignatureKeyOptions) => {
+ const normalisedEmail = email.trim().toLowerCase();
+
+ return createHash('sha256').update(`${organisationId}:${normalisedEmail}:${clientUserId}`).digest('hex');
+};
diff --git a/packages/lib/server-only/embedding/get-embed-signature-settings.ts b/packages/lib/server-only/embedding/get-embed-signature-settings.ts
new file mode 100644
index 000000000..3fdf0f90c
--- /dev/null
+++ b/packages/lib/server-only/embedding/get-embed-signature-settings.ts
@@ -0,0 +1,39 @@
+import { prisma } from '@documenso/prisma';
+
+import { AppError, AppErrorCode } from '../../errors/app-error';
+import { isEmbedSignaturePersistenceEnabled } from '../../utils/billing';
+
+export type GetEmbedSignatureSettingsByTeamIdOptions = {
+ teamId: number;
+};
+
+export const getEmbedSignatureSettingsByTeamId = async ({ teamId }: GetEmbedSignatureSettingsByTeamIdOptions) => {
+ const team = await prisma.team.findFirst({
+ where: {
+ id: teamId,
+ },
+ select: {
+ organisationId: true,
+ organisation: {
+ select: {
+ organisationClaim: {
+ select: {
+ flags: true,
+ },
+ },
+ },
+ },
+ },
+ });
+
+ if (!team) {
+ throw new AppError(AppErrorCode.NOT_FOUND, {
+ message: 'Team not found',
+ });
+ }
+
+ return {
+ organisationId: team.organisationId,
+ isEnabled: isEmbedSignaturePersistenceEnabled(team.organisation.organisationClaim.flags),
+ };
+};
diff --git a/packages/lib/server-only/embedding/get-embed-signature.ts b/packages/lib/server-only/embedding/get-embed-signature.ts
new file mode 100644
index 000000000..51aaf6d9d
--- /dev/null
+++ b/packages/lib/server-only/embedding/get-embed-signature.ts
@@ -0,0 +1,24 @@
+import { prisma } from '@documenso/prisma';
+
+import { createEmbedSignatureKey } from './create-embed-signature-key';
+
+export type GetEmbedSignatureOptions = {
+ organisationId: string;
+ email: string;
+ clientUserId: string;
+};
+
+export const getEmbedSignature = async ({ organisationId, email, clientUserId }: GetEmbedSignatureOptions) => {
+ const key = createEmbedSignatureKey({ organisationId, email, clientUserId });
+
+ const embedSignature = await prisma.embedSignature.findUnique({
+ where: {
+ key,
+ },
+ select: {
+ signature: true,
+ },
+ });
+
+ return embedSignature?.signature ?? null;
+};
diff --git a/packages/lib/server-only/embedding/resolve-embed-signature.ts b/packages/lib/server-only/embedding/resolve-embed-signature.ts
new file mode 100644
index 000000000..5717d0024
--- /dev/null
+++ b/packages/lib/server-only/embedding/resolve-embed-signature.ts
@@ -0,0 +1,66 @@
+import { prisma } from '@documenso/prisma';
+
+import { ZEmbedClientUserIdSchema } from '../../types/embed-signature';
+import type { TClaimFlags } from '../../types/subscription';
+import { isEmbedSignaturePersistenceEnabled } from '../../utils/billing';
+import { logger } from '../../utils/logger';
+import { getEmbedSignature } from './get-embed-signature';
+
+export type ResolveEmbedSignatureOptions = {
+ clientUserId: string | null | undefined;
+ teamId: number;
+ recipientEmail: string;
+ claimFlags: TClaimFlags;
+};
+
+export type ResolvedEmbedSignature = {
+ clientUserId: string;
+ persistedSignature: string | null;
+};
+
+/**
+ * Returns `null` when there is no usable `clientUserId` or the organisation
+ * isn't entitled, so the client knows not to attempt writes.
+ *
+ * Never throws: persistence is an enhancement and must not block signing.
+ */
+export const resolveEmbedSignature = async ({
+ clientUserId: rawClientUserId,
+ teamId,
+ recipientEmail,
+ claimFlags,
+}: ResolveEmbedSignatureOptions): Promise<ResolvedEmbedSignature | null> => {
+ const parsedClientUserId = ZEmbedClientUserIdSchema.safeParse(rawClientUserId);
+
+ if (!parsedClientUserId.success || !isEmbedSignaturePersistenceEnabled(claimFlags)) {
+ return null;
+ }
+
+ const clientUserId = parsedClientUserId.data;
+
+ try {
+ const team = await prisma.team.findFirstOrThrow({
+ where: {
+ id: teamId,
+ },
+ select: {
+ organisationId: true,
+ },
+ });
+
+ const persistedSignature = await getEmbedSignature({
+ organisationId: team.organisationId,
+ email: recipientEmail,
+ clientUserId,
+ });
+
+ return {
+ clientUserId,
+ persistedSignature,
+ };
+ } catch (error) {
+ logger.warn({ msg: 'Failed to resolve persisted embed signature', teamId, error });
+
+ return null;
+ }
+};
diff --git a/packages/lib/server-only/embedding/upsert-embed-signature.ts b/packages/lib/server-only/embedding/upsert-embed-signature.ts
new file mode 100644
index 000000000..638cd206a
--- /dev/null
+++ b/packages/lib/server-only/embedding/upsert-embed-signature.ts
@@ -0,0 +1,68 @@
+import { prisma } from '@documenso/prisma';
+
+import { AppError, AppErrorCode } from '../../errors/app-error';
+import { createEmbedSignatureKey } from './create-embed-signature-key';
+
+// `clientUserId` is caller-chosen, so without this a single recipient token
+// could mint unlimited rows by cycling identifiers. Best-effort under
+// concurrency; the rate limit bounds any overshoot.
+export const EMBED_SIGNATURES_PER_RECIPIENT_LIMIT = 5;
+
+export type UpsertEmbedSignatureOptions = {
+ organisationId: string;
+ recipientId: number;
+ email: string;
+ clientUserId: string;
+ signature: string;
+};
+
+export const upsertEmbedSignature = async ({
+ organisationId,
+ recipientId,
+ email,
+ clientUserId,
+ signature,
+}: UpsertEmbedSignatureOptions) => {
+ const key = createEmbedSignatureKey({ organisationId, email, clientUserId });
+
+ await prisma.$transaction(async (tx) => {
+ const existing = await tx.embedSignature.findUnique({
+ where: {
+ key,
+ },
+ select: {
+ key: true,
+ },
+ });
+
+ if (!existing) {
+ const count = await tx.embedSignature.count({
+ where: {
+ recipientId,
+ },
+ });
+
+ if (count >= EMBED_SIGNATURES_PER_RECIPIENT_LIMIT) {
+ throw new AppError(AppErrorCode.LIMIT_EXCEEDED, {
+ message: 'Too many persisted signatures for this recipient',
+ });
+ }
+ }
+
+ await tx.embedSignature.upsert({
+ where: {
+ key,
+ },
+ create: {
+ key,
+ organisationId,
+ recipientId,
+ signature,
+ },
+ update: {
+ recipientId,
+ signature,
+ },
+ });
+ });
+};
diff --git a/packages/lib/server-only/rate-limit/rate-limits.ts b/packages/lib/server-only/rate-limit/rate-limits.ts
index 89714475b..414843556 100644
--- a/packages/lib/server-only/rate-limit/rate-limits.ts
+++ b/packages/lib/server-only/rate-limit/rate-limits.ts
@@ -98,6 +98,15 @@ export const reportSenderRateLimit = createRateLimit({
window: '7d',
});
+// ---- Embedding ----
+
+export const persistEmbedSignatureRateLimit = createRateLimit({
+ action: 'embed.persist-signature',
+ max: 10,
+ globalMax: 30,
+ window: '1m',
+});
+
// ---- Billing ----
export const syncSubscriptionRateLimit = createRateLimit({
diff --git a/packages/lib/types/embed-signature.ts b/packages/lib/types/embed-signature.ts
new file mode 100644
index 000000000..c38941cb3
--- /dev/null
+++ b/packages/lib/types/embed-signature.ts
@@ -0,0 +1,3 @@
+import { z } from 'zod';
+
+export const ZEmbedClientUserIdSchema = z.string().trim().min(1).max(128);
diff --git a/packages/lib/utils/billing.ts b/packages/lib/utils/billing.ts
index 426ff43f3..ecdef15d6 100644
--- a/packages/lib/utils/billing.ts
+++ b/packages/lib/utils/billing.ts
@@ -3,7 +3,7 @@ import { OrganisationType } from '@prisma/client';
import { IS_BILLING_ENABLED } from '../constants/app';
import { AppError, AppErrorCode } from '../errors/app-error';
-import { INTERNAL_CLAIM_ID } from '../types/subscription';
+import { INTERNAL_CLAIM_ID, type TClaimFlags } from '../types/subscription';
/**
* Throws an error if billing is enabled and no subscription is found.
@@ -56,3 +56,7 @@ export const isOrganisationPendingPayment = (organisation: PendingPaymentOrganis
return organisation.organisationClaim.originalSubscriptionClaimId === INTERNAL_CLAIM_ID.FREE;
};
+
+export const isEmbedSignaturePersistenceEnabled = (flags: TClaimFlags) => {
+ return !IS_BILLING_ENABLED() || flags.embedSigningWhiteLabel === true;
+};
diff --git a/packages/prisma/migrations/20261019120000_add_embed_signature/migration.sql b/packages/prisma/migrations/20261019120000_add_embed_signature/migration.sql
new file mode 100644
index 000000000..4b17ebcb9
--- /dev/null
+++ b/packages/prisma/migrations/20261019120000_add_embed_signature/migration.sql
@@ -0,0 +1,20 @@
+-- CreateTable
+CREATE TABLE "EmbedSignature" (
+ "key" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+ "organisationId" TEXT NOT NULL,
+ "recipientId" INTEGER NOT NULL,
+ "signature" TEXT NOT NULL,
+
+ CONSTRAINT "EmbedSignature_pkey" PRIMARY KEY ("key")
+);
+
+-- CreateIndex
+CREATE INDEX "EmbedSignature_organisationId_idx" ON "EmbedSignature"("organisationId");
+
+-- CreateIndex
+CREATE INDEX "EmbedSignature_recipientId_idx" ON "EmbedSignature"("recipientId");
+
+-- AddForeignKey
+ALTER TABLE "EmbedSignature" ADD CONSTRAINT "EmbedSignature_organisationId_fkey" FOREIGN KEY ("organisationId") REFERENCES "Organisation"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prisma
index ef2ca786a..5ea6326cd 100644
--- a/packages/prisma/schema.prisma
+++ b/packages/prisma/schema.prisma
@@ -850,6 +850,8 @@ model Organisation {
monthlyStats OrganisationMonthlyStat[]
+ embedSignatures EmbedSignature[]
+
avatarImage AvatarImage? @relation(fields: [avatarImageId], references: [id], onDelete: SetNull)
ownerUserId Int
@@ -1277,6 +1279,26 @@ model Counter {
value Int
}
+/// `key` is sha256(organisationId:lower(recipientEmail):clientUserId) so neither
+/// the recipient email nor the embedder's identifier is stored in plaintext.
+model EmbedSignature {
+ key String @id
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ organisationId String
+ organisation Organisation @relation(fields: [organisationId], references: [id], onDelete: Cascade)
+
+ /// Last writer. Not a relation so the row survives document deletion and
+ /// remains useful for abuse tracing.
+ recipientId Int
+
+ signature String
+
+ @@index([organisationId])
+ @@index([recipientId])
+}
+
model RateLimit {
key String
action String
diff --git a/packages/trpc/server/embedding-router/_router.ts b/packages/trpc/server/embedding-router/_router.ts
index eeecd23ac..75ef7ba05 100644
--- a/packages/trpc/server/embedding-router/_router.ts
+++ b/packages/trpc/server/embedding-router/_router.ts
@@ -4,6 +4,7 @@ import { createEmbeddingEnvelopeRoute } from './create-embedding-envelope';
import { createEmbeddingPresignTokenRoute } from './create-embedding-presign-token';
import { createEmbeddingTemplateRoute } from './create-embedding-template';
import { getMultiSignDocumentRoute } from './get-multi-sign-document';
+import { persistEmbedSignatureRoute } from './persist-embed-signature';
import { updateEmbeddingDocumentRoute } from './update-embedding-document';
import { updateEmbeddingEnvelopeRoute } from './update-embedding-envelope';
import { updateEmbeddingTemplateRoute } from './update-embedding-template';
@@ -19,4 +20,5 @@ export const embeddingPresignRouter = router({
updateEmbeddingDocument: updateEmbeddingDocumentRoute,
updateEmbeddingTemplate: updateEmbeddingTemplateRoute,
getMultiSignDocument: getMultiSignDocumentRoute,
+ persistEmbedSignature: persistEmbedSignatureRoute,
});
diff --git a/packages/trpc/server/embedding-router/persist-embed-signature.ts b/packages/trpc/server/embedding-router/persist-embed-signature.ts
new file mode 100644
index 000000000..9f1922e7a
--- /dev/null
+++ b/packages/trpc/server/embedding-router/persist-embed-signature.ts
@@ -0,0 +1,80 @@
+import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
+import { getEmbedSignatureSettingsByTeamId } from '@documenso/lib/server-only/embedding/get-embed-signature-settings';
+import { upsertEmbedSignature } from '@documenso/lib/server-only/embedding/upsert-embed-signature';
+import { assertRateLimit } from '@documenso/lib/server-only/rate-limit/rate-limit-middleware';
+import { persistEmbedSignatureRateLimit } from '@documenso/lib/server-only/rate-limit/rate-limits';
+import { isRecipientExpired } from '@documenso/lib/utils/recipients';
+import { prisma } from '@documenso/prisma';
+import { DocumentStatus, EnvelopeType, SigningStatus } from '@prisma/client';
+
+import { procedure } from '../trpc';
+import {
+ ZPersistEmbedSignatureRequestSchema,
+ ZPersistEmbedSignatureResponseSchema,
+} from './persist-embed-signature.types';
+
+export const persistEmbedSignatureRoute = procedure
+ .input(ZPersistEmbedSignatureRequestSchema)
+ .output(ZPersistEmbedSignatureResponseSchema)
+ .mutation(async ({ input, ctx: { metadata } }) => {
+ const { token, clientUserId, signature } = input;
+
+ const recipient = await prisma.recipient.findFirst({
+ where: {
+ token,
+ signingStatus: SigningStatus.NOT_SIGNED,
+ envelope: {
+ type: EnvelopeType.DOCUMENT,
+ status: DocumentStatus.PENDING,
+ deletedAt: null,
+ },
+ },
+ select: {
+ id: true,
+ email: true,
+ expiresAt: true,
+ envelope: {
+ select: {
+ teamId: true,
+ },
+ },
+ },
+ });
+
+ if (!recipient || isRecipientExpired(recipient)) {
+ throw new AppError(AppErrorCode.NOT_FOUND, {
+ message: 'Recipient not found',
+ });
+ }
+
+ const { organisationId, isEnabled } = await getEmbedSignatureSettingsByTeamId({
+ teamId: recipient.envelope.teamId,
+ });
+
+ if (!isEnabled) {
+ throw new AppError(AppErrorCode.UNAUTHORIZED, {
+ message: 'Persisted embed signatures are not enabled for this organisation',
+ });
+ }
+
+ // Per recipient rather than per organisation so one token holder can't
+ // exhaust a budget shared with other signers.
+ const rateLimitResult = await persistEmbedSignatureRateLimit.check({
+ ip: metadata.requestMetadata.ipAddress ?? 'unknown',
+ identifier: `recipient:${recipient.id}`,
+ });
+
+ assertRateLimit(rateLimitResult);
+
+ await upsertEmbedSignature({
+ organisationId,
+ recipientId: recipient.id,
+ email: recipient.email,
+ clientUserId,
+ signature,
+ });
+
+ return {
+ success: true,
+ };
+ });
diff --git a/packages/trpc/server/embedding-router/persist-embed-signature.types.ts b/packages/trpc/server/embedding-router/persist-embed-signature.types.ts
new file mode 100644
index 000000000..a19c8b0ed
--- /dev/null
+++ b/packages/trpc/server/embedding-router/persist-embed-signature.types.ts
@@ -0,0 +1,40 @@
+import { isBase64Image, isPngSignatureDataUrl } from '@documenso/lib/constants/signatures';
+import { ZEmbedClientUserIdSchema } from '@documenso/lib/types/embed-signature';
+import { z } from 'zod';
+
+const IMAGE_SIGNATURE_MAX_LENGTH = 1024 * 1024;
+const TYPED_SIGNATURE_MAX_LENGTH = 256;
+
+// Unicode "Other" category: control characters, format characters, unassigned
+// code points and surrogates. None can be produced by the signature pad input.
+const CONTROL_CHARACTER_REGEX = /\p{C}/u;
+
+const ZEmbedSignatureValueSchema = z
+ .string()
+ .min(1)
+ .max(IMAGE_SIGNATURE_MAX_LENGTH)
+ .refine(
+ (value) => {
+ if (isBase64Image(value)) {
+ return isPngSignatureDataUrl(value);
+ }
+
+ return value.length <= TYPED_SIGNATURE_MAX_LENGTH && !CONTROL_CHARACTER_REGEX.test(value);
+ },
+ {
+ message: 'Signature must be a PNG data URL or a short typed signature',
+ },
+ );
+
+export const ZPersistEmbedSignatureRequestSchema = z.object({
+ token: z.string().min(1),
+ clientUserId: ZEmbedClientUserIdSchema,
+ signature: ZEmbedSignatureValueSchema,
+});
+
+export const ZPersistEmbedSignatureResponseSchema = z.object({
+ success: z.literal(true),
+});
+
+export type TPersistEmbedSignatureRequestSchema = z.infer<typeof ZPersistEmbedSignatureRequestSchema>;
+export type TPersistEmbedSignatureResponseSchema = z.infer<typeof ZPersistEmbedSignatureResponseSchema>;