Open source CapCut alternative.
TypeScript
feat(site): gate the hosted Cut app behind a local-network connect screen
David Le22dd75b829a0
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.mdindex f171ea26..51f74485 100644--- a/docs/guides/cut/README.md+++ b/docs/guides/cut/README.md@@ -20,7 +20,7 @@ browser ── API calls ──▶ Cut engine on 127.0.0.1 (spawned by the Donke· the user's own claude/codex CLI logins```-The client probes the engine's health endpoint (dedicated port first, dev server second) and remembers the winner. The engine grants the hosted origins cross-origin access, and only those origins. Without a running engine the page shows a "get Donkey / open Donkey" state that connects by itself as soon as the engine appears. Engine updates ride the Donkey app's own auto-updater, so the client never prompts to update.+The client probes the engine's health endpoint (dedicated port first, dev server second) and remembers the winner. Browsers permission-gate a hosted page's calls to the local machine, so the first hosted visit holds on a connect screen and fires the browser's permission prompt from the user's own click; a denied permission gets its own recovery screen. The engine grants the hosted origins cross-origin access, and only those origins. Without a running engine the page shows a "get Donkey / open Donkey" state that connects by itself as soon as the engine appears. Engine updates ride the Donkey app's own auto-updater, so the client never prompts to update.## One API surface, one routerdiff --git a/site/src/app/cut/app/layout.tsx b/site/src/app/cut/app/layout.tsxindex 79370303..ebaf0402 100644--- a/site/src/app/cut/app/layout.tsx+++ b/site/src/app/cut/app/layout.tsx@@ -1,6 +1,7 @@import type { ReactNode } from "react";import { AppSurfaceBackground } from "@/app/app/_components/AppSurfaceBackground";+import { ConnectGate } from "@/cut/components/ConnectGate";import { RequireSession } from "@/cut/components/RequireSession";// The Cut app (projects home, library, editor) renders on the same white@@ -9,12 +10,16 @@ import { RequireSession } from "@/cut/components/RequireSession";// html white so the cream does not show through the overscroll area, and// font-system matches the /app system font stack. RequireSession gates the// whole subtree on a signed-in session, redirecting signed-out visitors to-// sign-in with their target URL as the callback.+// sign-in with their target URL as the callback. ConnectGate holds the first+// hosted visit on a connect screen so the browser's local-network permission+// prompt fires from the user's own click instead of ambushing them at login.export default function CutAppLayout({ children }: { children: ReactNode }) {return (<div className="min-h-screen bg-white font-system text-foreground antialiased"><AppSurfaceBackground />- <RequireSession>{children}</RequireSession>+ <RequireSession>+ <ConnectGate>{children}</ConnectGate>+ </RequireSession></div>);}diff --git a/site/src/cut/components/ConnectGate.tsx b/site/src/cut/components/ConnectGate.tsxnew file mode 100644index 00000000..cf77330f--- /dev/null+++ b/site/src/cut/components/ConnectGate.tsx@@ -0,0 +1,111 @@+"use client";++import { useCallback, useEffect, useState, type ReactNode } from "react";+import { Loader2, Plug, ShieldX } from "lucide-react";++import { Button } from "@/components/ui/button";+import { engineConnect, servedFromEngine } from "@/cut/lib/api";++// Chrome gates a public https page's first fetch to 127.0.0.1 behind its+// Local Network Access prompt — "donkeycut.com wants to access other apps and+// services on this device". Left to fire from the projects list's mount-time+// probe, it ambushes the user right after login, and a reflexive Block+// silently strands every engine call. This gate holds the Cut app subtree+// until the user starts the connection themselves: a connect screen says what+// the browser is about to ask, the Connect click runs the first probe (which+// waits out the prompt), and a denied permission gets its own recovery+// screen. The screen shows once per browser — once connected (or+// acknowledged), later visits pass straight through — and never when the page+// is served by the engine itself, where loopback is same-origin.++const ACK_KEY = "cut-engine-connect-acked";++type Gate = "checking" | "connect" | "connecting" | "blocked" | "pass";++/** The browser's local-network permission state, null where the permission+ * (or the query) doesn't exist — non-Chrome browsers, older Chrome. */+async function permissionState(): Promise<PermissionState | null> {+ try {+ const status = await navigator.permissions.query({+ name: "local-network-access" as PermissionName,+ });+ return status.state;+ } catch {+ return null;+ }+}++export function ConnectGate({ children }: { children: ReactNode }) {+ const [gate, setGate] = useState<Gate>("checking");++ const check = useCallback(async () => {+ const perm = await permissionState();+ if (servedFromEngine() || perm === "granted") return setGate("pass");+ if (perm === "denied") return setGate("blocked");+ if (localStorage.getItem(ACK_KEY) === "1") return setGate("pass");+ setGate("connect");+ }, []);++ useEffect(() => {+ void check();+ }, [check]);++ const connect = async () => {+ setGate("connecting");+ localStorage.setItem(ACK_KEY, "1");+ await engineConnect();+ // Any answer resolves the probe; only an explicit Block needs its own+ // screen. Everything else falls through to the app, which shows its own+ // get-Donkey state when no engine answered.+ setGate((await permissionState()) === "denied" ? "blocked" : "pass");+ };++ if (gate === "pass") return <>{children}</>;++ if (gate === "checking")+ return (+ <div className="grid min-h-screen place-items-center text-muted-foreground">+ <Loader2 className="size-5 animate-spin" />+ </div>+ );++ if (gate === "blocked")+ return (+ <div className="grid min-h-screen place-items-center">+ <div className="flex max-w-sm flex-col items-center gap-4 text-center">+ <div className="grid size-14 place-items-center rounded-2xl bg-muted">+ <ShieldX className="size-7 text-muted-foreground" />+ </div>+ <h1 className="text-lg font-semibold tracking-tight">Connection blocked</h1>+ <p className="text-sm text-muted-foreground">+ Your browser is blocking this page from reaching the Donkey app on+ this Mac. Open the site settings from the icon next to the address+ bar, allow access to apps and services on this device, then try+ again.+ </p>+ <Button onClick={() => void check()}>Try again</Button>+ </div>+ </div>+ );++ const connecting = gate === "connecting";+ return (+ <div className="grid min-h-screen place-items-center">+ <div className="flex max-w-sm flex-col items-center gap-4 text-center">+ <div className="grid size-14 place-items-center rounded-2xl bg-muted">+ <Plug className="size-7 text-muted-foreground" />+ </div>+ <h1 className="text-lg font-semibold tracking-tight">Connect to the Donkey app</h1>+ <p className="text-sm text-muted-foreground">+ Donkey Cut runs locally — your projects live in the Donkey app on+ this Mac. Your browser will ask for permission to connect to apps on+ this device; choose <span className="font-medium text-foreground">Allow</span>.+ </p>+ <Button onClick={() => void connect()} disabled={connecting}>+ {connecting && <Loader2 className="animate-spin" data-icon="inline-start" />}+ {connecting ? "Choose Allow when your browser asks" : "Connect"}+ </Button>+ </div>+ </div>+ );+}diff --git a/site/src/cut/lib/api.ts b/site/src/cut/lib/api.tsindex 4726095a..20f0af0f 100644--- a/site/src/cut/lib/api.ts+++ b/site/src/cut/lib/api.ts@@ -13,10 +13,19 @@ import { DEFAULT_ENGINE_PORT } from "./ports";const ENGINE_PORTS = [DEFAULT_ENGINE_PORT, 3000];const PROBE_TIMEOUT_MS = 1200;+// A first-ever loopback fetch from the hosted page hangs on the browser's+// local-network permission prompt until the user answers it; the connect+// probe waits that decision out instead of racing the health timeout.+const CONNECT_TIMEOUT_MS = 30_000;const isLocalHost = (hostname: string) =>hostname === "localhost" || hostname === "127.0.0.1" || hostname.endsWith(".localhost");+/** Whether the page is served by the engine itself (same origin, so loopback+ * API calls need no browser permission). */+export const servedFromEngine = () =>+ typeof window !== "undefined" && isLocalHost(window.location.hostname);+let resolvedOrigin: string | null = null; // "" = same originlet resolving: Promise<string> | null = null;@@ -26,10 +35,10 @@ function candidates(): string[] {return [...(saved ? [saved] : []), ...ENGINE_PORTS.map((p) => `http://127.0.0.1:${p}`)];}-async function probe(origin: string): Promise<boolean> {+async function probe(origin: string, timeoutMs = PROBE_TIMEOUT_MS): Promise<boolean> {try {const res = await fetch(`${origin}/api/cut/engine/health`, {- signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),+ signal: AbortSignal.timeout(timeoutMs),});return res.ok;} catch {@@ -37,6 +46,25 @@ async function probe(origin: string): Promise<boolean> {}}+/** The hosted page's first connection to this Mac, run from the connect+ * screen's button so the browser's permission prompt lands in context. Probes+ * like engineReady but gives the user time to answer the prompt. Resolves+ * false when no engine answered; the app then shows its get-Donkey state. */+export async function engineConnect(): Promise<boolean> {+ if (resolvedOrigin !== null) return true;+ if (servedFromEngine()) {+ resolvedOrigin = "";+ return true;+ }+ for (const c of candidates()) {+ if (await probe(c, CONNECT_TIMEOUT_MS)) {+ resolvedOrigin = c;+ return true;+ }+ }+ return false;+}+/** Resolve (and memoize) the engine origin; throws when no engine answers so* callers surface the "start Donkey Cut on this Mac" state. A failed attempt* is not memoized — the next call probes again. */