Compare commits

..

6 Commits

Author SHA1 Message Date
Ephraim Atta-Duncan 357017314d feat: add digitized signatures 2025-08-19 08:48:04 +00:00
David Nguyen a51110d276 fix: prevent document unsigning on edit (#1963) 2025-08-18 13:48:51 +10:00
David Nguyen 7f81231467 fix: template e2e tests (#1969) 2025-08-18 12:42:36 +10:00
Lucas Smith 439262fd02 v1.12.2-rc.4 2025-08-16 19:16:29 +10:00
Lucas Smith 93a184355b chore: add translations (#1955) 2025-08-16 19:10:21 +10:00
David Nguyen 1dea0b8fab add dummy teamid (#1968) 2025-08-16 19:09:21 +10:00
51 changed files with 2197 additions and 1902 deletions
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from 'react';
import { useEffect, useState } from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import { Trans } from '@lingui/react/macro';
@@ -6,9 +6,9 @@ import { RecipientRole } from '@prisma/client';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { AppError } from '@documenso/lib/errors/app-error';
import { DocumentAuth, type TRecipientActionAuth } from '@documenso/lib/types/document-auth';
import { trpc } from '@documenso/trpc/react';
import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';
import { Alert, AlertDescription, AlertTitle } from '@documenso/ui/primitives/alert';
import { Button } from '@documenso/ui/primitives/button';
import { DialogFooter } from '@documenso/ui/primitives/dialog';
import {
@@ -20,8 +20,6 @@ import {
FormMessage,
} from '@documenso/ui/primitives/form/form';
import { PinInput, PinInputGroup, PinInputSlot } from '@documenso/ui/primitives/pin-input';
import { Tabs, TabsList, TabsTrigger } from '@documenso/ui/primitives/tabs';
import { useToast } from '@documenso/ui/primitives/use-toast';
import { EnableAuthenticatorAppDialog } from '~/components/forms/2fa/enable-authenticator-app-dialog';
@@ -53,7 +51,6 @@ export const DocumentSigningAuth2FA = ({
}: DocumentSigningAuth2FAProps) => {
const { recipient, user, isCurrentlyAuthenticating, setIsCurrentlyAuthenticating } =
useRequiredDocumentSigningAuthContext();
const { toast } = useToast();
const form = useForm<T2FAAuthFormSchema>({
resolver: zodResolver(Z2FAAuthFormSchema),
@@ -63,104 +60,27 @@ export const DocumentSigningAuth2FA = ({
});
const [is2FASetupSuccessful, setIs2FASetupSuccessful] = useState(false);
const [isEmailCodeSent, setIsEmailCodeSent] = useState(false);
const [isEmailCodeSending, setIsEmailCodeSending] = useState(false);
const [canResendEmail, setCanResendEmail] = useState(true);
const [resendCountdown, setResendCountdown] = useState(0);
const countdownTimerRef = useRef<NodeJS.Timeout | null>(null);
const [verificationMethod, setVerificationMethod] = useState<'app' | 'email'>(
user?.twoFactorEnabled ? 'app' : 'email',
);
const emailSendInitiatedRef = useRef(false);
const sendVerificationMutation = trpc.auth.sendEmailVerification.useMutation({
onSuccess: () => {
setIsEmailCodeSent(true);
setCanResendEmail(false);
setResendCountdown(60);
countdownTimerRef.current = setInterval(() => {
setResendCountdown((prev) => {
if (prev <= 1) {
if (countdownTimerRef.current) {
clearInterval(countdownTimerRef.current);
}
setCanResendEmail(true);
return 0;
}
return prev - 1;
});
}, 1000);
toast({
title: 'Verification code sent',
description: `A verification code has been sent to ${recipient.email}`,
});
},
onError: (error) => {
console.error('Failed to send verification code', error);
toast({
title: 'Failed to send verification code',
description: 'Please try again or contact support',
variant: 'destructive',
});
},
onSettled: () => {
setIsEmailCodeSending(false);
},
});
const verifyCodeMutation = trpc.auth.verifyEmailCode.useMutation();
const sendEmailVerificationCode = async () => {
try {
setIsEmailCodeSending(true);
await sendVerificationMutation.mutateAsync({
recipientId: recipient.id,
});
} catch (error) {
toast({
title: 'Failed to send verification code',
description: 'Please try again.',
variant: 'destructive',
});
}
};
useEffect(() => {
return () => {
if (countdownTimerRef.current) {
clearInterval(countdownTimerRef.current);
}
};
}, []);
const [formErrorCode, setFormErrorCode] = useState<string | null>(null);
const onFormSubmit = async ({ token }: T2FAAuthFormSchema) => {
try {
setIsCurrentlyAuthenticating(true);
if (verificationMethod === 'email') {
await verifyCodeMutation.mutateAsync({
code: token,
recipientId: recipient.id,
});
}
await onReauthFormSubmit({
type: DocumentAuth.TWO_FACTOR_AUTH,
token,
});
setIsCurrentlyAuthenticating(false);
onOpenChange(false);
} catch (err) {
setIsCurrentlyAuthenticating(false);
toast({
title: 'Unauthorized',
description: 'We were unable to verify your details.',
variant: 'destructive',
});
const error = AppError.parseError(err);
setFormErrorCode(error.code);
// Todo: Alert.
}
};
@@ -170,46 +90,21 @@ export const DocumentSigningAuth2FA = ({
});
setIs2FASetupSuccessful(false);
setIsEmailCodeSent(false);
setFormErrorCode(null);
if (open && !user?.twoFactorEnabled) {
setVerificationMethod('email');
}
}, [open, user?.twoFactorEnabled, form]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
useEffect(() => {
if (!open || verificationMethod !== 'email') {
emailSendInitiatedRef.current = false;
}
}, [open, verificationMethod]);
useEffect(() => {
if (open && verificationMethod === 'email' && !isEmailCodeSent && !isEmailCodeSending) {
if (!emailSendInitiatedRef.current) {
emailSendInitiatedRef.current = true;
void sendEmailVerificationCode();
}
}
}, [open, verificationMethod, isEmailCodeSent, isEmailCodeSending]);
if (verificationMethod === 'app' && !user?.twoFactorEnabled && !is2FASetupSuccessful) {
if (!user?.twoFactorEnabled && !is2FASetupSuccessful) {
return (
<div className="space-y-4">
<Tabs
value={verificationMethod}
onValueChange={(val) => setVerificationMethod(val as 'app' | 'email')}
>
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="app">Authenticator App</TabsTrigger>
<TabsTrigger value="email">Email Verification</TabsTrigger>
</TabsList>
</Tabs>
<Alert variant="warning">
<AlertDescription>
<p>
{recipient.role === RecipientRole.VIEWER && actionTarget === 'DOCUMENT' ? (
<Trans>You need to setup 2FA to mark this document as viewed.</Trans>
) : (
// Todo: Translate
`You need to setup 2FA to ${actionVerb.toLowerCase()} this ${actionTarget.toLowerCase()}.`
)}
</p>
@@ -234,106 +129,59 @@ export const DocumentSigningAuth2FA = ({
}
return (
<div className="space-y-4">
{user?.twoFactorEnabled && (
<Tabs
value={verificationMethod}
onValueChange={(val) => setVerificationMethod(val as 'app' | 'email')}
>
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="app">Authenticator App</TabsTrigger>
<TabsTrigger value="email">Email Verification</TabsTrigger>
</TabsList>
</Tabs>
)}
<Form {...form}>
<form onSubmit={form.handleSubmit(onFormSubmit)}>
<fieldset disabled={isCurrentlyAuthenticating}>
<div className="space-y-4">
<FormField
control={form.control}
name="token"
render={({ field }) => (
<FormItem>
<FormLabel required>2FA token</FormLabel>
{verificationMethod === 'email' && (
<Alert variant="secondary">
<AlertDescription>
{isEmailCodeSent ? (
<p>
<Trans>
A verification code has been sent to {recipient.email}. Please enter it below to
continue.
</Trans>
</p>
) : (
<p>
<Trans>
We'll send a verification code to {recipient.email} to verify your identity.
</Trans>
</p>
)}
</AlertDescription>
</Alert>
)}
<FormControl>
<PinInput {...field} value={field.value ?? ''} maxLength={6}>
{Array(6)
.fill(null)
.map((_, i) => (
<PinInputGroup key={i}>
<PinInputSlot index={i} />
</PinInputGroup>
))}
</PinInput>
</FormControl>
<Form {...form}>
<form onSubmit={form.handleSubmit(onFormSubmit)}>
<fieldset disabled={isCurrentlyAuthenticating}>
<div className="space-y-4">
<FormField
control={form.control}
name="token"
render={({ field }) => (
<FormItem>
<FormLabel required>
{verificationMethod === 'app' ? (
<Trans>2FA token</Trans>
) : (
<Trans>Verification code</Trans>
)}
</FormLabel>
<FormControl>
<PinInput {...field} value={field.value ?? ''} maxLength={6}>
{Array(6)
.fill(null)
.map((_, i) => (
<PinInputGroup key={i}>
<PinInputSlot index={i} />
</PinInputGroup>
))}
</PinInput>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{verificationMethod === 'email' && (
<div className="flex justify-center">
<Button
type="button"
variant="link"
disabled={isEmailCodeSending || !canResendEmail}
onClick={() => void sendEmailVerificationCode()}
>
{isEmailCodeSending ? (
<Trans>Sending...</Trans>
) : !canResendEmail ? (
<Trans>Resend code ({resendCountdown}s)</Trans>
) : (
<Trans>Resend code</Trans>
)}
</Button>
</div>
<FormMessage />
</FormItem>
)}
/>
<DialogFooter>
<Button type="button" variant="secondary" onClick={() => onOpenChange(false)}>
<Trans>Cancel</Trans>
</Button>
{formErrorCode && (
<Alert variant="destructive">
<AlertTitle>
<Trans>Unauthorized</Trans>
</AlertTitle>
<AlertDescription>
<Trans>
We were unable to verify your details. Please try again or contact support
</Trans>
</AlertDescription>
</Alert>
)}
<Button type="submit" loading={isCurrentlyAuthenticating}>
<Trans>{actionTarget === 'DOCUMENT' ? 'Sign Document' : 'Sign Field'}</Trans>
</Button>
</DialogFooter>
</div>
</fieldset>
</form>
</Form>
</div>
<DialogFooter>
<Button type="button" variant="secondary" onClick={() => onOpenChange(false)}>
<Trans>Cancel</Trans>
</Button>
<Button type="submit" loading={isCurrentlyAuthenticating}>
<Trans>Sign</Trans>
</Button>
</DialogFooter>
</div>
</fieldset>
</form>
</Form>
);
};
@@ -43,7 +43,6 @@ export const DocumentSigningAuthDialog = ({
title,
description,
availableAuthTypes,
actionTarget,
open,
onOpenChange,
onReauthFormSubmit,
@@ -108,32 +107,15 @@ export const DocumentSigningAuthDialog = ({
>
<ChevronLeftIcon className="h-4 w-4" />
</Button>
<span>
{title ||
(actionTarget === 'DOCUMENT' ? (
<Trans>Sign document</Trans>
) : (
<Trans>Sign field</Trans>
))}
</span>
<span>{title || <Trans>Sign field</Trans>}</span>
</div>
)}
{(!selectedAuthType || validAuthTypes.length === 1) &&
(title ||
(actionTarget === 'DOCUMENT' ? (
<Trans>Sign document</Trans>
) : (
<Trans>Sign field</Trans>
)))}
(title || <Trans>Sign field</Trans>)}
</DialogTitle>
<DialogDescription>
{description || (
<Trans>
Reauthentication is required to sign this{' '}
{actionTarget === 'DOCUMENT' ? 'document' : 'field'}
</Trans>
)}
{description || <Trans>Reauthentication is required to sign this field</Trans>}
</DialogDescription>
</DialogHeader>
@@ -198,7 +180,6 @@ export const DocumentSigningAuthDialog = ({
))
.with({ documentAuthType: DocumentAuth.TWO_FACTOR_AUTH }, () => (
<DocumentSigningAuth2FA
actionTarget={actionTarget === 'DOCUMENT' ? 'DOCUMENT' : 'FIELD'}
open={open}
onOpenChange={onOpenChange}
onReauthFormSubmit={onReauthFormSubmit}
@@ -42,7 +42,6 @@ export type DocumentSigningAuthContextValue = {
setPreferredPasskeyId: (_value: string | null) => void;
user?: SessionUser | null;
refetchPasskeys: () => Promise<void>;
isEnterprise: boolean;
};
const DocumentSigningAuthContext = createContext<DocumentSigningAuthContextValue | null>(null);
@@ -66,7 +65,6 @@ export interface DocumentSigningAuthProviderProps {
recipient: Recipient;
user?: SessionUser | null;
children: React.ReactNode;
isEnterprise: boolean;
}
export const DocumentSigningAuthProvider = ({
@@ -74,7 +72,6 @@ export const DocumentSigningAuthProvider = ({
recipient: initialRecipient,
user,
children,
isEnterprise,
}: DocumentSigningAuthProviderProps) => {
const [documentAuthOptions, setDocumentAuthOptions] = useState(initialDocumentAuthOptions);
const [recipient, setRecipient] = useState(initialRecipient);
@@ -147,13 +144,8 @@ export const DocumentSigningAuthProvider = ({
}, [derivedRecipientActionAuth, user, recipient]);
const executeActionAuthProcedure = async (options: ExecuteActionAuthProcedureOptions) => {
// Determine if authentication is required based on enterprise status and action target.
const requiresAuthTrigger = isEnterprise
? derivedRecipientActionAuth && options.actionTarget === FieldType.SIGNATURE
: derivedRecipientActionAuth && options.actionTarget === 'DOCUMENT';
// Directly run callback if no auth trigger is needed.
if (!requiresAuthTrigger) {
// Directly run callback if no auth required.
if (!derivedRecipientActionAuth || options.actionTarget !== FieldType.SIGNATURE) {
await options.onReauthFormSubmit();
return;
}
@@ -213,7 +205,6 @@ export const DocumentSigningAuthProvider = ({
preferredPasskeyId,
setPreferredPasskeyId,
refetchPasskeys,
isEnterprise,
}}
>
{children}
@@ -234,8 +225,6 @@ export const DocumentSigningAuthProvider = ({
type ExecuteActionAuthProcedureOptions = Omit<
DocumentSigningAuthDialogProps,
'open' | 'onOpenChange' | 'documentAuthType' | 'recipientRole' | 'availableAuthTypes'
> & {
actionTarget: FieldType | 'DOCUMENT';
};
>;
DocumentSigningAuthProvider.displayName = 'DocumentSigningAuthProvider';
@@ -27,7 +27,6 @@ import {
AssistantConfirmationDialog,
type NextSigner,
} from '../../dialogs/assistant-confirmation-dialog';
import { useRequiredDocumentSigningAuthContext } from './document-signing-auth-provider';
import { DocumentSigningCompleteDialog } from './document-signing-complete-dialog';
import { useRequiredDocumentSigningContext } from './document-signing-provider';
@@ -39,7 +38,6 @@ export type DocumentSigningFormProps = {
isRecipientsTurn: boolean;
allRecipients?: RecipientWithFields[];
setSelectedSignerId?: (id: number | null) => void;
isEnterprise: boolean;
};
export const DocumentSigningForm = ({
@@ -50,7 +48,6 @@ export const DocumentSigningForm = ({
isRecipientsTurn,
allRecipients = [],
setSelectedSignerId,
isEnterprise,
}: DocumentSigningFormProps) => {
const { sessionData } = useOptionalSession();
const user = sessionData?.user;
@@ -64,7 +61,6 @@ export const DocumentSigningForm = ({
const assistantSignersId = useId();
const { fullName, signature, setFullName, setSignature } = useRequiredDocumentSigningContext();
const { executeActionAuthProcedure } = useRequiredDocumentSigningAuthContext();
const [validateUninsertedFields, setValidateUninsertedFields] = useState(false);
const [isConfirmationDialogOpen, setIsConfirmationDialogOpen] = useState(false);
@@ -117,16 +113,11 @@ export const DocumentSigningForm = ({
setIsAssistantSubmitting(true);
try {
await executeActionAuthProcedure({
actionTarget: 'DOCUMENT',
onReauthFormSubmit: async (authOptions) => {
await completeDocument(authOptions, nextSigner);
},
});
await completeDocument(undefined, nextSigner);
} catch (err) {
toast({
title: _(msg`Error`),
description: _(msg`An error occurred while completing the document. Please try again.`),
title: 'Error',
description: 'An error occurred while completing the document. Please try again.',
variant: 'destructive',
});
@@ -216,12 +207,7 @@ export const DocumentSigningForm = ({
fields={fields}
fieldsValidated={fieldsValidated}
onSignatureComplete={async (nextSigner) => {
await executeActionAuthProcedure({
actionTarget: 'DOCUMENT',
onReauthFormSubmit: async (authOptions) => {
await completeDocument(authOptions, nextSigner);
},
});
await completeDocument(undefined, nextSigner);
}}
role={recipient.role}
allowDictateNextSigner={document.documentMeta?.allowDictateNextSigner}
@@ -381,12 +367,7 @@ export const DocumentSigningForm = ({
fieldsValidated={fieldsValidated}
disabled={!isRecipientsTurn}
onSignatureComplete={async (nextSigner) => {
await executeActionAuthProcedure({
actionTarget: 'DOCUMENT',
onReauthFormSubmit: async (authOptions) => {
await completeDocument(authOptions, nextSigner);
},
});
await completeDocument(undefined, nextSigner);
}}
role={recipient.role}
allowDictateNextSigner={
@@ -50,7 +50,6 @@ export type DocumentSigningPageViewProps = {
isRecipientsTurn: boolean;
allRecipients?: RecipientWithFields[];
includeSenderDetails: boolean;
isEnterprise: boolean;
};
export const DocumentSigningPageView = ({
@@ -61,7 +60,6 @@ export const DocumentSigningPageView = ({
isRecipientsTurn,
allRecipients = [],
includeSenderDetails,
isEnterprise,
}: DocumentSigningPageViewProps) => {
const { documentData, documentMeta } = document;
@@ -210,7 +208,6 @@ export const DocumentSigningPageView = ({
isRecipientsTurn={isRecipientsTurn}
allRecipients={allRecipients}
setSelectedSignerId={setSelectedSignerId}
isEnterprise={isEnterprise}
/>
</div>
</div>
@@ -36,6 +36,7 @@ export type DocumentSigningSignatureFieldProps = {
typedSignatureEnabled?: boolean;
uploadSignatureEnabled?: boolean;
drawSignatureEnabled?: boolean;
keyboardSignatureEnabled?: boolean;
};
export const DocumentSigningSignatureField = ({
@@ -45,6 +46,7 @@ export const DocumentSigningSignatureField = ({
typedSignatureEnabled,
uploadSignatureEnabled,
drawSignatureEnabled,
keyboardSignatureEnabled,
}: DocumentSigningSignatureFieldProps) => {
const { _ } = useLingui();
const { toast } = useToast();
@@ -283,6 +285,7 @@ export const DocumentSigningSignatureField = ({
typedSignatureEnabled={typedSignatureEnabled}
uploadSignatureEnabled={uploadSignatureEnabled}
drawSignatureEnabled={drawSignatureEnabled}
keyboardSignatureEnabled={keyboardSignatureEnabled}
/>
<DocumentSigningDisclosure />
@@ -157,7 +157,7 @@ export const TemplateEditForm = ({
toast({
title: _(msg`Error`),
description: _(msg`An error occurred while updating the template settings.`),
description: _(msg`An error occurred while updating the document settings.`),
variant: 'destructive',
});
}
@@ -9,10 +9,10 @@ import { trpc } from '@documenso/trpc/react';
import { Avatar, AvatarFallback, AvatarImage } from '@documenso/ui/primitives/avatar';
import { FolderGrid } from '~/components/general/folder/folder-grid';
import { TemplateDropZoneWrapper } from '~/components/general/template/template-drop-zone-wrapper';
import { TemplatesTable } from '~/components/tables/templates-table';
import { useCurrentTeam } from '~/providers/team';
import { appMetaTags } from '~/utils/meta';
import { TemplateDropZoneWrapper } from '~/components/general/template/template-drop-zone-wrapper';
export function meta() {
return appMetaTags('Templates');
@@ -94,7 +94,6 @@ export default function DirectTemplatePage() {
documentAuthOptions={template.authOptions}
recipient={directTemplateRecipient}
user={user}
isEnterprise={false}
>
<div className="mx-auto -mt-4 w-full max-w-screen-xl px-4 md:px-8">
<h1
@@ -19,7 +19,6 @@ import { getRecipientSignatures } from '@documenso/lib/server-only/recipient/get
import { getRecipientsForAssistant } from '@documenso/lib/server-only/recipient/get-recipients-for-assistant';
import { getTeamSettings } from '@documenso/lib/server-only/team/get-team-settings';
import { getUserByEmail } from '@documenso/lib/server-only/user/get-user-by-email';
import { isUserEnterprise } from '@documenso/lib/server-only/user/is-user-enterprise';
import { extractDocumentAuthMethods } from '@documenso/lib/utils/document-auth';
import { SigningCard3D } from '@documenso/ui/components/signing-card';
@@ -42,10 +41,6 @@ export async function loader({ params, request }: Route.LoaderArgs) {
throw new Response('Not Found', { status: 404 });
}
const isEnterprise = user?.id
? await isUserEnterprise({ userId: user.id }).catch(() => false)
: false;
const [document, recipient, fields, completedFields] = await Promise.all([
getDocumentAndSenderByToken({
token,
@@ -121,7 +116,6 @@ export async function loader({ params, request }: Route.LoaderArgs) {
isDocumentAccessValid: false,
recipientEmail: recipient.email,
recipientHasAccount,
isEnterprise,
} as const);
}
@@ -159,7 +153,6 @@ export async function loader({ params, request }: Route.LoaderArgs) {
recipientSignature,
isRecipientsTurn,
includeSenderDetails: settings.includeSenderDetails,
isEnterprise,
} as const);
}
@@ -188,7 +181,6 @@ export default function SigningPage() {
allRecipients,
includeSenderDetails,
recipientWithFields,
isEnterprise,
} = data;
if (document.deletedAt || document.status === DocumentStatus.REJECTED) {
@@ -254,7 +246,6 @@ export default function SigningPage() {
documentAuthOptions={document.authOptions}
recipient={recipient}
user={user}
isEnterprise={isEnterprise}
>
<DocumentSigningPageView
recipient={recipientWithFields}
@@ -264,7 +255,6 @@ export default function SigningPage() {
isRecipientsTurn={isRecipientsTurn}
allRecipients={allRecipients}
includeSenderDetails={includeSenderDetails}
isEnterprise={isEnterprise}
/>
</DocumentSigningAuthProvider>
</DocumentSigningProvider>
@@ -88,8 +88,6 @@ export async function loader({ params, request }: Route.LoaderArgs) {
const fields = template.fields.filter((field) => field.recipientId === directTemplateRecipientId);
const isEnterpriseDocument = Boolean(organisationClaim);
return superLoaderJson({
token,
user,
@@ -98,21 +96,12 @@ export async function loader({ params, request }: Route.LoaderArgs) {
fields,
hidePoweredBy,
allowEmbedSigningWhitelabel,
isEnterpriseDocument,
});
}
export default function EmbedDirectTemplatePage() {
const {
token,
user,
template,
recipient,
fields,
hidePoweredBy,
allowEmbedSigningWhitelabel,
isEnterpriseDocument,
} = useSuperLoaderData<typeof loader>();
const { token, user, template, recipient, fields, hidePoweredBy, allowEmbedSigningWhitelabel } =
useSuperLoaderData<typeof loader>();
return (
<DocumentSigningProvider
@@ -127,7 +116,6 @@ export default function EmbedDirectTemplatePage() {
documentAuthOptions={template.authOptions}
recipient={recipient}
user={user}
isEnterprise={isEnterpriseDocument}
>
<DocumentSigningRecipientProvider recipient={recipient}>
<EmbedDirectTemplateClientPage
@@ -109,8 +109,6 @@ export async function loader({ params, request }: Route.LoaderArgs) {
})
: [];
const isEnterpriseDocument = Boolean(organisationClaim);
return superLoaderJson({
token,
user,
@@ -121,7 +119,6 @@ export async function loader({ params, request }: Route.LoaderArgs) {
completedFields,
hidePoweredBy,
allowEmbedSigningWhitelabel,
isEnterpriseDocument,
});
}
@@ -136,7 +133,6 @@ export default function EmbedSignDocumentPage() {
completedFields,
hidePoweredBy,
allowEmbedSigningWhitelabel,
isEnterpriseDocument,
} = useSuperLoaderData<typeof loader>();
return (
@@ -152,7 +148,6 @@ export default function EmbedSignDocumentPage() {
documentAuthOptions={document.authOptions}
recipient={recipient}
user={user}
isEnterprise={isEnterpriseDocument}
>
<EmbedSignDocumentClientPage
token={token}
@@ -48,7 +48,6 @@ export async function loader({ request }: Route.LoaderArgs) {
user,
hidePoweredBy: false,
allowWhitelabelling: false,
isEnterprise: false,
});
}
@@ -56,19 +55,17 @@ export async function loader({ request }: Route.LoaderArgs) {
const allowWhitelabelling = organisationClaim.flags.embedSigningWhiteLabel;
const hidePoweredBy = organisationClaim.flags.hidePoweredBy;
const isEnterprise = Boolean(organisationClaim.flags.cfr21);
return superLoaderJson({
envelopes,
user,
hidePoweredBy,
allowWhitelabelling,
isEnterprise,
});
}
export default function MultisignPage() {
const { envelopes, user, hidePoweredBy, allowWhitelabelling, isEnterprise } =
const { envelopes, user, hidePoweredBy, allowWhitelabelling } =
useSuperLoaderData<typeof loader>();
const revalidator = useRevalidator();
@@ -267,7 +264,6 @@ export default function MultisignPage() {
documentAuthOptions={selectedDocument.authOptions}
recipient={selectedRecipient}
user={user}
isEnterprise={isEnterprise}
>
<DocumentSigningRecipientProvider recipient={selectedRecipient} targetSigner={null}>
<MultiSignDocumentSigningView
+1 -1
View File
@@ -101,5 +101,5 @@
"vite-plugin-babel-macros": "^1.0.6",
"vite-tsconfig-paths": "^5.1.4"
},
"version": "1.12.2-rc.3"
"version": "1.12.2-rc.4"
}
+3 -3
View File
@@ -1,12 +1,12 @@
{
"name": "@documenso/root",
"version": "1.12.2-rc.3",
"version": "1.12.2-rc.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@documenso/root",
"version": "1.12.2-rc.3",
"version": "1.12.2-rc.4",
"workspaces": [
"apps/*",
"packages/*"
@@ -89,7 +89,7 @@
},
"apps/remix": {
"name": "@documenso/remix",
"version": "1.12.2-rc.3",
"version": "1.12.2-rc.4",
"dependencies": {
"@documenso/api": "*",
"@documenso/assets": "*",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"private": true,
"version": "1.12.2-rc.3",
"version": "1.12.2-rc.4",
"scripts": {
"build": "turbo run build",
"dev": "turbo run dev --filter=@documenso/remix",
@@ -27,8 +27,8 @@ test('[DOCUMENT_FLOW]: add settings', async ({ page }) => {
await page.getByRole('option').filter({ hasText: 'Require account' }).click();
await expect(page.getByTestId('documentAccessSelectValue')).toContainText('Require account');
// Action auth should now be visible for all users
await expect(page.getByTestId('documentActionSelectValue')).toBeVisible();
// Action auth should NOT be visible.
await expect(page.getByTestId('documentActionSelectValue')).not.toBeVisible();
// Save the settings by going to the next step.
@@ -25,8 +25,8 @@ test('[TEMPLATE_FLOW]: add settings', async ({ page }) => {
await page.getByRole('option').filter({ hasText: 'Require account' }).click();
await expect(page.getByTestId('documentAccessSelectValue')).toContainText('Require account');
// Action auth should now be visible for all users
await expect(page.getByTestId('documentActionSelectValue')).toBeVisible();
// Action auth should NOT be visible.
await expect(page.getByTestId('documentActionSelectValue')).not.toBeVisible();
// Save the settings by going to the next step.
await page.getByRole('button', { name: 'Continue' }).click();
@@ -144,10 +144,11 @@ test('[TEMPLATES]: use template', async ({ page }) => {
await page.getByRole('button', { name: 'Use Template' }).click();
// Enter template values.
await page.getByPlaceholder('recipient.1@documenso.com').click();
await page.getByPlaceholder('recipient.1@documenso.com').fill(teamMemberUser.email);
await page.getByPlaceholder('Recipient 1').click();
await page.getByPlaceholder('Recipient 1').fill('name');
// Get input with Email label placeholder.
await page.getByLabel('Email').click();
await page.getByLabel('Email').fill(teamMemberUser.email);
await page.getByLabel('Name').click();
await page.getByLabel('Name').fill('name');
await page.getByRole('button', { name: 'Create as draft' }).click();
await page.waitForURL(/\/t\/.+\/documents/);
@@ -1,43 +0,0 @@
import { Trans } from '@lingui/react/macro';
import { Section, Text } from '../components';
import { TemplateDocumentImage } from './template-document-image';
export type TemplateVerificationCodeProps = {
verificationCode: string;
assetBaseUrl: string;
};
export const TemplateVerificationCode = ({
verificationCode,
assetBaseUrl,
}: TemplateVerificationCodeProps) => {
return (
<>
<TemplateDocumentImage className="mt-6" assetBaseUrl={assetBaseUrl} />
<Section className="flex-row items-center justify-center">
<Text className="text-primary mx-auto mb-0 max-w-[80%] text-center text-lg font-semibold">
<Trans>Your verification code</Trans>
</Text>
<Text className="my-1 text-center text-base text-slate-400">
<Trans>Please use the code below to verify your identity for document signing.</Trans>
</Text>
<Text className="my-6 text-center text-3xl font-bold tracking-widest">
{verificationCode}
</Text>
<Text className="my-1 text-center text-sm text-slate-400">
<Trans>
If you did not request this code, you can ignore this email. The code will expire after
10 minutes.
</Trans>
</Text>
</Section>
</>
);
};
export default TemplateVerificationCode;
@@ -1,62 +0,0 @@
import { msg } from '@lingui/core/macro';
import { useLingui } from '@lingui/react';
import { Body, Container, Head, Hr, Html, Img, Preview, Section } from '../components';
import { useBranding } from '../providers/branding';
import { TemplateFooter } from '../template-components/template-footer';
import type { TemplateVerificationCodeProps } from '../template-components/template-verification-code';
import { TemplateVerificationCode } from '../template-components/template-verification-code';
export type VerificationCodeTemplateProps = Partial<TemplateVerificationCodeProps>;
export const VerificationCodeTemplate = ({
verificationCode = '000000',
assetBaseUrl = 'http://localhost:3002',
}: VerificationCodeTemplateProps) => {
const { _ } = useLingui();
const branding = useBranding();
const previewText = msg`Your verification code for document signing`;
const getAssetUrl = (path: string) => {
return new URL(path, assetBaseUrl).toString();
};
return (
<Html>
<Head />
<Preview>{_(previewText)}</Preview>
<Body className="mx-auto my-auto font-sans">
<Section className="bg-white">
<Container className="mx-auto mb-2 mt-8 max-w-xl rounded-lg border border-solid border-slate-200 p-2 backdrop-blur-sm">
<Section className="p-2">
{branding.brandingEnabled && branding.brandingLogo ? (
<Img src={branding.brandingLogo} alt="Branding Logo" className="mb-4 h-6" />
) : (
<Img
src={getAssetUrl('/static/logo.png')}
alt="Documenso Logo"
className="mb-4 h-6"
/>
)}
<TemplateVerificationCode
verificationCode={verificationCode}
assetBaseUrl={assetBaseUrl}
/>
</Section>
</Container>
<Hr className="mx-auto mt-12 max-w-xl" />
<Container className="mx-auto max-w-xl">
<TemplateFooter isDocument={false} />
</Container>
</Section>
</Body>
</Html>
);
};
export default VerificationCodeTemplate;
+7
View File
@@ -69,4 +69,11 @@ export const DOCUMENT_SIGNATURE_TYPES = {
}),
value: DocumentSignatureType.UPLOAD,
},
[DocumentSignatureType.KEYBOARD]: {
label: msg({
message: `Keyboard`,
context: `Keyboard signatute type`,
}),
value: DocumentSignatureType.KEYBOARD,
},
} satisfies Record<DocumentSignatureType, DocumentSignatureTypeData>;
@@ -1,120 +0,0 @@
import { createElement } from 'react';
import { msg } from '@lingui/core/macro';
import { randomInt } from 'crypto';
import { AuthenticationErrorCode } from '@documenso/auth/server/lib/errors/error-codes';
import { mailer } from '@documenso/email/mailer';
import { VerificationCodeTemplate } from '@documenso/email/templates/verification-code';
import { AppError } from '@documenso/lib/errors/app-error';
import { prisma } from '@documenso/prisma';
import { getI18nInstance } from '../../client-only/providers/i18n-server';
import { NEXT_PUBLIC_WEBAPP_URL } from '../../constants/app';
import { FROM_ADDRESS, FROM_NAME } from '../../constants/email';
import { renderEmailWithI18N } from '../../utils/render-email-with-i18n';
const ExtendedAuthErrorCode = {
...AuthenticationErrorCode,
InternalError: 'INTERNAL_ERROR',
VerificationNotFound: 'VERIFICATION_NOT_FOUND',
VerificationExpired: 'VERIFICATION_EXPIRED',
};
const VERIFICATION_CODE_EXPIRY = 10 * 60 * 1000;
export type SendEmailVerificationOptions = {
userId: number;
email: string;
};
export const sendEmailVerification = async ({ userId, email }: SendEmailVerificationOptions) => {
try {
const verificationCode = randomInt(100000, 1000000).toString();
const i18n = await getI18nInstance();
await prisma.userTwoFactorEmailVerification.upsert({
where: {
userId,
},
create: {
userId,
verificationCode,
expiresAt: new Date(Date.now() + VERIFICATION_CODE_EXPIRY),
},
update: {
verificationCode,
expiresAt: new Date(Date.now() + VERIFICATION_CODE_EXPIRY),
},
});
const template = createElement(VerificationCodeTemplate, {
verificationCode,
assetBaseUrl: NEXT_PUBLIC_WEBAPP_URL(),
});
const [html, text] = await Promise.all([
renderEmailWithI18N(template, { lang: 'en' }),
renderEmailWithI18N(template, { lang: 'en', plainText: true }),
]);
await mailer.sendMail({
to: email,
from: {
name: FROM_NAME,
address: FROM_ADDRESS,
},
subject: i18n._(msg`Your verification code for document signing`),
html,
text,
});
return { success: true };
} catch (error) {
console.error('Error sending email verification', error);
throw new AppError(ExtendedAuthErrorCode.InternalError);
}
};
export type VerifyEmailCodeOptions = {
userId: number;
code: string;
};
export const verifyEmailCode = async ({ userId, code }: VerifyEmailCodeOptions) => {
try {
const verification = await prisma.userTwoFactorEmailVerification.findUnique({
where: {
userId,
},
});
if (!verification) {
throw new AppError(ExtendedAuthErrorCode.VerificationNotFound);
}
if (verification.expiresAt < new Date()) {
throw new AppError(ExtendedAuthErrorCode.VerificationExpired);
}
if (verification.verificationCode !== code) {
throw new AppError(AuthenticationErrorCode.InvalidTwoFactorCode);
}
await prisma.userTwoFactorEmailVerification.delete({
where: {
userId,
},
});
return { success: true };
} catch (error) {
console.error('Error verifying email code', error);
if (error instanceof AppError) {
throw error;
}
throw new AppError(ExtendedAuthErrorCode.InternalError);
}
};
@@ -111,7 +111,7 @@ export const getDocumentWhereInput = async ({
visibility: {
in: teamVisibilityFilters,
},
teamId,
teamId: team.id,
},
// Or, if they are a recipient of the document.
{
@@ -1,4 +1,5 @@
import { DocumentStatus, DocumentVisibility, TeamMemberRole } from '@prisma/client';
import { DocumentVisibility } from '@prisma/client';
import { DocumentStatus, TeamMemberRole } from '@prisma/client';
import { isDeepEqual } from 'remeda';
import { match } from 'ts-pattern';
@@ -118,6 +119,13 @@ export const updateDocument = async ({
const newGlobalActionAuth =
data?.globalActionAuth === undefined ? documentGlobalActionAuth : data.globalActionAuth;
// Check if user has permission to set the global action auth.
if (newGlobalActionAuth.length > 0 && !document.team.organisation.organisationClaim.flags.cfr21) {
throw new AppError(AppErrorCode.UNAUTHORIZED, {
message: 'You do not have permission to set the action auth',
});
}
const isTitleSame = data.title === undefined || data.title === document.title;
const isExternalIdSame = data.externalId === undefined || data.externalId === document.externalId;
const isGlobalAccessSame =
@@ -15,7 +15,7 @@ import { AUTO_SIGNABLE_FIELD_TYPES } from '../../constants/autosign';
import { DEFAULT_DOCUMENT_DATE_FORMAT } from '../../constants/date-formats';
import { DEFAULT_DOCUMENT_TIME_ZONE } from '../../constants/time-zones';
import { DOCUMENT_AUDIT_LOG_TYPE } from '../../types/document-audit-logs';
import type { TRecipientActionAuth, TRecipientActionAuthTypes } from '../../types/document-auth';
import type { TRecipientActionAuth } from '../../types/document-auth';
import {
ZCheckboxFieldMeta,
ZDropdownFieldMeta,
@@ -25,9 +25,7 @@ import {
} from '../../types/field-meta';
import type { RequestMetadata } from '../../universal/extract-request-metadata';
import { createDocumentAuditLogData } from '../../utils/document-audit-logs';
import { extractDocumentAuthMethods } from '../../utils/document-auth';
import { validateFieldAuth } from '../document/validate-field-auth';
import { isUserEnterprise } from '../user/is-user-enterprise';
export type SignFieldWithTokenOptions = {
token: string;
@@ -173,25 +171,13 @@ export const signFieldWithToken = async ({
}
}
const isEnterprise = userId ? await isUserEnterprise({ userId }) : false;
let requiredAuthType: TRecipientActionAuthTypes | null = null;
if (isEnterprise) {
const authType = await validateFieldAuth({
documentAuthOptions: document.authOptions,
recipient,
field,
userId,
authOptions,
});
requiredAuthType = authType ?? null;
} else {
const { derivedRecipientActionAuth } = extractDocumentAuthMethods({
documentAuth: document.authOptions,
recipientAuth: recipient.authOptions,
});
requiredAuthType = derivedRecipientActionAuth.length > 0 ? derivedRecipientActionAuth[0] : null;
}
const derivedRecipientActionAuth = await validateFieldAuth({
documentAuthOptions: document.authOptions,
recipient,
field,
userId,
authOptions,
});
const documentMeta = await prisma.documentMeta.findFirst({
where: {
@@ -325,9 +311,9 @@ export const signFieldWithToken = async ({
}),
)
.exhaustive(),
fieldSecurity: requiredAuthType
fieldSecurity: derivedRecipientActionAuth
? {
type: requiredAuthType,
type: derivedRecipientActionAuth,
}
: undefined,
},
@@ -37,23 +37,3 @@ export const getOrganisationClaimByTeamId = async ({ teamId }: { teamId: number
return organisationClaim;
};
export const getOrganisationClaimByUserId = async ({ userId }: { userId: number }) => {
const organisationClaim = await prisma.organisationClaim.findFirst({
where: {
organisation: {
members: {
some: {
userId: userId,
},
},
},
},
});
if (!organisationClaim) {
throw new AppError(AppErrorCode.NOT_FOUND);
}
return organisationClaim;
};
@@ -134,6 +134,9 @@ export const setDocumentRecipients = async ({
existingRecipient.id === recipient.id || existingRecipient.email === recipient.email,
);
const canPersistedRecipientBeModified =
existing && canRecipientBeModified(existing, document.fields);
if (
existing &&
hasRecipientBeenChanged(existing, recipient) &&
@@ -147,6 +150,7 @@ export const setDocumentRecipients = async ({
return {
...recipient,
_persisted: existing,
canPersistedRecipientBeModified,
};
});
@@ -162,6 +166,13 @@ export const setDocumentRecipients = async ({
});
}
if (recipient._persisted && !recipient.canPersistedRecipientBeModified) {
return {
...recipient._persisted,
clientId: recipient.clientId,
};
}
const upsertedRecipient = await tx.recipient.upsert({
where: {
id: recipient._persisted?.id ?? -1,
@@ -1,7 +1,5 @@
import type { Recipient } from '@prisma/client';
import { RecipientRole } from '@prisma/client';
import { SendStatus, SigningStatus } from '@prisma/client';
import { isDeepEqual } from 'remeda';
import { DOCUMENT_AUDIT_LOG_TYPE } from '@documenso/lib/types/document-audit-logs';
import type { TRecipientAccessAuthTypes } from '@documenso/lib/types/document-auth';
@@ -104,10 +102,7 @@ export const updateDocumentRecipients = async ({
});
}
if (
hasRecipientBeenChanged(originalRecipient, recipient) &&
!canRecipientBeModified(originalRecipient, document.fields)
) {
if (!canRecipientBeModified(originalRecipient, document.fields)) {
throw new AppError(AppErrorCode.INVALID_REQUEST, {
message: 'Cannot modify a recipient who has already interacted with the document',
});
@@ -203,9 +198,6 @@ export const updateDocumentRecipients = async ({
};
};
/**
* If you change this you MUST update the `hasRecipientBeenChanged` function.
*/
type RecipientData = {
id: number;
email?: string;
@@ -215,19 +207,3 @@ type RecipientData = {
accessAuth?: TRecipientAccessAuthTypes[];
actionAuth?: TRecipientActionAuthTypes[];
};
const hasRecipientBeenChanged = (recipient: Recipient, newRecipientData: RecipientData) => {
const authOptions = ZRecipientAuthOptionsSchema.parse(recipient.authOptions);
const newRecipientAccessAuth = newRecipientData.accessAuth || null;
const newRecipientActionAuth = newRecipientData.actionAuth || null;
return (
recipient.email !== newRecipientData.email ||
recipient.name !== newRecipientData.name ||
recipient.role !== newRecipientData.role ||
recipient.signingOrder !== newRecipientData.signingOrder ||
!isDeepEqual(authOptions.accessAuth, newRecipientAccessAuth) ||
!isDeepEqual(authOptions.actionAuth, newRecipientActionAuth)
);
};
@@ -4,10 +4,8 @@ import { prisma } from '@documenso/prisma';
import { AppError, AppErrorCode } from '../../errors/app-error';
import type { TDocumentAccessAuthTypes, TDocumentActionAuthTypes } from '../../types/document-auth';
import { DocumentAuth } from '../../types/document-auth';
import { createDocumentAuthOptions, extractDocumentAuthMethods } from '../../utils/document-auth';
import { buildTeamWhereQuery } from '../../utils/teams';
import { isUserEnterprise } from '../user/is-user-enterprise';
export type UpdateTemplateOptions = {
userId: number;
@@ -78,21 +76,10 @@ export const updateTemplate = async ({
data?.globalActionAuth === undefined ? documentGlobalActionAuth : data.globalActionAuth;
// Check if user has permission to set the global action auth.
// Only ACCOUNT and PASSKEY require enterprise permissions
if (
newGlobalActionAuth &&
(newGlobalActionAuth.includes(DocumentAuth.ACCOUNT) ||
newGlobalActionAuth.includes(DocumentAuth.PASSKEY))
) {
const isDocumentEnterprise = await isUserEnterprise({
userId,
if (newGlobalActionAuth.length > 0 && !template.team.organisation.organisationClaim.flags.cfr21) {
throw new AppError(AppErrorCode.UNAUTHORIZED, {
message: 'You do not have permission to set the action auth',
});
if (!isDocumentEnterprise) {
throw new AppError(AppErrorCode.UNAUTHORIZED, {
message: 'You do not have permission to set this action auth type',
});
}
}
const authOptions = createDocumentAuthOptions({
@@ -1,14 +0,0 @@
import { getOrganisationClaimByUserId } from '../organisation/get-organisation-claims';
/**
* Check if a user has enterprise features enabled (cfr21 flag).
*/
export const isUserEnterprise = async ({ userId }: { userId: number }): Promise<boolean> => {
try {
const organisationClaim = await getOrganisationClaimByUserId({ userId });
return Boolean(organisationClaim.flags.cfr21);
} catch {
// If we can't find the organisation claim, assume non-enterprise
return false;
}
};
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-14
View File
@@ -82,16 +82,6 @@ export const ZDocumentActionAuthTypesSchema = z
'The type of authentication required for the recipient to sign the document. This field is restricted to Enterprise plan users only.',
);
/**
* The non-enterprise document action auth methods.
*
* Only includes options available to non-enterprise users.
*/
export const ZNonEnterpriseDocumentActionAuthTypesSchema = z.enum([
DocumentAuth.TWO_FACTOR_AUTH,
DocumentAuth.EXPLICIT_NONE,
]);
/**
* The recipient access auth methods.
*
@@ -128,7 +118,6 @@ export const ZRecipientActionAuthTypesSchema = z
export const DocumentAccessAuth = ZDocumentAccessAuthTypesSchema.Enum;
export const DocumentActionAuth = ZDocumentActionAuthTypesSchema.Enum;
export const NonEnterpriseDocumentActionAuth = ZNonEnterpriseDocumentActionAuthTypesSchema.Enum;
export const RecipientAccessAuth = ZRecipientAccessAuthTypesSchema.Enum;
export const RecipientActionAuth = ZRecipientActionAuthTypesSchema.Enum;
@@ -212,9 +201,6 @@ export type TDocumentAccessAuth = z.infer<typeof ZDocumentAccessAuthSchema>;
export type TDocumentAccessAuthTypes = z.infer<typeof ZDocumentAccessAuthTypesSchema>;
export type TDocumentActionAuth = z.infer<typeof ZDocumentActionAuthSchema>;
export type TDocumentActionAuthTypes = z.infer<typeof ZDocumentActionAuthTypesSchema>;
export type TNonEnterpriseDocumentActionAuthTypes = z.infer<
typeof ZNonEnterpriseDocumentActionAuthTypesSchema
>;
export type TRecipientAccessAuth = z.infer<typeof ZRecipientAccessAuthSchema>;
export type TRecipientAccessAuthTypes = z.infer<typeof ZRecipientAccessAuthTypesSchema>;
export type TRecipientActionAuth = z.infer<typeof ZRecipientActionAuthSchema>;
+13 -1
View File
@@ -18,6 +18,7 @@ export enum DocumentSignatureType {
DRAW = 'draw',
TYPE = 'type',
UPLOAD = 'upload',
KEYBOARD = 'keyboard',
}
export const formatTeamUrl = (teamUrl: string, baseUrl?: string) => {
@@ -83,10 +84,16 @@ export const extractTeamSignatureSettings = (
typedSignatureEnabled: boolean | null;
drawSignatureEnabled: boolean | null;
uploadSignatureEnabled: boolean | null;
keyboardSignatureEnabled?: boolean | null;
} | null,
) => {
if (!settings) {
return [DocumentSignatureType.TYPE, DocumentSignatureType.UPLOAD, DocumentSignatureType.DRAW];
return [
DocumentSignatureType.TYPE,
DocumentSignatureType.UPLOAD,
DocumentSignatureType.DRAW,
DocumentSignatureType.KEYBOARD,
];
}
const signatureTypes: DocumentSignatureType[] = [];
@@ -103,6 +110,10 @@ export const extractTeamSignatureSettings = (
signatureTypes.push(DocumentSignatureType.UPLOAD);
}
if (settings.keyboardSignatureEnabled !== false) {
signatureTypes.push(DocumentSignatureType.KEYBOARD);
}
return signatureTypes;
};
@@ -175,6 +186,7 @@ export const generateDefaultTeamSettings = (): Omit<TeamGlobalSettings, 'id' | '
typedSignatureEnabled: null,
uploadSignatureEnabled: null,
drawSignatureEnabled: null,
keyboardSignatureEnabled: null,
brandingEnabled: null,
brandingLogo: null,
@@ -1,12 +0,0 @@
-- CreateTable
CREATE TABLE "UserTwoFactorEmailVerification" (
"userId" INTEGER NOT NULL,
"verificationCode" TEXT NOT NULL,
"expiresAt" TIMESTAMP(3) NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "UserTwoFactorEmailVerification_pkey" PRIMARY KEY ("userId")
);
-- AddForeignKey
ALTER TABLE "UserTwoFactorEmailVerification" ADD CONSTRAINT "UserTwoFactorEmailVerification_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "TeamGlobalSettings" ADD COLUMN "keyboardSignatureEnabled" BOOLEAN;
+4 -13
View File
@@ -59,10 +59,9 @@ model User {
ownedOrganisations Organisation[]
organisationMember OrganisationMember[]
twoFactorSecret String?
twoFactorEnabled Boolean @default(false)
twoFactorBackupCodes String?
twoFactorEmailVerification UserTwoFactorEmailVerification?
twoFactorSecret String?
twoFactorEnabled Boolean @default(false)
twoFactorBackupCodes String?
folders Folder[]
documents Document[]
@@ -777,6 +776,7 @@ model TeamGlobalSettings {
typedSignatureEnabled Boolean?
uploadSignatureEnabled Boolean?
drawSignatureEnabled Boolean?
keyboardSignatureEnabled Boolean?
emailId String?
email OrganisationEmail? @relation(fields: [emailId], references: [id])
@@ -986,15 +986,6 @@ model AvatarImage {
organisation Organisation[]
}
model UserTwoFactorEmailVerification {
userId Int @id
verificationCode String
expiresAt DateTime
createdAt DateTime @default(now())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
enum EmailDomainStatus {
PENDING
ACTIVE
@@ -1,10 +1,5 @@
import type { RegistrationResponseJSON } from '@simplewebauthn/types';
import { AppError } from '@documenso/lib/errors/app-error';
import {
sendEmailVerification,
verifyEmailCode,
} from '@documenso/lib/server-only/2fa/send-email-verification';
import { createPasskey } from '@documenso/lib/server-only/auth/create-passkey';
import { createPasskeyAuthenticationOptions } from '@documenso/lib/server-only/auth/create-passkey-authentication-options';
import { createPasskeyRegistrationOptions } from '@documenso/lib/server-only/auth/create-passkey-registration-options';
@@ -13,7 +8,6 @@ import { deletePasskey } from '@documenso/lib/server-only/auth/delete-passkey';
import { findPasskeys } from '@documenso/lib/server-only/auth/find-passkeys';
import { updatePasskey } from '@documenso/lib/server-only/auth/update-passkey';
import { nanoid } from '@documenso/lib/universal/id';
import { prisma } from '@documenso/prisma';
import { authenticatedProcedure, procedure, router } from '../trpc';
import {
@@ -21,9 +15,7 @@ import {
ZCreatePasskeyMutationSchema,
ZDeletePasskeyMutationSchema,
ZFindPasskeysQuerySchema,
ZSendEmailVerificationMutationSchema,
ZUpdatePasskeyMutationSchema,
ZVerifyEmailCodeMutationSchema,
} from './schema';
export const authRouter = router({
@@ -118,68 +110,4 @@ export const authRouter = router({
requestMetadata: ctx.metadata.requestMetadata,
});
}),
// Email verification for document signing
sendEmailVerification: authenticatedProcedure
.input(ZSendEmailVerificationMutationSchema)
.mutation(async ({ ctx, input }) => {
const { recipientId } = input;
const userId = ctx.user.id;
let email = ctx.user.email;
// If recipientId is provided, fetch that recipient's details
if (recipientId) {
const recipient = await prisma.recipient.findUnique({
where: {
id: recipientId,
},
select: {
email: true,
},
});
if (!recipient) {
throw new AppError('NOT_FOUND', {
message: 'Recipient not found',
});
}
email = recipient.email;
}
return sendEmailVerification({
userId,
email,
});
}),
verifyEmailCode: authenticatedProcedure
.input(ZVerifyEmailCodeMutationSchema)
.mutation(async ({ ctx, input }) => {
const { code, recipientId } = input;
const userId = ctx.user.id;
// If recipientId is provided, check that the user has access to it
if (recipientId) {
const recipient = await prisma.recipient.findUnique({
where: {
id: recipientId,
},
select: {
email: true,
},
});
if (!recipient) {
throw new AppError('NOT_FOUND', {
message: 'Recipient not found',
});
}
}
return verifyEmailCode({
userId,
code,
});
}),
});
@@ -71,18 +71,3 @@ export const ZFindPasskeysQuerySchema = ZFindSearchParamsSchema.extend({
});
export type TSignUpMutationSchema = z.infer<typeof ZSignUpMutationSchema>;
export const ZSendEmailVerificationMutationSchema = z.object({
recipientId: z.number().optional(),
});
export type TSendEmailVerificationMutationSchema = z.infer<
typeof ZSendEmailVerificationMutationSchema
>;
export const ZVerifyEmailCodeMutationSchema = z.object({
code: z.string().min(6).max(6),
recipientId: z.number().optional(),
});
export type TVerifyEmailCodeMutationSchema = z.infer<typeof ZVerifyEmailCodeMutationSchema>;
+1
View File
@@ -141,6 +141,7 @@ export const authenticatedMiddleware = t.middleware(async ({ ctx, next, path })
return await next({
ctx: {
...ctx,
teamId: ctx.teamId || -1,
logger: trpcSessionLogger,
user: ctx.user,
session: ctx.session,
@@ -4,70 +4,70 @@ import { Trans } from '@lingui/react/macro';
import { InfoIcon } from 'lucide-react';
import { DOCUMENT_AUTH_TYPES } from '@documenso/lib/constants/document-auth';
import {
DocumentActionAuth,
DocumentAuth,
NonEnterpriseDocumentActionAuth,
} from '@documenso/lib/types/document-auth';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@documenso/ui/primitives/select';
import { DocumentActionAuth, DocumentAuth } from '@documenso/lib/types/document-auth';
import { MultiSelect, type Option } from '@documenso/ui/primitives/multiselect';
import { Tooltip, TooltipContent, TooltipTrigger } from '@documenso/ui/primitives/tooltip';
export interface DocumentGlobalAuthActionSelectProps {
value?: string[];
defaultValue?: string[];
onValueChange?: (value: string[]) => void;
disabled?: boolean;
placeholder?: string;
isDocumentEnterprise?: boolean;
}
export const DocumentGlobalAuthActionSelect = ({
value,
defaultValue,
onValueChange,
disabled,
placeholder,
isDocumentEnterprise,
}: DocumentGlobalAuthActionSelectProps) => {
const { _ } = useLingui();
const authTypes = isDocumentEnterprise
? Object.values(DocumentActionAuth).filter((auth) => auth !== DocumentAuth.ACCOUNT)
: Object.values(NonEnterpriseDocumentActionAuth).filter(
(auth) => auth !== DocumentAuth.EXPLICIT_NONE,
);
// Convert auth types to MultiSelect options
const authOptions: Option[] = [
{
value: '-1',
label: _(msg`No restrictions`),
},
...Object.values(DocumentActionAuth)
.filter((auth) => auth !== DocumentAuth.ACCOUNT)
.map((authType) => ({
value: authType,
label: DOCUMENT_AUTH_TYPES[authType].value,
})),
];
const selectedValue = value?.[0] || '';
// Convert string array to Option array for MultiSelect
const selectedOptions =
(value
?.map((val) => authOptions.find((option) => option.value === val))
.filter(Boolean) as Option[]) || [];
const handleChange = (newValue: string) => {
if (newValue === '-1') {
onValueChange?.([]);
} else {
onValueChange?.([newValue]);
}
// Convert default value to Option array
const defaultOptions =
(defaultValue
?.map((val) => authOptions.find((option) => option.value === val))
.filter(Boolean) as Option[]) || [];
const handleChange = (options: Option[]) => {
const values = options.map((option) => option.value);
onValueChange?.(values);
};
return (
<Select value={selectedValue || '-1'} onValueChange={handleChange} disabled={disabled}>
<SelectTrigger
className="bg-background text-muted-foreground"
data-testid="documentActionSelectValue"
>
<SelectValue placeholder={placeholder || _(msg`Select authentication method`)} />
</SelectTrigger>
<SelectContent>
<SelectItem value="-1">{_(msg`No restrictions`)}</SelectItem>
{authTypes.map((authType) => (
<SelectItem key={authType} value={authType}>
{DOCUMENT_AUTH_TYPES[authType].value}
</SelectItem>
))}
</SelectContent>
</Select>
<MultiSelect
value={selectedOptions}
defaultOptions={defaultOptions}
options={authOptions}
onChange={handleChange}
disabled={disabled}
placeholder={placeholder || _(msg`Select authentication methods`)}
className="bg-background text-muted-foreground"
hideClearAllButton={false}
data-testid="documentActionSelectValue"
/>
);
};
@@ -86,14 +86,14 @@ export const DocumentGlobalAuthActionTooltip = () => (
<p>
<Trans>
The authentication method required for recipients to sign the signature field.
The authentication methods required for recipients to sign the signature field.
</Trans>
</p>
<p>
<Trans>
This can be overridden by setting the authentication requirements directly on each
recipient in the next step.
These can be overriden by setting the authentication requirements directly on each
recipient in the next step. Multiple methods can be selected.
</Trans>
</p>
@@ -294,27 +294,28 @@ export const AddSettingsFormPartial = ({
/>
)}
<FormField
control={form.control}
name="globalActionAuth"
render={({ field }) => (
<FormItem>
<FormLabel className="flex flex-row items-center">
<Trans>Recipient action authentication</Trans>
<DocumentGlobalAuthActionTooltip />
</FormLabel>
{organisation.organisationClaim.flags.cfr21 && (
<FormField
control={form.control}
name="globalActionAuth"
render={({ field }) => (
<FormItem>
<FormLabel className="flex flex-row items-center">
<Trans>Recipient action authentication</Trans>
<DocumentGlobalAuthActionTooltip />
</FormLabel>
<FormControl>
<DocumentGlobalAuthActionSelect
value={field.value}
disabled={field.disabled}
onValueChange={field.onChange}
isDocumentEnterprise={organisation?.organisationClaim?.flags?.cfr21 || false}
/>
</FormControl>
</FormItem>
)}
/>
<FormControl>
<DocumentGlobalAuthActionSelect
value={field.value}
disabled={field.disabled}
onValueChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
)}
<Accordion type="multiple" className="mt-6">
<AccordionItem value="advanced-options" className="border-none">
@@ -0,0 +1,207 @@
export enum KeyboardLayout {
QWERTY = 'QWERTY',
}
export type CurveType =
| 'linear'
| 'simple-curve'
| 'quadratic-bezier'
| 'cubic-bezier'
| 'catmull-rom';
export enum StrokeStyle {
SOLID = 'solid',
GRADIENT = 'gradient',
}
export interface StrokeConfig {
style: StrokeStyle;
color: string;
gradientStart: string;
gradientEnd: string;
width: number;
}
export interface Point {
x: number;
y: number;
}
export const getKeyboardLayout = (
layout: KeyboardLayout,
includeNumbers: boolean = false,
): Record<string, Point> => {
const qwertyLayout: Record<string, Point> = {
Q: { x: 0, y: includeNumbers ? 1 : 0 },
W: { x: 1, y: includeNumbers ? 1 : 0 },
E: { x: 2, y: includeNumbers ? 1 : 0 },
R: { x: 3, y: includeNumbers ? 1 : 0 },
T: { x: 4, y: includeNumbers ? 1 : 0 },
Y: { x: 5, y: includeNumbers ? 1 : 0 },
U: { x: 6, y: includeNumbers ? 1 : 0 },
I: { x: 7, y: includeNumbers ? 1 : 0 },
O: { x: 8, y: includeNumbers ? 1 : 0 },
P: { x: 9, y: includeNumbers ? 1 : 0 },
A: { x: 0.5, y: includeNumbers ? 2 : 1 },
S: { x: 1.5, y: includeNumbers ? 2 : 1 },
D: { x: 2.5, y: includeNumbers ? 2 : 1 },
F: { x: 3.5, y: includeNumbers ? 2 : 1 },
G: { x: 4.5, y: includeNumbers ? 2 : 1 },
H: { x: 5.5, y: includeNumbers ? 2 : 1 },
J: { x: 6.5, y: includeNumbers ? 2 : 1 },
K: { x: 7.5, y: includeNumbers ? 2 : 1 },
L: { x: 8.5, y: includeNumbers ? 2 : 1 },
Z: { x: 1, y: includeNumbers ? 3 : 2 },
X: { x: 2, y: includeNumbers ? 3 : 2 },
C: { x: 3, y: includeNumbers ? 3 : 2 },
V: { x: 4, y: includeNumbers ? 3 : 2 },
B: { x: 5, y: includeNumbers ? 3 : 2 },
N: { x: 6, y: includeNumbers ? 3 : 2 },
M: { x: 7, y: includeNumbers ? 3 : 2 },
};
if (includeNumbers) {
const numberRow = {
'1': { x: 0, y: 0 },
'2': { x: 1, y: 0 },
'3': { x: 2, y: 0 },
'4': { x: 3, y: 0 },
'5': { x: 4, y: 0 },
'6': { x: 5, y: 0 },
'7': { x: 6, y: 0 },
'8': { x: 7, y: 0 },
'9': { x: 8, y: 0 },
'0': { x: 9, y: 0 },
};
return { ...numberRow, ...qwertyLayout };
}
return qwertyLayout;
};
export const generatePath = (points: Point[], curveType: CurveType): string => {
if (points.length === 0) return '';
if (points.length === 1) return `M ${points[0].x} ${points[0].y}`;
switch (curveType) {
case 'linear':
return generateLinearPath(points);
case 'simple-curve':
return generateSimpleCurvePath(points);
case 'quadratic-bezier':
return generateQuadraticBezierPath(points);
case 'cubic-bezier':
return generateCubicBezierPath(points);
case 'catmull-rom':
return generateCatmullRomPath(points);
default:
return generateLinearPath(points);
}
};
const generateLinearPath = (points: Point[]): string => {
if (points.length === 0) return '';
let path = `M ${points[0].x} ${points[0].y}`;
for (let i = 1; i < points.length; i++) {
path += ` L ${points[i].x} ${points[i].y}`;
}
return path;
};
const generateSimpleCurvePath = (points: Point[]): string => {
if (points.length === 0) return '';
if (points.length === 1) return `M ${points[0].x} ${points[0].y}`;
let path = `M ${points[0].x} ${points[0].y}`;
for (let i = 1; i < points.length; i++) {
const prev = points[i - 1];
const curr = points[i];
const midX = (prev.x + curr.x) / 2;
const midY = (prev.y + curr.y) / 2;
if (i === 1) {
path += ` Q ${prev.x} ${prev.y} ${midX} ${midY}`;
} else {
path += ` T ${midX} ${midY}`;
}
}
const lastPoint = points[points.length - 1];
path += ` T ${lastPoint.x} ${lastPoint.y}`;
return path;
};
const generateQuadraticBezierPath = (points: Point[]): string => {
if (points.length === 0) return '';
if (points.length === 1) return `M ${points[0].x} ${points[0].y}`;
let path = `M ${points[0].x} ${points[0].y}`;
for (let i = 1; i < points.length; i++) {
const prev = points[i - 1];
const curr = points[i];
const controlX = prev.x + (curr.x - prev.x) * 0.5;
const controlY = prev.y - Math.abs(curr.x - prev.x) * 0.3;
path += ` Q ${controlX} ${controlY} ${curr.x} ${curr.y}`;
}
return path;
};
const generateCubicBezierPath = (points: Point[]): string => {
if (points.length === 0) return '';
if (points.length === 1) return `M ${points[0].x} ${points[0].y}`;
let path = `M ${points[0].x} ${points[0].y}`;
for (let i = 1; i < points.length; i++) {
const prev = points[i - 1];
const curr = points[i];
const dx = curr.x - prev.x;
const dy = curr.y - prev.y;
const cp1x = prev.x + dx * 0.25;
const cp1y = prev.y + dy * 0.25 - Math.abs(dx) * 0.2;
const cp2x = prev.x + dx * 0.75;
const cp2y = prev.y + dy * 0.75 - Math.abs(dx) * 0.2;
path += ` C ${cp1x} ${cp1y} ${cp2x} ${cp2y} ${curr.x} ${curr.y}`;
}
return path;
};
const generateCatmullRomPath = (points: Point[]): string => {
if (points.length === 0) return '';
if (points.length === 1) return `M ${points[0].x} ${points[0].y}`;
if (points.length === 2) return generateLinearPath(points);
let path = `M ${points[0].x} ${points[0].y}`;
for (let i = 1; i < points.length; i++) {
const p0 = i === 1 ? points[0] : points[i - 2];
const p1 = points[i - 1];
const p2 = points[i];
const p3 = i === points.length - 1 ? points[i] : points[i + 1];
const cp1x = p1.x + (p2.x - p0.x) / 6;
const cp1y = p1.y + (p2.y - p0.y) / 6;
const cp2x = p2.x - (p3.x - p1.x) / 6;
const cp2y = p2.y - (p3.y - p1.y) / 6;
path += ` C ${cp1x} ${cp1y} ${cp2x} ${cp2y} ${p2.x} ${p2.y}`;
}
return path;
};
@@ -0,0 +1,146 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { cn } from '../../lib/utils';
import { KeyboardLayout, StrokeStyle, generatePath, getKeyboardLayout } from './keyboard-utils';
export type SignaturePadKeyboardProps = {
className?: string;
onChange: (_value: string) => void;
};
export const SignaturePadKeyboard = ({ className, onChange }: SignaturePadKeyboardProps) => {
const [name, setName] = useState('');
const [currentKeyboardLayout] = useState<KeyboardLayout>(KeyboardLayout.QWERTY);
const curveType = 'linear';
const includeNumbers = false;
const strokeConfig = {
style: StrokeStyle.SOLID,
color: '#000000',
gradientStart: '#ff6b6b',
gradientEnd: '#4ecdc4',
width: 3,
};
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
const isInputFocused = document.activeElement === inputRef.current;
const isAnyInputFocused = document.activeElement?.tagName === 'INPUT';
if (!isInputFocused && !isAnyInputFocused) {
const regex = includeNumbers ? /^[a-zA-Z0-9]$/ : /^[a-zA-Z]$/;
if (regex.test(e.key) || e.key === 'Backspace') {
inputRef.current?.focus();
}
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [includeNumbers]);
// Generate signature path
const signaturePath = useMemo(() => {
if (!name) return '';
const points = [];
const currentLayout = getKeyboardLayout(currentKeyboardLayout, includeNumbers);
for (const char of name.toUpperCase()) {
if (char in currentLayout) {
const { x, y } = currentLayout[char];
const yOffset = includeNumbers ? 100 : 40;
points.push({ x: x * 60 + 28, y: y * 60 + yOffset });
}
}
if (points.length === 0) return '';
return generatePath(points, curveType);
}, [name, currentKeyboardLayout, curveType, includeNumbers]);
// Update parent component when signature changes
useEffect(() => {
if (signaturePath && name) {
// Convert SVG to data URL for consistency with other signature types
const svgData = generateSVGDataURL(signaturePath);
onChange(svgData);
} else {
onChange('');
}
}, [signaturePath, name, onChange]);
const generateSVGDataURL = (path: string): string => {
const height = includeNumbers ? 260 : 200;
const gradients =
strokeConfig.style === StrokeStyle.GRADIENT
? `<linearGradient id="pathGradient" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:${strokeConfig.gradientStart};stop-opacity:1" />
<stop offset="100%" style="stop-color:${strokeConfig.gradientEnd};stop-opacity:1" />
</linearGradient>`
: '';
const strokeColor =
strokeConfig.style === StrokeStyle.SOLID ? strokeConfig.color : 'url(#pathGradient)';
const svgContent = `<svg width="650" height="${height}" xmlns="http://www.w3.org/2000/svg">
<defs>${gradients}</defs>
<path d="${path}" stroke="${strokeColor}" stroke-width="${strokeConfig.width}" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
</svg>`;
return `data:image/svg+xml;base64,${btoa(svgContent)}`;
};
return (
<div className={cn('flex h-full w-full flex-col items-center justify-center', className)}>
<input
ref={inputRef}
value={name}
onChange={(e) => setName(e.target.value)}
className="sr-only"
autoFocus
/>
<div className="relative w-full max-w-lg">
<svg
className="pointer-events-none w-full"
viewBox="0 0 650 200"
preserveAspectRatio="xMidYMid meet"
style={{ height: '150px' }}
>
<defs>
{strokeConfig.style === StrokeStyle.GRADIENT && (
<linearGradient id="pathGradient" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stopColor={strokeConfig.gradientStart} stopOpacity={1} />
<stop offset="100%" stopColor={strokeConfig.gradientEnd} stopOpacity={1} />
</linearGradient>
)}
</defs>
{signaturePath && (
<path
d={signaturePath}
stroke={
strokeConfig.style === StrokeStyle.SOLID ? strokeConfig.color : 'url(#pathGradient)'
}
strokeWidth={strokeConfig.width}
fill="none"
strokeLinecap="round"
strokeLinejoin="round"
/>
)}
</svg>
</div>
<div className="mt-4 w-full max-w-lg">
<div className="text-muted-foreground/70 font-mono text-xs">{name}</div>
</div>
</div>
);
};
@@ -1,7 +1,7 @@
import type { HTMLAttributes } from 'react';
import { useState } from 'react';
import { KeyboardIcon, UploadCloudIcon } from 'lucide-react';
import { Keyboard, KeyboardIcon, UploadCloudIcon } from 'lucide-react';
import { match } from 'ts-pattern';
import { DocumentSignatureType } from '@documenso/lib/constants/document';
@@ -10,6 +10,7 @@ import { isBase64Image } from '@documenso/lib/constants/signatures';
import { SignatureIcon } from '../../icons/signature';
import { cn } from '../../lib/utils';
import { SignaturePadDraw } from './signature-pad-draw';
import { SignaturePadKeyboard } from './signature-pad-keyboard';
import { SignaturePadType } from './signature-pad-type';
import { SignaturePadUpload } from './signature-pad-upload';
import { Tabs, TabsContent, TabsList, TabsTrigger } from './signature-tabs';
@@ -28,6 +29,7 @@ export type SignaturePadProps = Omit<HTMLAttributes<HTMLCanvasElement>, 'onChang
typedSignatureEnabled?: boolean;
uploadSignatureEnabled?: boolean;
drawSignatureEnabled?: boolean;
keyboardSignatureEnabled?: boolean;
onValidityChange?: (isValid: boolean) => void;
};
@@ -39,10 +41,12 @@ export const SignaturePad = ({
typedSignatureEnabled = true,
uploadSignatureEnabled = true,
drawSignatureEnabled = true,
keyboardSignatureEnabled = true,
}: SignaturePadProps) => {
const [imageSignature, setImageSignature] = useState(isBase64Image(value) ? value : '');
const [drawSignature, setDrawSignature] = useState(isBase64Image(value) ? value : '');
const [typedSignature, setTypedSignature] = useState(isBase64Image(value) ? '' : value);
const [keyboardSignature, setKeyboardSignature] = useState(isBase64Image(value) ? value : '');
/**
* This is cooked.
@@ -51,7 +55,7 @@ export const SignaturePad = ({
* the first enabled tab.
*/
const [tab, setTab] = useState(
((): 'draw' | 'text' | 'image' => {
((): 'draw' | 'text' | 'image' | 'keyboard' => {
// First passthrough to check to see if there's a signature for a given tab.
if (drawSignatureEnabled && drawSignature) {
return 'draw';
@@ -65,6 +69,10 @@ export const SignaturePad = ({
return 'image';
}
if (keyboardSignatureEnabled && keyboardSignature) {
return 'keyboard';
}
// Second passthrough to just select the first avaliable tab.
if (drawSignatureEnabled) {
return 'draw';
@@ -78,6 +86,10 @@ export const SignaturePad = ({
return 'image';
}
if (keyboardSignatureEnabled) {
return 'keyboard';
}
throw new Error('No signature enabled');
})(),
);
@@ -109,7 +121,16 @@ export const SignaturePad = ({
});
};
const onTabChange = (value: 'draw' | 'text' | 'image') => {
const onKeyboardSignatureChange = (value: string) => {
setKeyboardSignature(value);
onChange?.({
type: DocumentSignatureType.KEYBOARD,
value,
});
};
const onTabChange = (value: 'draw' | 'text' | 'image' | 'keyboard') => {
if (disabled) {
return;
}
@@ -126,10 +147,18 @@ export const SignaturePad = ({
.with('image', () => {
onImageSignatureChange(imageSignature);
})
.with('keyboard', () => {
onKeyboardSignatureChange(keyboardSignature);
})
.exhaustive();
};
if (!drawSignatureEnabled && !typedSignatureEnabled && !uploadSignatureEnabled) {
if (
!drawSignatureEnabled &&
!typedSignatureEnabled &&
!uploadSignatureEnabled &&
!keyboardSignatureEnabled
) {
return null;
}
@@ -140,7 +169,7 @@ export const SignaturePad = ({
'pointer-events-none': disabled,
})}
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
onValueChange={(value) => onTabChange(value as 'draw' | 'text' | 'image')}
onValueChange={(value) => onTabChange(value as 'draw' | 'text' | 'image' | 'keyboard')}
>
<TabsList>
{drawSignatureEnabled && (
@@ -163,6 +192,13 @@ export const SignaturePad = ({
Upload
</TabsTrigger>
)}
{keyboardSignatureEnabled && (
<TabsTrigger value="keyboard">
<Keyboard className="mr-2 size-4" />
Keyboard
</TabsTrigger>
)}
</TabsList>
<TabsContent
@@ -194,6 +230,13 @@ export const SignaturePad = ({
>
<SignaturePadUpload value={imageSignature} onChange={onImageSignatureChange} />
</TabsContent>
<TabsContent
value="keyboard"
className="border-border aspect-signature-pad dark:bg-background relative flex items-center justify-center rounded-md border bg-neutral-50 text-center"
>
<SignaturePadKeyboard value={keyboardSignature} onChange={onKeyboardSignatureChange} />
</TabsContent>
</Tabs>
);
};
@@ -382,27 +382,28 @@ export const AddTemplateSettingsFormPartial = ({
)}
/>
<FormField
control={form.control}
name="globalActionAuth"
render={({ field }) => (
<FormItem>
<FormLabel className="flex flex-row items-center">
<Trans>Recipient action authentication</Trans>
<DocumentGlobalAuthActionTooltip />
</FormLabel>
{organisation.organisationClaim.flags.cfr21 && (
<FormField
control={form.control}
name="globalActionAuth"
render={({ field }) => (
<FormItem>
<FormLabel className="flex flex-row items-center">
<Trans>Recipient action authentication</Trans>
<DocumentGlobalAuthActionTooltip />
</FormLabel>
<FormControl>
<DocumentGlobalAuthActionSelect
value={field.value}
disabled={field.disabled}
onValueChange={field.onChange}
isDocumentEnterprise={organisation.organisationClaim.flags.cfr21}
/>
</FormControl>
</FormItem>
)}
/>
<FormControl>
<DocumentGlobalAuthActionSelect
value={field.value}
disabled={field.disabled}
onValueChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
)}
{distributionMethod === DocumentDistributionMethod.EMAIL && (
<Accordion type="multiple">