Skip to content

Open source CapCut alternative.

TypeScript

feat(chatgpt): one-use codes sign the card's frame into an editor session

David Leeff676f4fb68
diff --git a/site/package-lock.json b/site/package-lock.json
index caac2ac1..7858433a 100644
--- a/site/package-lock.json
+++ b/site/package-lock.json
@@ -47,6 +47,7 @@
"@types/mdx": "^2.0.13",
"ai": "^7.0.14",
"better-auth": "1.6.11",
+ "better-call": "1.3.5",
"browser-use-sdk": "^3.8.4",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
diff --git a/site/package.json b/site/package.json
index 8a8ac3da..a6fe52db 100644
--- a/site/package.json
+++ b/site/package.json
@@ -79,6 +79,7 @@
"@types/mdx": "^2.0.13",
"ai": "^7.0.14",
"better-auth": "1.6.11",
+ "better-call": "1.3.5",
"browser-use-sdk": "^3.8.4",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
diff --git a/site/src/app/api/chatgpt/embed/route.ts b/site/src/app/api/chatgpt/embed/route.ts
new file mode 100644
index 00000000..8e0e07bb
--- /dev/null
+++ b/site/src/app/api/chatgpt/embed/route.ts
@@ -0,0 +1 @@
+export { embedEndpoint as GET } from "@/clients/chatgpt/server/embed";
diff --git a/site/src/clients/chatgpt/server/cleanup.ts b/site/src/clients/chatgpt/server/cleanup.ts
index 179cdc2a..378b9811 100644
--- a/site/src/clients/chatgpt/server/cleanup.ts
+++ b/site/src/clients/chatgpt/server/cleanup.ts
@@ -1,11 +1,17 @@
import { prisma } from "@/lib/prisma";
import { chatgptConfig } from "@/clients/chatgpt/server/config";
+import { revokeEditorSessions } from "@/clients/chatgpt/server/oauthTokens";
export async function cleanupConnections() {
const config = await chatgptConfig();
if (!config.enabled) {
return Response.json({ skipped: true });
}
+ const dead = await prisma.chatgptGrant.findMany({
+ where: { OR: [{ expiresAt: { lte: new Date() } }, { revokedAt: { not: null } }] },
+ select: { id: true },
+ });
+ await revokeEditorSessions(dead.map((grant) => grant.id));
const [grants, consent] = await Promise.all([
prisma.chatgptGrant.deleteMany({
where: {
@@ -21,7 +27,7 @@ export async function cleanupConnections() {
]);
// Keep used refresh tokens until the family expires so replay still revokes it.
const access = await prisma.chatgptToken.deleteMany({
- where: { kind: "access", expiresAt: { lte: new Date() } },
+ where: { kind: { in: ["access", "embed", "session"] }, expiresAt: { lte: new Date() } },
});
return Response.json({
grants: grants.count,
diff --git a/site/src/clients/chatgpt/server/embed.ts b/site/src/clients/chatgpt/server/embed.ts
new file mode 100644
index 00000000..d0c1eaec
--- /dev/null
+++ b/site/src/clients/chatgpt/server/embed.ts
@@ -0,0 +1,67 @@
+import { serializeSignedCookie } from "better-call";
+import { auth } from "@/lib/auth";
+import { rateLimitResponse } from "@/lib/inference/rate-limit";
+import { chatgptConfig } from "@/clients/chatgpt/server/config";
+import {
+ enforceOAuthUserLimit,
+ limitOAuthSource,
+ OAuthRateLimitError,
+} from "@/clients/chatgpt/server/oauthRateLimit";
+import { recordEditorSession, redeemEditorCode } from "@/clients/chatgpt/server/oauthTokens";
+
+const NO_STORE_HEADERS = { "Cache-Control": "no-store", Pragma: "no-cache" };
+
+/**
+ * GET /api/chatgpt/embed?code=…&project=…: the card's frame redeems its one-use
+ * code for a session and lands on the editor. The session cookie is
+ * partitioned, so it exists only inside that frame under ChatGPT: the account's
+ * own sign-in never crosses into the frame, and the frame's never leaves it.
+ */
+export async function embedEndpoint(request: Request) {
+ const config = await chatgptConfig();
+ if (!config.enabled) {
+ return new Response("ChatGPT connection is not enabled.", { status: 503, headers: NO_STORE_HEADERS });
+ }
+ const limited = limitOAuthSource(request, "embed", config.oauthRequestsPerIpMinute);
+ if (limited) return limited;
+
+ const params = new URL(request.url).searchParams;
+ const project = params.get("project") ?? "";
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(project)) {
+ return new Response("Bad request.", { status: 400, headers: NO_STORE_HEADERS });
+ }
+ const redeemed = await redeemEditorCode(params.get("code") ?? "", config);
+ if (!redeemed) {
+ return new Response("This editor link has expired. Open the project again from ChatGPT.", {
+ status: 403,
+ headers: { ...NO_STORE_HEADERS, "Content-Type": "text/plain; charset=utf-8" },
+ });
+ }
+ try {
+ enforceOAuthUserLimit(redeemed.userId, "embed", config.requestsPerMinute);
+ } catch (error) {
+ if (error instanceof OAuthRateLimitError) return rateLimitResponse(error.retryAfterSeconds);
+ throw error;
+ }
+
+ const context = await auth.$context;
+ const expiresAt = new Date(Date.now() + config.editorSessionHours * 3_600_000);
+ const session = await context.internalAdapter.createSession(redeemed.userId, false, { expiresAt }, true);
+ await recordEditorSession(redeemed.grantId, { id: session.id, expiresAt: session.expiresAt });
+ const { name, attributes } = context.authCookies.sessionToken;
+ const cookie = await serializeSignedCookie(name, session.token, context.secret, {
+ ...attributes,
+ secure: true,
+ sameSite: "none",
+ partitioned: true,
+ maxAge: config.editorSessionHours * 3600,
+ });
+ return new Response(null, {
+ status: 303,
+ headers: {
+ ...NO_STORE_HEADERS,
+ "Set-Cookie": cookie,
+ Location: `${config.issuer}/app/p/${encodeURIComponent(project)}?embed=chatgpt`,
+ },
+ });
+}
diff --git a/site/src/clients/chatgpt/server/oauth.test.ts b/site/src/clients/chatgpt/server/oauth.test.ts
index d272f6c1..6e31e76e 100644
--- a/site/src/clients/chatgpt/server/oauth.test.ts
+++ b/site/src/clients/chatgpt/server/oauth.test.ts
@@ -13,7 +13,10 @@ import {
import {
accessIdentity,
createCode,
+ createEditorCode,
exchangeToken,
+ recordEditorSession,
+ redeemEditorCode,
revokeToken,
} from "@/clients/chatgpt/server/oauthTokens";
@@ -100,15 +103,34 @@ function createTestContext() {
Object.assign(token, data);
return { count: 1 };
},
+ findMany: async ({ where }: { where: { grantId: { in: string[] }; kind: string } }) =>
+ [...tokens.values()].filter((token) => where.grantId.in.includes(token.grantId) && token.kind === where.kind),
+ deleteMany: async ({ where }: { where: { grantId: { in: string[] }; kind: string } }) => {
+ let count = 0;
+ for (const [hash, token] of tokens) {
+ if (where.grantId.in.includes(token.grantId) && token.kind === where.kind) { tokens.delete(hash); count++; }
+ }
+ return { count };
+ },
createMany: async ({ data }: { data: Omit<Token, "consumedAt">[] }) => {
for (const row of data) {
tokens.set(row.hash, { ...row, consumedAt: null });
}
},
+ create: async ({ data }: { data: Omit<Token, "consumedAt"> }) => {
+ tokens.set(data.hash, { ...data, consumedAt: null });
+ },
},
};
+ const sessions = new Set<string>(["stray"]);
const db = {
...tx,
+ session: {
+ deleteMany: async ({ where }: { where: { id: { in: string[] } } }) => {
+ for (const id of where.id.in) sessions.delete(id);
+ return { count: where.id.in.length };
+ },
+ },
$transaction: async (run: (tx: unknown) => Promise<unknown>) => run(tx),
} as unknown as typeof prisma;
const exchange = (
@@ -121,7 +143,7 @@ function createTestContext() {
redirect_uri: input.redirect_uri,
code_verifier: verifier,
});
- return { db, grants, tokens, exchange };
+ return { db, grants, tokens, sessions, exchange };
}
describe("ChatGPT OAuth boundary", () => {
@@ -175,9 +197,34 @@ describe("ChatGPT OAuth boundary", () => {
expect(await accessIdentity(result!.access_token, config, db)).toEqual({
userId: "owner",
scopes: input.scope.split(" "),
+ grantId: "grant-0",
});
expect(await accessIdentity(result!.refresh_token, config, db)).toBeNull();
});
+ test("an editor code is one use, needs write scope, and revoking the connection ends its session", async () => {
+ const { db, tokens, sessions, exchange } = createTestContext();
+ const code = await createCode("owner", { ...input, scope: "projects:read projects:write" }, config, db);
+ const pair = (await exchangeToken(exchange(code), config, db))!;
+ const identity = (await accessIdentity(pair.access_token, config, db))!;
+ const editor = await createEditorCode(identity.grantId, db);
+ expect(tokens.has(editor)).toBe(false);
+ expect(await redeemEditorCode("nope", config, db)).toBeNull();
+ expect(await redeemEditorCode(editor, config, db)).toEqual({ userId: "owner", grantId: identity.grantId });
+ expect(await redeemEditorCode(editor, config, db)).toBeNull();
+ await recordEditorSession(identity.grantId, { id: "sess", expiresAt: new Date(Date.now() + 60_000) }, db);
+ sessions.add("sess");
+ await revokeToken(pair.access_token, config, db);
+ expect(sessions.has("sess")).toBe(false);
+ expect(sessions.has("stray")).toBe(true);
+ expect([...tokens.values()].some((token) => token.kind === "session")).toBe(false);
+
+ const readOnly = createTestContext();
+ const readCode = await createCode("owner", { ...input, scope: "projects:read" }, config, readOnly.db);
+ const readPair = (await exchangeToken({ ...readOnly.exchange(readCode) }, config, readOnly.db))!;
+ const readIdentity = (await accessIdentity(readPair.access_token, config, readOnly.db))!;
+ const readEditor = await createEditorCode(readIdentity.grantId, readOnly.db);
+ expect(await redeemEditorCode(readEditor, config, readOnly.db)).toBeNull();
+ });
test("code replay revokes tokens already issued by that code", async () => {
const { db, exchange } = createTestContext();
const code = await createCode("owner", input, config, db);
diff --git a/site/src/clients/chatgpt/server/oauthRateLimit.ts b/site/src/clients/chatgpt/server/oauthRateLimit.ts
index 4b43a357..dd0bd43b 100644
--- a/site/src/clients/chatgpt/server/oauthRateLimit.ts
+++ b/site/src/clients/chatgpt/server/oauthRateLimit.ts
@@ -5,7 +5,7 @@ import {
} from "@/lib/inference/rate-limit";
import { tokenHash } from "@/clients/chatgpt/server/oauthPolicy";
-type OAuthOperation = "token" | "revoke";
+type OAuthOperation = "token" | "revoke" | "embed";
export class OAuthRateLimitError extends Error {
constructor(public readonly retryAfterSeconds: number) {
diff --git a/site/src/clients/chatgpt/server/oauthTokens.ts b/site/src/clients/chatgpt/server/oauthTokens.ts
index 7ce29178..6264843e 100644
--- a/site/src/clients/chatgpt/server/oauthTokens.ts
+++ b/site/src/clients/chatgpt/server/oauthTokens.ts
@@ -188,7 +188,7 @@ export async function accessIdentity(
return null;
}
- return { userId: grant.userId, scopes: grant.scope.split(" ") };
+ return { userId: grant.userId, scopes: grant.scope.split(" "), grantId: grant.id };
}
export async function revokeToken(
@@ -210,4 +210,89 @@ export async function revokeToken(
where: { id: token.grantId },
data: { revokedAt: new Date() },
});
+ await revokeEditorSessions([token.grantId], db);
+}
+
+const EDITOR_CODE_SECONDS = 60;
+const SESSION_REF = "session:";
+
+/** A one-use code the card's frame redeems for an editor session. */
+export async function createEditorCode(grantId: string, db = prisma) {
+ const code = newToken();
+ await db.chatgptToken.create({
+ data: {
+ hash: tokenHash(code),
+ grantId,
+ kind: "embed",
+ expiresAt: new Date(Date.now() + EDITOR_CODE_SECONDS * 1000),
+ },
+ });
+ return code;
+}
+
+export async function redeemEditorCode(
+ code: string,
+ config: ChatgptConfig,
+ db = prisma,
+) {
+ if (!/^[A-Za-z0-9_-]{43}$/.test(code)) {
+ return null;
+ }
+ const hash = tokenHash(code);
+ const token = await db.chatgptToken.findUnique({
+ where: { hash },
+ include: { grant: true },
+ });
+ if (!token || token.kind !== "embed" || token.consumedAt || token.expiresAt <= new Date()) {
+ return null;
+ }
+ const grant = token.grant;
+ if (grant.revokedAt || grant.expiresAt <= new Date()) {
+ return null;
+ }
+ if (grant.clientId !== CLIENT_ID || grant.resource !== resourceUrl(config)) {
+ return null;
+ }
+ if (!grant.scope.split(" ").includes("projects:write")) {
+ return null;
+ }
+ // One redemption: the request that marks the row first is the one it serves.
+ const claimed = await db.chatgptToken.updateMany({
+ where: { hash, consumedAt: null },
+ data: { consumedAt: new Date() },
+ });
+ if (claimed.count !== 1) {
+ return null;
+ }
+ return { userId: grant.userId, grantId: grant.id };
+}
+
+/** The editor session a code produced, kept so revoking the connection ends it. */
+export async function recordEditorSession(
+ grantId: string,
+ session: { id: string; expiresAt: Date },
+ db = prisma,
+) {
+ await db.chatgptToken.create({
+ data: { hash: `${SESSION_REF}${session.id}`, grantId, kind: "session", expiresAt: session.expiresAt },
+ });
+}
+
+export async function revokeEditorSessions(grantIds: string[], db = prisma) {
+ if (!grantIds.length) {
+ return;
+ }
+ const rows = await db.chatgptToken.findMany({
+ where: { grantId: { in: grantIds }, kind: "session" },
+ select: { hash: true },
+ });
+ if (!rows.length) {
+ return;
+ }
+ await db.session.deleteMany({
+ where: { id: { in: rows.map((row) => row.hash.slice(SESSION_REF.length)) } },
+ });
+ await db.chatgptToken.deleteMany({
+ where: { grantId: { in: grantIds }, kind: "session" },
+ });
}
diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.ts
index 57b3825e..5936b9bd 100644
--- a/site/src/lib/config/registry.ts
+++ b/site/src/lib/config/registry.ts
@@ -43,11 +43,13 @@ export const SETTINGS = defineSettings({
pollMs: z.number().int().min(1000).max(30000),
// How long a tool call waits on the worker before handing back a job id.
commandWaitMs: z.number().int().min(5000).max(240000).default(50000),
+ // How long the editor stays signed in inside the ChatGPT card.
+ editorSessionHours: z.number().int().min(1).max(72).default(12),
}).strict(),
- default: { enabled: false, issuer: "https://donkeycut.com", redirectUris: ["https://chatgpt.com/connector_platform_oauth_redirect"], accessSeconds: 3600, refreshDays: 30, requestsPerMinute: 120, oauthRequestsPerIpMinute: 600, pollMs: 2000, commandWaitMs: 50000 },
+ default: { enabled: false, issuer: "https://donkeycut.com", redirectUris: ["https://chatgpt.com/connector_platform_oauth_redirect"], accessSeconds: 3600, refreshDays: 30, requestsPerMinute: 120, oauthRequestsPerIpMinute: 600, pollMs: 2000, commandWaitMs: 50000, editorSessionHours: 12 },
public: false,
title: "ChatGPT app",
- description: "Account linking, allowed OAuth callbacks, token lifetimes, preview polling, and how long an edit call waits on the worker. Enable after the OAuth tables are deployed.",
+ description: "Account linking, allowed OAuth callbacks, token lifetimes, preview polling, how long an edit call waits on the worker, and how long the editor stays signed in inside the card. Enable after the OAuth tables are deployed.",
},
cutPreviewJobs: {
schema: z.object({ maxAttempts: z.number().int().min(1).max(10) }).strict(),