Skip to content

Open source CapCut alternative.

TypeScript

fix(site): return ChatGPT sign-in to its authorization

David Le4f37c63ad891
diff --git a/site/src/app/_components/landing/AuthPage.tsx b/site/src/app/_components/landing/AuthPage.tsx
index bb87f48b..404056fc 100644
--- a/site/src/app/_components/landing/AuthPage.tsx
+++ b/site/src/app/_components/landing/AuthPage.tsx
@@ -1,6 +1,8 @@
+import { cookies } from "next/headers";
import { Suspense } from "react";
import { AuthScreen } from "@/app/_components/landing/AuthScreen";
import { CutFooter } from "@/app/cut/_components/landing/CutFooter";
+import { SIGN_IN_RETURN_COOKIE, signInReturnPath } from "@/lib/signInReturn";
export type AuthSearchParams = Promise<{
method?: string | string[];
@@ -11,8 +13,13 @@ type Props = { mode: "sign-in" | "sign-up"; searchParams: AuthSearchParams };
async function Form({ mode, searchParams }: Props) {
const { method, callbackURL } = await searchParams;
+
+ // A sign-in URL without its callback (a new tab mid-authorization) still
+ // returns to the authorization that sent this browser here.
+ const remembered = (await cookies()).get(SIGN_IN_RETURN_COOKIE)?.value;
+ const returnPath = signInReturnPath(typeof callbackURL === "string" ? callbackURL : undefined, remembered);
return <AuthScreen mode={mode} method={method === "email" ? "email" : "google"}
- callbackURL={typeof callbackURL === "string" ? callbackURL : undefined} footer={<CutFooter />} />;
+ callbackURL={returnPath} footer={<CutFooter />} />;
}
export function AuthPage(props: Props) {
diff --git a/site/src/app/_components/landing/AuthScreen.tsx b/site/src/app/_components/landing/AuthScreen.tsx
index a20e53f6..23fa6318 100644
--- a/site/src/app/_components/landing/AuthScreen.tsx
+++ b/site/src/app/_components/landing/AuthScreen.tsx
@@ -66,16 +66,20 @@ export function AuthScreen({ mode, method = "google", callbackURL, footer }: Pro
if (callbackURL) alternateParams.set("callbackURL", callbackURL);
const alternateHref = `${screenCopy.alternateHref}${alternateParams.size ? `?${alternateParams}` : ""}`;
- const handleGoogleAuth = useCallback(async () => {
- const searchParams = new URLSearchParams(window.location.search);
- const callbackURL = searchParams.get("callbackURL") ?? "/app";
+ // An app that sent someone here to sign in (ChatGPT's connection) offers
+ // email too, carrying the callback, e.g. for accounts without Google.
+ const emailParams = new URLSearchParams({ method: "email" });
+ if (callbackURL) emailParams.set("callbackURL", callbackURL);
+ const emailHref = `/${mode}?${emailParams}`;
+ const handleGoogleAuth = useCallback(async () => {
setIsPending(true);
setStatusMessage(null);
try {
await authClient.signIn.social({
- callbackURL,
+ // The streamed shell has no prop yet; its URL still carries the callback.
+ callbackURL: callbackURL ?? new URLSearchParams(window.location.search).get("callbackURL") ?? "/app",
// A brand-new account lands on the welcome sequence's own address, so
// its first paint is the sequence rather than the app home.
newUserCallbackURL: "/app/onboarding",
@@ -86,7 +90,7 @@ export function AuthScreen({ mode, method = "google", callbackURL, footer }: Pro
} finally {
setIsPending(false);
}
- }, []);
+ }, [callbackURL]);
const googleButtonWidth = Math.round(
(screenCopy.googleWidth * GOOGLE_BUTTON_HEIGHT) / 40,
@@ -94,7 +98,7 @@ export function AuthScreen({ mode, method = "google", callbackURL, footer }: Pro
const formContent = (
<>
- {method === "email" ? <EmailAuthForm mode={mode} /> : <button
+ {method === "email" ? <EmailAuthForm mode={mode} callbackURL={callbackURL} /> : <button
type="button"
aria-label={screenCopy.googleAlt}
disabled={isPending}
@@ -115,6 +119,14 @@ export function AuthScreen({ mode, method = "google", callbackURL, footer }: Pro
style={{ width: googleButtonWidth }}
/>
</button>}
+ {method === "google" && callbackURL ? (
+ <Link
+ href={emailHref}
+ className="mt-[18px] text-sm font-semibold text-ink underline underline-offset-[3px]"
+ >
+ Continue with email
+ </Link>
+ ) : null}
<p className="mt-[18px] text-sm leading-normal text-[#555]">
{screenCopy.alternateLead}{" "}
<Link
diff --git a/site/src/app/_components/landing/EmailAuthForm.tsx b/site/src/app/_components/landing/EmailAuthForm.tsx
index e6bd74d8..446be8fa 100644
--- a/site/src/app/_components/landing/EmailAuthForm.tsx
+++ b/site/src/app/_components/landing/EmailAuthForm.tsx
@@ -3,9 +3,9 @@
import { useState, type FormEvent } from "react";
import { authClient } from "@/lib/auth-client";
-type Props = { mode: "sign-in" | "sign-up" };
+type Props = { mode: "sign-in" | "sign-up"; callbackURL?: string };
-export function EmailAuthForm({ mode }: Props) {
+export function EmailAuthForm({ mode, callbackURL }: Props) {
const signingUp = mode === "sign-up";
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -19,7 +19,7 @@ export function EmailAuthForm({ mode }: Props) {
const credentials = {
email: String(data.get("email")),
password: String(data.get("password")),
- callbackURL: new URLSearchParams(window.location.search).get("callbackURL") ?? (signingUp ? "/app/onboarding" : "/app"),
+ callbackURL: callbackURL ?? (signingUp ? "/app/onboarding" : "/app"),
};
const result = signingUp
? await authClient.signUp.email({ ...credentials, name: String(data.get("name")) })
diff --git a/site/src/clients/chatgpt/server/oauthRoutes.test.ts b/site/src/clients/chatgpt/server/oauthRoutes.test.ts
new file mode 100644
index 00000000..c7d74990
--- /dev/null
+++ b/site/src/clients/chatgpt/server/oauthRoutes.test.ts
@@ -0,0 +1,44 @@
+import { expect, test } from "bun:test";
+import { SIGN_IN_RETURN_COOKIE, signInReturnPath } from "@/lib/signInReturn";
+import { SETTINGS } from "@/lib/config/registry";
+import { stubModule } from "@/lib/testing/stubModule";
+
+await stubModule<typeof import("@/lib/prisma")>("@/lib/prisma", import.meta.url, {
+ prisma: {
+ settingOverride: { findUnique: async () => ({ value: { ...SETTINGS.chatgptApp.default, enabled: true } }) },
+ } as never,
+});
+await stubModule<typeof import("@/lib/donkey-api-auth")>("@/lib/donkey-api-auth", import.meta.url, {
+ getDonkeyAuthContext: async () => null,
+});
+const { authorize } = await import("@/clients/chatgpt/server/oauthRoutes");
+const { CLIENT_ID, OAUTH_PATH } = await import("@/clients/chatgpt/server/config");
+const { pkceChallenge } = await import("@/clients/chatgpt/server/oauthPolicy");
+
+const SEE_OTHER = 303;
+
+// A signed-out person reaches sign-in, then opens the email form in a new tab.
+test("a signed-out authorization survives a sign-in that drops the callback", async () => {
+ const query = new URLSearchParams({
+ response_type: "code",
+ client_id: CLIENT_ID,
+ redirect_uri: "https://chatgpt.com/connector_platform_oauth_redirect",
+ resource: "https://donkeycut.com/api/chatgpt/mcp",
+ scope: "openid email projects:read",
+ state: "oauth_s_test",
+ code_challenge_method: "S256",
+ code_challenge: pkceChallenge("a".repeat(43)),
+ });
+ const response = await authorize(
+ new Request(`https://donkeycut.com${OAUTH_PATH}/authorize?${query}`),
+ );
+
+ expect(response.status).toBe(SEE_OTHER);
+ const signIn = new URL(response.headers.get("location")!);
+ const authorizePath = `${OAUTH_PATH}/authorize?${query}`;
+ expect(signIn.searchParams.get("callbackURL")).toBe(authorizePath);
+
+ const cookie = response.headers.get("set-cookie")!;
+ const remembered = cookie.match(new RegExp(`${SIGN_IN_RETURN_COOKIE}=([^;]+)`))![1];
+ expect(signInReturnPath(undefined, decodeURIComponent(remembered))).toBe(authorizePath);
+});
diff --git a/site/src/clients/chatgpt/server/oauthRoutes.ts b/site/src/clients/chatgpt/server/oauthRoutes.ts
index b127efd9..77cd158e 100644
--- a/site/src/clients/chatgpt/server/oauthRoutes.ts
+++ b/site/src/clients/chatgpt/server/oauthRoutes.ts
@@ -33,6 +33,7 @@ import {
OAuthRateLimitError,
} from "@/clients/chatgpt/server/oauthRateLimit";
import { identitySigner, openIdMetadata } from "@/clients/chatgpt/server/oidc";
+import { signInReturnCookie } from "@/lib/signInReturn";
const NO_STORE_HEADERS = { "Cache-Control": "no-store", Pragma: "no-cache" };
const CONSENT_COOKIE_NAME = "__Host-donkey-chatgpt-consent";
@@ -99,14 +100,21 @@ export async function authorize(request: Request) {
return oauthError("invalid_request");
}
+ // Sign-in also remembers this authorization, so a sign-in page opened
+ // without the callback (a new tab, a typed URL) still comes back here.
const identity = await getDonkeyAuthContext(request.headers);
if (!identity) {
+ const authorizePath = `${OAUTH_PATH}/authorize?${searchParams}`;
const loginUrl = new URL("/sign-in", config.issuer);
- loginUrl.searchParams.set(
- "callbackURL",
- `${OAUTH_PATH}/authorize?${searchParams}`,
- );
- return Response.redirect(loginUrl, 303);
+ loginUrl.searchParams.set("callbackURL", authorizePath);
+ return new Response(null, {
+ status: 303,
+ headers: {
+ ...NO_STORE_HEADERS,
+ Location: loginUrl.href,
+ "Set-Cookie": signInReturnCookie(authorizePath),
+ },
+ });
}
const rateLimit = checkInMemoryRateLimit({
@@ -137,7 +145,10 @@ export async function authorize(request: Request) {
},
});
- return consentPage(nonce, authorization, browserToken);
+ // Signed in now, so the remembered sign-in return has done its job.
+ const page = consentPage(nonce, authorization, browserToken);
+ page.headers.append("Set-Cookie", signInReturnCookie(null));
+ return page;
}
/** POST /api/chatgpt/oauth/authorize: explicit, browser-bound consent. */
diff --git a/site/src/lib/signInReturn.test.ts b/site/src/lib/signInReturn.test.ts
new file mode 100644
index 00000000..850b6bfc
--- /dev/null
+++ b/site/src/lib/signInReturn.test.ts
@@ -0,0 +1,21 @@
+import { expect, test } from "bun:test";
+import { signInReturnCookie, signInReturnPath } from "@/lib/signInReturn";
+
+const value = (cookie: string) => decodeURIComponent(cookie.split(";")[0].split("=")[1]);
+
+test("the URL's callback wins over the remembered one", () => {
+ const remembered = value(signInReturnCookie("/api/chatgpt/oauth/authorize?state=a"));
+ expect(signInReturnPath("/app/p/1", remembered)).toBe("/app/p/1");
+ expect(signInReturnPath(undefined, remembered)).toBe("/api/chatgpt/oauth/authorize?state=a");
+});
+
+test("only same-site paths come back from the cookie", () => {
+ expect(signInReturnPath(undefined, "https://evil.example/x")).toBeUndefined();
+ expect(signInReturnPath(undefined, "//evil.example/x")).toBeUndefined();
+ expect(signInReturnPath(undefined, "/\\evil.example")).toBeUndefined();
+ expect(signInReturnPath(undefined, undefined)).toBeUndefined();
+});
+
+test("clearing expires the cookie", () => {
+ expect(signInReturnCookie(null)).toContain("Max-Age=0");
+});
diff --git a/site/src/lib/signInReturn.ts b/site/src/lib/signInReturn.ts
new file mode 100644
index 00000000..b69516bd
--- /dev/null
+++ b/site/src/lib/signInReturn.ts
@@ -0,0 +1,20 @@
+// Where sign-in returns when the sign-in URL lost its callback, for example
+// when someone opens the email form in a new tab mid-authorization.
+export const SIGN_IN_RETURN_COOKIE = "__Host-donkey-sign-in-return";
+const SIGN_IN_RETURN_SECONDS = 900;
+
+/** Set-Cookie value that remembers a same-site path for sign-in, or clears it with null. */
+export function signInReturnCookie(path: string | null) {
+ const maxAge = path === null ? 0 : SIGN_IN_RETURN_SECONDS;
+ return `${SIGN_IN_RETURN_COOKIE}=${encodeURIComponent(path ?? "")}; Max-Age=${maxAge}; Path=/; HttpOnly; Secure; SameSite=Lax`;
+}
+
+/** The path sign-in returns to: the URL's callback, else the remembered (decoded) same-site path. */
+export function signInReturnPath(callbackURL: string | undefined, remembered: string | undefined) {
+ if (callbackURL) {
+ return callbackURL;
+ }
+
+ // Only a path on this site: "/x", never "//host" or "/\host".
+ return remembered && /^\/(?![/\\])/.test(remembered) ? remembered : undefined;
+}