Skip to content

Open source CapCut alternative.

TypeScript

feat(chatgpt): add account linking and cloud previews [rebuild]

David Lea3effe5af462
diff --git a/docs/README.md b/docs/README.md
index bbcb930a..813da9ae 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -18,6 +18,8 @@ Supported product and engineering guides live in `docs/guides/`. This list is th
- [Local Compute](guides/cut/local-compute.md) — why a project the engine doesn't store still uses the Mac when there is one, and the rule that keeps its data where it lives regardless.
- [Performance](guides/performance.md) — the frame budget, the four ways we keep the main thread clear, the memory budget, and how a change is measured before it ships.
+- [ChatGPT App](guides/chatgpt-app.md) — account linking, cloud project previews, and the boundary between the ChatGPT client and shared playback.
+
**Site and backend**
- [Backend API Guide](guides/backend-apis.md) — the hosted routes the app and site call for model-backed work.
diff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.md
index 8e40e9fa..ab2a9de6 100644
--- a/docs/guides/backend-apis.md
+++ b/docs/guides/backend-apis.md
@@ -7,7 +7,9 @@ the site's own client views, signed in with a session cookie.
endpoint is a deliberate exception with a product reason — today only Better
Auth's own routes, the signature-verified Stripe and Resend webhooks, the
HMAC-token-verified one-click email unsubscribe and promotion button redirect,
-the token-authorized Cut project and library share viewers, and a plain health check. Ship
+the token-authorized Cut project and library share viewers, the scoped OAuth
+ChatGPT MCP endpoint and its OAuth discovery/exchange endpoints, authenticated
+cron jobs, and a plain health check. Ship
a handler without the wrapper and the endpoint is open to anyone.
## Authentication
@@ -36,6 +38,10 @@ The hosted deploy needs `BETTER_AUTH_URL`, `BETTER_AUTH_SECRET`,
`GOOGLE_CLIENT_ID`, and `GOOGLE_CLIENT_SECRET`. Never commit real OAuth
credentials.
+The [ChatGPT app](chatgpt-app.md) uses scoped OAuth tokens for its MCP transport.
+Its consent submission requires the existing Donkey Cut session and a browser-bound
+challenge. OAuth tokens authorize only the tools exposed by that adapter.
+
## Handler Rules
- Validate every request body, search param, and route param with Zod before
diff --git a/docs/guides/chatgpt-app.md b/docs/guides/chatgpt-app.md
new file mode 100644
index 00000000..433cf085
--- /dev/null
+++ b/docs/guides/chatgpt-app.md
@@ -0,0 +1,114 @@
+# ChatGPT App
+
+The ChatGPT app connects a Donkey Cut account, lists its cloud projects, and plays
+rendered previews inside the conversation. ChatGPT chooses the tools; Donkey Cut
+checks ownership and renders the saved project revision.
+
+**The one rule:** the ChatGPT adapter lives under `site/src/clients/chatgpt`.
+Shared rendering stays in Cut, and reusable playback lives in a workspace package.
+
+```text
+ChatGPT tools and embedded preview
+ ↓
+Scoped OAuth connection
+ ↓
+Cloud project and preview services
+ ↓
+Captured document → worker renderer → signed media
+```
+
+## Client boundaries
+
+The standalone widget imports `@donkeycut/artifact-player/ArtifactVideo`, the
+same player used by website previews and shared videos. The package owns video
+buffers, visibility handling, and teardown. HLS loads on demand. The widget's
+hashed assets are built by `npm run chatgpt:build`, which also runs before the
+site's development and production builds. Rebuild it after editing widget code.
+
+The MCP adapter exposes project listing, project opening, preview rendering,
+and render status. Its schemas and widget data types share one contract. Signed
+media URLs travel in tool-result metadata, which reaches the widget. The model
+gets project metadata, render state, and an Open in Donkey Cut link.
+
+Cloud previews use the existing headless renderer and a captured document.
+Repeated requests for the same saved revision reuse a queued, running, or
+available completed preview. A collected preview can be rendered again.
+Browser and Mac projects retain their existing render paths; they become
+accessible to ChatGPT after the user saves them to the cloud in Donkey Cut.
+
+The widget polls while visible and renews expiring playback URLs through the
+host bridge. It has no account cookie or OAuth token. Preview rendering uses
+no Donkey Cut AI credits. Derived previews remain exempt from storage quota;
+retained media uses the account's existing storage allowance.
+
+## 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 |
+| `/.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 |
+
+## Deployment and verification
+
+The integration defaults to disabled in the `chatgptApp` setting. Deploy the
+Prisma models in `site/prisma/Chatgpt.prisma` through the project's database
+release process, deploy the site and cloud worker, then enable the setting in
+su. Generating the Prisma client does not deploy those tables.
+
+Set the same `CUT_RUNNER_SECRET` on the hosted site and the
+`donkey-cut-worker` Cloudflare Worker before deployment. The Worker passes it
+to the render container so document-backed renders can read media and fonts
+through the authenticated hosted API.
+
+Create a ChatGPT developer-mode app pointing at
+`https://donkeycut.com/api/chatgpt/mcp`. Use the predefined public OAuth client
+ID `donkey-chatgpt`, no client secret, and scopes `projects:read previews:render`.
+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
+resource declares `https://chatgpt.donkeycut.com` as its dedicated widget domain.
+ChatGPT uses this identifier to derive an OpenAI-hosted sandbox origin. The
+widget HTML arrives through MCP, its scripts and styles load from
+`donkeycut.com`, and video loads from `media.donkeycut.com`. This setup requires
+no DNS record or Cloudflare Worker for `chatgpt.donkeycut.com`.
+
+Public submission verifies control of the MCP server's host, `donkeycut.com`,
+through OpenAI's generated well-known challenge URL. Add the exact token from
+the submission portal when that challenge is issued.
+
+Run the client tests with `bun test src/clients/chatgpt`. The browser fixture
+`bun run scripts/eval-chatgpt-widget.ts` checks selection, repeated polling,
+playback, URL recovery, hidden playback, and teardown against a mock host.
+The final deployment check connects a real account in ChatGPT, opens a cloud
+project, renders it, and reconnects after revocation. The fixture does not
+exercise ChatGPT's account-linking UI or the production database.
+
+## Source entrypoints
+
+- `site/src/clients/chatgpt/server/` — OAuth, MCP tools, and cloud-project adapter.
+- `site/src/clients/chatgpt/ui/` — standalone MCP Apps widget and host bridge.
+- `site/packages/artifact-player/` — shared website and widget playback.
+- `site/src/cut/server/cloud/previewJobs.ts` — revision reuse and document-backed rendering.
+
+The protocol follows OpenAI's [authentication guidance](https://developers.openai.com/apps-sdk/build/auth)
+and [MCP Apps UI guidance](https://developers.openai.com/plugins/build/chatgpt-ui).
diff --git a/site/.gitignore b/site/.gitignore
index ec4bf809..0e18c8f1 100644
--- a/site/.gitignore
+++ b/site/.gitignore
@@ -64,3 +64,7 @@ next-env.d.ts
/public/cut-fonts/
/public/models/rife_v4.25.onnx
/public/ort/
+
+# Generated MCP Apps UI resource
+/src/clients/chatgpt/widget.generated.ts
+/public/clients/chatgpt/
diff --git a/site/eslint.config.mjs b/site/eslint.config.mjs
index 82b56c25..417bb0df 100644
--- a/site/eslint.config.mjs
+++ b/site/eslint.config.mjs
@@ -14,6 +14,8 @@ const eslintConfig = defineConfig([
"dist/**",
"public/mediapipe/**",
"next-env.d.ts",
+ "src/clients/chatgpt/widget.generated.ts",
+ "public/clients/chatgpt/**",
// Cloudflare Worker shell for the Cut render worker: compiled by wrangler
// against workers types, excluded from the site's tsconfig.
"src/cut/worker/cf/**",
diff --git a/site/next.config.ts b/site/next.config.ts
index dad656ec..6e087bba 100644
--- a/site/next.config.ts
+++ b/site/next.config.ts
@@ -4,7 +4,7 @@ import type { NextConfig } from "next";
const nextConfig: NextConfig = {
pageExtensions: ["js", "jsx", "ts", "tsx", "md", "mdx"],
// Workspace packages ship TypeScript source; the app build transpiles them.
- transpilePackages: ["@donkeycut/effects-kit", "@donkeycut/abexp"],
+ transpilePackages: ["@donkeycut/effects-kit", "@donkeycut/abexp", "@donkeycut/artifact-player"],
// Cache Components: pages prerender to a static shell and anything uncached
// streams behind its own Suspense boundary. It is what the `instant`
// export on the public pages and the app's home routes validates against, and
@@ -36,6 +36,14 @@ const nextConfig: NextConfig = {
// every chunk, stylesheet and font in Search Console as a candidate page.
// The header lets them be fetched and keeps them out of the index.
headers: async () => [
+ {
+ source: "/clients/chatgpt/:path*",
+ headers: [
+ { key: "Access-Control-Allow-Origin", value: "*" },
+ { key: "Cache-Control", value: "public, max-age=31536000, immutable" },
+ { key: "X-Content-Type-Options", value: "nosniff" },
+ ],
+ },
{
source: "/_next/static/:path*",
headers: [{ key: "X-Robots-Tag", value: "noindex" }],
diff --git a/site/package-lock.json b/site/package-lock.json
index 578050e8..6afad1d3 100644
--- a/site/package-lock.json
+++ b/site/package-lock.json
@@ -22,6 +22,7 @@
"@better-auth/kysely-adapter": "1.6.11",
"@better-auth/utils": "0.4.0",
"@donkeycut/abexp": "*",
+ "@donkeycut/artifact-player": "*",
"@donkeycut/effects-kit": "*",
"@earendil-works/pi-agent-core": "0.84.1",
"@earendil-works/pi-ai": "0.84.1",
@@ -32,6 +33,8 @@
"@mdxeditor/editor": "^4.2.4",
"@mediabunny/server": "^1.55.1",
"@mediapipe/tasks-vision": "^1.0.1",
+ "@modelcontextprotocol/ext-apps": "^2.0.0",
+ "@modelcontextprotocol/sdk": "^1.30.0",
"@next/mdx": "^16.3.4",
"@posthog/react": "^1.10.3",
"@prisma/adapter-pg": "^7.8.0",
@@ -48,7 +51,6 @@
"cn": "^0.2.6",
"date-fns": "^4.4.0",
"defuddle": "^0.18.1",
- "hls.js": "^1.6.16",
"lexical": "^0.48.0",
"linkedom": "^0.18.12",
"lucide-react": "^1.23.0",
@@ -1871,6 +1873,10 @@
"resolved": "packages/abexp",
"link": true
},
+ "node_modules/@donkeycut/artifact-player": {
+ "resolved": "packages/artifact-player",
+ "link": true
+ },
"node_modules/@donkeycut/effects-kit": {
"resolved": "packages/effects-kit",
"link": true
@@ -4658,13 +4664,79 @@
"license": "BSD-2-Clause",
"optional": true
},
+ "node_modules/@modelcontextprotocol/client": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.0.0.tgz",
+ "integrity": "sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw==",
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@modelcontextprotocol/core": "2.0.0",
+ "cross-spawn": "^7.0.5",
+ "eventsource": "^3.0.2",
+ "eventsource-parser": "^3.0.0",
+ "jose": "^6.1.3",
+ "pkce-challenge": "^5.0.0",
+ "zod": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@modelcontextprotocol/core": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.0.0.tgz",
+ "integrity": "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==",
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "zod": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@modelcontextprotocol/ext-apps": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/ext-apps/-/ext-apps-2.0.0.tgz",
+ "integrity": "sha512-a6tXzFcIbIIdnqumQ7W8Oxd8W/KAPkAKYpoxpD9nDgxZ24ywgxG5pK/8G9W5pOFUygS7gWHQhPv8cwRB44/8yg==",
+ "license": "MIT",
+ "workspaces": [
+ "examples/*"
+ ],
+ "dependencies": {
+ "@standard-schema/spec": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "peerDependencies": {
+ "@modelcontextprotocol/client": "^2.0.0",
+ "@modelcontextprotocol/core": "^2.0.0",
+ "@modelcontextprotocol/server": "^2.0.0",
+ "react": "^17.0.0 || ^18.0.0 || ^19.0.0",
+ "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0",
+ "zod": "^4.2.0"
+ },
+ "peerDependenciesMeta": {
+ "@modelcontextprotocol/server": {
+ "optional": true
+ },
+ "react": {
+ "optional": true
+ },
+ "react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@modelcontextprotocol/sdk": {
- "version": "1.29.0",
- "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz",
- "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==",
+ "version": "1.30.0",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.30.0.tgz",
+ "integrity": "sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA==",
"license": "MIT",
"dependencies": {
- "@hono/node-server": "^1.19.9",
+ "@hono/node-server": "^1.19.9 || ^2.0.5",
"ajv": "^8.17.1",
"ajv-formats": "^3.0.1",
"content-type": "^1.0.5",
@@ -9504,6 +9576,72 @@
"node": ">=14.0.0"
}
},
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": {
+ "version": "1.10.0",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/wasi-threads": "1.2.1",
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": {
+ "version": "1.10.0",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": {
+ "version": "1.2.1",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": {
+ "version": "1.1.4",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@tybys/wasm-util": "^0.10.1"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ },
+ "peerDependencies": {
+ "@emnapi/core": "^1.7.1",
+ "@emnapi/runtime": "^1.7.1"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": {
+ "version": "0.10.1",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": {
+ "version": "2.8.1",
+ "dev": true,
+ "inBundle": true,
+ "license": "0BSD",
+ "optional": true
+ },
"node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.0.tgz",
@@ -23573,6 +23711,16 @@
"zod": "^4.0.0"
}
},
+ "packages/artifact-player": {
+ "name": "@donkeycut/artifact-player",
+ "version": "0.1.0",
+ "dependencies": {
+ "hls.js": "^1.6.16"
+ },
+ "peerDependencies": {
+ "react": "^19.0.0"
+ }
+ },
"packages/effects-kit": {
"name": "@donkeycut/effects-kit",
"version": "0.1.0",
diff --git a/site/package.json b/site/package.json
index 751a8b26..9040af98 100644
--- a/site/package.json
+++ b/site/package.json
@@ -36,7 +36,11 @@
"eval:cut-preview-selection": "bun run scripts/eval-cut-preview-selection.ts",
"eval:cut-timeline-operations": "bun run scripts/eval-cut-timeline-operations.ts",
"eval:cut-timeline-rows": "bun run scripts/eval-cut-timeline-rows.ts",
- "eval:cut-export": "bun run scripts/eval-cut-export.ts"
+ "eval:cut-export": "bun run scripts/eval-cut-export.ts",
+ "chatgpt:build": "bun run scripts/build-chatgpt-widget.ts",
+ "predev": "npm run chatgpt:build",
+ "prebuild": "npm run chatgpt:build",
+ "eval:chatgpt-widget": "bun run scripts/eval-chatgpt-widget.ts"
},
"dependencies": {
"@ai-sdk/react": "^4.0.15",
@@ -58,6 +62,8 @@
"@mdxeditor/editor": "^4.2.4",
"@mediabunny/server": "^1.55.1",
"@mediapipe/tasks-vision": "^1.0.1",
+ "@modelcontextprotocol/ext-apps": "^2.0.0",
+ "@modelcontextprotocol/sdk": "^1.30.0",
"@next/mdx": "^16.3.4",
"@posthog/react": "^1.10.3",
"@prisma/adapter-pg": "^7.8.0",
@@ -74,7 +80,6 @@
"cn": "^0.2.6",
"date-fns": "^4.4.0",
"defuddle": "^0.18.1",
- "hls.js": "^1.6.16",
"lexical": "^0.48.0",
"linkedom": "^0.18.12",
"lucide-react": "^1.23.0",
@@ -102,7 +107,8 @@
"tailwind-merge": "^3.6.0",
"tw-animate-css": "^1.4.0",
"zod": "^4.4.3",
- "zustand": "^5.0.5"
+ "zustand": "^5.0.5",
+ "@donkeycut/artifact-player": "*"
},
"devDependencies": {
"@cloudflare/containers": "^0.3.7",
diff --git a/site/packages/artifact-player/package.json b/site/packages/artifact-player/package.json
new file mode 100644
index 00000000..cbe9d931
--- /dev/null
+++ b/site/packages/artifact-player/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "@donkeycut/artifact-player",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "exports": {
+ "./ArtifactVideo": "./src/ArtifactVideo.tsx"
+ },
+ "peerDependencies": {
+ "react": "^19.0.0"
+ },
+ "dependencies": {
+ "hls.js": "^1.6.16"
+ }
+}
diff --git a/site/src/cut/components/ArtifactVideo.tsx b/site/packages/artifact-player/src/ArtifactVideo.tsx
similarity index 100%
rename from site/src/cut/components/ArtifactVideo.tsx
rename to site/packages/artifact-player/src/ArtifactVideo.tsx
diff --git a/site/prisma/Auth.prisma b/site/prisma/Auth.prisma
index 49bd204e..e41146e6 100644
--- a/site/prisma/Auth.prisma
+++ b/site/prisma/Auth.prisma
@@ -23,6 +23,7 @@ model User {
creditLimits UserCreditLimit[]
creditAutoReload CreditAutoReload?
apiKeys Apikey[]
+ chatgptGrants ChatgptGrant[]
proSubscription ProSubscription?
avatar UserAvatar?
onboarding UserOnboarding?
diff --git a/site/prisma/Chatgpt.prisma b/site/prisma/Chatgpt.prisma
new file mode 100644
index 00000000..899cb0b7
--- /dev/null
+++ b/site/prisma/Chatgpt.prisma
@@ -0,0 +1,30 @@
+// Each connection owns a rotating token family. Only token hashes are stored.
+model ChatgptGrant {
+ id String @id @default(cuid())
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ clientId String
+ resource String
+ scope String
+ redirectUri String
+ challenge String
+ expiresAt DateTime
+ revokedAt DateTime?
+ createdAt DateTime @default(now())
+ tokens ChatgptToken[]
+
+ @@index([userId])
+ @@index([expiresAt])
+}
+
+model ChatgptToken {
+ hash String @id
+ grantId String
+ grant ChatgptGrant @relation(fields: [grantId], references: [id], onDelete: Cascade)
+ kind String // code | access | refresh
+ expiresAt DateTime
+ consumedAt DateTime?
+
+ @@index([grantId])
+ @@index([expiresAt])
+}
diff --git a/site/prisma/migrations/20260916055217/migration.sql b/site/prisma/migrations/20260916055217/migration.sql
new file mode 100644
index 00000000..82afad15
--- /dev/null
+++ b/site/prisma/migrations/20260916055217/migration.sql
@@ -0,0 +1,44 @@
+-- CreateTable
+CREATE TABLE "ChatgptGrant" (
+ "id" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+ "clientId" TEXT NOT NULL,
+ "resource" TEXT NOT NULL,
+ "scope" TEXT NOT NULL,
+ "redirectUri" TEXT NOT NULL,
+ "challenge" TEXT NOT NULL,
+ "expiresAt" TIMESTAMP(3) NOT NULL,
+ "revokedAt" TIMESTAMP(3),
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "ChatgptGrant_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "ChatgptToken" (
+ "hash" TEXT NOT NULL,
+ "grantId" TEXT NOT NULL,
+ "kind" TEXT NOT NULL,
+ "expiresAt" TIMESTAMP(3) NOT NULL,
+ "consumedAt" TIMESTAMP(3),
+
+ CONSTRAINT "ChatgptToken_pkey" PRIMARY KEY ("hash")
+);
+
+-- CreateIndex
+CREATE INDEX "ChatgptGrant_userId_idx" ON "ChatgptGrant"("userId");
+
+-- CreateIndex
+CREATE INDEX "ChatgptGrant_expiresAt_idx" ON "ChatgptGrant"("expiresAt");
+
+-- CreateIndex
+CREATE INDEX "ChatgptToken_grantId_idx" ON "ChatgptToken"("grantId");
+
+-- CreateIndex
+CREATE INDEX "ChatgptToken_expiresAt_idx" ON "ChatgptToken"("expiresAt");
+
+-- AddForeignKey
+ALTER TABLE "ChatgptGrant" ADD CONSTRAINT "ChatgptGrant_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "ChatgptToken" ADD CONSTRAINT "ChatgptToken_grantId_fkey" FOREIGN KEY ("grantId") REFERENCES "ChatgptGrant"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/site/scripts/build-chatgpt-widget.ts b/site/scripts/build-chatgpt-widget.ts
new file mode 100644
index 00000000..721ed60a
--- /dev/null
+++ b/site/scripts/build-chatgpt-widget.ts
@@ -0,0 +1,21 @@
+import { mkdir, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+
+// Hashed chunks let the widget load MP4 playback without downloading the HLS decoder.
+const root = path.resolve(import.meta.dir, "..");
+const outdir = path.join(root, "public/clients/chatgpt");
+await rm(outdir, { recursive: true, force: true });
+await mkdir(outdir, { recursive: true });
+const result = await Bun.build({
+ entrypoints: [path.join(root, "src/clients/chatgpt/ui/main.tsx")],
+ target: "browser", format: "esm", splitting: true, minify: true, outdir,
+ naming: { entry: "[name]-[hash].[ext]", chunk: "[name]-[hash].[ext]", asset: "[name]-[hash].[ext]" },
+ define: { "process.env.NODE_ENV": JSON.stringify("production") },
+});
+if (!result.success) throw new AggregateError(result.logs, "ChatGPT widget build failed");
+const entry = result.outputs.find((o) => o.kind === "entry-point" && o.path.endsWith(".js"))!;
+const css = result.outputs.find((o) => o.path.endsWith(".css"));
+const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Donkey Cut preview</title>${css ? `<link rel="stylesheet" href="WIDGET_ORIGIN/clients/chatgpt/${path.basename(css.path)}">` : ""}</head><body><div id="root"></div><script type="module" src="WIDGET_ORIGIN/clients/chatgpt/${path.basename(entry.path)}"></script></body></html>`;
+const output = path.join(root, "src/clients/chatgpt/widget.generated.ts");
+await writeFile(output, `// Generated by scripts/build-chatgpt-widget.ts\nexport const widgetHtml = (origin: string) => ${JSON.stringify(html)}.replaceAll("WIDGET_ORIGIN", origin);\n`);
+console.log(`ChatGPT widget entry: ${Math.round(entry.size / 1024)} KiB; HLS loads on demand`);
diff --git a/site/scripts/eval-chatgpt-oauth.ts b/site/scripts/eval-chatgpt-oauth.ts
new file mode 100644
index 00000000..cf53fc56
--- /dev/null
+++ b/site/scripts/eval-chatgpt-oauth.ts
@@ -0,0 +1,216 @@
+import assert from "node:assert/strict";
+import { mock } from "bun:test";
+import { chromium } from "playwright";
+import type {
+ DonkeyAuthenticatedRequest,
+ DonkeyAuthHandler,
+} from "@/lib/donkey-api-auth";
+import { SETTINGS } from "@/lib/config/registry";
+
+type ConsentChallenge = {
+ id: string;
+ identifier: string;
+ value: string;
+ expiresAt: Date;
+};
+
+// Run in its own process: these test doubles isolate the browser flow from accounts and storage.
+const challenges = new Map<string, ConsentChallenge>();
+const submittedOrigins: Array<string | null> = [];
+let issuedCodes = 0;
+let tokenExchanges = 0;
+let revocations = 0;
+
+const callbackServer = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ fetch: () => new Response("ChatGPT callback received"),
+});
+const appServer = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ async fetch(request) {
+ if (request.method === "POST") {
+ submittedOrigins.push(request.headers.get("origin"));
+ return consent(request as DonkeyAuthenticatedRequest);
+ }
+ return authorize(request);
+ },
+});
+const issuer = appServer.url.origin;
+const redirectUri = new URL("/callback", callbackServer.url).href;
+const oauthPath = "/api/chatgpt/oauth";
+const resource = `${issuer}/api/chatgpt/mcp`;
+const config = {
+ ...SETTINGS.chatgptApp.default,
+ enabled: true,
+ issuer,
+ redirectUris: [redirectUri],
+ requestsPerMinute: 2,
+ oauthRequestsPerIpMinute: 2,
+};
+
+mock.module("@/clients/chatgpt/server/config", () => ({
+ CLIENT_ID: "donkey-chatgpt",
+ SCOPES: ["projects:read", "previews:render"],
+ OAUTH_PATH: oauthPath,
+ chatgptConfig: async () => config,
+ resourceUrl: () => resource,
+}));
+mock.module("@/lib/donkey-api-auth", () => ({
+ getDonkeyAuthContext: async () => ({ userId: "owner" }),
+ withDonkeyAuth: (handler: DonkeyAuthHandler) => (request: Request) => {
+ return handler(
+ Object.assign(request, {
+ donkey: { userId: "owner" },
+ }) as DonkeyAuthenticatedRequest,
+ );
+ },
+}));
+mock.module("@/lib/prisma", () => ({
+ prisma: {
+ verification: {
+ create: async ({ data }: { data: ConsentChallenge }) => {
+ challenges.set(data.id, data);
+ },
+ findUnique: async ({ where }: { where: { id: string } }) =>
+ challenges.get(where.id),
+ deleteMany: async ({ where }: { where: { id?: string } }) => ({
+ count: where.id && challenges.delete(where.id) ? 1 : 0,
+ }),
+ },
+ },
+}));
+mock.module("@/clients/chatgpt/server/oauthTokens", () => ({
+ createCode: async () => {
+ issuedCodes++;
+ return "test-authorization-code";
+ },
+ exchangeToken: async () => {
+ tokenExchanges++;
+ return { access_token: "fixture-access-token", token_type: "Bearer" };
+ },
+ revokeToken: async () => {
+ revocations++;
+ },
+}));
+const { authorize, consent, tokenEndpoint, revocationEndpoint } =
+ await import("@/clients/chatgpt/server/oauthRoutes");
+for (const [operation, endpoint] of [
+ ["token", tokenEndpoint],
+ ["revoke", revocationEndpoint],
+] as const) {
+ const request = (source: string | null, form: URLSearchParams) => {
+ const headers = new Headers({
+ "Content-Type": "application/x-www-form-urlencoded",
+ });
+ if (source) headers.set("x-vercel-forwarded-for", source);
+ return new Request(`${issuer}${oauthPath}/${operation}`, {
+ method: "POST",
+ headers,
+ body: form,
+ });
+ };
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const malformed = await endpoint(
+ request("192.0.2.10", new URLSearchParams({ invalid: "request" })),
+ );
+ assert.equal(malformed.status, 400);
+ }
+ const throttled = await endpoint(
+ request("192.0.2.10", new URLSearchParams({ invalid: "request" })),
+ );
+ assert.equal(throttled.status, 429);
+ assert.ok(Number(throttled.headers.get("Retry-After")) > 0);
+
+ const validForm =
+ operation === "token"
+ ? new URLSearchParams({
+ grant_type: "authorization_code",
+ client_id: "donkey-chatgpt",
+ resource,
+ code: "a".repeat(43),
+ code_verifier: "b".repeat(43),
+ redirect_uri: redirectUri,
+ })
+ : new URLSearchParams({
+ client_id: "donkey-chatgpt",
+ token: "c".repeat(43),
+ });
+ const otherSource = await endpoint(request("192.0.2.11", validForm));
+ assert.equal(otherSource.status, 200);
+ const local = await endpoint(request(null, validForm));
+ assert.equal(local.status, 200);
+}
+assert.equal(tokenExchanges, 2);
+assert.equal(revocations, 2);
+
+const browser = await chromium.launch();
+
+try {
+ for (const decision of ["Connect", "Cancel"]) {
+ const context = await browser.newContext();
+ try {
+ const page = await context.newPage();
+ const authorizationUrl = new URL(`${oauthPath}/authorize`, issuer);
+ authorizationUrl.search = new URLSearchParams({
+ response_type: "code",
+ client_id: "donkey-chatgpt",
+ redirect_uri: redirectUri,
+ scope: "projects:read previews:render",
+ state: "browser-consent-state",
+ code_challenge: "a".repeat(43),
+ code_challenge_method: "S256",
+ resource,
+ }).toString();
+ await page.goto(authorizationUrl.href);
+
+ // Reject a foreign Origin without consuming the pending consent.
+ const nonce = await page.locator('input[name="nonce"]').inputValue();
+ const rejected = await fetch(new URL(`${oauthPath}/authorize`, issuer), {
+ method: "POST",
+ headers: {
+ Origin: callbackServer.url.origin,
+ "Content-Type": "application/x-www-form-urlencoded",
+ Cookie: `__Host-donkey-chatgpt-consent=${nonce}`,
+ },
+ body: new URLSearchParams({ nonce, decision: "allow" }),
+ });
+ assert.equal(rejected.status, 400);
+ assert.equal(challenges.size, 1);
+
+ await Promise.all([
+ page.waitForURL((url) => url.origin === callbackServer.url.origin),
+ page.getByRole("button", { name: decision, exact: true }).click(),
+ ]);
+ const callbackUrl = new URL(page.url());
+ assert.equal(
+ callbackUrl.searchParams.get("state"),
+ "browser-consent-state",
+ );
+ assert.equal(callbackUrl.searchParams.get("iss"), issuer);
+ assert.equal(submittedOrigins.at(-1), issuer);
+ assert.equal(challenges.size, 0);
+ if (decision === "Connect") {
+ assert.equal(
+ callbackUrl.searchParams.get("code"),
+ "test-authorization-code",
+ );
+ assert.equal(callbackUrl.searchParams.has("error"), false);
+ } else {
+ assert.equal(callbackUrl.searchParams.get("error"), "access_denied");
+ assert.equal(callbackUrl.searchParams.has("code"), false);
+ }
+ } finally {
+ await context.close();
+ }
+ }
+ assert.equal(issuedCodes, 1);
+ console.log(
+ "PASS: browser consent, cancellation, cross-origin callbacks, foreign-Origin rejection, and isolated OAuth rate limits.",
+ );
+} finally {
+ await browser.close();
+ appServer.stop(true);
+ callbackServer.stop(true);
+}
diff --git a/site/scripts/eval-chatgpt-widget.ts b/site/scripts/eval-chatgpt-widget.ts
new file mode 100644
index 00000000..1dfdc158
--- /dev/null
+++ b/site/scripts/eval-chatgpt-widget.ts
@@ -0,0 +1,78 @@
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { chromium } from "playwright";
+import { widgetHtml } from "../src/clients/chatgpt/widget.generated";
+
+const root = path.resolve(import.meta.dir, "..");
+const scratch = await mkdtemp(path.join(os.tmpdir(), "donkey-chatgpt-widget-"));
+const video = path.join(scratch, "preview.mp4");
+execFileSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=blue:s=640x360:r=24", "-t", "2", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-movflags", "+faststart", video]);
+const server = Bun.serve({ port: 0, fetch(request) {
+ const url = new URL(request.url);
+ if (url.pathname === "/widget") return new Response(widgetHtml(url.origin), { headers: { "Content-Type": "text/html" } });
+ if (url.pathname === "/preview.mp4") return new Response(Bun.file(video));
+ if (url.pathname.startsWith("/clients/chatgpt/")) return new Response(Bun.file(path.join(root, "public/clients/chatgpt", path.basename(url.pathname))));
+ return new Response(hostHtml, { headers: { "Content-Type": "text/html" } });
+} });
+const hostHtml = `<!doctype html><html><body><iframe title="Donkey Cut preview" src="/widget" style="width:700px;height:700px;border:0"></iframe><script>
+const frame = document.querySelector('iframe');
+const project = {id:'project',name:'Launch film',revision:'cloud:2',url:'https://donkeycut.com/app/p/project'};
+let count = 0, renewals = 0;
+window.calls = []; window.links = [];
+const view = (selected, preview = null) => ({view:selected?'project':'projects',projects:selected?[]:[project],nextCursor:null,project:selected?project:null,preview,canRender:true});
+const result = (data, playback = null) => ({content:[{type:'text',text:'Preview'}],structuredContent:data,_meta:{playback,pollMs:1000}});
+const reply = (id, result) => frame.contentWindow.postMessage({jsonrpc:'2.0',id,result},'*');
+window.addEventListener('message', ({source,data}) => {
+ if(source !== frame.contentWindow || !data.method) return;
+ if(data.method === 'ui/initialize') reply(data.id,{protocolVersion:data.params.protocolVersion,hostInfo:{name:'fixture',version:'1'},hostCapabilities:{serverTools:{},openLinks:{}},hostContext:{theme:'light'}});
+ if(data.method === 'ui/notifications/initialized') frame.contentWindow.postMessage({jsonrpc:'2.0',method:'ui/notifications/tool-result',params:result(view(false))},'*');
+ if(data.method === 'tools/call') {
+ const name = data.params.name; window.calls.push(name);
+ if(name === 'list_projects') reply(data.id,result(view(false)));
+ if(name === 'open_project') reply(data.id,result(view(true)));
+ if(name === 'render_preview') { count=0; reply(data.id,result(view(true,{id:'job',status:'queued',progress:0,revision:'cloud:2'}))); }
+ if(name === 'get_preview_status') {
+ count++; const done = count >= 3;
+ reply(data.id,result(view(true,{id:'job',status:done?'done':'running',progress:done?1:count/3,revision:'cloud:2'}),done?{url:location.origin+'/preview.mp4?v='+renewals++,expiresAt:Date.now()+3600000}:null));
+ }
+ }
+ if(data.method === 'ui/open-link') { window.links.push(data.params.url); reply(data.id,{}); }
+});
+</script></body></html>`;
+const browser = await chromium.launch({ headless: true });
+try {
+ const page = await browser.newPage();
+ const errors: string[] = [], requests: string[] = [];
+ page.on("pageerror", (error) => errors.push(error.message));
+ page.on("request", (request) => requests.push(request.url()));
+ await page.goto(`http://localhost:${server.port}`);
+ const app = page.frameLocator("iframe");
+ await app.getByRole("button", { name: "Launch film" }).click();
+ await app.getByRole("button", { name: "Render preview", exact: true }).click();
+ await app.locator("video").waitFor();
+ const frame = page.frames().find((f) => f.url().endsWith("/widget"))!;
+ await frame.waitForFunction(() => (document.querySelector("video")?.readyState ?? 0) >= 2);
+ const calls = await page.evaluate(() => (window as unknown as { calls: string[] }).calls);
+ assert.equal(calls.filter((name) => name === "get_preview_status").length, 3, "poll through repeated running states");
+ assert.equal(requests.some((url) => url.includes("/hls-")), false, "MP4 must not download HLS");
+ await frame.evaluate(() => document.querySelector("video")!.dispatchEvent(new Event("error")));
+ await frame.waitForFunction(() => document.querySelector("video")?.src.endsWith("v=1"));
+ await frame.evaluate(async () => { const video = document.querySelector("video")!; video.muted = true; await video.play(); });
+ await frame.evaluate(() => { Object.defineProperty(document, "hidden", { configurable: true, value: true }); document.dispatchEvent(new Event("visibilitychange")); });
+ await frame.waitForFunction(() => document.querySelector("video")?.paused === true);
+ await frame.evaluate(() => { Object.defineProperty(document, "hidden", { configurable: true, value: false }); document.dispatchEvent(new Event("visibilitychange")); });
+ await app.getByRole("button", { name: "Open in Donkey Cut" }).click();
+ await page.waitForFunction(() => (window as unknown as { links: string[] }).links.length === 1);
+ assert.deepEqual(await page.evaluate(() => (window as unknown as { links: string[] }).links), ["https://donkeycut.com/app/p/project"]);
+ await page.screenshot({ path: "/tmp/donkey-chatgpt-widget.png" });
+ await app.getByRole("button", { name: "Projects", exact: true }).click();
+ await app.locator("video").waitFor({ state: "detached" });
+ assert.equal(await app.locator("video").count(), 0, "project picker releases the video");
+ assert.deepEqual(errors, []);
+ console.log("PASS: project selection, repeated polling, native playback, URL recovery, hidden pause, Open in Donkey Cut, decoder teardown, lazy HLS.");
+} finally {
+ await browser.close(); server.stop(true); await rm(scratch, { recursive: true, force: true });
+}
diff --git a/site/src/app/.well-known/oauth-authorization-server/route.ts b/site/src/app/.well-known/oauth-authorization-server/route.ts
new file mode 100644
index 00000000..ebc64f56
--- /dev/null
+++ b/site/src/app/.well-known/oauth-authorization-server/route.ts
@@ -0,0 +1 @@
+export { authorizationMetadata as GET } from "@/clients/chatgpt/server/oauthRoutes";
diff --git a/site/src/app/.well-known/oauth-protected-resource/api/chatgpt/mcp/route.ts b/site/src/app/.well-known/oauth-protected-resource/api/chatgpt/mcp/route.ts
new file mode 100644
index 00000000..a3b1c532
--- /dev/null
+++ b/site/src/app/.well-known/oauth-protected-resource/api/chatgpt/mcp/route.ts
@@ -0,0 +1 @@
+export { protectedResourceMetadata as GET } from "@/clients/chatgpt/server/oauthRoutes";
diff --git a/site/src/app/api/chatgpt/gc/route.ts b/site/src/app/api/chatgpt/gc/route.ts
new file mode 100644
index 00000000..8c3c7fbe
--- /dev/null
+++ b/site/src/app/api/chatgpt/gc/route.ts
@@ -0,0 +1,7 @@
+import type { NextRequest } from "next/server";
+import { isVercelCron, withSuperUser } from "@/lib/donkey-api-auth";
+import { cleanupConnections } from "@/clients/chatgpt/server/cleanup";
+
+const admin = withSuperUser(cleanupConnections);
+/** GET /api/chatgpt/gc: expire OAuth families and consent challenges daily. */
+export const GET = (request: NextRequest) => isVercelCron(request) ? cleanupConnections() : admin(request);
diff --git a/site/src/app/api/chatgpt/mcp/route.ts b/site/src/app/api/chatgpt/mcp/route.ts
new file mode 100644
index 00000000..8475f407
--- /dev/null
+++ b/site/src/app/api/chatgpt/mcp/route.ts
@@ -0,0 +1,4 @@
+export { mcpEndpoint as POST } from "@/clients/chatgpt/server/mcp";
+// The stateless transport has no event stream or session to terminate.
+export function GET() { return new Response(null, { status: 405, headers: { Allow: "POST" } }); }
+export const DELETE = GET;
diff --git a/site/src/app/api/chatgpt/oauth/authorize/route.ts b/site/src/app/api/chatgpt/oauth/authorize/route.ts
new file mode 100644
index 00000000..f885747b
--- /dev/null
+++ b/site/src/app/api/chatgpt/oauth/authorize/route.ts
@@ -0,0 +1 @@
+export { authorize as GET, consent as POST } from "@/clients/chatgpt/server/oauthRoutes";
diff --git a/site/src/app/api/chatgpt/oauth/revoke/route.ts b/site/src/app/api/chatgpt/oauth/revoke/route.ts
new file mode 100644
index 00000000..869d4982
--- /dev/null
+++ b/site/src/app/api/chatgpt/oauth/revoke/route.ts
@@ -0,0 +1 @@
+export { revocationEndpoint as POST } from "@/clients/chatgpt/server/oauthRoutes";
diff --git a/site/src/app/api/chatgpt/oauth/token/route.ts b/site/src/app/api/chatgpt/oauth/token/route.ts
new file mode 100644
index 00000000..f6eee5e2
--- /dev/null
+++ b/site/src/app/api/chatgpt/oauth/token/route.ts
@@ -0,0 +1 @@
+export { tokenEndpoint as POST } from "@/clients/chatgpt/server/oauthRoutes";
diff --git a/site/src/clients/chatgpt/contracts.ts b/site/src/clients/chatgpt/contracts.ts
new file mode 100644
index 00000000..e6a5bca3
--- /dev/null
+++ b/site/src/clients/chatgpt/contracts.ts
@@ -0,0 +1,12 @@
+import { z } from "zod";
+
+export const WIDGET_URI = "ui://donkey/project-preview-v1.html";
+export const projectSchema = z.object({ id: z.string(), name: z.string(), url: z.url(), revision: z.string() });
+export const previewSchema = z.object({ id: z.string(), status: z.enum(["queued", "running", "done", "error", "expired"]), progress: z.number(), revision: z.string().nullable(), error: z.string().optional() });
+export const viewSchema = z.object({
+ view: z.enum(["projects", "project"]), projects: z.array(projectSchema), nextCursor: z.string().nullable(),
+ project: projectSchema.nullable(), preview: previewSchema.nullable(), canRender: z.boolean(),
+});
+export const playbackSchema = z.object({ url: z.url(), expiresAt: z.number() });
+export type ProjectView = z.infer<typeof viewSchema>;
+export type Playback = z.infer<typeof playbackSchema>;
diff --git a/site/src/clients/chatgpt/server/cleanup.ts b/site/src/clients/chatgpt/server/cleanup.ts
new file mode 100644
index 00000000..179cdc2a
--- /dev/null
+++ b/site/src/clients/chatgpt/server/cleanup.ts
@@ -0,0 +1,31 @@
+import { prisma } from "@/lib/prisma";
+import { chatgptConfig } from "@/clients/chatgpt/server/config";
+
+export async function cleanupConnections() {
+ const config = await chatgptConfig();
+ if (!config.enabled) {
+ return Response.json({ skipped: true });
+ }
+ const [grants, consent] = await Promise.all([
+ prisma.chatgptGrant.deleteMany({
+ where: {
+ OR: [{ expiresAt: { lte: new Date() } }, { revokedAt: { not: null } }],
+ },
+ }),
+ prisma.verification.deleteMany({
+ where: {
+ identifier: { startsWith: "chatgpt-consent:" },
+ expiresAt: { lte: new Date() },
+ },
+ }),
+ ]);
+ // 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() } },
+ });
+ return Response.json({
+ grants: grants.count,
+ consent: consent.count,
+ access: access.count,
+ });
+}
diff --git a/site/src/clients/chatgpt/server/config.ts b/site/src/clients/chatgpt/server/config.ts
new file mode 100644
index 00000000..fc35f5b2
--- /dev/null
+++ b/site/src/clients/chatgpt/server/config.ts
@@ -0,0 +1,25 @@
+import { prisma } from "@/lib/prisma";
+import { resolveSettings } from "@/lib/config/resolve";
+
+export const CLIENT_ID = "donkey-chatgpt";
+export const SCOPES = ["projects:read", "previews:render"] as const;
+export const MCP_PATH = "/api/chatgpt/mcp";
+export const OAUTH_PATH = "/api/chatgpt/oauth";
+export const RESOURCE_METADATA_PATH =
+ "/.well-known/oauth-protected-resource/api/chatgpt/mcp";
+
+export async function chatgptConfig() {
+ const override = await prisma.settingOverride.findUnique({
+ where: { key: "chatgptApp" },
+ select: { value: true },
+ });
+ const overrides = override ? { chatgptApp: override.value } : {};
+ const { settings } = resolveSettings(overrides, []);
+ return settings.chatgptApp;
+}
+
+export type ChatgptConfig = Awaited<ReturnType<typeof chatgptConfig>>;
+
+export function resourceUrl(config: ChatgptConfig) {
+ return `${config.issuer}${MCP_PATH}`;
+}
diff --git a/site/src/clients/chatgpt/server/mcp.test.ts b/site/src/clients/chatgpt/server/mcp.test.ts
new file mode 100644
index 00000000..48a771ad
--- /dev/null
+++ b/site/src/clients/chatgpt/server/mcp.test.ts
@@ -0,0 +1,181 @@
+import { describe, expect, test } from "bun:test";
+import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
+import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
+import { SETTINGS } from "@/lib/config/registry";
+import { createChatgptServer } from "@/clients/chatgpt/server/mcp";
+import { WIDGET_URI } from "@/clients/chatgpt/contracts";
+import type { ProjectResult } from "@/clients/chatgpt/server/projects";
+
+const config = SETTINGS.chatgptApp.schema.parse({
+ ...SETTINGS.chatgptApp.default,
+ enabled: true,
+});
+const project = {
+ id: "project",
+ name: "Project",
+ revision: "cloud:2",
+ url: "https://donkeycut.com/app/p/project",
+};
+const data: ProjectResult = {
+ view: {
+ view: "project",
+ projects: [],
+ nextCursor: null,
+ project,
+ preview: {
+ id: "preview",
+ status: "done",
+ progress: 1,
+ revision: "cloud:2",
+ },
+ canRender: true,
+ },
+ playback: {
+ url: "https://media.donkeycut.com/object?private=token",
+ expiresAt: Date.now() + 3600000,
+ },
+};
+
+describe("ChatGPT MCP protocol", () => {
+ test("tools validate inputs, expose their safety annotations, and keep signed URLs out of model content", async () => {
+ const server = createChatgptServer(
+ { userId: "owner", scopes: ["projects:read", "previews:render"] },
+ config,
+ {
+ list: async () => data,
+ status: async () => data,
+ render: async () => data,
+ },
+ );
+ const client = new Client({ name: "test", version: "1" });
+ const [serverTransport, clientTransport] =
+ InMemoryTransport.createLinkedPair();
+ await server.connect(serverTransport);
+ await client.connect(clientTransport);
+ try {
+ const { tools } = await client.listTools();
+ expect(tools).toHaveLength(4);
+ expect(
+ tools.find((tool) => tool.name === "render_preview")?.annotations,
+ ).toMatchObject({
+ readOnlyHint: false,
+ destructiveHint: false,
+ openWorldHint: false,
+ });
+ const result = await client.callTool({
+ name: "open_project",
+ arguments: { projectId: "project" },
+ });
+ expect(result.structuredContent).toEqual(data.view);
+ expect(JSON.stringify(result.content)).not.toContain("private=token");
+ expect(JSON.stringify(result.structuredContent)).not.toContain(
+ "private=token",
+ );
+ expect(result._meta).toMatchObject({ playback: data.playback });
+ const invalid = await client.callTool({
+ name: "get_preview_status",
+ arguments: { projectId: "project" },
+ });
+ expect(invalid.isError).toBe(true);
+ const resource = await client.readResource({ uri: WIDGET_URI });
+ expect(resource.contents[0].mimeType).toBe("text/html;profile=mcp-app");
+ expect(resource.contents[0]._meta).toMatchObject({
+ ui: {
+ csp: {
+ resourceDomains: [config.issuer, "https://media.donkeycut.com"],
+ },
+ },
+ });
+ } finally {
+ await client.close();
+ await server.close();
+ }
+ });
+});
+
+test("render scope requests a reconnect through the MCP authentication challenge", async () => {
+ const server = createChatgptServer(
+ { userId: "owner", scopes: ["projects:read"] },
+ config,
+ {
+ list: async () => data,
+ status: async () => data,
+ render: async () => {
+ throw new Error("must not render without scope");
+ },
+ },
+ );
+ const client = new Client({ name: "test", version: "1" });
+ const [serverTransport, clientTransport] =
+ InMemoryTransport.createLinkedPair();
+ await server.connect(serverTransport);
+ await client.connect(clientTransport);
+ try {
+ const result = await client.callTool({
+ name: "render_preview",
+ arguments: { projectId: "project" },
+ });
+ expect(result.isError).toBe(true);
+ expect(JSON.stringify(result._meta)).toContain("insufficient_scope");
+ } finally {
+ await client.close();
+ await server.close();
+ }
+});
+
+test("stateless HTTP initializes and serves independent tool requests", async () => {
+ for (const message of [
+ {
+ jsonrpc: "2.0",
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: "2025-11-25",
+ capabilities: {},
+ clientInfo: { name: "test", version: "1" },
+ },
+ },
+ {
+ jsonrpc: "2.0",
+ id: 2,
+ method: "tools/call",
+ params: { name: "open_project", arguments: { projectId: "project" } },
+ },
+ ]) {
+ const server = createChatgptServer(
+ { userId: "owner", scopes: ["projects:read"] },
+ config,
+ {
+ list: async () => data,
+ status: async () => data,
+ render: async () => data,
+ },
+ );
+ const transport = new WebStandardStreamableHTTPServerTransport({
+ sessionIdGenerator: undefined,
+ enableJsonResponse: true,
+ });
+ await server.connect(transport);
+ try {
+ const response = await transport.handleRequest(
+ new Request(`${config.issuer}/api/chatgpt/mcp`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Accept: "application/json, text/event-stream",
+ },
+ body: JSON.stringify(message),
+ }),
+ );
+ expect(response.status).toBe(200);
+ const body = await response.json();
+ expect(body.id).toBe(message.id);
+ if (message.method === "tools/call") {
+ expect(body.result.structuredContent).toEqual(data.view);
+ }
+ } finally {
+ await server.close();
+ }
+ }
+});
diff --git a/site/src/clients/chatgpt/server/mcp.ts b/site/src/clients/chatgpt/server/mcp.ts
new file mode 100644
index 00000000..0af1577f
--- /dev/null
+++ b/site/src/clients/chatgpt/server/mcp.ts
@@ -0,0 +1,253 @@
+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
+import { z } from "zod";
+import {
+ checkInMemoryRateLimit,
+ rateLimitResponse,
+} from "@/lib/inference/rate-limit";
+import {
+ viewSchema,
+ WIDGET_URI,
+ type ProjectView,
+} from "@/clients/chatgpt/contracts";
+import {
+ chatgptConfig,
+ RESOURCE_METADATA_PATH,
+ type ChatgptConfig,
+} from "@/clients/chatgpt/server/config";
+import { accessIdentity } from "@/clients/chatgpt/server/oauthTokens";
+import {
+ ProjectToolError,
+ projectTools,
+ type ProjectResult,
+} from "@/clients/chatgpt/server/projects";
+import { widgetHtml } from "@/clients/chatgpt/widget.generated";
+
+const idSchema = z.string().min(1).max(128);
+const readOnlyAnnotations = {
+ readOnlyHint: true,
+ destructiveHint: false,
+ openWorldHint: false,
+ idempotentHint: true,
+};
+
+type Identity = { userId: string; scopes: string[] };
+export function createChatgptServer(
+ identity: Identity,
+ config: ChatgptConfig,
+ projects = projectTools(identity, config),
+) {
+ const server = new McpServer({ name: "donkey-cut", version: "1.0.0" });
+ const readMetadata = {
+ securitySchemes: [{ type: "oauth2", scopes: ["projects:read"] }],
+ };
+ const renderMetadata = {
+ securitySchemes: [
+ { type: "oauth2", scopes: ["projects:read", "previews:render"] },
+ ],
+ };
+ const runTool = async (run: () => Promise<ProjectResult>) => {
+ try {
+ const { view, playback } = await run();
+ const text = describeProjectView(view);
+ return {
+ content: [{ type: "text" as const, text }],
+ structuredContent: view,
+ _meta: { playback, pollMs: config.pollMs },
+ };
+ } catch (error) {
+ if (!(error instanceof ProjectToolError)) {
+ console.error(
+ "[chatgpt] project tool failed",
+ error instanceof Error ? error.name : "Unknown error",
+ );
+ }
+ const message =
+ error instanceof ProjectToolError
+ ? error.message
+ : "Donkey Cut could not complete this request. Try again shortly.";
+ return {
+ isError: true,
+ content: [{ type: "text" as const, text: message }],
+ };
+ }
+ };
+
+ server.registerTool(
+ "list_projects",
+ {
+ title: "List Donkey Cut cloud projects",
+ description:
+ "List the connected user's saved cloud projects. Browser and Mac projects become available after being saved to the cloud. Follow nextCursor for more results.",
+ inputSchema: { cursor: idSchema.optional() },
+ outputSchema: viewSchema,
+ annotations: readOnlyAnnotations,
+ _meta: readMetadata,
+ },
+ ({ cursor }) => runTool(() => projects.list(cursor)),
+ );
+
+ server.registerTool(
+ "open_project",
+ {
+ title: "Open a Donkey Cut preview",
+ description:
+ "Show a selected cloud project and its latest available preview. The preview can be from an earlier edit; render_preview renders the current saved revision. With no projectId, show the project picker.",
+ inputSchema: { projectId: idSchema.optional() },
+ outputSchema: viewSchema,
+ annotations: readOnlyAnnotations,
+ _meta: { ...readMetadata, ui: { resourceUri: WIDGET_URI } },
+ },
+ ({ projectId }) =>
+ runTool(() => (projectId ? projects.status(projectId) : projects.list())),
+ );
+
+ server.registerTool(
+ "render_preview",
+ {
+ title: "Render a Donkey Cut preview",
+ description:
+ "Render the current saved cloud project into a playable preview. Returns a job immediately; use get_preview_status to check it. Reuses a render of the same saved revision. Consumes no AI credits. Does not edit the project.",
+ inputSchema: { projectId: idSchema },
+ outputSchema: viewSchema,
+ annotations: { ...readOnlyAnnotations, readOnlyHint: false },
+ _meta: renderMetadata,
+ },
+ ({ projectId }) => {
+ if (!identity.scopes.includes("previews:render")) {
+ return {
+ isError: true,
+ content: [
+ {
+ type: "text",
+ text: "Reconnect Donkey Cut to allow preview rendering.",
+ },
+ ],
+ _meta: {
+ "mcp/www_authenticate": [
+ `Bearer error="insufficient_scope", resource_metadata="${config.issuer}${RESOURCE_METADATA_PATH}", scope="projects:read previews:render"`,
+ ],
+ },
+ };
+ }
+ return runTool(() => projects.render(projectId));
+ },
+ );
+
+ server.registerTool(
+ "get_preview_status",
+ {
+ title: "Check a Donkey Cut preview",
+ description:
+ "Read render progress or renew the playback URL of an existing preview. Returns expired when the preview needs rendering again.",
+ inputSchema: { projectId: idSchema, jobId: idSchema },
+ outputSchema: viewSchema,
+ annotations: readOnlyAnnotations,
+ _meta: readMetadata,
+ },
+ ({ projectId, jobId }) => runTool(() => projects.status(projectId, jobId)),
+ );
+
+ server.registerResource(
+ "project-preview",
+ WIDGET_URI,
+ { mimeType: "text/html;profile=mcp-app" },
+ async () => ({
+ contents: [
+ {
+ uri: WIDGET_URI,
+ mimeType: "text/html;profile=mcp-app",
+ text: widgetHtml(config.issuer),
+ _meta: {
+ ui: {
+ prefersBorder: true,
+ domain: "https://chatgpt.donkeycut.com",
+ csp: {
+ connectDomains: ["https://media.donkeycut.com"],
+ resourceDomains: [config.issuer, "https://media.donkeycut.com"],
+ },
+ },
+ "openai/widgetDescription":
+ "Donkey Cut cloud project picker and video preview with render progress and an Open in Donkey Cut link.",
+ },
+ },
+ ],
+ }),
+ );
+ return server;
+}
+
+function describeProjectView(view: ProjectView): string {
+ if (view.view === "projects") {
+ if (!view.projects.length) {
+ return "No cloud projects yet. Open Donkey Cut to save a project to the cloud.";
+ }
+ return view.projects
+ .map((project) => `${project.name}: ${project.id} (${project.url})`)
+ .join("\n");
+ }
+
+ const project = view.project!;
+ const previewStatus = view.preview
+ ? `preview ${view.preview.status}`
+ : "no preview yet";
+ return `${project.name}: ${previewStatus}. Open in Donkey Cut: ${project.url}`;
+}
+
+/** POST /api/chatgpt/mcp: this protocol accepts scoped OAuth access tokens. */
+export async function mcpEndpoint(request: Request) {
+ const config = await chatgptConfig();
+ if (!config.enabled) {
+ return new Response("ChatGPT connection is not enabled.", { status: 503 });
+ }
+ // ChatGPT's server-to-server transport has no Origin. Browser callers use the app bridge.
+ const origin = request.headers.get("origin");
+ if (origin && origin !== config.issuer) {
+ return new Response("Forbidden", { status: 403 });
+ }
+
+ const authorizationHeader = request.headers.get("authorization");
+ const identity =
+ authorizationHeader && /^Bearer /i.test(authorizationHeader)
+ ? await accessIdentity(authorizationHeader.slice(7), config)
+ : null;
+ if (!identity || !identity.scopes.includes("projects:read")) {
+ return new Response(null, {
+ status: identity ? 403 : 401,
+ headers: {
+ "WWW-Authenticate": `Bearer resource_metadata="${config.issuer}${RESOURCE_METADATA_PATH}", scope="projects:read previews:render"`,
+ "Cache-Control": "no-store",
+ },
+ });
+ }
+
+ const rateLimit = checkInMemoryRateLimit({
+ key: `chatgpt:mcp:${identity.userId}`,
+ limit: config.requestsPerMinute,
+ windowMs: 60000,
+ });
+ if (!rateLimit.ok) {
+ return rateLimitResponse(rateLimit.retryAfterSeconds);
+ }
+
+ const server = createChatgptServer(identity, config);
+ const transport = new WebStandardStreamableHTTPServerTransport({
+ sessionIdGenerator: undefined,
+ enableJsonResponse: true,
+ });
+ try {
+ await server.connect(transport);
+ const response = await transport.handleRequest(request);
+ // Materialize the JSON response before closing this stateless request's transport.
+ const body = await response.arrayBuffer();
+ return new Response(body.byteLength ? body : null, {
+ status: response.status,
+ headers: {
+ ...Object.fromEntries(response.headers),
+ "Cache-Control": "no-store",
+ },
+ });
+ } finally {
+ await server.close();
+ }
+}
diff --git a/site/src/clients/chatgpt/server/oauth.test.ts b/site/src/clients/chatgpt/server/oauth.test.ts
new file mode 100644
index 00000000..d272f6c1
--- /dev/null
+++ b/site/src/clients/chatgpt/server/oauth.test.ts
@@ -0,0 +1,361 @@
+import { describe, expect, test } from "bun:test";
+import type { prisma } from "@/lib/prisma";
+import { SETTINGS } from "@/lib/config/registry";
+import { CLIENT_ID, resourceUrl } from "@/clients/chatgpt/server/config";
+import {
+ authorizeInput,
+ newToken,
+ pkceChallenge,
+ tokenHash,
+ type Exchange,
+ type Authorization,
+} from "@/clients/chatgpt/server/oauthPolicy";
+import {
+ accessIdentity,
+ createCode,
+ exchangeToken,
+ revokeToken,
+} from "@/clients/chatgpt/server/oauthTokens";
+
+const config = SETTINGS.chatgptApp.schema.parse({
+ ...SETTINGS.chatgptApp.default,
+ enabled: true,
+});
+const verifier = "a".repeat(43);
+const input: Authorization = {
+ response_type: "code" as const,
+ client_id: CLIENT_ID,
+ redirect_uri: config.redirectUris[0],
+ resource: resourceUrl(config),
+ scope: "projects:read previews:render",
+ state: "opaque-state",
+ code_challenge_method: "S256" as const,
+ code_challenge: pkceChallenge(verifier),
+};
+
+type Grant = {
+ id: string;
+ userId: string;
+ clientId: string;
+ resource: string;
+ scope: string;
+ redirectUri: string;
+ challenge: string;
+ expiresAt: Date;
+ revokedAt: Date | null;
+};
+type Token = {
+ hash: string;
+ grantId: string;
+ kind: string;
+ expiresAt: Date;
+ consumedAt: Date | null;
+};
+function createTestContext() {
+ const grants = new Map<string, Grant>(),
+ tokens = new Map<string, Token>();
+ const tx = {
+ chatgptGrant: {
+ create: async ({
+ data,
+ }: {
+ data: Omit<Grant, "id" | "revokedAt"> & {
+ tokens: { create: Omit<Token, "grantId" | "consumedAt"> };
+ };
+ }) => {
+ const id = `grant-${grants.size}`;
+ grants.set(id, { ...data, id, revokedAt: null });
+ tokens.set(data.tokens.create.hash, {
+ ...data.tokens.create,
+ grantId: id,
+ consumedAt: null,
+ });
+ },
+ update: async ({
+ where,
+ data,
+ }: {
+ where: { id: string };
+ data: { revokedAt: Date };
+ }) => Object.assign(grants.get(where.id)!, data),
+ },
+ chatgptToken: {
+ findUnique: async ({ where }: { where: { hash: string } }) => {
+ const token = tokens.get(where.hash);
+ return token
+ ? { ...token, grant: { ...grants.get(token.grantId)! } }
+ : null;
+ },
+ updateMany: async ({
+ where,
+ data,
+ }: {
+ where: { hash: string };
+ data: { consumedAt: Date };
+ }) => {
+ const token = tokens.get(where.hash);
+ if (!token || token.consumedAt || token.expiresAt <= new Date()) {
+ return { count: 0 };
+ }
+ Object.assign(token, data);
+ return { count: 1 };
+ },
+ createMany: async ({ data }: { data: Omit<Token, "consumedAt">[] }) => {
+ for (const row of data) {
+ tokens.set(row.hash, { ...row, consumedAt: null });
+ }
+ },
+ },
+ };
+ const db = {
+ ...tx,
+ $transaction: async (run: (tx: unknown) => Promise<unknown>) => run(tx),
+ } as unknown as typeof prisma;
+ const exchange = (
+ code: string,
+ ): Extract<Exchange, { grant_type: "authorization_code" }> => ({
+ grant_type: "authorization_code",
+ client_id: CLIENT_ID,
+ resource: input.resource,
+ code,
+ redirect_uri: input.redirect_uri,
+ code_verifier: verifier,
+ });
+ return { db, grants, tokens, exchange };
+}
+
+describe("ChatGPT OAuth boundary", () => {
+ test("authorization accepts only exact callbacks, resource, public client, and S256", () => {
+ expect(authorizeInput(new URLSearchParams(input), config)).toEqual(input);
+ for (const patch of [
+ { redirect_uri: `${input.redirect_uri}/other` },
+ { redirect_uri: `${input.redirect_uri}?next=https://attacker.test` },
+ { resource: "https://attacker.test" },
+ { client_id: "someone-else" },
+ { code_challenge_method: "plain" },
+ { scope: "projects:read admin" },
+ { scope: "previews:render" },
+ { state: "" },
+ ]) {
+ expect(
+ authorizeInput(new URLSearchParams({ ...input, ...patch }), config),
+ ).toBeNull();
+ }
+ const repeated = new URLSearchParams(input);
+ repeated.append("redirect_uri", input.redirect_uri);
+ expect(authorizeInput(repeated, config)).toBeNull();
+ });
+ test("PKCE matches the RFC 7636 vector", () => {
+ expect(pkceChallenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")).toBe(
+ "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
+ );
+ });
+ test("wrong verifier and callback cannot consume a code; successful exchange stores only hashes", async () => {
+ const { db, tokens, exchange } = createTestContext();
+ const code = await createCode("owner", input, config, db);
+ const valid = exchange(code);
+ expect(
+ await exchangeToken(
+ { ...valid, code_verifier: "b".repeat(43) },
+ config,
+ db,
+ ),
+ ).toBeNull();
+ expect(
+ await exchangeToken(
+ { ...valid, redirect_uri: "https://attacker.test" },
+ config,
+ db,
+ ),
+ ).toBeNull();
+ const result = await exchangeToken(valid, config, db);
+ expect(result?.scope).toBe(input.scope);
+ expect(tokens.has(result!.access_token)).toBe(false);
+ expect(tokens.has(tokenHash(result!.access_token))).toBe(true);
+ expect(await accessIdentity(result!.access_token, config, db)).toEqual({
+ userId: "owner",
+ scopes: input.scope.split(" "),
+ });
+ expect(await accessIdentity(result!.refresh_token, config, 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);
+ const pair = await exchangeToken(exchange(code), config, db);
+ expect(await exchangeToken(exchange(code), config, db)).toBeNull();
+ expect(await accessIdentity(pair!.access_token, config, db)).toBeNull();
+ });
+ test("refresh rotation and replay revoke the entire family", async () => {
+ const { db, exchange } = createTestContext();
+ const code = await createCode("owner", input, config, db);
+ const pair = (await exchangeToken(exchange(code), config, db))!;
+ const refresh: Exchange = {
+ grant_type: "refresh_token",
+ client_id: CLIENT_ID,
+ resource: input.resource,
+ refresh_token: pair.refresh_token,
+ };
+ const rotated = await exchangeToken(refresh, config, db);
+ expect(rotated?.refresh_token === pair.refresh_token).toBe(false);
+ expect(await exchangeToken(refresh, config, db)).toBeNull();
+ expect(await accessIdentity(rotated!.access_token, config, db)).toBeNull();
+ });
+ test("resource substitution, expired tokens, and revocation deny access", async () => {
+ const { db, exchange, tokens } = createTestContext();
+ const code = await createCode("owner", input, config, db);
+ expect(
+ await exchangeToken(
+ { ...exchange(code), resource: "https://attacker.test" },
+ config,
+ db,
+ ),
+ ).toBeNull();
+ const pair = (await exchangeToken(exchange(code), config, db))!;
+ expect(
+ await accessIdentity(
+ pair.access_token,
+ { ...config, issuer: "https://another.test" },
+ db,
+ ),
+ ).toBeNull();
+ tokens.get(tokenHash(pair.access_token))!.expiresAt = new Date(0);
+ expect(await accessIdentity(pair.access_token, config, db)).toBeNull();
+ await revokeToken(pair.refresh_token, config, db);
+ expect(
+ await exchangeToken(
+ {
+ grant_type: "refresh_token",
+ client_id: CLIENT_ID,
+ resource: input.resource,
+ refresh_token: pair.refresh_token,
+ },
+ config,
+ db,
+ ),
+ ).toBeNull();
+ expect(await accessIdentity(newToken(), config, db)).toBeNull();
+ });
+ test("concurrent code exchanges cannot both issue tokens", async () => {
+ const { db, exchange } = createTestContext();
+ const code = await createCode("owner", input, config, db);
+ const results = await Promise.all([
+ exchangeToken(exchange(code), config, db),
+ exchangeToken(exchange(code), config, db),
+ ]);
+ expect(results.filter(Boolean)).toHaveLength(1);
+ });
+});
+
+test("configuration rejects malformed or non-HTTPS issuer and callbacks without throwing", () => {
+ for (const issuer of [
+ "invalid",
+ "http://donkeycut.com",
+ "https://donkeycut.com/path",
+ "https://donkeycut.com/",
+ ]) {
+ expect(
+ SETTINGS.chatgptApp.schema.safeParse({ ...config, issuer }).success,
+ ).toBe(false);
+ }
+ for (const redirect of [
+ "invalid",
+ "http://chatgpt.com/callback",
+ "https://chatgpt.com/callback#fragment",
+ ]) {
+ expect(
+ SETTINGS.chatgptApp.schema.safeParse({
+ ...config,
+ redirectUris: [redirect],
+ }).success,
+ ).toBe(false);
+ }
+});
+
+describe("OAuth per-user limits", () => {
+ const limitedConfig = { ...config, requestsPerMinute: 2 };
+
+ test("invalid proof cannot exhaust a user's budget, and another user can still exchange", async () => {
+ const { db, tokens, exchange } = createTestContext();
+ const first = await createCode("limited-exchange-owner", input, config, db);
+ const second = await createCode(
+ "limited-exchange-owner",
+ input,
+ config,
+ db,
+ );
+ const third = await createCode("limited-exchange-owner", input, config, db);
+ const other = await createCode("other-exchange-owner", input, config, db);
+
+ for (let attempt = 0; attempt < 3; attempt++) {
+ expect(
+ await exchangeToken(
+ { ...exchange(first), code_verifier: "wrong" },
+ limitedConfig,
+ db,
+ ),
+ ).toBeNull();
+ }
+ expect(
+ await exchangeToken(exchange(first), limitedConfig, db),
+ ).not.toBeNull();
+ expect(
+ await exchangeToken(exchange(second), limitedConfig, db),
+ ).not.toBeNull();
+ await expect(
+ exchangeToken(exchange(third), limitedConfig, db),
+ ).rejects.toThrow("OAuth request limit reached");
+ expect(tokens.get(tokenHash(third))?.consumedAt).toBeNull();
+ expect(
+ await exchangeToken(exchange(other), limitedConfig, db),
+ ).not.toBeNull();
+ });
+
+ test("rotation preserves the user budget and replay still revokes a throttled connection", async () => {
+ const { db, tokens, exchange } = createTestContext();
+ const code = await createCode("limited-refresh-owner", input, config, db);
+ const pair = (await exchangeToken(exchange(code), limitedConfig, db))!;
+ const refresh = (refreshToken: string): Exchange => ({
+ grant_type: "refresh_token",
+ client_id: CLIENT_ID,
+ resource: input.resource,
+ refresh_token: refreshToken,
+ });
+ const rotated = (await exchangeToken(
+ refresh(pair.refresh_token),
+ limitedConfig,
+ db,
+ ))!;
+ await expect(
+ exchangeToken(refresh(rotated.refresh_token), limitedConfig, db),
+ ).rejects.toThrow("OAuth request limit reached");
+ expect(tokens.get(tokenHash(rotated.refresh_token))?.consumedAt).toBeNull();
+ expect(
+ await exchangeToken(refresh(pair.refresh_token), limitedConfig, db),
+ ).toBeNull();
+ expect(await accessIdentity(rotated.access_token, config, db)).toBeNull();
+ });
+
+ test("revocation has its own per-user budget and leaves a throttled grant unchanged", async () => {
+ const { db, grants, tokens, exchange } = createTestContext();
+ const first = await createCode("limited-revoke-owner", input, config, db);
+ const second = await createCode("limited-revoke-owner", input, config, db);
+ const third = await createCode("limited-revoke-owner", input, config, db);
+ const other = await createCode("other-revoke-owner", input, config, db);
+
+ await revokeToken(first, limitedConfig, db);
+ await revokeToken(second, limitedConfig, db);
+ await expect(revokeToken(third, limitedConfig, db)).rejects.toThrow(
+ "OAuth request limit reached",
+ );
+ expect(
+ grants.get(tokens.get(tokenHash(third))!.grantId)?.revokedAt,
+ ).toBeNull();
+ await revokeToken(other, limitedConfig, db);
+ expect(
+ grants.get(tokens.get(tokenHash(other))!.grantId)?.revokedAt,
+ ).not.toBeNull();
+ expect(
+ await exchangeToken(exchange(third), limitedConfig, db),
+ ).not.toBeNull();
+ });
+});
diff --git a/site/src/clients/chatgpt/server/oauthPolicy.ts b/site/src/clients/chatgpt/server/oauthPolicy.ts
new file mode 100644
index 00000000..df97cb8a
--- /dev/null
+++ b/site/src/clients/chatgpt/server/oauthPolicy.ts
@@ -0,0 +1,81 @@
+import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
+import { z } from "zod";
+import {
+ CLIENT_ID,
+ SCOPES,
+ resourceUrl,
+ type ChatgptConfig,
+} from "@/clients/chatgpt/server/config";
+
+export const tokenHash = (value: string) =>
+ createHash("sha256").update(value).digest("hex");
+export const newToken = () => randomBytes(32).toString("base64url");
+export const pkceChallenge = (verifier: string) =>
+ createHash("sha256").update(verifier).digest("base64url");
+export function sameSecret(a: string, b: string) {
+ const left = Buffer.from(a);
+ const right = Buffer.from(b);
+ return left.length === right.length && timingSafeEqual(left, right);
+}
+
+export const authorizationSchema = z.object({
+ response_type: z.literal("code"),
+ client_id: z.literal(CLIENT_ID),
+ redirect_uri: z.url(),
+ scope: z.string().min(1).max(200),
+ state: z.string().min(1).max(2048),
+ code_challenge: z.string().regex(/^[A-Za-z0-9_-]{43}$/),
+ code_challenge_method: z.literal("S256"),
+ resource: z.url(),
+});
+export type Authorization = z.infer<typeof authorizationSchema>;
+
+export function authorizeInput(
+ params: URLSearchParams,
+ config: ChatgptConfig,
+): Authorization | null {
+ if ([...params.keys()].some((key) => params.getAll(key).length !== 1)) {
+ return null;
+ }
+ const parsed = authorizationSchema.safeParse(Object.fromEntries(params));
+ if (!parsed.success) {
+ return null;
+ }
+ const input = parsed.data;
+ if (!config.redirectUris.includes(input.redirect_uri)) {
+ return null;
+ }
+ if (input.resource !== resourceUrl(config)) {
+ return null;
+ }
+ const scopes = input.scope.split(" ");
+ if (!scopes.includes("projects:read")) {
+ return null;
+ }
+ const hasUnknownScope = scopes.some(
+ (scope) => !SCOPES.some((known) => known === scope),
+ );
+ if (hasUnknownScope) {
+ return null;
+ }
+ return input;
+}
+
+export const exchangeSchema = z.discriminatedUnion("grant_type", [
+ z.object({
+ grant_type: z.literal("authorization_code"),
+ client_id: z.literal(CLIENT_ID),
+ resource: z.url(),
+ code: z.string().min(32).max(128),
+ redirect_uri: z.url(),
+ code_verifier: z.string().regex(/^[A-Za-z0-9._~-]{43,128}$/),
+ }),
+ z.object({
+ grant_type: z.literal("refresh_token"),
+ client_id: z.literal(CLIENT_ID),
+ resource: z.url(),
+ refresh_token: z.string().min(32).max(128),
+ scope: z.string().optional(),
+ }),
+]);
+export type Exchange = z.infer<typeof exchangeSchema>;
diff --git a/site/src/clients/chatgpt/server/oauthRateLimit.test.ts b/site/src/clients/chatgpt/server/oauthRateLimit.test.ts
new file mode 100644
index 00000000..8e97d6bc
--- /dev/null
+++ b/site/src/clients/chatgpt/server/oauthRateLimit.test.ts
@@ -0,0 +1,39 @@
+import { expect, test } from "bun:test";
+import { limitOAuthSource } from "@/clients/chatgpt/server/oauthRateLimit";
+import { SETTINGS } from "@/lib/config/registry";
+
+function requestFrom(address: string) {
+ return new Request("https://donkeycut.com/api/chatgpt/oauth/token", {
+ headers: { "x-vercel-forwarded-for": address },
+ });
+}
+
+test("source abuse is isolated by address and endpoint", () => {
+ const abusiveSource = requestFrom("192.0.2.1");
+ expect(limitOAuthSource(abusiveSource, "token", 2)).toBeNull();
+ expect(limitOAuthSource(abusiveSource, "token", 2)).toBeNull();
+ const limited = limitOAuthSource(abusiveSource, "token", 2);
+ expect(limited?.status).toBe(429);
+ expect(Number(limited?.headers.get("Retry-After"))).toBeGreaterThan(0);
+ expect(limitOAuthSource(requestFrom("192.0.2.2"), "token", 2)).toBeNull();
+ expect(limitOAuthSource(abusiveSource, "revoke", 2)).toBeNull();
+});
+
+test("missing trusted addresses never share a catch-all bucket", () => {
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const request = new Request("http://localhost/api/chatgpt/oauth/token", {
+ headers: { "x-forwarded-for": "192.0.2.1", "x-real-ip": "192.0.2.1" },
+ });
+ expect(limitOAuthSource(request, "token", 2)).toBeNull();
+ }
+});
+
+test("existing app settings receive the source limit without losing enabled state", () => {
+ const { oauthRequestsPerIpMinute, ...existing } = SETTINGS.chatgptApp.default;
+ const parsed = SETTINGS.chatgptApp.schema.parse({
+ ...existing,
+ enabled: true,
+ });
+ expect(parsed.enabled).toBe(true);
+ expect(parsed.oauthRequestsPerIpMinute).toBe(oauthRequestsPerIpMinute);
+});
diff --git a/site/src/clients/chatgpt/server/oauthRateLimit.ts b/site/src/clients/chatgpt/server/oauthRateLimit.ts
new file mode 100644
index 00000000..4b43a357
--- /dev/null
+++ b/site/src/clients/chatgpt/server/oauthRateLimit.ts
@@ -0,0 +1,48 @@
+import { isIP } from "node:net";
+import {
+ checkInMemoryRateLimit,
+ rateLimitResponse,
+} from "@/lib/inference/rate-limit";
+import { tokenHash } from "@/clients/chatgpt/server/oauthPolicy";
+
+type OAuthOperation = "token" | "revoke";
+
+export class OAuthRateLimitError extends Error {
+ constructor(public readonly retryAfterSeconds: number) {
+ super("OAuth request limit reached.");
+ }
+}
+
+/** Limit unauthenticated traffic using the address supplied by the hosting proxy. */
+export function limitOAuthSource(
+ request: Request,
+ operation: OAuthOperation,
+ requestsPerMinute: number,
+): Response | null {
+ const address = request.headers.get("x-vercel-forwarded-for")?.trim();
+ // Local servers lack Vercel's trusted address; their authenticated user limits still apply.
+ if (!address || !isIP(address)) return null;
+
+ const rateLimit = checkInMemoryRateLimit({
+ key: `chatgpt:oauth:${operation}:source:${tokenHash(address)}`,
+ limit: requestsPerMinute,
+ windowMs: 60_000,
+ });
+ return rateLimit.ok ? null : rateLimitResponse(rateLimit.retryAfterSeconds);
+}
+
+/** Call only after the credential and its owner have been verified. */
+export function enforceOAuthUserLimit(
+ userId: string,
+ operation: OAuthOperation,
+ requestsPerMinute: number,
+): void {
+ const rateLimit = checkInMemoryRateLimit({
+ key: `chatgpt:oauth:${operation}:user:${userId}`,
+ limit: requestsPerMinute,
+ windowMs: 60_000,
+ });
+ if (!rateLimit.ok) {
+ throw new OAuthRateLimitError(rateLimit.retryAfterSeconds);
+ }
+}
diff --git a/site/src/clients/chatgpt/server/oauthRoutes.ts b/site/src/clients/chatgpt/server/oauthRoutes.ts
new file mode 100644
index 00000000..e457791f
--- /dev/null
+++ b/site/src/clients/chatgpt/server/oauthRoutes.ts
@@ -0,0 +1,389 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { getDonkeyAuthContext, withDonkeyAuth } from "@/lib/donkey-api-auth";
+import {
+ checkInMemoryRateLimit,
+ rateLimitResponse,
+} from "@/lib/inference/rate-limit";
+import { prisma } from "@/lib/prisma";
+import {
+ CLIENT_ID,
+ chatgptConfig,
+ OAUTH_PATH,
+ SCOPES,
+ resourceUrl,
+} from "@/clients/chatgpt/server/config";
+import {
+ authorizationSchema,
+ authorizeInput,
+ exchangeSchema,
+ newToken,
+ sameSecret,
+ tokenHash,
+ type Authorization,
+} from "@/clients/chatgpt/server/oauthPolicy";
+import {
+ createCode,
+ exchangeToken,
+ revokeToken,
+} from "@/clients/chatgpt/server/oauthTokens";
+
+import {
+ limitOAuthSource,
+ OAuthRateLimitError,
+} from "@/clients/chatgpt/server/oauthRateLimit";
+
+const NO_STORE_HEADERS = { "Cache-Control": "no-store", Pragma: "no-cache" };
+const CONSENT_COOKIE_NAME = "__Host-donkey-chatgpt-consent";
+const consentSchema = z.object({
+ nonce: z.string().regex(/^[A-Za-z0-9_-]{43}$/),
+ decision: z.enum(["allow", "deny"]),
+});
+
+export async function authorizationMetadata() {
+ await connection();
+ const config = await chatgptConfig();
+ if (!config.enabled) {
+ return oauthError("temporarily_unavailable", 503);
+ }
+
+ const baseUrl = `${config.issuer}${OAUTH_PATH}`;
+ 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,
+ },
+ { headers: NO_STORE_HEADERS },
+ );
+}
+
+export async function protectedResourceMetadata() {
+ await connection();
+ const config = await chatgptConfig();
+ if (!config.enabled) {
+ return oauthError("temporarily_unavailable", 503);
+ }
+
+ return Response.json(
+ {
+ resource: resourceUrl(config),
+ authorization_servers: [config.issuer],
+ scopes_supported: SCOPES,
+ bearer_methods_supported: ["header"],
+ resource_name: "Donkey Cut",
+ },
+ { headers: NO_STORE_HEADERS },
+ );
+}
+
+/** GET /api/chatgpt/oauth/authorize: validate before login or consent. */
+export async function authorize(request: Request) {
+ const config = await chatgptConfig();
+ if (!config.enabled) {
+ return oauthError("temporarily_unavailable", 503);
+ }
+
+ const searchParams = new URL(request.url).searchParams;
+ const authorization = authorizeInput(searchParams, config);
+ if (!authorization) {
+ return oauthError("invalid_request");
+ }
+
+ const identity = await getDonkeyAuthContext(request.headers);
+ if (!identity) {
+ const loginUrl = new URL("/sign-in", config.issuer);
+ loginUrl.searchParams.set(
+ "callbackURL",
+ `${OAUTH_PATH}/authorize?${searchParams}`,
+ );
+ return Response.redirect(loginUrl, 303);
+ }
+
+ const rateLimit = checkInMemoryRateLimit({
+ key: `chatgpt:consent:${identity.userId}`,
+ limit: config.requestsPerMinute,
+ windowMs: 60_000,
+ });
+ if (!rateLimit.ok) {
+ return rateLimitResponse(rateLimit.retryAfterSeconds);
+ }
+
+ const nonce = newToken();
+ const identifier = `chatgpt-consent:${identity.userId}`;
+ await prisma.verification.deleteMany({
+ where: { identifier, expiresAt: { lte: new Date() } },
+ });
+ await prisma.verification.create({
+ data: {
+ id: `chatgpt:${tokenHash(nonce)}`,
+ identifier,
+ value: JSON.stringify(authorization),
+ expiresAt: new Date(Date.now() + 600_000),
+ },
+ });
+
+ return consentPage(nonce, authorization);
+}
+
+/** POST /api/chatgpt/oauth/authorize: explicit, browser-bound consent. */
+export const consent = withDonkeyAuth(async (request) => {
+ const config = await chatgptConfig();
+ if (!config.enabled) {
+ return oauthError("temporarily_unavailable", 503);
+ }
+ if (request.headers.get("origin") !== config.issuer) {
+ return oauthError("invalid_request");
+ }
+
+ const form = await readOAuthForm(request);
+ if (!form) {
+ return oauthError("invalid_request");
+ }
+ const parsed = consentSchema.safeParse(Object.fromEntries(form));
+ if (!parsed.success) {
+ return oauthError("invalid_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 challengeId = `chatgpt:${tokenHash(nonce)}`;
+ const challenge = await prisma.verification.findUnique({
+ where: { id: challengeId },
+ });
+ if (!challenge || challenge.expiresAt <= new Date()) {
+ return oauthError("invalid_request");
+ }
+ if (challenge.identifier !== `chatgpt-consent:${request.donkey.userId}`) {
+ return oauthError("invalid_request");
+ }
+
+ // Revalidate against current settings before issuing a code.
+ const authorization = authorizationSchema.parse(JSON.parse(challenge.value));
+ if (!authorizeInput(new URLSearchParams(authorization), config)) {
+ return oauthError("invalid_request");
+ }
+
+ const consumed = await prisma.verification.deleteMany({
+ where: { id: challengeId, expiresAt: { gt: new Date() } },
+ });
+ if (!consumed.count) {
+ return oauthError("invalid_request");
+ }
+
+ const callbackUrl = new URL(authorization.redirect_uri);
+ callbackUrl.searchParams.set("state", authorization.state);
+ callbackUrl.searchParams.set("iss", config.issuer);
+ if (decision === "deny") {
+ callbackUrl.searchParams.set("error", "access_denied");
+ } else {
+ const code = await createCode(request.donkey.userId, authorization, config);
+ callbackUrl.searchParams.set("code", code);
+ }
+
+ return new Response(null, {
+ status: 303,
+ headers: {
+ ...NO_STORE_HEADERS,
+ Location: callbackUrl.href,
+ "Set-Cookie": consentCookie("", 0),
+ },
+ });
+});
+
+/** POST /api/chatgpt/oauth/token: authenticate with the submitted code or refresh token. */
+export async function tokenEndpoint(request: Request) {
+ const config = await chatgptConfig();
+ if (!config.enabled) {
+ return oauthError("temporarily_unavailable", 503);
+ }
+
+ const limited = limitOAuthSource(
+ request,
+ "token",
+ config.oauthRequestsPerIpMinute,
+ );
+ if (limited) return limited;
+
+ const form = await readOAuthForm(request);
+ const input = exchangeSchema.safeParse(
+ form ? Object.fromEntries(form) : null,
+ );
+ if (!input.success) {
+ return oauthError("invalid_request");
+ }
+
+ try {
+ const tokens = await exchangeToken(input.data, config);
+ if (!tokens) return oauthError("invalid_grant");
+ return Response.json(tokens, { headers: NO_STORE_HEADERS });
+ } catch (error) {
+ if (error instanceof OAuthRateLimitError) {
+ return rateLimitResponse(error.retryAfterSeconds);
+ }
+ throw error;
+ }
+}
+
+/** POST /api/chatgpt/oauth/revoke: revoke the connection owning the submitted token. */
+export async function revocationEndpoint(request: Request) {
+ const config = await chatgptConfig();
+ if (!config.enabled) {
+ return oauthError("temporarily_unavailable", 503);
+ }
+
+ const limited = limitOAuthSource(
+ request,
+ "revoke",
+ config.oauthRequestsPerIpMinute,
+ );
+ if (limited) return limited;
+
+ const form = await readOAuthForm(request);
+ if (form?.get("client_id") !== CLIENT_ID) {
+ return oauthError("invalid_client");
+ }
+
+ const token = z
+ .string()
+ .regex(/^[A-Za-z0-9_-]{43}$/)
+ .safeParse(form.get("token"));
+ try {
+ if (token.success) await revokeToken(token.data, config);
+ return new Response(null, { status: 200, headers: NO_STORE_HEADERS });
+ } catch (error) {
+ if (error instanceof OAuthRateLimitError) {
+ return rateLimitResponse(error.retryAfterSeconds);
+ }
+ throw error;
+ }
+}
+
+async function readOAuthForm(
+ request: Request,
+): Promise<URLSearchParams | null> {
+ const contentType = request.headers.get("content-type");
+ if (!contentType?.startsWith("application/x-www-form-urlencoded")) {
+ return null;
+ }
+
+ const reader = request.body?.getReader();
+ if (!reader) {
+ return null;
+ }
+
+ const chunks: Uint8Array[] = [];
+ let byteLength = 0;
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) {
+ break;
+ }
+ byteLength += value.length;
+ if (byteLength > 8192) {
+ await reader.cancel();
+ return null;
+ }
+ chunks.push(value);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+
+ const form = new URLSearchParams(Buffer.concat(chunks).toString("utf8"));
+ const hasRepeatedFields = [...form.keys()].some(
+ (key) => form.getAll(key).length !== 1,
+ );
+ return hasRepeatedFields ? null : form;
+}
+
+function oauthError(error: string, status = 400) {
+ return Response.json({ error }, { status, headers: NO_STORE_HEADERS });
+}
+
+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) {
+ const canRender = authorization.scope.split(" ").includes("previews:render");
+ const renderPermission = canRender
+ ? " It can also render previews of your saved edits."
+ : "";
+ const escapedNonce = nonce.replace(
+ /[&<>"']/g,
+ (character) =>
+ ({
+ "&": "&amp;",
+ "<": "&lt;",
+ ">": "&gt;",
+ '"': "&quot;",
+ "'": "&#39;",
+ })[character]!,
+ );
+ const html = `<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width,initial-scale=1">
+ <title>Connect Donkey Cut to ChatGPT</title>
+ <style>
+ body { font: 17px system-ui; max-width: 460px; margin: 12vh auto; padding: 24px; color: #202020; background: #faf9f7; }
+ h1 { font-size: 30px; }
+ p { line-height: 1.6; }
+ button { font: inherit; padding: 12px 20px; border-radius: 10px; border: 1px solid #ccc; cursor: pointer; }
+ button[value=allow] { background: #202020; color: white; }
+ form { display: flex; gap: 12px; }
+ </style>
+ </head>
+ <body>
+ <h1>Connect Donkey Cut to ChatGPT</h1>
+ <p>ChatGPT can read your cloud project names and play their previews.${renderPermission}</p>
+ <p>Preview rendering uses no AI credits. Your existing storage allowance applies to retained media.</p>
+ <form method="post" action="${OAUTH_PATH}/authorize">
+ <input type="hidden" name="nonce" value="${escapedNonce}">
+ <button name="decision" value="allow">Connect</button>
+ <button name="decision" value="deny">Cancel</button>
+ </form>
+ </body>
+</html>`;
+
+ // Chromium applies form-action to the redirect after the consent POST, too.
+ const callbackOrigin = new URL(authorization.redirect_uri).origin;
+ const contentSecurityPolicy = [
+ "default-src 'none'",
+ "style-src 'unsafe-inline'",
+ `form-action 'self' ${callbackOrigin}`,
+ "frame-ancestors 'none'",
+ "base-uri 'none'",
+ ].join("; ");
+
+ return new Response(html, {
+ headers: {
+ ...NO_STORE_HEADERS,
+ "Content-Type": "text/html; charset=utf-8",
+ "Set-Cookie": consentCookie(nonce, 600),
+ "Content-Security-Policy": contentSecurityPolicy,
+ // Preserve the same-origin POST's Origin for consent validation.
+ "Referrer-Policy": "strict-origin-when-cross-origin",
+ "X-Content-Type-Options": "nosniff",
+ },
+ });
+}
diff --git a/site/src/clients/chatgpt/server/oauthTokens.ts b/site/src/clients/chatgpt/server/oauthTokens.ts
new file mode 100644
index 00000000..7ce29178
--- /dev/null
+++ b/site/src/clients/chatgpt/server/oauthTokens.ts
@@ -0,0 +1,213 @@
+import type { ChatgptGrant, Prisma } from "@/generated/prisma/client";
+import { prisma } from "@/lib/prisma";
+import {
+ CLIENT_ID,
+ resourceUrl,
+ type ChatgptConfig,
+} from "@/clients/chatgpt/server/config";
+import {
+ newToken,
+ pkceChallenge,
+ sameSecret,
+ tokenHash,
+ type Authorization,
+ type Exchange,
+} from "@/clients/chatgpt/server/oauthPolicy";
+
+import { enforceOAuthUserLimit } from "@/clients/chatgpt/server/oauthRateLimit";
+
+/** The code and every rotated token belong to one revocable connection. */
+export async function createCode(
+ userId: string,
+ authorization: Authorization,
+ config: ChatgptConfig,
+ db = prisma,
+) {
+ 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),
+ },
+ },
+ },
+ });
+ return code;
+}
+
+export async function exchangeToken(
+ input: Exchange,
+ config: ChatgptConfig,
+ db = prisma,
+) {
+ if (input.resource !== resourceUrl(config)) {
+ return null;
+ }
+
+ const isRefresh = input.grant_type === "refresh_token";
+ const credential = isRefresh ? input.refresh_token : input.code;
+ const expectedKind = isRefresh ? "refresh" : "code";
+ const hash = tokenHash(credential);
+
+ return db.$transaction(async (tx) => {
+ const token = await tx.chatgptToken.findUnique({
+ where: { hash },
+ include: { grant: true },
+ });
+ if (!token || token.kind !== expectedKind) {
+ return null;
+ }
+
+ const grant = token.grant;
+ if (
+ grant.clientId !== input.client_id ||
+ grant.resource !== input.resource
+ ) {
+ return null;
+ }
+ if (grant.revokedAt || grant.expiresAt <= new Date()) {
+ return null;
+ }
+
+ if (input.grant_type === "authorization_code") {
+ if (grant.redirectUri !== input.redirect_uri) {
+ return null;
+ }
+ if (!sameSecret(grant.challenge, pkceChallenge(input.code_verifier))) {
+ return null;
+ }
+ } else if (input.scope !== undefined && input.scope !== grant.scope) {
+ return null;
+ }
+
+ // Consumed hashes remain until the grant expires, so replay revokes the connection.
+ if (token.consumedAt) {
+ await tx.chatgptGrant.update({
+ where: { id: grant.id },
+ data: { revokedAt: new Date() },
+ });
+ return null;
+ }
+ if (token.expiresAt <= new Date()) {
+ return null;
+ }
+
+ // Throttling leaves the credential usable when this user's window resets.
+ enforceOAuthUserLimit(grant.userId, "token", config.requestsPerMinute);
+
+ // Only one exchange can consume the credential, including concurrent requests.
+ const consumed = await tx.chatgptToken.updateMany({
+ where: { hash, consumedAt: null, expiresAt: { gt: new Date() } },
+ data: { consumedAt: new Date() },
+ });
+ if (!consumed.count) {
+ await tx.chatgptGrant.update({
+ where: { id: grant.id },
+ data: { revokedAt: new Date() },
+ });
+ return null;
+ }
+
+ return issueTokenPair(tx, grant, config);
+ });
+}
+
+async function issueTokenPair(
+ tx: Prisma.TransactionClient,
+ grant: Pick<ChatgptGrant, "id" | "scope" | "expiresAt">,
+ config: ChatgptConfig,
+) {
+ const grantSecondsRemaining = Math.floor(
+ (grant.expiresAt.getTime() - Date.now()) / 1000,
+ );
+ const accessSeconds = Math.min(config.accessSeconds, grantSecondsRemaining);
+ if (accessSeconds <= 0) {
+ return null;
+ }
+
+ const accessToken = newToken();
+ const refreshToken = newToken();
+ await tx.chatgptToken.createMany({
+ data: [
+ {
+ hash: tokenHash(accessToken),
+ grantId: grant.id,
+ kind: "access",
+ expiresAt: new Date(Date.now() + accessSeconds * 1000),
+ },
+ {
+ hash: tokenHash(refreshToken),
+ grantId: grant.id,
+ kind: "refresh",
+ expiresAt: grant.expiresAt,
+ },
+ ],
+ });
+
+ return {
+ access_token: accessToken,
+ refresh_token: refreshToken,
+ token_type: "Bearer",
+ expires_in: accessSeconds,
+ scope: grant.scope,
+ };
+}
+
+export async function accessIdentity(
+ bearer: string,
+ config: ChatgptConfig,
+ db = prisma,
+) {
+ if (!/^[A-Za-z0-9_-]{43}$/.test(bearer)) {
+ return null;
+ }
+
+ const token = await db.chatgptToken.findUnique({
+ where: { hash: tokenHash(bearer) },
+ include: { grant: true },
+ });
+ if (!token || token.kind !== "access" || 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;
+ }
+
+ return { userId: grant.userId, scopes: grant.scope.split(" ") };
+}
+
+export async function revokeToken(
+ credential: string,
+ config: ChatgptConfig,
+ db = prisma,
+) {
+ const token = await db.chatgptToken.findUnique({
+ where: { hash: tokenHash(credential) },
+ select: { grantId: true, grant: { select: { userId: true } } },
+ });
+ if (!token) {
+ return;
+ }
+
+ enforceOAuthUserLimit(token.grant.userId, "revoke", config.requestsPerMinute);
+
+ await db.chatgptGrant.update({
+ where: { id: token.grantId },
+ data: { revokedAt: new Date() },
+ });
+}
diff --git a/site/src/clients/chatgpt/server/projects.test.ts b/site/src/clients/chatgpt/server/projects.test.ts
new file mode 100644
index 00000000..6ede4709
--- /dev/null
+++ b/site/src/clients/chatgpt/server/projects.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, mock, test } from "bun:test";
+import type { prisma } from "@/lib/prisma";
+import { SETTINGS } from "@/lib/config/registry";
+import { projectTools } from "@/clients/chatgpt/server/projects";
+
+const config = SETTINGS.chatgptApp.schema.parse(SETTINGS.chatgptApp.default);
+function createTestContext() {
+ const project = { id: "mine", userId: "owner", name: "My video", version: 4 };
+ const jobs = mock(async (args: unknown) => {
+ void args;
+ return null as unknown;
+ });
+ const db = {
+ cutProject: {
+ findFirst: mock(
+ async ({ where }: { where: { id: string; userId: string } }) =>
+ where.id === project.id && where.userId === project.userId
+ ? project
+ : null,
+ ),
+ findMany: mock(async (args: unknown) => {
+ void args;
+ return [project];
+ }),
+ },
+ cutRenderJob: { findFirst: jobs },
+ cutMediaObject: {
+ findFirst: mock(async (args: unknown) => {
+ void args;
+ return null;
+ }),
+ },
+ };
+ return {
+ db,
+ tools: projectTools(
+ { userId: "owner", scopes: ["projects:read"] },
+ config,
+ db as unknown as typeof prisma,
+ ),
+ };
+}
+
+describe("ChatGPT cloud projects", () => {
+ test("foreign projects and cursors fail before reading previews or listing", async () => {
+ const { tools, db } = createTestContext();
+ await expect(tools.status("foreign", "preview")).rejects.toThrow(
+ "Project not found",
+ );
+ await expect(tools.list("foreign")).rejects.toThrow("Project not found");
+ expect(db.cutRenderJob.findFirst).not.toHaveBeenCalled();
+ expect(db.cutProject.findMany).not.toHaveBeenCalled();
+ });
+ test("read scope cannot enqueue renders", async () => {
+ const { tools } = createTestContext();
+ await expect(tools.render("mine")).rejects.toThrow("permission");
+ });
+ test("status is constrained to the owner, selected project, and preview kind", async () => {
+ const { tools, db } = createTestContext();
+ await expect(tools.status("mine", "foreign-job")).rejects.toThrow(
+ "Preview not found",
+ );
+ expect(db.cutRenderJob.findFirst.mock.calls[0][0]).toMatchObject({
+ where: {
+ userId: "owner",
+ projectId: "mine",
+ kind: "preview",
+ id: "foreign-job",
+ },
+ });
+ });
+ test("collected artifacts are reported as expired with no playback URL", async () => {
+ const { tools, db } = createTestContext();
+ db.cutRenderJob.findFirst.mockResolvedValue({
+ id: "job",
+ state: "done",
+ progress: 1,
+ outputKey: "old-preview",
+ spec: { revision: "cloud:3" },
+ });
+ const result = await tools.status("mine", "job");
+ expect(result.view.preview?.status).toBe("expired");
+ expect(result.playback).toBeNull();
+ expect(result.view.project?.revision).toBe("cloud:4");
+ });
+ test("list returns only public project metadata and paging state", async () => {
+ const { tools, db } = createTestContext();
+ const result = await tools.list();
+ expect(result.view.projects).toEqual([
+ {
+ id: "mine",
+ name: "My video",
+ revision: "cloud:4",
+ url: "https://donkeycut.com/app/p/mine",
+ },
+ ]);
+ expect(db.cutProject.findMany.mock.calls[0][0]).toMatchObject({
+ where: { userId: "owner" },
+ take: 21,
+ select: { id: true, name: true, version: true },
+ });
+ expect(result.view.canRender).toBe(false);
+ });
+});
diff --git a/site/src/clients/chatgpt/server/projects.ts b/site/src/clients/chatgpt/server/projects.ts
new file mode 100644
index 00000000..b8428835
--- /dev/null
+++ b/site/src/clients/chatgpt/server/projects.ts
@@ -0,0 +1,167 @@
+import { prisma } from "@/lib/prisma";
+import { previewFromDoc } from "@/cut/server/cloud/previewJobs";
+import { mediaObjectUrl, mediaUrlLifetime } from "@/cut/server/cloud/mediaCdn";
+import { wakeRenderWorker } from "@/cut/server/cloud/wake";
+import type { Playback, ProjectView } from "@/clients/chatgpt/contracts";
+import type { ChatgptConfig } from "@/clients/chatgpt/server/config";
+
+type Identity = { userId: string; scopes: string[] };
+export class ProjectToolError extends Error {}
+export type ProjectResult = { view: ProjectView; playback: Playback | null };
+
+export function projectTools(
+ identity: Identity,
+ config: ChatgptConfig,
+ db = prisma,
+) {
+ const canRender = identity.scopes.includes("previews:render");
+ const projectSummary = (row: {
+ id: string;
+ name: string;
+ version: number;
+ }) => ({
+ id: row.id,
+ name: row.name,
+ revision: `cloud:${row.version}`,
+ url: `${config.issuer}/app/p/${encodeURIComponent(row.id)}`,
+ });
+ const emptyProjectView = (): ProjectView => ({
+ view: "projects",
+ projects: [],
+ nextCursor: null,
+ project: null,
+ preview: null,
+ canRender,
+ });
+
+ async function getOwnedProject(projectId: string) {
+ const row = await db.cutProject.findFirst({
+ where: { id: projectId, userId: identity.userId },
+ select: { id: true, name: true, version: true },
+ });
+ if (!row) {
+ throw new ProjectToolError(
+ "Project not found. Choose one of your cloud projects.",
+ );
+ }
+ return projectSummary(row);
+ }
+
+ async function getPreviewStatus(
+ projectId: string,
+ jobId?: string,
+ ): Promise<ProjectResult> {
+ const selectedProject = await getOwnedProject(projectId);
+ const job = await db.cutRenderJob.findFirst({
+ where: {
+ userId: identity.userId,
+ projectId,
+ kind: "preview",
+ ...(jobId
+ ? { id: jobId }
+ : { state: { in: ["queued", "running", "done"] } }),
+ },
+ orderBy: { createdAt: "desc" },
+ });
+ const view: ProjectView = {
+ ...emptyProjectView(),
+ view: "project",
+ project: selectedProject,
+ };
+ if (!job) {
+ if (jobId) {
+ throw new ProjectToolError(
+ "Preview not found. Open the project again.",
+ );
+ }
+ return { view, playback: null };
+ }
+
+ const isStaleRender =
+ job.state === "running" && job.updatedAt.getTime() < Date.now() - 30_000;
+ if (job.state === "queued" || isStaleRender) {
+ wakeRenderWorker();
+ }
+
+ const status =
+ job.state === "queued" || job.state === "running" || job.state === "done"
+ ? job.state
+ : "error";
+ view.preview = {
+ id: job.id,
+ status,
+ progress: Math.max(0, Math.min(1, job.progress)),
+ revision: (job.spec as { revision?: string } | null)?.revision ?? null,
+ };
+ if (status === "error") {
+ view.preview.error = "Preview could not finish. Render a new preview.";
+ }
+ if (status !== "done") {
+ return { view, playback: null };
+ }
+
+ const media = job.outputKey
+ ? await db.cutMediaObject.findFirst({
+ where: {
+ r2Key: job.outputKey,
+ userId: identity.userId,
+ projectId,
+ kind: "preview",
+ uploadState: "complete",
+ },
+ select: { r2Key: true },
+ })
+ : null;
+ if (!media) {
+ view.preview.status = "expired";
+ return { view, playback: null };
+ }
+
+ return {
+ view,
+ playback: {
+ url: mediaObjectUrl(media.r2Key),
+ expiresAt: Date.now() + mediaUrlLifetime() * 1000,
+ },
+ };
+ }
+
+ return {
+ async list(cursor?: string): Promise<ProjectResult> {
+ // A cursor names an account-owned row, so a foreign id cannot influence pagination.
+ if (cursor) {
+ await getOwnedProject(cursor);
+ }
+ const rows = await db.cutProject.findMany({
+ where: { userId: identity.userId },
+ select: { id: true, name: true, version: true },
+ orderBy: { id: "asc" },
+ take: 21,
+ ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
+ });
+ return {
+ view: {
+ ...emptyProjectView(),
+ projects: rows.slice(0, 20).map(projectSummary),
+ nextCursor: rows.length > 20 ? rows[19].id : null,
+ },
+ playback: null,
+ };
+ },
+ status: getPreviewStatus,
+ async render(projectId: string): Promise<ProjectResult> {
+ if (!canRender) {
+ throw new ProjectToolError(
+ "Reconnect Donkey Cut with preview rendering permission.",
+ );
+ }
+ const job = await previewFromDoc(identity.userId, projectId);
+ if (!job) {
+ throw new ProjectToolError(
+ "Project not found. Choose one of your cloud projects.",
+ );
+ }
+ return getPreviewStatus(projectId, job.id);
+ },
+ };
+}
diff --git a/site/src/clients/chatgpt/ui/PreviewApp.tsx b/site/src/clients/chatgpt/ui/PreviewApp.tsx
new file mode 100644
index 00000000..91ad3dd5
--- /dev/null
+++ b/site/src/clients/chatgpt/ui/PreviewApp.tsx
@@ -0,0 +1,40 @@
+import { ArtifactVideo } from "@donkeycut/artifact-player/ArtifactVideo";
+import { useProjectApp } from "./useProjectApp";
+import "./preview.css";
+
+export function PreviewApp() {
+ const { ready, view, playback, error, busy, visible, run, playbackFailed, openDonkey } = useProjectApp();
+ const project = view?.project;
+ const preview = view?.preview;
+ const rendering = preview?.status === "queued" || preview?.status === "running";
+ return <main aria-busy={busy}>
+ <header><span className="brand">Donkey Cut</span><span>Cloud projects</span></header>
+ {error && <p role="alert" className="error">{error}</p>}
+ {!view && <p role="status">{ready ? "Choose a project to preview." : "Connecting to Donkey Cut…"}</p>}
+ {!view && ready && <button onClick={() => void run("list_projects", {})}>Load projects</button>}
+ {view?.view === "projects" && <>
+ <h1>Your projects</h1>
+ {view.projects.length === 0 && <p>Save a project to the cloud in Donkey Cut to preview it here.</p>}
+ <div className="projects">{view.projects.map((p) => <button key={p.id} disabled={busy || !ready} onClick={() => void run("open_project", { projectId: p.id })}>
+ <span>{p.name}</span><span aria-hidden="true">→</span>
+ </button>)}</div>
+ <nav>{view.nextCursor && <button disabled={busy} onClick={() => void run("list_projects", { cursor: view.nextCursor! })}>More projects</button>}
+ <button disabled={busy || !ready} onClick={() => void run("list_projects", {})}>Refresh list</button></nav>
+ </>}
+ {project && <>
+ <h1>{project.name}</h1>
+ {playback && <ArtifactVideo src={playback.url} format="file" active={visible} onError={playbackFailed} aria-label={`Preview of ${project.name}`} />}
+ {rendering && <div role="status"><p>{preview.status === "queued" ? "Waiting to render…" : `Rendering preview… ${Math.round(preview.progress * 100)}%`}</p><progress max={1} value={preview.progress} /></div>}
+ {!preview && <p>Render a preview to watch this project here.</p>}
+ {preview?.status === "expired" && <p>This preview has expired. Render it again to watch.</p>}
+ {preview?.status === "error" && <p role="alert">{preview.error}</p>}
+ {preview?.status === "done" && preview.revision !== project.revision && <p className="muted">This preview may be from an earlier edit.</p>}
+ <nav>
+ {view.canRender && <button className="primary" disabled={busy || rendering || !ready} onClick={() => void run("render_preview", { projectId: project.id })}>Render preview</button>}
+ <button disabled={!ready} onClick={() => void openDonkey()}>Open in Donkey Cut ↗</button>
+ <button disabled={busy || !ready} onClick={() => void run("list_projects", {})}>Projects</button>
+ {error && <button disabled={busy || !ready} onClick={() => void run("open_project", { projectId: project.id })}>Try again</button>}
+ </nav>
+ </>}
+ </main>;
+}
diff --git a/site/src/clients/chatgpt/ui/main.tsx b/site/src/clients/chatgpt/ui/main.tsx
new file mode 100644
index 00000000..5add2ec5
--- /dev/null
+++ b/site/src/clients/chatgpt/ui/main.tsx
@@ -0,0 +1,4 @@
+import { createRoot } from "react-dom/client";
+import { PreviewApp } from "./PreviewApp";
+
+createRoot(document.getElementById("root")!).render(<PreviewApp />);
diff --git a/site/src/clients/chatgpt/ui/preview.css b/site/src/clients/chatgpt/ui/preview.css
new file mode 100644
index 00000000..de4a21ad
--- /dev/null
+++ b/site/src/clients/chatgpt/ui/preview.css
@@ -0,0 +1,3 @@
+:root{font:14px/1.5 system-ui,sans-serif;color:#20201e;background:#faf9f7;color-scheme:light;--line:#dddcd6;--muted:#66645e;--panel:#fff}
+:root[data-theme=dark]{color:#eeede8;background:#20201e;color-scheme:dark;--line:#45443f;--muted:#b6b3a8;--panel:#292925}
+*{box-sizing:border-box}body{margin:0}main{padding:20px;max-width:840px;margin:auto}header{display:flex;justify-content:space-between;color:var(--muted);font-size:12px}.brand{font-weight:800;font-size:16px;color:inherit}h1{font-size:22px;line-height:1.2;margin:24px 0 16px;overflow-wrap:anywhere}video{width:100%;max-height:65vh;display:block;border-radius:12px;background:#000}button{font:inherit;color:inherit;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:10px 14px;cursor:pointer}button:hover{filter:brightness(.95)}button:disabled{opacity:.5;cursor:default}button:focus-visible{outline:2px solid #5d80cc;outline-offset:3px}.primary{background:#eac36a;color:#242018;border-color:#eac36a}nav{display:flex;flex-wrap:wrap;gap:8px;margin-top:16px}.projects{display:grid;gap:8px}.projects button{display:flex;justify-content:space-between;gap:16px;text-align:left}.projects button span:first-child{overflow-wrap:anywhere;min-width:0}.muted{color:var(--muted);font-size:12px}.error{color:#ba453b}progress{width:100%;accent-color:#d8a743}p{overflow-wrap:anywhere}
diff --git a/site/src/clients/chatgpt/ui/useProjectApp.ts b/site/src/clients/chatgpt/ui/useProjectApp.ts
new file mode 100644
index 00000000..05744a16
--- /dev/null
+++ b/site/src/clients/chatgpt/ui/useProjectApp.ts
@@ -0,0 +1,97 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { App } from "@modelcontextprotocol/ext-apps";
+import { playbackSchema, viewSchema, type Playback, type ProjectView } from "../contracts";
+
+type ToolResult = { isError?: boolean; structuredContent?: unknown; _meta?: Record<string, unknown>; content?: unknown[] };
+
+/** The host carries authentication; the iframe only calls the MCP Apps bridge. */
+export function useProjectApp() {
+ const appRef = useRef<App | null>(null);
+ const epoch = useRef(0);
+ const [ready, setReady] = useState(false);
+ const [view, setView] = useState<ProjectView | null>(null);
+ const [playback, setPlayback] = useState<Playback | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [visible, setVisible] = useState(!document.hidden);
+ const [pollMs, setPollMs] = useState(2000);
+ const recoveries = useRef(0);
+
+ const receive = useCallback((result: ToolResult) => {
+ if (result.isError) throw new Error("Donkey Cut could not complete this request. Try again.");
+ const parsed = viewSchema.safeParse(result.structuredContent);
+ if (!parsed.success) throw new Error("The preview response could not be read.");
+ const media = playbackSchema.safeParse(result._meta?.playback);
+ const interval = result._meta?.pollMs;
+ if (typeof interval === "number" && interval >= 1000 && interval <= 30000) setPollMs(interval);
+ setView(parsed.data);
+ setPlayback(media.success ? media.data : null);
+ setError(null);
+ }, []);
+
+ useEffect(() => {
+ const app = new App({ name: "Donkey Cut preview", version: "1.0.0" }, {}, { strict: true });
+ appRef.current = app;
+ let live = true;
+ app.ontoolresult = (result) => {
+ if (!live) return;
+ epoch.current++;
+ recoveries.current = 0;
+ setBusy(false);
+ try { receive(result); } catch (e) { setError((e as Error).message); }
+ };
+ app.onhostcontextchanged = ({ theme }) => { if (theme) document.documentElement.dataset.theme = theme; };
+ void app.connect().then(() => {
+ if (!live) return;
+ document.documentElement.dataset.theme = app.getHostContext()?.theme ?? "light";
+ setReady(true);
+ }).catch(() => { if (live) setError("Connect this preview from ChatGPT to continue."); });
+ const visibility = () => setVisible(!document.hidden);
+ document.addEventListener("visibilitychange", visibility);
+ return () => {
+ live = false;
+ appRef.current = null;
+ document.removeEventListener("visibilitychange", visibility);
+ void app.close().catch(() => {});
+ };
+ }, [receive]);
+
+ const run = useCallback(async (name: string, args: Record<string, string>, manual = true) => {
+ const app = appRef.current;
+ if (!app || !ready) return;
+ const current = ++epoch.current;
+ if (manual) { recoveries.current = 0; setBusy(true); setError(null); }
+ try {
+ const result = await app.callServerTool({ name, arguments: args });
+ if (current === epoch.current && appRef.current === app) receive(result);
+ } catch (e) {
+ if (current === epoch.current && appRef.current === app) setError(e instanceof Error ? e.message : "Request failed.");
+ } finally { if (current === epoch.current && appRef.current === app) setBusy(false); }
+ }, [ready, receive]);
+
+ const projectId = view?.project?.id;
+ const jobId = view?.preview?.id;
+ const status = view?.preview?.status;
+ useEffect(() => {
+ if (!ready || !visible || busy || error || !projectId || !jobId) return;
+ const waiting = status === "queued" || status === "running";
+ if (!waiting && !playback) return;
+ const delay = waiting ? pollMs : Math.max(1000, playback!.expiresAt - Date.now() - 60000);
+ const timeout = window.setTimeout(() => { void run("get_preview_status", { projectId, jobId }, false); }, delay);
+ return () => window.clearTimeout(timeout);
+ }, [ready, visible, busy, error, projectId, jobId, status, playback, pollMs, run, view]);
+
+ const playbackFailed = useCallback(() => {
+ if (!projectId || !jobId) return;
+ if (recoveries.current++ >= 1) { setError("Video could not load. Try opening the project again."); return; }
+ setPlayback(null);
+ void run("get_preview_status", { projectId, jobId }, false);
+ }, [projectId, jobId, run]);
+
+ const openDonkey = async () => {
+ if (!view?.project || !appRef.current) return;
+ try { const result = await appRef.current.openLink({ url: view.project.url }); if (result.isError) setError("Could not open Donkey Cut."); }
+ catch { setError("Could not open Donkey Cut."); }
+ };
+ return { ready, view, playback, error, busy, visible, run, playbackFailed, openDonkey };
+}
diff --git a/site/src/cut/components/PlatformPreview.tsx b/site/src/cut/components/PlatformPreview.tsx
index a7a53889..57913395 100644
--- a/site/src/cut/components/PlatformPreview.tsx
+++ b/site/src/cut/components/PlatformPreview.tsx
@@ -1,6 +1,6 @@
"use client";
-import { ArtifactVideo } from "./ArtifactVideo";
+import { ArtifactVideo } from "@donkeycut/artifact-player/ArtifactVideo";
import { useEffect, useRef, useState } from "react";
import { MEDIA_CORS } from "@/cut/lib/mediaCors";
diff --git a/site/src/cut/components/share/MobileShare.tsx b/site/src/cut/components/share/MobileShare.tsx
index 18be7d87..630b7de5 100644
--- a/site/src/cut/components/share/MobileShare.tsx
+++ b/site/src/cut/components/share/MobileShare.tsx
@@ -5,7 +5,7 @@ import { Clapperboard, FileText, Images, Loader2, MessageSquare, Captions } from
import { Button } from "@/components/ui/button";
import type { ProjectDoc, ShareFeatures, StoredAsset } from "@/cut/lib/types";
import { BottomSheet } from "./BottomSheet";
-import { ArtifactVideo } from "../ArtifactVideo";
+import { ArtifactVideo } from "@donkeycut/artifact-player/ArtifactVideo";
/**
* The share as a phone should see it: the cut playing as one video, with the
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index 09cea184..cf74065c 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -1896,6 +1896,10 @@ export async function renderShareLadder(
}
}
+export function previewSettings(aspect: Aspect): ExportSettings {
+ return { ...scaledFrame(aspect, 360), fps: 24, crf: 30, preset: "veryfast", ...DELIVERY_DEFAULTS };
+}
+
export type PreviewArtifact = { id: string; projectId: string; revision: string; url: string; expiresAt?: number };
export type PreviewJob = PreviewArtifact & { status: "queued" | "done"; statusUrl?: string };
@@ -1906,7 +1910,7 @@ export async function submitPreviewSnapshot(
): Promise<PreviewJob> {
const { operation: { projectId, backend }, doc, revision } = snapshot;
signal?.throwIfAborted();
- const settings: ExportSettings = { ...scaledFrame(doc.aspect, 360), fps: 24, crf: 30, preset: "veryfast", ...DELIVERY_DEFAULTS };
+ const settings = previewSettings(doc.aspect);
if (backend.kind === "browser") {
const directory = await projectDir(projectId);
if (!directory) throw new Error("Project not found in browser storage.");
diff --git a/site/src/cut/lib/headless/docExport.ts b/site/src/cut/lib/headless/docExport.ts
index f34d0dd6..7c36a8c7 100644
--- a/site/src/cut/lib/headless/docExport.ts
+++ b/site/src/cut/lib/headless/docExport.ts
@@ -5,6 +5,7 @@ import {
EXPORT_PRESETS,
originalSettings,
presetSettings,
+ previewSettings,
type ExportSettings,
} from "../exportClient";
import { renderDoc, type ExportDoc } from "@/cut/lib/renderSnapshot";
@@ -44,12 +45,13 @@ export async function buildDocExportSpec(
projectId: string,
preset: DocExportPreset,
tmpDir: string,
- snapshot: CloudDocSnapshot
+ snapshot: CloudDocSnapshot,
+ target: "export" | "preview" = "export"
): Promise<object> {
bindHeadlessSession(session);
await openCloudSnapshot(session, projectId, snapshot);
const doc = renderDoc(useEditor.getState());
- const payload = await buildExportPayload(projectId, doc, settingsFor(preset, doc), "export");
+ const payload = await buildExportPayload(projectId, doc, target === "preview" ? previewSettings(doc.aspect) : settingsFor(preset, doc), target);
await Promise.all(
payload.pngs.map(async (p) =>
writeFile(
diff --git a/site/src/cut/server/cloud/jobs.ts b/site/src/cut/server/cloud/jobs.ts
index 71149a1f..382f419d 100644
--- a/site/src/cut/server/cloud/jobs.ts
+++ b/site/src/cut/server/cloud/jobs.ts
@@ -5,6 +5,7 @@ import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
import { cutLimitsFor, EXPORT_QUOTA_MARGIN, renderJobCheck } from "./limits";
import { wakeRenderWorker } from "./wake";
+import { queuePreview } from "./previewJobs";
import { getProject } from "./projects";
import { MEDIA_REDIRECT_HEADERS, mediaObjectUrl, mediaUrlLifetime } from "./mediaCdn";
import { del, head, overlayKey, overlayPrefix, presignPut, projectExportKey } from "./r2";
@@ -309,25 +310,7 @@ export const jobsCloud = {
} as unknown as Prisma.InputJsonValue;
if (target === "preview") {
- const row = await prisma.$transaction(async (tx) => {
- if (body.revision) {
- const existing = await tx.cutRenderJob.findFirst({
- where: { userId, projectId, kind: target, state: { in: ["queued", "running", "done"] },
- spec: { path: ["revision"], equals: body.revision } },
- });
- if (existing && (existing.state !== "done" || (existing.outputKey && await tx.cutMediaObject.findUnique({
- where: { r2Key: existing.outputKey }, select: { id: true },
- })))) return existing;
- }
- await tx.cutRenderJob.updateMany({
- where: { userId, projectId, kind: target, state: "queued" },
- data: { state: "canceled", error: "A newer preview was requested." },
- });
- return tx.cutRenderJob.create({
- data: { userId, projectId, kind: target, spec: jobSpec, outName: "preview.mp4" },
- });
- }, { isolationLevel: "Serializable" });
- wakeRenderWorker();
+ const row = await queuePreview(userId, projectId, jobSpec, body.revision);
return Response.json({ id: row.id });
}
diff --git a/site/src/cut/server/cloud/previewJobs.test.ts b/site/src/cut/server/cloud/previewJobs.test.ts
new file mode 100644
index 00000000..5afbfd3a
--- /dev/null
+++ b/site/src/cut/server/cloud/previewJobs.test.ts
@@ -0,0 +1,61 @@
+import { expect, mock, test } from "bun:test";
+import { Prisma } from "@/generated/prisma/client";
+import type { prisma } from "@/lib/prisma";
+import { previewFromDoc, queuePreview } from "./previewJobs";
+
+function harness() {
+ const wake = mock(() => {});
+ const tx = {
+ cutRenderJob: {
+ findFirst: mock(async (args: unknown) => { void args; return null as unknown; }),
+ updateMany: mock(async (args: unknown) => { void args; return { count: 1 }; }),
+ create: mock(async ({ data }: { data: unknown }) => ({ id: "new", state: "queued", data })),
+ },
+ cutMediaObject: { findUnique: mock(async () => null as unknown) },
+ };
+ const db = {
+ settingOverride: { findUnique: async () => ({ value: { maxAttempts: 3 } }) },
+ cutProject: { findFirst: mock(async (args: unknown) => { void args; return null as unknown; }) },
+ $transaction: mock(async (run: (tx: unknown) => Promise<unknown>, options: unknown): Promise<unknown> => { void options; return run(tx); }),
+ };
+ return { tx, db, wake, deps: { db: db as unknown as typeof prisma, wake } };
+}
+
+test("available previews are reused without canceling or creating a job", async () => {
+ const h = harness();
+ h.tx.cutRenderJob.findFirst.mockResolvedValue({ id: "old", state: "done", outputKey: "key" });
+ h.tx.cutMediaObject.findUnique.mockResolvedValue({ id: "media" });
+ expect((await queuePreview("owner", "project", {}, "revision", h.deps)).id).toBe("old");
+ expect(h.tx.cutRenderJob.create).not.toHaveBeenCalled();
+ expect(h.tx.cutRenderJob.updateMany).not.toHaveBeenCalled();
+ expect(h.wake).not.toHaveBeenCalled();
+});
+
+test("collected previews queue a new render and replace only this project's waiting job", async () => {
+ const h = harness();
+ h.tx.cutRenderJob.findFirst.mockResolvedValue({ id: "old", state: "done", outputKey: "collected" });
+ expect((await queuePreview("owner", "project", { revision: "cloud:3" }, "cloud:3", h.deps)).id).toBe("new");
+ expect(h.tx.cutRenderJob.updateMany.mock.calls[0][0]).toMatchObject({ where: { userId: "owner", projectId: "project", kind: "preview", state: "queued" } });
+ expect(h.wake).toHaveBeenCalled();
+});
+
+test("serialization conflicts retry within the configured bound", async () => {
+ const h = harness(); let attempts = 0;
+ h.db.$transaction.mockImplementation(async (run) => {
+ if (++attempts < 3) throw new Prisma.PrismaClientKnownRequestError("conflict", { code: "P2034", clientVersion: "test" });
+ return run(h.tx);
+ });
+ await queuePreview("owner", "project", {}, "revision", h.deps);
+ expect(attempts).toBe(3);
+ expect(h.tx.cutRenderJob.create.mock.calls).toHaveLength(1);
+});
+
+test("remote preview captures the saved document and checks ownership", async () => {
+ const h = harness();
+ expect(await previewFromDoc("owner", "foreign", h.deps)).toBeNull();
+ expect(h.db.$transaction).not.toHaveBeenCalled();
+ h.db.cutProject.findFirst.mockResolvedValue({ doc: { clips: [{ id: "clip" }] }, version: 7 });
+ await previewFromDoc("owner", "project", h.deps);
+ expect(h.db.cutProject.findFirst.mock.calls[1][0]).toMatchObject({ where: { id: "project", userId: "owner" } });
+ expect(h.tx.cutRenderJob.create.mock.calls[0][0]).toMatchObject({ data: { kind: "preview", spec: { revision: "cloud:7", fromDoc: { snapshot: { doc: { clips: [{ id: "clip" }] }, version: "7" } } } } });
+});
diff --git a/site/src/cut/server/cloud/previewJobs.ts b/site/src/cut/server/cloud/previewJobs.ts
new file mode 100644
index 00000000..94aadb86
--- /dev/null
+++ b/site/src/cut/server/cloud/previewJobs.ts
@@ -0,0 +1,42 @@
+import { Prisma } from "@/generated/prisma/client";
+import { prisma } from "@/lib/prisma";
+import { resolveSettings } from "@/lib/config/resolve";
+import { wakeRenderWorker } from "./wake";
+
+const dependencies = { db: prisma, wake: wakeRenderWorker };
+
+/** All clients share revision reuse and the one-waiting-preview queue. */
+export async function queuePreview(userId: string, projectId: string, spec: Prisma.InputJsonValue, revision?: string, { db, wake } = dependencies) {
+ const override = await db.settingOverride.findUnique({ where: { key: "cutPreviewJobs" }, select: { value: true } });
+ const { maxAttempts } = resolveSettings(override ? { cutPreviewJobs: override.value } : {}, []).settings.cutPreviewJobs;
+ for (let attempt = 1; ; attempt++) {
+ try {
+ const row = await db.$transaction(async (tx) => {
+ if (revision) {
+ const existing = await tx.cutRenderJob.findFirst({
+ where: { userId, projectId, kind: "preview", state: { in: ["queued", "running", "done"] }, spec: { path: ["revision"], equals: revision } },
+ orderBy: { createdAt: "desc" },
+ });
+ if (existing && (existing.state !== "done" || (existing.outputKey && await tx.cutMediaObject.findUnique({
+ where: { r2Key: existing.outputKey }, select: { id: true },
+ })))) return existing;
+ }
+ await tx.cutRenderJob.updateMany({ where: { userId, projectId, kind: "preview", state: "queued" }, data: { state: "canceled", error: "A newer preview was requested." } });
+ return tx.cutRenderJob.create({ data: { userId, projectId, kind: "preview", spec, outName: "preview.mp4" } });
+ }, { isolationLevel: "Serializable" });
+ if (row.state !== "done") wake();
+ return row;
+ } catch (error) {
+ if (!(error instanceof Prisma.PrismaClientKnownRequestError) || error.code !== "P2034" || attempt >= maxAttempts) throw error;
+ }
+ }
+}
+
+/** A remote client renders the saved revision through the same headless renderer. */
+export async function previewFromDoc(userId: string, projectId: string, deps = dependencies) {
+ const { db } = deps;
+ const project = await db.cutProject.findFirst({ where: { id: projectId, userId }, select: { doc: true, version: true } });
+ if (!project) return null;
+ const revision = `cloud:${project.version}`;
+ return queuePreview(userId, projectId, { revision, fromDoc: { snapshot: { doc: project.doc, version: String(project.version) } } } as Prisma.InputJsonValue, revision, deps);
+}
diff --git a/site/src/cut/worker/cf/worker.ts b/site/src/cut/worker/cf/worker.ts
index 803c45f4..9a45af96 100644
--- a/site/src/cut/worker/cf/worker.ts
+++ b/site/src/cut/worker/cf/worker.ts
@@ -17,6 +17,7 @@ type WorkerEnv = MediaEnv & {
R2_ACCESS_KEY_ID: string;
R2_SECRET_ACCESS_KEY: string;
CUT_WAKE_SECRET: string;
+ CUT_RUNNER_SECRET?: string;
CUT_COPY_EXECUTE_URL: string;
CUT_COPY_EXECUTE_SECRET: string;
JOBS_EXECUTE_URL: string;
@@ -57,6 +58,8 @@ export class CutRenderWorker extends Container<WorkerEnv> {
R2_ACCOUNT_ID: env.R2_ACCOUNT_ID,
R2_ACCESS_KEY_ID: env.R2_ACCESS_KEY_ID,
R2_SECRET_ACCESS_KEY: env.R2_SECRET_ACCESS_KEY,
+ // Document-backed renders authenticate their media and font reads on the site.
+ ...(env.CUT_RUNNER_SECRET ? { CUT_RUNNER_SECRET: env.CUT_RUNNER_SECRET } : {}),
// The container records a finished HLS ladder in KV. It is not a Worker,
// so it has no binding and goes over the REST API like the site does.
CLOUDFLARE_KV_API_TOKEN: env.CLOUDFLARE_KV_API_TOKEN,
diff --git a/site/src/cut/worker/exportJob.ts b/site/src/cut/worker/exportJob.ts
index 7fe915c5..96cd7223 100644
--- a/site/src/cut/worker/exportJob.ts
+++ b/site/src/cut/worker/exportJob.ts
@@ -139,7 +139,8 @@ export async function runExportJob(
projectId,
isDocExportPreset(stored.fromDoc.preset) ? stored.fromDoc.preset : "original",
handle.tmpDir,
- stored.fromDoc.snapshot
+ stored.fromDoc.snapshot,
+ job.kind === "preview" ? "preview" : "export"
)) as ExportSpec,
}
: stored;
diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.ts
index 553878ef..6c74d0c3 100644
--- a/site/src/lib/config/registry.ts
+++ b/site/src/lib/config/registry.ts
@@ -31,6 +31,29 @@ function validTimeZone(zone: string): boolean {
}
export const SETTINGS = defineSettings({
+ chatgptApp: {
+ schema: z.object({
+ enabled: z.boolean(),
+ issuer: z.url().pipe(z.string().refine((v) => new URL(v).protocol === "https:" && new URL(v).origin === v)),
+ redirectUris: z.array(z.url().pipe(z.string().refine((v) => new URL(v).protocol === "https:" && !new URL(v).hash))).min(1),
+ accessSeconds: z.number().int().min(60).max(3600),
+ refreshDays: z.number().int().min(1).max(90),
+ requestsPerMinute: z.number().int().min(10).max(600),
+ oauthRequestsPerIpMinute: z.number().int().min(10).max(10000).default(600),
+ pollMs: z.number().int().min(1000).max(30000),
+ }).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 },
+ public: false,
+ title: "ChatGPT app",
+ description: "Account linking, allowed OAuth callbacks, token lifetimes, and preview polling. Enable after the OAuth tables are deployed.",
+ },
+ cutPreviewJobs: {
+ schema: z.object({ maxAttempts: z.number().int().min(1).max(10) }).strict(),
+ default: { maxAttempts: 5 },
+ public: false,
+ title: "Cloud preview queue",
+ description: "Maximum attempts when concurrent preview submissions conflict.",
+ },
cutStorageTransactions: {
schema: z.object({ maxAttempts: z.number().int().min(1).max(10) }).strict(),
default: { maxAttempts: 5 },
diff --git a/site/vercel.json b/site/vercel.json
index f3a7378f..0bd649d1 100644
--- a/site/vercel.json
+++ b/site/vercel.json
@@ -1,5 +1,6 @@
{
"crons": [
+ { "path": "/api/chatgpt/gc", "schedule": "15 4 * * *" },
{ "path": "/api/credits/expire", "schedule": "30 0 * * *" },
{ "path": "/api/credits/expiry-notices", "schedule": "0 16 * * *" },
{ "path": "/api/cut-cloud/gc", "schedule": "0 4 * * *" },