Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Do not treat a leftover session cookie as signed in

Claude3058b5fb75ac
diff --git a/e2e/signing-flow.spec.ts b/e2e/signing-flow.spec.ts
index b484fb1..c07d4a9 100644
--- a/e2e/signing-flow.spec.ts
+++ b/e2e/signing-flow.spec.ts
@@ -34,6 +34,7 @@ async function expectPdfResponse(response: {
}
test("a new install is set up, a sender sends a PDF and a recipient signs it", async ({
+ baseURL,
browser,
page,
}, testInfo) => {
@@ -204,6 +205,38 @@ test("a new install is set up, a sender sends a PDF and a recipient signs it", a
})
).status(),
).toBe(403);
+
+ // Signed in, the login page has nothing to offer and sends them on.
+ await page.goto("/login");
+ await expect(page).toHaveURL(/\/dashboard$/);
+ });
+
+ await test.step("a cookie left from a session that is gone still reaches the login page", async () => {
+ // Signed out elsewhere, expired, or from a database since replaced:
+ // the browser keeps the cookie either way. Treating it as signed in
+ // would send the visitor to the dashboard, which sends them back.
+ const staleContext = await browser.newContext();
+
+ await staleContext.addCookies([
+ {
+ name: "better-auth.session_token",
+ url: baseURL ?? "",
+ value: "no-such-session.c2lnbmF0dXJl",
+ },
+ ]);
+
+ const stalePage = await staleContext.newPage();
+
+ for (const authPage of ["/login", "/signup"]) {
+ await stalePage.goto(authPage);
+ await expect(stalePage).toHaveURL(new RegExp(`${authPage}$`));
+ }
+
+ await stalePage.goto("/login");
+ await expect(
+ stalePage.getByRole("button", { name: "Log in" }),
+ ).toBeVisible();
+ await staleContext.close();
});
await test.step("upload a PDF", async () => {
diff --git a/src/app/(auth)/login/page.tsx b/src/app/(auth)/login/page.tsx
index 725f8c4..95447d7 100644
--- a/src/app/(auth)/login/page.tsx
+++ b/src/app/(auth)/login/page.tsx
@@ -1,4 +1,5 @@
import { LoginShell } from "@/components/auth/login-shell";
+import { redirectIfSignedIn } from "@/lib/auth/server";
type LoginPageProps = {
searchParams?: Promise<{
@@ -10,6 +11,12 @@ type LoginPageProps = {
export default async function LoginPage({ searchParams }: LoginPageProps) {
const resolvedSearchParams = searchParams ? await searchParams : undefined;
+ // A link from a password reset email is for this page whoever is signed
+ // in, so it is shown as it is.
+ if (!resolvedSearchParams?.token && !resolvedSearchParams?.error) {
+ await redirectIfSignedIn();
+ }
+
return (
<LoginShell
resetError={
diff --git a/src/app/(auth)/signup/page.tsx b/src/app/(auth)/signup/page.tsx
index b7b1e65..08d5d7e 100644
--- a/src/app/(auth)/signup/page.tsx
+++ b/src/app/(auth)/signup/page.tsx
@@ -1,9 +1,12 @@
import { SignupShell } from "@/components/auth/signup-shell";
+import { redirectIfSignedIn } from "@/lib/auth/server";
import { buildBranding } from "@/lib/branding";
import { getSettings } from "@/lib/settings";
import { describeSignupPolicy } from "@/lib/signup-policy";
export default async function SignupPage() {
+ await redirectIfSignedIn();
+
const settings = await getSettings();
return (
diff --git a/src/lib/auth/server.ts b/src/lib/auth/server.ts
index bcc4401..f80b6ee 100644
--- a/src/lib/auth/server.ts
+++ b/src/lib/auth/server.ts
@@ -3,6 +3,7 @@ import { createAuthMiddleware } from "better-auth/api";
import { nextCookies } from "better-auth/next-js";
import { haveIBeenPwned } from "better-auth/plugins";
import { headers } from "next/headers";
+import { redirect, unstable_rethrow } from "next/navigation";
import { after } from "next/server";
import type { Pool } from "pg";
import { cache } from "react";
@@ -17,7 +18,10 @@ import {
import { withUserEmailLegalFooter } from "../services/email-legal-footer.ts";
import { consumeRateLimit } from "../security/rate-limit.ts";
import { getClientIpHeaderNames } from "../security/request.ts";
-import { requireConfigValue } from "../services/service-config.ts";
+import {
+ requireConfigValue,
+ ServiceConfigurationError,
+} from "../services/service-config.ts";
import { evaluateSignupRequest, getBranding } from "../settings.ts";
import {
getEnv,
@@ -476,3 +480,29 @@ const getCachedAuthSession = cache(async () => {
export function getAuthSession() {
return getCachedAuthSession();
}
+
+/**
+ * For the sign-in and sign-up pages: someone who is already signed in is
+ * sent on to their documents. This asks the auth server, so a cookie left
+ * over from a session that no longer exists does not count as signed in.
+ */
+export async function redirectIfSignedIn(): Promise<void> {
+ let signedIn = false;
+
+ try {
+ signedIn = (await getAuthSession()) !== null;
+ } catch (error) {
+ // Next.js throws to say a page cannot be built ahead of time. That is
+ // not a failure, and it is Next's to handle.
+ unstable_rethrow(error);
+
+ // Not being able to ask is no reason to fail a page that shows a form.
+ if (!(error instanceof ServiceConfigurationError)) {
+ console.error("[auth] Could not check for a session:", error);
+ }
+ }
+
+ if (signedIn) {
+ redirect("/dashboard");
+ }
+}
diff --git a/src/proxy.ts b/src/proxy.ts
index 909a074..4ddee69 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -1,5 +1,5 @@
import type { NextRequest } from "next/server";
-import { getCookieCache, getSessionCookie } from "better-auth/cookies";
+import { getCookieCache } from "better-auth/cookies";
import { NextResponse } from "next/server";
import { supportsDirectUploads } from "@/lib/services/storage/driver";
@@ -153,27 +153,32 @@ function applySecurityHeaders(response: NextResponse, pathname: string) {
return response;
}
-async function hasOptimisticSession(request: NextRequest) {
+// True only for a session the auth server would accept without looking it
+// up: its signed, short-lived copy in the cookie cache. The session token
+// cookie on its own proves nothing. It outlives a session that was signed
+// out elsewhere, expired, or belongs to a database that has been replaced,
+// and sending such a visitor to the dashboard would bounce them straight
+// back here, forever. Someone signed in whose cached copy has run out is
+// sent on by the page itself, which asks the auth server.
+async function hasVerifiedSession(request: NextRequest) {
// Resolved the same way the auth server does, so this keeps working when
// the secret is derived rather than set.
const secret = resolveAuthSecret();
- if (secret) {
- try {
- const session = await getCookieCache(request, {
- isSecure: resolveAuthUrl()?.startsWith("https://") ?? false,
- secret,
- });
-
- if (session) {
- return true;
- }
- } catch {
- // Fall back to the session token check if cookie-cache parsing fails.
- }
+ if (!secret) {
+ return false;
}
- return getSessionCookie(request) !== null;
+ try {
+ const session = await getCookieCache(request, {
+ isSecure: resolveAuthUrl()?.startsWith("https://") ?? false,
+ secret,
+ });
+
+ return session !== null;
+ } catch {
+ return false;
+ }
}
async function maybeRedirectAuthenticatedAuthRoute(request: NextRequest) {
@@ -193,7 +198,7 @@ async function maybeRedirectAuthenticatedAuthRoute(request: NextRequest) {
}
}
- const hasSession = await hasOptimisticSession(request);
+ const hasSession = await hasVerifiedSession(request);
if (!hasSession) {
return null;