Skip to content

The Open Source DocuSign Alternative.

fix: support cross-site authentication in embeds (#3429)

Lucas Smitha166cabde7c6
diff --git a/.agents/skills/envelope-editor-v2-e2e/SKILL.md b/.agents/skills/envelope-editor-v2-e2e/SKILL.md
index 0ac584a76..f1cf65d53 100644
--- a/.agents/skills/envelope-editor-v2-e2e/SKILL.md
+++ b/.agents/skills/envelope-editor-v2-e2e/SKILL.md
@@ -369,3 +369,4 @@ npm run test:dev -w @documenso/app-tests -- --grep "documents/<id>: add myself"
- **Parallel test isolation**: Always use a unique `externalId` via `nanoid()` so parallel tests don't collide.
- **Navigation verification**: Navigate away from and back to the current step to verify UI state persistence (the editor may re-render).
- **Delete confirmation**: Native surfaces show a confirmation dialog for item deletion; embedded surfaces delete immediately.
+- **`Origin` header on `request.post()`**: Playwright's `APIRequestContext` never sends `Origin`, and the CSRF middleware (`apps/remix/server/csrf-middleware.ts`) rejects cookie-authenticated mutations without it (403). Spread `WEBAPP_ORIGIN_HEADERS` from `fixtures/authentication.ts` into `headers` on every `page.context().request.post()` / `.put()` / `.delete()` to `/api/auth/*`, `/api/trpc/*`, `/api/v2/*`, `/api/files/*` or `/api/ai/*`. Not needed for `Authorization: Bearer` / `api_` requests (exempt) or GETs.
diff --git a/apps/remix/app/components/embed/embed-authentication-required.tsx b/apps/remix/app/components/embed/embed-authentication-required.tsx
index 8beb4ca98..db37b4461 100644
--- a/apps/remix/app/components/embed/embed-authentication-required.tsx
+++ b/apps/remix/app/components/embed/embed-authentication-required.tsx
@@ -1,26 +1,15 @@
import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';
import { Trans } from '@lingui/react/macro';
-import { SignInForm } from '~/components/forms/signin';
+import { EmbedPopupAuth } from '~/components/embed/embed-popup-auth';
import { BrandingLogo } from '~/components/general/branding-logo';
export type EmbedAuthenticationRequiredProps = {
email?: string;
- returnTo: string;
- isGoogleSSOEnabled?: boolean;
- isMicrosoftSSOEnabled?: boolean;
- isOIDCSSOEnabled?: boolean;
- oidcProviderLabel?: string;
};
-export const EmbedAuthenticationRequired = ({
- email,
- returnTo,
- // isGoogleSSOEnabled,
- // isMicrosoftSSOEnabled,
- // isOIDCSSOEnabled,
- // oidcProviderLabel,
-}: EmbedAuthenticationRequiredProps) => {
+// Rendered from an ErrorBoundary, so providers come from public env rather than loader data.
+export const EmbedAuthenticationRequired = ({ email }: EmbedAuthenticationRequiredProps) => {
return (
<div className="flex min-h-[100dvh] w-full items-center justify-center">
<div className="flex w-full max-w-md flex-col">
@@ -32,16 +21,7 @@ export const EmbedAuthenticationRequired = ({
</AlertDescription>
</Alert>
- <SignInForm
- // Embed currently not supported.
- // isGoogleSSOEnabled={isGoogleSSOEnabled}
- // isMicrosoftSSOEnabled={isMicrosoftSSOEnabled}
- // isOIDCSSOEnabled={isOIDCSSOEnabled}
- // oidcProviderLabel={oidcProviderLabel}
- className="mt-4"
- initialEmail={email}
- returnTo={returnTo}
- />
+ <EmbedPopupAuth className="mt-4" email={email} onSuccess={() => window.location.reload()} />
</div>
</div>
);
diff --git a/apps/remix/app/components/embed/embed-csc-authentication-required.tsx b/apps/remix/app/components/embed/embed-csc-authentication-required.tsx
new file mode 100644
index 000000000..d0872caa4
--- /dev/null
+++ b/apps/remix/app/components/embed/embed-csc-authentication-required.tsx
@@ -0,0 +1,66 @@
+import { useEmbedPopupAuth } from '@documenso/lib/client-only/hooks/use-embed-popup-auth';
+import { Alert, AlertDescription, AlertTitle } from '@documenso/ui/primitives/alert';
+import { Button } from '@documenso/ui/primitives/button';
+import { Trans } from '@lingui/react/macro';
+
+import { EmbedPopupAuthFlowStatus } from '~/components/embed/embed-popup-auth';
+import { BrandingLogo } from '~/components/general/branding-logo';
+import { getCscRecipientBlockedCopy } from '~/components/general/document-signing/csc-recipient-blocked-page';
+
+export type EmbedCscAuthenticationRequiredProps = {
+ token: string;
+
+ blockedCode?: string;
+};
+
+export const EmbedCscAuthenticationRequired = ({ token, blockedCode }: EmbedCscAuthenticationRequiredProps) => {
+ const { status, error, start, continueWithStorageAccess, cancel } = useEmbedPopupAuth({
+ onSuccess: () => window.location.reload(),
+ });
+
+ const isBusy = status !== 'idle' && status !== 'error';
+
+ const blockedCopy = blockedCode ? getCscRecipientBlockedCopy(blockedCode) : null;
+
+ const onStartClick = () => {
+ start('csc', { csc: { scope: 'service', token } });
+ };
+
+ return (
+ <div className="flex min-h-[100dvh] w-full items-center justify-center">
+ <div className="flex w-full max-w-md flex-col gap-y-4">
+ <BrandingLogo className="mb-4 h-8" />
+
+ {blockedCopy ? (
+ <Alert variant="destructive">
+ <AlertTitle>{blockedCopy.title}</AlertTitle>
+
+ <AlertDescription>{blockedCopy.description}</AlertDescription>
+ </Alert>
+ ) : (
+ <Alert variant="warning">
+ <AlertDescription>
+ <Trans>
+ This document requires a qualified electronic signature. Sign in with your signing provider to continue.
+ </Trans>
+ </AlertDescription>
+ </Alert>
+ )}
+
+ <fieldset className="flex w-full flex-col" disabled={isBusy}>
+ <Button type="button" size="lg" onClick={onStartClick}>
+ {blockedCode ? <Trans>Try again</Trans> : <Trans>Sign in with your signing provider</Trans>}
+ </Button>
+ </fieldset>
+
+ <EmbedPopupAuthFlowStatus
+ status={status}
+ error={error}
+ onCancel={cancel}
+ onContinueWithStorageAccess={continueWithStorageAccess}
+ waitingMessage={<Trans>Complete sign in with your signing provider in the popup window</Trans>}
+ />
+ </div>
+ </div>
+ );
+};
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 ff583ed22..afd9a774f 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
@@ -139,11 +139,32 @@ export const EmbedSignDocumentV1ClientPage = ({
return;
}
- await completeDocumentWithToken({
+ const result = await completeDocumentWithToken({
documentId,
token,
});
+ // TSP envelopes return a CSC authorize URL that only the v2 embed can run.
+ if (result.status === 'REDIRECT') {
+ if (window.parent) {
+ window.parent.postMessage(
+ {
+ action: 'document-error',
+ data: null,
+ },
+ '*',
+ );
+ }
+
+ toast({
+ title: _(msg`Unable to sign document`),
+ description: _(msg`Qualified electronic signatures are not supported in this embed.`),
+ variant: 'destructive',
+ });
+
+ return;
+ }
+
if (window.parent) {
window.parent.postMessage(
{
diff --git a/apps/remix/app/components/embed/embed-popup-auth.tsx b/apps/remix/app/components/embed/embed-popup-auth.tsx
new file mode 100644
index 000000000..58f79b7bc
--- /dev/null
+++ b/apps/remix/app/components/embed/embed-popup-auth.tsx
@@ -0,0 +1,204 @@
+import type {
+ EmbedPopupAuthError,
+ EmbedPopupAuthProvider,
+ EmbedPopupAuthStatus,
+} from '@documenso/lib/client-only/hooks/use-embed-popup-auth';
+import { useEmbedPopupAuth } from '@documenso/lib/client-only/hooks/use-embed-popup-auth';
+import { isSigninEnabledForProvider } from '@documenso/lib/constants/auth';
+import { getEmbedPopupAuthProviders } from '@documenso/lib/constants/embed-auth';
+import { cn } from '@documenso/ui/lib/utils';
+import { Alert, AlertDescription, AlertTitle } from '@documenso/ui/primitives/alert';
+import { Button } from '@documenso/ui/primitives/button';
+import { Trans } from '@lingui/react/macro';
+import { KeyRoundIcon, Loader2Icon, MailIcon } from 'lucide-react';
+import type { ReactNode } from 'react';
+import { FaIdCardClip } from 'react-icons/fa6';
+import { FcGoogle } from 'react-icons/fc';
+import { match } from 'ts-pattern';
+
+export type EmbedPopupAuthProps = {
+ className?: string;
+
+ email?: string;
+
+ // No sign out step is needed; redeem always overwrites the embed session cookie.
+ signedInAs?: string;
+
+ onSuccess: () => void;
+};
+
+export const EmbedPopupAuth = ({ className, email, signedInAs, onSuccess }: EmbedPopupAuthProps) => {
+ const { status, error, start, continueWithStorageAccess, cancel } = useEmbedPopupAuth({ onSuccess });
+
+ const providers = getEmbedPopupAuthProviders();
+
+ const isIdle = status === 'idle' || status === 'error';
+ const isBusy = !isIdle;
+
+ const isEmailPasswordSigninEnabled = isSigninEnabledForProvider('email');
+
+ const onProviderClick = (provider: Exclude<EmbedPopupAuthProvider, 'csc'>) => {
+ start(provider, { email });
+ };
+
+ return (
+ <div className={cn('flex w-full flex-col gap-y-4', className)}>
+ {signedInAs && (
+ <p className="text-muted-foreground text-sm">
+ <Trans>
+ You are currently signed in as <strong>{signedInAs}</strong>. Signing in below will switch accounts.
+ </Trans>
+ </p>
+ )}
+
+ <fieldset className="flex w-full flex-col gap-y-4" disabled={isBusy}>
+ {providers.account && (
+ <Button type="button" size="lg" onClick={() => onProviderClick('account')}>
+ {isEmailPasswordSigninEnabled ? (
+ <>
+ <MailIcon className="mr-2 h-4 w-4" />
+ <Trans>Sign in with email or passkey</Trans>
+ </>
+ ) : (
+ <>
+ <KeyRoundIcon className="mr-2 h-4 w-4" />
+ <Trans>Sign in with passkey</Trans>
+ </>
+ )}
+ </Button>
+ )}
+
+ {providers.google && (
+ <Button
+ type="button"
+ size="lg"
+ variant="outline"
+ className="border bg-background text-muted-foreground"
+ onClick={() => onProviderClick('google')}
+ >
+ <FcGoogle className="mr-2 h-5 w-5" />
+ Google
+ </Button>
+ )}
+
+ {providers.microsoft && (
+ <Button
+ type="button"
+ size="lg"
+ variant="outline"
+ className="border bg-background text-muted-foreground"
+ onClick={() => onProviderClick('microsoft')}
+ >
+ <img className="mr-2 h-4 w-4" alt="Microsoft Logo" src={'/static/microsoft.svg'} />
+ Microsoft
+ </Button>
+ )}
+
+ {providers.oidc && (
+ <Button
+ type="button"
+ size="lg"
+ variant="outline"
+ className="border bg-background text-muted-foreground"
+ onClick={() => onProviderClick('oidc')}
+ >
+ <FaIdCardClip className="mr-2 h-5 w-5" />
+ {providers.oidcProviderLabel || 'OIDC'}
+ </Button>
+ )}
+ </fieldset>
+
+ <EmbedPopupAuthFlowStatus
+ status={status}
+ error={error}
+ onCancel={cancel}
+ onContinueWithStorageAccess={continueWithStorageAccess}
+ />
+ </div>
+ );
+};
+
+export type EmbedPopupAuthFlowStatusProps = {
+ status: EmbedPopupAuthStatus;
+ error: EmbedPopupAuthError | null;
+ onCancel: () => void;
+ onContinueWithStorageAccess: () => void | Promise<void>;
+
+ waitingMessage?: ReactNode;
+};
+
+export const EmbedPopupAuthFlowStatus = ({
+ status,
+ error,
+ onCancel,
+ onContinueWithStorageAccess,
+ waitingMessage,
+}: EmbedPopupAuthFlowStatusProps) => {
+ return (
+ <>
+ {(status === 'waiting' || status === 'redeeming') && (
+ <div className="flex flex-col items-center gap-y-3">
+ <p className="flex items-center justify-center gap-x-2 text-center text-muted-foreground text-sm">
+ <Loader2Icon className="h-4 w-4 animate-spin" />
+ {status === 'waiting' ? (
+ (waitingMessage ?? <Trans>Complete sign in in the popup window</Trans>)
+ ) : (
+ <Trans>Signing you in...</Trans>
+ )}
+ </p>
+
+ <Button type="button" variant="secondary" size="sm" onClick={onCancel}>
+ <Trans>Cancel</Trans>
+ </Button>
+ </div>
+ )}
+
+ {status === 'needs-storage-access' && (
+ <Alert variant="warning">
+ <AlertTitle>
+ <Trans>Almost there</Trans>
+ </AlertTitle>
+
+ <AlertDescription>
+ <Trans>
+ Your browser needs permission to keep you signed in inside this embed. Press Continue and allow access
+ when Safari asks.
+ </Trans>
+ </AlertDescription>
+
+ <Button type="button" size="sm" className="mt-2" onClick={() => void onContinueWithStorageAccess()}>
+ <Trans>Continue</Trans>
+ </Button>
+ </Alert>
+ )}
+
+ {status === 'error' && error && (
+ <Alert variant="destructive">
+ <AlertDescription>
+ <EmbedPopupAuthErrorMessage error={error} />
+ </AlertDescription>
+ </Alert>
+ )}
+ </>
+ );
+};
+
+const EmbedPopupAuthErrorMessage = ({ error }: { error: EmbedPopupAuthError }) => {
+ return match(error)
+ .with('popup-blocked', () => (
+ <Trans>Your browser blocked the sign in window. Allow popups for this site and try again.</Trans>
+ ))
+ .with('timeout', () => <Trans>Sign in timed out. Please try again.</Trans>)
+ .with('auth-failed', () => <Trans>Sign in did not complete. Please try again.</Trans>)
+ .with('cookie-blocked', () => (
+ <Trans>
+ Your browser is blocking the cookies needed to keep you signed in inside this embed. Open this document in a new
+ tab instead.
+ </Trans>
+ ))
+ .with('storage-access-denied', () => (
+ <Trans>Storage access was denied, so we cannot keep you signed in inside this embed. Please try again.</Trans>
+ ))
+ .with('request-failed', () => <Trans>Something went wrong while signing you in. Please try again.</Trans>)
+ .exhaustive();
+};
diff --git a/apps/remix/app/components/embed/multisign/multi-sign-document-signing-view.tsx b/apps/remix/app/components/embed/multisign/multi-sign-document-signing-view.tsx
index 8964033a6..1c49af7b3 100644
--- a/apps/remix/app/components/embed/multisign/multi-sign-document-signing-view.tsx
+++ b/apps/remix/app/components/embed/multisign/multi-sign-document-signing-view.tsx
@@ -143,11 +143,24 @@ export const MultiSignDocumentSigningView = ({
try {
setIsSubmitting(true);
- await completeDocumentWithToken({
+ const result = await completeDocumentWithToken({
documentId: document!.id,
token,
});
+ // TSP envelopes return a CSC authorize URL the multisign embed cannot run.
+ if (result.status === 'REDIRECT') {
+ onDocumentError?.();
+
+ toast({
+ title: _(msg`Unable to sign document`),
+ description: _(msg`Qualified electronic signatures are not supported in this embed.`),
+ variant: 'destructive',
+ });
+
+ return;
+ }
+
onBack();
onDocumentCompleted?.({
diff --git a/apps/remix/app/components/forms/signin.tsx b/apps/remix/app/components/forms/signin.tsx
index 6270bc948..2a83d3101 100644
--- a/apps/remix/app/components/forms/signin.tsx
+++ b/apps/remix/app/components/forms/signin.tsx
@@ -65,6 +65,11 @@ export type SignInFormProps = {
isOIDCSSOEnabled?: boolean;
oidcProviderLabel?: string;
returnTo?: string;
+
+ hideForgotPassword?: boolean;
+
+ /** Called instead of navigating to `/unverified-account`. */
+ onUnverifiedEmail?: () => void;
};
export const SignInForm = ({
@@ -76,6 +81,8 @@ export const SignInForm = ({
isOIDCSSOEnabled,
oidcProviderLabel,
returnTo,
+ hideForgotPassword = false,
+ onUnverifiedEmail,
}: SignInFormProps) => {
const { _ } = useLingui();
const { toast } = useToast();
@@ -83,7 +90,6 @@ export const SignInForm = ({
const navigate = useNavigate();
const [isTwoFactorAuthenticationDialogOpen, setIsTwoFactorAuthenticationDialogOpen] = useState(false);
- const [isEmbeddedRedirect, setIsEmbeddedRedirect] = useState(false);
const [twoFactorAuthenticationMethod, setTwoFactorAuthenticationMethod] = useState<'totp' | 'backup'>('totp');
@@ -238,6 +244,12 @@ export const SignInForm = ({
}
if (error.code === AuthenticationErrorCode.UnverifiedEmail) {
+ if (onUnverifiedEmail) {
+ onUnverifiedEmail();
+
+ return;
+ }
+
await navigate('/unverified-account');
toast({
@@ -319,8 +331,6 @@ export const SignInForm = ({
if (email) {
form.setValue('email', email);
}
-
- setIsEmbeddedRedirect(params.get('embedded') === 'true');
}, [form]);
return (
@@ -362,14 +372,16 @@ export const SignInForm = ({
<FormMessage />
- <p className="mt-2 text-right">
- <Link
- to="/forgot-password"
- className="text-muted-foreground text-sm duration-200 hover:opacity-70"
- >
- <Trans>Forgot your password?</Trans>
- </Link>
- </p>
+ {!hideForgotPassword && (
+ <p className="mt-2 text-right">
+ <Link
+ to="/forgot-password"
+ className="text-muted-foreground text-sm duration-200 hover:opacity-70"
+ >
+ <Trans>Forgot your password?</Trans>
+ </Link>
+ </p>
+ )}
</FormItem>
)}
/>
@@ -396,60 +408,56 @@ export const SignInForm = ({
</>
)}
- {!isEmbeddedRedirect && (
- <>
- {isEmailPasswordSigninEnabled && hasSocialAuthEnabled && (
- <div className="relative flex items-center justify-center gap-x-4 py-2 text-xs uppercase">
- <div className="h-px flex-1 bg-border" />
- <span className="bg-transparent text-muted-foreground">
- <Trans>Or continue with</Trans>
- </span>
- <div className="h-px flex-1 bg-border" />
- </div>
- )}
+ {isEmailPasswordSigninEnabled && hasSocialAuthEnabled && (
+ <div className="relative flex items-center justify-center gap-x-4 py-2 text-xs uppercase">
+ <div className="h-px flex-1 bg-border" />
+ <span className="bg-transparent text-muted-foreground">
+ <Trans>Or continue with</Trans>
+ </span>
+ <div className="h-px flex-1 bg-border" />
+ </div>
+ )}
- {isGoogleSSOEnabled && (
- <Button
- type="button"
- size="lg"
- variant="outline"
- className="border bg-background text-muted-foreground"
- disabled={isSubmitting}
- onClick={onSignInWithGoogleClick}
- >
- <FcGoogle className="mr-2 h-5 w-5" />
- Google
- </Button>
- )}
+ {isGoogleSSOEnabled && (
+ <Button
+ type="button"
+ size="lg"
+ variant="outline"
+ className="border bg-background text-muted-foreground"
+ disabled={isSubmitting}
+ onClick={onSignInWithGoogleClick}
+ >
+ <FcGoogle className="mr-2 h-5 w-5" />
+ Google
+ </Button>
+ )}
- {isMicrosoftSSOEnabled && (
- <Button
- type="button"
- size="lg"
- variant="outline"
- className="border bg-background text-muted-foreground"
- 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="border bg-background text-muted-foreground"
+ 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="border bg-background text-muted-foreground"
- disabled={isSubmitting}
- onClick={onSignInWithOIDCClick}
- >
- <FaIdCardClip className="mr-2 h-5 w-5" />
- {oidcProviderLabel || 'OIDC'}
- </Button>
- )}
- </>
+ {isOIDCSSOEnabled && (
+ <Button
+ type="button"
+ size="lg"
+ variant="outline"
+ className="border bg-background text-muted-foreground"
+ disabled={isSubmitting}
+ onClick={onSignInWithOIDCClick}
+ >
+ <FaIdCardClip className="mr-2 h-5 w-5" />
+ {oidcProviderLabel || 'OIDC'}
+ </Button>
)}
<Button
diff --git a/apps/remix/app/components/general/document-signing/csc-recipient-blocked-page.tsx b/apps/remix/app/components/general/document-signing/csc-recipient-blocked-page.tsx
index 0e2bb6fb2..86cbc937c 100644
--- a/apps/remix/app/components/general/document-signing/csc-recipient-blocked-page.tsx
+++ b/apps/remix/app/components/general/document-signing/csc-recipient-blocked-page.tsx
@@ -2,6 +2,7 @@ import { AppErrorCode } from '@documenso/lib/errors/app-error';
import { Button } from '@documenso/ui/primitives/button';
import { Trans } from '@lingui/react/macro';
import { AlertTriangleIcon } from 'lucide-react';
+import { match } from 'ts-pattern';
export type CscRecipientBlockedPageProps = {
code: string;
@@ -21,41 +22,18 @@ export type CscRecipientBlockedPageProps = {
export const CscRecipientBlockedPage = ({ code, recipientToken }: CscRecipientBlockedPageProps) => {
const retryUrl = `/api/csc/oauth/authorize?scope=service&token=${encodeURIComponent(recipientToken)}`;
+ const { title, description } = getCscRecipientBlockedCopy(code);
+
return (
<div className="-mx-4 flex max-w-[100vw] flex-col items-center overflow-x-hidden px-4 pt-16 md:-mx-8 md:px-8 lg:pt-16 xl:pt-24">
<AlertTriangleIcon className="h-12 w-12 text-destructive" />
<h2 className="mt-6 max-w-[35ch] text-center font-semibold text-2xl leading-normal md:text-3xl lg:text-4xl">
- {code === AppErrorCode.CSC_CREDENTIAL_LIST_EMPTY ? (
- <Trans>No signing credentials available</Trans>
- ) : code === AppErrorCode.CSC_CERT_INVALID ? (
- <Trans>Signing certificate is invalid</Trans>
- ) : code === AppErrorCode.CSC_ALGORITHM_REFUSED ? (
- <Trans>Signing algorithm is not supported</Trans>
- ) : (
- <Trans>Unable to start the signing flow</Trans>
- )}
+ {title}
</h2>
<p className="mt-2.5 max-w-[60ch] text-center font-medium text-muted-foreground/60 text-sm md:text-base">
- {code === AppErrorCode.CSC_CREDENTIAL_LIST_EMPTY ? (
- <Trans>
- Your signing provider returned no usable credentials for this account. Contact your administrator or signing
- provider for assistance.
- </Trans>
- ) : code === AppErrorCode.CSC_CERT_INVALID ? (
- <Trans>
- Your signing certificate is invalid, expired, or missing a required key. Contact your administrator or
- signing provider for assistance.
- </Trans>
- ) : code === AppErrorCode.CSC_ALGORITHM_REFUSED ? (
- <Trans>
- Your signing provider does not advertise a signing algorithm this document accepts. Contact your
- administrator or signing provider for assistance.
- </Trans>
- ) : (
- <Trans>Something went wrong while preparing the remote signature. Please try again.</Trans>
- )}
+ {description}
</p>
<Button asChild className="mt-8">
@@ -66,3 +44,37 @@ export const CscRecipientBlockedPage = ({ code, recipientToken }: CscRecipientBl
</div>
);
};
+
+export const getCscRecipientBlockedCopy = (code: string) =>
+ match(code)
+ .with(AppErrorCode.CSC_CREDENTIAL_LIST_EMPTY, () => ({
+ title: <Trans>No signing credentials available</Trans>,
+ description: (
+ <Trans>
+ Your signing provider returned no usable credentials for this account. Contact your administrator or signing
+ provider for assistance.
+ </Trans>
+ ),
+ }))
+ .with(AppErrorCode.CSC_CERT_INVALID, () => ({
+ title: <Trans>Signing certificate is invalid</Trans>,
+ description: (
+ <Trans>
+ Your signing certificate is invalid, expired, or missing a required key. Contact your administrator or signing
+ provider for assistance.
+ </Trans>
+ ),
+ }))
+ .with(AppErrorCode.CSC_ALGORITHM_REFUSED, () => ({
+ title: <Trans>Signing algorithm is not supported</Trans>,
+ description: (
+ <Trans>
+ Your signing provider does not advertise a signing algorithm this document accepts. Contact your administrator
+ or signing provider for assistance.
+ </Trans>
+ ),
+ }))
+ .otherwise(() => ({
+ title: <Trans>Unable to start the signing flow</Trans>,
+ description: <Trans>Something went wrong while preparing the remote signature. Please try again.</Trans>,
+ }));
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.tsx
index 509cddced..09fa9a935 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
@@ -1,4 +1,6 @@
import { authClient } from '@documenso/auth/client';
+import { useIsFramed } from '@documenso/lib/client-only/hooks/use-is-framed';
+import { useOptionalSession } from '@documenso/lib/client-only/providers/session';
import { formatPath } from '@documenso/lib/constants/app';
import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';
import { Button } from '@documenso/ui/primitives/button';
@@ -7,8 +9,11 @@ import { useToast } from '@documenso/ui/primitives/use-toast';
import { Trans, useLingui } from '@lingui/react/macro';
import { RecipientRole } from '@prisma/client';
import { useState } from 'react';
+import { useRevalidator } from 'react-router';
import { match } from 'ts-pattern';
+import { EmbedPopupAuth } from '~/components/embed/embed-popup-auth';
+
import { useRequiredDocumentSigningAuthContext } from './document-signing-auth-provider';
export type DocumentSigningAuthAccountProps = {
@@ -20,24 +25,38 @@ export const DocumentSigningAuthAccount = ({
actionTarget = 'FIELD',
onOpenChange,
}: DocumentSigningAuthAccountProps) => {
- const { recipient, isDirectTemplate } = useRequiredDocumentSigningAuthContext();
+ const { recipient, user, isDirectTemplate } = useRequiredDocumentSigningAuthContext();
const { t } = useLingui();
const { toast } = useToast();
+ const isFramed = useIsFramed();
+
+ const { refreshSession } = useOptionalSession();
+ const { revalidate } = useRevalidator();
+
const [isSigningOut, setIsSigningOut] = useState(false);
+ // Direct templates accept any account, so a mismatch only matters for regular recipients.
+ const mismatchedUserEmail = user && !isDirectTemplate && user.email !== recipient.email ? user.email : undefined;
+
+ const onPopupAuthSuccess = async () => {
+ await Promise.all([refreshSession(), revalidate()]);
+
+ onOpenChange(false);
+ };
+
const handleChangeAccount = async (email: string) => {
try {
setIsSigningOut(true);
const currentPath = `${window.location.pathname}${window.location.search}${window.location.hash}`;
+ const emailHash = isDirectTemplate ? '' : `#email=${encodeURIComponent(email)}`;
+
await authClient.signOut({
- redirectPath: formatPath(
- `/signin?returnTo=${encodeURIComponent(currentPath)}#embedded=true&email=${isDirectTemplate ? '' : email}`,
- ),
+ redirectPath: formatPath(`/signin?returnTo=${encodeURIComponent(currentPath)}${emailHash}`),
});
} catch {
setIsSigningOut(false);
@@ -152,15 +171,31 @@ export const DocumentSigningAuthAccount = ({
</AlertDescription>
</Alert>
- <DialogFooter>
- <Button type="button" variant="secondary" onClick={() => onOpenChange(false)}>
- <Trans>Cancel</Trans>
- </Button>
+ {isFramed ? (
+ <>
+ <EmbedPopupAuth
+ email={isDirectTemplate ? undefined : recipient.email}
+ signedInAs={mismatchedUserEmail}
+ onSuccess={() => void onPopupAuthSuccess()}
+ />
+
+ <DialogFooter>
+ <Button type="button" variant="secondary" onClick={() => onOpenChange(false)}>
+ <Trans>Cancel</Trans>
+ </Button>
+ </DialogFooter>
+ </>
+ ) : (
+ <DialogFooter>
+ <Button type="button" variant="secondary" onClick={() => onOpenChange(false)}>
+ <Trans>Cancel</Trans>
+ </Button>
- <Button onClick={async () => handleChangeAccount(recipient.email)} loading={isSigningOut}>
- <Trans>Login</Trans>
- </Button>
- </DialogFooter>
+ <Button onClick={async () => handleChangeAccount(recipient.email)} loading={isSigningOut}>
+ <Trans>Login</Trans>
+ </Button>
+ </DialogFooter>
+ )}
</fieldset>
);
};
diff --git a/apps/remix/app/components/general/document-signing/document-signing-auth-page.tsx b/apps/remix/app/components/general/document-signing/document-signing-auth-page.tsx
index a762eef57..0df2b6e5e 100644
--- a/apps/remix/app/components/general/document-signing/document-signing-auth-page.tsx
+++ b/apps/remix/app/components/general/document-signing/document-signing-auth-page.tsx
@@ -1,4 +1,6 @@
import { authClient } from '@documenso/auth/client';
+import { useIsFramed } from '@documenso/lib/client-only/hooks/use-is-framed';
+import { useOptionalSession } from '@documenso/lib/client-only/providers/session';
import { formatPath } from '@documenso/lib/constants/app';
import { Button } from '@documenso/ui/primitives/button';
import { useToast } from '@documenso/ui/primitives/use-toast';
@@ -7,6 +9,8 @@ import { useLingui } from '@lingui/react';
import { Trans } from '@lingui/react/macro';
import { useState } from 'react';
+import { EmbedPopupAuth } from '~/components/embed/embed-popup-auth';
+
export type DocumentSigningAuthPageViewProps = {
email?: string;
emailHasAccount?: boolean;
@@ -16,8 +20,15 @@ export const DocumentSigningAuthPageView = ({ email, emailHasAccount }: Document
const { _ } = useLingui();
const { toast } = useToast();
+ const isFramed = useIsFramed();
+
+ const { sessionData } = useOptionalSession();
+
const [isSigningOut, setIsSigningOut] = useState(false);
+ const mismatchedUserEmail =
+ sessionData?.user && email && sessionData.user.email !== email ? sessionData.user.email : undefined;
+
const handleChangeAccount = async (email?: string) => {
try {
setIsSigningOut(true);
@@ -45,7 +56,7 @@ export const DocumentSigningAuthPageView = ({ email, emailHasAccount }: Document
return (
<div className="mx-auto flex h-[70vh] w-full max-w-md flex-col items-center justify-center">
- <div>
+ <div className="w-full">
<h1 className="font-semibold text-3xl">
<Trans>Authentication required</Trans>
</h1>
@@ -60,14 +71,23 @@ export const DocumentSigningAuthPageView = ({ email, emailHasAccount }: Document
)}
</p>
- <Button
- className="mt-4 w-full"
- type="submit"
- onClick={async () => handleChangeAccount(email)}
- loading={isSigningOut}
- >
- {emailHasAccount ? <Trans>Login</Trans> : <Trans>Sign up</Trans>}
- </Button>
+ {isFramed ? (
+ <EmbedPopupAuth
+ className="mt-4"
+ email={email || undefined}
+ signedInAs={mismatchedUserEmail}
+ onSuccess={() => window.location.reload()}
+ />
+ ) : (
+ <Button
+ className="mt-4 w-full"
+ type="submit"
+ onClick={async () => handleChangeAccount(email)}
+ loading={isSigningOut}
+ >
+ {emailHasAccount ? <Trans>Login</Trans> : <Trans>Sign up</Trans>}
+ </Button>
+ )}
</div>
</div>
);
diff --git a/apps/remix/app/components/general/document-signing/document-signing-auth-passkey.tsx b/apps/remix/app/components/general/document-signing/document-signing-auth-passkey.tsx
index 0b5f24d12..e930b86ad 100644
--- a/apps/remix/app/components/general/document-signing/document-signing-auth-passkey.tsx
+++ b/apps/remix/app/components/general/document-signing/document-signing-auth-passkey.tsx
@@ -1,3 +1,4 @@
+import { useIsFramed } from '@documenso/lib/client-only/hooks/use-is-framed';
import { AppError } from '@documenso/lib/errors/app-error';
import { DocumentAuth, type TRecipientActionAuth } from '@documenso/lib/types/document-auth';
import { trpc } from '@documenso/trpc/react';
@@ -64,6 +65,9 @@ export const DocumentSigningAuthPasskey = ({
trpc.auth.passkey.createAuthenticationOptions.useMutation();
const [formErrorCode, setFormErrorCode] = useState<string | null>(null);
+ const [isBlockedByEmbed, setIsBlockedByEmbed] = useState(false);
+
+ const isFramed = useIsFramed();
const onFormSubmit = async ({ passkeyId }: TPasskeyAuthFormSchema) => {
try {
@@ -89,6 +93,11 @@ export const DocumentSigningAuthPasskey = ({
setIsCurrentlyAuthenticating(false);
if (err.name === 'NotAllowedError') {
+ // Inside an iframe this is most likely a missing `allow="publickey-credentials-get"`.
+ if (isFramed) {
+ setIsBlockedByEmbed(true);
+ }
+
return;
}
@@ -105,6 +114,7 @@ export const DocumentSigningAuthPasskey = ({
});
setFormErrorCode(null);
+ setIsBlockedByEmbed(false);
}, [open, form, preferredPasskeyId]);
if (!browserSupportsWebAuthn()) {
@@ -281,6 +291,17 @@ export const DocumentSigningAuthPasskey = ({
)}
/>
+ {isBlockedByEmbed && (
+ <Alert variant="warning">
+ <AlertDescription>
+ <Trans>
+ Passkeys could not be used here. If this document is embedded in another site, that site needs to
+ allow passkeys for the embed.
+ </Trans>
+ </AlertDescription>
+ </Alert>
+ )}
+
{formErrorCode && (
<Alert variant="destructive">
<AlertTitle>
diff --git a/apps/remix/app/components/general/document-signing/document-signing-complete-dialog.tsx b/apps/remix/app/components/general/document-signing/document-signing-complete-dialog.tsx
index b8caa4a83..39b466dbb 100644
--- a/apps/remix/app/components/general/document-signing/document-signing-complete-dialog.tsx
+++ b/apps/remix/app/components/general/document-signing/document-signing-complete-dialog.tsx
@@ -20,6 +20,7 @@ import { zodResolver } from '@hookform/resolvers/zod';
import { Trans, useLingui } from '@lingui/react/macro';
import type { Field, Recipient } from '@prisma/client';
import { RecipientRole } from '@prisma/client';
+import type { ReactNode } from 'react';
import { useMemo, useState } from 'react';
import { useForm } from 'react-hook-form';
import { match } from 'ts-pattern';
@@ -57,6 +58,11 @@ export type DocumentSigningCompleteDialogProps = {
buttonSize?: 'sm' | 'lg';
position?: 'start' | 'end' | 'center';
disableNameInput?: boolean;
+
+ /** When provided, replaces the confirmation form (and 2FA step) as the dialog body. */
+ children?: ReactNode;
+
+ onOpenChange?: (open: boolean) => void;
};
const ZNextSignerFormSchema = z.object({
@@ -88,6 +94,8 @@ export const DocumentSigningCompleteDialog = ({
buttonSize = 'lg',
position,
disableNameInput = false,
+ children,
+ onOpenChange,
}: DocumentSigningCompleteDialogProps) => {
const analytics = useAnalytics();
const { t, i18n } = useLingui();
@@ -140,6 +148,7 @@ export const DocumentSigningCompleteDialog = ({
}
setShowDialog(open);
+ onOpenChange?.(open);
};
const onFormSubmit = async (data: TNextSignerFormSchema) => {
@@ -270,75 +279,36 @@ export const DocumentSigningCompleteDialog = ({
<p className="font-medium text-muted-foreground text-sm">{documentTitle}</p>
</div>
- {!showTwoFactorForm && (
- <fieldset disabled={form.formState.isSubmitting} className="border-none p-0">
- {recipientPayload && !recipientPayload.email && (
- <Form {...recipientForm}>
- <div className="mb-4 flex flex-col gap-4">
- <div className="flex flex-col gap-4 md:flex-row">
- <FormField
- control={recipientForm.control}
- name="name"
- render={({ field }) => (
- <FormItem className="flex-1">
- <FormLabel>
- <Trans>Your Name</Trans>
- </FormLabel>
- <FormControl>
- <Input
- {...field}
- className="mt-2"
- placeholder={t`Enter your name`}
- disabled={isNameLocked || disableNameInput}
- />
- </FormControl>
-
- <FormMessage />
- </FormItem>
- )}
- />
-
- <FormField
- control={recipientForm.control}
- name="email"
- render={({ field }) => (
- <FormItem className="flex-1">
- <FormLabel>
- <Trans>Your Email</Trans>
- </FormLabel>
- <FormControl>
- <Input
- {...field}
- type="email"
- className="mt-2"
- placeholder={t`Enter your email`}
- disabled={!!field.value && isEmailLocked}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- </div>
- </Form>
- )}
-
- <Form {...form}>
- <form onSubmit={form.handleSubmit(onFormSubmit)}>
- {canDictateNextSigner && (
+ {match({ hasChildren: Boolean(children), showTwoFactorForm })
+ .with({ hasChildren: true }, () => children)
+ .with({ showTwoFactorForm: true }, () => (
+ <AccessAuth2FAForm
+ token={recipient.token}
+ error={twoFactorValidationError}
+ onSubmit={onTwoFactorFormSubmit}
+ />
+ ))
+ .otherwise(() => (
+ <fieldset disabled={form.formState.isSubmitting} className="border-none p-0">
+ {recipientPayload && !recipientPayload.email && (
+ <Form {...recipientForm}>
<div className="mb-4 flex flex-col gap-4">
<div className="flex flex-col gap-4 md:flex-row">
<FormField
- control={form.control}
+ control={recipientForm.control}
name="name"
render={({ field }) => (
<FormItem className="flex-1">
<FormLabel>
- <Trans>Next Recipient Name</Trans>
+ <Trans>Your Name</Trans>
</FormLabel>
<FormControl>
- <Input {...field} className="mt-2" placeholder={t`Enter the next signer's name`} />
+ <Input
+ {...field}
+ className="mt-2"
+ placeholder={t`Enter your name`}
+ disabled={isNameLocked || disableNameInput}
+ />
</FormControl>
<FormMessage />
@@ -347,19 +317,20 @@ export const DocumentSigningCompleteDialog = ({
/>
<FormField
- control={form.control}
+ control={recipientForm.control}
name="email"
render={({ field }) => (
<FormItem className="flex-1">
<FormLabel>
- <Trans>Next Recipient Email</Trans>
+ <Trans>Your Email</Trans>
</FormLabel>
<FormControl>
<Input
{...field}
type="email"
className="mt-2"
- placeholder={t`Enter the next signer's email`}
+ placeholder={t`Enter your email`}
+ disabled={!!field.value && isEmailLocked}
/>
</FormControl>
<FormMessage />
@@ -368,42 +339,81 @@ export const DocumentSigningCompleteDialog = ({
/>
</div>
</div>
- )}
-
- <DocumentSigningDisclosure />
-
- <DialogFooter className="mt-4">
- <Button
- type="button"
- variant="secondary"
- onClick={() => setShowDialog(false)}
- disabled={form.formState.isSubmitting}
- >
- <Trans>Cancel</Trans>
- </Button>
-
- <Button type="submit" disabled={!isComplete} loading={form.formState.isSubmitting}>
- {match(recipient.role)
- .with(RecipientRole.VIEWER, () => <Trans>Mark as Viewed</Trans>)
- .with(RecipientRole.SIGNER, () => <Trans>Sign</Trans>)
- .with(RecipientRole.APPROVER, () => <Trans>Approve</Trans>)
- .with(RecipientRole.CC, () => <Trans>Mark as Viewed</Trans>)
- .with(RecipientRole.ASSISTANT, () => <Trans>Complete</Trans>)
- .exhaustive()}
- </Button>
- </DialogFooter>
- </form>
- </Form>
- </fieldset>
- )}
-
- {showTwoFactorForm && (
- <AccessAuth2FAForm
- token={recipient.token}
- error={twoFactorValidationError}
- onSubmit={onTwoFactorFormSubmit}
- />
- )}
+ </Form>
+ )}
+
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onFormSubmit)}>
+ {canDictateNextSigner && (
+ <div className="mb-4 flex flex-col gap-4">
+ <div className="flex flex-col gap-4 md:flex-row">
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem className="flex-1">
+ <FormLabel>
+ <Trans>Next Recipient Name</Trans>
+ </FormLabel>
+ <FormControl>
+ <Input {...field} className="mt-2" placeholder={t`Enter the next signer's name`} />
+ </FormControl>
+
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="email"
+ render={({ field }) => (
+ <FormItem className="flex-1">
+ <FormLabel>
+ <Trans>Next Recipient Email</Trans>
+ </FormLabel>
+ <FormControl>
+ <Input
+ {...field}
+ type="email"
+ className="mt-2"
+ placeholder={t`Enter the next signer's email`}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+ </div>
+ )}
+
+ <DocumentSigningDisclosure />
+
+ <DialogFooter className="mt-4">
+ <Button
+ type="button"
+ variant="secondary"
+ onClick={() => setShowDialog(false)}
+ disabled={form.formState.isSubmitting}
+ >
+ <Trans>Cancel</Trans>
+ </Button>
+
+ <Button type="submit" disabled={!isComplete} loading={form.formState.isSubmitting}>
+ {match(recipient.role)
+ .with(RecipientRole.VIEWER, () => <Trans>Mark as Viewed</Trans>)
+ .with(RecipientRole.SIGNER, () => <Trans>Sign</Trans>)
+ .with(RecipientRole.APPROVER, () => <Trans>Approve</Trans>)
+ .with(RecipientRole.CC, () => <Trans>Mark as Viewed</Trans>)
+ .with(RecipientRole.ASSISTANT, () => <Trans>Complete</Trans>)
+ .exhaustive()}
+ </Button>
+ </DialogFooter>
+ </form>
+ </Form>
+ </fieldset>
+ ))}
</DialogContent>
</Dialog>
);
diff --git a/apps/remix/app/components/general/envelope-signing/envelope-signing-complete-dialog.tsx b/apps/remix/app/components/general/envelope-signing/envelope-signing-complete-dialog.tsx
index c522419ca..3f836be9b 100644
--- a/apps/remix/app/components/general/envelope-signing/envelope-signing-complete-dialog.tsx
+++ b/apps/remix/app/components/general/envelope-signing/envelope-signing-complete-dialog.tsx
@@ -1,21 +1,28 @@
import { useAnalytics } from '@documenso/lib/client-only/hooks/use-analytics';
+import type { EmbedPopupAuthCscOptions } from '@documenso/lib/client-only/hooks/use-embed-popup-auth';
+import { openPopupWindow, useEmbedPopupAuth } from '@documenso/lib/client-only/hooks/use-embed-popup-auth';
+import { useIsFramed } from '@documenso/lib/client-only/hooks/use-is-framed';
import { useCurrentEnvelopeRender } from '@documenso/lib/client-only/providers/envelope-render-provider';
import { PDF_VIEWER_CONTENT_SELECTOR } from '@documenso/lib/constants/pdf-viewer';
import { isBase64Image } from '@documenso/lib/constants/signatures';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import type { TRecipientAccessAuth } from '@documenso/lib/types/document-auth';
+import { isTspEnvelope } from '@documenso/lib/types/signature-level';
import { mapSecondaryIdToDocumentId } from '@documenso/lib/utils/envelope';
import { trpc } from '@documenso/trpc/react';
import { useToast } from '@documenso/ui/primitives/use-toast';
import { useLingui } from '@lingui/react/macro';
import { FieldType } from '@prisma/client';
-import { useMemo } from 'react';
+import { useMemo, useState } from 'react';
import { useNavigate, useRevalidator, useSearchParams } from 'react-router';
import { useEmbedSigningContext } from '~/components/embed/embed-signing-context';
import { DocumentSigningCompleteDialog } from '../document-signing/document-signing-complete-dialog';
import { useRequiredEnvelopeSigningContext } from '../document-signing/envelope-signing-provider';
+import { EnvelopeSigningCscStatus } from './envelope-signing-csc-status';
+
+type PendingCscSigning = Extract<EmbedPopupAuthCscOptions, { scope: 'credential' }>;
export const EnvelopeSignerCompleteDialog = () => {
const navigate = useNavigate();
@@ -42,15 +49,114 @@ export const EnvelopeSignerCompleteDialog = () => {
const { onDocumentCompleted, onDocumentError } = useEmbedSigningContext() || {};
- const {
- mutateAsync: completeDocument,
- isPending,
- isSuccess,
- } = trpc.recipient.completeDocumentWithToken.useMutation();
+ const isFramed = useIsFramed();
+
+ const { mutateAsync: completeDocument, isPending } = trpc.recipient.completeDocumentWithToken.useMutation();
const { mutateAsync: createDocumentFromDirectTemplate } =
trpc.template.createDocumentFromDirectTemplate.useMutation();
+ const {
+ mutateAsync: signEnvelopeWithCsc,
+ isPending: isSigningWithCsc,
+ error: cscSignError,
+ reset: resetCscSignMutation,
+ } = trpc.enterprise.csc.signEnvelope.useMutation();
+
+ // Keeps the trigger locked while the browser navigates to the completed page.
+ const [isRedirecting, setIsRedirecting] = useState(false);
+
+ // Set while the embedded CSC popup flow owns the dialog body. Kept across
+ // popup errors so a retry can reopen the popup without re-preparing the session.
+ const [pendingCsc, setPendingCsc] = useState<PendingCscSigning | null>(null);
+
+ const cscPopupAuth = useEmbedPopupAuth({
+ onSuccess: () => void handleCscAuthorised(),
+ });
+
+ const isCscPopupBusy = cscPopupAuth.status !== 'idle' && cscPopupAuth.status !== 'error';
+
+ const cscSignErrorCode = cscSignError ? AppError.parseError(cscSignError).code || AppErrorCode.UNKNOWN_ERROR : null;
+
+ const handleDocumentCompleted = async () => {
+ setIsRedirecting(true);
+
+ if (onDocumentCompleted) {
+ onDocumentCompleted({
+ token: recipient.token,
+ documentId: mapSecondaryIdToDocumentId(envelope.secondaryId),
+ recipientId: recipient.id,
+ envelopeId: envelope.id,
+ });
+
+ await revalidate();
+
+ return;
+ }
+
+ if (envelope.documentMeta.redirectUrl) {
+ window.location.href = envelope.documentMeta.redirectUrl;
+ } else {
+ window.location.href = `/sign/${recipient.token}/complete`;
+ }
+ };
+
+ // Do NOT re-invoke `completeDocumentWithToken` here: for TSP envelopes it
+ // re-runs prep, which upserts the `CscSession` and clears the SAD just authorised.
+ const handleCscAuthorised = async () => {
+ if (!pendingCsc) {
+ return;
+ }
+
+ try {
+ await signEnvelopeWithCsc({
+ sessionId: pendingCsc.sessionId,
+ recipientToken: recipient.token,
+ });
+
+ await handleDocumentCompleted();
+ } catch (err) {
+ analytics.captureException(err, {
+ source: 'signing',
+ location: 'complete_document_csc',
+ recipientId: recipient.id,
+ envelopeId: envelope.id,
+ });
+
+ onDocumentError?.();
+ }
+ };
+
+ const startCscPopupFlow = (csc: PendingCscSigning, popup: Window | null = null) => {
+ setPendingCsc(csc);
+ resetCscSignMutation();
+
+ cscPopupAuth.reset();
+ cscPopupAuth.start('csc', { csc, popup });
+ };
+
+ const onCscRetryClick = () => {
+ if (!pendingCsc) {
+ return;
+ }
+
+ startCscPopupFlow(pendingCsc);
+ };
+
+ const resetCscFlow = () => {
+ cscPopupAuth.cancel();
+ resetCscSignMutation();
+ setPendingCsc(null);
+ };
+
+ const onDialogOpenChange = (open: boolean) => {
+ if (open) {
+ return;
+ }
+
+ resetCscFlow();
+ };
+
const handleOnNextFieldClick = () => {
const nextField = recipientFieldsRemaining[0];
@@ -92,6 +198,16 @@ export const EnvelopeSignerCompleteDialog = () => {
accessAuthOptions?: TRecipientAccessAuth,
recipientDetails?: { name: string; email: string },
) => {
+ // Preparing the signing session can outlive the click's user activation,
+ // so open the popup now and hand it to `start` later.
+ const preOpenedPopup = isFramed && isTspEnvelope(envelope) ? openPopupWindow() : null;
+
+ const closePreOpenedPopup = () => {
+ if (preOpenedPopup && !preOpenedPopup.closed) {
+ preOpenedPopup.close();
+ }
+ };
+
try {
const result = await completeDocument({
token: recipient.token,
@@ -106,10 +222,20 @@ export const EnvelopeSignerCompleteDialog = () => {
// before the sync sign mutation can run. Short-circuit here so the
// analytics / completion handlers don't run with a still-unsigned doc.
if (result.status === 'REDIRECT') {
- window.location.href = result.redirectUrl;
+ if (!isFramed) {
+ closePreOpenedPopup();
+
+ window.location.href = result.redirectUrl;
+ return;
+ }
+
+ startCscPopupFlow({ scope: 'credential', token: recipient.token, sessionId: result.sessionId }, preOpenedPopup);
+
return;
}
+ closePreOpenedPopup();
+
// The document was already completed by an earlier request (retry,
// stale tab or concurrent submission). Let the user know this click
// didn't complete the document, then continue to the completed page.
@@ -120,25 +246,10 @@ export const EnvelopeSignerCompleteDialog = () => {
});
}
- if (onDocumentCompleted) {
- onDocumentCompleted({
- token: recipient.token,
- documentId: mapSecondaryIdToDocumentId(envelope.secondaryId),
- recipientId: recipient.id,
- envelopeId: envelope.id,
- });
-
- await revalidate();
-
- return;
- }
-
- if (envelope.documentMeta.redirectUrl) {
- window.location.href = envelope.documentMeta.redirectUrl;
- } else {
- window.location.href = `/sign/${recipient.token}/complete`;
- }
+ await handleDocumentCompleted();
} catch (err) {
+ closePreOpenedPopup();
+
const error = AppError.parseError(err);
if (error.code !== AppErrorCode.TWO_FACTOR_AUTH_FAILED) {
@@ -259,9 +370,12 @@ export const EnvelopeSignerCompleteDialog = () => {
};
}, [email, fullName, isDirectTemplate, recipient.email, recipient.name, recipient.fields]);
+ const isSubmitting = isPending || isSigningWithCsc || isCscPopupBusy || isRedirecting;
+
return (
<DocumentSigningCompleteDialog
- isSubmitting={isPending || isSuccess}
+ isSubmitting={isSubmitting}
+ onOpenChange={onDialogOpenChange}
recipientPayload={recipientPayload}
onSignatureComplete={isDirectTemplate ? handleDirectTemplateCompleteClick : handleOnCompleteClick}
documentTitle={envelope.title}
@@ -273,6 +387,16 @@ export const EnvelopeSignerCompleteDialog = () => {
defaultNextSigner={nextRecipient ? { name: nextRecipient.name, email: nextRecipient.email } : undefined}
buttonSize="sm"
position="center"
- />
+ >
+ {pendingCsc && (
+ <EnvelopeSigningCscStatus
+ popupAuth={cscPopupAuth}
+ isSigning={isSigningWithCsc || isRedirecting}
+ signErrorCode={cscSignErrorCode}
+ onCancel={resetCscFlow}
+ onRetry={onCscRetryClick}
+ />
+ )}
+ </DocumentSigningCompleteDialog>
);
};
diff --git a/apps/remix/app/components/general/envelope-signing/envelope-signing-csc-status.tsx b/apps/remix/app/components/general/envelope-signing/envelope-signing-csc-status.tsx
new file mode 100644
index 000000000..b68a7e300
--- /dev/null
+++ b/apps/remix/app/components/general/envelope-signing/envelope-signing-csc-status.tsx
@@ -0,0 +1,83 @@
+import type { EmbedPopupAuth } from '@documenso/lib/client-only/hooks/use-embed-popup-auth';
+import { AppErrorCode } from '@documenso/lib/errors/app-error';
+import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';
+import { Button } from '@documenso/ui/primitives/button';
+import { Trans } from '@lingui/react/macro';
+import { Loader2Icon } from 'lucide-react';
+import { match } from 'ts-pattern';
+
+import { EmbedPopupAuthFlowStatus } from '~/components/embed/embed-popup-auth';
+
+export type EnvelopeSigningCscStatusProps = {
+ popupAuth: Pick<EmbedPopupAuth, 'status' | 'error' | 'continueWithStorageAccess'>;
+
+ /** True while the signature is being applied or the page is navigating away after success. */
+ isSigning: boolean;
+
+ /** Error code from the sign mutation, if the signature could not be applied after authorisation. */
+ signErrorCode: string | null;
+
+ onCancel: () => void;
+ onRetry: () => void;
+};
+
+/**
+ * Body of the completion dialog while an embedded recipient authorises and
+ * applies a CSC (AES/QES) signature via the popup flow.
+ */
+export const EnvelopeSigningCscStatus = ({
+ popupAuth,
+ isSigning,
+ signErrorCode,
+ onCancel,
+ onRetry,
+}: EnvelopeSigningCscStatusProps) => {
+ const hasSignError = signErrorCode !== null;
+ const canRetry = popupAuth.status === 'error' || hasSignError;
+
+ return (
+ <div className="flex flex-col gap-y-4">
+ {isSigning ? (
+ <p className="flex items-center justify-center gap-x-2 text-center text-muted-foreground text-sm">
+ <Loader2Icon className="h-4 w-4 animate-spin" />
+ <Trans>Applying your signature...</Trans>
+ </p>
+ ) : (
+ <EmbedPopupAuthFlowStatus
+ status={popupAuth.status}
+ error={popupAuth.error}
+ onCancel={onCancel}
+ onContinueWithStorageAccess={popupAuth.continueWithStorageAccess}
+ waitingMessage={<Trans>Authorise your signature with your signing provider in the popup window</Trans>}
+ />
+ )}
+
+ {hasSignError && (
+ <Alert variant="destructive">
+ <AlertDescription>
+ <EnvelopeSigningCscSignErrorMessage code={signErrorCode} />
+ </AlertDescription>
+ </Alert>
+ )}
+
+ {canRetry && (
+ <Button type="button" onClick={onRetry}>
+ {hasSignError ? <Trans>Reauthorise and retry</Trans> : <Trans>Try again</Trans>}
+ </Button>
+ )}
+ </div>
+ );
+};
+
+const EnvelopeSigningCscSignErrorMessage = ({ code }: { code: string }) => {
+ return match(code)
+ .with(AppErrorCode.CSC_TSP_TIMEOUT, () => (
+ <Trans>The signing provider did not respond in time. Please retry.</Trans>
+ ))
+ .with(AppErrorCode.CSC_SAD_EXPIRED_PRE_SIGN, () => (
+ <Trans>
+ Your signing authorisation expired before the signature could be applied. Please reauthorise to retry.
+ </Trans>
+ ))
+ .otherwise(() => <Trans>Something went wrong while applying your signature. Please retry.</Trans>);
+};
diff --git a/apps/remix/app/middleware/authenticated.ts b/apps/remix/app/middleware/authenticated.ts
new file mode 100644
index 000000000..faef3e320
--- /dev/null
+++ b/apps/remix/app/middleware/authenticated.ts
@@ -0,0 +1,20 @@
+import { getOptionalSession } from '@documenso/auth/server/lib/utils/get-session';
+import { type MiddlewareFunction, redirect } from 'react-router';
+
+/**
+ * Gate for the `_authenticated+` route tree. Lives in middleware rather than the
+ * layout loader so it also runs when single fetch requests a subset of loaders
+ * via `?_routes=`.
+ *
+ * Embed sessions only exist to sign inside an iframe and are treated as signed
+ * out here.
+ */
+export const authenticatedMiddleware: MiddlewareFunction = async ({ request }, next) => {
+ const { session } = await getOptionalSession(request);
+
+ if (!session || session.isEmbed) {
+ throw redirect('/signin');
+ }
+
+ return next();
+};
diff --git a/apps/remix/app/routes/_authenticated+/_layout.tsx b/apps/remix/app/routes/_authenticated+/_layout.tsx
index 9c1054b23..1b1be54c5 100644
--- a/apps/remix/app/routes/_authenticated+/_layout.tsx
+++ b/apps/remix/app/routes/_authenticated+/_layout.tsx
@@ -1,4 +1,3 @@
-import { getOptionalSession } from '@documenso/auth/server/lib/utils/get-session';
import { useChildRouteFlags } from '@documenso/lib/client-only/hooks/use-child-route-flags';
import { OrganisationProvider } from '@documenso/lib/client-only/providers/organisation';
import { useSession } from '@documenso/lib/client-only/providers/session';
@@ -8,7 +7,7 @@ import { cn } from '@documenso/ui/lib/utils';
import { Button } from '@documenso/ui/primitives/button';
import { msg } from '@lingui/core/macro';
import { Trans } from '@lingui/react/macro';
-import { Link, Outlet, redirect } from 'react-router';
+import { Link, Outlet } from 'react-router';
import { AppBanner } from '~/components/general/app-banner';
import { Header } from '~/components/general/app-header';
@@ -16,6 +15,7 @@ import { GenericErrorLayout } from '~/components/general/generic-error-layout';
import { OrganisationBillingBanner } from '~/components/general/organisations/organisation-billing-banner';
import { OrganisationQuotaBanner } from '~/components/general/organisations/organisation-quota-banner';
import { VerifyEmailBanner } from '~/components/general/verify-email-banner';
+import { authenticatedMiddleware } from '~/middleware/authenticated';
import { TeamProvider } from '~/providers/team';
import type { Route } from './+types/_layout';
@@ -27,15 +27,12 @@ import type { Route } from './+types/_layout';
*/
export const shouldRevalidate = () => false;
-export async function loader({ request }: Route.LoaderArgs) {
- const [session, banner] = await Promise.all([
- getOptionalSession(request),
- getSiteSettings().then((settings) => settings.find((setting) => setting.id === SITE_SETTINGS_BANNER_ID)),
- ]);
+export const middleware = [authenticatedMiddleware];
- if (!session.isAuthenticated) {
- throw redirect('/signin');
- }
+export async function loader() {
+ const banner = await getSiteSettings().then((settings) =>
+ settings.find((setting) => setting.id === SITE_SETTINGS_BANNER_ID),
+ );
return {
banner,
diff --git a/apps/remix/app/routes/_authenticated+/settings+/security.sessions.tsx b/apps/remix/app/routes/_authenticated+/settings+/security.sessions.tsx
index 1c8963ed4..124699dad 100644
--- a/apps/remix/app/routes/_authenticated+/settings+/security.sessions.tsx
+++ b/apps/remix/app/routes/_authenticated+/settings+/security.sessions.tsx
@@ -1,4 +1,5 @@
import { authClient } from '@documenso/auth/client';
+import type { ActiveSession } from '@documenso/auth/server/lib/utils/get-session';
import { useSession } from '@documenso/lib/client-only/providers/session';
import { Badge } from '@documenso/ui/primitives/badge';
import { Button } from '@documenso/ui/primitives/button';
@@ -36,6 +37,9 @@ export default function SettingsSecuritySessions() {
const results = data?.sessions ?? [];
+ const sessions = results.filter((result) => !result.isEmbed);
+ const embedSessions = results.filter((result) => result.isEmbed);
+
const columns = useMemo(() => {
return [
{
@@ -89,7 +93,7 @@ export default function SettingsSecuritySessions() {
/>
),
},
- ] satisfies DataTableColumnDef<(typeof results)[number]>[];
+ ] satisfies DataTableColumnDef<ActiveSession>[];
}, []);
return (
@@ -99,42 +103,76 @@ export default function SettingsSecuritySessions() {
</SettingsHeader>
<div className="mt-4">
- <DataTable
- columns={columns}
- data={results}
- hasFilters={false}
- error={{
- enable: isLoadingError,
- }}
- skeleton={{
- enable: isLoading,
- rows: 3,
- component: (
- <>
- <TableCell>
- <Skeleton className="h-4 w-40 rounded-full" />
- </TableCell>
- <TableCell>
- <Skeleton className="h-4 w-24 rounded-full" />
- </TableCell>
- <TableCell>
- <Skeleton className="h-4 w-24 rounded-full" />
- </TableCell>
- <TableCell>
- <Skeleton className="h-4 w-24 rounded-full" />
- </TableCell>
- <TableCell>
- <Skeleton className="h-8 w-16 rounded" />
- </TableCell>
- </>
- ),
- }}
- />
+ <SessionsTable columns={columns} data={sessions} isLoading={isLoading} isLoadingError={isLoadingError} />
</div>
+
+ {embedSessions.length > 0 && (
+ <div className="mt-8">
+ <h3 className="font-medium text-lg">
+ <Trans>Embed sessions</Trans>
+ </h3>
+
+ <p className="mt-1 text-muted-foreground text-sm">
+ <Trans>Sessions created by signing in to Documenso embedded on another website.</Trans>
+ </p>
+
+ <div className="mt-4">
+ <SessionsTable
+ columns={columns}
+ data={embedSessions}
+ isLoading={isLoading}
+ isLoadingError={isLoadingError}
+ />
+ </div>
+ </div>
+ )}
</div>
);
}
+type SessionsTableProps = {
+ columns: DataTableColumnDef<ActiveSession>[];
+ data: ActiveSession[];
+ isLoading: boolean;
+ isLoadingError: boolean;
+};
+
+const SessionsTable = ({ columns, data, isLoading, isLoadingError }: SessionsTableProps) => {
+ return (
+ <DataTable
+ columns={columns}
+ data={data}
+ hasFilters={false}
+ error={{
+ enable: isLoadingError,
+ }}
+ skeleton={{
+ enable: isLoading,
+ rows: 3,
+ component: (
+ <>
+ <TableCell>
+ <Skeleton className="h-4 w-40 rounded-full" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-4 w-24 rounded-full" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-4 w-24 rounded-full" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-4 w-24 rounded-full" />
+ </TableCell>
+ <TableCell>
+ <Skeleton className="h-8 w-16 rounded" />
+ </TableCell>
+ </>
+ ),
+ }}
+ />
+ );
+};
+
type SessionRevokeButtonProps = {
sessionId: string;
isCurrentSession: boolean;
diff --git a/apps/remix/app/routes/_index.tsx b/apps/remix/app/routes/_index.tsx
index 6b541d2ab..65424ce57 100644
--- a/apps/remix/app/routes/_index.tsx
+++ b/apps/remix/app/routes/_index.tsx
@@ -11,7 +11,8 @@ import type { Route } from './+types/_index';
export async function loader({ request }: Route.LoaderArgs) {
const session = await getOptionalSession(request);
- if (session.isAuthenticated) {
+ // Embed sessions are rejected by the authenticated tree, so treat them as signed out here.
+ if (session.isAuthenticated && !session.session.isEmbed) {
const teamUrlCookie = extractCookieFromHeaders(PREFERRED_TEAM_URL_COOKIE, request.headers);
// const referrer = request.headers.get('referer');
diff --git a/apps/remix/app/routes/_recipient+/sign.$token+/_index.tsx b/apps/remix/app/routes/_recipient+/sign.$token+/_index.tsx
index e10f6f71c..a03191633 100644
--- a/apps/remix/app/routes/_recipient+/sign.$token+/_index.tsx
+++ b/apps/remix/app/routes/_recipient+/sign.$token+/_index.tsx
@@ -1,7 +1,7 @@
import signingCelebration from '@documenso/assets/images/signing-celebration.png';
import { getOptionalSession } from '@documenso/auth/server/lib/utils/get-session';
import {
- buildClearCscBlockingErrorCookieHeader,
+ expiredCscBlockingErrorCookieHeader,
readCscBlockingErrorFromRequest,
} from '@documenso/ee/server-only/signing/csc/cookies/blocking-error-cookie';
import { readCscSadSessionFromRequest } from '@documenso/ee/server-only/signing/csc/cookies/sad-session-cookie';
@@ -289,7 +289,7 @@ const handleV2Loader = async ({ params, request }: Route.LoaderArgs) => {
isDocumentAccessValid: true,
envelopeForSigning,
csc: { state: 'blocked', code: blockingError.code } as const,
- responseHeaders: { 'Set-Cookie': buildClearCscBlockingErrorCookieHeader() },
+ responseHeaders: { 'Set-Cookie': expiredCscBlockingErrorCookieHeader() },
} as const;
}
diff --git a/apps/remix/app/routes/_unauthenticated+/o.$orgUrl.signin.tsx b/apps/remix/app/routes/_unauthenticated+/o.$orgUrl.signin.tsx
index 2078d4ecf..96c7c13fe 100644
--- a/apps/remix/app/routes/_unauthenticated+/o.$orgUrl.signin.tsx
+++ b/apps/remix/app/routes/_unauthenticated+/o.$orgUrl.signin.tsx
@@ -44,7 +44,10 @@ export function ErrorBoundary() {
}
export async function loader({ request, params }: Route.LoaderArgs) {
- const { isAuthenticated, user } = await getOptionalSession(request);
+ const { session, user } = await getOptionalSession(request);
+
+ // Embed sessions are rejected by the authenticated tree, so treat them as signed out here.
+ const isAuthenticated = session !== null && !session.isEmbed;
const orgUrl = params.orgUrl;
diff --git a/apps/remix/app/routes/_unauthenticated+/signin.tsx b/apps/remix/app/routes/_unauthenticated+/signin.tsx
index 4f9920fc3..5ffd89559 100644
--- a/apps/remix/app/routes/_unauthenticated+/signin.tsx
+++ b/apps/remix/app/routes/_unauthenticated+/signin.tsx
@@ -15,7 +15,7 @@ import { msg } from '@lingui/core/macro';
import { useLingui } from '@lingui/react';
import { Trans } from '@lingui/react/macro';
import { Loader2Icon } from 'lucide-react';
-import { useEffect, useState } from 'react';
+import { useEffect } from 'react';
import { Link, redirect, useSearchParams } from 'react-router';
import { SignInForm } from '~/components/forms/signin';
@@ -29,7 +29,10 @@ export function meta() {
}
export async function loader({ request }: Route.LoaderArgs) {
- const { isAuthenticated } = await getOptionalSession(request);
+ const { session } = await getOptionalSession(request);
+
+ // Embed sessions are rejected by the authenticated tree, so treat them as signed out here.
+ const isAuthenticated = session !== null && !session.isEmbed;
// SSR env variables.
const isEmailPasswordSigninEnabled = isSigninEnabledForProvider('email');
@@ -87,19 +90,10 @@ export default function SignIn({ loaderData }: Route.ComponentProps) {
const { _ } = useLingui();
const [searchParams] = useSearchParams();
- const [isEmbeddedRedirect, setIsEmbeddedRedirect] = useState(false);
const errorParam = searchParams.get('error');
const signupError = errorParam ? SIGNUP_ERROR_MESSAGES[errorParam] : undefined;
- useEffect(() => {
- const hash = window.location.hash.slice(1);
-
- const params = new URLSearchParams(hash);
-
- setIsEmbeddedRedirect(params.get('embedded') === 'true');
- }, []);
-
useEffect(() => {
if (!shouldAutoRedirectToOIDC) {
return;
@@ -148,7 +142,7 @@ export default function SignIn({ loaderData }: Route.ComponentProps) {
returnTo={returnTo}
/>
- {!isEmbeddedRedirect && isSignupEnabled && (
+ {isSignupEnabled && (
<p className="mt-6 text-center text-muted-foreground text-sm">
<Trans>
Don't have an account?{' '}
diff --git a/apps/remix/app/routes/embed+/_v0+/_layout.tsx b/apps/remix/app/routes/embed+/_v0+/_layout.tsx
index 76e178da6..4d9eb83e6 100644
--- a/apps/remix/app/routes/embed+/_v0+/_layout.tsx
+++ b/apps/remix/app/routes/embed+/_v0+/_layout.tsx
@@ -1,15 +1,10 @@
import { useAnalytics } from '@documenso/lib/client-only/hooks/use-analytics';
-import {
- IS_GOOGLE_SSO_ENABLED,
- IS_MICROSOFT_SSO_ENABLED,
- IS_OIDC_SSO_ENABLED,
- OIDC_PROVIDER_LABEL,
-} from '@documenso/lib/constants/auth';
import { Trans } from '@lingui/react/macro';
import { useEffect } from 'react';
import { isRouteErrorResponse, Outlet, useRouteError } from 'react-router';
import { EmbedAuthenticationRequired } from '~/components/embed/embed-authentication-required';
+import { EmbedCscAuthenticationRequired } from '~/components/embed/embed-csc-authentication-required';
import { EmbedDocumentCompleted } from '~/components/embed/embed-document-completed';
import { EmbedDocumentRejected } from '~/components/embed/embed-document-rejected';
import { EmbedDocumentWaitingForTurn } from '~/components/embed/embed-document-waiting-for-turn';
@@ -17,8 +12,6 @@ import { EmbedPaywall } from '~/components/embed/embed-paywall';
import { EmbedRecipientExpired } from '~/components/embed/embed-recipient-expired';
import { EmbedSenderDisabled } from '~/components/embed/embed-sender-disabled';
-import type { Route } from './+types/_layout';
-
// Note: CSP (`frame-ancestors *`), `Referrer-Policy`, and
// `X-Content-Type-Options` are now emitted globally by
// `securityHeadersMiddleware` for any path under `/embed`. See
@@ -28,28 +21,11 @@ import type { Route } from './+types/_layout';
// HTML page renders, where CORS preflight does not apply, so they were a
// no-op and have been dropped along with the rest of `headers()`.
-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,
- };
-}
-
export default function Layout() {
return <Outlet />;
}
-export function ErrorBoundary({ loaderData }: Route.ErrorBoundaryProps) {
- const { isGoogleSSOEnabled, isMicrosoftSSOEnabled, isOIDCSSOEnabled, oidcProviderLabel } = loaderData || {};
-
+export function ErrorBoundary() {
const analytics = useAnalytics();
const error = useRouteError();
@@ -60,6 +36,7 @@ export function ErrorBoundary({ loaderData }: Route.ErrorBoundaryProps) {
isRouteErrorResponse(error) &&
[
'embed-authentication-required',
+ 'embed-csc-authentication-required',
'embed-paywall',
'embed-waiting-for-turn',
'embed-recipient-expired',
@@ -77,16 +54,11 @@ export function ErrorBoundary({ loaderData }: Route.ErrorBoundaryProps) {
if (isRouteErrorResponse(error)) {
if (error.status === 401 && error.data.type === 'embed-authentication-required') {
- return (
- <EmbedAuthenticationRequired
- isGoogleSSOEnabled={isGoogleSSOEnabled}
- isMicrosoftSSOEnabled={isMicrosoftSSOEnabled}
- isOIDCSSOEnabled={isOIDCSSOEnabled}
- oidcProviderLabel={oidcProviderLabel}
- email={error.data.email}
- returnTo={error.data.returnTo}
- />
- );
+ return <EmbedAuthenticationRequired email={error.data.email} />;
+ }
+
+ if (error.status === 401 && error.data.type === 'embed-csc-authentication-required') {
+ return <EmbedCscAuthenticationRequired token={error.data.token} blockedCode={error.data.blockedCode} />;
}
if (error.status === 403 && error.data.type === 'embed-paywall') {
diff --git a/apps/remix/app/routes/embed+/_v0+/direct.$token.tsx b/apps/remix/app/routes/embed+/_v0+/direct.$token.tsx
index 31e932c16..63352725e 100644
--- a/apps/remix/app/routes/embed+/_v0+/direct.$token.tsx
+++ b/apps/remix/app/routes/embed+/_v0+/direct.$token.tsx
@@ -78,7 +78,6 @@ async function handleV1Loader({ params, request }: Route.LoaderArgs) {
throw data(
{
type: 'embed-authentication-required',
- returnTo: `/embed/direct/${token}`,
},
{
status: 401,
@@ -170,7 +169,6 @@ async function handleV2Loader({ params, request }: Route.LoaderArgs) {
{
type: 'embed-authentication-required',
email: envelopeForSigning.recipientEmail,
- returnTo: `/embed/direct/${token}`,
},
{
status: 401,
@@ -212,8 +210,7 @@ async function handleV2Loader({ params, request }: Route.LoaderArgs) {
throw data(
{
type: 'embed-authentication-required',
- email: user?.email || recipient.email,
- returnTo: `/embed/direct/${token}`,
+ email: recipient.email,
},
{
status: 401,
diff --git a/apps/remix/app/routes/embed+/_v0+/sign.$token.tsx b/apps/remix/app/routes/embed+/_v0+/sign.$token.tsx
index 3458a2b53..36b44ffbe 100644
--- a/apps/remix/app/routes/embed+/_v0+/sign.$token.tsx
+++ b/apps/remix/app/routes/embed+/_v0+/sign.$token.tsx
@@ -1,4 +1,5 @@
import { getOptionalSession } from '@documenso/auth/server/lib/utils/get-session';
+import { assertEmbedCscServiceSession } from '@documenso/ee/server-only/signing/csc/assert-embed-service-session';
import { EnvelopeRenderProvider } from '@documenso/lib/client-only/providers/envelope-render-provider';
import { IS_BILLING_ENABLED } from '@documenso/lib/constants/app';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
@@ -111,8 +112,7 @@ async function handleV1Loader({ params, request }: Route.LoaderArgs) {
throw data(
{
type: 'embed-authentication-required',
- email: user?.email || recipient.email,
- returnTo: `/embed/sign/${token}`,
+ email: recipient.email,
},
{
status: 401,
@@ -139,6 +139,8 @@ async function handleV1Loader({ params, request }: Route.LoaderArgs) {
recipientAccessAuth: derivedRecipientAccessAuth,
});
+ await assertEmbedCscServiceSession({ request, token, envelope: document, isCompleted, isRejected });
+
const allRecipients =
recipient.role === RecipientRole.ASSISTANT
? await getRecipientsForAssistant({
@@ -226,7 +228,6 @@ async function handleV2Loader({ params, request }: Route.LoaderArgs) {
{
type: 'embed-authentication-required',
email: envelopeForSigning.recipientEmail,
- returnTo: `/embed/sign/${token}`,
},
{
status: 401,
@@ -234,7 +235,7 @@ async function handleV2Loader({ params, request }: Route.LoaderArgs) {
);
}
- const { envelope, recipient, isRecipientsTurn, isExpired } = envelopeForSigning;
+ const { envelope, recipient, isRecipientsTurn, isExpired, isCompleted, isRejected } = envelopeForSigning;
const organisationClaim = await getOrganisationClaimByTeamId({ teamId: envelope.teamId });
@@ -290,8 +291,7 @@ async function handleV2Loader({ params, request }: Route.LoaderArgs) {
throw data(
{
type: 'embed-authentication-required',
- email: user?.email || recipient.email,
- returnTo: `/embed/sign/${token}`,
+ email: recipient.email,
},
{
status: 401,
@@ -305,6 +305,8 @@ async function handleV2Loader({ params, request }: Route.LoaderArgs) {
recipientAccessAuth: derivedRecipientAccessAuth,
}).catch(() => null);
+ await assertEmbedCscServiceSession({ request, token, envelope, isCompleted, isRejected });
+
fireAndForget(async () => {
const team = await prisma.team.findFirst({
where: {
diff --git a/apps/remix/app/routes/embed+/auth+/complete.tsx b/apps/remix/app/routes/embed+/auth+/complete.tsx
new file mode 100644
index 000000000..4841d7ea6
--- /dev/null
+++ b/apps/remix/app/routes/embed+/auth+/complete.tsx
@@ -0,0 +1,66 @@
+import {
+ EMBED_AUTH_MESSAGE_COMPLETE,
+ EMBED_AUTH_MESSAGE_FAILED,
+ ZEmbedAuthCompleteStatusSchema,
+} from '@documenso/lib/constants/embed-auth';
+import { Trans } from '@lingui/react/macro';
+import { useEffect } from 'react';
+
+import { BrandingLogo } from '~/components/general/branding-logo';
+
+import type { Route } from './+types/complete';
+
+export function loader({ request }: Route.LoaderArgs) {
+ const url = new URL(request.url);
+
+ const parsedStatus = ZEmbedAuthCompleteStatusSchema.safeParse(url.searchParams.get('status'));
+
+ const status = parsedStatus.success ? parsedStatus.data : 'error';
+
+ return {
+ status,
+ };
+}
+
+/**
+ * `window.opener` is frequently null here: COOP-enforcing IdPs (Google) sever
+ * the opener link permanently. The iframe is polling redeem regardless, so the
+ * messages are only accelerators. `window.close()` still works either way.
+ */
+export default function EmbedAuthCompletePage({ loaderData }: Route.ComponentProps) {
+ const { status } = loaderData;
+
+ useEffect(() => {
+ const opener: Window | null = window.opener;
+
+ if (status !== 'ok') {
+ if (opener) {
+ opener.postMessage({ type: EMBED_AUTH_MESSAGE_FAILED }, window.location.origin);
+ }
+
+ return;
+ }
+
+ if (opener) {
+ opener.postMessage({ type: EMBED_AUTH_MESSAGE_COMPLETE }, window.location.origin);
+ }
+
+ window.close();
+ }, [status]);
+
+ return (
+ <div className="flex min-h-screen flex-col items-center justify-center gap-y-8 px-6">
+ <BrandingLogo className="h-6 w-auto" />
+
+ {status === 'ok' ? (
+ <p className="text-center text-muted-foreground text-sm">
+ <Trans>You can close this window.</Trans>
+ </p>
+ ) : (
+ <p className="text-center text-destructive text-sm">
+ <Trans>Sign in did not complete. Close this window and try again.</Trans>
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/apps/remix/app/routes/embed+/auth+/popup.tsx b/apps/remix/app/routes/embed+/auth+/popup.tsx
new file mode 100644
index 000000000..ce31d68a1
--- /dev/null
+++ b/apps/remix/app/routes/embed+/auth+/popup.tsx
@@ -0,0 +1,374 @@
+import { authClient } from '@documenso/auth/client';
+import { isSigninEnabledForProvider } from '@documenso/lib/constants/auth';
+import type { EmbedPopupAuthCscOptions, EmbedPopupAuthProvider } from '@documenso/lib/constants/embed-auth';
+import {
+ EMBED_AUTH_MESSAGE_FAILED,
+ EMBED_AUTH_MESSAGE_READY,
+ getEmbedPopupAuthProviders,
+ ZEmbedAuthNonceMessageSchema,
+ ZEmbedPopupAuthCscOptionsSchema,
+ ZEmbedPopupAuthProviderSchema,
+} from '@documenso/lib/constants/embed-auth';
+import { AppError } from '@documenso/lib/errors/app-error';
+import { zEmail } from '@documenso/lib/utils/zod';
+import { Button } from '@documenso/ui/primitives/button';
+import { Trans } from '@lingui/react/macro';
+import { Loader2Icon } from 'lucide-react';
+import type { ReactNode } from 'react';
+import { useEffect, useState } from 'react';
+import { data, isRouteErrorResponse } from 'react-router';
+import { match } from 'ts-pattern';
+
+import { SignInForm } from '~/components/forms/signin';
+import { BrandingLogo } from '~/components/general/branding-logo';
+
+import type { Route } from './+types/popup';
+
+const READY_PING_INTERVAL_MS = 250;
+
+const READY_PING_TIMEOUT_MS = 10_000;
+
+type PopupErrorCode = 'opener-missing' | 'opener-timeout' | 'request-failed' | 'csc-options-invalid';
+
+type PopupState =
+ | { status: 'connecting' }
+ | { status: 'starting' }
+ | { status: 'ready'; redirectUrl: string }
+ | { status: 'redirecting' }
+ | { status: 'account'; returnTo: string; email?: string }
+ | { status: 'unverified-email' }
+ | { status: 'error'; code: PopupErrorCode; message?: string };
+
+type HashOptions = {
+ email?: string;
+ csc?: EmbedPopupAuthCscOptions;
+};
+
+// Clears the fragment so the recipient token does not linger in history and
+// `SignInForm` (which also reads `#email`) only sees the validated prop.
+const consumeHashOptions = (): HashOptions => {
+ const params = new URLSearchParams(window.location.hash.slice(1));
+
+ if (window.location.hash) {
+ window.history.replaceState(null, '', `${window.location.pathname}${window.location.search}`);
+ }
+
+ const parsedEmail = zEmail().safeParse(params.get('email'));
+
+ const parsedCsc = ZEmbedPopupAuthCscOptionsSchema.safeParse({
+ scope: params.get('scope') ?? undefined,
+ token: params.get('token') ?? undefined,
+ sessionId: params.get('sessionId') ?? undefined,
+ });
+
+ return {
+ email: parsedEmail.success ? parsedEmail.data : undefined,
+ csc: parsedCsc.success ? parsedCsc.data : undefined,
+ };
+};
+
+export function loader({ request }: Route.LoaderArgs) {
+ const url = new URL(request.url);
+
+ const parsedProvider = ZEmbedPopupAuthProviderSchema.safeParse(url.searchParams.get('provider'));
+
+ if (!parsedProvider.success) {
+ throw data(
+ {
+ type: 'invalid-provider',
+ },
+ {
+ status: 400,
+ },
+ );
+ }
+
+ return {
+ provider: parsedProvider.data,
+ };
+}
+
+export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
+ const isInvalidProvider = isRouteErrorResponse(error) && error.status === 400;
+
+ return (
+ <EmbedAuthPopupLayout>
+ <ErrorLine>
+ {isInvalidProvider ? (
+ <Trans>Unknown sign in provider.</Trans>
+ ) : (
+ <Trans>Something went wrong. Close this window and try again.</Trans>
+ )}
+ </ErrorLine>
+ </EmbedAuthPopupLayout>
+ );
+}
+
+export default function EmbedAuthPopupPage({ loaderData }: Route.ComponentProps) {
+ const { provider } = loaderData;
+
+ const [state, setState] = useState<PopupState>({ status: 'connecting' });
+
+ // COOP-enforcing IdPs sever `window.opener` only after we navigate to them,
+ // so the handshake here is unaffected; only the completion page copes with a null opener.
+ useEffect(() => {
+ const opener: Window | null = window.opener;
+
+ if (!opener) {
+ setState({ status: 'error', code: 'opener-missing' });
+
+ return;
+ }
+
+ let hasReceivedNonce = false;
+ let readyInterval: number | null = null;
+ let readyTimeout: number | null = null;
+
+ const postReady = () => {
+ opener.postMessage({ type: EMBED_AUTH_MESSAGE_READY }, window.location.origin);
+ };
+
+ const stopReadyPings = () => {
+ if (readyInterval !== null) {
+ window.clearInterval(readyInterval);
+ readyInterval = null;
+ }
+
+ if (readyTimeout !== null) {
+ window.clearTimeout(readyTimeout);
+ readyTimeout = null;
+ }
+ };
+
+ const startFlow = async (nonce: string) => {
+ setState({ status: 'starting' });
+
+ const { email, csc } = consumeHashOptions();
+
+ if (provider === 'csc' && !csc) {
+ setState({ status: 'error', code: 'csc-options-invalid' });
+
+ return;
+ }
+
+ try {
+ const { redirectUrl, returnTo } = await authClient.embed.start({
+ nonce,
+ provider,
+ csc: provider === 'csc' ? csc : undefined,
+ });
+
+ if (returnTo !== null) {
+ setState({ status: 'account', returnTo, email });
+
+ return;
+ }
+
+ if (redirectUrl === null) {
+ setState({ status: 'error', code: 'request-failed' });
+
+ return;
+ }
+
+ // Deliberately not navigating here; see `RedirectPrompt`.
+ setState({ status: 'ready', redirectUrl });
+ } catch (err) {
+ const error = AppError.parseError(err);
+
+ setState({
+ status: 'error',
+ code: 'request-failed',
+ message: error.userMessage ?? error.message,
+ });
+ }
+ };
+
+ const onMessage = (event: MessageEvent) => {
+ if (event.origin !== window.location.origin || event.source !== opener) {
+ return;
+ }
+
+ const parsed = ZEmbedAuthNonceMessageSchema.safeParse(event.data);
+
+ if (!parsed.success) {
+ return;
+ }
+
+ if (hasReceivedNonce) {
+ return;
+ }
+
+ hasReceivedNonce = true;
+
+ stopReadyPings();
+
+ void startFlow(parsed.data.nonce);
+ };
+
+ window.addEventListener('message', onMessage);
+
+ readyInterval = window.setInterval(postReady, READY_PING_INTERVAL_MS);
+
+ readyTimeout = window.setTimeout(() => {
+ if (hasReceivedNonce) {
+ return;
+ }
+
+ stopReadyPings();
+
+ setState({ status: 'error', code: 'opener-timeout' });
+ }, READY_PING_TIMEOUT_MS);
+
+ postReady();
+
+ return () => {
+ stopReadyPings();
+
+ window.removeEventListener('message', onMessage);
+ };
+ }, [provider]);
+
+ const isTerminal = state.status === 'error' || state.status === 'unverified-email';
+
+ useEffect(() => {
+ if (!isTerminal) {
+ return;
+ }
+
+ const opener: Window | null = window.opener;
+
+ if (opener) {
+ opener.postMessage({ type: EMBED_AUTH_MESSAGE_FAILED }, window.location.origin);
+ }
+ }, [isTerminal]);
+
+ return (
+ <EmbedAuthPopupLayout isCsc={provider === 'csc'}>
+ {match(state)
+ .with({ status: 'connecting' }, () => (
+ <StatusLine>
+ <Trans>Connecting to the embed...</Trans>
+ </StatusLine>
+ ))
+ .with({ status: 'starting' }, () => (
+ <StatusLine>
+ <Trans>Starting sign in...</Trans>
+ </StatusLine>
+ ))
+ .with({ status: 'ready' }, ({ redirectUrl }) => (
+ <RedirectPrompt
+ provider={provider}
+ onContinue={() => {
+ setState({ status: 'redirecting' });
+
+ window.location.href = redirectUrl;
+ }}
+ />
+ ))
+ .with({ status: 'redirecting' }, () => (
+ <StatusLine>
+ <Trans>Redirecting to your sign in provider...</Trans>
+ </StatusLine>
+ ))
+ .with({ status: 'account' }, ({ returnTo, email }) => (
+ // Password recovery and email verification would navigate away from
+ // the flow, so they are handled as terminal states instead.
+ <SignInForm
+ className="w-full max-w-sm"
+ initialEmail={email}
+ isEmailPasswordSigninEnabled={isSigninEnabledForProvider('email')}
+ returnTo={returnTo}
+ hideForgotPassword
+ onUnverifiedEmail={() => setState({ status: 'unverified-email' })}
+ />
+ ))
+ .with({ status: 'unverified-email' }, () => (
+ <p className="text-center text-muted-foreground text-sm">
+ <Trans>Verify your email, then close this window and try again.</Trans>
+ </p>
+ ))
+ .with({ status: 'error' }, ({ code, message }) => (
+ <ErrorLine>
+ {match(code)
+ .with('opener-missing', () => <Trans>This window must be opened from a Documenso embed.</Trans>)
+ .with('opener-timeout', () => (
+ <Trans>Could not connect to the Documenso embed. Close this window and try again.</Trans>
+ ))
+ .with('csc-options-invalid', () => (
+ <Trans>This signing request is missing its details. Close this window and try again.</Trans>
+ ))
+ .with('request-failed', () =>
+ message ? (
+ message
+ ) : (
+ <Trans>We were unable to start the sign in flow. Close this window and try again.</Trans>
+ ),
+ )
+ .exhaustive()}
+ </ErrorLine>
+ ))
+ .exhaustive()}
+ </EmbedAuthPopupLayout>
+ );
+}
+
+/**
+ * This click is load-bearing. WebKit only grants `requestStorageAccess()` in
+ * the iframe if the user has recently interacted with our origin as a top-level
+ * page, and with an auto-redirect they never would have.
+ * https://webkit.org/blog/11545/updates-to-the-storage-access-api/
+ */
+const RedirectPrompt = ({ provider, onContinue }: { provider: EmbedPopupAuthProvider; onContinue: () => void }) => {
+ const { oidcProviderLabel } = getEmbedPopupAuthProviders();
+
+ return (
+ <div className="flex w-full max-w-sm flex-col gap-y-4">
+ <p className="text-center text-muted-foreground text-sm">
+ <Trans>You will be redirected to sign in, then returned here.</Trans>
+ </p>
+
+ <Button type="button" size="lg" onClick={onContinue}>
+ {match(provider)
+ .with('google', () => <Trans>Continue with Google</Trans>)
+ .with('microsoft', () => <Trans>Continue with Microsoft</Trans>)
+ .with('oidc', () => <Trans>Continue with {oidcProviderLabel || 'OIDC'}</Trans>)
+ .with('csc', () => <Trans>Continue to your signing provider</Trans>)
+ .with('account', () => <Trans>Continue</Trans>)
+ .exhaustive()}
+ </Button>
+ </div>
+ );
+};
+
+const StatusLine = ({ children }: { children: ReactNode }) => {
+ return (
+ <p className="flex items-center justify-center gap-x-2 text-muted-foreground text-sm">
+ <Loader2Icon className="h-4 w-4 animate-spin" />
+ {children}
+ </p>
+ );
+};
+
+const ErrorLine = ({ children }: { children: ReactNode }) => {
+ return <p className="text-center text-destructive text-sm">{children}</p>;
+};
+
+const EmbedAuthPopupLayout = ({ children, isCsc = false }: { children: ReactNode; isCsc?: boolean }) => {
+ return (
+ <div className="flex min-h-screen flex-col items-center justify-center gap-y-8 px-6 py-8">
+ <div className="flex flex-col items-center gap-y-4">
+ <BrandingLogo className="h-6 w-auto" />
+
+ <h1 className="text-center font-medium text-sm">
+ {isCsc ? (
+ <Trans>Sign in with your signing provider to continue</Trans>
+ ) : (
+ <Trans>Sign in to Documenso to continue</Trans>
+ )}
+ </h1>
+ </div>
+
+ {children}
+ </div>
+ );
+};
diff --git a/apps/remix/app/routes/embed+/v1+/multisign+/_index.tsx b/apps/remix/app/routes/embed+/v1+/multisign+/_index.tsx
index 1759a6121..449af41e6 100644
--- a/apps/remix/app/routes/embed+/v1+/multisign+/_index.tsx
+++ b/apps/remix/app/routes/embed+/v1+/multisign+/_index.tsx
@@ -1,11 +1,14 @@
import { getOptionalSession } from '@documenso/auth/server/lib/utils/get-session';
+import { IS_INSTANCE_CSC_MODE } from '@documenso/lib/constants/app';
import { captureServerEvent } from '@documenso/lib/server-only/analytics/capture-server-event';
import { getDocumentAndSenderByToken } from '@documenso/lib/server-only/document/get-document-by-token';
import { getOrganisationClaimByTeamId } from '@documenso/lib/server-only/organisation/get-organisation-claims';
import { getRecipientByToken } from '@documenso/lib/server-only/recipient/get-recipient-by-token';
import { ZSignDocumentEmbedDataSchema } from '@documenso/lib/types/embed-document-sign-schema';
+import { isTspEnvelope } from '@documenso/lib/types/signature-level';
import { fireAndForget } from '@documenso/lib/universal/fire-and-forget';
import { prisma } from '@documenso/prisma';
+import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';
import { Trans } from '@lingui/react/macro';
import { SigningStatus } from '@prisma/client';
import { useEffect, useLayoutEffect, useState } from 'react';
@@ -41,6 +44,9 @@ export async function loader({ request }: Route.LoaderArgs) {
}),
);
+ // The CSC popup flow is only implemented by the v2 embed.
+ const hasUnsupportedTspEnvelope = IS_INSTANCE_CSC_MODE() && envelopes.some(({ document }) => isTspEnvelope(document));
+
// Check the first envelope for whitelabelling settings (assuming all docs are from same team)
const firstDocument = envelopes[0]?.document;
@@ -59,6 +65,7 @@ export async function loader({ request }: Route.LoaderArgs) {
user,
hidePoweredBy: false,
allowWhitelabelling: false,
+ hasUnsupportedTspEnvelope,
});
}
@@ -95,11 +102,13 @@ export async function loader({ request }: Route.LoaderArgs) {
user,
hidePoweredBy,
allowWhitelabelling,
+ hasUnsupportedTspEnvelope,
});
}
export default function MultisignPage() {
- const { envelopes, user, hidePoweredBy, allowWhitelabelling } = useSuperLoaderData<typeof loader>();
+ const { envelopes, user, hidePoweredBy, allowWhitelabelling, hasUnsupportedTspEnvelope } =
+ useSuperLoaderData<typeof loader>();
const revalidator = useRevalidator();
@@ -258,6 +267,18 @@ export default function MultisignPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
+ if (hasUnsupportedTspEnvelope) {
+ return (
+ <div className="flex min-h-[100dvh] w-full items-center justify-center p-4">
+ <Alert variant="destructive" className="w-full max-w-md">
+ <AlertDescription>
+ <Trans>Qualified electronic signatures are not supported in this embed.</Trans>
+ </AlertDescription>
+ </Alert>
+ </div>
+ );
+ }
+
// If a document is selected, show the signing view
if (selectedDocument && selectedRecipient) {
// Determine the full name to use - prioritize embed data, then user name, then recipient name
diff --git a/apps/remix/app/storage/lang-cookie.server.ts b/apps/remix/app/storage/lang-cookie.server.ts
index 261017319..d7bb3ef78 100644
--- a/apps/remix/app/storage/lang-cookie.server.ts
+++ b/apps/remix/app/storage/lang-cookie.server.ts
@@ -1,9 +1,9 @@
-import { env } from '@documenso/lib/utils/env';
+import { shouldUseSecureCookies } from '@documenso/lib/constants/auth';
import { createCookie } from 'react-router';
export const langCookie = createCookie('lang', {
path: '/',
maxAge: 60 * 60 * 24 * 365 * 2,
httpOnly: true,
- secure: env('NODE_ENV') === 'production',
+ secure: shouldUseSecureCookies(),
});
diff --git a/apps/remix/app/storage/theme-session.server.ts b/apps/remix/app/storage/theme-session.server.ts
index 3a1d6be7b..31b02b646 100644
--- a/apps/remix/app/storage/theme-session.server.ts
+++ b/apps/remix/app/storage/theme-session.server.ts
@@ -1,4 +1,4 @@
-import { getCookieDomain, useSecureCookies } from '@documenso/lib/constants/auth';
+import { getCookieDomain, shouldUseSecureCookies } from '@documenso/lib/constants/auth';
import { createCookieSessionStorage } from 'react-router';
import { createThemeSessionResolver } from 'remix-themes';
@@ -9,7 +9,7 @@ const themeSessionStorage = createCookieSessionStorage({
httpOnly: true,
sameSite: 'lax',
secrets: ['insecure-secret-do-not-care'],
- secure: useSecureCookies,
+ secure: shouldUseSecureCookies(),
domain: getCookieDomain(),
maxAge: 60 * 60 * 24 * 365,
},
diff --git a/apps/remix/server/api/files/files.helpers.ts b/apps/remix/server/api/files/files.helpers.ts
index 3b0dc1f05..2465d878b 100644
--- a/apps/remix/server/api/files/files.helpers.ts
+++ b/apps/remix/server/api/files/files.helpers.ts
@@ -1,4 +1,4 @@
-import { getOptionalSession } from '@documenso/auth/server/lib/utils/get-session';
+import { getOptionalNonEmbedSession } from '@documenso/auth/server/lib/session/embed-session-restrictions';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { verifyEmbeddingPresignToken } from '@documenso/lib/server-only/embedding-presign/verify-embedding-presign-token';
import { generatePartialSignedPdf } from '@documenso/lib/server-only/pdf/generate-partial-signed-pdf';
@@ -29,7 +29,7 @@ type DocumentDataInput = {
};
export const resolveFileUploadUserId = async (c: Context<HonoEnv>): Promise<number | null> => {
- const session = await getOptionalSession(c);
+ const session = await getOptionalNonEmbedSession(c);
if (session.user?.id) {
return session.user.id;
diff --git a/apps/remix/server/api/files/files.ts b/apps/remix/server/api/files/files.ts
index bbca38885..4ed139d0b 100644
--- a/apps/remix/server/api/files/files.ts
+++ b/apps/remix/server/api/files/files.ts
@@ -1,4 +1,4 @@
-import { getOptionalSession } from '@documenso/auth/server/lib/utils/get-session';
+import { getOptionalNonEmbedSession } from '@documenso/auth/server/lib/session/embed-session-restrictions';
import { APP_DOCUMENT_UPLOAD_SIZE_LIMIT } from '@documenso/lib/constants/app';
import { AppError } from '@documenso/lib/errors/app-error';
import { verifyEmbeddingPresignToken } from '@documenso/lib/server-only/embedding-presign/verify-embedding-presign-token';
@@ -65,7 +65,7 @@ export const filesRoute = new Hono<HonoEnv>()
const { envelopeId, envelopeItemId } = c.req.valid('param');
const { token } = c.req.query();
- const session = await getOptionalSession(c);
+ const session = await getOptionalNonEmbedSession(c);
let userId = session.user?.id;
@@ -141,7 +141,7 @@ export const filesRoute = new Hono<HonoEnv>()
try {
const { envelopeId, envelopeItemId, version } = c.req.valid('param');
- const session = await getOptionalSession(c);
+ const session = await getOptionalNonEmbedSession(c);
if (!session.user) {
return c.json({ error: 'Unauthorized' }, 401);
diff --git a/apps/remix/server/api/files/routes/get-envelope-item-pdf.ts b/apps/remix/server/api/files/routes/get-envelope-item-pdf.ts
index 425717121..de9a17804 100644
--- a/apps/remix/server/api/files/routes/get-envelope-item-pdf.ts
+++ b/apps/remix/server/api/files/routes/get-envelope-item-pdf.ts
@@ -1,4 +1,4 @@
-import { getOptionalSession } from '@documenso/auth/server/lib/utils/get-session';
+import { getOptionalNonEmbedSession } from '@documenso/auth/server/lib/session/embed-session-restrictions';
import { verifyEmbeddingPresignToken } from '@documenso/lib/server-only/embedding-presign/verify-embedding-presign-token';
import type { DocumentDataVersion } from '@documenso/lib/types/document';
import { sha256 } from '@documenso/lib/universal/crypto';
@@ -37,7 +37,7 @@ route.get(
const { presignToken } = c.req.valid('query');
- const session = await getOptionalSession(c);
+ const session = await getOptionalNonEmbedSession(c);
let userId = session.user?.id;
diff --git a/apps/remix/server/csrf-middleware.ts b/apps/remix/server/csrf-middleware.ts
new file mode 100644
index 000000000..636c1a3a4
--- /dev/null
+++ b/apps/remix/server/csrf-middleware.ts
@@ -0,0 +1,59 @@
+import { NEXT_PUBLIC_WEBAPP_URL } from '@documenso/lib/constants/app';
+import { createMiddleware } from 'hono/factory';
+
+import type { HonoEnv } from './router';
+
+const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
+
+/**
+ * Origin-based CSRF protection for cookie-authenticated mutations.
+ *
+ * Needed because the embed session cookie is `SameSite=None; Partitioned`, so
+ * any page hosting our embed iframe can send credentialed cross-site form/fetch
+ * requests that skip CORS preflight.
+ *
+ * Bearer/API-token requests are exempt since a browser can't attach
+ * `Authorization` cross-site without a preflight we never grant. Browser-managed
+ * schemes (e.g. `Basic` via a reverse proxy) deliberately aren't exempt.
+ */
+export const csrfMiddleware = createMiddleware<HonoEnv>(async (c, next) => {
+ if (SAFE_METHODS.has(c.req.method)) {
+ return await next();
+ }
+
+ if (isApiAuthorization(c.req.header('Authorization'))) {
+ return await next();
+ }
+
+ const origin = c.req.header('Origin');
+ const validOrigin = new URL(NEXT_PUBLIC_WEBAPP_URL()).origin;
+
+ if (origin !== validOrigin) {
+ c.get('logger').warn({
+ event: 'csrf.origin_rejected',
+ method: c.req.method,
+ path: c.req.path,
+ origin: origin ?? null,
+ });
+
+ return c.json(
+ {
+ message: 'Forbidden',
+ statusCode: 403,
+ },
+ 403,
+ );
+ }
+
+ return await next();
+});
+
+const isApiAuthorization = (header: string | undefined): boolean => {
+ if (!header) {
+ return false;
+ }
+
+ const value = header.trim().toLowerCase();
+
+ return value.startsWith('bearer ') || value.startsWith('api_');
+};
diff --git a/apps/remix/server/router.ts b/apps/remix/server/router.ts
index 83681fba9..bb9610371 100644
--- a/apps/remix/server/router.ts
+++ b/apps/remix/server/router.ts
@@ -1,5 +1,6 @@
import { tsRestHonoApp } from '@documenso/api/hono';
import { auth } from '@documenso/auth/server';
+import { rejectEmbedSessionMiddleware } from '@documenso/auth/server/lib/session/embed-session-restrictions';
import { csc } from '@documenso/ee/server-only/signing/csc/hono';
import { jobsClient } from '@documenso/lib/jobs/client';
import { LicenseClient } from '@documenso/lib/server-only/license/license-client';
@@ -28,6 +29,7 @@ import { aiRoute } from './api/ai/route';
import { downloadRoute } from './api/download/download';
import { filesRoute } from './api/files/files';
import { type AppContext, appContext } from './context';
+import { csrfMiddleware } from './csrf-middleware';
import { appMiddleware } from './middleware';
import { securityHeadersMiddleware } from './security-headers';
import { openApiTrpcServerHandler } from './trpc/hono-trpc-open-api';
@@ -94,6 +96,21 @@ app.use(async (c, next) => {
await next();
});
+// CSRF: mount on every route that accepts a session cookie. Must run after the logger.
+// Not mounted on `/api/v1` (Authorization header only, see `authenticatedMiddleware`),
+// `/api/jobs` (signature auth) or `/api/csc` (GET only).
+app.use('/api/auth/*', csrfMiddleware);
+app.use('/api/trpc/*', csrfMiddleware);
+app.use('/api/v2/*', csrfMiddleware);
+app.use('/api/v2-beta/*', csrfMiddleware);
+app.use('/api/files/*', csrfMiddleware);
+app.use('/api/ai/*', csrfMiddleware);
+
+// Embed sessions are signing-only. `/api/files` instead ignores them per route
+// (`getOptionalNonEmbedSession`) so embedded authoring on a host that also ran
+// embedded signing still falls through to its presign token.
+app.use('/api/ai/*', rejectEmbedSessionMiddleware);
+
// Apply cors and rate limits to API routes.
app.use(`/api/v1/*`, cors());
app.use('/api/v1/*', apiV1RateLimitMiddleware);
diff --git a/apps/remix/server/security-headers.ts b/apps/remix/server/security-headers.ts
index 5ec894f81..8706589c2 100644
--- a/apps/remix/server/security-headers.ts
+++ b/apps/remix/server/security-headers.ts
@@ -19,31 +19,30 @@ const NON_PAGE_PATH_REGEX = /^(\/api\/|\/ingest\/|\/__manifest|\/assets\/|\/appl
const EMBED_PATH_REGEX = /^\/embed(\/|\.data|$)/;
/**
- * Non-`/embed` page routes that customers iframe directly, plus the auth
- * pages reachable from inside an embed iframe during the
- * reauth-as-different-account flow.
+ * The popup auth pages exchange the auth nonce with their opener via
+ * `postMessage` and must never be framed, or a hostile page could drive the
+ * handshake. Checked before `EMBED_PATH_REGEX`.
+ */
+const EMBED_AUTH_PATH_REGEX = /^\/embed\/auth(\/|\.data|$)/;
+
+/**
+ * Non-`/embed` page routes that customers iframe directly.
*
- * Signing routes (`/sign/:token`, `/d/:token`):
- * Some customer integrations embed these URLs directly (without going
- * through `EmbedSignDocument`). Without `frame-ancestors *` here, those
- * integrations break with a "refused to connect" iframe error.
+ * Some customer integrations embed `/sign/:token` and `/d/:token` directly
+ * (without going through `EmbedSignDocument`). Without `frame-ancestors *`
+ * here, those integrations break with a "refused to connect" iframe error.
*
- * Auth routes (`/signin`, `/forgot-password`, `/check-email`,
- * `/unverified-account`):
- * `apps/remix/app/components/general/document-signing/document-signing-auth-account.tsx`
- * does `window.location.href = '/signin?...'` inside the iframe when the
- * user needs to sign out and sign back in as a different account, and
- * `<SignInForm>` links/navigates to `/forgot-password`, `/check-email`, and
- * `/unverified-account` from there. Without `frame-ancestors *` on these
- * routes, the customer's iframe gets blocked the moment the user clicks
- * "Login" in the reauth dialog.
+ * Direct framing is best-effort; `/embed/*` is the supported surface. Sign in
+ * from these pages goes through the popup flow, so `/signin` etc. are never
+ * framed and keep `frame-ancestors 'self'`. CSC/TSP signing is not supported
+ * when framed directly.
*
* These routes still get the strict nonced `script-src`/`style-src-elem`
* policy — only `frame-ancestors` is relaxed. The `(\/|\.data|$)` tail
* keeps `/sign` from matching `/signin`/`/signup` and `/d` from matching
* `/dashboard`.
*/
-const FRAMEABLE_PATH_REGEX = /^\/(signin|forgot-password|check-email|unverified-account|sign|d)(\/|\.data|$)/;
+const FRAMEABLE_PATH_REGEX = /^\/(sign|d)(\/|\.data|$)/;
/**
* Hono context variable name where the per-request CSP nonce is stashed.
@@ -67,7 +66,7 @@ const generateNonce = () => {
return btoa(binary);
};
-type CspPathKind = 'embed' | 'frameable' | 'default';
+type CspPathKind = 'embed' | 'embed-auth' | 'frameable' | 'default';
const buildCspHeader = ({ nonce, kind }: { nonce: string; kind: CspPathKind }) => {
// `'self'` is included alongside `'strict-dynamic'` as a fallback for
@@ -95,19 +94,18 @@ const buildCspHeader = ({ nonce, kind }: { nonce: string; kind: CspPathKind }) =
// Embeds inject customer-supplied CSS via runtime-created `<style>`
// elements (see apps/remix/app/utils/css-vars.ts). Nonce-stamping those
// would be brittle for white-label customers, so we accept
- // `'unsafe-inline'` on the embed scope only. Frameable (auth/signing)
- // pages do NOT load customer CSS and keep the strict nonced policy.
+ // `'unsafe-inline'` on the embed scope only. Everything else does NOT load
+ // customer CSS and keeps the strict nonced policy.
if (kind === 'embed') {
directives.push(`style-src-elem 'self' 'unsafe-inline'`);
} else {
directives.push(`style-src-elem 'self' 'nonce-${nonce}'`);
}
- // Embed, signing, and auth routes are all reachable from inside a
- // customer's iframe and therefore need `frame-ancestors *`. Every other
- // page gets clickjacking protection.
if (kind === 'embed' || kind === 'frameable') {
directives.push(`frame-ancestors *`);
+ } else if (kind === 'embed-auth') {
+ directives.push(`frame-ancestors 'none'`);
} else {
directives.push(`frame-ancestors 'self'`);
}
@@ -116,6 +114,10 @@ const buildCspHeader = ({ nonce, kind }: { nonce: string; kind: CspPathKind }) =
};
const classifyPath = (path: string): CspPathKind => {
+ if (EMBED_AUTH_PATH_REGEX.test(path)) {
+ return 'embed-auth';
+ }
+
if (EMBED_PATH_REGEX.test(path)) {
return 'embed';
}
@@ -141,11 +143,11 @@ const classifyPath = (path: string): CspPathKind => {
* - `embed` — wildcard `frame-ancestors`, `'unsafe-inline'`
* style-src-elem (white-label CSS injection), strict
* nonced script-src.
- * - `frameable` — wildcard `frame-ancestors` only; needed because the
- * embed reauth flow redirects the iframe to `/signin` etc,
- * and because some customers iframe `/sign/:token` and
- * `/d/:token` directly without using `EmbedSignDocument`.
- * Strict nonced script-src and style-src-elem otherwise.
+ * - `embed-auth` — strict policy with `frame-ancestors 'none'`; the popup
+ * auth pages must never be framed.
+ * - `frameable` — wildcard `frame-ancestors` only; some customers iframe
+ * `/sign/:token` and `/d/:token` directly. Strict nonced
+ * script-src and style-src-elem otherwise.
* - default — strict nonced script-src and style-src-elem,
* `frame-ancestors 'self'` for clickjacking protection.
*/
@@ -168,7 +170,7 @@ export const securityHeadersMiddleware = createMiddleware<HonoEnv>(async (c, nex
// Preserved from the per-route `headers()` export in
// apps/remix/app/routes/embed+/_v0+/_layout.tsx, which has been removed.
- if (kind === 'embed') {
+ if (kind === 'embed' || kind === 'embed-auth') {
if (!c.res.headers.has('Referrer-Policy')) {
c.res.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
}
diff --git a/packages/app-tests/e2e/api/trpc/admin/delete-organisation.spec.ts b/packages/app-tests/e2e/api/trpc/admin/delete-organisation.spec.ts
index b2383be2f..57567a5ba 100644
--- a/packages/app-tests/e2e/api/trpc/admin/delete-organisation.spec.ts
+++ b/packages/app-tests/e2e/api/trpc/admin/delete-organisation.spec.ts
@@ -4,7 +4,7 @@ import { seedUser } from '@documenso/prisma/seed/users';
import type { Page } from '@playwright/test';
import { expect, test } from '@playwright/test';
-import { apiSignin } from '../../../fixtures/authentication';
+import { apiSignin, WEBAPP_ORIGIN_HEADERS } from '../../../fixtures/authentication';
const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
@@ -19,7 +19,7 @@ const callDeleteOrganisation = async (
},
) => {
return await page.context().request.post(`${WEBAPP_BASE_URL}/api/trpc/admin.organisation.delete`, {
- headers: { 'content-type': 'application/json' },
+ headers: { ...WEBAPP_ORIGIN_HEADERS, 'content-type': 'application/json' },
data: JSON.stringify({ json: input }),
});
};
@@ -161,7 +161,7 @@ test('[ADMIN][TRPC][DELETE_ORG]: zod schema rejects malformed input', async ({ p
// Missing organisationName and sendEmailToOwner.
const res = await page.context().request.post(`${WEBAPP_BASE_URL}/api/trpc/admin.organisation.delete`, {
- headers: { 'content-type': 'application/json' },
+ headers: { ...WEBAPP_ORIGIN_HEADERS, 'content-type': 'application/json' },
data: JSON.stringify({ json: { organisationId: 'whatever' } }),
});
diff --git a/packages/app-tests/e2e/api/trpc/admin/delete-recipient.spec.ts b/packages/app-tests/e2e/api/trpc/admin/delete-recipient.spec.ts
index 9e78acc7d..313c40064 100644
--- a/packages/app-tests/e2e/api/trpc/admin/delete-recipient.spec.ts
+++ b/packages/app-tests/e2e/api/trpc/admin/delete-recipient.spec.ts
@@ -7,7 +7,7 @@ import type { Page } from '@playwright/test';
import { expect, test } from '@playwright/test';
import { DocumentSigningOrder, DocumentStatus, SendStatus, SigningStatus } from '@prisma/client';
-import { apiSignin } from '../../../fixtures/authentication';
+import { apiSignin, WEBAPP_ORIGIN_HEADERS } from '../../../fixtures/authentication';
const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
@@ -15,7 +15,7 @@ test.describe.configure({ mode: 'parallel' });
const callDeleteRecipient = async (page: Page, input: { id: number; reason?: string }) => {
return await page.context().request.post(`${WEBAPP_BASE_URL}/api/trpc/admin.recipient.delete`, {
- headers: { 'content-type': 'application/json' },
+ headers: { ...WEBAPP_ORIGIN_HEADERS, 'content-type': 'application/json' },
data: JSON.stringify({ json: { reason: 'Removed at the request of the sender', ...input } }),
});
};
diff --git a/packages/app-tests/e2e/api/trpc/envelope/expired-recipient-field-signing.spec.ts b/packages/app-tests/e2e/api/trpc/envelope/expired-recipient-field-signing.spec.ts
index 2ae53a0ea..8614385ed 100644
--- a/packages/app-tests/e2e/api/trpc/envelope/expired-recipient-field-signing.spec.ts
+++ b/packages/app-tests/e2e/api/trpc/envelope/expired-recipient-field-signing.spec.ts
@@ -6,6 +6,8 @@ import type { Page } from '@playwright/test';
import { expect, test } from '@playwright/test';
import { FieldType } from '@prisma/client';
+import { WEBAPP_ORIGIN_HEADERS } from '../../../fixtures/authentication';
+
const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
/**
@@ -16,7 +18,7 @@ const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
const callSignEnvelopeField = async (page: Page, input: { token: string; fieldId: number; value: string }) => {
return await page.context().request.post(`${WEBAPP_BASE_URL}/api/trpc/envelope.field.sign`, {
- headers: { 'content-type': 'application/json' },
+ headers: { ...WEBAPP_ORIGIN_HEADERS, 'content-type': 'application/json' },
data: JSON.stringify({
json: {
token: input.token,
diff --git a/packages/app-tests/e2e/api/v2/partial-signed-pdf-download.spec.ts b/packages/app-tests/e2e/api/v2/partial-signed-pdf-download.spec.ts
index a80072a0c..16589b7b8 100644
--- a/packages/app-tests/e2e/api/v2/partial-signed-pdf-download.spec.ts
+++ b/packages/app-tests/e2e/api/v2/partial-signed-pdf-download.spec.ts
@@ -8,6 +8,7 @@ import { expect, test } from '@playwright/test';
import { DocumentStatus, FieldType, SigningStatus } from '@prisma/client';
import { apiSeedDraftDocument, apiSeedPendingDocument } from '../../fixtures/api-seeds';
+import { WEBAPP_ORIGIN_HEADERS } from '../../fixtures/authentication';
const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
const API_BASE_URL = `${WEBAPP_BASE_URL}/api/v2-beta`;
@@ -15,6 +16,7 @@ const API_BASE_URL = `${WEBAPP_BASE_URL}/api/v2-beta`;
const trpcMutation = async (request: APIRequestContext, procedure: string, input: Record<string, unknown>) => {
const res = await request.post(`${WEBAPP_BASE_URL}/api/trpc/${procedure}`, {
headers: {
+ ...WEBAPP_ORIGIN_HEADERS,
'content-type': 'application/json',
},
data: JSON.stringify({ json: input }),
diff --git a/packages/app-tests/e2e/api/v2/test-unauthorized-api-access.spec.ts b/packages/app-tests/e2e/api/v2/test-unauthorized-api-access.spec.ts
index 3d05ef297..49e948788 100644
--- a/packages/app-tests/e2e/api/v2/test-unauthorized-api-access.spec.ts
+++ b/packages/app-tests/e2e/api/v2/test-unauthorized-api-access.spec.ts
@@ -37,7 +37,7 @@ import type {
import { expect, test } from '@playwright/test';
import type { Team, User } from '@prisma/client';
-import { apiSignin } from '../../fixtures/authentication';
+import { apiSignin, WEBAPP_ORIGIN_HEADERS } from '../../fixtures/authentication';
const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
@@ -3082,6 +3082,7 @@ test.describe('Document API V2', () => {
const res = await page.context().request.post(`${WEBAPP_BASE_URL}/api/trpc/envelope.getMany`, {
headers: {
+ ...WEBAPP_ORIGIN_HEADERS,
'x-team-id': String(teamA.id),
},
data: {
@@ -3110,6 +3111,7 @@ test.describe('Document API V2', () => {
const res = await page.context().request.post(`${WEBAPP_BASE_URL}/api/trpc/envelope.getMany`, {
headers: {
+ ...WEBAPP_ORIGIN_HEADERS,
'Content-Type': 'application/json',
'x-team-id': String(teamA.id),
},
@@ -3145,6 +3147,7 @@ test.describe('Document API V2', () => {
const res = await page.context().request.post(`${WEBAPP_BASE_URL}/api/trpc/envelope.getMany`, {
headers: {
+ ...WEBAPP_ORIGIN_HEADERS,
'x-team-id': String(teamA.id),
},
data: {
diff --git a/packages/app-tests/e2e/api/v2/unauthorized-api-access/api-access-file-upload.spec.ts b/packages/app-tests/e2e/api/v2/unauthorized-api-access/api-access-file-upload.spec.ts
index 6aac373cf..70c800091 100644
--- a/packages/app-tests/e2e/api/v2/unauthorized-api-access/api-access-file-upload.spec.ts
+++ b/packages/app-tests/e2e/api/v2/unauthorized-api-access/api-access-file-upload.spec.ts
@@ -6,6 +6,8 @@ import { createApiToken } from '@documenso/lib/server-only/public-api/create-api
import { seedUser } from '@documenso/prisma/seed/users';
import { expect, test } from '@playwright/test';
+import { WEBAPP_ORIGIN_HEADERS } from '../../../fixtures/authentication';
+
const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
const examplePdf = fs.readFileSync(path.join(__dirname, '../../../../../../assets/example.pdf'));
@@ -37,6 +39,7 @@ const buildPdfFormData = () => {
test.describe('File upload endpoint authorization', () => {
test('rejects an unauthenticated upload-pdf request', async ({ request }) => {
const res = await request.post(`${WEBAPP_BASE_URL}/api/files/upload-pdf`, {
+ headers: WEBAPP_ORIGIN_HEADERS,
multipart: buildPdfFormData(),
});
diff --git a/packages/app-tests/e2e/branding-logo-upload.spec.ts b/packages/app-tests/e2e/branding-logo-upload.spec.ts
index 2b7bd6602..0f7ee655f 100644
--- a/packages/app-tests/e2e/branding-logo-upload.spec.ts
+++ b/packages/app-tests/e2e/branding-logo-upload.spec.ts
@@ -6,7 +6,7 @@ import { prisma } from '@documenso/prisma';
import { seedUser } from '@documenso/prisma/seed/users';
import { expect, type Page, test } from '@playwright/test';
-import { apiSignin } from './fixtures/authentication';
+import { apiSignin, WEBAPP_ORIGIN_HEADERS } from './fixtures/authentication';
test.describe.configure({ mode: 'parallel' });
@@ -43,7 +43,10 @@ const postOrganisationBrandingLogo = async (page: Page, organisationId: string,
return await page
.context()
- .request.post(`${NEXT_PUBLIC_WEBAPP_URL()}/api/trpc/organisation.settings.updateBrandingLogo`, { multipart });
+ .request.post(`${NEXT_PUBLIC_WEBAPP_URL()}/api/trpc/organisation.settings.updateBrandingLogo`, {
+ headers: WEBAPP_ORIGIN_HEADERS,
+ multipart,
+ });
};
/**
diff --git a/packages/app-tests/e2e/document-auth/assistant-null-order.spec.ts b/packages/app-tests/e2e/document-auth/assistant-null-order.spec.ts
index b7eb5597c..561a9d561 100644
--- a/packages/app-tests/e2e/document-auth/assistant-null-order.spec.ts
+++ b/packages/app-tests/e2e/document-auth/assistant-null-order.spec.ts
@@ -9,6 +9,8 @@ import type { Page } from '@playwright/test';
import { expect, test } from '@playwright/test';
import { DocumentSigningOrder, FieldType, RecipientRole } from '@prisma/client';
+import { WEBAPP_ORIGIN_HEADERS } from '../fixtures/authentication';
+
const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
/**
@@ -67,7 +69,7 @@ const seedAssistantDocument = async (options: {
const callSignEnvelopeField = async (page: Page, input: { token: string; fieldId: number }) => {
return await page.context().request.post(`${WEBAPP_BASE_URL}/api/trpc/envelope.field.sign`, {
- headers: { 'content-type': 'application/json' },
+ headers: { ...WEBAPP_ORIGIN_HEADERS, 'content-type': 'application/json' },
data: JSON.stringify({
json: {
token: input.token,
diff --git a/packages/app-tests/e2e/document-auth/assistant-signing-auth.spec.ts b/packages/app-tests/e2e/document-auth/assistant-signing-auth.spec.ts
index f6f9e0fef..ae0d7c8d8 100644
--- a/packages/app-tests/e2e/document-auth/assistant-signing-auth.spec.ts
+++ b/packages/app-tests/e2e/document-auth/assistant-signing-auth.spec.ts
@@ -4,6 +4,7 @@ import { type APIRequestContext, expect, test } from '@playwright/test';
import { FieldType, SigningStatus } from '@prisma/client';
import { apiSeedPendingDocument } from '../fixtures/api-seeds';
+import { WEBAPP_ORIGIN_HEADERS } from '../fixtures/authentication';
const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
@@ -90,7 +91,7 @@ const seedTwoPendingEnvelopes = async (request: APIRequestContext): Promise<Seed
const trpcMutation = async (request: APIRequestContext, procedure: string, input: Record<string, unknown>) => {
return await request.post(`${WEBAPP_BASE_URL}/api/trpc/${procedure}`, {
- headers: { 'content-type': 'application/json' },
+ headers: { ...WEBAPP_ORIGIN_HEADERS, 'content-type': 'application/json' },
data: JSON.stringify({ json: input }),
});
};
diff --git a/packages/app-tests/e2e/document-auth/assistant-signing-groups.spec.ts b/packages/app-tests/e2e/document-auth/assistant-signing-groups.spec.ts
index 0bb1f732d..d3231f09c 100644
--- a/packages/app-tests/e2e/document-auth/assistant-signing-groups.spec.ts
+++ b/packages/app-tests/e2e/document-auth/assistant-signing-groups.spec.ts
@@ -5,6 +5,7 @@ import { type APIRequestContext, expect, test } from '@playwright/test';
import { FieldType } from '@prisma/client';
import { apiSeedPendingDocument } from '../fixtures/api-seeds';
+import { WEBAPP_ORIGIN_HEADERS } from '../fixtures/authentication';
const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
@@ -106,7 +107,7 @@ const seedGroupedAssistantEnvelope = async (request: APIRequestContext): Promise
const trpcMutation = async (request: APIRequestContext, procedure: string, input: Record<string, unknown>) => {
return await request.post(`${WEBAPP_BASE_URL}/api/trpc/${procedure}`, {
- headers: { 'content-type': 'application/json' },
+ headers: { ...WEBAPP_ORIGIN_HEADERS, 'content-type': 'application/json' },
data: JSON.stringify({ json: input }),
});
};
diff --git a/packages/app-tests/e2e/embed/embed-popup-auth.spec.ts b/packages/app-tests/e2e/embed/embed-popup-auth.spec.ts
new file mode 100644
index 000000000..5b1247ef8
--- /dev/null
+++ b/packages/app-tests/e2e/embed/embed-popup-auth.spec.ts
@@ -0,0 +1,152 @@
+import { EMBED_AUTH_COMPLETE_API_PATH, EMBED_AUTH_POPUP_PATH } from '@documenso/lib/constants/embed-auth';
+import { createDocumentAuthOptions } from '@documenso/lib/utils/document-auth';
+import { seedPendingDocumentWithFullFields } from '@documenso/prisma/seed/documents';
+import { seedUser } from '@documenso/prisma/seed/users';
+import { expect, test } from '@playwright/test';
+import { FieldType } from '@prisma/client';
+
+import { waitForHydration } from '../fixtures/hydration';
+
+const PDF_PAGE_SELECTOR = 'img[data-page-number]';
+
+const EMBED_AUTH_PROVIDER_BUTTON_SELECTOR = 'fieldset button';
+
+const EMBED_AUTH_COMPLETE_PAGE_PATH = '/embed/auth/complete';
+
+// Redeem polling starts after a 5s delay and repeats every 2s.
+const EMBED_REDEEM_TIMEOUT_MS = 30_000;
+
+test.describe.configure({ mode: 'parallel', timeout: 90_000 });
+
+test('[EMBED_POPUP_AUTH]: signs in via account popup and unlocks the embed', async ({ page, context }) => {
+ const { user: owner, team } = await seedUser();
+
+ const recipientPassword = 'password';
+
+ const { user: recipient } = await seedUser({ password: recipientPassword });
+
+ const { recipients } = await seedPendingDocumentWithFullFields({
+ owner,
+ teamId: team.id,
+ recipients: [recipient],
+ fields: [FieldType.SIGNATURE],
+ updateDocumentOptions: {
+ authOptions: createDocumentAuthOptions({
+ globalAccessAuth: ['ACCOUNT'],
+ globalActionAuth: [],
+ }),
+ },
+ });
+
+ const { token } = recipients[0];
+
+ const embedSignPath = `/embed/sign/${token}`;
+
+ await page.goto(embedSignPath);
+
+ await expect(page.getByRole('alert')).toContainText('please sign in to continue');
+
+ const signInWithEmailButton = page.getByRole('button', { name: 'Sign in with email or passkey' });
+
+ await expect(signInWithEmailButton).toBeVisible();
+
+ // Clicking before hydration is a no-op and the popup never opens.
+ await waitForHydration(page, EMBED_AUTH_PROVIDER_BUTTON_SELECTOR);
+
+ const popupPromise = context.waitForEvent('page');
+
+ await signInWithEmailButton.click();
+
+ const popup = await popupPromise;
+
+ await popup.waitForURL((url) => url.pathname === EMBED_AUTH_POPUP_PATH);
+
+ const popupUrl = new URL(popup.url());
+
+ expect(popupUrl.pathname).toBe(EMBED_AUTH_POPUP_PATH);
+ expect(popupUrl.searchParams.get('provider')).toBe('account');
+
+ expect(popup.url()).not.toContain('nonce');
+
+ await expect(popup.getByRole('heading', { name: 'Sign in to Documenso to continue' })).toBeVisible();
+
+ await expect(page.getByText('Complete sign in in the popup window')).toBeVisible();
+
+ // Email is prefilled from the fragment but filled explicitly to avoid timing sensitivity.
+ const emailInput = popup.getByLabel('Email');
+
+ await expect(emailInput).toBeVisible();
+
+ await emailInput.fill(recipient.email);
+ await popup.getByRole('textbox', { name: 'Password' }).fill(recipientPassword);
+
+ // The completion page closes itself and may do so before we observe the URL.
+ const completePagePromise = popup
+ .waitForURL((url) => url.pathname === EMBED_AUTH_COMPLETE_PAGE_PATH && url.searchParams.get('status') === 'ok', {
+ timeout: 15_000,
+ })
+ .then(() => 'ok' as const)
+ .catch((err: unknown) => {
+ if (popup.isClosed()) {
+ return 'closed' as const;
+ }
+
+ throw err;
+ });
+
+ const completeResponsePromise = popup.waitForResponse(
+ (response) =>
+ response.request().method() === 'GET' && new URL(response.url()).pathname === EMBED_AUTH_COMPLETE_API_PATH,
+ { timeout: 15_000 },
+ );
+
+ await popup.getByRole('button', { name: 'Sign In' }).click();
+
+ const completeResponse = await completeResponsePromise;
+
+ const completeUrl = new URL(completeResponse.url());
+
+ expect(completeUrl.searchParams.get('state')).toBeTruthy();
+ expect(completeResponse.url()).not.toContain('nonce');
+
+ expect(completeResponse.status()).toBe(302);
+
+ const completeLocation = completeResponse.headers().location;
+
+ expect(completeLocation).toBeDefined();
+
+ const completeLocationUrl = new URL(completeLocation, completeResponse.url());
+
+ expect(completeLocationUrl.pathname).toBe(EMBED_AUTH_COMPLETE_PAGE_PATH);
+ expect(completeLocationUrl.searchParams.get('status')).toBe('ok');
+
+ const completeResult = await completePagePromise;
+
+ expect(['ok', 'closed']).toContain(completeResult);
+
+ if (completeResult === 'ok') {
+ expect(popup.url()).not.toContain('nonce');
+ }
+
+ await expect(page.locator(PDF_PAGE_SELECTOR).first()).toBeVisible({ timeout: EMBED_REDEEM_TIMEOUT_MS });
+
+ await expect(page.getByRole('button', { name: 'Sign in with email or passkey' })).toHaveCount(0);
+
+ expect(new URL(page.url()).pathname).toBe(embedSignPath);
+
+ // Over http the embed cookie has no `__Host-` prefix, is `SameSite=Lax` and not partitioned.
+ const cookies = await context.cookies();
+
+ const embedSessionCookie = cookies.find((cookie) => cookie.name === 'embedSessionId');
+
+ expect(embedSessionCookie).toBeDefined();
+ expect(embedSessionCookie?.domain).toContain('localhost');
+ expect(embedSessionCookie?.secure).toBe(false);
+ expect(embedSessionCookie?.httpOnly).toBe(true);
+ expect(embedSessionCookie?.sameSite).toBe('Lax');
+
+ const sessionCookie = cookies.find((cookie) => cookie.name === 'sessionId');
+
+ expect(sessionCookie).toBeDefined();
+ expect(sessionCookie?.sameSite).toBe('Lax');
+});
diff --git a/packages/app-tests/e2e/envelopes/envelope-expiration-signing.spec.ts b/packages/app-tests/e2e/envelopes/envelope-expiration-signing.spec.ts
index e98bacdf3..4f83f20c7 100644
--- a/packages/app-tests/e2e/envelopes/envelope-expiration-signing.spec.ts
+++ b/packages/app-tests/e2e/envelopes/envelope-expiration-signing.spec.ts
@@ -6,7 +6,7 @@ import { seedUser } from '@documenso/prisma/seed/users';
import { type APIRequestContext, expect, test } from '@playwright/test';
import { apiSeedPendingDocument } from '../fixtures/api-seeds';
-import { apiSignin } from '../fixtures/authentication';
+import { apiSignin, WEBAPP_ORIGIN_HEADERS } from '../fixtures/authentication';
import { signSignaturePad } from '../fixtures/signature';
test.describe.configure({ mode: 'parallel' });
@@ -133,7 +133,7 @@ test('[ENVELOPE_EXPIRATION]: expired recipient cannot complete signing', async (
const trpcMutation = async (request: APIRequestContext, procedure: string, input: Record<string, unknown>) => {
return await request.post(`${NEXT_PUBLIC_WEBAPP_URL()}/api/trpc/${procedure}`, {
- headers: { 'content-type': 'application/json' },
+ headers: { ...WEBAPP_ORIGIN_HEADERS, 'content-type': 'application/json' },
data: JSON.stringify({ json: input }),
});
};
diff --git a/packages/app-tests/e2e/fixtures/authentication.ts b/packages/app-tests/e2e/fixtures/authentication.ts
index 6fb465afb..63df92262 100644
--- a/packages/app-tests/e2e/fixtures/authentication.ts
+++ b/packages/app-tests/e2e/fixtures/authentication.ts
@@ -1,6 +1,12 @@
import { NEXT_PUBLIC_WEBAPP_URL } from '@documenso/lib/constants/app';
import type { Page } from '@playwright/test';
+// Playwright's `APIRequestContext` never sends `Origin`, which the CSRF
+// middleware requires on cookie-authenticated mutations.
+export const WEBAPP_ORIGIN_HEADERS = {
+ Origin: new URL(NEXT_PUBLIC_WEBAPP_URL()).origin,
+} as const;
+
type LoginOptions = {
page: Page;
email?: string;
@@ -23,6 +29,7 @@ export const apiSignin = async ({
const csrfToken = await getCsrfToken(page);
await request.post(`${NEXT_PUBLIC_WEBAPP_URL()}/api/auth/email-password/authorize`, {
+ headers: WEBAPP_ORIGIN_HEADERS,
data: {
email,
password,
@@ -37,7 +44,9 @@ export const apiSignin = async ({
export const apiSignout = async ({ page }: { page: Page }) => {
const { request } = page.context();
- await request.post(`${NEXT_PUBLIC_WEBAPP_URL()}/api/auth/signout`);
+ await request.post(`${NEXT_PUBLIC_WEBAPP_URL()}/api/auth/signout`, {
+ headers: WEBAPP_ORIGIN_HEADERS,
+ });
await page.goto(`${NEXT_PUBLIC_WEBAPP_URL()}/signin`);
};
diff --git a/packages/app-tests/e2e/organisations/organisation-permission-hierarchy.spec.ts b/packages/app-tests/e2e/organisations/organisation-permission-hierarchy.spec.ts
index 23483a48e..4104d5601 100644
--- a/packages/app-tests/e2e/organisations/organisation-permission-hierarchy.spec.ts
+++ b/packages/app-tests/e2e/organisations/organisation-permission-hierarchy.spec.ts
@@ -6,7 +6,7 @@ import { seedUser } from '@documenso/prisma/seed/users';
import { expect, type Page, test } from '@playwright/test';
import { OrganisationGroupType, type OrganisationMemberRole } from '@prisma/client';
-import { apiSignin } from '../fixtures/authentication';
+import { apiSignin, WEBAPP_ORIGIN_HEADERS } from '../fixtures/authentication';
const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
@@ -18,7 +18,7 @@ const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
*/
const trpcMutation = async (page: Page, procedure: string, input: Record<string, unknown>) => {
return await page.request.post(`${WEBAPP_BASE_URL}/api/trpc/${procedure}`, {
- headers: { 'content-type': 'application/json' },
+ headers: { ...WEBAPP_ORIGIN_HEADERS, 'content-type': 'application/json' },
data: JSON.stringify({ json: input }),
});
};
diff --git a/packages/app-tests/e2e/teams/team-groups.spec.ts b/packages/app-tests/e2e/teams/team-groups.spec.ts
index 74c7f6372..b9e752b76 100644
--- a/packages/app-tests/e2e/teams/team-groups.spec.ts
+++ b/packages/app-tests/e2e/teams/team-groups.spec.ts
@@ -6,7 +6,7 @@ import { seedUser } from '@documenso/prisma/seed/users';
import { expect, type Page, test } from '@playwright/test';
import { OrganisationGroupType, OrganisationMemberRole, TeamMemberRole } from '@prisma/client';
-import { apiSignin } from '../fixtures/authentication';
+import { apiSignin, WEBAPP_ORIGIN_HEADERS } from '../fixtures/authentication';
const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
@@ -26,7 +26,11 @@ const callTeamGroupMutation = (
input: Record<string, unknown>,
) =>
page.context().request.post(`${WEBAPP_BASE_URL}/api/trpc/${procedure}`, {
- headers: { 'content-type': 'application/json', 'x-team-id': teamId.toString() },
+ headers: {
+ ...WEBAPP_ORIGIN_HEADERS,
+ 'content-type': 'application/json',
+ 'x-team-id': teamId.toString(),
+ },
data: JSON.stringify({ json: input }),
});
diff --git a/packages/app-tests/e2e/teams/team-profile-access.spec.ts b/packages/app-tests/e2e/teams/team-profile-access.spec.ts
index ecff18fed..c3900ffa5 100644
--- a/packages/app-tests/e2e/teams/team-profile-access.spec.ts
+++ b/packages/app-tests/e2e/teams/team-profile-access.spec.ts
@@ -4,7 +4,7 @@ import { TeamMemberRole } from '@documenso/prisma/client';
import { seedTeam, seedTeamMember } from '@documenso/prisma/seed/teams';
import { expect, test } from '@playwright/test';
-import { apiSignin } from '../fixtures/authentication';
+import { apiSignin, WEBAPP_ORIGIN_HEADERS } from '../fixtures/authentication';
const WEBAPP_BASE_URL = NEXT_PUBLIC_WEBAPP_URL();
@@ -21,7 +21,11 @@ test('[TEAMS]: a member cannot edit the team public profile', async ({ page }) =
await apiSignin({ page, email: member.email });
const profileRes = await page.context().request.post(`${WEBAPP_BASE_URL}/api/trpc/team.update`, {
- headers: { 'content-type': 'application/json', 'x-team-id': team.id.toString() },
+ headers: {
+ ...WEBAPP_ORIGIN_HEADERS,
+ 'content-type': 'application/json',
+ 'x-team-id': team.id.toString(),
+ },
data: JSON.stringify({
json: {
teamId: team.id,
@@ -38,7 +42,11 @@ test('[TEAMS]: a member cannot edit the team public profile', async ({ page }) =
// The name/url path of the same route is also management-gated.
const nameRes = await page.context().request.post(`${WEBAPP_BASE_URL}/api/trpc/team.update`, {
- headers: { 'content-type': 'application/json', 'x-team-id': team.id.toString() },
+ headers: {
+ ...WEBAPP_ORIGIN_HEADERS,
+ 'content-type': 'application/json',
+ 'x-team-id': team.id.toString(),
+ },
data: JSON.stringify({
json: { teamId: team.id, data: { name: 'renamed-by-member' } },
}),
diff --git a/packages/app-tests/e2e/templates/organisation-templates.spec.ts b/packages/app-tests/e2e/templates/organisation-templates.spec.ts
index 1e51ca714..02d421fbb 100644
--- a/packages/app-tests/e2e/templates/organisation-templates.spec.ts
+++ b/packages/app-tests/e2e/templates/organisation-templates.spec.ts
@@ -10,7 +10,7 @@ import { expect, test } from '@playwright/test';
import { TemplateType } from '@prisma/client';
import { customAlphabet } from 'nanoid';
-import { apiSignin, apiSignout } from '../fixtures/authentication';
+import { apiSignin, apiSignout, WEBAPP_ORIGIN_HEADERS } from '../fixtures/authentication';
const nanoid = customAlphabet('1234567890abcdef', 10);
@@ -83,6 +83,7 @@ const trpcMutation = async (page: Page, procedure: string, input: Record<string,
const url = `${WEBAPP_BASE_URL}/api/trpc/${procedure}`;
const headers: Record<string, string> = {
+ ...WEBAPP_ORIGIN_HEADERS,
'content-type': 'application/json',
};
diff --git a/packages/app-tests/e2e/user/password-two-factor.spec.ts b/packages/app-tests/e2e/user/password-two-factor.spec.ts
index 8c19adc8a..612eecbde 100644
--- a/packages/app-tests/e2e/user/password-two-factor.spec.ts
+++ b/packages/app-tests/e2e/user/password-two-factor.spec.ts
@@ -8,7 +8,7 @@ import { expect, test } from '@playwright/test';
import { base32 } from '@scure/base';
import { generateHOTP } from 'oslo/otp';
-import { apiSignin } from '../fixtures/authentication';
+import { apiSignin, WEBAPP_ORIGIN_HEADERS } from '../fixtures/authentication';
import { waitForHydration } from '../fixtures/hydration';
test.describe.configure({ mode: 'parallel', timeout: 60000 });
@@ -93,6 +93,7 @@ test('[USER] password update API rejects a missing 2FA code when 2FA is enabled'
await enableTwoFactorAuthentication({ user: userWithSecret, code: await getCurrentTotpCode(user.id) });
const response = await page.request.post('/api/auth/email-password/update-password', {
+ headers: WEBAPP_ORIGIN_HEADERS,
data: { currentPassword: 'password', password: 'Test123!' },
});
diff --git a/packages/auth/client/index.ts b/packages/auth/client/index.ts
index a7ac7977f..febbef37c 100644
--- a/packages/auth/client/index.ts
+++ b/packages/auth/client/index.ts
@@ -33,6 +33,19 @@ type TPasskeySignin = InferRequestType<AuthClientType['passkey']['authorize']['$
redirectPath?: string;
};
+type TEmbedAuthStart = InferRequestType<AuthClientType['embed']['start']['$post']>['json'];
+
+type TEmbedAuthRedeem = InferRequestType<AuthClientType['embed']['redeem']['$post']>['json'];
+
+export type TEmbedAuthRedeemResult = 'ok' | 'pending' | 'rate-limited' | 'failed';
+
+// Cross-site iframe requests need `credentials: 'include'` to carry the partitioned cookie.
+const embedRequestOptions = {
+ init: {
+ credentials: 'include',
+ },
+} as const;
+
export class AuthClient {
public client: AuthClientType;
@@ -273,6 +286,64 @@ export class AuthClient {
},
};
+ public embed = {
+ start: async (data: TEmbedAuthStart): Promise<{ redirectUrl: string | null; returnTo: string | null }> => {
+ const response = await this.client.embed.start.$post({ json: data });
+
+ if (!response.ok) {
+ const error = await response.json();
+
+ throw AppError.parseError(error);
+ }
+
+ const result = await response.json();
+
+ return {
+ redirectUrl: result.redirectUrl,
+ returnTo: 'returnTo' in result ? result.returnTo : null,
+ };
+ },
+
+ redeem: async (data: TEmbedAuthRedeem): Promise<TEmbedAuthRedeemResult> => {
+ const response = await this.client.embed.redeem.$post({ json: data }, embedRequestOptions);
+
+ // The RPC type does not know about the rate limit middleware's 429.
+ const status: number = response.status;
+
+ if (status === 429) {
+ return 'rate-limited';
+ }
+
+ if (!response.ok) {
+ const error = await response.json();
+
+ throw AppError.parseError(error);
+ }
+
+ if (response.status === 202) {
+ return 'pending';
+ }
+
+ const result = await response.json();
+
+ return result.status === 'failed' ? 'failed' : 'ok';
+ },
+
+ getSession: async () => {
+ const response = await this.client['session-json'].$get(undefined, embedRequestOptions);
+
+ if (!response.ok) {
+ const error = await response.json();
+
+ throw AppError.parseError(error);
+ }
+
+ const result = await response.json();
+
+ return superjson.deserialize<SessionValidationResult>(result);
+ },
+ };
+
public google = {
signIn: async ({ redirectPath }: { redirectPath?: string } = {}) => {
const response = await this.client['oauth'].authorize.google.$post({
diff --git a/packages/auth/server/config.ts b/packages/auth/server/config.ts
index 57234294b..834e6b4f8 100644
--- a/packages/auth/server/config.ts
+++ b/packages/auth/server/config.ts
@@ -6,6 +6,10 @@ import { env } from '@documenso/lib/utils/env';
*/
export const AUTH_SESSION_LIFETIME = 1000 * 60 * 60 * 24 * 30; // 30 days.
+// Short and non-sliding: embed sessions live in a third-party partition outside
+// the user's normal sign-out path and only need to outlast a signing session.
+export const AUTH_EMBED_SESSION_LIFETIME = 1000 * 60 * 60 * 12; // 12 hours.
+
export type OAuthClientOptions = {
id: string;
scope: string[];
diff --git a/packages/auth/server/index.ts b/packages/auth/server/index.ts
index 1fd7088b6..335018972 100644
--- a/packages/auth/server/index.ts
+++ b/packages/auth/server/index.ts
@@ -1,14 +1,15 @@
-import { NEXT_PUBLIC_WEBAPP_URL } from '@documenso/lib/constants/app';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { extractRequestMetadata } from '@documenso/lib/universal/extract-request-metadata';
import { Hono } from 'hono';
import { HTTPException } from 'hono/http-exception';
import type { ContentfulStatusCode } from 'hono/utils/http-status';
+import { rejectEmbedSessionMiddleware } from './lib/session/embed-session-restrictions';
import { setCsrfCookie } from './lib/session/session-cookies';
import { accountRoute } from './routes/account';
import { callbackRoute } from './routes/callback';
import { emailPasswordRoute } from './routes/email-password';
+import { embedRoute } from './routes/embed';
import { oauthRoute } from './routes/oauth';
import { passkeyRoute } from './routes/passkey';
import { sessionRoute } from './routes/session';
@@ -21,21 +22,13 @@ export const auth = new Hono<HonoAuthContext>()
.use(async (c, next) => {
c.set('requestMetadata', extractRequestMetadata(c.req.raw));
- const validOrigin = new URL(NEXT_PUBLIC_WEBAPP_URL()).origin;
- const headerOrigin = c.req.header('Origin');
-
- if (headerOrigin && headerOrigin !== validOrigin) {
- return c.json(
- {
- message: 'Forbidden',
- statusCode: 403,
- },
- 403,
- );
- }
-
await next();
})
+ .use('/accounts', rejectEmbedSessionMiddleware)
+ .use('/account/*', rejectEmbedSessionMiddleware)
+ .use('/email-password/update-password', rejectEmbedSessionMiddleware)
+ .use('/email-password/2fa/*', rejectEmbedSessionMiddleware)
+ .use('/two-factor/*', rejectEmbedSessionMiddleware)
.get('/csrf', async (c) => {
const csrfToken = await setCsrfCookie(c);
@@ -47,6 +40,7 @@ export const auth = new Hono<HonoAuthContext>()
.route('/callback', callbackRoute)
.route('/oauth', oauthRoute)
.route('/email-password', emailPasswordRoute)
+ .route('/embed', embedRoute)
.route('/passkey', passkeyRoute)
.route('/two-factor', twoFactorRoute);
diff --git a/packages/auth/server/lib/errors/error-codes.ts b/packages/auth/server/lib/errors/error-codes.ts
index dbce82f09..a70097591 100644
--- a/packages/auth/server/lib/errors/error-codes.ts
+++ b/packages/auth/server/lib/errors/error-codes.ts
@@ -4,6 +4,7 @@ export const AuthenticationErrorCode = {
InvalidCredentials: 'INVALID_CREDENTIALS',
SessionNotFound: 'SESSION_NOT_FOUND',
SessionExpired: 'SESSION_EXPIRED',
+ EmbedSessionRestricted: 'EMBED_SESSION_RESTRICTED',
InvalidToken: 'INVALID_TOKEN',
MissingToken: 'MISSING_TOKEN',
InvalidRequest: 'INVALID_REQUEST',
diff --git a/packages/auth/server/lib/handoff/constants.ts b/packages/auth/server/lib/handoff/constants.ts
new file mode 100644
index 000000000..1a0374d87
--- /dev/null
+++ b/packages/auth/server/lib/handoff/constants.ts
@@ -0,0 +1 @@
+export const AUTH_HANDOFF_TTL_MS = 3 * 60_000;
diff --git a/packages/auth/server/lib/handoff/create-auth-handoff.ts b/packages/auth/server/lib/handoff/create-auth-handoff.ts
new file mode 100644
index 000000000..c04acf606
--- /dev/null
+++ b/packages/auth/server/lib/handoff/create-auth-handoff.ts
@@ -0,0 +1,61 @@
+import type { TAuthHandoffCreate } from '@documenso/lib/constants/auth-handoff';
+import { ZAuthHandoffCreateSchema } from '@documenso/lib/constants/auth-handoff';
+import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
+import { prisma } from '@documenso/prisma';
+
+import { getAuthSecret } from '../session/session-cookies';
+import { AUTH_HANDOFF_TTL_MS } from './constants';
+import { hashAuthHandoffNonce, ZAuthHandoffNonceSchema } from './hash-auth-handoff-nonce';
+import { encryptAuthHandoffPayload } from './payload-crypto';
+
+export type CreateAuthHandoffOptions = TAuthHandoffCreate & {
+ nonce: string;
+};
+
+// Upserted so a retried flow overwrites the previous handoff for the nonce.
+export const createAuthHandoff = async ({ nonce, type, payload }: CreateAuthHandoffOptions) => {
+ const parsedNonce = ZAuthHandoffNonceSchema.safeParse(nonce);
+
+ if (!parsedNonce.success) {
+ throw new AppError(AppErrorCode.INVALID_REQUEST, {
+ message: 'Invalid auth handoff nonce',
+ });
+ }
+
+ const parsedHandoff = ZAuthHandoffCreateSchema.safeParse({ type, payload });
+
+ if (!parsedHandoff.success) {
+ throw new AppError(AppErrorCode.INVALID_REQUEST, {
+ message: 'Invalid auth handoff payload',
+ });
+ }
+
+ const id = hashAuthHandoffNonce(parsedNonce.data);
+
+ const encryptedPayload = encryptAuthHandoffPayload({
+ secret: getAuthSecret(),
+ id,
+ type: parsedHandoff.data.type,
+ payload: parsedHandoff.data.payload,
+ });
+
+ const expiresAt = new Date(Date.now() + AUTH_HANDOFF_TTL_MS);
+
+ await prisma.authHandoff.upsert({
+ where: {
+ id,
+ },
+ create: {
+ id,
+ type: parsedHandoff.data.type,
+ payload: encryptedPayload,
+ expiresAt,
+ },
+ update: {
+ type: parsedHandoff.data.type,
+ payload: encryptedPayload,
+ createdAt: new Date(),
+ expiresAt,
+ },
+ });
+};
diff --git a/packages/auth/server/lib/handoff/hash-auth-handoff-nonce.ts b/packages/auth/server/lib/handoff/hash-auth-handoff-nonce.ts
new file mode 100644
index 000000000..26a1de6fb
--- /dev/null
+++ b/packages/auth/server/lib/handoff/hash-auth-handoff-nonce.ts
@@ -0,0 +1,9 @@
+import { sha256 } from '@oslojs/crypto/sha2';
+import { encodeHexLowerCase } from '@oslojs/encoding';
+import { z } from 'zod';
+
+export const ZAuthHandoffNonceSchema = z.string().uuid();
+
+export const hashAuthHandoffNonce = (nonce: string): string => {
+ return encodeHexLowerCase(sha256(new TextEncoder().encode(nonce)));
+};
diff --git a/packages/auth/server/lib/handoff/payload-crypto.ts b/packages/auth/server/lib/handoff/payload-crypto.ts
new file mode 100644
index 000000000..7954c262b
--- /dev/null
+++ b/packages/auth/server/lib/handoff/payload-crypto.ts
@@ -0,0 +1,65 @@
+import { symmetricDecrypt, symmetricEncrypt } from '@documenso/lib/universal/crypto';
+import { z } from 'zod';
+
+export type EncryptAuthHandoffPayloadOptions = {
+ secret: string;
+ id: string;
+ type: string;
+ payload: unknown;
+};
+
+// `id` and `type` are sealed inside the ciphertext so a payload cannot be
+// replayed on another row or under another type.
+export const encryptAuthHandoffPayload = ({ secret, id, type, payload }: EncryptAuthHandoffPayloadOptions): string => {
+ return symmetricEncrypt({
+ key: secret,
+ data: JSON.stringify({ id, type, payload }),
+ });
+};
+
+export type DecryptAuthHandoffPayloadOptions = {
+ secret: string;
+ id: string;
+ type: string;
+ encryptedPayload: string;
+};
+
+const ZSealedAuthHandoffSchema = z.object({
+ id: z.string(),
+ type: z.string(),
+ payload: z.unknown(),
+});
+
+export const decryptAuthHandoffPayload = ({
+ secret,
+ id,
+ type,
+ encryptedPayload,
+}: DecryptAuthHandoffPayloadOptions): unknown | null => {
+ let sealed: unknown;
+
+ try {
+ sealed = JSON.parse(
+ new TextDecoder().decode(
+ symmetricDecrypt({
+ key: secret,
+ data: encryptedPayload,
+ }),
+ ),
+ );
+ } catch {
+ return null;
+ }
+
+ const parsed = ZSealedAuthHandoffSchema.safeParse(sealed);
+
+ if (!parsed.success) {
+ return null;
+ }
+
+ if (parsed.data.id !== id || parsed.data.type !== type) {
+ return null;
+ }
+
+ return parsed.data.payload ?? null;
+};
diff --git a/packages/auth/server/lib/handoff/record-embed-auth-failure.ts b/packages/auth/server/lib/handoff/record-embed-auth-failure.ts
new file mode 100644
index 000000000..961551640
--- /dev/null
+++ b/packages/auth/server/lib/handoff/record-embed-auth-failure.ts
@@ -0,0 +1,52 @@
+import { AUTH_HANDOFF_TYPE } from '@documenso/lib/constants/auth-handoff';
+import { logger } from '@documenso/lib/utils/logger';
+import type { Context } from 'hono';
+
+import { clearEmbedAuthFlowCookie, getEmbedAuthFlowCookie } from '../session/session-cookies';
+import { isEqualSecret } from '../utils/is-equal-secret';
+import { createAuthHandoff } from './create-auth-handoff';
+
+// Best effort; if the write fails the iframe still has Cancel and the flow timeout.
+export const recordEmbedAuthFailure = async (nonce: string, reason: string): Promise<void> => {
+ try {
+ await createAuthHandoff({
+ nonce,
+ type: AUTH_HANDOFF_TYPE.EMBED_FAILED,
+ payload: {},
+ });
+ } catch (err) {
+ logger.error({
+ event: 'auth.embed.failure_record_failed',
+ reason,
+ error: err,
+ });
+ }
+};
+
+/**
+ * Without a `state` match nothing is recorded: a lingering flow cookie may
+ * belong to a newer attempt, and failing it from an unrelated request would
+ * break that attempt. Returns whether the request belonged to an embed flow.
+ */
+export const failEmbedAuthFlow = async (c: Context, state: string | undefined, reason: string): Promise<boolean> => {
+ if (!state) {
+ return false;
+ }
+
+ const flow = await getEmbedAuthFlowCookie(c);
+
+ if (!flow || !isEqualSecret(flow.state, state)) {
+ return false;
+ }
+
+ clearEmbedAuthFlowCookie(c);
+
+ await recordEmbedAuthFailure(flow.nonce, reason);
+
+ logger.warn({
+ event: 'auth.embed.flow_failed',
+ reason,
+ });
+
+ return true;
+};
diff --git a/packages/auth/server/lib/handoff/redeem-auth-handoff.ts b/packages/auth/server/lib/handoff/redeem-auth-handoff.ts
new file mode 100644
index 000000000..4a3420480
--- /dev/null
+++ b/packages/auth/server/lib/handoff/redeem-auth-handoff.ts
@@ -0,0 +1,244 @@
+import type {
+ TAuthHandoffEmbedCscBlockingErrorPayload,
+ TAuthHandoffEmbedCscSadPayload,
+} from '@documenso/lib/constants/auth-handoff';
+import { AUTH_HANDOFF_TYPE, ZAuthHandoffStoredSchema } from '@documenso/lib/constants/auth-handoff';
+import { prisma } from '@documenso/prisma';
+import { match } from 'ts-pattern';
+
+import { createSession, generateSessionToken } from '../session/session';
+import { getAuthSecret } from '../session/session-cookies';
+import { AUTH_HANDOFF_TTL_MS } from './constants';
+import { hashAuthHandoffNonce, ZAuthHandoffNonceSchema } from './hash-auth-handoff-nonce';
+import { decryptAuthHandoffPayload, encryptAuthHandoffPayload } from './payload-crypto';
+
+export type RedeemAuthHandoffOptions = {
+ nonce: string;
+ ipAddress?: string;
+ userAgent?: string;
+};
+
+export type RedeemAuthHandoffResult =
+ | {
+ type: typeof AUTH_HANDOFF_TYPE.EMBED_SESSION;
+ payload: {
+ sessionToken: string;
+ };
+ }
+ | {
+ type: typeof AUTH_HANDOFF_TYPE.EMBED_CSC_SERVICE;
+ payload: {
+ recipientToken: string;
+ ttlSeconds: number;
+ };
+ }
+ | {
+ type: typeof AUTH_HANDOFF_TYPE.EMBED_CSC_SAD;
+ payload: TAuthHandoffEmbedCscSadPayload;
+ }
+ | {
+ type: typeof AUTH_HANDOFF_TYPE.EMBED_CSC_BLOCKING_ERROR;
+ payload: TAuthHandoffEmbedCscBlockingErrorPayload;
+ }
+ | {
+ type: typeof AUTH_HANDOFF_TYPE.EMBED_FAILED;
+ };
+
+const SESSION_CLAIM_MAX_RETRIES = 1;
+
+/**
+ * Redeem is intentionally NOT one-time: some browsers (older Safari) drop the
+ * first `Set-Cookie` from within an iframe and the embed must retry after
+ * `requestStorageAccess()`. `EMBED_SESSION` mints a session on first redeem and
+ * writes the token back into the encrypted payload for subsequent redeems.
+ */
+export const redeemAuthHandoff = async ({
+ nonce,
+ ipAddress,
+ userAgent,
+}: RedeemAuthHandoffOptions): Promise<RedeemAuthHandoffResult | null> => {
+ const parsedNonce = ZAuthHandoffNonceSchema.safeParse(nonce);
+
+ if (!parsedNonce.success) {
+ return null;
+ }
+
+ const id = hashAuthHandoffNonce(parsedNonce.data);
+
+ return await redeemAuthHandoffById({ id, ipAddress, userAgent, retriesLeft: SESSION_CLAIM_MAX_RETRIES });
+};
+
+type RedeemAuthHandoffByIdOptions = {
+ id: string;
+ ipAddress?: string;
+ userAgent?: string;
+ retriesLeft: number;
+};
+
+const redeemAuthHandoffById = async ({
+ id,
+ ipAddress,
+ userAgent,
+ retriesLeft,
+}: RedeemAuthHandoffByIdOptions): Promise<RedeemAuthHandoffResult | null> => {
+ const row = await prisma.authHandoff.findUnique({
+ where: {
+ id,
+ },
+ });
+
+ if (!row) {
+ return null;
+ }
+
+ if (row.expiresAt.getTime() <= Date.now()) {
+ await prisma.authHandoff.deleteMany({
+ where: {
+ id,
+ },
+ });
+
+ return null;
+ }
+
+ const authSecret = getAuthSecret();
+
+ const parsed = ZAuthHandoffStoredSchema.safeParse({
+ type: row.type,
+ payload: decryptAuthHandoffPayload({
+ secret: authSecret,
+ id,
+ type: row.type,
+ encryptedPayload: row.payload,
+ }),
+ });
+
+ if (!parsed.success) {
+ return null;
+ }
+
+ const handoff = parsed.data;
+
+ return match(handoff)
+ .with({ type: AUTH_HANDOFF_TYPE.EMBED_SESSION }, async ({ payload }) => {
+ if (payload.sessionToken) {
+ return {
+ type: AUTH_HANDOFF_TYPE.EMBED_SESSION,
+ payload: { sessionToken: payload.sessionToken },
+ };
+ }
+
+ // The handoff must not outlive the top-level session that produced it.
+ const originatingSession = await prisma.session.findFirst({
+ where: {
+ id: payload.sessionId,
+ expiresAt: {
+ gt: new Date(),
+ },
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (!originatingSession) {
+ await prisma.authHandoff.deleteMany({
+ where: {
+ id,
+ },
+ });
+
+ return null;
+ }
+
+ const sessionToken = generateSessionToken();
+
+ const claimedPayload = encryptAuthHandoffPayload({
+ secret: authSecret,
+ id,
+ type: AUTH_HANDOFF_TYPE.EMBED_SESSION,
+ payload: {
+ userId: payload.userId,
+ sessionId: payload.sessionId,
+ sessionToken,
+ },
+ });
+
+ // Optimistic claim on the exact ciphertext read so concurrent first-redeems
+ // cannot both mint a session. TTL restarts so a Safari storage-access
+ // round trip has the full window to redeem again.
+ const isClaimed = await prisma.$transaction(async (tx) => {
+ const { count } = await tx.authHandoff.updateMany({
+ where: {
+ id,
+ payload: row.payload,
+ expiresAt: {
+ gt: new Date(),
+ },
+ },
+ data: {
+ payload: claimedPayload,
+ expiresAt: new Date(Date.now() + AUTH_HANDOFF_TTL_MS),
+ },
+ });
+
+ if (count === 0) {
+ return false;
+ }
+
+ await createSession(sessionToken, payload.userId, { ipAddress, userAgent }, { isEmbed: true, tx });
+
+ return true;
+ });
+
+ if (isClaimed) {
+ return {
+ type: AUTH_HANDOFF_TYPE.EMBED_SESSION,
+ payload: { sessionToken },
+ };
+ }
+
+ if (retriesLeft <= 0) {
+ return null;
+ }
+
+ return redeemAuthHandoffById({ id, ipAddress, userAgent, retriesLeft: retriesLeft - 1 });
+ })
+ .with({ type: AUTH_HANDOFF_TYPE.EMBED_CSC_SERVICE }, ({ payload }): RedeemAuthHandoffResult => {
+ const ttlSeconds = remainingSeconds(payload.expiresAt);
+
+ if (ttlSeconds < 1) {
+ return { type: AUTH_HANDOFF_TYPE.EMBED_FAILED };
+ }
+
+ return {
+ type: AUTH_HANDOFF_TYPE.EMBED_CSC_SERVICE,
+ payload: {
+ recipientToken: payload.recipientToken,
+ ttlSeconds,
+ },
+ };
+ })
+ .with({ type: AUTH_HANDOFF_TYPE.EMBED_CSC_SAD }, ({ payload }): RedeemAuthHandoffResult => {
+ if (remainingSeconds(payload.expiresAt) < 1) {
+ return { type: AUTH_HANDOFF_TYPE.EMBED_FAILED };
+ }
+
+ return {
+ type: AUTH_HANDOFF_TYPE.EMBED_CSC_SAD,
+ payload,
+ };
+ })
+ .with({ type: AUTH_HANDOFF_TYPE.EMBED_CSC_BLOCKING_ERROR }, ({ payload }) => ({
+ type: AUTH_HANDOFF_TYPE.EMBED_CSC_BLOCKING_ERROR,
+ payload,
+ }))
+ .with({ type: AUTH_HANDOFF_TYPE.EMBED_FAILED }, () => ({
+ type: AUTH_HANDOFF_TYPE.EMBED_FAILED,
+ }))
+ .exhaustive();
+};
+
+const remainingSeconds = (expiresAt: Date): number => {
+ return Math.floor((expiresAt.getTime() - Date.now()) / 1000);
+};
diff --git a/packages/auth/server/lib/session/embed-session-restrictions.ts b/packages/auth/server/lib/session/embed-session-restrictions.ts
new file mode 100644
index 000000000..a65028bf7
--- /dev/null
+++ b/packages/auth/server/lib/session/embed-session-restrictions.ts
@@ -0,0 +1,54 @@
+import { AppError } from '@documenso/lib/errors/app-error';
+import type { Session } from '@prisma/client';
+import type { Context } from 'hono';
+import { createMiddleware } from 'hono/factory';
+
+import { AuthenticationErrorCode } from '../errors/error-codes';
+import type { SessionValidationResult } from '../session/session';
+import { getOptionalSession } from '../utils/get-session';
+
+/**
+ * Embed sessions exist only to let a recipient sign inside an iframe. Anything
+ * else is refused so a leaked embed session is not enough to act on the account.
+ * TRPC routes opt in via `allowEmbedSession` meta; Hono routes mount
+ * `rejectEmbedSessionMiddleware`.
+ */
+export const assertNotEmbedSession = (session: Pick<Session, 'isEmbed'> | null | undefined): void => {
+ if (!session?.isEmbed) {
+ return;
+ }
+
+ throw new AppError(AuthenticationErrorCode.EmbedSessionRestricted, {
+ message: 'This action is not available from an embedded session. Sign in to Documenso directly to continue.',
+ statusCode: 403,
+ });
+};
+
+/**
+ * Resolves the session but treats an embed session as anonymous. For routes
+ * that fall back to a token when there is no session, so a partitioned embed
+ * cookie left by a signing iframe does not shadow the token (e.g. embedded
+ * authoring on the same host after embedded signing).
+ */
+export const getOptionalNonEmbedSession = async (c: Context | Request): Promise<SessionValidationResult> => {
+ const result = await getOptionalSession(c);
+
+ if (result.session?.isEmbed) {
+ return {
+ isAuthenticated: false,
+ session: null,
+ user: null,
+ };
+ }
+
+ return result;
+};
+
+// Anonymous requests pass through so the route's own `getSession` produces its usual 401.
+export const rejectEmbedSessionMiddleware = createMiddleware(async (c: Context, next) => {
+ const { session } = await getOptionalSession(c);
+
+ assertNotEmbedSession(session);
+
+ await next();
+});
diff --git a/packages/auth/server/lib/session/session-cookies.ts b/packages/auth/server/lib/session/session-cookies.ts
index 39ed9f45c..c1f51ba66 100644
--- a/packages/auth/server/lib/session/session-cookies.ts
+++ b/packages/auth/server/lib/session/session-cookies.ts
@@ -1,17 +1,45 @@
-import { formatSecureCookieName, getCookieDomain, useSecureCookies } from '@documenso/lib/constants/auth';
+import {
+ formatHostCookieName,
+ formatSecureCookieName,
+ getCookieDomain,
+ shouldUseSecureCookies,
+} from '@documenso/lib/constants/auth';
import { appLog } from '@documenso/lib/utils/debugger';
import { env } from '@documenso/lib/utils/env';
import type { Context } from 'hono';
import { deleteCookie, getSignedCookie, setSignedCookie } from 'hono/cookie';
+import { z } from 'zod';
-import { AUTH_SESSION_LIFETIME } from '../../config';
+import { AUTH_EMBED_SESSION_LIFETIME, AUTH_SESSION_LIFETIME } from '../../config';
import { extractCookieFromHeaders } from '../utils/cookies';
import { generateSessionToken } from './session';
-export const sessionCookieName = formatSecureCookieName('sessionId');
-export const csrfCookieName = formatSecureCookieName('csrfToken');
+const sessionCookieName = formatSecureCookieName('sessionId');
+const csrfCookieName = formatSecureCookieName('csrfToken');
-const getAuthSecret = () => {
+// Both are `__Host-` prefixed: cannot be set by a subdomain and must not carry a `Domain` attribute.
+const embedSessionCookieName = formatHostCookieName('embedSessionId');
+const embedAuthFlowCookieName = formatHostCookieName('embed_auth_flow');
+
+const embedAuthFlowCookieMaxAge = 60 * 10;
+
+const embedAuthFlowMaxAgeMs = embedAuthFlowCookieMaxAge * 1000;
+
+/**
+ * `iat` lets the server expire the flow independently of the browser honouring
+ * `Max-Age`. `state` doubles as the OAuth `state` and must be echoed on
+ * `/complete`, so a second popup that overwrote this cookie cannot complete
+ * this flow.
+ */
+const ZEmbedAuthFlowCookiePayloadSchema = z.object({
+ nonce: z.string().uuid(),
+ iat: z.number().int().positive(),
+ state: z.string().min(1),
+});
+
+export type EmbedAuthFlowCookiePayload = z.infer<typeof ZEmbedAuthFlowCookiePayloadSchema>;
+
+export const getAuthSecret = () => {
const authSecret = env('NEXTAUTH_SECRET');
if (!authSecret) {
@@ -27,13 +55,24 @@ const getAuthSecret = () => {
export const sessionCookieOptions = {
httpOnly: true,
path: '/',
- sameSite: useSecureCookies ? 'none' : 'lax',
- secure: useSecureCookies,
+ sameSite: 'lax', // Embeds use the partitioned embed cookie instead of relaxing this to 'none'.
+ secure: shouldUseSecureCookies(),
domain: getCookieDomain(),
} as const;
+// Partitioned (CHIPS) so it can be set and read from inside a cross-site iframe.
+export const embedSessionCookieOptions = {
+ httpOnly: true,
+ path: '/',
+ sameSite: shouldUseSecureCookies() ? 'none' : 'lax',
+ secure: shouldUseSecureCookies(),
+ partitioned: shouldUseSecureCookies(),
+} as const;
+
export const extractSessionCookieFromHeaders = (headers: Headers): string | null => {
- return extractCookieFromHeaders(sessionCookieName, headers);
+ return (
+ extractCookieFromHeaders(sessionCookieName, headers) ?? extractCookieFromHeaders(embedSessionCookieName, headers)
+ );
};
/**
@@ -45,7 +84,13 @@ export const extractSessionCookieFromHeaders = (headers: Headers): string | null
export const getSessionCookie = async (c: Context): Promise<string | null> => {
const sessionId = await getSignedCookie(c, getAuthSecret(), sessionCookieName);
- return sessionId || null;
+ if (sessionId) {
+ return sessionId;
+ }
+
+ const embedSessionId = await getSignedCookie(c, getAuthSecret(), embedSessionCookieName);
+
+ return embedSessionId || null;
};
/**
@@ -75,6 +120,87 @@ export const deleteSessionCookie = (c: Context) => {
deleteCookie(c, sessionCookieName, sessionCookieOptions);
};
+export const setEmbedSessionCookie = async (c: Context, sessionToken: string) => {
+ await setSignedCookie(c, embedSessionCookieName, sessionToken, getAuthSecret(), {
+ ...embedSessionCookieOptions,
+ expires: new Date(Date.now() + AUTH_EMBED_SESSION_LIFETIME),
+ }).catch((err) => {
+ appLog('SetEmbedSessionCookie', `Error setting signed embed cookie: ${err}`);
+
+ throw err;
+ });
+};
+
+export const deleteEmbedSessionCookie = (c: Context) => {
+ deleteCookie(c, embedSessionCookieName, embedSessionCookieOptions);
+};
+
+// `SameSite=Lax` so it survives the top-level OAuth redirect back to the app.
+export const embedAuthFlowCookieOptions = {
+ httpOnly: true,
+ path: '/',
+ sameSite: 'lax',
+ secure: shouldUseSecureCookies(),
+ maxAge: embedAuthFlowCookieMaxAge,
+} as const;
+
+export const getEmbedAuthFlowCookie = async (c: Context): Promise<EmbedAuthFlowCookiePayload | null> => {
+ const rawValue = await getSignedCookie(c, getAuthSecret(), embedAuthFlowCookieName);
+
+ if (!rawValue) {
+ return null;
+ }
+
+ let parsedJson: unknown;
+
+ try {
+ parsedJson = JSON.parse(rawValue);
+ } catch {
+ return null;
+ }
+
+ const parsed = ZEmbedAuthFlowCookiePayloadSchema.safeParse(parsedJson);
+
+ if (!parsed.success) {
+ return null;
+ }
+
+ const age = Date.now() - parsed.data.iat;
+
+ if (age < 0 || age > embedAuthFlowMaxAgeMs) {
+ return null;
+ }
+
+ return parsed.data;
+};
+
+export const setEmbedAuthFlowCookie = async (c: Context, nonce: string, state: string) => {
+ const payload: EmbedAuthFlowCookiePayload = {
+ nonce,
+ iat: Date.now(),
+ state,
+ };
+
+ await setSignedCookie(
+ c,
+ embedAuthFlowCookieName,
+ JSON.stringify(payload),
+ getAuthSecret(),
+ embedAuthFlowCookieOptions,
+ ).catch((err) => {
+ appLog('SetEmbedAuthFlowCookie', `Error setting signed embed auth flow cookie: ${err}`);
+
+ throw err;
+ });
+};
+
+export const clearEmbedAuthFlowCookie = (c: Context) => {
+ deleteCookie(c, embedAuthFlowCookieName, {
+ ...embedAuthFlowCookieOptions,
+ maxAge: undefined,
+ });
+};
+
export const getCsrfCookie = async (c: Context) => {
const csrfToken = await getSignedCookie(c, getAuthSecret(), csrfCookieName);
diff --git a/packages/auth/server/lib/session/session.ts b/packages/auth/server/lib/session/session.ts
index 75d3830d7..497cf61a3 100644
--- a/packages/auth/server/lib/session/session.ts
+++ b/packages/auth/server/lib/session/session.ts
@@ -3,9 +3,9 @@ import type { RequestMetadata } from '@documenso/lib/universal/extract-request-m
import { prisma } from '@documenso/prisma';
import { sha256 } from '@oslojs/crypto/sha2';
import { encodeBase32LowerCaseNoPadding, encodeHexLowerCase } from '@oslojs/encoding';
-import { type Session, type User, UserSecurityAuditLogType } from '@prisma/client';
+import { type Prisma, type Session, type User, UserSecurityAuditLogType } from '@prisma/client';
-import { AUTH_SESSION_LIFETIME } from '../../config';
+import { AUTH_EMBED_SESSION_LIFETIME, AUTH_SESSION_LIFETIME } from '../../config';
/**
* The user object to pass around the app.
@@ -35,7 +35,17 @@ export const generateSessionToken = (): string => {
return token;
};
-export const createSession = async (token: string, userId: number, metadata: RequestMetadata): Promise<Session> => {
+export type CreateSessionOptions = {
+ isEmbed?: boolean;
+ tx?: Prisma.TransactionClient;
+};
+
+export const createSession = async (
+ token: string,
+ userId: number,
+ metadata: RequestMetadata,
+ { isEmbed = false, tx = prisma }: CreateSessionOptions = {},
+): Promise<Session> => {
const hashedSessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(token)));
const session: Session = {
@@ -44,16 +54,17 @@ export const createSession = async (token: string, userId: number, metadata: Req
userId,
updatedAt: new Date(),
createdAt: new Date(),
- expiresAt: new Date(Date.now() + AUTH_SESSION_LIFETIME),
+ expiresAt: new Date(Date.now() + (isEmbed ? AUTH_EMBED_SESSION_LIFETIME : AUTH_SESSION_LIFETIME)),
ipAddress: metadata.ipAddress ?? null,
userAgent: metadata.userAgent ?? null,
+ isEmbed,
};
- await prisma.session.create({
+ await tx.session.create({
data: session,
});
- await prisma.userSecurityAuditLog.create({
+ await tx.userSecurityAuditLog.create({
data: {
userId,
ipAddress: metadata.ipAddress,
@@ -103,8 +114,9 @@ export const validateSessionToken = async (token: string): Promise<SessionValida
return { session: null, user: null, isAuthenticated: false };
}
- if (Date.now() >= session.expiresAt.getTime() - 1000 * 60 * 60 * 24 * 15) {
- session.expiresAt = new Date(Date.now() + 1000 * 60 * 60 * 24 * 30);
+ // Embed sessions are never extended; the user starts a new popup flow instead.
+ if (!session.isEmbed && Date.now() >= session.expiresAt.getTime() - 1000 * 60 * 60 * 24 * 15) {
+ session.expiresAt = new Date(Date.now() + AUTH_SESSION_LIFETIME);
await prisma.session.update({
where: {
diff --git a/packages/auth/server/lib/utils/get-session.ts b/packages/auth/server/lib/utils/get-session.ts
index 07049d3ff..e154b4510 100644
--- a/packages/auth/server/lib/utils/get-session.ts
+++ b/packages/auth/server/lib/utils/get-session.ts
@@ -59,6 +59,7 @@ export const getActiveSessions = async (c: Context | Request): Promise<ActiveSes
createdAt: true,
ipAddress: true,
userAgent: true,
+ isEmbed: true,
},
});
};
diff --git a/packages/auth/server/lib/utils/handle-oauth-authorize-url.ts b/packages/auth/server/lib/utils/handle-oauth-authorize-url.ts
index 32d1b13f6..294ef6810 100644
--- a/packages/auth/server/lib/utils/handle-oauth-authorize-url.ts
+++ b/packages/auth/server/lib/utils/handle-oauth-authorize-url.ts
@@ -27,6 +27,9 @@ type HandleOAuthAuthorizeUrlOptions = {
* Optional prompt to pass to the authorization endpoint.
*/
prompt?: 'none' | 'login' | 'consent' | 'select_account';
+
+ /** Generated when omitted. */
+ state?: string;
};
const isOidcPrompt = (value: unknown): value is HandleOAuthAuthorizeUrlOptions['prompt'] => {
@@ -51,7 +54,7 @@ export const handleOAuthAuthorizeUrl = async (options: HandleOAuthAuthorizeUrlOp
const oAuthClient = new OAuth2Client(clientOptions.clientId, clientOptions.clientSecret, clientOptions.redirectUrl);
const scopes = clientOptions.scope;
- const state = generateState();
+ const state = options.state ?? generateState();
const codeVerifier = generateCodeVerifier();
diff --git a/packages/auth/server/lib/utils/handle-oauth-callback-url.ts b/packages/auth/server/lib/utils/handle-oauth-callback-url.ts
index 5bae1f940..315b7c47c 100644
--- a/packages/auth/server/lib/utils/handle-oauth-callback-url.ts
+++ b/packages/auth/server/lib/utils/handle-oauth-callback-url.ts
@@ -4,12 +4,14 @@ import {
isEmailDomainAllowedForSignup,
isSignupEnabledForProvider,
} from '@documenso/lib/constants/auth';
+import { formatEmbedAuthCompletePageUrl } from '@documenso/lib/constants/embed-auth';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { getEmailBlocklistDomains } from '@documenso/lib/server-only/site-settings/get-email-blocklist-domains';
import { onCreateUserHook } from '@documenso/lib/server-only/user/create-user';
import { deletedServiceAccountEmail } from '@documenso/lib/server-only/user/service-accounts/deleted-account';
import { legacyServiceAccountEmail } from '@documenso/lib/server-only/user/service-accounts/legacy-service-account';
import { isValidReturnTo, normalizeReturnTo } from '@documenso/lib/utils/is-valid-return-to';
+import { logger } from '@documenso/lib/utils/logger';
import { prisma } from '@documenso/prisma';
import { UserSecurityAuditLogType } from '@prisma/client';
import { decodeIdToken, OAuth2Client } from 'arctic';
@@ -18,6 +20,7 @@ import { deleteCookie } from 'hono/cookie';
import type { OAuthClientOptions } from '../../config';
import { AuthenticationErrorCode } from '../errors/error-codes';
+import { failEmbedAuthFlow } from '../handoff/record-embed-auth-failure';
import { onAuthorize } from './authorizer';
import { getOpenIdConfiguration } from './open-id';
@@ -26,7 +29,44 @@ type HandleOAuthCallbackUrlOptions = {
clientOptions: OAuthClientOptions;
};
+const redirectToSignInError = async (c: Context, errorCode: string) => {
+ const isEmbedFlow = await failEmbedAuthFlow(c, c.req.query('state'), errorCode);
+
+ if (isEmbedFlow) {
+ return c.redirect(formatEmbedAuthCompletePageUrl('error'), 302);
+ }
+
+ const errorUrl = new URL(formatPath('/signin'), NEXT_PUBLIC_WEBAPP_URL());
+
+ errorUrl.searchParams.set('error', errorCode);
+
+ return c.redirect(errorUrl.toString(), 302);
+};
+
export const handleOAuthCallbackUrl = async (options: HandleOAuthCallbackUrlOptions) => {
+ const { c } = options;
+
+ try {
+ return await handleOAuthCallback(options);
+ } catch (err) {
+ const reason = err instanceof AppError ? err.code : AppErrorCode.UNKNOWN_ERROR;
+
+ const isEmbedFlow = await failEmbedAuthFlow(c, c.req.query('state'), reason);
+
+ if (!isEmbedFlow) {
+ throw err;
+ }
+
+ logger.error({
+ event: 'auth.embed.oauth_callback_failed',
+ error: err,
+ });
+
+ return c.redirect(formatEmbedAuthCompletePageUrl('error'), 302);
+ }
+};
+
+const handleOAuthCallback = async (options: HandleOAuthCallbackUrlOptions) => {
const { c, clientOptions } = options;
const requestMeta = c.get('requestMetadata');
@@ -37,6 +77,12 @@ export const handleOAuthCallbackUrl = async (options: HandleOAuthCallbackUrlOpti
});
if (email.toLowerCase() === legacyServiceAccountEmail() || email.toLowerCase() === deletedServiceAccountEmail()) {
+ const isEmbedFlow = await failEmbedAuthFlow(c, c.req.query('state'), 'service_account');
+
+ if (isEmbedFlow) {
+ return c.redirect(formatEmbedAuthCompletePageUrl('error'), 302);
+ }
+
return c.text('FORBIDDEN', 403);
}
@@ -121,31 +167,19 @@ export const handleOAuthCallbackUrl = async (options: HandleOAuthCallbackUrlOpti
// Check if signups are disabled for this provider.
if (!isSignupEnabledForProvider(clientOptions.id as 'google' | 'microsoft' | 'oidc')) {
- const errorUrl = new URL(formatPath('/signin'), NEXT_PUBLIC_WEBAPP_URL());
-
- errorUrl.searchParams.set('error', AuthenticationErrorCode.SignupDisabled);
-
- return c.redirect(errorUrl.toString(), 302);
+ return redirectToSignInError(c, AuthenticationErrorCode.SignupDisabled);
}
// Check domain restriction for new SSO users.
if (!isEmailDomainAllowedForSignup(email)) {
- const errorUrl = new URL(formatPath('/signin'), NEXT_PUBLIC_WEBAPP_URL());
-
- errorUrl.searchParams.set('error', AuthenticationErrorCode.SignupDisabled);
-
- return c.redirect(errorUrl.toString(), 302);
+ return redirectToSignInError(c, AuthenticationErrorCode.SignupDisabled);
}
// Reject disposable / throwaway email providers for new SSO users.
const additionalBlockedDomains = await getEmailBlocklistDomains();
if (isDisposableEmail(email, additionalBlockedDomains)) {
- const errorUrl = new URL(formatPath('/signin'), NEXT_PUBLIC_WEBAPP_URL());
-
- errorUrl.searchParams.set('error', AuthenticationErrorCode.SignupDisposableEmail);
-
- return c.redirect(errorUrl.toString(), 302);
+ return redirectToSignInError(c, AuthenticationErrorCode.SignupDisposableEmail);
}
// Handle new user.
diff --git a/packages/auth/server/lib/utils/is-equal-secret.ts b/packages/auth/server/lib/utils/is-equal-secret.ts
new file mode 100644
index 000000000..16a858ebd
--- /dev/null
+++ b/packages/auth/server/lib/utils/is-equal-secret.ts
@@ -0,0 +1,9 @@
+import { sha256 } from '@oslojs/crypto/sha2';
+import { constantTimeEqual } from '@oslojs/crypto/subtle';
+
+// Both sides are hashed first so lengths always match for `timingSafeEqual`.
+export const isEqualSecret = (a: string, b: string): boolean => {
+ const encoder = new TextEncoder();
+
+ return constantTimeEqual(sha256(encoder.encode(a)), sha256(encoder.encode(b)));
+};
diff --git a/packages/auth/server/routes/embed.ts b/packages/auth/server/routes/embed.ts
new file mode 100644
index 000000000..34df4f2ec
--- /dev/null
+++ b/packages/auth/server/routes/embed.ts
@@ -0,0 +1,267 @@
+import { setCscBlockingErrorCookie } from '@documenso/ee/server-only/signing/csc/cookies/blocking-error-cookie';
+import { setCscSadSessionCookie } from '@documenso/ee/server-only/signing/csc/cookies/sad-session-cookie';
+import { setCscServiceSessionCookie } from '@documenso/ee/server-only/signing/csc/cookies/service-session-cookie';
+import { formatPath, IS_INSTANCE_CSC_MODE } from '@documenso/lib/constants/app';
+import {
+ IS_GOOGLE_SSO_ENABLED,
+ IS_MICROSOFT_SSO_ENABLED,
+ IS_OIDC_SSO_ENABLED,
+ isSigninDisabledGlobally,
+ isSigninEnabledForProvider,
+} from '@documenso/lib/constants/auth';
+import { AUTH_HANDOFF_TYPE } from '@documenso/lib/constants/auth-handoff';
+import {
+ formatEmbedAuthCompleteApiUrl,
+ formatEmbedAuthCompletePageUrl,
+ ZEmbedPopupAuthCscOptionsSchema,
+ ZEmbedPopupAuthProviderSchema,
+} from '@documenso/lib/constants/embed-auth';
+import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
+import { createRateLimitMiddleware } from '@documenso/lib/server-only/rate-limit/rate-limit-middleware';
+import { embedAuthRedeemRateLimit, embedAuthStartRateLimit } from '@documenso/lib/server-only/rate-limit/rate-limits';
+import { logger } from '@documenso/lib/utils/logger';
+import { sValidator } from '@hono/standard-validator';
+import { generateState } from 'arctic';
+import type { Context } from 'hono';
+import { Hono } from 'hono';
+import { match } from 'ts-pattern';
+import { z } from 'zod';
+
+import { GoogleAuthOptions, MicrosoftAuthOptions, OidcAuthOptions } from '../config';
+import { createAuthHandoff } from '../lib/handoff/create-auth-handoff';
+import { ZAuthHandoffNonceSchema } from '../lib/handoff/hash-auth-handoff-nonce';
+import { recordEmbedAuthFailure } from '../lib/handoff/record-embed-auth-failure';
+import { redeemAuthHandoff } from '../lib/handoff/redeem-auth-handoff';
+import type { EmbedAuthFlowCookiePayload } from '../lib/session/session-cookies';
+import {
+ clearEmbedAuthFlowCookie,
+ getEmbedAuthFlowCookie,
+ setEmbedAuthFlowCookie,
+ setEmbedSessionCookie,
+} from '../lib/session/session-cookies';
+import { getOptionalSession } from '../lib/utils/get-session';
+import { handleOAuthAuthorizeUrl } from '../lib/utils/handle-oauth-authorize-url';
+import { isEqualSecret } from '../lib/utils/is-equal-secret';
+import type { HonoAuthContext } from '../types/context';
+
+const CSC_OAUTH_AUTHORIZE_PATH = '/api/csc/oauth/authorize';
+
+const ZStartEmbedAuthSchema = z.object({
+ nonce: ZAuthHandoffNonceSchema,
+ provider: ZEmbedPopupAuthProviderSchema,
+ csc: ZEmbedPopupAuthCscOptionsSchema.optional(),
+});
+
+const ZRedeemAuthHandoffSchema = z.object({
+ nonce: ZAuthHandoffNonceSchema,
+});
+
+const recordEmbedSessionHandoff = async (
+ c: Context<HonoAuthContext>,
+ flow: EmbedAuthFlowCookiePayload,
+): Promise<boolean> => {
+ const { session, user } = await getOptionalSession(c);
+
+ if (!session || !user) {
+ return false;
+ }
+
+ return await createAuthHandoff({
+ nonce: flow.nonce,
+ type: AUTH_HANDOFF_TYPE.EMBED_SESSION,
+ payload: { userId: user.id, sessionId: session.id },
+ })
+ .then(() => true)
+ .catch((err) => {
+ logger.error({
+ event: 'auth.embed.handoff_create_failed',
+ error: err,
+ });
+
+ return false;
+ });
+};
+
+// Throw instead of letting `sValidator` reply with the raw Zod result, so
+// validation failures hit `onError` and share the `AppError` response shape.
+const rejectInvalidBody: Parameters<typeof sValidator>[2] = (result) => {
+ if (!result.success) {
+ throw new AppError(AppErrorCode.INVALID_REQUEST, {
+ message: 'Invalid request body',
+ statusCode: 400,
+ });
+ }
+};
+
+export const embedRoute = new Hono<HonoAuthContext>()
+ /**
+ * Binds the popup's nonce to this browser via a signed cookie plus a per-flow
+ * `state`. `/complete` must present the same `state`, so a second popup that
+ * overwrites the cookie cannot complete (or receive the identity of) this
+ * flow. The nonce itself never appears in a URL.
+ */
+ .post(
+ '/start',
+ createRateLimitMiddleware(embedAuthStartRateLimit),
+ sValidator('json', ZStartEmbedAuthSchema, rejectInvalidBody),
+ async (c) => {
+ const { nonce, provider, csc } = c.req.valid('json');
+
+ const state = generateState();
+
+ if (provider === 'csc') {
+ if (!IS_INSTANCE_CSC_MODE()) {
+ throw new AppError(AppErrorCode.NOT_SETUP, {
+ message: 'Provider is not enabled',
+ statusCode: 400,
+ });
+ }
+
+ if (!csc) {
+ throw new AppError(AppErrorCode.INVALID_REQUEST, {
+ message: 'Missing CSC options',
+ statusCode: 400,
+ });
+ }
+
+ const searchParams = new URLSearchParams(
+ match(csc)
+ .with({ scope: 'service' }, ({ token }) => ({ scope: 'service', token }))
+ .with({ scope: 'credential' }, ({ sessionId }) => ({ scope: 'credential', session: sessionId }))
+ .exhaustive(),
+ );
+
+ searchParams.set('embed', '1');
+
+ await setEmbedAuthFlowCookie(c, nonce, state);
+
+ return c.json({ redirectUrl: `${formatPath(CSC_OAUTH_AUTHORIZE_PATH)}?${searchParams.toString()}` });
+ }
+
+ if (provider === 'account') {
+ // Passkeys have no per-provider flag; email/password is gated by its own routes.
+ if (isSigninDisabledGlobally()) {
+ throw new AppError(AppErrorCode.NOT_SETUP, {
+ message: 'Provider is not enabled',
+ statusCode: 400,
+ });
+ }
+
+ await setEmbedAuthFlowCookie(c, nonce, state);
+
+ return c.json({ redirectUrl: null, returnTo: formatEmbedAuthCompleteApiUrl(state) });
+ }
+
+ const clientOptions = match(provider)
+ .with('google', () =>
+ IS_GOOGLE_SSO_ENABLED && isSigninEnabledForProvider('google') ? GoogleAuthOptions : null,
+ )
+ .with('microsoft', () =>
+ IS_MICROSOFT_SSO_ENABLED && isSigninEnabledForProvider('microsoft') ? MicrosoftAuthOptions : null,
+ )
+ .with('oidc', () => (IS_OIDC_SSO_ENABLED && isSigninEnabledForProvider('oidc') ? OidcAuthOptions : null))
+ .exhaustive();
+
+ if (!clientOptions) {
+ throw new AppError(AppErrorCode.NOT_SETUP, {
+ message: 'Provider is not enabled',
+ statusCode: 400,
+ });
+ }
+
+ await setEmbedAuthFlowCookie(c, nonce, state);
+
+ return await handleOAuthAuthorizeUrl({
+ c,
+ clientOptions,
+ redirectPath: formatEmbedAuthCompleteApiUrl(state),
+ state,
+ });
+ },
+ )
+ /**
+ * On a missing flow or `state` mismatch nothing is recorded: there is no nonce
+ * this request is entitled to act on. `csc` never lands here; its callback
+ * records the handoff itself.
+ */
+ .get('/complete', async (c) => {
+ const flow = await getEmbedAuthFlowCookie(c);
+
+ clearEmbedAuthFlowCookie(c);
+
+ const state = c.req.query('state');
+
+ if (!flow || !state || !isEqualSecret(flow.state, state)) {
+ return c.redirect(formatEmbedAuthCompletePageUrl('error'), 302);
+ }
+
+ const isHandoffCreated = await recordEmbedSessionHandoff(c, flow);
+
+ if (!isHandoffCreated) {
+ await recordEmbedAuthFailure(flow.nonce, 'session_handoff_not_recorded');
+
+ return c.redirect(formatEmbedAuthCompletePageUrl('error'), 302);
+ }
+
+ return c.redirect(formatEmbedAuthCompletePageUrl('ok'), 302);
+ })
+ /**
+ * Called from the cross-site iframe; sets the partitioned cookie matching the
+ * handoff type. The ee CSC cookie setters are imported here, not in
+ * `lib/handoff/*`, to keep that module free of ee dependencies.
+ */
+ .post(
+ '/redeem',
+ createRateLimitMiddleware(embedAuthRedeemRateLimit),
+ sValidator('json', ZRedeemAuthHandoffSchema, rejectInvalidBody),
+ async (c) => {
+ const requestMetadata = c.get('requestMetadata');
+
+ const { nonce } = c.req.valid('json');
+
+ const handoff = await redeemAuthHandoff({
+ nonce,
+ ipAddress: requestMetadata.ipAddress,
+ userAgent: requestMetadata.userAgent,
+ });
+
+ if (!handoff) {
+ return c.json({ status: 'pending' }, 202);
+ }
+
+ if (handoff.type === AUTH_HANDOFF_TYPE.EMBED_FAILED) {
+ return c.json({ status: 'failed' } as const, 200);
+ }
+
+ await match(handoff)
+ .with({ type: AUTH_HANDOFF_TYPE.EMBED_SESSION }, async ({ payload }) =>
+ setEmbedSessionCookie(c, payload.sessionToken),
+ )
+ .with({ type: AUTH_HANDOFF_TYPE.EMBED_CSC_SERVICE }, async ({ payload }) =>
+ setCscServiceSessionCookie({
+ c,
+ recipientToken: payload.recipientToken,
+ ttlSeconds: payload.ttlSeconds,
+ }),
+ )
+ .with({ type: AUTH_HANDOFF_TYPE.EMBED_CSC_SAD }, async ({ payload }) =>
+ setCscSadSessionCookie({
+ c,
+ sessionId: payload.sessionId,
+ expiresAt: payload.expiresAt,
+ }),
+ )
+ .with({ type: AUTH_HANDOFF_TYPE.EMBED_CSC_BLOCKING_ERROR }, async ({ payload }) =>
+ setCscBlockingErrorCookie({
+ c,
+ payload: {
+ code: payload.code,
+ recipientToken: payload.recipientToken,
+ },
+ }),
+ )
+ .exhaustive();
+
+ return c.json({ status: 'ok' } as const, 200);
+ },
+ );
diff --git a/packages/auth/server/routes/sign-out.ts b/packages/auth/server/routes/sign-out.ts
index 9a8bf40bb..81d8607e1 100644
--- a/packages/auth/server/routes/sign-out.ts
+++ b/packages/auth/server/routes/sign-out.ts
@@ -4,7 +4,7 @@ import { Hono } from 'hono';
import { z } from 'zod';
import { invalidateSessions, validateSessionToken } from '../lib/session/session';
-import { deleteSessionCookie, getSessionCookie } from '../lib/session/session-cookies';
+import { deleteEmbedSessionCookie, deleteSessionCookie, getSessionCookie } from '../lib/session/session-cookies';
import type { HonoAuthContext } from '../types/context';
const ZSignoutSessionSchema = z.object({
@@ -25,6 +25,7 @@ export const signOutRoute = new Hono<HonoAuthContext>()
if (!session) {
deleteSessionCookie(c);
+ deleteEmbedSessionCookie(c);
return new Response('No session found', { status: 401 });
}
@@ -36,6 +37,7 @@ export const signOutRoute = new Hono<HonoAuthContext>()
});
deleteSessionCookie(c);
+ deleteEmbedSessionCookie(c);
return c.status(200);
})
@@ -52,6 +54,7 @@ export const signOutRoute = new Hono<HonoAuthContext>()
if (!session) {
deleteSessionCookie(c);
+ deleteEmbedSessionCookie(c);
return new Response('No session found', { status: 401 });
}
@@ -95,6 +98,7 @@ export const signOutRoute = new Hono<HonoAuthContext>()
if (!session) {
deleteSessionCookie(c);
+ deleteEmbedSessionCookie(c);
return new Response('No session found', { status: 401 });
}
@@ -107,6 +111,7 @@ export const signOutRoute = new Hono<HonoAuthContext>()
if (session.id === sessionIdToRevoke) {
deleteSessionCookie(c);
+ deleteEmbedSessionCookie(c);
}
return c.status(200);
diff --git a/packages/ee/server-only/signing/csc/assert-embed-service-session.ts b/packages/ee/server-only/signing/csc/assert-embed-service-session.ts
new file mode 100644
index 000000000..a58483684
--- /dev/null
+++ b/packages/ee/server-only/signing/csc/assert-embed-service-session.ts
@@ -0,0 +1,79 @@
+import { IS_INSTANCE_CSC_MODE } from '@documenso/lib/constants/app';
+import { isTspEnvelope } from '@documenso/lib/types/signature-level';
+
+import { expiredCscBlockingErrorCookieHeader, readCscBlockingErrorFromRequest } from './cookies/blocking-error-cookie';
+import { readCscServiceSessionFromRequest } from './cookies/service-session-cookie';
+
+/**
+ * `error.data.type` the embed layout's ErrorBoundary matches on to render
+ * `EmbedCscAuthenticationRequired`. Kept as a literal on both sides: the
+ * layout is a client module and must not import from `ee/server-only`.
+ */
+const EMBED_CSC_AUTHENTICATION_REQUIRED_ERROR_TYPE = 'embed-csc-authentication-required';
+
+export type AssertEmbedCscServiceSessionOptions = {
+ request: Request;
+ token: string;
+ envelope: { signatureLevel: string };
+ isCompleted: boolean;
+ isRejected: boolean;
+};
+
+/**
+ * Embed counterpart of the CSC branch in the top-level `/sign/{token}` loader.
+ *
+ * The TSP cannot be framed, so instead of redirecting we throw a 401 JSON
+ * `Response` that React Router surfaces as an `ErrorResponse`; the embed
+ * layout's ErrorBoundary renders it as `EmbedCscAuthenticationRequired`, which
+ * runs the OAuth round trip in a popup.
+ *
+ * Completed/rejected envelopes skip the check so they still render after the
+ * service cookie expires.
+ */
+export const assertEmbedCscServiceSession = async ({
+ request,
+ token,
+ envelope,
+ isCompleted,
+ isRejected,
+}: AssertEmbedCscServiceSessionOptions): Promise<void> => {
+ if (!IS_INSTANCE_CSC_MODE() || !isTspEnvelope(envelope)) {
+ return;
+ }
+
+ if (isCompleted || isRejected) {
+ return;
+ }
+
+ const blockingError = await readCscBlockingErrorFromRequest(request);
+
+ if (blockingError && blockingError.recipientToken === token) {
+ throw Response.json(
+ {
+ type: EMBED_CSC_AUTHENTICATION_REQUIRED_ERROR_TYPE,
+ token,
+ blockedCode: blockingError.code,
+ },
+ {
+ status: 401,
+ headers: {
+ 'Set-Cookie': expiredCscBlockingErrorCookieHeader(),
+ },
+ },
+ );
+ }
+
+ const serviceSessionToken = await readCscServiceSessionFromRequest(request);
+
+ if (serviceSessionToken !== token) {
+ throw Response.json(
+ {
+ type: EMBED_CSC_AUTHENTICATION_REQUIRED_ERROR_TYPE,
+ token,
+ },
+ {
+ status: 401,
+ },
+ );
+ }
+};
diff --git a/packages/ee/server-only/signing/csc/cookies/blocking-error-cookie.ts b/packages/ee/server-only/signing/csc/cookies/blocking-error-cookie.ts
index 7b44382d1..980e6cc7a 100644
--- a/packages/ee/server-only/signing/csc/cookies/blocking-error-cookie.ts
+++ b/packages/ee/server-only/signing/csc/cookies/blocking-error-cookie.ts
@@ -1,6 +1,5 @@
-import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import type { Context } from 'hono';
-import { deleteCookie, getSignedCookie, setSignedCookie } from 'hono/cookie';
+import { getSignedCookie, setSignedCookie } from 'hono/cookie';
import { parseSigned, serialize } from 'hono/utils/cookie';
import { z } from 'zod';
@@ -39,47 +38,38 @@ export const setCscBlockingErrorCookie = async (options: SetCscBlockingErrorCook
};
/**
- * Read + validate the blocking-error cookie. Returns `null` when absent or
- * signature-invalid; throws `INVALID_REQUEST` when signed-but-malformed
- * (tamper-shaped, mirroring `oauth-flow-cookie.ts`).
+ * The cookie is advisory (it only decides which error banner to show), so a
+ * malformed payload is treated the same as a missing one rather than failing
+ * the request.
*/
-export const getCscBlockingErrorCookie = async (c: Context): Promise<TCscBlockingErrorPayload | null> => {
- const raw = await getSignedCookie(c, getCscCookieSecret(), CSC_BLOCKING_ERROR_COOKIE_NAME);
-
- if (!raw) {
+const parseCscBlockingErrorPayload = (raw: string | undefined | false): TCscBlockingErrorPayload | null => {
+ if (typeof raw !== 'string') {
return null;
}
- let parsedJson: unknown;
-
try {
- parsedJson = JSON.parse(raw);
- } catch {
- throw new AppError(AppErrorCode.INVALID_REQUEST, {
- message: 'CSC blocking error cookie payload is not valid JSON.',
- });
- }
-
- const result = ZCscBlockingErrorPayloadSchema.safeParse(parsedJson);
+ const result = ZCscBlockingErrorPayloadSchema.safeParse(JSON.parse(raw));
- if (!result.success) {
- throw new AppError(AppErrorCode.INVALID_REQUEST, {
- message: 'CSC blocking error cookie payload failed schema validation.',
- });
+ return result.success ? result.data : null;
+ } catch {
+ return null;
}
-
- return result.data;
};
-export const clearCscBlockingErrorCookie = (c: Context): void => {
- deleteCookie(c, CSC_BLOCKING_ERROR_COOKIE_NAME, cscCookieBaseOptions);
+/**
+ * Hono reader. Returns `null` when the cookie is absent, signature-invalid or
+ * payload-malformed.
+ */
+export const getCscBlockingErrorCookie = async (c: Context): Promise<TCscBlockingErrorPayload | null> => {
+ const raw = await getSignedCookie(c, getCscCookieSecret(), CSC_BLOCKING_ERROR_COOKIE_NAME);
+
+ return parseCscBlockingErrorPayload(raw);
};
/**
* Remix-compatible reader: parses + HMAC-verifies the blocking-error cookie
- * from a raw `Cookie` header on a standard `Request`. Returns `null` when
- * absent, signature-invalid, or payload-malformed (no throw — the loader
- * only uses the cookie advisorily, so a bad cookie shouldn't break the page).
+ * from the raw `Cookie` header on a standard `Request`. Same `null` semantics
+ * as `getCscBlockingErrorCookie`.
*/
export const readCscBlockingErrorFromRequest = async (request: Request): Promise<TCscBlockingErrorPayload | null> => {
const cookieHeader = request.headers.get('cookie');
@@ -90,29 +80,15 @@ export const readCscBlockingErrorFromRequest = async (request: Request): Promise
const parsed = await parseSigned(cookieHeader, getCscCookieSecret(), CSC_BLOCKING_ERROR_COOKIE_NAME);
- const value = parsed[CSC_BLOCKING_ERROR_COOKIE_NAME];
-
- if (typeof value !== 'string') {
- return null;
- }
-
- try {
- const json = JSON.parse(value);
-
- const result = ZCscBlockingErrorPayloadSchema.safeParse(json);
-
- return result.success ? result.data : null;
- } catch {
- return null;
- }
+ return parseCscBlockingErrorPayload(parsed[CSC_BLOCKING_ERROR_COOKIE_NAME]);
};
/**
- * Serialised `Set-Cookie` header value that expires the cookie immediately.
- * Use in a Remix loader's response headers to clear the cookie after the
- * loader reads it once.
+ * `Set-Cookie` header value that expires the cookie immediately. Remix loaders
+ * attach it to the response after reading the cookie once, since they have no
+ * Hono context to call `deleteCookie` on.
*/
-export const buildClearCscBlockingErrorCookieHeader = (): string => {
+export const expiredCscBlockingErrorCookieHeader = (): string => {
return serialize(CSC_BLOCKING_ERROR_COOKIE_NAME, '', {
...cscCookieBaseOptions,
maxAge: 0,
diff --git a/packages/ee/server-only/signing/csc/cookies/oauth-flow-cookie.ts b/packages/ee/server-only/signing/csc/cookies/oauth-flow-cookie.ts
index 37eea9323..3e0be2198 100644
--- a/packages/ee/server-only/signing/csc/cookies/oauth-flow-cookie.ts
+++ b/packages/ee/server-only/signing/csc/cookies/oauth-flow-cookie.ts
@@ -3,7 +3,7 @@ import type { Context } from 'hono';
import { deleteCookie, getSignedCookie, setSignedCookie } from 'hono/cookie';
import { z } from 'zod';
-import { CSC_OAUTH_FLOW_COOKIE_NAME, cscCookieBaseOptions, getCscCookieSecret } from './shared';
+import { CSC_OAUTH_FLOW_COOKIE_NAME, cscOAuthFlowCookieOptions, getCscCookieSecret } from './shared';
/**
* `csc_oauth_flow` — single-round-trip carrier across `/api/csc/oauth/authorize`
@@ -28,6 +28,8 @@ export const ZCscOAuthFlowPayloadSchema = z.object({
recipientToken: z.string().min(1),
/** CSC session id — present only on `credential`-scope flows (set at prep). */
sessionId: z.string().min(1).optional(),
+ /** `sha256(nonce)` of the embed flow cookie; marks a round-trip started from the embed popup. */
+ embedNonceHash: z.string().min(1).optional(),
});
export type TCscOAuthFlowPayload = z.infer<typeof ZCscOAuthFlowPayloadSchema>;
@@ -41,7 +43,7 @@ export const setCscOAuthFlowCookie = async (options: SetCscOAuthFlowCookieOption
const { c, payload } = options;
await setSignedCookie(c, CSC_OAUTH_FLOW_COOKIE_NAME, JSON.stringify(payload), getCscCookieSecret(), {
- ...cscCookieBaseOptions,
+ ...cscOAuthFlowCookieOptions,
maxAge: CSC_OAUTH_FLOW_MAX_AGE_SECONDS,
});
};
@@ -81,5 +83,5 @@ export const getCscOAuthFlowCookie = async (c: Context): Promise<TCscOAuthFlowPa
};
export const clearCscOAuthFlowCookie = (c: Context): void => {
- deleteCookie(c, CSC_OAUTH_FLOW_COOKIE_NAME, cscCookieBaseOptions);
+ deleteCookie(c, CSC_OAUTH_FLOW_COOKIE_NAME, cscOAuthFlowCookieOptions);
};
diff --git a/packages/ee/server-only/signing/csc/cookies/shared.ts b/packages/ee/server-only/signing/csc/cookies/shared.ts
index 3280c0c2a..d6d956068 100644
--- a/packages/ee/server-only/signing/csc/cookies/shared.ts
+++ b/packages/ee/server-only/signing/csc/cookies/shared.ts
@@ -1,22 +1,21 @@
-import { formatSecureCookieName, getCookieDomain, useSecureCookies } from '@documenso/lib/constants/auth';
+import {
+ embedAuthFlowCookieOptions,
+ embedSessionCookieOptions,
+} from '@documenso/auth/server/lib/session/session-cookies';
+import { formatHostCookieName } from '@documenso/lib/constants/auth';
import { requireEnv } from '@documenso/lib/utils/env';
/**
* Shared HMAC secret + base attribute set for the CSC cookies.
*
* `NEXTAUTH_SECRET` is reused so signed-cookie verification stays uniform
- * across the auth + CSC surfaces. The `sameSite` conditional matches
- * `sessionCookieOptions` in `@documenso/auth` so a future embedding flow
- * (CSC inside an `<iframe>` on a partner host) works without a separate
- * cookie-attribute regime.
+ * across the auth + CSC surfaces.
*/
/** HMAC secret for hono `setSignedCookie` / `getSignedCookie`. */
export const getCscCookieSecret = (): string => requireEnv('NEXTAUTH_SECRET');
/**
- * CSC cookie names; prefixed with `__Secure-` in production over HTTPS.
- *
* Naming maps 1:1 to the CSC OAuth scope each cookie attests:
* - `csc_service_session` — service-scope grant (long-lived per-browser SCA
* attestation; lifetime = TSP `expires_in`).
@@ -28,19 +27,21 @@ export const getCscCookieSecret = (): string => requireEnv('NEXTAUTH_SECRET');
* service-scope error (e.g. empty credential list, refused algorithm) to
* the next `/sign/{token}` loader, read-once.
*/
-export const CSC_SERVICE_SESSION_COOKIE_NAME = formatSecureCookieName('csc_service_session');
-export const CSC_SAD_SESSION_COOKIE_NAME = formatSecureCookieName('csc_sad_session');
-export const CSC_OAUTH_FLOW_COOKIE_NAME = formatSecureCookieName('csc_oauth_flow');
-export const CSC_BLOCKING_ERROR_COOKIE_NAME = formatSecureCookieName('csc_blocking_error');
+export const CSC_SERVICE_SESSION_COOKIE_NAME = formatHostCookieName('csc_service_session');
+export const CSC_SAD_SESSION_COOKIE_NAME = formatHostCookieName('csc_sad_session');
+export const CSC_OAUTH_FLOW_COOKIE_NAME = formatHostCookieName('csc_oauth_flow');
+export const CSC_BLOCKING_ERROR_COOKIE_NAME = formatHostCookieName('csc_blocking_error');
/**
- * Base options spread into every CSC cookie. Callers add per-cookie expiry
- * (`maxAge` or `expires`) on top.
+ * Partitioned so the CSC cookies can be read from inside a cross-site embed
+ * iframe. Partitioning is harmless top-level (the key is our own site) and
+ * ignored by browsers that predate it. Callers add their own expiry.
*/
-export const cscCookieBaseOptions = {
- httpOnly: true,
- path: '/',
- sameSite: useSecureCookies ? 'none' : 'lax',
- secure: useSecureCookies,
- domain: getCookieDomain(),
+export const cscCookieBaseOptions = embedSessionCookieOptions;
+
+// The TSP redirect back is always top-level, so `SameSite=Lax` suffices here.
+// `maxAge` is owned by `oauth-flow-cookie.ts`.
+export const cscOAuthFlowCookieOptions = {
+ ...embedAuthFlowCookieOptions,
+ maxAge: undefined,
} as const;
diff --git a/packages/ee/server-only/signing/csc/hono/index.ts b/packages/ee/server-only/signing/csc/hono/index.ts
index 49939e0eb..8790902b1 100644
--- a/packages/ee/server-only/signing/csc/hono/index.ts
+++ b/packages/ee/server-only/signing/csc/hono/index.ts
@@ -6,18 +6,21 @@ import type { ContentfulStatusCode } from 'hono/utils/http-status';
import type { HonoCscEnv } from './context';
import { cscOAuthAuthorizeRoute } from './oauth-authorize';
import { cscOAuthCallbackRoute } from './oauth-callback';
+import { cscSessionStatusRoute } from './session-status';
/**
* `@documenso/ee` CSC subapp. Mount under `/api/csc` in the remix host (see
* `apps/remix/server/router.ts`). All CSC endpoints — OAuth authorize +
- * callback — are composed here so the host only has to wire one route.
+ * callback, plus the embed-facing session status probe — are composed here so
+ * the host only has to wire one route.
*
* Routes throw `AppError` freely; the `.onError` handler below normalises
* them into REST responses (mirrors `@documenso/auth/server`'s pattern).
*/
export const csc = new Hono<HonoCscEnv>()
.route('/oauth/authorize', cscOAuthAuthorizeRoute)
- .route('/oauth/callback', cscOAuthCallbackRoute);
+ .route('/oauth/callback', cscOAuthCallbackRoute)
+ .route('/session-status', cscSessionStatusRoute);
csc.onError((err, c) => {
const logger = c.get('logger');
diff --git a/packages/ee/server-only/signing/csc/hono/oauth-authorize.ts b/packages/ee/server-only/signing/csc/hono/oauth-authorize.ts
index a83791864..3c74b25e7 100644
--- a/packages/ee/server-only/signing/csc/hono/oauth-authorize.ts
+++ b/packages/ee/server-only/signing/csc/hono/oauth-authorize.ts
@@ -1,7 +1,12 @@
+import { hashAuthHandoffNonce } from '@documenso/auth/server/lib/handoff/hash-auth-handoff-nonce';
+import { recordEmbedAuthFailure } from '@documenso/auth/server/lib/handoff/record-embed-auth-failure';
+import { getEmbedAuthFlowCookie } from '@documenso/auth/server/lib/session/session-cookies';
+import { formatEmbedAuthCompletePageUrl } from '@documenso/lib/constants/embed-auth';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { getRecipientByToken } from '@documenso/lib/server-only/recipient/get-recipient-by-token';
import { prisma } from '@documenso/prisma';
import { sValidator } from '@hono/standard-validator';
+import type { Context } from 'hono';
import { Hono } from 'hono';
import { z } from 'zod';
@@ -28,17 +33,25 @@ import type { HonoCscEnv } from './context';
* - `credential`: authorised by an active `CscSession`; binds the issued SAD
* to the per-item hashes captured at prep.
*
- * Errors bubble to the parent app's `.onError` handler (see `./index.ts`).
+ * `?embed=1` marks a round-trip started from the embed auth popup; the callback
+ * then hands the resulting cookie to the iframe instead of redirecting.
+ *
+ * Errors bubble to the parent app's `.onError` handler (see `./index.ts`),
+ * except for embed round-trips, which fail the embed flow instead.
*/
-const ZAuthorizeQuerySchema = z.discriminatedUnion('scope', [
+const ZEmbedFlagSchema = z.literal('1').optional();
+
+const ZAuthorizeQuerySchema = z.union([
z.object({
scope: z.literal('service'),
token: z.string().min(1),
+ embed: ZEmbedFlagSchema,
}),
z.object({
scope: z.literal('credential'),
session: z.string().min(1),
+ embed: ZEmbedFlagSchema,
}),
]);
@@ -50,105 +63,161 @@ export const cscOAuthAuthorizeRoute = new Hono<HonoCscEnv>().get(
const query = c.req.valid('query');
- const transport = await getCscTransport();
+ const isEmbed = query.embed === '1';
+
+ let embedNonce: string | undefined;
- if (query.scope === 'service') {
- const recipient = await getRecipientByToken({ token: query.token }).catch(() => null);
+ if (isEmbed) {
+ const embedFlow = await getEmbedAuthFlowCookie(c);
- if (!recipient) {
- throw new AppError(AppErrorCode.NOT_FOUND, {
- message: 'Recipient not found for the provided token.',
+ if (!embedFlow) {
+ logger.warn({
+ event: 'csc.oauth.authorize.embed.flow_missing',
+ scope: query.scope,
});
+
+ return c.redirect(formatEmbedAuthCompletePageUrl('error'), 302);
}
- logger.info({
- event: 'csc.oauth.authorize.start',
- scope: 'service',
- recipientId: recipient.id,
- });
+ embedNonce = embedFlow.nonce;
+ }
- const state = generateState();
- const codeVerifier = generateCodeVerifier();
+ try {
+ return await startCscAuthorize({ c, query, embedNonce });
+ } catch (err) {
+ if (!embedNonce) {
+ throw err;
+ }
- const authorizeUrl = buildCscServiceScopeAuthorizeUrl({
- client: transport.oauthClient,
- oauthBaseUrl: transport.oauthBaseUrl,
- state,
- codeVerifier,
+ logger.error({
+ event: 'csc.oauth.authorize.embed.failed',
+ scope: query.scope,
+ code: err instanceof AppError ? err.code : AppErrorCode.UNKNOWN_ERROR,
+ error: err,
});
- await setCscOAuthFlowCookie({
- c,
- payload: {
- scope: 'service',
- state,
- codeVerifier,
- recipientToken: query.token,
- },
- });
+ await recordEmbedAuthFailure(embedNonce, 'csc_authorize_failed');
- return c.redirect(authorizeUrl.toString(), 302);
+ return c.redirect(formatEmbedAuthCompletePageUrl('error'), 302);
}
+ },
+);
- const session = await loadCscSession(query.session);
+type StartCscAuthorizeOptions = {
+ c: Context<HonoCscEnv>;
+ query: z.infer<typeof ZAuthorizeQuerySchema>;
+ embedNonce: string | undefined;
+};
- if (!session) {
- throw new AppError(AppErrorCode.NOT_FOUND, {
- message: 'CSC session not found or already consumed.',
- });
- }
+const startCscAuthorize = async ({ c, query, embedNonce }: StartCscAuthorizeOptions) => {
+ const logger = c.get('logger');
- const credential = await loadCscCredential(session.recipientId);
+ const isEmbed = embedNonce !== undefined;
- if (!credential) {
- throw new AppError(AppErrorCode.NOT_FOUND, {
- message: 'CSC credential missing — service-scope OAuth must complete first.',
- });
- }
+ const embedNonceHash = embedNonce !== undefined ? hashAuthHandoffNonce(embedNonce) : undefined;
- const recipient = await prisma.recipient.findUnique({
- where: { id: session.recipientId },
- select: { token: true },
- });
+ const transport = await getCscTransport();
+
+ if (query.scope === 'service') {
+ const recipient = await getRecipientByToken({ token: query.token }).catch(() => null);
if (!recipient) {
throw new AppError(AppErrorCode.NOT_FOUND, {
- message: 'Recipient not found for the CSC session.',
+ message: 'Recipient not found for the provided token.',
});
}
logger.info({
event: 'csc.oauth.authorize.start',
- scope: 'credential',
- recipientId: session.recipientId,
- sessionId: session.id,
- numSignatures: session.items.length,
+ scope: 'service',
+ recipientId: recipient.id,
+ embed: isEmbed,
});
const state = generateState();
const codeVerifier = generateCodeVerifier();
- const authorizeUrl = buildCscCredentialScopeAuthorizeUrl({
+ const authorizeUrl = buildCscServiceScopeAuthorizeUrl({
client: transport.oauthClient,
oauthBaseUrl: transport.oauthBaseUrl,
state,
codeVerifier,
- credentialId: credential.credentialId,
- numSignatures: session.items.length,
- hashes: session.items.map((item) => item.hashB64),
});
await setCscOAuthFlowCookie({
c,
payload: {
- scope: 'credential',
+ scope: 'service',
state,
codeVerifier,
- recipientToken: recipient.token,
- sessionId: session.id,
+ recipientToken: query.token,
+ embedNonceHash,
},
});
return c.redirect(authorizeUrl.toString(), 302);
- },
-);
+ }
+
+ const session = await loadCscSession(query.session);
+
+ if (!session) {
+ throw new AppError(AppErrorCode.NOT_FOUND, {
+ message: 'CSC session not found or already consumed.',
+ });
+ }
+
+ const credential = await loadCscCredential(session.recipientId);
+
+ if (!credential) {
+ throw new AppError(AppErrorCode.NOT_FOUND, {
+ message: 'CSC credential missing — service-scope OAuth must complete first.',
+ });
+ }
+
+ const recipient = await prisma.recipient.findUnique({
+ where: { id: session.recipientId },
+ select: { token: true },
+ });
+
+ if (!recipient) {
+ throw new AppError(AppErrorCode.NOT_FOUND, {
+ message: 'Recipient not found for the CSC session.',
+ });
+ }
+
+ logger.info({
+ event: 'csc.oauth.authorize.start',
+ scope: 'credential',
+ recipientId: session.recipientId,
+ sessionId: session.id,
+ numSignatures: session.items.length,
+ embed: isEmbed,
+ });
+
+ const state = generateState();
+ const codeVerifier = generateCodeVerifier();
+
+ const authorizeUrl = buildCscCredentialScopeAuthorizeUrl({
+ client: transport.oauthClient,
+ oauthBaseUrl: transport.oauthBaseUrl,
+ state,
+ codeVerifier,
+ credentialId: credential.credentialId,
+ numSignatures: session.items.length,
+ hashes: session.items.map((item) => item.hashB64),
+ });
+
+ await setCscOAuthFlowCookie({
+ c,
+ payload: {
+ scope: 'credential',
+ state,
+ codeVerifier,
+ recipientToken: recipient.token,
+ sessionId: session.id,
+ embedNonceHash,
+ },
+ });
+
+ return c.redirect(authorizeUrl.toString(), 302);
+};
diff --git a/packages/ee/server-only/signing/csc/hono/oauth-callback.ts b/packages/ee/server-only/signing/csc/hono/oauth-callback.ts
index d2549d0fb..ea96851ed 100644
--- a/packages/ee/server-only/signing/csc/hono/oauth-callback.ts
+++ b/packages/ee/server-only/signing/csc/hono/oauth-callback.ts
@@ -1,3 +1,10 @@
+import { createAuthHandoff } from '@documenso/auth/server/lib/handoff/create-auth-handoff';
+import { hashAuthHandoffNonce } from '@documenso/auth/server/lib/handoff/hash-auth-handoff-nonce';
+import { recordEmbedAuthFailure } from '@documenso/auth/server/lib/handoff/record-embed-auth-failure';
+import { clearEmbedAuthFlowCookie, getEmbedAuthFlowCookie } from '@documenso/auth/server/lib/session/session-cookies';
+import type { TAuthHandoffCreate } from '@documenso/lib/constants/auth-handoff';
+import { AUTH_HANDOFF_TYPE } from '@documenso/lib/constants/auth-handoff';
+import { formatEmbedAuthCompletePageUrl } from '@documenso/lib/constants/embed-auth';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { getRecipientByToken } from '@documenso/lib/server-only/recipient/get-recipient-by-token';
import { DOCUMENT_AUDIT_LOG_TYPE } from '@documenso/lib/types/document-audit-logs';
@@ -6,6 +13,7 @@ import { createDocumentAuditLogData } from '@documenso/lib/utils/document-audit-
import { formatSigningLink } from '@documenso/lib/utils/recipients';
import { prisma } from '@documenso/prisma';
import { sValidator } from '@hono/standard-validator';
+import type { Context } from 'hono';
import { Hono } from 'hono';
import { z } from 'zod';
@@ -15,6 +23,7 @@ import { encryptCscToken } from '../ciphers';
import { cscCredentialsInfo, cscCredentialsList } from '../client/credentials';
import { exchangeCscAuthorizationCode } from '../client/oauth';
import { setCscBlockingErrorCookie } from '../cookies/blocking-error-cookie';
+import type { TCscOAuthFlowPayload } from '../cookies/oauth-flow-cookie';
import { clearCscOAuthFlowCookie, getCscOAuthFlowCookie } from '../cookies/oauth-flow-cookie';
import { setCscSadSessionCookie } from '../cookies/sad-session-cookie';
import { setCscServiceSessionCookie } from '../cookies/service-session-cookie';
@@ -42,6 +51,11 @@ import type { HonoCscEnv } from './context';
*
* Non-blocking errors bubble to the parent app's `.onError` (see
* `./index.ts`) — mirrors `oauth-authorize.ts`.
+ *
+ * Embed variant (`cookie.embedNonceHash` set): the popup's cookies are invisible
+ * to the cross-site iframe, so every cookie-borne outcome is also recorded as an
+ * auth handoff for the iframe to redeem. Cookies are still set so a top-level
+ * retry keeps working.
*/
const ZCallbackQuerySchema = z.object({
@@ -85,88 +99,242 @@ export const cscOAuthCallbackRoute = new Hono<HonoCscEnv>().get(
// outcome; clear it now so a retry restarts from `/api/csc/oauth/authorize`.
clearCscOAuthFlowCookie(c);
- if (query.error) {
- throw new AppError(AppErrorCode.CSC_REQUEST_FAILED, {
- message: `CSC TSP returned OAuth error: ${query.error}${query.error_description ? ' — ' + query.error_description : ''}`,
- });
+ // The flow cookie must be the one the authorize route saw; a different nonce
+ // means this round trip belongs to another embed attempt.
+ let embedNonce: string | null = null;
+
+ if (cookie.embedNonceHash !== undefined) {
+ const embedFlow = await getEmbedAuthFlowCookie(c);
+
+ clearEmbedAuthFlowCookie(c);
+
+ const isEmbedFlowBound = embedFlow !== null && hashAuthHandoffNonce(embedFlow.nonce) === cookie.embedNonceHash;
+
+ if (!isEmbedFlowBound) {
+ logger.warn({
+ event: 'csc.oauth.callback.embed.flow_missing',
+ scope: cookie.scope,
+ reason: embedFlow === null ? 'missing' : 'nonce_mismatch',
+ });
+
+ return c.redirect(formatEmbedAuthCompletePageUrl('error'), 302);
+ }
+
+ embedNonce = embedFlow.nonce;
}
- if (!query.code) {
- throw new AppError(AppErrorCode.INVALID_REQUEST, {
- message: 'CSC OAuth callback missing code parameter.',
+ const embedOutcome: EmbedOutcome = { isRecorded: false };
+
+ try {
+ return await completeCscCallback({ c, query, cookie, embedNonce, embedOutcome });
+ } catch (err) {
+ // An error after the outcome handoff exists must not overwrite it.
+ if (!embedNonce || embedOutcome.isRecorded) {
+ throw err;
+ }
+
+ logger.error({
+ event: 'csc.oauth.callback.embed.failed',
+ scope: cookie.scope,
+ code: err instanceof AppError ? err.code : AppErrorCode.UNKNOWN_ERROR,
+ error: err,
});
+
+ await recordEmbedAuthFailure(embedNonce, 'csc_callback_failed');
+
+ return c.redirect(formatEmbedAuthCompletePageUrl('error'), 302);
+ }
+ },
+);
+
+type EmbedOutcome = {
+ isRecorded: boolean;
+};
+
+type CompleteCscCallbackOptions = {
+ c: Context<HonoCscEnv>;
+ query: z.infer<typeof ZCallbackQuerySchema>;
+ cookie: TCscOAuthFlowPayload;
+ embedNonce: string | null;
+ embedOutcome: EmbedOutcome;
+};
+
+const completeCscCallback = async ({ c, query, cookie, embedNonce, embedOutcome }: CompleteCscCallbackOptions) => {
+ const logger = c.get('logger');
+
+ const isEmbed = embedNonce !== null;
+
+ const resolveRedirectUrl = () =>
+ isEmbed ? formatEmbedAuthCompletePageUrl('ok') : formatSigningLink(cookie.recipientToken);
+
+ const recordEmbedHandoff = async (handoff: TAuthHandoffCreate): Promise<boolean> => {
+ if (!embedNonce) {
+ return true;
}
- const transport = await getCscTransport();
+ try {
+ await createAuthHandoff({ nonce: embedNonce, ...handoff });
- const recipient = await getRecipientByToken({ token: cookie.recipientToken }).catch(() => null);
+ embedOutcome.isRecorded = true;
- if (!recipient) {
- throw new AppError(AppErrorCode.NOT_FOUND, {
- message: 'Recipient not found for CSC OAuth flow cookie.',
+ return true;
+ } catch (err) {
+ logger.error({
+ event: 'csc.oauth.callback.embed.handoff_failed',
+ scope: cookie.scope,
+ type: handoff.type,
+ error: err,
});
+
+ return false;
+ }
+ };
+
+ const redirectEmbedFailure = async () => {
+ if (embedNonce) {
+ await recordEmbedAuthFailure(embedNonce, 'csc_handoff_not_recorded');
}
- if (cookie.scope === 'service') {
- const tokens = await exchangeCscAuthorizationCode({
- client: transport.oauthClient,
- oauthBaseUrl: transport.oauthBaseUrl,
- code: query.code,
- codeVerifier: cookie.codeVerifier,
+ return c.redirect(formatEmbedAuthCompletePageUrl('error'), 302);
+ };
+
+ if (query.error) {
+ throw new AppError(AppErrorCode.CSC_REQUEST_FAILED, {
+ message: `CSC TSP returned OAuth error: ${query.error}${query.error_description ? ' — ' + query.error_description : ''}`,
+ });
+ }
+
+ if (!query.code) {
+ throw new AppError(AppErrorCode.INVALID_REQUEST, {
+ message: 'CSC OAuth callback missing code parameter.',
+ });
+ }
+
+ const transport = await getCscTransport();
+
+ const recipient = await getRecipientByToken({ token: cookie.recipientToken }).catch(() => null);
+
+ if (!recipient) {
+ throw new AppError(AppErrorCode.NOT_FOUND, {
+ message: 'Recipient not found for CSC OAuth flow cookie.',
+ });
+ }
+
+ if (cookie.scope === 'service') {
+ const tokens = await exchangeCscAuthorizationCode({
+ client: transport.oauthClient,
+ oauthBaseUrl: transport.oauthBaseUrl,
+ code: query.code,
+ codeVerifier: cookie.codeVerifier,
+ });
+
+ try {
+ const listResp = await cscCredentialsList({
+ baseUrl: transport.serviceBaseUrl,
+ accessToken: tokens.accessToken(),
});
- try {
- const listResp = await cscCredentialsList({
- baseUrl: transport.serviceBaseUrl,
- accessToken: tokens.accessToken(),
- });
+ // V1 picks the first credential per spec section "Out of scope for
+ // V1": multi-credential selection UI lands in a later iteration.
+ const credentialId = listResp.credentialIDs[0];
+
+ const infoResp = await cscCredentialsInfo({
+ baseUrl: transport.serviceBaseUrl,
+ accessToken: tokens.accessToken(),
+ credentialID: credentialId,
+ certificates: 'chain',
+ certInfo: true,
+ });
- // V1 picks the first credential per spec section "Out of scope for
- // V1": multi-credential selection UI lands in a later iteration.
- const credentialId = listResp.credentialIDs[0];
+ const policy = resolveCscAlgorithmPolicy(infoResp);
- const infoResp = await cscCredentialsInfo({
- baseUrl: transport.serviceBaseUrl,
- accessToken: tokens.accessToken(),
- credentialID: credentialId,
- certificates: 'chain',
- certInfo: true,
+ if (!infoResp.cert.certificates || infoResp.cert.certificates.length === 0) {
+ throw new AppError(AppErrorCode.CSC_CERT_INVALID, {
+ message: 'CSC credential info response omitted required certificate chain.',
});
+ }
- const policy = resolveCscAlgorithmPolicy(infoResp);
+ const certCache = encodeCscCertChain(infoResp.cert.certificates);
+ const serviceTokenCiphertext = encryptCscToken(tokens.accessToken());
+ const serviceTokenExpiresAt = tokens.accessTokenExpiresAt();
+
+ await upsertCscCredential({
+ recipientId: recipient.id,
+ providerId: transport.serviceBaseUrl,
+ credentialId,
+ certCache,
+ signatureAlgorithm: policy.signAlgoOid,
+ keyType: policy.keyType,
+ digestAlgorithm: policy.digestAlgorithm,
+ keyLenBits: policy.keyLenBits,
+ serviceTokenCiphertext,
+ serviceTokenExpiresAt,
+ });
- if (!infoResp.cert.certificates || infoResp.cert.certificates.length === 0) {
- throw new AppError(AppErrorCode.CSC_CERT_INVALID, {
- message: 'CSC credential info response omitted required certificate chain.',
- });
- }
+ await setCscServiceSessionCookie({
+ c,
+ recipientToken: cookie.recipientToken,
+ ttlSeconds: tokens.accessTokenExpiresInSeconds(),
+ });
- const certCache = encodeCscCertChain(infoResp.cert.certificates);
- const serviceTokenCiphertext = encryptCscToken(tokens.accessToken());
- const serviceTokenExpiresAt = tokens.accessTokenExpiresAt();
+ const isServiceHandoffRecorded = await recordEmbedHandoff({
+ type: AUTH_HANDOFF_TYPE.EMBED_CSC_SERVICE,
+ payload: {
+ recipientToken: cookie.recipientToken,
+ expiresAt: serviceTokenExpiresAt,
+ },
+ });
- await upsertCscCredential({
- recipientId: recipient.id,
- providerId: transport.serviceBaseUrl,
- credentialId,
- certCache,
- signatureAlgorithm: policy.signAlgoOid,
- keyType: policy.keyType,
- digestAlgorithm: policy.digestAlgorithm,
- keyLenBits: policy.keyLenBits,
- serviceTokenCiphertext,
- serviceTokenExpiresAt,
- });
+ if (!isServiceHandoffRecorded) {
+ return await redirectEmbedFailure();
+ }
+
+ await prisma.documentAuditLog.create({
+ data: createDocumentAuditLogData({
+ type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_RECIPIENT_CSC_AUTHENTICATED,
+ envelopeId: recipient.envelopeId,
+ user: { name: recipient.name, email: recipient.email },
+ requestMetadata: extractRequestMetadata(c.req.raw),
+ data: {
+ recipientEmail: recipient.email,
+ recipientName: recipient.name,
+ recipientId: recipient.id,
+ recipientRole: recipient.role,
+ providerId: transport.serviceBaseUrl,
+ credentialId,
+ signatureAlgorithm: policy.signAlgoOid,
+ digestAlgorithm: policy.digestAlgorithm,
+ },
+ }),
+ });
+
+ logger.info({
+ event: 'csc.oauth.callback.service.complete',
+ recipientId: recipient.id,
+ embed: isEmbed,
+ });
- await setCscServiceSessionCookie({
+ return c.redirect(resolveRedirectUrl(), 302);
+ } catch (err) {
+ if (err instanceof AppError && isBlockingServiceError(err.code)) {
+ await setCscBlockingErrorCookie({
c,
- recipientToken: cookie.recipientToken,
- ttlSeconds: tokens.accessTokenExpiresInSeconds(),
+ payload: { code: err.code, recipientToken: cookie.recipientToken },
+ });
+
+ // A blocking error is a completed flow from the popup's view, hence `ok`.
+ const isBlockingHandoffRecorded = await recordEmbedHandoff({
+ type: AUTH_HANDOFF_TYPE.EMBED_CSC_BLOCKING_ERROR,
+ payload: { code: err.code, recipientToken: cookie.recipientToken },
});
+ if (!isBlockingHandoffRecorded) {
+ return await redirectEmbedFailure();
+ }
+
await prisma.documentAuditLog.create({
data: createDocumentAuditLogData({
- type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_RECIPIENT_CSC_AUTHENTICATED,
+ type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_RECIPIENT_CSC_AUTHENTICATION_FAILED,
envelopeId: recipient.envelopeId,
user: { name: recipient.name, email: recipient.email },
requestMetadata: extractRequestMetadata(c.req.raw),
@@ -176,128 +344,109 @@ export const cscOAuthCallbackRoute = new Hono<HonoCscEnv>().get(
recipientId: recipient.id,
recipientRole: recipient.role,
providerId: transport.serviceBaseUrl,
- credentialId,
- signatureAlgorithm: policy.signAlgoOid,
- digestAlgorithm: policy.digestAlgorithm,
+ reason: err.code,
},
}),
});
- logger.info({
- event: 'csc.oauth.callback.service.complete',
+ logger.warn({
+ event: 'csc.oauth.callback.service.blocking',
recipientId: recipient.id,
+ code: err.code,
+ embed: isEmbed,
});
- return c.redirect(formatSigningLink(cookie.recipientToken), 302);
- } catch (err) {
- if (err instanceof AppError && isBlockingServiceError(err.code)) {
- await setCscBlockingErrorCookie({
- c,
- payload: { code: err.code, recipientToken: cookie.recipientToken },
- });
-
- await prisma.documentAuditLog.create({
- data: createDocumentAuditLogData({
- type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_RECIPIENT_CSC_AUTHENTICATION_FAILED,
- envelopeId: recipient.envelopeId,
- user: { name: recipient.name, email: recipient.email },
- requestMetadata: extractRequestMetadata(c.req.raw),
- data: {
- recipientEmail: recipient.email,
- recipientName: recipient.name,
- recipientId: recipient.id,
- recipientRole: recipient.role,
- providerId: transport.serviceBaseUrl,
- reason: err.code,
- },
- }),
- });
-
- logger.warn({
- event: 'csc.oauth.callback.service.blocking',
- recipientId: recipient.id,
- code: err.code,
- });
-
- return c.redirect(formatSigningLink(cookie.recipientToken), 302);
- }
-
- throw err;
+ return c.redirect(resolveRedirectUrl(), 302);
}
- }
- if (!cookie.sessionId) {
- throw new AppError(AppErrorCode.INVALID_REQUEST, {
- message: 'CSC credential-scope OAuth callback missing sessionId in cookie.',
- });
+ throw err;
}
+ }
- const tokens = await exchangeCscAuthorizationCode({
- client: transport.oauthClient,
- oauthBaseUrl: transport.oauthBaseUrl,
- code: query.code,
- codeVerifier: cookie.codeVerifier,
+ if (!cookie.sessionId) {
+ throw new AppError(AppErrorCode.INVALID_REQUEST, {
+ message: 'CSC credential-scope OAuth callback missing sessionId in cookie.',
});
-
- // CSC §8.3.3 says credential-scope returns `token_type === 'SAD'`. We
- // don't hard-fail on a divergent label — the binding is by scope + hash,
- // not by `token_type` — but we log so operator metrics can spot loose
- // TSPs.
- if (tokens.tokenType() !== 'SAD') {
- logger.warn({
- event: 'csc.oauth.callback.credential.unexpected_token_type',
- actual: tokens.tokenType(),
- });
- }
-
- const sadCiphertext = encryptCscToken(tokens.accessToken());
- const sadExpiresAt = tokens.accessTokenExpiresAt();
-
- await updateCscSessionWithSad({
- sessionId: cookie.sessionId,
- encryptedSad: sadCiphertext,
- sadExpiresAt,
+ }
+
+ const tokens = await exchangeCscAuthorizationCode({
+ client: transport.oauthClient,
+ oauthBaseUrl: transport.oauthBaseUrl,
+ code: query.code,
+ codeVerifier: cookie.codeVerifier,
+ });
+
+ // CSC §8.3.3 says credential-scope returns `token_type === 'SAD'`. We
+ // don't hard-fail on a divergent label — the binding is by scope + hash,
+ // not by `token_type` — but we log so operator metrics can spot loose
+ // TSPs.
+ if (tokens.tokenType() !== 'SAD') {
+ logger.warn({
+ event: 'csc.oauth.callback.credential.unexpected_token_type',
+ actual: tokens.tokenType(),
});
-
- await setCscSadSessionCookie({
- c,
+ }
+
+ const sadCiphertext = encryptCscToken(tokens.accessToken());
+ const sadExpiresAt = tokens.accessTokenExpiresAt();
+
+ await updateCscSessionWithSad({
+ sessionId: cookie.sessionId,
+ encryptedSad: sadCiphertext,
+ sadExpiresAt,
+ });
+
+ await setCscSadSessionCookie({
+ c,
+ sessionId: cookie.sessionId,
+ expiresAt: sadExpiresAt,
+ });
+
+ const isSadHandoffRecorded = await recordEmbedHandoff({
+ type: AUTH_HANDOFF_TYPE.EMBED_CSC_SAD,
+ payload: {
sessionId: cookie.sessionId,
expiresAt: sadExpiresAt,
- });
-
- const credential = await loadCscCredential(recipient.id);
+ },
+ });
- if (!credential) {
- throw new AppError(AppErrorCode.NOT_FOUND, {
- message: 'CSC credential missing at credential-scope callback.',
- });
- }
+ if (!isSadHandoffRecorded) {
+ return await redirectEmbedFailure();
+ }
- await prisma.documentAuditLog.create({
- data: createDocumentAuditLogData({
- type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_RECIPIENT_CSC_AUTHORIZED,
- envelopeId: recipient.envelopeId,
- user: { name: recipient.name, email: recipient.email },
- requestMetadata: extractRequestMetadata(c.req.raw),
- data: {
- recipientEmail: recipient.email,
- recipientName: recipient.name,
- recipientId: recipient.id,
- recipientRole: recipient.role,
- providerId: credential.providerId,
- credentialId: credential.credentialId,
- sessionId: cookie.sessionId,
- sadExpiresAt,
- },
- }),
- });
+ const credential = await loadCscCredential(recipient.id);
- logger.info({
- event: 'csc.oauth.callback.credential.complete',
- recipientId: recipient.id,
- sessionId: cookie.sessionId,
+ if (!credential) {
+ throw new AppError(AppErrorCode.NOT_FOUND, {
+ message: 'CSC credential missing at credential-scope callback.',
});
-
- return c.redirect(formatSigningLink(cookie.recipientToken), 302);
- },
-);
+ }
+
+ await prisma.documentAuditLog.create({
+ data: createDocumentAuditLogData({
+ type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_RECIPIENT_CSC_AUTHORIZED,
+ envelopeId: recipient.envelopeId,
+ user: { name: recipient.name, email: recipient.email },
+ requestMetadata: extractRequestMetadata(c.req.raw),
+ data: {
+ recipientEmail: recipient.email,
+ recipientName: recipient.name,
+ recipientId: recipient.id,
+ recipientRole: recipient.role,
+ providerId: credential.providerId,
+ credentialId: credential.credentialId,
+ sessionId: cookie.sessionId,
+ sadExpiresAt,
+ },
+ }),
+ });
+
+ logger.info({
+ event: 'csc.oauth.callback.credential.complete',
+ recipientId: recipient.id,
+ sessionId: cookie.sessionId,
+ embed: isEmbed,
+ });
+
+ return c.redirect(resolveRedirectUrl(), 302);
+};
diff --git a/packages/ee/server-only/signing/csc/hono/session-status.ts b/packages/ee/server-only/signing/csc/hono/session-status.ts
new file mode 100644
index 000000000..7adb7ce1a
--- /dev/null
+++ b/packages/ee/server-only/signing/csc/hono/session-status.ts
@@ -0,0 +1,47 @@
+import { sValidator } from '@hono/standard-validator';
+import { Hono } from 'hono';
+import { z } from 'zod';
+
+import { getCscBlockingErrorCookie } from '../cookies/blocking-error-cookie';
+import { getCscSadSessionCookie } from '../cookies/sad-session-cookie';
+import { getCscServiceSessionCookie } from '../cookies/service-session-cookie';
+import type { HonoCscEnv } from './context';
+
+// The CSC cookies are httpOnly, so this is how the embed iframe learns whether
+// the browser kept the redeemed cookie. Reveals only whether the caller's own
+// token/session id matches.
+const ZSessionStatusQuerySchema = z.discriminatedUnion('scope', [
+ z.object({
+ scope: z.literal('service'),
+ token: z.string().min(1),
+ }),
+ z.object({
+ scope: z.literal('credential'),
+ sessionId: z.string().min(1),
+ }),
+]);
+
+export const cscSessionStatusRoute = new Hono<HonoCscEnv>().get(
+ '/',
+ sValidator('query', ZSessionStatusQuerySchema),
+ async (c) => {
+ const query = c.req.valid('query');
+
+ if (query.scope === 'credential') {
+ const sadSessionId = await getCscSadSessionCookie(c);
+
+ return c.json({ active: sadSessionId === query.sessionId });
+ }
+
+ const serviceSessionToken = await getCscServiceSessionCookie(c);
+
+ if (serviceSessionToken === query.token) {
+ return c.json({ active: true });
+ }
+
+ // A blocked service-scope flow also counts as landed; the iframe reloads to render it.
+ const blockingError = await getCscBlockingErrorCookie(c);
+
+ return c.json({ active: blockingError?.recipientToken === query.token });
+ },
+);
diff --git a/packages/ee/server-only/signing/csc/prepare-recipient-signing.ts b/packages/ee/server-only/signing/csc/prepare-recipient-signing.ts
index 38f671c42..2420bacd6 100644
--- a/packages/ee/server-only/signing/csc/prepare-recipient-signing.ts
+++ b/packages/ee/server-only/signing/csc/prepare-recipient-signing.ts
@@ -52,6 +52,8 @@ export type PrepareCscRecipientSigningOptions = {
export type PrepareCscRecipientSigningResult = {
status: 'REDIRECT';
redirectUrl: string;
+ /** The `CscSession` the redirect authorises; embeds use it to drive the popup flow instead of navigating. */
+ sessionId: string;
};
export const prepareCscRecipientSigning = async (
@@ -244,5 +246,6 @@ export const prepareCscRecipientSigning = async (
return {
status: 'REDIRECT',
redirectUrl,
+ sessionId: session.id,
};
};
diff --git a/packages/lib/client-only/hooks/use-embed-popup-auth.ts b/packages/lib/client-only/hooks/use-embed-popup-auth.ts
new file mode 100644
index 000000000..821163a41
--- /dev/null
+++ b/packages/lib/client-only/hooks/use-embed-popup-auth.ts
@@ -0,0 +1,632 @@
+import type { TEmbedAuthRedeemResult } from '@documenso/auth/client';
+import { authClient } from '@documenso/auth/client';
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { match } from 'ts-pattern';
+import { z } from 'zod';
+
+import { formatPath } from '../../constants/app';
+import type { EmbedPopupAuthCscOptions, EmbedPopupAuthProvider } from '../../constants/embed-auth';
+import {
+ EMBED_AUTH_MESSAGE_NONCE,
+ EMBED_AUTH_POPUP_PATH,
+ EMBED_AUTH_POPUP_WINDOW_FEATURES,
+ EMBED_AUTH_POPUP_WINDOW_NAME,
+ ZEmbedAuthCompleteMessageSchema,
+ ZEmbedAuthFailedMessageSchema,
+ ZEmbedAuthReadyMessageSchema,
+} from '../../constants/embed-auth';
+import { alphaid } from '../../universal/id';
+import { sleep } from '../../universal/sleep';
+
+const REDEEM_POLL_INTERVAL_MS = 2_000;
+
+const REDEEM_POLL_INITIAL_DELAY_MS = 5_000;
+
+const REDEEM_RATE_LIMITED_DELAY_MS = 5_000;
+
+const REDEEM_MAX_CONSECUTIVE_FAILURES = 3;
+
+/**
+ * Matches the server-side embed auth flow cookie max-age.
+ *
+ * `popup.closed` is deliberately not used to detect cancellation: some IdPs
+ * (Google) enforce `Cross-Origin-Opener-Policy: same-origin`, which severs the
+ * opener link and makes `closed` report true while the popup is still open.
+ */
+const FLOW_TIMEOUT_MS = 10 * 60 * 1_000;
+
+const STORAGE_ACCESS_REDEEM_ATTEMPTS = 5;
+
+const STORAGE_ACCESS_REDEEM_INTERVAL_MS = 1_000;
+
+const CSC_SESSION_STATUS_PATH = '/api/csc/session-status';
+
+const ZCscSessionStatusResponseSchema = z.object({
+ active: z.boolean(),
+});
+
+export type { EmbedPopupAuthCscOptions, EmbedPopupAuthProvider };
+
+export type EmbedPopupAuthStatus = 'idle' | 'waiting' | 'redeeming' | 'needs-storage-access' | 'success' | 'error';
+
+export type EmbedPopupAuthError =
+ | 'popup-blocked'
+ | 'timeout'
+ | 'auth-failed'
+ | 'cookie-blocked'
+ | 'storage-access-denied'
+ | 'request-failed';
+
+export type UseEmbedPopupAuthOptions = {
+ onSuccess: () => void;
+};
+
+type EmbedPopupAuthBaseStartOptions = {
+ email?: string;
+
+ /**
+ * Window pre-opened via `openPopupWindow()` inside the click's user activation,
+ * for callers that need async work before `start`.
+ */
+ popup?: Window | null;
+};
+
+export type EmbedPopupAuthCscStartOptions = EmbedPopupAuthBaseStartOptions & {
+ csc: EmbedPopupAuthCscOptions;
+};
+
+export type EmbedPopupAuthAccountStartOptions = EmbedPopupAuthBaseStartOptions & {
+ csc?: never;
+};
+
+export type EmbedPopupAuthStartOptions = EmbedPopupAuthCscStartOptions | EmbedPopupAuthAccountStartOptions;
+
+export type EmbedPopupAuthStart = {
+ (provider: 'csc', options: EmbedPopupAuthCscStartOptions): void;
+ (provider: Exclude<EmbedPopupAuthProvider, 'csc'>, options?: EmbedPopupAuthAccountStartOptions): void;
+};
+
+/**
+ * Email and CSC options travel in the fragment, not the query string, so they
+ * never reach the server with the page request.
+ */
+const buildPopupHash = (options: EmbedPopupAuthStartOptions): string => {
+ const params = new URLSearchParams();
+
+ if (options.email) {
+ params.set('email', options.email);
+ }
+
+ if (options.csc) {
+ params.set('scope', options.csc.scope);
+ params.set('token', options.csc.token);
+
+ if (options.csc.scope === 'credential') {
+ params.set('sessionId', options.csc.sessionId);
+ }
+ }
+
+ const hash = params.toString();
+
+ return hash ? `#${hash}` : '';
+};
+
+const buildPopupWindowName = () => `${EMBED_AUTH_POPUP_WINDOW_NAME}-${alphaid(6)}`;
+
+/**
+ * Must be called synchronously from a click handler so `window.open` is not
+ * blocked. Returns null when it was.
+ */
+export const openPopupWindow = (): Window | null => {
+ return window.open('about:blank', buildPopupWindowName(), EMBED_AUTH_POPUP_WINDOW_FEATURES);
+};
+
+type Attempt = {
+ nonce: string;
+ generation: number;
+ popup: Window | null;
+ isActive: boolean;
+ isRedeemInFlight: boolean;
+ shouldRedeemImmediately: boolean;
+ consecutiveFailures: number;
+ redeemTimer: number | null;
+ flowTimeout: number | null;
+ onMessage: ((event: MessageEvent) => void) | null;
+};
+
+/**
+ * CSC handoffs do not create a user session, so `getSession()` cannot verify
+ * the redeemed cookie landed in the iframe's partition.
+ */
+const hasCscSession = async (csc: EmbedPopupAuthCscOptions): Promise<boolean> => {
+ const params = new URLSearchParams({ scope: csc.scope, token: csc.token });
+
+ if (csc.scope === 'credential') {
+ params.set('sessionId', csc.sessionId);
+ }
+
+ try {
+ const response = await fetch(`${formatPath(CSC_SESSION_STATUS_PATH)}?${params.toString()}`, {
+ credentials: 'include',
+ });
+
+ if (!response.ok) {
+ return false;
+ }
+
+ const result = ZCscSessionStatusResponseSchema.safeParse(await response.json());
+
+ return result.success && result.data.active;
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * Drives the embed popup login flow from inside a cross-site embed iframe.
+ *
+ * `start()` and `continueWithStorageAccess()` must be called synchronously from
+ * a click handler (`window.open` and `requestStorageAccess` need user activation).
+ *
+ * The nonce is only ever exchanged via same-origin `postMessage` and request
+ * bodies, never a URL.
+ */
+export const useEmbedPopupAuth = ({ onSuccess }: UseEmbedPopupAuthOptions) => {
+ const [status, setStatusState] = useState<EmbedPopupAuthStatus>('idle');
+ const [error, setError] = useState<EmbedPopupAuthError | null>(null);
+
+ // Synchronous mirror so `reset()` then `start()` in one click handler works.
+ const statusRef = useRef<EmbedPopupAuthStatus>('idle');
+
+ const setStatus = useCallback((next: EmbedPopupAuthStatus) => {
+ statusRef.current = next;
+ setStatusState(next);
+ }, []);
+
+ const attemptRef = useRef<Attempt | null>(null);
+ const nonceRef = useRef<string | null>(null);
+
+ // Async continuations bail out after each await if this has moved on, so a
+ // cancelled or superseded flow can never flip status or fire `onSuccess` late.
+ const generationRef = useRef(0);
+
+ const verifyCookieRef = useRef<(() => Promise<boolean>) | null>(null);
+
+ // Redeem always overwrites the embed cookie, so an unchanged session id means
+ // the browser dropped it and a stale cookie is still being sent.
+ const sessionSnapshotRef = useRef<Promise<string | null> | null>(null);
+
+ const onSuccessRef = useRef(onSuccess);
+
+ onSuccessRef.current = onSuccess;
+
+ const teardownAttempt = useCallback(() => {
+ const attempt = attemptRef.current;
+
+ if (!attempt) {
+ return;
+ }
+
+ attempt.isActive = false;
+
+ if (attempt.redeemTimer !== null) {
+ window.clearTimeout(attempt.redeemTimer);
+ }
+
+ if (attempt.flowTimeout !== null) {
+ window.clearTimeout(attempt.flowTimeout);
+ }
+
+ if (attempt.onMessage) {
+ window.removeEventListener('message', attempt.onMessage);
+ }
+
+ attemptRef.current = null;
+ }, []);
+
+ const fail = useCallback(
+ (code: EmbedPopupAuthError, generation: number) => {
+ if (generation !== generationRef.current) {
+ return;
+ }
+
+ teardownAttempt();
+
+ setError(code);
+ setStatus('error');
+ },
+ [teardownAttempt, setStatus],
+ );
+
+ const hasSession = useCallback(async () => {
+ try {
+ const [session, snapshotSessionId] = await Promise.all([
+ authClient.embed.getSession(),
+ sessionSnapshotRef.current ?? Promise.resolve(null),
+ ]);
+
+ if (!session.user) {
+ return false;
+ }
+
+ return snapshotSessionId === null || session.session.id !== snapshotSessionId;
+ } catch {
+ return false;
+ }
+ }, []);
+
+ const verifyCookie = useCallback(() => {
+ const verify = verifyCookieRef.current ?? hasSession;
+
+ return verify();
+ }, [hasSession]);
+
+ const finalize = useCallback(
+ async (attempt: Attempt) => {
+ const { generation } = attempt;
+
+ if (generation !== generationRef.current) {
+ return;
+ }
+
+ teardownAttempt();
+
+ setStatus('redeeming');
+
+ const isSignedIn = await verifyCookie();
+
+ if (generation !== generationRef.current) {
+ return;
+ }
+
+ if (isSignedIn) {
+ setStatus('success');
+ onSuccessRef.current();
+
+ return;
+ }
+
+ if (typeof document.requestStorageAccess === 'function') {
+ setStatus('needs-storage-access');
+
+ return;
+ }
+
+ fail('cookie-blocked', generation);
+ },
+ [teardownAttempt, verifyCookie, fail, setStatus],
+ );
+
+ const scheduleRedeem = useCallback((attempt: Attempt, delay: number, run: (attempt: Attempt) => void) => {
+ if (attempt.redeemTimer !== null) {
+ window.clearTimeout(attempt.redeemTimer);
+ }
+
+ attempt.redeemTimer = window.setTimeout(() => {
+ attempt.redeemTimer = null;
+
+ run(attempt);
+ }, delay);
+ }, []);
+
+ const runRedeem = useCallback(
+ async (attempt: Attempt) => {
+ if (!attempt.isActive) {
+ return;
+ }
+
+ if (attempt.isRedeemInFlight) {
+ attempt.shouldRedeemImmediately = true;
+
+ return;
+ }
+
+ if (attempt.redeemTimer !== null) {
+ window.clearTimeout(attempt.redeemTimer);
+ attempt.redeemTimer = null;
+ }
+
+ attempt.isRedeemInFlight = true;
+ attempt.shouldRedeemImmediately = false;
+
+ let result: TEmbedAuthRedeemResult | null = null;
+
+ try {
+ result = await authClient.embed.redeem({ nonce: attempt.nonce });
+ } catch {
+ result = null;
+ }
+
+ attempt.isRedeemInFlight = false;
+
+ if (!attempt.isActive) {
+ return;
+ }
+
+ if (result === null) {
+ attempt.consecutiveFailures += 1;
+
+ if (attempt.consecutiveFailures >= REDEEM_MAX_CONSECUTIVE_FAILURES) {
+ fail('request-failed', attempt.generation);
+
+ return;
+ }
+
+ scheduleRedeem(attempt, REDEEM_POLL_INTERVAL_MS, (next) => void runRedeem(next));
+
+ return;
+ }
+
+ attempt.consecutiveFailures = 0;
+
+ if (result === 'failed') {
+ fail('auth-failed', attempt.generation);
+
+ return;
+ }
+
+ const delay = match(result)
+ .with('ok', () => null)
+ .with('pending', () => (attempt.shouldRedeemImmediately ? 0 : REDEEM_POLL_INTERVAL_MS))
+ .with('rate-limited', () => REDEEM_RATE_LIMITED_DELAY_MS)
+ .exhaustive();
+
+ if (delay === null) {
+ void finalize(attempt);
+
+ return;
+ }
+
+ scheduleRedeem(attempt, delay, (next) => void runRedeem(next));
+ },
+ [fail, finalize, scheduleRedeem],
+ );
+
+ const start = useCallback<EmbedPopupAuthStart>(
+ (provider: EmbedPopupAuthProvider, options: EmbedPopupAuthStartOptions = {}) => {
+ const closePreOpenedPopup = () => {
+ if (options.popup && !options.popup.closed) {
+ options.popup.close();
+ }
+ };
+
+ if (statusRef.current !== 'idle' && statusRef.current !== 'error') {
+ closePreOpenedPopup();
+
+ return;
+ }
+
+ teardownAttempt();
+
+ generationRef.current += 1;
+
+ const generation = generationRef.current;
+
+ setError(null);
+
+ const nonce = crypto.randomUUID();
+
+ nonceRef.current = nonce;
+
+ const csc = options.csc;
+
+ verifyCookieRef.current = csc ? async () => hasCscSession(csc) : hasSession;
+
+ sessionSnapshotRef.current = authClient.embed
+ .getSession()
+ .then((session) => session.session?.id ?? null)
+ .catch(() => null);
+
+ const attempt: Attempt = {
+ nonce,
+ generation,
+ popup: null,
+ isActive: true,
+ isRedeemInFlight: false,
+ shouldRedeemImmediately: false,
+ consecutiveFailures: 0,
+ redeemTimer: null,
+ flowTimeout: null,
+ onMessage: null,
+ };
+
+ const onMessage = (event: MessageEvent) => {
+ const popup = attempt.popup;
+
+ if (!attempt.isActive || !popup) {
+ return;
+ }
+
+ if (event.origin !== window.location.origin || event.source !== popup) {
+ return;
+ }
+
+ if (ZEmbedAuthReadyMessageSchema.safeParse(event.data).success) {
+ popup.postMessage({ type: EMBED_AUTH_MESSAGE_NONCE, nonce }, window.location.origin);
+
+ return;
+ }
+
+ if (ZEmbedAuthCompleteMessageSchema.safeParse(event.data).success) {
+ void runRedeem(attempt);
+
+ return;
+ }
+
+ if (ZEmbedAuthFailedMessageSchema.safeParse(event.data).success) {
+ fail('auth-failed', generation);
+ }
+ };
+
+ attempt.onMessage = onMessage;
+
+ window.addEventListener('message', onMessage);
+
+ const popupHash = buildPopupHash(options);
+
+ const popupUrl = `${formatPath(EMBED_AUTH_POPUP_PATH)}?provider=${encodeURIComponent(provider)}${popupHash}`;
+
+ const preOpenedPopup = options.popup && !options.popup.closed ? options.popup : null;
+
+ let popup: Window | null;
+
+ if (preOpenedPopup) {
+ preOpenedPopup.location.href = popupUrl;
+
+ popup = preOpenedPopup;
+ } else {
+ popup = window.open(popupUrl, buildPopupWindowName(), EMBED_AUTH_POPUP_WINDOW_FEATURES);
+ }
+
+ if (!popup) {
+ window.removeEventListener('message', onMessage);
+
+ setError('popup-blocked');
+ setStatus('error');
+
+ return;
+ }
+
+ attempt.popup = popup;
+ attemptRef.current = attempt;
+
+ setStatus('waiting');
+
+ attempt.flowTimeout = window.setTimeout(() => {
+ fail('timeout', generation);
+ }, FLOW_TIMEOUT_MS);
+
+ scheduleRedeem(attempt, REDEEM_POLL_INITIAL_DELAY_MS, (next) => void runRedeem(next));
+ },
+ [teardownAttempt, fail, runRedeem, scheduleRedeem, hasSession, setStatus],
+ );
+
+ const continueWithStorageAccess = useCallback(async () => {
+ if (statusRef.current !== 'needs-storage-access') {
+ return;
+ }
+
+ const nonce = nonceRef.current;
+ const generation = generationRef.current;
+
+ if (!nonce) {
+ fail('request-failed', generation);
+
+ return;
+ }
+
+ try {
+ await document.requestStorageAccess();
+ } catch {
+ fail('storage-access-denied', generation);
+
+ return;
+ }
+
+ if (generation !== generationRef.current) {
+ return;
+ }
+
+ setStatus('redeeming');
+
+ let isRedeemed = false;
+
+ for (let i = 0; i < STORAGE_ACCESS_REDEEM_ATTEMPTS; i += 1) {
+ let result: TEmbedAuthRedeemResult;
+
+ try {
+ result = await authClient.embed.redeem({ nonce });
+ } catch {
+ fail('request-failed', generation);
+
+ return;
+ }
+
+ if (generation !== generationRef.current) {
+ return;
+ }
+
+ if (result === 'ok') {
+ isRedeemed = true;
+
+ break;
+ }
+
+ if (result === 'failed') {
+ fail('auth-failed', generation);
+
+ return;
+ }
+
+ await sleep(STORAGE_ACCESS_REDEEM_INTERVAL_MS);
+
+ if (generation !== generationRef.current) {
+ return;
+ }
+ }
+
+ if (!isRedeemed) {
+ fail('cookie-blocked', generation);
+
+ return;
+ }
+
+ const isSignedIn = await verifyCookie();
+
+ if (generation !== generationRef.current) {
+ return;
+ }
+
+ if (!isSignedIn) {
+ fail('cookie-blocked', generation);
+
+ return;
+ }
+
+ setStatus('success');
+ onSuccessRef.current();
+ }, [fail, verifyCookie, setStatus]);
+
+ const reset = useCallback(() => {
+ teardownAttempt();
+
+ generationRef.current += 1;
+
+ nonceRef.current = null;
+ verifyCookieRef.current = null;
+ sessionSnapshotRef.current = null;
+
+ setError(null);
+ setStatus('idle');
+ }, [teardownAttempt, setStatus]);
+
+ // After a COOP-enforcing IdP `close()` is a no-op; the user dismisses the window.
+ const cancel = useCallback(() => {
+ const popup = attemptRef.current?.popup ?? null;
+
+ if (popup && !popup.closed) {
+ popup.close();
+ }
+
+ reset();
+ }, [reset]);
+
+ useEffect(() => {
+ return () => {
+ generationRef.current += 1;
+
+ teardownAttempt();
+ };
+ }, [teardownAttempt]);
+
+ return {
+ status,
+ error,
+ start,
+ continueWithStorageAccess,
+ reset,
+ cancel,
+ };
+};
+
+export type EmbedPopupAuth = ReturnType<typeof useEmbedPopupAuth>;
diff --git a/packages/lib/client-only/hooks/use-is-framed.ts b/packages/lib/client-only/hooks/use-is-framed.ts
new file mode 100644
index 000000000..5162814bb
--- /dev/null
+++ b/packages/lib/client-only/hooks/use-is-framed.ts
@@ -0,0 +1,12 @@
+import { useEffect, useState } from 'react';
+
+// Resolves after mount so SSR and first client render agree.
+export const useIsFramed = () => {
+ const [isFramed, setIsFramed] = useState(false);
+
+ useEffect(() => {
+ setIsFramed(window.self !== window.top);
+ }, []);
+
+ return isFramed;
+};
diff --git a/packages/lib/constants/auth-handoff.ts b/packages/lib/constants/auth-handoff.ts
new file mode 100644
index 000000000..419d01b1b
--- /dev/null
+++ b/packages/lib/constants/auth-handoff.ts
@@ -0,0 +1,91 @@
+import { z } from 'zod';
+
+// Stored as a plain string column so new types do not need a DB enum migration.
+export const AUTH_HANDOFF_TYPE = {
+ EMBED_SESSION: 'EMBED_SESSION',
+ EMBED_CSC_SERVICE: 'EMBED_CSC_SERVICE',
+ EMBED_CSC_SAD: 'EMBED_CSC_SAD',
+ EMBED_CSC_BLOCKING_ERROR: 'EMBED_CSC_BLOCKING_ERROR',
+ EMBED_FAILED: 'EMBED_FAILED',
+} as const;
+
+// All schemas are strict so an unexpected key in a decrypted row is treated as corruption.
+const ZEmbedSessionCreatePayloadSchema = z
+ .object({
+ userId: z.number().int().positive(),
+ sessionId: z.string().min(1),
+ })
+ .strict();
+
+// `generateSessionToken` output: 20 random bytes, unpadded lower case base32.
+const ZSessionTokenSchema = z.string().regex(/^[a-z2-7]{32}$/);
+
+const ZEmbedSessionStoredPayloadSchema = ZEmbedSessionCreatePayloadSchema.extend({
+ sessionToken: ZSessionTokenSchema.optional(),
+}).strict();
+
+const ZEmbedCscServicePayloadSchema = z
+ .object({
+ recipientToken: z.string().min(1),
+ expiresAt: z.coerce.date(),
+ })
+ .strict();
+
+const ZEmbedCscSadPayloadSchema = z
+ .object({
+ sessionId: z.string().min(1),
+ expiresAt: z.coerce.date(),
+ })
+ .strict();
+
+const ZEmbedCscBlockingErrorPayloadSchema = z
+ .object({
+ code: z.string().min(1),
+ recipientToken: z.string().min(1),
+ })
+ .strict();
+
+const cscHandoffVariants = [
+ z.object({
+ type: z.literal(AUTH_HANDOFF_TYPE.EMBED_CSC_SERVICE),
+ payload: ZEmbedCscServicePayloadSchema,
+ }),
+ z.object({
+ type: z.literal(AUTH_HANDOFF_TYPE.EMBED_CSC_SAD),
+ payload: ZEmbedCscSadPayloadSchema,
+ }),
+ z.object({
+ type: z.literal(AUTH_HANDOFF_TYPE.EMBED_CSC_BLOCKING_ERROR),
+ payload: ZEmbedCscBlockingErrorPayloadSchema,
+ }),
+] as const;
+
+const ZEmbedFailedPayloadSchema = z.object({}).strict();
+
+const embedFailedHandoffVariant = z.object({
+ type: z.literal(AUTH_HANDOFF_TYPE.EMBED_FAILED),
+ payload: ZEmbedFailedPayloadSchema,
+});
+
+export const ZAuthHandoffCreateSchema = z.discriminatedUnion('type', [
+ z.object({
+ type: z.literal(AUTH_HANDOFF_TYPE.EMBED_SESSION),
+ payload: ZEmbedSessionCreatePayloadSchema,
+ }),
+ ...cscHandoffVariants,
+ embedFailedHandoffVariant,
+]);
+
+export type TAuthHandoffCreate = z.infer<typeof ZAuthHandoffCreateSchema>;
+
+export const ZAuthHandoffStoredSchema = z.discriminatedUnion('type', [
+ z.object({
+ type: z.literal(AUTH_HANDOFF_TYPE.EMBED_SESSION),
+ payload: ZEmbedSessionStoredPayloadSchema,
+ }),
+ ...cscHandoffVariants,
+ embedFailedHandoffVariant,
+]);
+
+export type TAuthHandoffEmbedCscSadPayload = z.infer<typeof ZEmbedCscSadPayloadSchema>;
+export type TAuthHandoffEmbedCscBlockingErrorPayload = z.infer<typeof ZEmbedCscBlockingErrorPayloadSchema>;
diff --git a/packages/lib/constants/auth.ts b/packages/lib/constants/auth.ts
index cb514979b..a7f84a865 100644
--- a/packages/lib/constants/auth.ts
+++ b/packages/lib/constants/auth.ts
@@ -65,12 +65,14 @@ export const PASSKEY_TIMEOUT = 60000;
*/
export const MAXIMUM_PASSKEYS = 50;
-export const useSecureCookies =
- env('NODE_ENV') === 'production' && String(NEXT_PUBLIC_WEBAPP_URL()).startsWith('https://');
+// Keyed off the scheme only: browsers reject `Secure`/`Partitioned`/`__Host-`
+// over plain http (Safari even on localhost), including local https dev.
+export const shouldUseSecureCookies = () => String(NEXT_PUBLIC_WEBAPP_URL()).startsWith('https://');
-const secureCookiePrefix = useSecureCookies ? '__Secure-' : '';
+export const formatSecureCookieName = (name: string) => (shouldUseSecureCookies() ? `__Secure-${name}` : name);
-export const formatSecureCookieName = (name: string) => `${secureCookiePrefix}${name}`;
+// `__Host-` requires `Secure`, `Path=/` and no `Domain`, so a subdomain cannot set it.
+export const formatHostCookieName = (name: string) => (shouldUseSecureCookies() ? `__Host-${name}` : name);
export const getCookieDomain = () => {
const url = new URL(NEXT_PUBLIC_WEBAPP_URL());
@@ -182,12 +184,16 @@ export const isSignupEnabledForProvider = (provider: 'email' | 'google' | 'micro
return env(flagMap[provider]) !== 'true';
};
+export const isSigninDisabledGlobally = (): boolean => {
+ return env('NEXT_PUBLIC_DISABLE_SIGNIN') === 'true';
+};
+
/**
* Check if signin is enabled for the given provider.
* The master switch takes precedence over the per-provider flags.
*/
export const isSigninEnabledForProvider = (provider: 'email' | 'google' | 'microsoft' | 'oidc'): boolean => {
- if (env('NEXT_PUBLIC_DISABLE_SIGNIN') === 'true') {
+ if (isSigninDisabledGlobally()) {
return false;
}
diff --git a/packages/lib/constants/embed-auth.ts b/packages/lib/constants/embed-auth.ts
new file mode 100644
index 000000000..19a107ae0
--- /dev/null
+++ b/packages/lib/constants/embed-auth.ts
@@ -0,0 +1,113 @@
+import { z } from 'zod';
+
+import { env } from '../utils/env';
+import { formatPath } from './app';
+import {
+ IS_GOOGLE_SSO_ENABLED,
+ IS_MICROSOFT_SSO_ENABLED,
+ IS_OIDC_SSO_ENABLED,
+ isSigninDisabledGlobally,
+ isSigninEnabledForProvider,
+ OIDC_PROVIDER_LABEL,
+} from './auth';
+
+export const EMBED_AUTH_POPUP_PATH = '/embed/auth/popup';
+export const EMBED_AUTH_COMPLETE_API_PATH = '/api/auth/embed/complete';
+export const EMBED_AUTH_COMPLETE_PAGE_PATH = '/embed/auth/complete';
+
+// `account` is the email/password and/or passkey form; the rest are redirect based.
+export const ZEmbedPopupAuthProviderSchema = z.enum(['google', 'microsoft', 'oidc', 'csc', 'account']);
+
+export type EmbedPopupAuthProvider = z.infer<typeof ZEmbedPopupAuthProviderSchema>;
+
+// CSC auth is recipient scoped, not user scoped, so the popup needs to know what to authorise.
+export const ZEmbedPopupAuthCscOptionsSchema = z.union([
+ z.object({
+ scope: z.literal('service'),
+ token: z.string().min(1),
+ }),
+ z.object({
+ scope: z.literal('credential'),
+ token: z.string().min(1),
+ sessionId: z.string().min(1),
+ }),
+]);
+
+export type EmbedPopupAuthCscOptions = z.infer<typeof ZEmbedPopupAuthCscOptionsSchema>;
+
+export const formatEmbedAuthCompleteApiUrl = (state: string) => {
+ const searchParams = new URLSearchParams({ state });
+
+ return `${formatPath(EMBED_AUTH_COMPLETE_API_PATH)}?${searchParams.toString()}`;
+};
+
+export const ZEmbedAuthCompleteStatusSchema = z.enum(['ok', 'error']);
+
+export type EmbedAuthCompleteStatus = z.infer<typeof ZEmbedAuthCompleteStatusSchema>;
+
+export const formatEmbedAuthCompletePageUrl = (status: EmbedAuthCompleteStatus) => {
+ return `${formatPath(EMBED_AUTH_COMPLETE_PAGE_PATH)}?status=${status}`;
+};
+
+// The private OAuth credentials are absent from `window.__ENV__`; the client
+// only has the derived `NEXT_PUBLIC_*_SSO_ENABLED` booleans from `createPublicEnv()`.
+const getSsoAvailability = () => {
+ if (typeof window === 'undefined') {
+ return {
+ google: IS_GOOGLE_SSO_ENABLED,
+ microsoft: IS_MICROSOFT_SSO_ENABLED,
+ oidc: IS_OIDC_SSO_ENABLED,
+ oidcProviderLabel: OIDC_PROVIDER_LABEL,
+ };
+ }
+
+ return {
+ google: env('NEXT_PUBLIC_GOOGLE_SSO_ENABLED') === 'true',
+ microsoft: env('NEXT_PUBLIC_MICROSOFT_SSO_ENABLED') === 'true',
+ oidc: env('NEXT_PUBLIC_OIDC_SSO_ENABLED') === 'true',
+ oidcProviderLabel: env('NEXT_PUBLIC_OIDC_PROVIDER_LABEL'),
+ };
+};
+
+// Display only; `/start` re-checks server side.
+export const getEmbedPopupAuthProviders = () => {
+ const sso = getSsoAvailability();
+
+ return {
+ google: sso.google && isSigninEnabledForProvider('google'),
+ microsoft: sso.microsoft && isSigninEnabledForProvider('microsoft'),
+ oidc: sso.oidc && isSigninEnabledForProvider('oidc'),
+ oidcProviderLabel: sso.oidcProviderLabel || undefined,
+ // Passkeys stay available when email/password is disabled, matching `/signin`.
+ account: !isSigninDisabledGlobally(),
+ };
+};
+
+export const EMBED_AUTH_POPUP_WINDOW_NAME = 'documenso-embed-auth';
+
+export const EMBED_AUTH_POPUP_WINDOW_FEATURES = 'popup,width=500,height=680';
+
+export const EMBED_AUTH_MESSAGE_READY = 'documenso-embed-auth:ready';
+export const EMBED_AUTH_MESSAGE_NONCE = 'documenso-embed-auth:nonce';
+
+// `complete` and `failed` are accelerators only; the iframe learns the outcome
+// via redeem polling if the opener link was severed.
+export const EMBED_AUTH_MESSAGE_COMPLETE = 'documenso-embed-auth:complete';
+export const EMBED_AUTH_MESSAGE_FAILED = 'documenso-embed-auth:failed';
+
+export const ZEmbedAuthReadyMessageSchema = z.object({
+ type: z.literal(EMBED_AUTH_MESSAGE_READY),
+});
+
+export const ZEmbedAuthNonceMessageSchema = z.object({
+ type: z.literal(EMBED_AUTH_MESSAGE_NONCE),
+ nonce: z.string().uuid(),
+});
+
+export const ZEmbedAuthCompleteMessageSchema = z.object({
+ type: z.literal(EMBED_AUTH_MESSAGE_COMPLETE),
+});
+
+export const ZEmbedAuthFailedMessageSchema = z.object({
+ type: z.literal(EMBED_AUTH_MESSAGE_FAILED),
+});
diff --git a/packages/lib/jobs/client.ts b/packages/lib/jobs/client.ts
index fd81f304a..c834fc8f8 100644
--- a/packages/lib/jobs/client.ts
+++ b/packages/lib/jobs/client.ts
@@ -23,6 +23,7 @@ import { ALERT_ORGANISATION_SEAT_DRIFT_JOB_DEFINITION } from './definitions/inte
import { BACKPORT_SUBSCRIPTION_CLAIM_JOB_DEFINITION } from './definitions/internal/backport-subscription-claims';
import { BULK_SEND_TEMPLATE_JOB_DEFINITION } from './definitions/internal/bulk-send-template';
import { CANCEL_ORGANISATION_SUBSCRIPTION_JOB_DEFINITION } from './definitions/internal/cancel-organisation-subscription';
+import { CLEANUP_AUTH_HANDOFFS_JOB_DEFINITION } from './definitions/internal/cleanup-auth-handoffs';
import { CLEANUP_RATE_LIMITS_JOB_DEFINITION } from './definitions/internal/cleanup-rate-limits';
import { EXECUTE_WEBHOOK_JOB_DEFINITION } from './definitions/internal/execute-webhook';
import { EXPIRE_RECIPIENTS_SWEEP_JOB_DEFINITION } from './definitions/internal/expire-recipients-sweep';
@@ -68,6 +69,7 @@ export const jobsClient = new JobClient([
SEND_SIGNING_REMINDERS_SWEEP_JOB_DEFINITION,
PROCESS_SIGNING_REMINDER_JOB_DEFINITION,
CLEANUP_RATE_LIMITS_JOB_DEFINITION,
+ CLEANUP_AUTH_HANDOFFS_JOB_DEFINITION,
SYNC_EMAIL_DOMAINS_JOB_DEFINITION,
ADMIN_DELETE_ORGANISATION_JOB_DEFINITION,
ALERT_ORGANISATION_SEAT_DRIFT_JOB_DEFINITION,
diff --git a/packages/lib/jobs/definitions/internal/cleanup-auth-handoffs.handler.ts b/packages/lib/jobs/definitions/internal/cleanup-auth-handoffs.handler.ts
new file mode 100644
index 000000000..cb4ad9b81
--- /dev/null
+++ b/packages/lib/jobs/definitions/internal/cleanup-auth-handoffs.handler.ts
@@ -0,0 +1,20 @@
+import { prisma } from '@documenso/prisma';
+
+import type { JobRunIO } from '../../client/_internal/job';
+import type { TCleanupAuthHandoffsJobDefinition } from './cleanup-auth-handoffs';
+
+export const run = async ({ io }: { payload: TCleanupAuthHandoffsJobDefinition; io: JobRunIO }) => {
+ const { count } = await prisma.authHandoff.deleteMany({
+ where: {
+ expiresAt: {
+ lt: new Date(),
+ },
+ },
+ });
+
+ if (count > 0) {
+ io.logger.info(`Cleaned up ${count} expired auth handoffs`);
+ } else {
+ io.logger.info('No expired auth handoffs to clean up');
+ }
+};
diff --git a/packages/lib/jobs/definitions/internal/cleanup-auth-handoffs.ts b/packages/lib/jobs/definitions/internal/cleanup-auth-handoffs.ts
new file mode 100644
index 000000000..8edd5e906
--- /dev/null
+++ b/packages/lib/jobs/definitions/internal/cleanup-auth-handoffs.ts
@@ -0,0 +1,25 @@
+import { z } from 'zod';
+
+import type { JobDefinition } from '../../client/_internal/job';
+
+const CLEANUP_AUTH_HANDOFFS_JOB_DEFINITION_ID = 'internal.cleanup-auth-handoffs';
+
+const CLEANUP_AUTH_HANDOFFS_JOB_DEFINITION_SCHEMA = z.object({});
+
+export type TCleanupAuthHandoffsJobDefinition = z.infer<typeof CLEANUP_AUTH_HANDOFFS_JOB_DEFINITION_SCHEMA>;
+
+export const CLEANUP_AUTH_HANDOFFS_JOB_DEFINITION = {
+ id: CLEANUP_AUTH_HANDOFFS_JOB_DEFINITION_ID,
+ name: 'Cleanup Auth Handoffs',
+ version: '1.0.0',
+ trigger: {
+ name: CLEANUP_AUTH_HANDOFFS_JOB_DEFINITION_ID,
+ schema: CLEANUP_AUTH_HANDOFFS_JOB_DEFINITION_SCHEMA,
+ cron: '*/15 * * * *', // Every 15 minutes.
+ },
+ handler: async ({ payload, io }) => {
+ const handler = await import('./cleanup-auth-handoffs.handler');
+
+ await handler.run({ payload, io });
+ },
+} as const satisfies JobDefinition<typeof CLEANUP_AUTH_HANDOFFS_JOB_DEFINITION_ID, TCleanupAuthHandoffsJobDefinition>;
diff --git a/packages/lib/server-only/rate-limit/rate-limits.ts b/packages/lib/server-only/rate-limit/rate-limits.ts
index 1d59e5501..89714475b 100644
--- a/packages/lib/server-only/rate-limit/rate-limits.ts
+++ b/packages/lib/server-only/rate-limit/rate-limits.ts
@@ -66,6 +66,20 @@ export const linkOrgAccountRateLimit = createRateLimit({
window: '1h',
});
+export const embedAuthStartRateLimit = createRateLimit({
+ action: 'auth.embed-start',
+ max: 100,
+ window: '15m',
+});
+
+// IP only: the nonce must never be a rate limit key (it would be persisted in plaintext).
+// The client polls every 2s, so this allows ~40 concurrent flows behind one IP.
+export const embedAuthRedeemRateLimit = createRateLimit({
+ action: 'auth.embed-redeem',
+ max: 1200,
+ window: '1m',
+});
+
// ---- Auth (Tier 3 - Authenticated, verifies secrets) ----
/**
diff --git a/packages/lib/universal/sleep.ts b/packages/lib/universal/sleep.ts
new file mode 100644
index 000000000..3e288d571
--- /dev/null
+++ b/packages/lib/universal/sleep.ts
@@ -0,0 +1 @@
+export const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
diff --git a/packages/lib/utils/env.ts b/packages/lib/utils/env.ts
index 6a10456a3..d53c61706 100644
--- a/packages/lib/utils/env.ts
+++ b/packages/lib/utils/env.ts
@@ -60,4 +60,15 @@ export const createPublicEnv = () => ({
// feature UI on a boolean.
NEXT_PUBLIC_AI_FEATURES_ENABLED:
process.env.GOOGLE_VERTEX_PROJECT_ID && process.env.GOOGLE_VERTEX_API_KEY ? 'true' : 'false',
+ NEXT_PUBLIC_GOOGLE_SSO_ENABLED:
+ process.env.NEXT_PRIVATE_GOOGLE_CLIENT_ID && process.env.NEXT_PRIVATE_GOOGLE_CLIENT_SECRET ? 'true' : 'false',
+ NEXT_PUBLIC_MICROSOFT_SSO_ENABLED:
+ process.env.NEXT_PRIVATE_MICROSOFT_CLIENT_ID && process.env.NEXT_PRIVATE_MICROSOFT_CLIENT_SECRET ? 'true' : 'false',
+ NEXT_PUBLIC_OIDC_SSO_ENABLED:
+ process.env.NEXT_PRIVATE_OIDC_WELL_KNOWN &&
+ process.env.NEXT_PRIVATE_OIDC_CLIENT_ID &&
+ process.env.NEXT_PRIVATE_OIDC_CLIENT_SECRET
+ ? 'true'
+ : 'false',
+ NEXT_PUBLIC_OIDC_PROVIDER_LABEL: process.env.NEXT_PRIVATE_OIDC_PROVIDER_LABEL ?? '',
});
diff --git a/packages/prisma/migrations/20260922002212_add_auth_handoff/migration.sql b/packages/prisma/migrations/20260922002212_add_auth_handoff/migration.sql
new file mode 100644
index 000000000..4075e4f98
--- /dev/null
+++ b/packages/prisma/migrations/20260922002212_add_auth_handoff/migration.sql
@@ -0,0 +1,16 @@
+-- CreateTable
+CREATE TABLE "AuthHandoff" (
+ "id" TEXT NOT NULL,
+ "type" TEXT NOT NULL,
+ "payload" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "expiresAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "AuthHandoff_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "AuthHandoff_expiresAt_idx" ON "AuthHandoff"("expiresAt");
+
+-- AlterTable
+ALTER TABLE "Session" ADD COLUMN "isEmbed" BOOLEAN NOT NULL DEFAULT false;
diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prisma
index 13768e34f..ef2ca786a 100644
--- a/packages/prisma/schema.prisma
+++ b/packages/prisma/schema.prisma
@@ -372,12 +372,26 @@ model Session {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
+ isEmbed Boolean @default(false)
+
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId])
@@index([sessionToken])
}
+// Short-lived, nonce-keyed relay of a secret between two browsing contexts.
+// `id` is sha256(nonce), `type` is AUTH_HANDOFF_TYPE, `payload` is encrypted JSON.
+model AuthHandoff {
+ id String @id
+ type String
+ payload String
+ createdAt DateTime @default(now())
+ expiresAt DateTime
+
+ @@index([expiresAt])
+}
+
enum DocumentStatus {
DRAFT
PENDING
diff --git a/packages/trpc/server/auth-router/create-passkey-authentication-options.ts b/packages/trpc/server/auth-router/create-passkey-authentication-options.ts
index 6b507f7ca..7d7fca1a3 100644
--- a/packages/trpc/server/auth-router/create-passkey-authentication-options.ts
+++ b/packages/trpc/server/auth-router/create-passkey-authentication-options.ts
@@ -7,6 +7,7 @@ import {
} from './create-passkey-authentication-options.types';
export const createPasskeyAuthenticationOptionsRoute = authenticatedProcedure
+ .meta({ allowEmbedSession: true })
.input(ZCreatePasskeyAuthenticationOptionsRequestSchema)
.output(ZCreatePasskeyAuthenticationOptionsResponseSchema)
.mutation(async ({ ctx, input }) => {
diff --git a/packages/trpc/server/auth-router/find-passkeys.ts b/packages/trpc/server/auth-router/find-passkeys.ts
index ff7e5be79..b903224fd 100644
--- a/packages/trpc/server/auth-router/find-passkeys.ts
+++ b/packages/trpc/server/auth-router/find-passkeys.ts
@@ -4,6 +4,7 @@ import { authenticatedProcedure } from '../trpc';
import { ZFindPasskeysRequestSchema, ZFindPasskeysResponseSchema } from './find-passkeys.types';
export const findPasskeysRoute = authenticatedProcedure
+ .meta({ allowEmbedSession: true })
.input(ZFindPasskeysRequestSchema)
.output(ZFindPasskeysResponseSchema)
.query(async ({ input, ctx }) => {
diff --git a/packages/trpc/server/auth-router/get-auth-methods.ts b/packages/trpc/server/auth-router/get-auth-methods.ts
index bf018d8b7..d30ce3eac 100644
--- a/packages/trpc/server/auth-router/get-auth-methods.ts
+++ b/packages/trpc/server/auth-router/get-auth-methods.ts
@@ -7,6 +7,7 @@ import { ZGetAuthMethodsResponseSchema } from './get-auth-methods.types';
* Get the sign in methods available to the current user.
*/
export const getAuthMethodsRoute = authenticatedProcedure
+ .meta({ allowEmbedSession: true })
.output(ZGetAuthMethodsResponseSchema)
.query(async ({ ctx }) => {
const authMethods = await getUserAuthMethods({
diff --git a/packages/trpc/server/recipient-router/schema.ts b/packages/trpc/server/recipient-router/schema.ts
index 6bb2cb6dc..1d162344d 100644
--- a/packages/trpc/server/recipient-router/schema.ts
+++ b/packages/trpc/server/recipient-router/schema.ts
@@ -181,15 +181,15 @@ export type TCompleteDocumentWithTokenMutationSchema = z.infer<typeof ZCompleteD
/**
* Discriminated response: SES envelopes return `{ status: 'SIGNED' }` after
* the in-place completion; TSP (AES/QES) envelopes return
- * `{ status: 'REDIRECT', redirectUrl }` pointing at the credential-scope
- * OAuth authorize endpoint. `{ status: 'ALREADY_SIGNED' }` is returned when
+ * `{ status: 'REDIRECT', redirectUrl, sessionId }` pointing at the credential-scope
+ * OAuth authorize endpoint for the given `CscSession`. `{ status: 'ALREADY_SIGNED' }` is returned when
* the recipient had already signed prior to this request (retries, stale
* tabs, concurrent submissions) so callers can notify the user instead of
* erroring. Frontend callers can branch on `status` — existing callers
* ignored the response and remain compatible.
*/
export const ZCompleteDocumentWithTokenResponseSchema = z.discriminatedUnion('status', [
- z.object({ status: z.literal('REDIRECT'), redirectUrl: z.string() }),
+ z.object({ status: z.literal('REDIRECT'), redirectUrl: z.string(), sessionId: z.string() }),
z.object({ status: z.literal('SIGNED') }),
z.object({ status: z.literal('ALREADY_SIGNED') }),
]);
diff --git a/packages/trpc/server/template-router/router.ts b/packages/trpc/server/template-router/router.ts
index e7a7a9d90..7da8739a3 100644
--- a/packages/trpc/server/template-router/router.ts
+++ b/packages/trpc/server/template-router/router.ts
@@ -608,6 +608,8 @@ export const templateRouter = router({
* @private
*/
createDocumentFromDirectTemplate: maybeAuthenticatedProcedure
+ // Embed direct-template signing relies on the session for `ACCOUNT` access auth.
+ .meta({ allowEmbedSession: true })
// .meta({
// openapi: {
// method: 'POST',
diff --git a/packages/trpc/server/trpc.ts b/packages/trpc/server/trpc.ts
index 2d2f8673c..3e76b447c 100644
--- a/packages/trpc/server/trpc.ts
+++ b/packages/trpc/server/trpc.ts
@@ -1,3 +1,4 @@
+import { assertNotEmbedSession } from '@documenso/auth/server/lib/session/embed-session-restrictions';
import { AppError, genericErrorCodeToTrpcErrorCodeMap } from '@documenso/lib/errors/app-error';
import { getApiTokenByToken } from '@documenso/lib/server-only/public-api/get-api-token-by-token';
import { assertUserNotDisabled } from '@documenso/lib/server-only/user/assert-user-not-disabled';
@@ -29,6 +30,12 @@ export type TrpcRouteMeta = {
successDescription?: string;
errorResponses?: number[] | Record<number, string>;
};
+ /**
+ * Embed sessions exist only to let a recipient sign inside an iframe and are
+ * rejected by `authenticatedProcedure` (and downgraded to anonymous by
+ * `maybeAuthenticatedProcedure`) unless the route opts in here.
+ */
+ allowEmbedSession?: boolean;
} & Record<string, unknown>;
const t = initTRPC
@@ -150,6 +157,10 @@ export const authenticatedMiddleware = t.middleware(async ({ ctx, next, path, me
// authenticated TRPC call here.
assertUserNotDisabled(ctx.user);
+ if (!meta?.allowEmbedSession) {
+ assertNotEmbedSession(ctx.session);
+ }
+
// Recreate the logger with a sub request ID to differentiate between batched
// requests, as well as identifying attributes so every subsequent log line
// (including errors) inherits them.
@@ -257,8 +268,11 @@ export const maybeAuthenticatedMiddleware = t.middleware(async ({ ctx, next, pat
// `maybeAuthenticatedProcedure` are signer/invite flows that key off an
// input token rather than `ctx.user`, so downgrading lets those keep
// working while routes that genuinely need an account naturally fall
- // through to their own auth checks.
- const sessionUser = ctx.user && !ctx.user.disabled ? ctx.user : null;
+ // through to their own auth checks. Embed sessions get the same treatment
+ // unless the route has opted in via `allowEmbedSession`.
+ const isEmbedSessionAllowed = !ctx.session?.isEmbed || Boolean(meta?.allowEmbedSession);
+
+ const sessionUser = ctx.user && !ctx.user.disabled && isEmbedSessionAllowed ? ctx.user : null;
const sessionRecord = sessionUser ? ctx.session : null;
// Resolve `auth` once so it stays in sync between the logger bindings and
@@ -312,6 +326,8 @@ export const adminMiddleware = t.middleware(async ({ ctx, next, path }) => {
// Disabled admins shouldn't be able to do anything either.
assertUserNotDisabled(ctx.user);
+ assertNotEmbedSession(ctx.session);
+
const isUserAdmin = isAdmin(ctx.user);
if (!isUserAdmin) {
diff --git a/packages/tsconfig/process-env.d.ts b/packages/tsconfig/process-env.d.ts
index f2a5d9957..27a0af0fb 100644
--- a/packages/tsconfig/process-env.d.ts
+++ b/packages/tsconfig/process-env.d.ts
@@ -7,12 +7,21 @@ declare namespace NodeJS {
NEXT_PRIVATE_GOOGLE_CLIENT_ID?: string;
NEXT_PRIVATE_GOOGLE_CLIENT_SECRET?: string;
+ NEXT_PRIVATE_MICROSOFT_CLIENT_ID?: string;
+ NEXT_PRIVATE_MICROSOFT_CLIENT_SECRET?: string;
+
NEXT_PRIVATE_OIDC_WELL_KNOWN?: string;
NEXT_PRIVATE_OIDC_CLIENT_ID?: string;
NEXT_PRIVATE_OIDC_CLIENT_SECRET?: string;
NEXT_PRIVATE_OIDC_PROVIDER_LABEL?: string;
NEXT_PRIVATE_OIDC_SKIP_VERIFY?: string;
+ // Derived in `createPublicEnv()`; do not set manually.
+ NEXT_PUBLIC_GOOGLE_SSO_ENABLED?: 'true' | 'false';
+ NEXT_PUBLIC_MICROSOFT_SSO_ENABLED?: 'true' | 'false';
+ NEXT_PUBLIC_OIDC_SSO_ENABLED?: 'true' | 'false';
+ NEXT_PUBLIC_OIDC_PROVIDER_LABEL?: string;
+
NEXT_PRIVATE_DATABASE_URL: string;
NEXT_PRIVATE_ENCRYPTION_KEY: string;
NEXT_PRIVATE_ENCRYPTION_SECONDARY_KEY: string;
diff --git a/turbo.json b/turbo.json
index d0bd4d274..b3b002dc4 100644
--- a/turbo.json
+++ b/turbo.json
@@ -86,6 +86,8 @@
"NEXT_PRIVATE_USE_LEGACY_SIGNING_SUBFILTER",
"NEXT_PRIVATE_GOOGLE_CLIENT_ID",
"NEXT_PRIVATE_GOOGLE_CLIENT_SECRET",
+ "NEXT_PRIVATE_MICROSOFT_CLIENT_ID",
+ "NEXT_PRIVATE_MICROSOFT_CLIENT_SECRET",
"NEXT_PRIVATE_OIDC_WELL_KNOWN",
"NEXT_PRIVATE_OIDC_CLIENT_ID",
"NEXT_PRIVATE_OIDC_CLIENT_SECRET",