Skip to content

Open source CapCut alternative.

TypeScript

feat(chatgpt): add OpenID identity sharing and resilient consent

David Le030b7c8a302f
diff --git a/docs/guides/chatgpt-app.md b/docs/guides/chatgpt-app.md
index e678e852..a4d33662 100644
--- a/docs/guides/chatgpt-app.md
+++ b/docs/guides/chatgpt-app.md
@@ -72,30 +72,24 @@ as the app's own editor on its own domain.
## Account linking
-Donkey Cut is the OAuth authorization server and MCP resource server. The account
-owner signs in and explicitly grants access on Donkey Cut. Consent is bound to the
-browser, account, callback, requested scopes, resource, and S256 challenge.
-
-Each connection owns a token family. Codes are single use; refresh tokens
-rotate. A replay revokes the family. Tokens are stored as hashes, and every
-MCP request checks expiration, revocation, resource, and scope. Revocation
-invalidates subsequent tool calls. Already issued media links retain their
-normal short lifetime. The daily authenticated cleanup removes expired grants
-and their tokens.
-
-Token exchange and revocation have separate per-user request budgets. Hosted
-requests also have per-source abuse limits using Vercel's forwarded address.
-Local servers without that address use the authenticated user limits. Source
-limits are configured through `chatgptApp.oauthRequestsPerIpMinute`.
-
-| Endpoint | Purpose |
-| --- | --- |
-| `/api/chatgpt/mcp` | Stateless MCP over HTTP POST, serving protocol 2026-07-28 requests directly and older initialize-based clients the same way |
-| `/.well-known/oauth-authorization-server` | OAuth server discovery |
-| `/.well-known/oauth-protected-resource/api/chatgpt/mcp` | MCP resource discovery |
-| `/api/chatgpt/oauth/authorize` | Login and explicit consent |
-| `/api/chatgpt/oauth/token` | Code exchange and refresh rotation |
-| `/api/chatgpt/oauth/revoke` | Revoke a connection using its credential |
+Donkey Cut supplies the account identity to ChatGPT through OpenID Connect.
+The user signs in and consents to project access and identity sharing. The
+`openid` and `email` scopes expose the account ID, email, and stored verification
+status through `/api/chatgpt/oauth/userinfo`. Unverified accounts can connect;
+profile settings offer email verification.
+
+Discovery lives at `/.well-known/openid-configuration` and
+`/.well-known/oauth-authorization-server`. Configure `CHATGPT_OIDC_PRIVATE_KEY`
+with a PKCS#8 RSA private key of at least 2048 bits before deploying. Code
+exchange signs an ID token bound to the client and requested nonce; the public
+key is served at `/api/chatgpt/oauth/jwks`.
+
+Consent binds the browser, account, callback, scopes, resource, and S256 challenge.
+Codes are single use, refresh tokens rotate, and replay revokes the connection.
+Tokens are hashed in storage. MCP and UserInfo check expiration, revocation,
+resource, and scopes on every request. Source and account rate limits apply;
+daily cleanup removes expired grants, tokens, and challenges. Revocation leaves
+already issued media links valid until their normal expiry.
## Deployment and verification
@@ -111,15 +105,11 @@ through the authenticated hosted API.
Create a ChatGPT developer-mode app pointing at
`https://donkeycut.com/api/chatgpt/mcp`. Upload `site/public/chatgpt-app-icon.png`
-as the app icon: 256×256, under 10 KB, a full-bleed white square with square
-corners, because ChatGPT applies its own rounded mask, and the mark inside a
-safe area so the mask never clips it. Use the predefined public OAuth client
+as the app icon. Use the predefined public OAuth client
ID `donkey-chatgpt`, no client secret, and scopes
-`projects:read previews:render projects:write`. The app listing's description
-should say what the server instructions say: Donkey Cut is an open-source video
-editor (Apache 2.0, github.com/DonkeyCut/Donkey) that ChatGPT can edit with
-directly; editing, previews and exports are free, hosted AI generation spends
-credits, and cloud storage counts against the account's allowance.
+`projects:read previews:render projects:write openid email`. The listing
+should describe supported editing and disclose generation credits and storage
+limits.
Configure the exact redirect URI supplied by ChatGPT in `chatgptApp.redirectUris`.
The default is ChatGPT's stable callback; discovery advertises issuer
identification, and every authorization redirect includes `iss`. The embedded
diff --git a/site/.env.example b/site/.env.example
index 856b44b3..fe19cc95 100644
--- a/site/.env.example
+++ b/site/.env.example
@@ -3,6 +3,10 @@ DIRECT_URL="postgresql://postgres:[PASSWORD]@db.[PROJECT-REF].supabase.co:5432/p
BETTER_AUTH_SECRET="replace-with-a-long-random-secret"
+# ChatGPT OpenID ID-token signing: PKCS#8 PEM RSA private key (2048+ bits).
+# Generate outside the repository: openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072
+CHATGPT_OIDC_PRIVATE_KEY="replace-with-private-key-pem"
+
# Vercel sends this as a bearer token on cron invocations; the cron routes
# (analytics run, cut-cloud gc) reject requests without it.
CRON_SECRET="replace-with-a-long-random-secret"
diff --git a/site/scripts/eval-chatgpt-oauth.ts b/site/scripts/eval-chatgpt-oauth.ts
index cf53fc56..f57958d7 100644
--- a/site/scripts/eval-chatgpt-oauth.ts
+++ b/site/scripts/eval-chatgpt-oauth.ts
@@ -1,6 +1,5 @@
import assert from "node:assert/strict";
import { mock } from "bun:test";
-import { chromium } from "playwright";
import type {
DonkeyAuthenticatedRequest,
DonkeyAuthHandler,
@@ -53,6 +52,7 @@ const config = {
mock.module("@/clients/chatgpt/server/config", () => ({
CLIENT_ID: "donkey-chatgpt",
SCOPES: ["projects:read", "previews:render"],
+ PROJECT_SCOPES: ["projects:read", "previews:render"],
OAUTH_PATH: oauthPath,
chatgptConfig: async () => config,
resourceUrl: () => resource,
@@ -145,6 +145,99 @@ for (const [operation, endpoint] of [
assert.equal(tokenExchanges, 2);
assert.equal(revocations, 2);
+config.requestsPerMinute = 100;
+const consentUrl = (state: string) => {
+ const url = new URL(`${oauthPath}/authorize`, issuer);
+ url.search = new URLSearchParams({
+ response_type: "code",
+ client_id: "donkey-chatgpt",
+ redirect_uri: redirectUri,
+ scope: "projects:read previews:render",
+ state,
+ code_challenge: "a".repeat(43),
+ code_challenge_method: "S256",
+ resource,
+ }).toString();
+ return url;
+};
+const openConsent = async (state: string, browserCookie = "") => {
+ const response = await authorize(
+ new Request(consentUrl(state), { headers: { Cookie: browserCookie } }),
+ );
+ assert.equal(response.status, 200);
+ const html = await response.text();
+ const nonce = /name="nonce" value="([A-Za-z0-9_-]+)"/.exec(html)?.[1];
+ assert.ok(nonce);
+ const cookie = response.headers.get("set-cookie")!.split(";")[0];
+ return { nonce, cookie };
+};
+const submitConsent = (
+ nonce: string,
+ cookie: string,
+ decision = "allow",
+ origin = issuer,
+) =>
+ consent(
+ new Request(`${issuer}${oauthPath}/authorize`, {
+ method: "POST",
+ headers: {
+ Origin: origin,
+ Cookie: cookie,
+ "Content-Type": "application/x-www-form-urlencoded",
+ },
+ body: new URLSearchParams({ nonce, decision }),
+ }) as DonkeyAuthenticatedRequest,
+ );
+const first = await openConsent("first-tab");
+const second = await openConsent("second-tab", first.cookie);
+const jar = second.cookie;
+assert.equal(
+ (
+ await submitConsent(
+ first.nonce,
+ "__Host-donkey-chatgpt-consent=" + "b".repeat(43),
+ )
+ ).status,
+ 400,
+);
+assert.equal(
+ (await submitConsent(first.nonce, jar, "allow", "https://attacker.test"))
+ .status,
+ 400,
+);
+for (const [page, state] of [
+ [first, "first-tab"],
+ [second, "second-tab"],
+] as const) {
+ const response = await submitConsent(page.nonce, jar);
+ assert.equal(response.status, 303);
+ assert.equal(
+ new URL(response.headers.get("location")!).searchParams.get("state"),
+ state,
+ );
+ assert.equal(
+ response.headers.get("set-cookie"),
+ null,
+ "Completing one connection must leave other tabs usable",
+ );
+ assert.equal((await submitConsent(page.nonce, jar)).status, 400);
+}
+const stale = await openConsent("expired-tab");
+for (const challenge of challenges.values()) challenge.expiresAt = new Date(0);
+const expired = await submitConsent(stale.nonce, stale.cookie);
+assert.equal(expired.status, 400);
+assert.match(await expired.text(), /start.*again/i);
+challenges.clear();
+issuedCodes = 0;
+console.log(
+ "PASS: parallel consent tabs, cookie binding, foreign origins, replay, and expired-page recovery.",
+);
+if (process.argv.includes("--http-only")) {
+ appServer.stop(true);
+ callbackServer.stop(true);
+ process.exit(0);
+}
+const { chromium } = await import("playwright");
const browser = await chromium.launch();
try {
diff --git a/site/src/app/.well-known/openid-configuration/route.ts b/site/src/app/.well-known/openid-configuration/route.ts
new file mode 100644
index 00000000..ebc64f56
--- /dev/null
+++ b/site/src/app/.well-known/openid-configuration/route.ts
@@ -0,0 +1 @@
+export { authorizationMetadata as GET } from "@/clients/chatgpt/server/oauthRoutes";
diff --git a/site/src/app/api/chatgpt/oauth/jwks/route.ts b/site/src/app/api/chatgpt/oauth/jwks/route.ts
new file mode 100644
index 00000000..943473c9
--- /dev/null
+++ b/site/src/app/api/chatgpt/oauth/jwks/route.ts
@@ -0,0 +1 @@
+export { identityKeys as GET } from "@/clients/chatgpt/server/oauthRoutes";
diff --git a/site/src/app/api/chatgpt/oauth/userinfo/route.ts b/site/src/app/api/chatgpt/oauth/userinfo/route.ts
new file mode 100644
index 00000000..8bb08066
--- /dev/null
+++ b/site/src/app/api/chatgpt/oauth/userinfo/route.ts
@@ -0,0 +1 @@
+export { userInfoEndpoint as GET, userInfoEndpoint as POST } from "@/clients/chatgpt/server/userInfo";
diff --git a/site/src/app/legal/PrivacyPolicy.mdx b/site/src/app/legal/PrivacyPolicy.mdx
index 959380ee..b72a2449 100644
--- a/site/src/app/legal/PrivacyPolicy.mdx
+++ b/site/src/app/legal/PrivacyPolicy.mdx
@@ -182,6 +182,8 @@ We also may need to share your personal information in the following situations:
- **With Your Direction or Consent.** We may share information when you direct us to do so, such as when you share a project or a link to it, use a feature that calls a model provider, import media from a third-party service, or request support.
+- **Connected ChatGPT Accounts.** When you connect Donkey Cut to ChatGPT and approve identity sharing, we provide OpenAI with your Donkey Cut account ID, email address, and email verification status for account linking and workspace restrictions. Project information and editing results are shared according to the access you approve. Disconnecting the integration stops future access through that connection.
+
### 5. WHAT IS OUR STANCE ON THIRD-PARTY WEBSITES?
**In Short:** _We are not responsible for the safety of any information that you share with third parties that we may link to or interact with through our Services, but are not affiliated with, our Services._
diff --git a/site/src/clients/chatgpt/server/cleanup.ts b/site/src/clients/chatgpt/server/cleanup.ts
index 378b9811..53fad249 100644
--- a/site/src/clients/chatgpt/server/cleanup.ts
+++ b/site/src/clients/chatgpt/server/cleanup.ts
@@ -20,7 +20,10 @@ export async function cleanupConnections() {
}),
prisma.verification.deleteMany({
where: {
- identifier: { startsWith: "chatgpt-consent:" },
+ OR: [
+ { identifier: { startsWith: "chatgpt-consent:" } },
+ { identifier: "chatgpt-oidc-code" },
+ ],
expiresAt: { lte: new Date() },
},
}),
diff --git a/site/src/clients/chatgpt/server/config.ts b/site/src/clients/chatgpt/server/config.ts
index fbdf8446..2f09a688 100644
--- a/site/src/clients/chatgpt/server/config.ts
+++ b/site/src/clients/chatgpt/server/config.ts
@@ -2,7 +2,8 @@ import { prisma } from "@/lib/prisma";
import { resolveSettings } from "@/lib/config/resolve";
export const CLIENT_ID = "donkey-chatgpt";
-export const SCOPES = ["projects:read", "previews:render", "projects:write"] as const;
+export const PROJECT_SCOPES = ["projects:read", "previews:render", "projects:write"] as const;
+export const SCOPES = [...PROJECT_SCOPES, "openid", "email"] as const;
export const MCP_PATH = "/api/chatgpt/mcp";
export const OAUTH_PATH = "/api/chatgpt/oauth";
export const RESOURCE_METADATA_PATH =
diff --git a/site/src/clients/chatgpt/server/oauth.test.ts b/site/src/clients/chatgpt/server/oauth.test.ts
index 6e31e76e..fc1efd9c 100644
--- a/site/src/clients/chatgpt/server/oauth.test.ts
+++ b/site/src/clients/chatgpt/server/oauth.test.ts
@@ -1,4 +1,7 @@
import { describe, expect, test } from "bun:test";
+import { createPublicKey, generateKeyPairSync, verify } from "node:crypto";
+import { identitySigner, openIdMetadata } from "@/clients/chatgpt/server/oidc";
+import { userInfoResponse } from "@/clients/chatgpt/server/userInfo";
import type { prisma } from "@/lib/prisma";
import { SETTINGS } from "@/lib/config/registry";
import { CLIENT_ID, resourceUrl } from "@/clients/chatgpt/server/config";
@@ -57,7 +60,18 @@ type Token = {
function createTestContext() {
const grants = new Map<string, Grant>(),
tokens = new Map<string, Token>();
+ const contexts = new Map<string, { id: string; identifier: string; value: string; expiresAt: Date }>();
+ const user = { id: "owner", email: "[email protected]", emailVerified: false };
const tx = {
+ user: {
+ findUnique: async () => user,
+ findUniqueOrThrow: async () => user,
+ },
+ verification: {
+ create: async ({ data }: { data: { id: string; identifier: string; value: string; expiresAt: Date } }) => contexts.set(data.id, data),
+ findUnique: async ({ where }: { where: { id: string } }) => contexts.get(where.id) ?? null,
+ deleteMany: async ({ where }: { where: { id: string } }) => ({ count: contexts.delete(where.id) ? 1 : 0 }),
+ },
chatgptGrant: {
create: async ({
data,
@@ -143,9 +157,71 @@ function createTestContext() {
redirect_uri: input.redirect_uri,
code_verifier: verifier,
});
- return { db, grants, tokens, sessions, exchange };
+ return { db, grants, tokens, sessions, exchange, user, contexts };
}
+test("OpenID code exchange signs the consented identity and nonce; UserInfo follows live verification and revocation", async () => {
+ const priorKey = process.env.CHATGPT_OIDC_PRIVATE_KEY;
+ const { privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
+ process.env.CHATGPT_OIDC_PRIVATE_KEY = privateKey.export({ type: "pkcs8", format: "pem" }).toString();
+ try {
+ const { db, exchange, user, contexts, tokens } = createTestContext();
+ const authorization = { ...input, scope: "projects:read openid email", nonce: "client-nonce" };
+ expect(authorizeInput(new URLSearchParams(authorization), config)).toEqual(authorization);
+ for (const patch of [{ scope: "projects:read email" }, { scope: "projects:read" }, { nonce: "" }, { prompt: "none" }]) {
+ expect(authorizeInput(new URLSearchParams({ ...authorization, ...patch }), config)).toBeNull();
+ }
+ const metadata = openIdMetadata(config);
+ expect(metadata.scopes_supported).toContain("openid");
+ expect(metadata.scopes_supported).toContain("email");
+ expect(metadata.userinfo_endpoint).toBe(`${config.issuer}/api/chatgpt/oauth/userinfo`);
+ const code = await createCode("owner", authorization, config, db);
+ const pair = (await exchangeToken(exchange(code), config, db))!;
+ const [header, payload, signature] = pair.id_token!.split(".");
+ const jwk = identitySigner().jwk;
+ expect(Object.hasOwn(jwk, "d")).toBe(false);
+ expect(JSON.parse(Buffer.from(header, "base64url").toString())).toMatchObject({ alg: "RS256", kid: jwk.kid });
+ expect(verify("RSA-SHA256", Buffer.from(`${header}.${payload}`), createPublicKey({ key: jwk, format: "jwk" }), Buffer.from(signature, "base64url"))).toBe(true);
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString());
+ expect(claims).toMatchObject({ sub: "owner", iss: config.issuer, aud: CLIENT_ID, nonce: "client-nonce", email: user.email, email_verified: false });
+ expect(claims.exp).toBeGreaterThan(claims.iat);
+ expect(contexts.size).toBe(0);
+ const info = (credential: string, extraConfig = config) => userInfoResponse(new Request(metadata.userinfo_endpoint, { headers: { Authorization: `Bearer ${credential}` } }), extraConfig, db);
+ const response = await info(pair.access_token);
+ expect(response.headers.get("cache-control")).toBe("no-store");
+ expect(await response.json()).toEqual({ sub: "owner", email: user.email, email_verified: false });
+ user.emailVerified = true;
+ expect(await (await info(pair.access_token)).json()).toMatchObject({ email_verified: true });
+ expect((await info(pair.refresh_token)).status).toBe(401);
+ expect((await info(code)).status).toBe(401);
+ expect((await info(pair.access_token, { ...config, issuer: "https://other.test" })).status).toBe(401);
+ expect((await info(pair.access_token, { ...config, enabled: false })).status).toBe(503);
+ const missing = await userInfoResponse(new Request(metadata.userinfo_endpoint), config, db);
+ expect(missing.status).toBe(401);
+ expect(missing.headers.get("www-authenticate")).toContain("invalid_token");
+
+ const subjectCode = await createCode("owner", { ...input, scope: "projects:read openid" }, config, db);
+ const subjectPair = (await exchangeToken(exchange(subjectCode), config, db))!;
+ expect(await (await info(subjectPair.access_token)).json()).toEqual({ sub: "owner" });
+ const subjectClaims = JSON.parse(Buffer.from(subjectPair.id_token!.split(".")[1], "base64url").toString());
+ expect(Object.hasOwn(subjectClaims, "email")).toBe(false);
+ expect(Object.hasOwn(subjectClaims, "nonce")).toBe(false);
+ const readCode = await createCode("owner", input, config, db);
+ const readPair = (await exchangeToken(exchange(readCode), config, db))!;
+ expect(Object.hasOwn(readPair, "id_token")).toBe(false);
+ expect((await info(readPair.access_token)).status).toBe(403);
+ const rotated = (await exchangeToken({ grant_type: "refresh_token", client_id: CLIENT_ID, resource: input.resource, refresh_token: pair.refresh_token }, config, db))!;
+ expect(await (await info(rotated.access_token)).json()).toMatchObject({ email_verified: true });
+ tokens.get(tokenHash(pair.access_token))!.expiresAt = new Date(0);
+ expect((await info(pair.access_token)).status).toBe(401);
+ await revokeToken(rotated.access_token, config, db);
+ expect((await info(rotated.access_token)).status).toBe(401);
+ } finally {
+ if (priorKey === undefined) delete process.env.CHATGPT_OIDC_PRIVATE_KEY;
+ else process.env.CHATGPT_OIDC_PRIVATE_KEY = priorKey;
+ }
+});
+
describe("ChatGPT OAuth boundary", () => {
test("authorization accepts only exact callbacks, resource, public client, and S256", () => {
expect(authorizeInput(new URLSearchParams(input), config)).toEqual(input);
diff --git a/site/src/clients/chatgpt/server/oauthPolicy.ts b/site/src/clients/chatgpt/server/oauthPolicy.ts
index df97cb8a..cdf9a10d 100644
--- a/site/src/clients/chatgpt/server/oauthPolicy.ts
+++ b/site/src/clients/chatgpt/server/oauthPolicy.ts
@@ -27,6 +27,8 @@ export const authorizationSchema = z.object({
code_challenge: z.string().regex(/^[A-Za-z0-9_-]{43}$/),
code_challenge_method: z.literal("S256"),
resource: z.url(),
+ nonce: z.string().min(1).max(2048).optional(),
+ prompt: z.literal("consent").optional(),
});
export type Authorization = z.infer<typeof authorizationSchema>;
@@ -52,6 +54,8 @@ export function authorizeInput(
if (!scopes.includes("projects:read")) {
return null;
}
+ if (scopes.includes("email") && !scopes.includes("openid")) return null;
+ if (input.nonce !== undefined && !scopes.includes("openid")) return null;
const hasUnknownScope = scopes.some(
(scope) => !SCOPES.some((known) => known === scope),
);
diff --git a/site/src/clients/chatgpt/server/oauthRateLimit.ts b/site/src/clients/chatgpt/server/oauthRateLimit.ts
index dd0bd43b..93c2c930 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" | "embed";
+type OAuthOperation = "token" | "revoke" | "embed" | "userinfo";
export class OAuthRateLimitError extends Error {
constructor(public readonly retryAfterSeconds: number) {
diff --git a/site/src/clients/chatgpt/server/oauthRoutes.ts b/site/src/clients/chatgpt/server/oauthRoutes.ts
index 9a61abae..b127efd9 100644
--- a/site/src/clients/chatgpt/server/oauthRoutes.ts
+++ b/site/src/clients/chatgpt/server/oauthRoutes.ts
@@ -10,7 +10,7 @@ import {
CLIENT_ID,
chatgptConfig,
OAUTH_PATH,
- SCOPES,
+ PROJECT_SCOPES,
resourceUrl,
} from "@/clients/chatgpt/server/config";
import {
@@ -32,6 +32,7 @@ import {
limitOAuthSource,
OAuthRateLimitError,
} from "@/clients/chatgpt/server/oauthRateLimit";
+import { identitySigner, openIdMetadata } from "@/clients/chatgpt/server/oidc";
const NO_STORE_HEADERS = { "Cache-Control": "no-store", Pragma: "no-cache" };
const CONSENT_COOKIE_NAME = "__Host-donkey-chatgpt-consent";
@@ -39,6 +40,10 @@ const consentSchema = z.object({
nonce: z.string().regex(/^[A-Za-z0-9_-]{43}$/),
decision: z.enum(["allow", "deny"]),
});
+const challengeSchema = z.object({
+ authorization: authorizationSchema,
+ browserTokenHash: z.string().regex(/^[a-f0-9]{64}$/),
+});
export async function authorizationMetadata() {
await connection();
@@ -47,20 +52,17 @@ export async function authorizationMetadata() {
return oauthError("temporarily_unavailable", 503);
}
- const baseUrl = `${config.issuer}${OAUTH_PATH}`;
+ identitySigner();
+ return Response.json(openIdMetadata(config), { headers: NO_STORE_HEADERS });
+}
+
+/** GET /api/chatgpt/oauth/jwks: public keys for verifying ID tokens. */
+export async function identityKeys() {
+ await connection();
+ const config = await chatgptConfig();
+ if (!config.enabled) return oauthError("temporarily_unavailable", 503);
return Response.json(
- {
- issuer: config.issuer,
- authorization_endpoint: `${baseUrl}/authorize`,
- token_endpoint: `${baseUrl}/token`,
- revocation_endpoint: `${baseUrl}/revoke`,
- response_types_supported: ["code"],
- grant_types_supported: ["authorization_code", "refresh_token"],
- code_challenge_methods_supported: ["S256"],
- token_endpoint_auth_methods_supported: ["none"],
- authorization_response_iss_parameter_supported: true,
- scopes_supported: SCOPES,
- },
+ { keys: [identitySigner().jwk] },
{ headers: NO_STORE_HEADERS },
);
}
@@ -76,7 +78,7 @@ export async function protectedResourceMetadata() {
{
resource: resourceUrl(config),
authorization_servers: [config.issuer],
- scopes_supported: SCOPES,
+ scopes_supported: PROJECT_SCOPES,
bearer_methods_supported: ["header"],
resource_name: "Donkey Cut",
},
@@ -117,6 +119,8 @@ export async function authorize(request: Request) {
}
const nonce = newToken();
+ const browserToken =
+ consentBrowserToken(request.headers.get("cookie")) ?? newToken();
const identifier = `chatgpt-consent:${identity.userId}`;
await prisma.verification.deleteMany({
where: { identifier, expiresAt: { lte: new Date() } },
@@ -125,12 +129,15 @@ export async function authorize(request: Request) {
data: {
id: `chatgpt:${tokenHash(nonce)}`,
identifier,
- value: JSON.stringify(authorization),
+ value: JSON.stringify({
+ authorization,
+ browserTokenHash: tokenHash(browserToken),
+ }),
expiresAt: new Date(Date.now() + 600_000),
},
});
- return consentPage(nonce, authorization);
+ return consentPage(nonce, authorization, browserToken);
}
/** POST /api/chatgpt/oauth/authorize: explicit, browser-bound consent. */
@@ -153,29 +160,31 @@ export const consent = withDonkeyAuth(async (request) => {
}
const { nonce, decision } = parsed.data;
- const cookieHeader = request.headers.get("cookie");
- const consentCookieValue = cookieHeader
- ?.split(";")
- .map((cookie) => cookie.trim())
- .find((cookie) => cookie.startsWith(`${CONSENT_COOKIE_NAME}=`))
- ?.slice(CONSENT_COOKIE_NAME.length + 1);
- if (!consentCookieValue || !sameSecret(consentCookieValue, nonce)) {
- return oauthError("invalid_request");
- }
+ const browserToken = consentBrowserToken(request.headers.get("cookie"));
+ if (!browserToken) return expiredConsent();
const challengeId = `chatgpt:${tokenHash(nonce)}`;
const challenge = await prisma.verification.findUnique({
where: { id: challengeId },
});
if (!challenge || challenge.expiresAt <= new Date()) {
- return oauthError("invalid_request");
+ return expiredConsent();
}
if (challenge.identifier !== `chatgpt-consent:${request.donkey.userId}`) {
- return oauthError("invalid_request");
+ return expiredConsent();
}
// Revalidate against current settings before issuing a code.
- const authorization = authorizationSchema.parse(JSON.parse(challenge.value));
+ const parsedChallenge = challengeSchema.safeParse(
+ JSON.parse(challenge.value),
+ );
+ if (
+ !parsedChallenge.success ||
+ !sameSecret(parsedChallenge.data.browserTokenHash, tokenHash(browserToken))
+ ) {
+ return expiredConsent();
+ }
+ const { authorization } = parsedChallenge.data;
if (!authorizeInput(new URLSearchParams(authorization), config)) {
return oauthError("invalid_request");
}
@@ -184,7 +193,7 @@ export const consent = withDonkeyAuth(async (request) => {
where: { id: challengeId, expiresAt: { gt: new Date() } },
});
if (!consumed.count) {
- return oauthError("invalid_request");
+ return expiredConsent();
}
const callbackUrl = new URL(authorization.redirect_uri);
@@ -202,7 +211,6 @@ export const consent = withDonkeyAuth(async (request) => {
headers: {
...NO_STORE_HEADERS,
Location: callbackUrl.href,
- "Set-Cookie": consentCookie("", 0),
},
});
});
@@ -322,7 +330,38 @@ function consentCookie(value: string, maxAgeSeconds: number) {
return `${CONSENT_COOKIE_NAME}=${value}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${maxAgeSeconds}`;
}
-function consentPage(nonce: string, authorization: Authorization) {
+function consentBrowserToken(header: string | null) {
+ const matches = header
+ ?.split(";")
+ .map((cookie) => cookie.trim())
+ .filter((cookie) => cookie.startsWith(`${CONSENT_COOKIE_NAME}=`));
+ const value =
+ matches?.length === 1
+ ? matches[0].slice(CONSENT_COOKIE_NAME.length + 1)
+ : undefined;
+ return value && /^[A-Za-z0-9_-]{43}$/.test(value) ? value : null;
+}
+
+function expiredConsent() {
+ return new Response(
+ `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Restart connection</title></head><body><h1>Start the connection again</h1><p>This connection page expired or your signed-in account changed. Return to OpenAI and start the connection again.</p></body></html>`,
+ {
+ status: 400,
+ headers: {
+ ...NO_STORE_HEADERS,
+ "Content-Type": "text/html; charset=utf-8",
+ "Content-Security-Policy":
+ "default-src 'none'; frame-ancestors 'none'; base-uri 'none'",
+ },
+ },
+ );
+}
+
+function consentPage(
+ nonce: string,
+ authorization: Authorization,
+ browserToken: string,
+) {
const scopes = authorization.scope.split(" ");
const access = scopes.includes("projects:write") ? "view and edit" : "view";
const escapedNonce = nonce.replace(
@@ -354,7 +393,7 @@ function consentPage(nonce: string, authorization: Authorization) {
</head>
<body>
<h1><img src="/donkey-logo.svg" alt="">Donkey Cut</h1>
- <p>Connect to ChatGPT. ChatGPT can ${access} your projects.</p>
+ <p>ChatGPT can ${access} your projects${scopes.includes("openid") ? ` and read your account information${scopes.includes("email") ? ", including your email address" : ""}` : ""}.</p>
<form method="post" action="${OAUTH_PATH}/authorize">
<input type="hidden" name="nonce" value="${escapedNonce}">
<button name="decision" value="allow">Connect</button>
@@ -378,7 +417,7 @@ function consentPage(nonce: string, authorization: Authorization) {
headers: {
...NO_STORE_HEADERS,
"Content-Type": "text/html; charset=utf-8",
- "Set-Cookie": consentCookie(nonce, 600),
+ "Set-Cookie": consentCookie(browserToken, 600),
"Content-Security-Policy": contentSecurityPolicy,
// Preserve the same-origin POST's Origin for consent validation.
"Referrer-Policy": "strict-origin-when-cross-origin",
diff --git a/site/src/clients/chatgpt/server/oauthTokens.ts b/site/src/clients/chatgpt/server/oauthTokens.ts
index 6264843e..b9ab80cc 100644
--- a/site/src/clients/chatgpt/server/oauthTokens.ts
+++ b/site/src/clients/chatgpt/server/oauthTokens.ts
@@ -15,6 +15,10 @@ import {
} from "@/clients/chatgpt/server/oauthPolicy";
import { enforceOAuthUserLimit } from "@/clients/chatgpt/server/oauthRateLimit";
+import { identitySigner } from "@/clients/chatgpt/server/oidc";
+import { z } from "zod";
+
+const oidcCodeSchema = z.object({ nonce: z.string().optional() });
/** The code and every rotated token belong to one revocable connection. */
export async function createCode(
@@ -23,24 +27,37 @@ export async function createCode(
config: ChatgptConfig,
db = prisma,
) {
+ const openid = authorization.scope.split(" ").includes("openid");
+ if (openid) identitySigner();
const code = newToken();
- await db.chatgptGrant.create({
- data: {
- userId,
- clientId: authorization.client_id,
- resource: authorization.resource,
- scope: authorization.scope,
- redirectUri: authorization.redirect_uri,
- challenge: authorization.code_challenge,
- expiresAt: new Date(Date.now() + config.refreshDays * 86_400_000),
- tokens: {
- create: {
- hash: tokenHash(code),
- kind: "code",
- expiresAt: new Date(Date.now() + 300_000),
+ await db.$transaction(async (tx) => {
+ await tx.chatgptGrant.create({
+ data: {
+ userId,
+ clientId: authorization.client_id,
+ resource: authorization.resource,
+ scope: authorization.scope,
+ redirectUri: authorization.redirect_uri,
+ challenge: authorization.code_challenge,
+ expiresAt: new Date(Date.now() + config.refreshDays * 86_400_000),
+ tokens: {
+ create: {
+ hash: tokenHash(code),
+ kind: "code",
+ expiresAt: new Date(Date.now() + 300_000),
+ },
},
},
- },
+ });
+ if (openid)
+ await tx.verification.create({
+ data: {
+ id: `chatgpt-oidc:${tokenHash(code)}`,
+ identifier: "chatgpt-oidc-code",
+ value: JSON.stringify({ nonce: authorization.nonce }),
+ expiresAt: new Date(Date.now() + 300_000),
+ },
+ });
});
return code;
}
@@ -102,6 +119,31 @@ export async function exchangeToken(
return null;
}
+ const scopes = grant.scope.split(" ");
+ let idToken: string | undefined;
+ if (!isRefresh && scopes.includes("openid")) {
+ const contextId = `chatgpt-oidc:${hash}`;
+ const context = await tx.verification.findUnique({
+ where: { id: contextId },
+ });
+ if (!context || context.expiresAt <= new Date()) return null;
+ const { nonce } = oidcCodeSchema.parse(JSON.parse(context.value));
+ const user = await tx.user.findUniqueOrThrow({
+ where: { id: grant.userId },
+ select: { id: true, email: true, emailVerified: true },
+ });
+ idToken = identitySigner().sign(
+ user,
+ scopes,
+ config.issuer,
+ Math.min(
+ config.accessSeconds,
+ Math.floor((grant.expiresAt.getTime() - Date.now()) / 1000),
+ ),
+ nonce,
+ );
+ }
+
// Throttling leaves the credential usable when this user's window resets.
enforceOAuthUserLimit(grant.userId, "token", config.requestsPerMinute);
@@ -118,7 +160,12 @@ export async function exchangeToken(
return null;
}
- return issueTokenPair(tx, grant, config);
+ const pair = await issueTokenPair(tx, grant, config);
+ if (idToken)
+ await tx.verification.deleteMany({
+ where: { id: `chatgpt-oidc:${hash}` },
+ });
+ return pair ? { ...pair, ...(idToken ? { id_token: idToken } : {}) } : null;
});
}
@@ -188,7 +235,11 @@ export async function accessIdentity(
return null;
}
- return { userId: grant.userId, scopes: grant.scope.split(" "), grantId: grant.id };
+ return {
+ userId: grant.userId,
+ scopes: grant.scope.split(" "),
+ grantId: grant.id,
+ };
}
export async function revokeToken(
@@ -243,7 +294,12 @@ export async function redeemEditorCode(
where: { hash },
include: { grant: true },
});
- if (!token || token.kind !== "embed" || token.consumedAt || token.expiresAt <= new Date()) {
+ if (
+ !token ||
+ token.kind !== "embed" ||
+ token.consumedAt ||
+ token.expiresAt <= new Date()
+ ) {
return null;
}
const grant = token.grant;
@@ -274,7 +330,12 @@ export async function recordEditorSession(
db = prisma,
) {
await db.chatgptToken.create({
- data: { hash: `${SESSION_REF}${session.id}`, grantId, kind: "session", expiresAt: session.expiresAt },
+ data: {
+ hash: `${SESSION_REF}${session.id}`,
+ grantId,
+ kind: "session",
+ expiresAt: session.expiresAt,
+ },
});
}
@@ -290,7 +351,9 @@ export async function revokeEditorSessions(grantIds: string[], db = prisma) {
return;
}
await db.session.deleteMany({
- where: { id: { in: rows.map((row) => row.hash.slice(SESSION_REF.length)) } },
+ 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/clients/chatgpt/server/oidc.ts b/site/src/clients/chatgpt/server/oidc.ts
new file mode 100644
index 00000000..fc25e918
--- /dev/null
+++ b/site/src/clients/chatgpt/server/oidc.ts
@@ -0,0 +1,115 @@
+import {
+ createHash,
+ createPrivateKey,
+ createPublicKey,
+ sign,
+} from "node:crypto";
+import {
+ CLIENT_ID,
+ OAUTH_PATH,
+ SCOPES,
+ type ChatgptConfig,
+} from "@/clients/chatgpt/server/config";
+
+export type IdentityUser = {
+ id: string;
+ email: string;
+ emailVerified: boolean;
+};
+
+export function identityClaims(user: IdentityUser, scopes: readonly string[]) {
+ return {
+ sub: user.id,
+ ...(scopes.includes("email")
+ ? { email: user.email, email_verified: user.emailVerified }
+ : {}),
+ };
+}
+
+export function createIdentitySigner(pem: string) {
+ const key = createPrivateKey(pem);
+ if (
+ key.asymmetricKeyType !== "rsa" ||
+ (key.asymmetricKeyDetails?.modulusLength ?? 0) < 2048
+ ) {
+ throw new Error(
+ "ChatGPT OpenID signing requires an RSA private key of at least 2048 bits.",
+ );
+ }
+ const { e, n, kty } = createPublicKey(key).export({ format: "jwk" });
+ const kid = createHash("sha256")
+ .update(JSON.stringify({ e, kty, n }))
+ .digest("base64url");
+ const jwk = { e, n, kty, kid, use: "sig", alg: "RS256" };
+ return {
+ jwk,
+ sign(
+ user: IdentityUser,
+ scopes: readonly string[],
+ issuer: string,
+ expiresIn: number,
+ nonce?: string,
+ ) {
+ const now = Math.floor(Date.now() / 1000);
+ const header = Buffer.from(
+ JSON.stringify({ alg: "RS256", typ: "JWT", kid }),
+ ).toString("base64url");
+ const payload = Buffer.from(
+ JSON.stringify({
+ ...identityClaims(user, scopes),
+ iss: issuer,
+ aud: CLIENT_ID,
+ iat: now,
+ exp: now + expiresIn,
+ ...(nonce === undefined ? {} : { nonce }),
+ }),
+ ).toString("base64url");
+ const input = `${header}.${payload}`;
+ return `${input}.${sign("RSA-SHA256", Buffer.from(input), key).toString("base64url")}`;
+ },
+ };
+}
+
+let cached:
+ { pem: string; signer: ReturnType<typeof createIdentitySigner> } | undefined;
+
+export function identitySigner() {
+ const pem = process.env.CHATGPT_OIDC_PRIVATE_KEY;
+ if (!pem)
+ throw new Error(
+ "CHATGPT_OIDC_PRIVATE_KEY is required for OpenID account linking.",
+ );
+ if (cached?.pem !== pem) cached = { pem, signer: createIdentitySigner(pem) };
+ return cached.signer;
+}
+
+export function openIdMetadata(config: ChatgptConfig) {
+ const baseUrl = `${config.issuer}${OAUTH_PATH}`;
+ return {
+ issuer: config.issuer,
+ authorization_endpoint: `${baseUrl}/authorize`,
+ token_endpoint: `${baseUrl}/token`,
+ revocation_endpoint: `${baseUrl}/revoke`,
+ userinfo_endpoint: `${baseUrl}/userinfo`,
+ jwks_uri: `${baseUrl}/jwks`,
+ response_types_supported: ["code"],
+ response_modes_supported: ["query"],
+ grant_types_supported: ["authorization_code", "refresh_token"],
+ subject_types_supported: ["public"],
+ id_token_signing_alg_values_supported: ["RS256"],
+ claims_supported: [
+ "sub",
+ "iss",
+ "aud",
+ "iat",
+ "exp",
+ "nonce",
+ "email",
+ "email_verified",
+ ],
+ code_challenge_methods_supported: ["S256"],
+ token_endpoint_auth_methods_supported: ["none"],
+ authorization_response_iss_parameter_supported: true,
+ scopes_supported: SCOPES,
+ };
+}
diff --git a/site/src/clients/chatgpt/server/userInfo.ts b/site/src/clients/chatgpt/server/userInfo.ts
new file mode 100644
index 00000000..129df954
--- /dev/null
+++ b/site/src/clients/chatgpt/server/userInfo.ts
@@ -0,0 +1,75 @@
+import { prisma } from "@/lib/prisma";
+import {
+ chatgptConfig,
+ type ChatgptConfig,
+} from "@/clients/chatgpt/server/config";
+import { identityClaims } from "@/clients/chatgpt/server/oidc";
+import { accessIdentity } from "@/clients/chatgpt/server/oauthTokens";
+import {
+ enforceOAuthUserLimit,
+ limitOAuthSource,
+ OAuthRateLimitError,
+} from "@/clients/chatgpt/server/oauthRateLimit";
+import { rateLimitResponse } from "@/lib/inference/rate-limit";
+
+const HEADERS = { "Cache-Control": "no-store", Pragma: "no-cache" };
+
+function denied(error: "invalid_token" | "insufficient_scope") {
+ return Response.json(
+ { error },
+ {
+ status: error === "invalid_token" ? 401 : 403,
+ headers: {
+ ...HEADERS,
+ "WWW-Authenticate": `Bearer error="${error}"${error === "insufficient_scope" ? ', scope="openid"' : ""}`,
+ },
+ },
+ );
+}
+
+export async function userInfoResponse(
+ request: Request,
+ config: ChatgptConfig,
+ db = prisma,
+) {
+ if (!config.enabled)
+ return Response.json(
+ { error: "temporarily_unavailable" },
+ { status: 503, headers: HEADERS },
+ );
+ const limited = limitOAuthSource(
+ request,
+ "userinfo",
+ config.oauthRequestsPerIpMinute,
+ );
+ if (limited) return limited;
+ const bearer = /^Bearer ([A-Za-z0-9_-]{43})$/i.exec(
+ request.headers.get("authorization") ?? "",
+ )?.[1];
+ const identity = bearer ? await accessIdentity(bearer, config, db) : null;
+ if (!identity) return denied("invalid_token");
+ if (!identity.scopes.includes("openid")) return denied("insufficient_scope");
+ try {
+ enforceOAuthUserLimit(
+ identity.userId,
+ "userinfo",
+ config.requestsPerMinute,
+ );
+ } catch (error) {
+ if (error instanceof OAuthRateLimitError)
+ return rateLimitResponse(error.retryAfterSeconds);
+ throw error;
+ }
+ const user = await db.user.findUnique({
+ where: { id: identity.userId },
+ select: { id: true, email: true, emailVerified: true },
+ });
+ return user
+ ? Response.json(identityClaims(user, identity.scopes), { headers: HEADERS })
+ : denied("invalid_token");
+}
+
+/** GET/POST /api/chatgpt/oauth/userinfo: identity shared by this OAuth grant. */
+export async function userInfoEndpoint(request: Request) {
+ return userInfoResponse(request, await chatgptConfig());
+}