The Open Source DocuSign Alternative.
TypeScript digital-signaturedocument-signingdocusign-alternativee-signatureesignesignaturenext-authnextjsopen-sourcepades-standardpdfpdf-signpdf-signaturepostgresqlprismaself-hostedsigningtypescript
fix: embedded direct template recipient auth
Lucas Smith7f19ec12650f
diff --git a/apps/remix/app/components/embed/embed-authentication-required.tsx b/apps/remix/app/components/embed/embed-authentication-required.tsxindex db65e7a2f..4147f0e6f 100644--- a/apps/remix/app/components/embed/embed-authentication-required.tsx+++ b/apps/remix/app/components/embed/embed-authentication-required.tsx@@ -9,6 +9,7 @@ export type EmbedAuthenticationRequiredProps = {email?: string;returnTo: string;isGoogleSSOEnabled?: boolean;+ isMicrosoftSSOEnabled?: boolean;isOIDCSSOEnabled?: boolean;oidcProviderLabel?: string;};@@ -17,6 +18,7 @@ export const EmbedAuthenticationRequired = ({email,returnTo,// isGoogleSSOEnabled,+ // isMicrosoftSSOEnabled,// isOIDCSSOEnabled,// oidcProviderLabel,}: EmbedAuthenticationRequiredProps) => {@@ -37,6 +39,7 @@ export const EmbedAuthenticationRequired = ({<SignInForm// Embed currently not supported.// isGoogleSSOEnabled={isGoogleSSOEnabled}+ // isMicrosoftSSOEnabled={isMicrosoftSSOEnabled}// isOIDCSSOEnabled={isOIDCSSOEnabled}// oidcProviderLabel={oidcProviderLabel}className="mt-4"diff --git a/apps/remix/app/components/forms/signin.tsx b/apps/remix/app/components/forms/signin.tsxindex 3ce7a935b..5ea14ee44 100644--- a/apps/remix/app/components/forms/signin.tsx+++ b/apps/remix/app/components/forms/signin.tsx@@ -92,6 +92,7 @@ export const SignInForm = ({const [isTwoFactorAuthenticationDialogOpen, setIsTwoFactorAuthenticationDialogOpen] =useState(false);+ const [isEmbeddedRedirect, setIsEmbeddedRedirect] = useState(false);const [twoFactorAuthenticationMethod, setTwoFactorAuthenticationMethod] = useState<'totp' | 'backup'@@ -317,6 +318,8 @@ export const SignInForm = ({if (email) {form.setValue('email', email);}++ setIsEmbeddedRedirect(params.get('embedded') === 'true');}, [form]);return (@@ -383,56 +386,64 @@ export const SignInForm = ({{isSubmitting ? <Trans>Signing in...</Trans> : <Trans>Sign In</Trans>}</Button>- {hasSocialAuthEnabled && (- <div className="relative flex items-center justify-center gap-x-4 py-2 text-xs uppercase">- <div className="bg-border h-px flex-1" />- <span className="text-muted-foreground bg-transparent">- <Trans>Or continue with</Trans>- </span>- <div className="bg-border h-px flex-1" />- </div>- )}+ {!isEmbeddedRedirect && (+ <>+ {hasSocialAuthEnabled && (+ <div className="relative flex items-center justify-center gap-x-4 py-2 text-xs uppercase">+ <div className="bg-border h-px flex-1" />+ <span className="text-muted-foreground bg-transparent">+ <Trans>Or continue with</Trans>+ </span>+ <div className="bg-border h-px flex-1" />+ </div>+ )}- {isGoogleSSOEnabled && (- <Button- type="button"- size="lg"- variant="outline"- className="bg-background text-muted-foreground border"- disabled={isSubmitting}- onClick={onSignInWithGoogleClick}- >- <FcGoogle className="mr-2 h-5 w-5" />- </Button>- )}+ {isGoogleSSOEnabled && (+ <Button+ type="button"+ size="lg"+ variant="outline"+ className="bg-background text-muted-foreground border"+ disabled={isSubmitting}+ onClick={onSignInWithGoogleClick}+ >+ <FcGoogle className="mr-2 h-5 w-5" />+ </Button>+ )}- {isMicrosoftSSOEnabled && (- <Button- type="button"- size="lg"- variant="outline"- className="bg-background text-muted-foreground border"- disabled={isSubmitting}- onClick={onSignInWithMicrosoftClick}- >- <img className="mr-2 h-4 w-4" alt="Microsoft Logo" src={'/static/microsoft.svg'} />- Microsoft- </Button>- )}+ {isMicrosoftSSOEnabled && (+ <Button+ type="button"+ size="lg"+ variant="outline"+ className="bg-background text-muted-foreground border"+ disabled={isSubmitting}+ onClick={onSignInWithMicrosoftClick}+ >+ <img+ className="mr-2 h-4 w-4"+ alt="Microsoft Logo"+ src={'/static/microsoft.svg'}+ />+ Microsoft+ </Button>+ )}- {isOIDCSSOEnabled && (- <Button- type="button"- size="lg"- variant="outline"- className="bg-background text-muted-foreground border"- disabled={isSubmitting}- onClick={onSignInWithOIDCClick}- >- <FaIdCardClip className="mr-2 h-5 w-5" />- {oidcProviderLabel || 'OIDC'}- </Button>+ {isOIDCSSOEnabled && (+ <Button+ type="button"+ size="lg"+ variant="outline"+ className="bg-background text-muted-foreground border"+ disabled={isSubmitting}+ onClick={onSignInWithOIDCClick}+ >+ <FaIdCardClip className="mr-2 h-5 w-5" />+ {oidcProviderLabel || 'OIDC'}+ </Button>+ )}+ </>)}<Buttondiff --git a/apps/remix/app/components/forms/signup.tsx b/apps/remix/app/components/forms/signup.tsxindex 0dbd7cc67..1c4be853f 100644--- a/apps/remix/app/components/forms/signup.tsx+++ b/apps/remix/app/components/forms/signup.tsx@@ -68,6 +68,7 @@ export type SignUpFormProps = {isGoogleSSOEnabled?: boolean;isMicrosoftSSOEnabled?: boolean;isOIDCSSOEnabled?: boolean;+ returnTo?: string;};export const SignUpForm = ({@@ -76,6 +77,7 @@ export const SignUpForm = ({isGoogleSSOEnabled,isMicrosoftSSOEnabled,isOIDCSSOEnabled,+ returnTo,}: SignUpFormProps) => {const { _ } = useLingui();const { toast } = useToast();@@ -110,7 +112,7 @@ export const SignUpForm = ({signature,});- await navigate(`/unverified-account`);+ await navigate(returnTo ? returnTo : '/unverified-account');toast({title: _(msg`Registration Successful`),diff --git a/apps/remix/app/components/general/document-signing/document-signing-auth-account.tsx b/apps/remix/app/components/general/document-signing/document-signing-auth-account.tsxindex b2877f2e6..3d991d5ee 100644--- a/apps/remix/app/components/general/document-signing/document-signing-auth-account.tsx+++ b/apps/remix/app/components/general/document-signing/document-signing-auth-account.tsx@@ -22,7 +22,7 @@ export const DocumentSigningAuthAccount = ({actionVerb = 'sign',onOpenChange,}: DocumentSigningAuthAccountProps) => {- const { recipient } = useRequiredDocumentSigningAuthContext();+ const { recipient, isDirectTemplate } = useRequiredDocumentSigningAuthContext();const { t } = useLingui();@@ -34,8 +34,10 @@ export const DocumentSigningAuthAccount = ({try {setIsSigningOut(true);+ const currentPath = `${window.location.pathname}${window.location.search}${window.location.hash}`;+await authClient.signOut({- redirectPath: `/signin#email=${email}`,+ redirectPath: `/signin?returnTo=${encodeURIComponent(currentPath)}#embedded=true&email=${isDirectTemplate ? '' : email}`,});} catch {setIsSigningOut(false);@@ -55,16 +57,28 @@ export const DocumentSigningAuthAccount = ({<AlertDescription>{actionTarget === 'DOCUMENT' && recipient.role === RecipientRole.VIEWER ? (<span>- <Trans>- To mark this document as viewed, you need to be logged in as{' '}- <strong>{recipient.email}</strong>- </Trans>+ {isDirectTemplate ? (+ <Trans>To mark this document as viewed, you need to be logged in.</Trans>+ ) : (+ <Trans>+ To mark this document as viewed, you need to be logged in as{' '}+ <strong>{recipient.email}</strong>+ </Trans>+ )}</span>) : (<span>- {/* Todo: Translate */}- To {actionVerb.toLowerCase()} this {actionTarget.toLowerCase()}, you need to be logged- in as <strong>{recipient.email}</strong>+ {isDirectTemplate ? (+ <Trans>+ To {actionVerb.toLowerCase()} this {actionTarget.toLowerCase()}, you need to be+ logged in.+ </Trans>+ ) : (+ <Trans>+ To {actionVerb.toLowerCase()} this {actionTarget.toLowerCase()}, you need to be+ logged in as <strong>{recipient.email}</strong>+ </Trans>+ )}</span>)}</AlertDescription>diff --git a/apps/remix/app/components/general/document-signing/document-signing-auth-dialog.tsx b/apps/remix/app/components/general/document-signing/document-signing-auth-dialog.tsxindex 706daf686..9225b3bc6 100644--- a/apps/remix/app/components/general/document-signing/document-signing-auth-dialog.tsx+++ b/apps/remix/app/components/general/document-signing/document-signing-auth-dialog.tsx@@ -47,7 +47,8 @@ export const DocumentSigningAuthDialog = ({onOpenChange,onReauthFormSubmit,}: DocumentSigningAuthDialogProps) => {- const { recipient, user, isCurrentlyAuthenticating } = useRequiredDocumentSigningAuthContext();+ const { recipient, user, isCurrentlyAuthenticating, isDirectTemplate } =+ useRequiredDocumentSigningAuthContext();// Filter out EXPLICIT_NONE from available auth types for the chooserconst validAuthTypes = availableAuthTypes.filter(@@ -168,7 +169,11 @@ export const DocumentSigningAuthDialog = ({match({ documentAuthType: selectedAuthType, user }).with({ documentAuthType: DocumentAuth.ACCOUNT },- { user: P.when((user) => !user || user.email !== recipient.email) }, // Assume all current auth methods requires them to be logged in.+ {+ user: P.when(+ (user) => !user || (user.email !== recipient.email && !isDirectTemplate),+ ),+ }, // Assume all current auth methods requires them to be logged in.() => <DocumentSigningAuthAccount onOpenChange={onOpenChange} />,).with({ documentAuthType: DocumentAuth.PASSKEY }, () => (diff --git a/apps/remix/app/components/general/document-signing/document-signing-auth-provider.tsx b/apps/remix/app/components/general/document-signing/document-signing-auth-provider.tsxindex b5c82ecfe..f8a6d13bd 100644--- a/apps/remix/app/components/general/document-signing/document-signing-auth-provider.tsx+++ b/apps/remix/app/components/general/document-signing/document-signing-auth-provider.tsx@@ -40,6 +40,7 @@ export type DocumentSigningAuthContextValue = {derivedRecipientAccessAuth: TRecipientAccessAuthTypes[];derivedRecipientActionAuth: TRecipientActionAuthTypes[];isAuthRedirectRequired: boolean;+ isDirectTemplate?: boolean;isCurrentlyAuthenticating: boolean;setIsCurrentlyAuthenticating: (_value: boolean) => void;passkeyData: PasskeyData;@@ -68,6 +69,7 @@ export const useRequiredDocumentSigningAuthContext = () => {export interface DocumentSigningAuthProviderProps {documentAuthOptions: Envelope['authOptions'];recipient: SigningAuthRecipient;+ isDirectTemplate?: boolean;user?: SessionUser | null;children: React.ReactNode;}@@ -75,6 +77,7 @@ export interface DocumentSigningAuthProviderProps {export const DocumentSigningAuthProvider = ({documentAuthOptions: initialDocumentAuthOptions,recipient: initialRecipient,+ isDirectTemplate = false,user,children,}: DocumentSigningAuthProviderProps) => {@@ -204,6 +207,7 @@ export const DocumentSigningAuthProvider = ({derivedRecipientAccessAuth,derivedRecipientActionAuth,isAuthRedirectRequired,+ isDirectTemplate,isCurrentlyAuthenticating,setIsCurrentlyAuthenticating,passkeyData,diff --git a/apps/remix/app/routes/_recipient+/d.$token+/_index.tsx b/apps/remix/app/routes/_recipient+/d.$token+/_index.tsxindex 15bf3ba8a..1484e70e7 100644--- a/apps/remix/app/routes/_recipient+/d.$token+/_index.tsx+++ b/apps/remix/app/routes/_recipient+/d.$token+/_index.tsx@@ -184,6 +184,7 @@ const DirectSigningPageV1 = ({ data }: { data: Awaited<ReturnType<typeof handleV<DocumentSigningAuthProviderdocumentAuthOptions={template.authOptions}recipient={directTemplateRecipient}+ isDirectTemplate={true}user={user}><>diff --git a/apps/remix/app/routes/_unauthenticated+/signin.tsx b/apps/remix/app/routes/_unauthenticated+/signin.tsxindex 8fd9a200a..c85a6846a 100644--- a/apps/remix/app/routes/_unauthenticated+/signin.tsx+++ b/apps/remix/app/routes/_unauthenticated+/signin.tsx@@ -1,3 +1,5 @@+import { useEffect, useState } from 'react';+import { Trans } from '@lingui/react/macro';import { Link, redirect } from 'react-router';@@ -9,6 +11,7 @@ import {OIDC_PROVIDER_LABEL,} from '@documenso/lib/constants/auth';import { env } from '@documenso/lib/utils/env';+import { isValidReturnTo, normalizeReturnTo } from '@documenso/lib/utils/is-valid-return-to';import { SignInForm } from '~/components/forms/signin';import { appMetaTags } from '~/utils/meta';@@ -28,8 +31,12 @@ export async function loader({ request }: Route.LoaderArgs) {const isOIDCSSOEnabled = IS_OIDC_SSO_ENABLED;const oidcProviderLabel = OIDC_PROVIDER_LABEL;+ let returnTo = new URL(request.url).searchParams.get('returnTo') ?? undefined;++ returnTo = isValidReturnTo(returnTo) ? normalizeReturnTo(returnTo) : undefined;+if (isAuthenticated) {- throw redirect('/');+ throw redirect(returnTo || '/');}return {@@ -37,12 +44,28 @@ export async function loader({ request }: Route.LoaderArgs) {isMicrosoftSSOEnabled,isOIDCSSOEnabled,oidcProviderLabel,+ returnTo,};}export default function SignIn({ loaderData }: Route.ComponentProps) {- const { isGoogleSSOEnabled, isMicrosoftSSOEnabled, isOIDCSSOEnabled, oidcProviderLabel } =- loaderData;+ const {+ isGoogleSSOEnabled,+ isMicrosoftSSOEnabled,+ isOIDCSSOEnabled,+ oidcProviderLabel,+ returnTo,+ } = loaderData;++ const [isEmbeddedRedirect, setIsEmbeddedRedirect] = useState(false);++ useEffect(() => {+ const hash = window.location.hash.slice(1);++ const params = new URLSearchParams(hash);++ setIsEmbeddedRedirect(params.get('embedded') === 'true');+ }, []);return (<div className="w-screen max-w-lg px-4">@@ -61,13 +84,17 @@ export default function SignIn({ loaderData }: Route.ComponentProps) {isMicrosoftSSOEnabled={isMicrosoftSSOEnabled}isOIDCSSOEnabled={isOIDCSSOEnabled}oidcProviderLabel={oidcProviderLabel}+ returnTo={returnTo}/>- {env('NEXT_PUBLIC_DISABLE_SIGNUP') !== 'true' && (+ {!isEmbeddedRedirect && env('NEXT_PUBLIC_DISABLE_SIGNUP') !== 'true' && (<p className="text-muted-foreground mt-6 text-center text-sm"><Trans>Don't have an account?{' '}- <Link to="/signup" className="text-documenso-700 duration-200 hover:opacity-70">+ <Link+ to={returnTo ? `/signup?returnTo=${encodeURIComponent(returnTo)}` : '/signup'}+ className="text-documenso-700 duration-200 hover:opacity-70"+ >Sign up</Link></Trans>diff --git a/apps/remix/app/routes/_unauthenticated+/signup.tsx b/apps/remix/app/routes/_unauthenticated+/signup.tsxindex 699251a41..b01e88d23 100644--- a/apps/remix/app/routes/_unauthenticated+/signup.tsx+++ b/apps/remix/app/routes/_unauthenticated+/signup.tsx@@ -6,6 +6,7 @@ import {IS_OIDC_SSO_ENABLED,} from '@documenso/lib/constants/auth';import { env } from '@documenso/lib/utils/env';+import { isValidReturnTo, normalizeReturnTo } from '@documenso/lib/utils/is-valid-return-to';import { SignUpForm } from '~/components/forms/signup';import { appMetaTags } from '~/utils/meta';@@ -16,7 +17,7 @@ export function meta() {return appMetaTags('Sign Up');}-export function loader() {+export function loader({ request }: Route.LoaderArgs) {const NEXT_PUBLIC_DISABLE_SIGNUP = env('NEXT_PUBLIC_DISABLE_SIGNUP');// SSR env variables.@@ -28,15 +29,20 @@ export function loader() {throw redirect('/signin');}+ let returnTo = new URL(request.url).searchParams.get('returnTo') ?? undefined;++ returnTo = isValidReturnTo(returnTo) ? normalizeReturnTo(returnTo) : undefined;+return {isGoogleSSOEnabled,isMicrosoftSSOEnabled,isOIDCSSOEnabled,+ returnTo,};}export default function SignUp({ loaderData }: Route.ComponentProps) {- const { isGoogleSSOEnabled, isMicrosoftSSOEnabled, isOIDCSSOEnabled } = loaderData;+ const { isGoogleSSOEnabled, isMicrosoftSSOEnabled, isOIDCSSOEnabled, returnTo } = loaderData;return (<SignUpForm@@ -44,6 +50,7 @@ export default function SignUp({ loaderData }: Route.ComponentProps) {isGoogleSSOEnabled={isGoogleSSOEnabled}isMicrosoftSSOEnabled={isMicrosoftSSOEnabled}isOIDCSSOEnabled={isOIDCSSOEnabled}+ returnTo={returnTo}/>);}diff --git a/apps/remix/app/routes/embed+/_v0+/_layout.tsx b/apps/remix/app/routes/embed+/_v0+/_layout.tsxindex 10204c63f..17ba7dfab 100644--- a/apps/remix/app/routes/embed+/_v0+/_layout.tsx+++ b/apps/remix/app/routes/embed+/_v0+/_layout.tsx@@ -2,6 +2,7 @@ import { Outlet, isRouteErrorResponse, useRouteError } from 'react-router';import {IS_GOOGLE_SSO_ENABLED,+ IS_MICROSOFT_SSO_ENABLED,IS_OIDC_SSO_ENABLED,OIDC_PROVIDER_LABEL,} from '@documenso/lib/constants/auth';@@ -31,11 +32,13 @@ export function headers({ loaderHeaders }: Route.HeadersArgs) {export function loader() {// SSR env variables.const isGoogleSSOEnabled = IS_GOOGLE_SSO_ENABLED;+ const isMicrosoftSSOEnabled = IS_MICROSOFT_SSO_ENABLED;const isOIDCSSOEnabled = IS_OIDC_SSO_ENABLED;const oidcProviderLabel = OIDC_PROVIDER_LABEL;return {isGoogleSSOEnabled,+ isMicrosoftSSOEnabled,isOIDCSSOEnabled,oidcProviderLabel,};@@ -46,7 +49,8 @@ export default function Layout() {}export function ErrorBoundary({ loaderData }: Route.ErrorBoundaryProps) {- const { isGoogleSSOEnabled, isOIDCSSOEnabled, oidcProviderLabel } = loaderData || {};+ const { isGoogleSSOEnabled, isMicrosoftSSOEnabled, isOIDCSSOEnabled, oidcProviderLabel } =+ loaderData || {};const error = useRouteError();@@ -57,6 +61,7 @@ export function ErrorBoundary({ loaderData }: Route.ErrorBoundaryProps) {return (<EmbedAuthenticationRequiredisGoogleSSOEnabled={isGoogleSSOEnabled}+ isMicrosoftSSOEnabled={isMicrosoftSSOEnabled}isOIDCSSOEnabled={isOIDCSSOEnabled}oidcProviderLabel={oidcProviderLabel}email={error.data.email}diff --git a/apps/remix/app/routes/embed+/_v0+/direct.$token.tsx b/apps/remix/app/routes/embed+/_v0+/direct.$token.tsxindex 0c9c75cc5..e5791264e 100644--- a/apps/remix/app/routes/embed+/_v0+/direct.$token.tsx+++ b/apps/remix/app/routes/embed+/_v0+/direct.$token.tsx@@ -76,7 +76,6 @@ async function handleV1Loader({ params, request }: Route.LoaderArgs) {throw data({type: 'embed-authentication-required',- email: user?.email,returnTo: `/embed/direct/${token}`,},{@@ -319,6 +318,7 @@ const EmbedDirectTemplatePageV2 = ({documentAuthOptions={envelope.authOptions}recipient={recipient}user={user}+ isDirectTemplate={true}><EnvelopeRenderProvider envelope={envelope} token={recipient.token}><EmbedSignDocumentV2ClientPagediff --git a/packages/auth/server/lib/utils/handle-oauth-callback-url.ts b/packages/auth/server/lib/utils/handle-oauth-callback-url.tsindex 34a3aa4fe..92273fdeb 100644--- a/packages/auth/server/lib/utils/handle-oauth-callback-url.ts+++ b/packages/auth/server/lib/utils/handle-oauth-callback-url.ts@@ -5,6 +5,7 @@ import { deleteCookie } from 'hono/cookie';import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';import { onCreateUserHook } from '@documenso/lib/server-only/user/create-user';+import { isValidReturnTo, normalizeReturnTo } from '@documenso/lib/utils/is-valid-return-to';import { prisma } from '@documenso/prisma';import type { OAuthClientOptions } from '../../config';@@ -177,6 +178,12 @@ export const validateOauth = async (options: HandleOAuthCallbackUrlOptions) => {redirectPath = '/';}+ if (!isValidReturnTo(redirectPath)) {+ redirectPath = '/';+ }++ redirectPath = normalizeReturnTo(redirectPath) || '/';+const tokens = await oAuthClient.validateAuthorizationCode(token_endpoint,code,diff --git a/packages/lib/utils/is-valid-return-to.ts b/packages/lib/utils/is-valid-return-to.tsnew file mode 100644index 000000000..7ac3a3766--- /dev/null+++ b/packages/lib/utils/is-valid-return-to.ts@@ -0,0 +1,37 @@+import { NEXT_PUBLIC_WEBAPP_URL } from '@documenso/lib/constants/app';++export const isValidReturnTo = (returnTo?: string) => {+ if (!returnTo) {+ return false;+ }++ try {+ // Decode if it's URL encoded+ const decodedReturnTo = decodeURIComponent(returnTo);+ const returnToUrl = new URL(decodedReturnTo, NEXT_PUBLIC_WEBAPP_URL());++ if (returnToUrl.origin !== NEXT_PUBLIC_WEBAPP_URL()) {+ return false;+ }++ return true;+ } catch {+ return false;+ }+};++export const normalizeReturnTo = (returnTo?: string) => {+ if (!returnTo) {+ return undefined;+ }++ try {+ // Decode if it's URL encoded+ const decodedReturnTo = decodeURIComponent(returnTo);+ const returnToUrl = new URL(decodedReturnTo, NEXT_PUBLIC_WEBAPP_URL());++ return `${returnToUrl.pathname}${returnToUrl.search}${returnToUrl.hash}`;+ } catch {+ return undefined;+ }+};