diff --git a/apps/contract/package.json b/apps/contract/package.json index 7bf09ddc..15a99d6e 100644 --- a/apps/contract/package.json +++ b/apps/contract/package.json @@ -11,6 +11,7 @@ "typecheck": "tsc --noEmit" }, "dependencies": { + "@codeworksh/schema": "workspace:*", "@codeworksh/widget": "workspace:*", "effect": "4.0.5" }, diff --git a/apps/contract/src/contract.ts b/apps/contract/src/contract.ts index 6779f00c..b3d3fcae 100644 --- a/apps/contract/src/contract.ts +++ b/apps/contract/src/contract.ts @@ -1,3 +1,4 @@ +import { Machine } from "@codeworksh/schema"; import { Schema } from "effect"; import { Rpc, RpcGroup } from "effect/rpc"; import { @@ -817,6 +818,30 @@ export const Api = RpcGroup.make( success: ModelList, error: Schema.Union([CodeworkUnavailable, ModelsError]), }), + /** The default machine and the workspaces it is connected to. */ + Rpc.make("machine.info", { + success: Machine.Status, + error: CodeworkUnavailable, + }), + /** Names the default machine for people; an empty name goes back to the OS's. */ + Rpc.make("machine.rename", { + payload: { givenName: Schema.String }, + success: Machine.Status, + error: CodeworkUnavailable, + }), + /** Disconnects the default machine from a workspace. */ + Rpc.make("machine.disconnect", { + payload: Machine.Disconnect, + success: Machine.Disconnected, + error: Schema.Union([CodeworkUnavailable, Machine.ConnectError]), + }), + /** Connects the default machine to a workspace: the code to approve, then the link. */ + Rpc.make("machine.connect", { + payload: { workspaceId: Schema.String }, + success: Machine.ConnectEvent, + error: Schema.Union([CodeworkUnavailable, Machine.ConnectError]), + stream: true, + }), /** The OS home directory, and the folder `host.create` makes projects in. */ Rpc.make("host.info", { success: Schema.Struct({ home: Schema.String, projects: Schema.String }), @@ -993,6 +1018,12 @@ export const Api = RpcGroup.make( success: Schema.Void, error: ServersError, }), + /** Installs codework with the install script, into its default folder, then starts the local server `id`. */ + Rpc.make("servers.install", { + payload: { id: Schema.String }, + success: Schema.Void, + error: ServersError, + }), /** Runs `codework service ` with a local server's executable, home, arguments and variables. */ Rpc.make("servers.service", { payload: { id: Schema.String, action: CliAction }, diff --git a/apps/desktop/package.json b/apps/desktop/package.json index a2bf4a98..0009059b 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -13,10 +13,12 @@ "package": "node scripts/package.mjs" }, "devDependencies": { + "@clerk/electron": "0.1.10", "@types/node": "catalog:", "bumpp": "^12.3.0", "electron": "44.4.2", "electron-builder": "^26.15.3", + "electron-store": "8.2.0", "typescript": "catalog:", "vite-plus": "catalog:" } diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index b0a7699d..7297d857 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -1,3 +1,5 @@ +import { createClerkBridge } from "@clerk/electron"; +import { storage } from "@clerk/electron/storage"; import { app, BrowserWindow, dialog, ipcMain, net, protocol, shell } from "electron"; import { readFile, stat } from "node:fs/promises"; import path from "node:path"; @@ -14,7 +16,7 @@ app.setPath( path.join(app.getPath("appData"), channel() === "latest" ? "codework" : `codework${channel()}`), ); -const SCHEME = app.isPackaged ? "codework" : "codework-dev"; +const SCHEME = app.isPackaged ? "codework" : "codeworkdev"; const HOST = "app"; const APP_URL = `${SCHEME}://${HOST}/`; @@ -50,10 +52,16 @@ const MIME_TYPES: Record = { ".txt": "text/plain", }; -// Must run synchronously before Electron emits `ready`. -protocol.registerSchemesAsPrivileged([ - { +// Must run synchronously before Electron emits `ready`. Clerk's bridge registers the renderer's scheme +// as privileged (one registration per process), keeps the signed-in session encrypted under userData, +// and carries OAuth back to the renderer on the same origin. +createClerkBridge({ + storage: storage({ path: path.join(app.getPath("userData"), "clerk") }), + // The app takes the lock itself, below, before any window opens. + manageSingleInstanceLock: false, + renderer: { scheme: SCHEME, + host: HOST, privileges: { standard: true, secure: true, @@ -63,7 +71,7 @@ protocol.registerSchemesAsPrivileged([ codeCache: true, }, }, -]); +}); async function serveAsset(request: Request): Promise { const url = new URL(request.url); @@ -105,7 +113,7 @@ function handleRequest(request: Request): Promise { if (DEV_SERVER_URL) { const url = new URL(request.url); if (url.host !== HOST) return Promise.resolve(new Response(null, { status: 404 })); - // Module scripts carry `Origin: codework-dev://app`; forwarding it makes + // Module scripts carry `Origin: codeworkdev://app`; forwarding it makes // net.fetch a CORS request the dev server never allows, failing every script. const headers = new Headers(request.headers); headers.delete("origin"); diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index ce8ec81f..0ff695dc 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -1,3 +1,4 @@ +import { exposeClerkBridge } from "@clerk/electron/preload"; import { contextBridge, ipcRenderer } from "electron"; import { HOME_CHANNEL, PICK_FOLDER_CHANNEL, REVEAL_CHANNEL, SERVER_CHANNEL } from "./ipc.ts"; @@ -12,3 +13,6 @@ contextBridge.exposeInMainWorld("desktopBridge", { reveal: (path: string) => ipcRenderer.invoke(REVEAL_CHANNEL, path) as Promise, }), }); + +// The narrow bridge @clerk/electron/react uses for token storage and OAuth. +exposeClerkBridge(); diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index daf97969..4338f386 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -2,7 +2,10 @@ import { defineConfig } from "vite-plus"; // The main process is bundled to CJS; only `electron` (and Node built-ins) // stay external — everything else is inlined into the artifact. -const isExternal = (id: string) => id === "electron" || id.startsWith("electron/") || id.startsWith("node:"); +// `@clerk/electron-passkeys` is an optional native module Clerk imports only when passkeys are on, +// which they are not. +const isExternal = (id: string) => + id === "electron" || id.startsWith("electron/") || id.startsWith("node:") || id === "@clerk/electron-passkeys"; // One config per entry: a sandboxed preload cannot require sibling files, so // modules shared with main must be inlined rather than split into a chunk. diff --git a/apps/server/src/cli.ts b/apps/server/src/cli.ts index f6b72522..c96fc7a4 100644 --- a/apps/server/src/cli.ts +++ b/apps/server/src/cli.ts @@ -35,11 +35,12 @@ const run = ( return { output: output.trim(), code: Number(code) }; }).pipe(Effect.scoped, Effect.timeout(timeout)); -// A Node crash prints the source line first; the error line says what went wrong. +// A Node crash prints the source line first; the error line says what went wrong, shown without its +// "Error:" label. The exit code only stands in when there is no output to show. const reason = (output: string, code: number) => { const lines = output.split("\n").map((line) => line.trim()); const line = lines.findLast((candidate) => /error/i.test(candidate)) ?? lines.findLast(Boolean); - return line === undefined ? `exited with code ${code}` : `exited with code ${code}: ${line.slice(0, 240)}`; + return line === undefined ? `exited with code ${code}` : line.replace(/^error:\s*/i, "").slice(0, 240); }; // An app opened from the Dock does not inherit the terminal's PATH, so the login shell is asked. @@ -201,9 +202,49 @@ export const service = Effect.fn("Cli.service")(function* (row: Servers.LocalRow const { output, code } = yield* run(file, [...prefix, "service", action, ...args], "30 seconds", { ...env, CODEWORK_HOME_DIR: servers.homeOf(row).path, - }).pipe(Effect.mapError((error) => new ServersError({ message: `codework service ${action}: ${error.message}` }))); - if (code !== 0) return yield* new ServersError({ message: `codework service ${action} ${reason(output, code)}` }); + }).pipe( + Effect.mapError((error) => new ServersError({ message: `Couldn't ${action} the server: ${error.message}` })), + ); + if (code !== 0) + return yield* new ServersError({ message: `Couldn't ${action} the server: ${reason(output, code)}` }); if (row.isDefault && action !== "stop") yield* awaitConnection; }); +// The script `curl -fsSL https://codework.sh/install | sh` runs; overridable so a test serves its own. +const installScript = Config.String("CODEWORK_INSTALL_SCRIPT").pipe( + Config.withDefault("https://codework.sh/install"), + Effect.orDie, +); + +/** + * Installs codework the way the install command does, into the install script's folder, then starts + * `row`. The shell's startup file is left alone: the app finds the binary in that folder by itself. + * A development or canary build of the app installs the newest development build. + */ +export const install = Effect.fn("Cli.install")(function* (row: Servers.LocalRow) { + const url = yield* installScript; + const channel = yield* Config.String("CODEWORK_CHANNEL").pipe(Config.withDefault("latest"), Effect.orDie); + const script = yield* Effect.tryPromise({ + try: () => + fetch(url).then((response) => { + if (!response.ok) throw new Error(`the download answered ${response.status}`); + return response.text(); + }), + // fetch rejects with a TypeError when the network is down or the host unknown. + catch: (error) => + new ServersError({ + message: + error instanceof TypeError + ? "Couldn't download the installer. Check your connection, then try again." + : `Couldn't download the installer: ${error instanceof Error ? error.message : String(error)}`, + }), + }); + const flags = ["--no-modify-path", ...(channel === "dev" || channel === "canary" ? ["--dev"] : [])]; + const { output, code } = yield* run("sh", ["-c", script, "install", ...flags], "300 seconds", { + CODEWORK_INSTALL_DIR: yield* installDir, + }).pipe(Effect.mapError((error) => new ServersError({ message: `Couldn't install codework: ${error.message}` }))); + if (code !== 0) return yield* new ServersError({ message: `Couldn't install codework: ${reason(output, code)}` }); + yield* service(row, "start"); +}); + export * as Cli from "./cli.ts"; diff --git a/apps/server/src/handlers.ts b/apps/server/src/handlers.ts index 44f63c22..0eabe66e 100644 --- a/apps/server/src/handlers.ts +++ b/apps/server/src/handlers.ts @@ -110,6 +110,33 @@ export const layer = Contract.Api.toLayer( "metrics.usage": (input) => Metrics.usage(input).pipe(Effect.provideService(SqlClient.SqlClient, sql)), "metrics.hours": (input) => Metrics.hours(input).pipe(Effect.provideService(SqlClient.SqlClient, sql)), + "machine.info": Effect.fn("machine.info")(function* () { + return yield* call((client) => client("machine.info", {})); + }), + "machine.rename": Effect.fn("machine.rename")(function* ({ givenName }) { + return yield* call((client) => client("machine.rename", { givenName })); + }), + // The CLI's own failure (not connected to that workspace) keeps its message. + "machine.disconnect": Effect.fn("machine.disconnect")(function* (input) { + const reply = yield* call((client) => + client("machine.disconnect", input).pipe( + Effect.map((disconnected) => ({ disconnected })), + Effect.catchTag("Machine.ConnectError", (failed) => Effect.succeed({ failed })), + ), + ); + return yield* "failed" in reply ? Effect.fail(reply.failed) : Effect.succeed(reply.disconnected); + }), + // The CLI's own connect failure (the relay unreachable, the code expired) keeps its message; only + // a dropped server reads as unavailable. + "machine.connect": ({ workspaceId }) => + Codework.stream((client) => + client("machine.connect", { workspaceId }).pipe( + Stream.map((event) => ({ event })), + Stream.catchTag("Machine.ConnectError", (failed) => Stream.succeed({ failed })), + ), + ).pipe( + Stream.flatMap((item) => ("failed" in item ? Stream.fail(item.failed) : Stream.succeed(item.event))), + ), "host.info": Effect.fn("host.info")(function* () { return yield* call((client) => client("host.info", {})); }), @@ -206,6 +233,9 @@ export const layer = Contract.Api.toLayer( yield* changingDefault(servers.setDefault(id)); yield* health.check; }), + "servers.install": Effect.fn("servers.install")(function* ({ id }: { readonly id: string }) { + yield* Cli.install(yield* servers.getLocal(id)).pipe(Effect.ensuring(health.check)); + }), "servers.service": Effect.fn("servers.service")(function* ({ id, action, diff --git a/apps/server/src/sync.ts b/apps/server/src/sync.ts index b3baf333..5dab5008 100644 --- a/apps/server/src/sync.ts +++ b/apps/server/src/sync.ts @@ -495,7 +495,11 @@ export const layer = Layer.effect( ); const client = Context.get(context, Client); clients.set(row.id, client); - yield* Effect.addFinalizer(() => Effect.sync(() => clients.delete(row.id))); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + if (clients.get(row.id) === client) clients.delete(row.id); + }), + ); yield* Effect.forkScoped(followUsage(row.id, client)); yield* connected(row.id, client).pipe( Effect.catchCause((cause) => diff --git a/apps/web/package.json b/apps/web/package.json index 1215d50e..1dfdc0dc 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -13,10 +13,13 @@ "typecheck": "tsc --noEmit" }, "dependencies": { + "@clerk/electron": "0.1.10", "@codeworksh/contract": "workspace:*", + "@codeworksh/schema": "workspace:*", "@codeworksh/widget": "workspace:*", "@effect/atom-react": "4.0.5", "@fontsource-variable/inter": "^5.3.0", + "@fontsource-variable/lilex": "5.3.0", "@legendapp/list": "3.3.5", "@phosphor-icons/react": "2.1.10", "@pierre/diffs": "1.6.2", diff --git a/apps/web/src/auth.tsx b/apps/web/src/auth.tsx new file mode 100644 index 00000000..79035c7b --- /dev/null +++ b/apps/web/src/auth.tsx @@ -0,0 +1,94 @@ +import { ClerkProvider, SignIn, SignUp, useAuth, useClerk } from "@clerk/electron/react"; +import { type ReactNode, useEffect, useState } from "react"; + +import { isElectron } from "./env"; +import { setSession } from "./kernel/relay"; +import { reveal } from "./splash"; + +const key: unknown = import.meta.env.CLERK_PUBLISHABLE_KEY; +const publishableKey = typeof key === "string" && key !== "" ? key : undefined; + +/** Whether this app signs people in: the desktop app, built with a publishable key. */ +export const isSignedInApp = isElectron && publishableKey !== undefined; + +// Signing in and up live on these paths of the app's own origin. Clerk's default, its hosted Account +// Portal, cannot return to an Electron window. The app's router reads only the hash, so these paths +// never reach it; finishing returns to the root. +const SIGN_IN = "/sign-in"; +const SIGN_UP = "/sign-up"; +const HOME = "/#/"; + +/** + * The desktop app requires a signed-in account. A browser build of the web app, or a build without a + * publishable key, runs without one. + */ +export function Auth({ children }: { readonly children: ReactNode }) { + // Clerk moves between sign-in, sign-up and their steps through these, so the gate re-renders. + // The app opens at its root; Clerk's forms render only on their own paths, so it starts on sign-in. + // The hash, which is the app's route, is kept. + const [path, setPath] = useState(() => { + const { pathname, hash } = window.location; + if (isSignedInApp && !pathname.startsWith(SIGN_IN) && !pathname.startsWith(SIGN_UP)) { + window.history.replaceState(null, "", `${SIGN_IN}${hash}`); + } + return window.location.pathname; + }); + if (!isSignedInApp || publishableKey === undefined) return children; + const navigate = (replace: boolean) => (to: string) => { + window.history[replace ? "replaceState" : "pushState"](null, "", to); + setPath(window.location.pathname); + }; + return ( + + {children} + + ); +} + +function Gate({ signingUp, children }: { readonly signingUp: boolean; readonly children: ReactNode }) { + const clerk = useClerk(); + const { isLoaded, isSignedIn, getToken, userId } = useAuth(); + // Before the app renders, so the relay client's first call already carries the session. + setSession(getToken, userId); + // Clerk unreachable (offline): local work keeps running; only cloud features wait for it. + if (clerk.status === "error") return children; + // Clerk is briefly not loaded while it signs out too, after the splash is gone: the screen's backdrop + // holds the window instead of an empty page. + if (!isLoaded) return ; + return isSignedIn ? children : ; +} + +function Screen({ children }: { readonly children?: ReactNode }) { + return ( +
+
+
{children}
+
+ ); +} + +function SignInScreen({ signingUp }: { readonly signingUp: boolean }) { + useEffect(reveal, []); + return ( + + {signingUp ? ( + + ) : ( + + )} + + ); +} diff --git a/apps/web/src/components/collapse.tsx b/apps/web/src/components/collapse.tsx new file mode 100644 index 00000000..5359f326 --- /dev/null +++ b/apps/web/src/components/collapse.tsx @@ -0,0 +1,39 @@ +import { type ReactNode, useState } from "react"; + +/** + * Opens and closes its content by height and opacity together, so the card grows and shrinks instead of + * jumping. Closed content stays mounted, inert, so it can animate out. The content is clipped only while + * it moves: open, focus rings and shadows show whole. `onOpened` runs once it has finished opening, the + * moment to focus a field inside without the motion fighting the browser's scroll-into-view. + */ +export function Collapse({ + open, + onOpened, + children, +}: { + readonly open: boolean; + readonly onOpened?: (() => void) | undefined; + readonly children: ReactNode; +}) { + const [settled, setSettled] = useState(open); + // Each open or close starts clipped again until its motion ends. + const [lastOpen, setLastOpen] = useState(open); + if (open !== lastOpen) { + setLastOpen(open); + setSettled(false); + } + return ( +
{ + if (!open || event.target !== event.currentTarget || event.propertyName !== "grid-template-rows") return; + setSettled(true); + onOpened?.(); + }} + // Reduced motion keeps a 1ms transition, so its end still arrives. + className={`grid transition-[grid-template-rows,opacity] duration-250 ease-(--ease-out) motion-reduce:duration-1 ${open ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0"}`} + > +
{children}
+
+ ); +} diff --git a/apps/web/src/components/copyable.tsx b/apps/web/src/components/copyable.tsx new file mode 100644 index 00000000..1138439e --- /dev/null +++ b/apps/web/src/components/copyable.tsx @@ -0,0 +1,28 @@ +import { CheckIcon, CopyIcon } from "@phosphor-icons/react"; +import { useState } from "react"; + +import { Button } from "@/components/ui/button"; + +/** A shell command to run by hand, with a copy button that confirms. */ +export function CopyCommand({ command }: { command: string }) { + const [copied, setCopied] = useState(false); + return ( + + {command} + + + ); +} diff --git a/apps/web/src/components/ui/button.tsx b/apps/web/src/components/ui/button.tsx index 9d21b147..648ec8bc 100644 --- a/apps/web/src/components/ui/button.tsx +++ b/apps/web/src/components/ui/button.tsx @@ -4,13 +4,13 @@ import { cn } from "@/lib/utils"; import { Slot } from "radix-ui"; const buttonVariants = cva( - "inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", + "inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-ui font-medium whitespace-nowrap transition-[background-color,color,box-shadow,transform] duration-150 ease-out outline-none active:scale-[0.97] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", { variants: { variant: { default: "bg-primary text-primary-foreground hover:bg-primary/90", destructive: - "bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40", + "bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40", outline: "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50", secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80", @@ -18,14 +18,15 @@ const buttonVariants = cva( link: "text-primary underline-offset-4 hover:underline", }, size: { - default: "h-9 px-4 py-2 has-[>svg]:px-3", + // 32px pills for actions, 28px rounded rectangles for compact controls, 44px pills that stand alone. + default: "h-8 rounded-full px-3.5 has-[>svg]:px-3", xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3", - sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5", - lg: "h-10 rounded-md px-6 has-[>svg]:px-4", - icon: "size-9", + sm: "h-7 gap-1.5 rounded-lg px-2.5 has-[>svg]:px-2", + lg: "h-11 rounded-full px-5 has-[>svg]:px-4", + icon: "size-8 rounded-lg", "icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3", - "icon-sm": "size-8", - "icon-lg": "size-10", + "icon-sm": "size-7 rounded-lg", + "icon-lg": "size-10 rounded-lg", }, }, defaultVariants: { diff --git a/apps/web/src/components/ui/dropdown-menu.tsx b/apps/web/src/components/ui/dropdown-menu.tsx index 213de025..f1fa5906 100644 --- a/apps/web/src/components/ui/dropdown-menu.tsx +++ b/apps/web/src/components/ui/dropdown-menu.tsx @@ -45,6 +45,8 @@ function DropdownMenuGroup({ ...props }: React.ComponentProps; } +// A row lights up at once under the pointer and lets go over 150ms, so sweeping down a menu leaves a +// short trail instead of a flicker, and never lags behind the pointer. function DropdownMenuItem({ className, inset, @@ -60,7 +62,7 @@ function DropdownMenuItem({ data-inset={inset} data-variant={variant} className={cn( - "relative flex min-h-7 cursor-default items-center gap-2 rounded-[8px] px-2 py-1 outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!", + "relative flex min-h-8 cursor-default items-center gap-2 rounded-[8px] px-2.5 py-1 outline-hidden transition-colors duration-150 ease-out select-none focus:bg-accent focus:duration-0 focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!", className, )} {...props} @@ -174,13 +176,13 @@ function DropdownMenuSubTrigger({ data-slot="dropdown-menu-sub-trigger" data-inset={inset} className={cn( - "flex min-h-7 cursor-default items-center gap-2 rounded-[8px] px-2 py-1 outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground", + "flex min-h-8 cursor-default items-center gap-2 rounded-[8px] px-2.5 py-1 outline-hidden transition-colors duration-150 ease-out select-none focus:bg-accent focus:duration-0 data-[state=open]:duration-0 focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground", className, )} {...props} > {children} - + ); } diff --git a/apps/web/src/components/ui/input.tsx b/apps/web/src/components/ui/input.tsx index 70131293..e22bcac6 100644 --- a/apps/web/src/components/ui/input.tsx +++ b/apps/web/src/components/ui/input.tsx @@ -1,13 +1,34 @@ import * as React from "react"; +import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; -function Input({ className, type, ...props }: React.ComponentProps<"input">) { +// A compact field for settings and dialogs; `lg` stands alone as a page's main field. +const inputVariants = cva( + "w-full min-w-0 border border-input bg-transparent py-1 text-ui shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-5 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30", + { + variants: { + size: { + default: "h-7 rounded-lg px-2.5", + lg: "h-11 rounded-xl px-3", + }, + }, + defaultVariants: { size: "default" }, + }, +); + +function Input({ + className, + type, + size, + ...props +}: Omit, "size"> & VariantProps) { return ( +
+ + {end} +
+ {children} +
+ ); +} diff --git a/apps/web/src/join.tsx b/apps/web/src/join.tsx new file mode 100644 index 00000000..7b55d9dc --- /dev/null +++ b/apps/web/src/join.tsx @@ -0,0 +1,126 @@ +import { useClerk } from "@clerk/electron/react"; +import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { CaretDownIcon, SignOutIcon } from "@phosphor-icons/react"; +import { useNavigate } from "@tanstack/react-router"; +import { AsyncResult } from "effect/reactivity"; +import { useState } from "react"; + +import { Button } from "@/components/ui/button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { Input } from "@/components/ui/input"; +import { isSignedInApp } from "./auth"; +import { Frame } from "./frame"; +import { createWorkspaceAtom, meAtom, relayFailure } from "./kernel/relay"; + +/** Creates a workspace: a name, then Create Workspace. Full window, outside the app's sidebar. */ +export function Join() { + const navigate = useNavigate(); + const create = useAtomSet(createWorkspaceAtom, { mode: "promise" }); + const [name, setName] = useState(""); + const [pending, setPending] = useState(false); + const [error, setError] = useState(null); + const trimmed = name.trim(); + return ( + }> + {/* Extra room below lifts the form a little above center, where it reads as centered. */} +
+
{ + event.preventDefault(); + if (pending) return; + // Checked on submit, not while typing; the error clears on the next keystroke. + if (trimmed === "") { + setError("Enter a name."); + return; + } + setPending(true); + setError(null); + create(trimmed) + .then((workspace) => + navigate({ + to: "/workspaces/$workspaceId/settings/machines/setup", + params: { workspaceId: workspace.id }, + // The form is done; Back from setup shouldn't land on it again. + replace: true, + }), + ) + .catch((cause: unknown) => { + setError(relayFailure(cause)); + setPending(false); + }); + }} + > +
+

Create a Workspace

+

Start a Workspace for your Team & Projects

+
+
+
+ + { + setName(event.target.value); + setError(null); + }} + maxLength={64} + autoComplete="off" + spellCheck={false} + data-1p-ignore + data-lpignore="true" + aria-invalid={error !== null} + aria-describedby={error === null ? undefined : "workspace-error"} + // oxlint-disable-next-line jsx-a11y/no-autofocus -- the page's only field + autoFocus + // Read-only, not disabled, so the field keeps focus while it saves and after a failure. + readOnly={pending} + /> + {error !== null && ( + + )} +
+ +
+
+
+ + ); +} + +/** The signed-in email, with Sign Out. */ +function Account() { + const me = useAtomValue(meAtom); + const clerk = useClerk(); + if (!AsyncResult.isSuccess(me)) return null; + const { email } = me.value.account; + return ( + + + {email} + + + + {email} + void clerk.signOut()}> + + Sign Out + + + + ); +} diff --git a/apps/web/src/kernel/relay.ts b/apps/web/src/kernel/relay.ts new file mode 100644 index 00000000..bd12b3ef --- /dev/null +++ b/apps/web/src/kernel/relay.ts @@ -0,0 +1,265 @@ +import { Relay } from "@codeworksh/schema"; +import { Cause, Context, Effect, Layer, Schema } from "effect"; +import { FetchHttpClient, HttpClient, HttpClientError, HttpClientRequest } from "effect/http"; +import { HttpApiClient } from "effect/http-api"; +import { AsyncResult, Atom } from "effect/reactivity"; + +import { messageOf } from "@/lib/utils"; + +const configured: unknown = import.meta.env.CODEWORK_RELAY_URL; +/** The relay the app talks to; `CODEWORK_RELAY_URL` in the repo's .env.local points a dev build elsewhere. */ +const relayUrl = typeof configured === "string" && configured !== "" ? configured : "https://relay.codework.sh"; + +// The signed-in person's session token, read fresh for each call (Clerk's tokens live a minute). The auth +// gate sets it once Clerk has loaded; until then calls go without one and the relay refuses them. +type TokenSource = (options?: { readonly skipCache?: boolean }) => Promise; +let sessionToken: TokenSource = () => Promise.resolve(null); +/** Where the signed-in person's account is remembered on this device, so it shows while out of reach. */ +let accountKey: string | undefined; +export const setSession = (source: TokenSource, userId: string | null | undefined) => { + sessionToken = source; + accountKey = userId == null ? undefined : `codework.account.${userId}`; +}; + +const remembered = (): Relay.Me | undefined => { + try { + const saved = accountKey === undefined ? null : localStorage.getItem(accountKey); + return saved === null ? undefined : Schema.decodeUnknownSync(Relay.Me)(JSON.parse(saved)); + } catch { + // Unreadable or from an older shape: nothing remembered. + return undefined; + } +}; +const remember = (me: Relay.Me) => { + try { + if (accountKey !== undefined) localStorage.setItem(accountKey, JSON.stringify(Schema.encodeSync(Relay.Me)(me))); + } catch { + // Unsaved, the account still shows until the app quits. + } +}; + +/** + * Whether the relay answers, as the latest call to it found: `unreachable` (no answer at all) or + * `unavailable` (it answered that its sign-in vendor is out of reach). + */ +export type Reach = "ok" | "unreachable" | "unavailable" | "signedOut"; +let reach: Reach = "ok"; +const reachListeners = new Set<(next: Reach) => void>(); +const report = (next: Reach) => { + if (next === reach) return; + reach = next; + for (const listener of reachListeners) listener(next); +}; +export const reachAtom = Atom.make((get) => { + const listener = (next: Reach) => get.setSelf(next); + reachListeners.add(listener); + get.addFinalizer(() => reachListeners.delete(listener)); + return reach; +}).pipe(Atom.keepAlive); + +/** No session token yet: Clerk is still loading or unreachable. Worth asking again. */ +class SessionPending extends Schema.TaggedError()("Relay.SessionPending", { + message: Schema.String, +}) {} +const pending = () => new SessionPending({ message: "Waiting for your sign-in to load" }); +/** The current token, or none when Clerk can't give one (still loading, offline). */ +const currentToken = (skipCache = false) => + Effect.tryPromise(() => sessionToken({ skipCache })).pipe(Effect.orElseSucceed(() => null)); + +class Client extends Context.Service>()("codework/web/Relay") { + static readonly layer = Layer.effect( + Client, + HttpApiClient.make(Relay.Api, { + baseUrl: relayUrl, + transformClient: (client) => + client.pipe( + HttpClient.mapRequestEffect((request) => + currentToken().pipe( + Effect.map((token) => (token === null ? request : HttpClientRequest.bearerToken(request, token))), + ), + ), + HttpClient.transform((response, request) => + Effect.gen(function* () { + const first = yield* response; + if (first.status !== 401) return first; + const token = yield* currentToken(true); + return token === null + ? first + : yield* client.execute(HttpClientRequest.bearerToken(request, token)); + }), + ), + HttpClient.tap((response) => + Effect.sync(() => + report(response.status === 401 ? "signedOut" : response.status === 503 ? "unavailable" : "ok"), + ), + ), + HttpClient.tapError((error) => + Effect.sync(() => { + if (error.reason._tag === "TransportError") report("unreachable"); + }), + ), + ), + }), + ).pipe(Layer.provide(FetchHttpClient.layer)); +} + +const runtime = Atom.runtime(Client.layer); + +const isUnauthorized = Schema.is(Relay.Unauthorized); + +const unreachable = /transport error|fetch failed|econnrefused|enotfound|etimedout|network/i; + +/** A relay failure in people's words: a network failure reads as one; the relay's own message otherwise. */ +export const relayFailure = (cause: unknown) => { + if (isUnauthorized(Cause.isCause(cause) ? Cause.squash(cause) : cause)) + return "Your sign-in expired. Sign in again."; + const message = messageOf(cause); + return unreachable.test(message) + ? "Can't reach CodeWork's servers. Check your connection, then try again." + : message; +}; + +/** A failure that passes on its own: the relay or its sign-in vendor out of reach, or no session yet. */ +export const isTransient = (cause: unknown) => { + const error = Cause.isCause(cause) ? Cause.squash(cause) : cause; + return ( + Schema.is(Relay.Unavailable)(error) || + Schema.is(SessionPending)(error) || + (HttpClientError.isHttpClientError(error) && error.reason._tag === "TransportError") + ); +}; + +/** The relay refused the session even with a fresh token: the person has to sign in again. */ +export const isSignedOut = (cause: unknown) => isUnauthorized(Cause.isCause(cause) ? Cause.squash(cause) : cause); + +/** + * The signed-in account and the workspaces it belongs to. A refused session gets one more try with a + * fresh token (it may only be stale after sleep). Out of reach, it is what the relay last said on this + * device, and the status slot says so; it fails only when nothing was remembered yet. + */ +export const meAtom = runtime + .atom( + Effect.gen(function* () { + const client = yield* Client; + // Without a session yet there is nothing to ask the relay with; wait for one. + const get = Effect.gen(function* () { + if ((yield* currentToken()) === null) return yield* pending(); + return yield* client.me.get(); + }); + return yield* get.pipe( + Effect.tap((me) => Effect.sync(() => remember(me))), + Effect.catchIf(isTransient, (error) => { + const known = remembered(); + return known === undefined ? Effect.fail(error) : Effect.succeed(known); + }), + ); + }), + ) + .pipe(Atom.keepAlive); + +const workspaceKey = "codework.workspace"; + +const savedWorkspace = () => { + try { + return localStorage.getItem(workspaceKey) ?? undefined; + } catch { + // Storage can be unavailable; the first workspace is used. + return undefined; + } +}; + +/** The workspace picked in this app, remembered across launches. */ +const chosenAtom = Atom.writable( + () => savedWorkspace(), + (ctx, id: string) => { + try { + localStorage.setItem(workspaceKey, id); + } catch { + // Unsaved, the choice still holds until the app quits. + } + ctx.setSelf(id); + }, +); + +/** Picks the workspace the app works in. */ +export const chooseWorkspaceAtom = Atom.writable( + () => undefined, + (ctx, id: string) => ctx.set(chosenAtom, id), +); + +/** The workspace the app works in: the one picked, while the account still belongs to it, else the first. */ +export const workspaceAtom = Atom.make((get) => { + const chosen = get(chosenAtom); + return AsyncResult.map( + get(meAtom), + (me) => me.workspaces.find((workspace) => workspace.id === chosen) ?? me.workspaces[0], + ); +}); + +/** Creates a workspace the account owns and switches the app to it. */ +export const createWorkspaceAtom = runtime.fn((name: string, get) => + Effect.gen(function* () { + const client = yield* Client; + const workspace = yield* client.workspace.create({ payload: { name } }); + get.set(chosenAtom, workspace.id); + get.refresh(meAtom); + return workspace; + }), +); + +/** Approves a machine's connect code for a workspace the account belongs to. */ +export const approveAtom = runtime.fn((input: { readonly userCode: string; readonly workspaceId: string }) => + Effect.gen(function* () { + const client = yield* Client; + return yield* client.workspace.approve({ payload: input }); + }), +); + +/** The machines connected to a workspace, as the relay last heard from them. */ +export const machinesAtom = Atom.family((workspaceId: string) => + runtime.atom( + Effect.gen(function* () { + const client = yield* Client; + return yield* client.workspace.machines({ params: { workspaceId } }); + }), + ), +); + +/** A workspace's pending connects: machines that ran `codework connect --workspace` and wait for approval. */ +export const pairingsAtom = Atom.family((workspaceId: string) => + runtime.atom( + Effect.gen(function* () { + const client = yield* Client; + return yield* client.workspace.pairings({ params: { workspaceId } }); + }), + ), +); + +/** Turns a pending connect away. */ +export const declineAtom = runtime.fn((input: { readonly userCode: string; readonly workspaceId: string }) => + Effect.gen(function* () { + const client = yield* Client; + return yield* client.workspace.decline({ payload: input }); + }), +); + +/** Disconnects another machine from a workspace, as its owner or a workspace owner or admin. */ +export const removeMachineAtom = runtime.fn( + (input: { + readonly workspaceId: string; + readonly machineId: string; + readonly keyId: string; + readonly afterDisconnect: boolean; + }) => + Effect.gen(function* () { + const client = yield* Client; + const remove = client.workspace.remove({ + params: { workspaceId: input.workspaceId, machineId: input.machineId }, + payload: { keyId: input.keyId }, + }); + // The machine may already have revoked this key before its acknowledgement was lost. + return yield* input.afterDisconnect + ? remove.pipe(Effect.catchTag("Relay.NotFound", () => Effect.void)) + : remove; + }), +); diff --git a/apps/web/src/kernel/servers.ts b/apps/web/src/kernel/servers.ts index 72ac4443..f85239f0 100644 --- a/apps/web/src/kernel/servers.ts +++ b/apps/web/src/kernel/servers.ts @@ -4,6 +4,15 @@ import { AsyncResult, Atom, Reactivity } from "effect/reactivity"; import { Server } from "./rpc"; +/** Starts, restarts or stops a server through its CLI. */ +export const serviceAtom = Server.mutation("servers.service"); + +/** The install script, for running it by hand. */ +export const INSTALL = "curl -fsSL https://codework.sh/install | sh"; + +/** Runs the install script for a server whose CLI is missing. */ +export const installAtom = Server.mutation("servers.install"); + /** Queries answered by the default CodeWork server; they load again once it is back. */ export const codeworkKey = ["codework"]; @@ -76,9 +85,14 @@ export const serversAtom = Server.runtime ) .pipe(Atom.keepAlive); +/** The default server's status once known; undefined until then. */ +export const defaultServerAtom = Atom.make((get) => { + const result = get(serversAtom); + return AsyncResult.isSuccess(result) ? defaultOf(result.value) : undefined; +}); + /** The default server's problem once its status is known; undefined until then, and while there is none. */ export const problemAtom = Atom.make((get) => { - const result = get(serversAtom); - const status = AsyncResult.isSuccess(result) ? defaultOf(result.value) : undefined; + const status = get(defaultServerAtom); return status === undefined ? undefined : problemOf(status); }); diff --git a/apps/web/src/landing/sidebar.tsx b/apps/web/src/landing/sidebar.tsx index 255be27d..e9860ec9 100644 --- a/apps/web/src/landing/sidebar.tsx +++ b/apps/web/src/landing/sidebar.tsx @@ -5,7 +5,6 @@ import { ChatsIcon, FolderIcon, FolderOpenIcon, - GearSixIcon, MagnifyingGlassIcon, NotePencilIcon, PlusIcon, @@ -29,6 +28,7 @@ import { SidebarInput, SidebarRail, } from "@/components/ui/sidebar"; +import { ConnectionStatus } from "../shell/status"; import { isMac, openMode } from "@codeworksh/widget/view"; import { sessionAddress, threadRef } from "../widgets/session/address"; import { projectsAtom } from "../widgets/session/projects"; @@ -38,6 +38,7 @@ import { useTabs, tabTag } from "../wm/tabs"; import { useOpenElsewhere } from "../wm/open"; import { Ago } from "../widgets/time"; import { OpenProviderSettings } from "@/components/offline"; +import { WorkspaceSwitcher } from "../shell/workspace"; import { ProviderIcon } from "@/components/provider"; import { problemAtom } from "../kernel/servers"; import { Empty, EmptyAction } from "./empty"; @@ -52,9 +53,9 @@ import { type Entry, GROUPS, type Group, groupLabel, groupsOf, ORDERS, useDispla * Recent sessions across every project, newest first, beside every page. With none yet it invites * adding a project: the folder the start page's composer then works in. */ -/** A sidebar action: New, Threads, Settings. Each sets its own colour: New, the primary action, is full ink. */ +/** A sidebar action: New, Threads. Each sets its own colour: New, the primary action, is full ink. */ const NAV_ROW = - "flex h-7 w-full items-center gap-2 rounded-md px-2 text-left text-ui outline-none hover:bg-selection-subtle hover:text-ink active:scale-[0.99] focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"; + "flex h-7 w-full items-center gap-2.5 rounded-lg px-2.5 text-left text-ui font-medium outline-none hover:bg-selection-subtle hover:text-ink active:scale-[0.99] focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"; const collapsedKey = "codework.sidebar.collapsed"; const decodeCollapsed = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Array(Schema.String))); @@ -142,6 +143,7 @@ export function SessionsSidebar() { return ( + + + )} + + + + ); +} + +/** Machines that ran `codework connect --workspace` for this workspace, each with the code to check. */ +function Waiting({ workspace }: { readonly workspace: Relay.Workspace }) { + const pairings = useAtomValue(pairingsAtom(workspace.id)); + const refreshPairings = useAtomRefresh(pairingsAtom(workspace.id)); + const refreshMachines = useAtomRefresh(machinesAtom(workspace.id)); + const approve = useAtomSet(approveAtom, { mode: "promise" }); + const decline = useAtomSet(declineAtom, { mode: "promise" }); + const [busy, setBusy] = useState>(new Set()); + const [error, setError] = useState(null); + useEffect(() => { + const timer = setInterval(refreshPairings, PENDING_MS); + return () => clearInterval(timer); + }, [refreshPairings]); + + const list = AsyncResult.isSuccess(pairings) ? pairings.value : []; + // A connect leaves the list once its machine takes the link (or gives up): the machines list moves. + const codes = list.map((pairing) => pairing.userCode).join(" "); + const previous = useRef(codes); + useEffect(() => { + const now = new Set(codes.split(" ")); + if (previous.current.split(" ").some((code) => code !== "" && !now.has(code))) refreshMachines(); + previous.current = codes; + }, [codes, refreshMachines]); + const act = (pairing: Relay.PendingPairing, how: "approve" | "decline") => { + setBusy((codes) => new Set(codes).add(pairing.userCode)); + setError(null); + const input = { userCode: pairing.userCode, workspaceId: workspace.id }; + (how === "approve" ? approve(input) : decline(input)) + .then(() => { + refreshPairings(); + refreshMachines(); + }) + .catch((cause: unknown) => setError(relayFailure(cause))) + .finally(() => + setBusy((codes) => { + const next = new Set(codes); + next.delete(pairing.userCode); + return next; + }), + ); + }; + const command = `codework connect --workspace ${workspace.id}`; + return ( +
+
+

+ Waiting to Join{list.length > 0 && · {list.length}} +

+
+ + {list.map((pairing) => { + const approved = pairing.status === "approved"; + const working = busy.has(pairing.userCode) || approved; + return ( +
+ + {pairing.machine.os} {pairing.machine.arch} · {pairing.machine.id} · Code{" "} + {pairing.userCode} + {pairing.replaces && <> · Replaces the connected Machine} + + } + > +
+ + +
+
+
+ ); + })} +
+ + Run this on a Machine to add it. It shows up here with its Code; check it matches before approving. + + + {error !== null &&

{error}

} + +
+
+
+ ); +} + +/** + * The way in for a machine that isn't listed (its connect didn't name this workspace): type the code it + * shows. Enter adds it; the field clears and keeps focus for the next. + */ +function ManualCode({ workspace, onAdded }: { readonly workspace: Relay.Workspace; readonly onAdded: () => void }) { + const input = useRef(null); + const approve = useAtomSet(approveAtom, { mode: "promise" }); + const [open, setOpen] = useState(false); + const [code, setCode] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [added, setAdded] = useState(null); + const submit = () => { + if (busy) return; + if (code.trim() === "") { + setError("Enter the Code the Machine shows."); + return; + } + setBusy(true); + setError(null); + approve({ userCode: code.trim().toUpperCase(), workspaceId: workspace.id }) + .then(({ machine }) => { + setAdded(machine.givenName ?? machine.localHostName); + setCode(""); + onAdded(); + }) + .catch((cause: unknown) => setError(relayFailure(cause))) + .finally(() => { + setBusy(false); + input.current?.focus(); + }); + }; + return ( +
+ + input.current?.focus({ preventScroll: true })}> +
{ + event.preventDefault(); + submit(); + }} + > +
+ { + setCode(event.target.value); + setError(null); + }} + /> + {error !== null &&

{error}

} + {added !== null && error === null && ( +

+ + Approved {added} +

+ )} +
+ +
+
+
+ ); +} + +function WorkspaceMachines({ workspace }: { readonly workspace: Relay.Workspace }) { + const machines = useAtomValue(machinesAtom(workspace.id)); + const refresh = useAtomRefresh(machinesAtom(workspace.id)); + const machineAtom = useMachineAtom(); + const local = useAtomValue(machineAtom); + const refreshLocal = useAtomRefresh(machineAtom); + const me = useAtomValue(meAtom); + const localId = AsyncResult.isSuccess(local) ? local.value.id : null; + const localKey = AsyncResult.isSuccess(local) + ? local.value.workspaces.find((option) => option.id === workspace.id)?.keyId + : undefined; + const accountId = AsyncResult.isSuccess(me) ? me.value.account.id : null; + // Machines seen when the page opened; any other is new and arrives with a highlight. + const [seen, setSeen] = useState | null>(null); + // The relay's list and this machine's own record both move: a link removed elsewhere is forgotten on + // the machine's next heartbeat, and a terminal can connect or disconnect it. + useEffect(() => { + const timer = setInterval(() => { + refresh(); + refreshLocal(); + }, REFRESH_MS); + return () => clearInterval(timer); + }, [refresh, refreshLocal]); + // Back in reach: ask now instead of on the next tick. + const reach = useAtomValue(reachAtom); + useEffect(() => { + if (reach === "ok") refresh(); + }, [reach, refresh]); + + if (AsyncResult.isInitial(machines)) { + return ( +
+ +
+ ); + } + // Out of reach, the list the relay last gave stays, marked as such; with none yet, there is nothing to show. + const last = AsyncResult.isFailure(machines) ? Option.getOrUndefined(machines.previousSuccess) : undefined; + if (AsyncResult.isFailure(machines) && last === undefined) { + return ( +
+ +
+ ); + } + const stale = last !== undefined; + const list = AsyncResult.isSuccess(machines) ? machines.value : (last?.value ?? []); + if (seen === null && AsyncResult.isSuccess(machines)) setSeen(new Set(list.map((machine) => machine.id))); + // This machine first, then the newest: a machine just added appears where you are looking. + const ordered = [ + ...list.filter((machine) => machine.id === localId), + ...list.filter((machine) => machine.id !== localId).reverse(), + ]; + return ( +
0 ? ` · ${list.length}` : ""}`} + description={stale ? "As CodeWork last said; it can't be reached now." : undefined} + > + + {list.length === 0 ? ( + } + title="No Machines Yet" + description="Set up this Machine, or run codework connect on another." + /> + ) : ( + + {ordered.map((machine) => ( + + ))} + + )} + +
+ ); +} + +function MachineRow({ + machine, + workspace, + isLocal, + strayLocal, + fresh, + canRemove, + stale, + onGone, +}: { + readonly machine: Relay.Machine; + readonly workspace: Relay.Workspace; + readonly isLocal: boolean; + /** This machine's id under a key it doesn't hold: a link it lost, which only Remove clears. */ + readonly strayLocal: boolean; + /** The last list the relay gave, while it can't be reached: online state is unknown and nothing acts. */ + readonly stale: boolean; + readonly fresh: boolean; + readonly canRemove: boolean; + readonly onGone: () => void; +}) { + const [leaving, setLeaving] = useState(false); + const [tint, setTint] = useState(fresh); + useEffect(() => { + if (!tint) return; + const timer = setTimeout(() => setTint(false), 1600); + return () => clearTimeout(timer); + }, [tint]); + const name = machine.givenName ?? machine.localHostName; + return ( +
+
+
+ + {name} + {isLocal && This Machine} + {strayLocal && This Machine · Not Connected Here} + + } + description={`${machine.os} ${machine.arch} · v${machine.version} · ${machine.id}`} + > + {stale ? ( + Unknown + ) : machine.online ? ( + Online + ) : machine.lastSeenAt === null ? ( + Never Seen + ) : ( + + Last Seen + + )} + {!stale && (isLocal || canRemove || strayLocal) && ( + { + setLeaving(true); + setTimeout(onGone, 260); + }} + /> + )} + +
+
+
+ ); +} + +/** This machine disconnects itself; another is removed by its owner or a workspace owner or admin. */ +function MachineMenu({ + name, + machineId, + keyId, + workspace, + isLocal, + onDone, +}: { + readonly name: string; + readonly machineId: string; + readonly keyId: string; + readonly workspace: Relay.Workspace; + readonly isLocal: boolean; + readonly onDone: () => void; +}) { + const disconnect = useAtomSet(disconnectAtom, { mode: "promise" }); + const remove = useAtomSet(removeMachineAtom, { mode: "promise" }); + const refreshLocal = useAtomRefresh(useMachineAtom()); + const [asking, setAsking] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const confirm = () => { + setBusy(true); + setError(null); + const removeAsPerson = () => remove({ workspaceId: workspace.id, machineId, keyId, afterDisconnect: isLocal }); + (isLocal + ? disconnect({ payload: { workspaceId: workspace.id, keyId } }) + // The relay didn't confirm the machine's own revoke: remove it as the signed-in person instead. + .then(({ revoked }) => + revoked + ? undefined + : removeAsPerson().catch(() => { + throw new Error( + "Disconnected here, but CodeWork's servers didn't confirm. Remove it from the list when you're back online.", + ); + }), + ) + .finally(refreshLocal) + : removeAsPerson() + ) + .then(() => { + setAsking(false); + onDone(); + }) + .catch((cause: unknown) => setError(relayFailure(cause))) + .finally(() => setBusy(false)); + }; + return ( + <> + + + + + + setAsking(true)}> + {isLocal ? "Disconnect…" : `Remove from ${workspace.name}…`} + + + + !busy && setAsking(next)}> + + + {isLocal ? `Disconnect ${name}?` : `Remove ${name}?`} + + {isLocal + ? `It leaves ${workspace.name} and stops showing up here. Connect it again from Setup.` + : `It's disconnected from ${workspace.name}. It can join again with codework connect.`} + + + {error !== null &&

{error}

} + + Cancel + { + // Held open until the call returns, so a failure shows here. + event.preventDefault(); + confirm(); + }} + > + {busy ? (isLocal ? "Disconnecting…" : "Removing…") : isLocal ? "Disconnect" : "Remove"} + + +
+
+ + ); +} + +/** Content that replaces a placeholder fades in where it stood, instead of cutting over. */ +function Loaded({ children }: { readonly children: ReactNode }) { + return ( +
+ {children} +
+ ); +} + +/** Rows the size of real ones while the first answer is on its way, so nothing jumps when it lands. */ +function Placeholder({ rows }: { readonly rows: number }) { + return ( + + {Array.from({ length: rows }, (_, index) => ( +
+
+ + +
+ +
+ ))} +
+ ); +} diff --git a/apps/web/src/settings/profile.tsx b/apps/web/src/settings/profile.tsx new file mode 100644 index 00000000..90fd0de6 --- /dev/null +++ b/apps/web/src/settings/profile.tsx @@ -0,0 +1,101 @@ +import { useUser } from "@clerk/electron/react"; +import { useRef, useState } from "react"; + +import { messageOf } from "@/lib/utils"; +import { isSignedInApp } from "../auth"; +import { Group, Page, quietField, Row, SavingInput } from "./blocks"; +import { EmptyState } from "./controls"; + +/** The signed-in account: picture, email and name, as the sign-in provider keeps them. */ +export function ProfileSettings() { + return ( + + {isSignedInApp ? ( + + ) : ( + + )} + + ); +} + +function Account() { + const { isLoaded, user } = useUser(); + const [error, setError] = useState<{ + readonly field: "picture" | "first" | "last"; + readonly message: string; + } | null>(null); + if (!isLoaded) return null; + if (user === null || user === undefined) + return ; + const failed = (field: "picture" | "first" | "last") => (cause: unknown) => + setError({ field, message: messageOf(cause) }); + const errorOf = (field: "picture" | "first" | "last") => (error?.field === field ? error.message : undefined); + return ( + + + { + setError(null); + user.setProfileImage({ file }).catch(failed("picture")); + }} + /> + + + {user.primaryEmailAddress?.emailAddress} + + + { + setError(null); + user.update({ firstName }).catch(failed("first")); + }} + /> + + + { + setError(null); + user.update({ lastName }).catch(failed("last")); + }} + /> + + + ); +} + +/** The picture as a button that picks a new image file. */ +function Picture({ url, onPick }: { readonly url: string; readonly onPick: (file: File) => void }) { + const input = useRef(null); + return ( + <> + + { + const file = event.target.files?.[0]; + event.target.value = ""; + if (file !== undefined) onPick(file); + }} + /> + + ); +} diff --git a/apps/web/src/settings/sections.ts b/apps/web/src/settings/sections.ts index f97a340b..3cd09551 100644 --- a/apps/web/src/settings/sections.ts +++ b/apps/web/src/settings/sections.ts @@ -3,6 +3,7 @@ import { ChatTextIcon, CpuIcon, CubeIcon, + DesktopTowerIcon, HardDrivesIcon, type Icon, KeyboardIcon, @@ -12,10 +13,18 @@ import { SlidersHorizontalIcon, SparkleIcon, StackIcon, + UserIcon, + WrenchIcon, } from "@phosphor-icons/react"; +/** Whether a path is a settings page: the app's own, or the account's and workspace's under a workspace. */ +export const isSettingsPath = (pathname: string) => + pathname.startsWith("/settings") || /^\/workspaces\/[^/]+\/settings(\/|$)/.test(pathname); + export interface SettingsSection { readonly to: + | "/workspaces/$workspaceId/settings/account/profile" + | "/workspaces/$workspaceId/settings/machines/setup" | "/settings/general" | "/settings/tabs" | "/settings/themes" @@ -26,57 +35,65 @@ export interface SettingsSection { | "/settings/mcp" | "/settings/skills" | "/settings/plugins" + | "/workspaces/$workspaceId/settings/machines" | "/settings/sandboxes" | "/settings/archive"; readonly label: string; readonly icon: Icon; /** Sidebar heading the section sits under. */ - readonly group: string; + readonly group: "Personal" | "Application" | "Administration"; /** Extra words the search matches, beyond the label. */ readonly keywords: readonly string[]; } const sections: readonly SettingsSection[] = [ + { + to: "/workspaces/$workspaceId/settings/account/profile", + label: "Profile", + icon: UserIcon, + group: "Personal", + keywords: ["account", "name", "email", "picture", "photo", "avatar"], + }, { to: "/settings/general", label: "General", icon: SlidersHorizontalIcon, - group: "App", + group: "Application", keywords: ["notifications", "sounds", "alerts", "quick", "composer", "editor", "terminal", "version", "updates"], }, { to: "/settings/tabs", label: "Tabs", icon: StackIcon, - group: "App", + group: "Application", keywords: ["tabs", "shortcuts", "reorder", "rename", "delete"], }, { to: "/settings/themes", label: "Themes", icon: PaletteIcon, - group: "App", + group: "Application", keywords: ["appearance", "colors", "dark", "light"], }, { to: "/settings/servers", label: "Providers", icon: HardDrivesIcon, - group: "App", + group: "Application", keywords: ["servers", "provider", "local", "remote", "cli", "service", "install", "codework", "version", "rpc"], }, { to: "/settings/keybindings", label: "Keybindings", icon: KeyboardIcon, - group: "App", + group: "Application", keywords: ["shortcuts", "hotkeys", "keyboard", "bindings", "keys", "palette"], }, { to: "/settings/models", label: "Models", icon: CpuIcon, - group: "Agents", + group: "Application", keywords: [ "accounts", "oauth", @@ -95,14 +112,14 @@ const sections: readonly SettingsSection[] = [ to: "/settings/chat", label: "Chat", icon: ChatTextIcon, - group: "Agents", + group: "Application", keywords: ["transcript", "composer", "prompt", "steer", "queue", "follow-up", "usage", "tokens", "games"], }, { to: "/settings/mcp", label: "MCP", icon: PlugsConnectedIcon, - group: "Agents", + group: "Application", keywords: [ "mcp", "tools", @@ -120,28 +137,42 @@ const sections: readonly SettingsSection[] = [ to: "/settings/skills", label: "Skills", icon: SparkleIcon, - group: "Agents", + group: "Application", keywords: ["skills", "skill.md", "instructions", "workflows", "project", "personal"], }, { to: "/settings/plugins", label: "Plugins", icon: PuzzlePieceIcon, - group: "Agents", + group: "Application", keywords: ["plugins", "extensions", "npm", "tools", "prompt", "bash", "grep", "find", "reload"], }, + { + to: "/workspaces/$workspaceId/settings/machines/setup", + label: "Setup", + icon: WrenchIcon, + group: "Administration", + keywords: ["set up", "install", "cli", "start", "server", "connect", "this machine", "onboarding"], + }, + { + to: "/workspaces/$workspaceId/settings/machines", + label: "Machines", + icon: DesktopTowerIcon, + group: "Administration", + keywords: ["machines", "connect", "online", "offline", "rename", "name", "relay", "harness", "computer"], + }, { to: "/settings/sandboxes", label: "Sandboxes", icon: CubeIcon, - group: "Workspace", + group: "Application", keywords: ["sandboxes", "worktrees", "git", "branch", "vercel", "daytona", "memory", "isolation"], }, { to: "/settings/archive", label: "Archive", icon: ArchiveIcon, - group: "Workspace", + group: "Application", keywords: ["archived", "restore", "unarchive", "sessions", "projects", "hidden"], }, ]; diff --git a/apps/web/src/settings/servers/local.tsx b/apps/web/src/settings/servers/local.tsx index 890674df..c4a01424 100644 --- a/apps/web/src/settings/servers/local.tsx +++ b/apps/web/src/settings/servers/local.tsx @@ -1,4 +1,4 @@ -import { ArrowCounterClockwiseIcon, CheckIcon, CopyIcon, TrashIcon, WarningIcon } from "@phosphor-icons/react"; +import { ArrowCounterClockwiseIcon, TrashIcon, WarningIcon } from "@phosphor-icons/react"; import { useAtomSet } from "@effect/atom-react"; import { type CliAction, LOCAL_SERVER, type LocalServerStatus, type ServerUpdate } from "@codeworksh/contract"; @@ -19,16 +19,15 @@ import { Button } from "@/components/ui/button"; import { messageOf } from "@/lib/utils"; import brand from "../../assets/codework.png"; import { Server } from "../../kernel/rpc"; +import { INSTALL, installAtom, serviceAtom } from "../../kernel/servers"; import { Code, Group as Card, quietField as field, SavingInput } from "../blocks"; import { Variables } from "./variables"; +import { CopyCommand } from "@/components/copyable"; -const serviceAtom = Server.mutation("servers.service"); const updateAtom = Server.mutation("servers.update"); const removeAtom = Server.mutation("servers.remove"); const setDefaultAtom = Server.mutation("servers.setDefault"); -const INSTALL = "curl -fsSL https://codework.sh/install | sh"; - type Tone = "success" | "warning" | "danger" | "info" | "muted"; const TONES: Record = { @@ -232,7 +231,12 @@ export function LocalDetail({ status }: { status: LocalServerStatus }) { placeholder={cli !== null && !cli.custom ? cli.path : "codework"} onSave={(next) => configure({ executable: next || null })} > - {cli === null && } + {cli === null && ( + + + + + )} {cli !== null && "failure" in cli && {cli.failure}} (null); return ( - - {command} + + {error !== null && {error}} ); } diff --git a/apps/web/src/setup.tsx b/apps/web/src/setup.tsx new file mode 100644 index 00000000..9b7c98ad --- /dev/null +++ b/apps/web/src/setup.tsx @@ -0,0 +1,352 @@ +import { shellQuoted } from "@codeworksh/schema"; +import { useAtom, useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react"; +import { CaretRightIcon, CheckIcon, CircleNotchIcon } from "@phosphor-icons/react"; +import { useNavigate } from "@tanstack/react-router"; +import { AsyncResult, Atom } from "effect/reactivity"; +import { type ReactNode, useEffect, useState } from "react"; + +import { Collapse } from "@/components/collapse"; +import { CopyCommand } from "@/components/copyable"; +import { Button } from "@/components/ui/button"; +import { messageOf } from "@/lib/utils"; +import { Frame } from "./frame"; +import { isSignedInApp } from "./auth"; +import { meAtom, workspaceAtom } from "./kernel/relay"; +import { defaultServerAtom, INSTALL, installAtom, serviceAtom } from "./kernel/servers"; +import { approveLabel, canAct, CodeSlot, useMachineAtom, useConnect } from "./shell/connect"; + +/** Set Up Later, per workspace: the app stops opening this page for it. */ +const laterKey = (workspaceId: string) => `codework.setup.later.${workspaceId}`; + +const setUpLater = (workspaceId: string) => { + try { + localStorage.setItem(laterKey(workspaceId), "1"); + } catch { + // Unsaved, the page opens again on the next launch. + } +}; + +const putOff = (workspaceId: string) => { + try { + return localStorage.getItem(laterKey(workspaceId)) !== null; + } catch { + return false; + } +}; + +// Once per sign-in: after that, the app stays where the person goes. The atom registry is mounted inside +// the auth gate, so it starts over for each account that signs in. +const checkedAtom = Atom.make(false).pipe(Atom.keepAlive); + +/** + * Opens setup when this machine isn't set up for the workspace the app opens in: the CLI missing, its + * server not running, or the machine not connected. Not for a workspace set up later, and never while the + * relay or the local server is still unknown; local work never waits on it. + */ +export function SetupGate() { + const navigate = useNavigate(); + const [checked, setChecked] = useAtom(checkedAtom); + const current = useAtomValue(workspaceAtom); + const status = useAtomValue(defaultServerAtom); + const machineAtom = useMachineAtom(); + const machine = useAtomValue(machineAtom); + const workspace = AsyncResult.isSuccess(current) ? current.value : undefined; + const running = status?.server._tag === "Running"; + const needs = + workspace === undefined || status === undefined + ? undefined + : status.cli === null || !("version" in status.cli) || !running + ? true + : AsyncResult.isSuccess(machine) + ? !machine.value.workspaces.some((option) => option.id === workspace.id) + : undefined; + useEffect(() => { + if (checked || !isSignedInApp || workspace === undefined || needs === undefined) return; + setChecked(true); + if (needs && !putOff(workspace.id)) { + void navigate({ + to: "/workspaces/$workspaceId/settings/machines/setup", + params: { workspaceId: workspace.id }, + replace: true, + }); + } + }, [checked, setChecked, needs, workspace, navigate]); + return null; +} + +/** + * Sets up this machine for a workspace in three steps: install the CLI, start its server, connect to + * the workspace. Only the current step is open; each also offers its terminal command. + */ +export function Setup({ workspaceId }: { readonly workspaceId: string }) { + const navigate = useNavigate(); + const status = useAtomValue(defaultServerAtom); + const machineAtom = useMachineAtom(); + const machine = useAtomValue(machineAtom); + const refreshMachine = useAtomRefresh(machineAtom); + const me = useAtomValue(meAtom); + const install = useAtomSet(installAtom, { mode: "promise" }); + const service = useAtomSet(serviceAtom, { mode: "promise" }); + const [busy, setBusy] = useState<"install" | "start" | null>(null); + const [error, setError] = useState(null); + const [connecting, setConnecting] = useState(false); + + const workspace = AsyncResult.isSuccess(me) + ? me.value.workspaces.find((option) => option.id === workspaceId) + : undefined; + const workspaceName = workspace?.name ?? "Your Workspace"; + const cli = status?.cli ?? null; + const version = cli !== null && "version" in cli ? cli.version : undefined; + const running = status?.server._tag === "Running"; + // The terminal commands reach this server's home: a home chosen in Settings isn't the CLI's default. + const home = + status !== undefined && "home" in status && status.home.custom ? ` --home ${shellQuoted(status.home.path)}` : ""; + const connected = + AsyncResult.isSuccess(machine) && machine.value.workspaces.some((option) => option.id === workspaceId); + const name = AsyncResult.isSuccess(machine) + ? (machine.value.givenName ?? machine.value.localHostName) + : (status?.name ?? "This Machine"); + const current = version === undefined ? 0 : !running ? 1 : !connected ? 2 : 3; + + // A call's step stays busy until the server's status moves past it, a moment after the call returns, + // so its button never flips back to ready in between. + useEffect(() => { + setBusy(null); + }, [current]); + + // A server that just started answers machine.info now; read it again to see its workspaces. + useEffect(() => { + if (running) refreshMachine(); + }, [running, refreshMachine]); + + const run = (step: "install" | "start") => { + if (status === undefined) return; + setBusy(step); + setError(null); + const done = + step === "install" + ? install({ payload: { id: status.id } }) + : service({ payload: { id: status.id, action: "start" } }); + done.catch((cause: unknown) => { + setError(messageOf(cause)); + setBusy(null); + }); + }; + + return ( + +
+
+
+

Set Up CodeWork

+

+ Setting up {name} +

+
+
    + + + + + + + + {connecting ? ( + setConnecting(false)} /> + ) : ( + + )} + +
+
+ + +
+
+
+ + ); +} + +/** A running connect: its code to check, then Approve. The row keeps its shape through every phase. */ +function Connecting({ workspaceId, onCancel }: { readonly workspaceId: string; readonly onCancel: () => void }) { + const connect = useConnect(workspaceId); + return ( +
+
+ + + +
+ {connect.error !== null &&

{connect.error}

} +
+ ); +} + +/** A button label that swaps to its working form, a spinner and words, without changing width. */ +function BusyLabel({ + busy, + idle, + working, +}: { + readonly busy: boolean; + readonly idle: string; + readonly working: string; +}) { + return ( + + {idle} + + + {working} + + + ); +} + +function Step({ + index, + current, + title, + summary, + line, + problem, + command, + error, + children, +}: { + readonly index: number; + readonly current: number; + readonly title: string; + readonly summary: string; + readonly line: string; + /** What stands in the step's way, in place of its line and in the error's colour. */ + readonly problem: string | null; + readonly command: string; + readonly error: string | null; + readonly children: ReactNode; +}) { + const done = index < current; + const open = index === current; + const [terminal, setTerminal] = useState(false); + return ( +
  • + + {done ? ( + + ) : ( + index + 1 + )} + +
    +
    + + {title} + + {done && ( + + {summary} + + )} +
    + + {problem === null ? ( +

    {line}

    + ) : ( +

    {problem}

    + )} +
    +
    {children}
    + {error !== null &&

    {error}

    } +
    +
    + + +
    + +
    +
    +
    +
    +
    +
  • + ); +} diff --git a/apps/web/src/shell/connect.tsx b/apps/web/src/shell/connect.tsx new file mode 100644 index 00000000..88087713 --- /dev/null +++ b/apps/web/src/shell/connect.tsx @@ -0,0 +1,114 @@ +import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react"; +import { Effect, Stream } from "effect"; +import { AsyncResult, Atom } from "effect/reactivity"; +import { useEffect, useState } from "react"; + +import { approveAtom, relayFailure } from "../kernel/relay"; +import { Server } from "../kernel/rpc"; +import { defaultServerAtom } from "../kernel/servers"; + +/** This machine (the default CodeWork server) and the workspaces it is connected to. */ +export function useMachineAtom() { + const home = useAtomValue(defaultServerAtom)?.home.path; + return Server.query("machine.info", undefined, { reactivityKeys: ["codework", home] }); +} + +/** Disconnects this machine from a workspace. */ +export const disconnectAtom = Server.mutation("machine.disconnect"); + +/** + * A connect of this machine to one workspace, running while something reads it: the latest of its + * events, the code to approve and then the link. Closing the dialog that reads it cancels the connect. + */ +const connectAtom = Atom.family((workspaceId: string) => + Server.runtime.atom( + Stream.unwrap(Server.use((client) => Effect.succeed(client("machine.connect", { workspaceId })))), + ), +); + +/** + * Connects this machine to a workspace while mounted, and approves its code as the signed-in member. + * After Approve it holds as `approved` until the link arrives, which the relay reports on its next poll + * a few seconds later, so the code is never approved twice. Unmounting cancels the connect. + */ +export function useConnect(workspaceId: string) { + const progress = useAtomValue(connectAtom(workspaceId)); + const restart = useAtomRefresh(connectAtom(workspaceId)); + const refreshMachine = useAtomRefresh(useMachineAtom()); + const approve = useAtomSet(approveAtom, { mode: "promise" }); + const [sent, setSent] = useState<"approving" | "approved" | null>(null); + // The approved code stays on screen once the stream moves past it, until the link folds the step. + const [approved, setApproved] = useState(undefined); + const [error, setError] = useState(null); + const event = AsyncResult.isSuccess(progress) ? progress.value : undefined; + const failure = AsyncResult.isFailure(progress) ? relayFailure(progress.cause) : null; + const linked = event?._tag === "Connected" ? event.connected : undefined; + const code = event?._tag === "Code" ? event.userCode : approved; + // The machine's own record of its workspaces changed; the menu and setup read it. + useEffect(() => { + if (linked !== undefined) refreshMachine(); + }, [linked, refreshMachine]); + const phase = + linked !== undefined + ? "connected" + : failure !== null + ? "failed" + : (sent ?? (code === undefined ? "starting" : "code")); + return { + phase, + code, + /** Whether Cancel can still stop it: not once approved. */ + cancellable: phase !== "approved" && phase !== "connected", + linked, + error: failure ?? error, + /** Approves the code, or after a failure starts the connect again for a new one. */ + act: () => { + if (failure !== null) { + setSent(null); + setApproved(undefined); + setError(null); + restart(); + return; + } + if (code === undefined || sent !== null) return; + setSent("approving"); + setApproved(code); + setError(null); + approve({ userCode: code, workspaceId }).then( + () => setSent("approved"), + (cause: unknown) => { + setError(relayFailure(cause)); + setSent(null); + }, + ); + }, + }; +} + +/** What the approve button says in each phase; its width is held so the row doesn't move. */ +export const approveLabel = (phase: ReturnType["phase"]) => + phase === "approving" + ? "Approving…" + : phase === "approved" + ? "Connecting…" + : phase === "connected" + ? "Connected" + : phase === "failed" + ? "Try Again" + : "Approve"; + +/** Whether the approve button does anything now: Approve with a code, or Try Again after a failure. */ +export const canAct = (phase: ReturnType["phase"]) => phase === "code" || phase === "failed"; + +/** A code's slot: dots until the code comes, at the same width, so nothing shifts when it does. */ +export function CodeSlot({ code }: { readonly code: string | undefined }) { + return ( + + {code ?? "····-····"} + + ); +} diff --git a/apps/web/src/shell/shell.tsx b/apps/web/src/shell/shell.tsx index 2a6dfaf4..d0ca62b7 100644 --- a/apps/web/src/shell/shell.tsx +++ b/apps/web/src/shell/shell.tsx @@ -3,6 +3,7 @@ import { Outlet, useLocation, useNavigate, useParams } from "@tanstack/react-rou import { AsyncResult } from "effect/reactivity"; import { useEffect } from "react"; +import { isSettingsPath } from "../settings/sections"; import { Desktop } from "../wm/desktop"; import { deskQueryAtom } from "../wm/instances"; import { lastTabAtom, useTabs, useTabReturn, tabRoute, tabsAtom } from "../wm/tabs"; @@ -19,14 +20,16 @@ export function Shell() { const navigate = useNavigate(); // From the location, which changes before route params do: a match-based check lags a // render behind, in which the first tab would pass for the one settings returns to. - const inSettings = useLocation({ select: (location) => location.pathname.startsWith("/settings") }); + const inSettings = useLocation({ select: (location) => isSettingsPath(location.pathname) }); const overDesktop = useLocation({ select: (location) => - location.pathname.startsWith("/settings") || + isSettingsPath(location.pathname) || location.pathname === "/threads" || location.pathname === "/projects" || location.pathname === "/metrics", }); + // On a tab's own page. A page outside the shell, still shown while the next one loads, is not one. + const onTab = useLocation({ select: (location) => location.pathname.startsWith("/tabs/") }); // An id that no longer exists (a deleted tab) shows the first one. const shown = tabs.find((tab) => tab.id === tabId) ?? tabs[0]; const back = useTabReturn(); @@ -39,14 +42,14 @@ export function Shell() { const desk = useAtomValue(deskQueryAtom); const ready = AsyncResult.isSuccess(listed) && AsyncResult.isSuccess(desk); useEffect(() => { - if (loaded && tabs.length === 0 && !overDesktop) void navigate({ to: "/", replace: true }); - }, [loaded, tabs.length, overDesktop, navigate]); + if (loaded && tabs.length === 0 && onTab) void navigate({ to: "/", replace: true }); + }, [loaded, tabs.length, onTab, navigate]); // Remembered past this route, so the start page opens things where the user last was. const setLastTab = useAtomSet(lastTabAtom); useEffect(() => { - if (!overDesktop && shown !== undefined) setLastTab(shown.id); - }, [overDesktop, shown, setLastTab]); + if (onTab && shown !== undefined) setLastTab(shown.id); + }, [onTab, shown, setLastTab]); useEffect(() => { const onKeyDown = (event: KeyboardEvent) => { diff --git a/apps/web/src/shell/sources.tsx b/apps/web/src/shell/sources.tsx index bcbdc02d..0c2ae84b 100644 --- a/apps/web/src/shell/sources.tsx +++ b/apps/web/src/shell/sources.tsx @@ -11,7 +11,6 @@ import { } from "@phosphor-icons/react"; import { RegistryContext, useAtomSet, useAtomValue } from "@effect/atom-react"; import { useNavigate } from "@tanstack/react-router"; -import { Cause, Option } from "effect"; import { AsyncResult } from "effect/reactivity"; import { type KeyboardEvent, type ReactNode, useContext, useRef, useState } from "react"; @@ -77,9 +76,7 @@ const cloneAtom = Server.mutation("host.clone"); const lookupAtom = Server.mutation("github.lookup"); const failureOf = (result: AsyncResult.AsyncResult) => - AsyncResult.isFailure(result) - ? messageOf(Option.getOrElse(Cause.findErrorOption(result.cause), () => Cause.squash(result.cause))) - : undefined; + AsyncResult.isFailure(result) ? messageOf(result.cause) : undefined; /** The palette's Add Project steps: pick a source, then browse, name, or clone into a folder. */ export function AddProject(nav: Nav) { diff --git a/apps/web/src/shell/status.tsx b/apps/web/src/shell/status.tsx new file mode 100644 index 00000000..c55b5439 --- /dev/null +++ b/apps/web/src/shell/status.tsx @@ -0,0 +1,116 @@ +import { useClerk } from "@clerk/electron/react"; +import { useAtomRefresh, useAtomValue } from "@effect/atom-react"; +import { ArrowClockwiseIcon } from "@phosphor-icons/react"; +import { AsyncResult } from "effect/reactivity"; +import { useEffect, useState, useSyncExternalStore } from "react"; + +import { isSignedInApp } from "../auth"; +import { isSignedOut, isTransient, meAtom, reachAtom } from "../kernel/relay"; + +type Connection = "ok" | "offline" | "unreachable" | "unavailable" | "signedOut"; + +const LABELS: Record, { readonly label: string; readonly detail: string }> = { + offline: { label: "Offline", detail: "This device is offline. Workspaces show what CodeWork last said." }, + unreachable: { + label: "Can't Reach CodeWork", + detail: "CodeWork's servers aren't answering. Workspaces show what they last said.", + }, + unavailable: { + label: "Sign-In Unavailable", + detail: "CodeWork's sign-in service isn't responding. Workspaces show what CodeWork last said.", + }, + signedOut: { label: "Signed Out", detail: "Your sign-in expired." }, +}; + +const subscribeOnline = (notify: () => void) => { + window.addEventListener("online", notify); + window.addEventListener("offline", notify); + return () => { + window.removeEventListener("online", notify); + window.removeEventListener("offline", notify); + }; +}; + +/** Whether CodeWork's servers can be used now, from the device's network, the last relay call and the account. */ +function useConnection(): Connection { + const online = useSyncExternalStore(subscribeOnline, () => navigator.onLine); + const reach = useAtomValue(reachAtom); + const me = useAtomValue(meAtom); + if (!online) return "offline"; + if (AsyncResult.isFailure(me) && isSignedOut(me.cause)) return "signedOut"; + if (reach !== "ok") return reach; + if (AsyncResult.isFailure(me) && isTransient(me.cause)) return "unavailable"; + return "ok"; +} + +/** + * The one place the app says CodeWork's servers can't be used: a dot, the state, and Reconnect. Nothing + * while they can. While they can't, it asks again every few seconds, when the window comes back and when + * the network does; the rest of the app keeps what it last heard. + */ +export function ConnectionStatus() { + if (!isSignedInApp) return null; + return ; +} + +function Status() { + const connection = useConnection(); + const refreshMe = useAtomRefresh(meAtom); + const clerk = useClerk(); + const [reconnecting, setReconnecting] = useState(false); + const down = connection !== "ok" && connection !== "signedOut"; + + useEffect(() => { + if (!down) return; + window.addEventListener("focus", refreshMe); + window.addEventListener("online", refreshMe); + const timer = setInterval(refreshMe, 3_000); + return () => { + window.removeEventListener("focus", refreshMe); + window.removeEventListener("online", refreshMe); + clearInterval(timer); + }; + }, [down, refreshMe]); + + // "Reconnecting…" holds long enough to read, then the slot shows what the attempt found. + useEffect(() => { + if (!reconnecting) return; + const timer = setTimeout(() => setReconnecting(false), 1_500); + return () => clearTimeout(timer); + }, [reconnecting]); + + if (connection === "ok") return null; + const { label, detail } = LABELS[connection]; + return ( +
    + + {label} + {connection === "signedOut" ? ( + + ) : ( + + )} +
    + ); +} diff --git a/apps/web/src/shell/titlebar.tsx b/apps/web/src/shell/titlebar.tsx index e68aa1ee..f7ea98bc 100644 --- a/apps/web/src/shell/titlebar.tsx +++ b/apps/web/src/shell/titlebar.tsx @@ -3,6 +3,7 @@ import { useCanGoBack, useLocation, useNavigate, useParams, useRouter } from "@t import { SidebarTrigger, useSidebar } from "@/components/ui/sidebar"; import { isMac } from "@codeworksh/widget/view"; +import { isSettingsPath } from "../settings/sections"; import { MAX_TABS, useCreateTab, useTabs, useTabReturn, tabRoute } from "../wm/tabs"; import { Switcher } from "./switcher"; @@ -17,7 +18,7 @@ const chromeButton = /** Window-level navigation remains available on Home, tabs, and settings. */ export function NavigationControls() { const { open, isMobile } = useSidebar(); - const inSettings = useLocation({ select: (location) => location.pathname.startsWith("/settings") }); + const inSettings = useLocation({ select: (location) => isSettingsPath(location.pathname) }); const withSidebar = open && !isMobile; const { tabId } = useParams({ strict: false }); const tabs = useTabs(); diff --git a/apps/web/src/shell/workspace.tsx b/apps/web/src/shell/workspace.tsx new file mode 100644 index 00000000..037946d6 --- /dev/null +++ b/apps/web/src/shell/workspace.tsx @@ -0,0 +1,89 @@ +import { useClerk } from "@clerk/electron/react"; +import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { CaretDownIcon, CheckIcon, PlusIcon } from "@phosphor-icons/react"; +import { useNavigate } from "@tanstack/react-router"; +import { AsyncResult } from "effect/reactivity"; + +import { Monogram } from "@/components/monogram"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { isSignedInApp } from "../auth"; +import { chooseWorkspaceAtom, meAtom, workspaceAtom } from "../kernel/relay"; + +/** + * The workspace menu at the top of the sidebar: settings, members, switching workspaces and signing out. + * Out of reach it shows what the relay last said; with nothing remembered yet it reads CodeWork, since it is + * also the way to settings. The status slot in the sidebar says when CodeWork can't be reached. + */ +export function WorkspaceSwitcher() { + const navigate = useNavigate(); + const current = useAtomValue(workspaceAtom); + const workspace = AsyncResult.isSuccess(current) ? current.value : undefined; + const id = workspace?.id ?? "codework"; + const name = workspace?.name ?? "CodeWork"; + return ( + + + + {name} + + + + void navigate({ to: "/settings" })}>Settings + {isSignedInApp && ( + <> + {/* Members come with invites; the row marks where they will live. */} + Invite & Manage Members + + + + + )} + + + ); +} + +/** The account's workspaces in a submenu, the current one checked, and creating another. */ +function SwitchWorkspace({ current }: { readonly current: string | undefined }) { + const navigate = useNavigate(); + const me = useAtomValue(meAtom); + const choose = useAtomSet(chooseWorkspaceAtom); + if (!AsyncResult.isSuccess(me)) { + return Switch Workspace; + } + return ( + + Switch Workspace + + {me.value.account.email} + {me.value.workspaces.map((option) => ( + choose(option.id)}> + + {option.name} + {option.id === current && } + + ))} + + void navigate({ to: "/workspaces/join" })}> + + Create Workspace + + + + ); +} + +function SignOut() { + const clerk = useClerk(); + return void clerk.signOut()}>Sign Out; +} diff --git a/apps/web/src/splash.tsx b/apps/web/src/splash.tsx index 70136f4c..ebafca1c 100644 --- a/apps/web/src/splash.tsx +++ b/apps/web/src/splash.tsx @@ -7,7 +7,7 @@ import { serversAtom } from "./kernel/servers"; const LONGEST = 2_000; /** Fades the splash in index.html away; it is gone once the fade ends. */ -function reveal() { +export function reveal() { const shell = document.getElementById("boot-shell"); if (shell === null || shell.classList.contains("done")) return; shell.classList.add("done"); diff --git a/apps/web/src/style.css b/apps/web/src/style.css index ba222661..b9dbb58f 100644 --- a/apps/web/src/style.css +++ b/apps/web/src/style.css @@ -1,9 +1,14 @@ @import "tailwindcss"; -@import "@fontsource-variable/inter/standard.css"; -@import "@fontsource-variable/inter/standard-italic.css"; +/* Inter with its optical-size axis: large text such as page titles draws with Inter Display's tighter shapes. */ +@import "@fontsource-variable/inter/opsz.css"; +@import "@fontsource-variable/inter/opsz-italic.css"; +@import "@fontsource-variable/lilex/wght.css"; /* shadcn/ui's enter and exit animations (animate-in, fade-in-0, zoom-in-95, ...). */ @import "tw-animate-css"; +/* `dark:` follows the app's theme, not the system's: a light theme on a Mac in dark mode stays light. */ +@custom-variant dark (&:where(:root:not([data-theme="light"]), :root:not([data-theme="light"]) *)); + /* `--cw-*` are the theme contract widgets style against. They map onto the site palette's `--t-*` tokens, so switching data-theme restyles everything; light-dark() follows the theme's color-scheme. */ :root { @@ -11,7 +16,11 @@ --cw-frame: var(--t-surface); --cw-frame-top: var(--t-surface-2); --cw-edge: var(--t-border-subtle); - --cw-edge-focus: color-mix(in srgb, var(--t-text) 20%, transparent); + /* Field borders: a hairline in dark, as Linear draws them. */ + --cw-edge-focus: light-dark( + color-mix(in srgb, var(--t-text) 20%, transparent), + color-mix(in srgb, var(--t-text) 10%, transparent) + ); --cw-ink: var(--t-text); --cw-ink-secondary: var(--t-text-secondary); --cw-ink-muted: var(--t-text-muted); @@ -22,22 +31,23 @@ --cw-content-width: 832px; --cw-selection-subtle: light-dark( color-mix(in srgb, var(--cw-ink) 5%, transparent), - color-mix(in srgb, var(--cw-ink) 8%, transparent) + color-mix(in srgb, var(--cw-ink) 6%, transparent) ); --cw-selection: light-dark( color-mix(in srgb, var(--cw-ink) 6%, transparent), - color-mix(in srgb, var(--cw-ink) 10%, transparent) + color-mix(in srgb, var(--cw-ink) 8%, transparent) ); --cw-selection-strong: light-dark( color-mix(in srgb, var(--cw-ink) 7%, transparent), - color-mix(in srgb, var(--cw-ink) 12%, transparent) + color-mix(in srgb, var(--cw-ink) 9%, transparent) ); --cw-selection-hover: light-dark( - color-mix(in srgb, var(--cw-ink) 10%, transparent), - color-mix(in srgb, var(--cw-ink) 15%, transparent) + color-mix(in srgb, var(--cw-ink) 7%, transparent), + color-mix(in srgb, var(--cw-ink) 11%, transparent) ); - --cw-primary: var(--cw-ink); - --cw-primary-ink: var(--cw-frame); + /* Primary actions: the accent, as Linear does. */ + --cw-primary: var(--cw-brand); + --cw-primary-ink: light-dark(var(--cw-frame), var(--cw-brand-ink)); --cw-message: light-dark(#0a0a0a, var(--cw-selection)); --cw-message-ink: light-dark(#ffffff, var(--cw-ink)); --cw-composer: light-dark(var(--cw-frame), color-mix(in srgb, var(--cw-ink) 3%, transparent)); @@ -46,23 +56,39 @@ 0 2px 6px light-dark(color-mix(in srgb, var(--cw-ink) 6%, transparent), transparent), 0 6px 24px light-dark(color-mix(in srgb, var(--cw-ink) 9%, transparent), transparent); --cw-scrollbar: var(--t-scrollbar); - --cw-danger: light-dark(#dc2626, #f87171); - --cw-warning: light-dark(#d97706, #fbbf24); - --cw-success: light-dark(#16a34a, #4ade80); - --cw-info: light-dark(#2563eb, #60a5fa); + /* Dark takes Linear's status colours. */ + --cw-danger: light-dark(#dc2626, #eb5757); + --cw-warning: light-dark(#d97706, #f2c94c); + --cw-success: light-dark(#16a34a, #4cb782); + --cw-info: light-dark(#2563eb, #4ea7fc); --cw-link: light-dark(hsl(211 92% 40%), #7dd3fc); --cw-highlight: light-dark(rgb(255 255 255 / 0.9), color-mix(in oklab, var(--t-text) 9%, transparent)); --cw-drop-shadow: color-mix(in oklab, var(--t-text) 20%, transparent); --cw-shadow-near: light-dark(rgb(0 0 0 / 0.06), rgb(0 0 0 / 0.22)); --cw-shadow-far: light-dark(rgb(0 0 0 / 0.08), rgb(0 0 0 / 0.3)); --cw-dialog-shadow: 0 24px 64px -24px light-dark(rgb(0 0 0 / 0.35), rgb(0 0 0 / 0.9)); - --cw-menu-shadow: 0 16px 40px -18px light-dark(rgb(0 0 0 / 0.55), rgb(0 0 0 / 0.8)); + /* The main panel: a hairline border and the faintest drop, set into the window. */ + --cw-panel-shadow: + 0 3px 6px -2px light-dark(rgb(0 0 0 / 0.02), rgb(0 0 0 / 0.2)), + 0 1px 1px light-dark(rgb(0 0 0 / 0.04), rgb(0 0 0 / 0.25)); + /* A settings card: a hairline ring and a soft drop, lifting it off the panel without a border. */ + --cw-card-shadow: + 0 0 0 1px light-dark(rgb(0 0 0 / 0.06), rgb(255 255 255 / 0.06)), + 0 3px 6px -2px light-dark(rgb(0 0 0 / 0.03), rgb(0 0 0 / 0.25)), + 0 1px 1px light-dark(rgb(0 0 0 / 0.04), rgb(0 0 0 / 0.3)); + --cw-menu-shadow: + 0 6px 18px light-dark(rgb(0 0 0 / 0.04), rgb(0 0 0 / 0.35)), + 0 3px 9px light-dark(rgb(0 0 0 / 0.05), rgb(0 0 0 / 0.3)), + 0 1px 1px light-dark(rgb(0 0 0 / 0.05), rgb(0 0 0 / 0.3)); } @theme { /* Inter is bundled locally; code keeps the platform's monospace face. */ --font-sans: "Inter Variable", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif; - --font-mono: ui-monospace, "SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace; + /* Between regular and medium: secondary text, as Linear sets descriptions. */ + --font-weight-book: 450; + --font-mono: + "Lilex Variable", ui-monospace, "SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace; /* Tailwind's built-in curves are too weak for UI motion. */ --ease-out: cubic-bezier(0.23, 1, 0.32, 1); --ease-in-out: cubic-bezier(0.77, 0, 0.175, 1); @@ -74,6 +100,9 @@ --text-3xs--line-height: calc(0.875 / 0.625); --text-4xs: 0.5rem; --text-4xs--line-height: 1; + /* A settings section heading, between the 13px body and the 24px page title. */ + --text-section: 0.9375rem; + --text-section--line-height: 1.5; --text-ui: 0.8125rem; --text-ui--line-height: 1.4; --text-body: 0.8125rem; @@ -87,6 +116,8 @@ --spacing-tab: 27px; --spacing-pane: 36px; --container-conversation: var(--cw-content-width); + --container-settings: 44rem; + --container-metrics: 1100px; --color-selection-subtle: var(--cw-selection-subtle); --color-selection: var(--cw-selection); --color-selection-strong: var(--cw-selection-strong); @@ -127,7 +158,8 @@ --color-info: var(--cw-info); --color-border: var(--cw-edge); --color-input: var(--cw-edge-focus); - --color-ring: color-mix(in oklab, var(--cw-brand) 50%, transparent); + /* Focus rings: the accent at full strength in dark, where half of it sinks into the surface. */ + --color-ring: light-dark(color-mix(in oklab, var(--cw-brand) 50%, transparent), var(--cw-brand)); --color-sidebar: var(--cw-sidebar); --color-sidebar-foreground: var(--cw-ink); --color-sidebar-primary: var(--cw-ink); @@ -209,6 +241,19 @@ @apply bg-desktop font-sans text-ui text-ink antialiased; } + /* Lilex's ligatures suit code blocks (=>, !==) but not IDs, paths or keys, where -- and -> stay literal. */ + code, + kbd, + samp, + .font-mono { + font-variant-ligatures: none; + } + + pre, + pre code { + font-variant-ligatures: contextual; + } + ::selection { background: color-mix(in srgb, var(--cw-brand) 35%, transparent); } diff --git a/apps/web/src/themes.css b/apps/web/src/themes.css index 64a058dc..a3af25b9 100644 --- a/apps/web/src/themes.css +++ b/apps/web/src/themes.css @@ -1,18 +1,19 @@ -/* The desktop light and dark palettes. Dark applies when no theme is selected. */ +/* The desktop light and dark palettes. Dark applies when no theme is selected. Both follow Linear's + palettes: its sidebar, base and card surfaces, border and text scale, and indigo accent. */ :root, [data-theme="dark"] { --t-bg: #09090a; --t-surface: #121213; --t-surface-2: #1b1b1d; - --t-border-subtle: #252527; + --t-border-subtle: #212224; --t-border-strong: #7a7a7a; - --t-text: #ebebeb; - --t-text-secondary: #c4c4c4; - --t-text-muted: #969696; - --t-scrollbar: rgba(235, 235, 235, 0.28); - --t-brand: #4c9ef5; - --t-brand-ink: #171717; + --t-text: #f7f8f8; + --t-text-secondary: #e3e4e6; + --t-text-muted: #959597; + --t-scrollbar: rgba(247, 248, 248, 0.28); + --t-brand: #6d78d5; + --t-brand-ink: #ffffff; --t-field-bg: #070707; --t-field-dim: #2f2f2f; --t-field-mid: #5a5a5a; @@ -26,13 +27,13 @@ --t-bg: #efeff0; --t-surface: #f9f9fa; --t-surface-2: #ffffff; - --t-border-subtle: #dedee2; + --t-border-subtle: #e2e2e2; --t-border-strong: #c0c0c0; - --t-text: #2e2e2e; - --t-text-secondary: #383838; - --t-text-muted: #6d6d6d; - --t-scrollbar: rgba(46, 46, 46, 0.28); - --t-brand: #1f6fc4; + --t-text: #1b1b1b; + --t-text-secondary: #3b3b3d; + --t-text-muted: #5e5e60; + --t-scrollbar: rgba(27, 27, 27, 0.28); + --t-brand: #5e6ad2; --t-brand-ink: #ffffff; --t-field-bg: #e8e8e8; --t-field-dim: #c3c3c3; diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index d0deeb74..ba039be5 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -14,6 +14,10 @@ export default defineConfig({ ], // shadcn components import through "@/"; tsconfig.json declares the same alias. resolve: { alias: { "@": fileURLToPath(new URL("./src", import.meta.url)) } }, + // The repo root's .env.local supplies the Clerk publishable key and, in development, the relay URL. + // The prefixes admit only those public values, never CLERK_SECRET_KEY or any other secret. + envDir: fileURLToPath(new URL("../..", import.meta.url)), + envPrefix: ["VITE_", "CLERK_PUBLISHABLE_KEY", "CODEWORK_RELAY_URL"], // The diff highlighter's worker loads grammars on demand, which a classic worker bundle cannot split. worker: { format: "es" }, // Pinned so the desktop shell can proxy to a fixed address; `localhost` diff --git a/apps/widget/package.json b/apps/widget/package.json index 2b89a572..3d94e899 100644 --- a/apps/widget/package.json +++ b/apps/widget/package.json @@ -13,6 +13,9 @@ "scripts": { "typecheck": "tsc --noEmit" }, + "dependencies": { + "@codeworksh/schema": "workspace:*" + }, "devDependencies": { "@phosphor-icons/react": "2.1.10", "@types/react": "^19.3.0", diff --git a/apps/widget/src/codework.ts b/apps/widget/src/codework.ts index 4522d935..6e2c2e7e 100644 --- a/apps/widget/src/codework.ts +++ b/apps/widget/src/codework.ts @@ -1,3 +1,4 @@ +import { Machine } from "@codeworksh/schema"; import { Schema } from "effect"; import { Rpc, RpcGroup } from "effect/rpc"; @@ -798,6 +799,29 @@ export const Api = RpcGroup.make( success: Schema.Struct({ interrupted: Schema.Boolean }), error: ThreadError, }), + /** This machine and the workspaces it is connected to. */ + Rpc.make("machine.info", { + payload: {}, + success: Machine.Status, + }), + /** Names this machine for people; an empty name goes back to the OS's. */ + Rpc.make("machine.rename", { + payload: { givenName: Schema.String }, + success: Machine.Status, + }), + /** Leaves a workspace: the relay revokes this machine's link, and the machine forgets it. */ + Rpc.make("machine.disconnect", { + payload: Machine.Disconnect, + success: Machine.Disconnected, + error: Machine.ConnectError, + }), + /** Connects this machine to a workspace: the code a member approves, then the link once they have. */ + Rpc.make("machine.connect", { + payload: { workspaceId: Schema.optional(Schema.String) }, + success: Machine.ConnectEvent, + error: Machine.ConnectError, + stream: true, + }), /** The OS home directory, and the folder `host.create` makes projects in. */ Rpc.make("host.info", { payload: {}, diff --git a/infra/relay/compose.yaml b/infra/relay/compose.yaml new file mode 100644 index 00000000..bf42b5cb --- /dev/null +++ b/infra/relay/compose.yaml @@ -0,0 +1,20 @@ +# Local Postgres for development and the E2E tests. Production is managed Postgres behind Hyperdrive. +services: + postgres: + image: postgres:18 + environment: + POSTGRES_USER: relay + POSTGRES_PASSWORD: relay + POSTGRES_DB: relay + ports: + - "55432:5432" + volumes: + - relay-postgres:/var/lib/postgresql + healthcheck: + test: ["CMD-SHELL", "pg_isready -U relay -d relay"] + interval: 2s + timeout: 3s + retries: 15 + +volumes: + relay-postgres: diff --git a/infra/relay/package.json b/infra/relay/package.json new file mode 100644 index 00000000..3a3c1372 --- /dev/null +++ b/infra/relay/package.json @@ -0,0 +1,25 @@ +{ + "name": "@codeworksh/relay", + "version": "0.0.0", + "private": true, + "description": "The relay: the cloud API for accounts, workspaces and machines, at relay.codework.sh.", + "type": "module", + "scripts": { + "db": "docker compose up -d --wait", + "start": "node src/main.ts", + "test": "vp test", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@clerk/backend": "3.27.0", + "@codeworksh/schema": "workspace:*", + "@effect/platform-node": "4.0.5", + "@effect/sql-pg": "4.0.5", + "effect": "4.0.5" + }, + "devDependencies": { + "@types/node": "catalog:", + "typescript": "catalog:", + "vite-plus": "catalog:" + } +} diff --git a/infra/relay/src/accounts.ts b/infra/relay/src/accounts.ts new file mode 100644 index 00000000..bfb0a9a3 --- /dev/null +++ b/infra/relay/src/accounts.ts @@ -0,0 +1,101 @@ +import { Context, Effect, Layer } from "effect"; +import { SqlClient } from "effect/sql"; +import { Relay } from "@codeworksh/schema"; +import { Clerk } from "./clerk.ts"; + +/** People and the workspaces they belong to. */ +export class Accounts extends Context.Service< + Accounts, + { + /** The person's account and workspaces, creating the account and its default workspace on first sight. */ + readonly ensure: (authId: string) => Effect.Effect; + /** A new workspace the person owns. */ + readonly createWorkspace: (authId: string, name: string) => Effect.Effect; + } +>()("relay/Accounts") { + static readonly layer = Layer.effect( + Accounts, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const clerk = yield* Clerk; + + const find = (authId: string) => + sql<{ readonly id: string; readonly email: string; readonly name: string | null }>` + SELECT id, email, name FROM account WHERE auth_id = ${authId} + `.pipe(Effect.map((rows) => rows[0])); + + // Concurrent first calls both reach the insert; the unique auth_id makes the loser wait for the + // winner's commit and insert nothing, so exactly one default workspace is created. + const create = Effect.fn("Accounts.create")(function* (authId: string) { + const profile = yield* clerk.profile(authId); + const workspaceName = `${profile.firstName ?? profile.email.split("@")[0]}'s Workspace`; + yield* sql.withTransaction( + Effect.gen(function* () { + const created = yield* sql<{ readonly id: string; readonly createdBy: string }>` + WITH inserted AS ( + INSERT INTO account (auth_id, email, name) + VALUES (${authId}, ${profile.email}, ${profile.name}) + ON CONFLICT (auth_id) DO NOTHING + RETURNING id + ) + INSERT INTO workspace (name, created_by) + SELECT ${workspaceName}, id FROM inserted + RETURNING id, created_by + `; + for (const workspace of created) { + yield* sql` + INSERT INTO member (workspace_id, account_id, role) + VALUES (${workspace.id}, ${workspace.createdBy}, 'owner') + `; + } + }), + ); + }); + + const ensure = Effect.fn("Accounts.ensure")( + function* (authId: string) { + const account = (yield* find(authId)) ?? (yield* create(authId).pipe(Effect.andThen(find(authId)))); + if (account === undefined) return yield* Effect.die(new Error(`No account for ${authId}`)); + const workspaces = yield* sql<{ + readonly id: string; + readonly name: string; + readonly role: typeof Relay.Role.Type; + }>` + SELECT w.id, w.name, m.role + FROM member m JOIN workspace w ON w.id = m.workspace_id + WHERE m.account_id = ${account.id} + ORDER BY w.created_at, w.id + `; + return new Relay.Me({ + account: new Relay.Account(account), + workspaces: workspaces.map((row) => new Relay.Workspace(row)), + }); + }, + Effect.catchTag("SqlError", Effect.die), + ); + + return Accounts.of({ + ensure, + createWorkspace: Effect.fn("Accounts.createWorkspace")( + function* (authId, name) { + const { account } = yield* ensure(authId); + return yield* sql.withTransaction( + Effect.gen(function* () { + const [workspace] = yield* sql<{ readonly id: string }>` + INSERT INTO workspace (name, created_by) VALUES (${name}, ${account.id}) RETURNING id + `; + if (workspace === undefined) return yield* Effect.die(new Error("No workspace inserted")); + yield* sql` + INSERT INTO member (workspace_id, account_id, role) + VALUES (${workspace.id}, ${account.id}, 'owner') + `; + return new Relay.Workspace({ id: workspace.id, name, role: "owner" }); + }), + ); + }, + Effect.catchTag("SqlError", Effect.die), + ), + }); + }), + ); +} diff --git a/infra/relay/src/clerk.ts b/infra/relay/src/clerk.ts new file mode 100644 index 00000000..769773b5 --- /dev/null +++ b/infra/relay/src/clerk.ts @@ -0,0 +1,65 @@ +import { createClerkClient, verifyToken } from "@clerk/backend"; +import { TokenVerificationError, TokenVerificationErrorReason } from "@clerk/backend/errors"; +import { Config, Context, Effect, Layer, Option, Redacted } from "effect"; +import { Relay } from "@codeworksh/schema"; + +export interface Profile { + readonly email: string; + readonly firstName: string | null; + readonly name: string | null; +} + +/** The auth vendor, behind the two things the relay needs from it. */ +export class Clerk extends Context.Service< + Clerk, + { + /** The verified subject (`auth_id`) of a session token. */ + readonly verify: (token: string) => Effect.Effect; + readonly profile: (authId: string) => Effect.Effect; + } +>()("relay/Clerk") { + static readonly layer = Layer.effect( + Clerk, + Effect.gen(function* () { + const secretKey = Redacted.value(yield* Config.Redacted("CLERK_SECRET_KEY")); + // The vendor's API, overridable so the E2E suite can make it unreachable. + const apiUrl = Option.getOrUndefined(yield* Config.option(Config.String("CLERK_API_URL"))); + const client = createClerkClient({ secretKey, ...(apiUrl === undefined ? {} : { apiUrl }) }); + return Clerk.of({ + verify: Effect.fn("Clerk.verify")(function* (token) { + // The package's verifyToken resolves to the claims and rejects on any failure. A token it refuses + // (`token-*`: expired, forged, wrong audience) is the caller's fault; anything else, such as its + // keys failing to load, means the vendor is out of reach and the client should try again. + const claims: unknown = yield* Effect.tryPromise({ + try: () => verifyToken(token, { secretKey, ...(apiUrl === undefined ? {} : { apiUrl }) }), + catch: (cause) => + cause instanceof TokenVerificationError && + (cause.reason.startsWith("token-") || cause.reason === TokenVerificationErrorReason.JWKKidMismatch) + ? new Relay.Unauthorized({ message: "Invalid or expired session token" }) + : new Relay.Unavailable({ message: "CodeWork's sign-in service isn't responding" }), + }); + if ( + typeof claims !== "object" || + claims === null || + !("sub" in claims) || + typeof claims.sub !== "string" + ) { + return yield* new Relay.Unauthorized({ message: "Invalid or expired session token" }); + } + return claims.sub; + }), + profile: Effect.fn("Clerk.profile")(function* (authId) { + // Needed once, on a person's first sign-in: the vendor out of reach then is "try again". + const user = yield* Effect.tryPromise({ + try: () => client.users.getUser(authId), + catch: () => new Relay.Unavailable({ message: "CodeWork's sign-in service isn't responding" }), + }); + const email = user.primaryEmailAddress?.emailAddress; + if (email === undefined) + return yield* Effect.die(new Error(`Clerk user ${authId} has no email address`)); + return { email, firstName: user.firstName, name: user.fullName }; + }), + }); + }), + ); +} diff --git a/infra/relay/src/db.ts b/infra/relay/src/db.ts new file mode 100644 index 00000000..1098e3e9 --- /dev/null +++ b/infra/relay/src/db.ts @@ -0,0 +1,14 @@ +import { PgClient } from "@effect/sql-pg"; +import { Config, String as Str } from "effect"; +import { Migrator } from "effect/sql"; +import { migrations } from "./migrations.ts"; + +/** The relay's Postgres, from `DATABASE_URL`; camelCase fields map to snake_case columns. */ +export const layer = PgClient.layerConfig({ + url: Config.Redacted("DATABASE_URL"), + transformQueryNames: Config.succeed(Str.camelToSnake), + transformResultNames: Config.succeed(Str.snakeToCamel), +}); + +/** Applies pending migrations. The generic migrator needs only the client, not `pg_dump`. */ +export const migrate = Migrator.make({})({ loader: Migrator.fromRecord(migrations) }); diff --git a/infra/relay/src/http.ts b/infra/relay/src/http.ts new file mode 100644 index 00000000..98d7ca74 --- /dev/null +++ b/infra/relay/src/http.ts @@ -0,0 +1,110 @@ +import { Relay } from "@codeworksh/schema"; +import { Effect, Layer, Redacted } from "effect"; +import { HttpRouter } from "effect/http"; +import { HttpApiBuilder } from "effect/http-api"; +import { Accounts } from "./accounts.ts"; +import { Clerk } from "./clerk.ts"; +import { Machines } from "./machines.ts"; + +const PersonAuthLayer = Layer.effect( + Relay.PersonAuth, + Effect.gen(function* () { + const clerk = yield* Clerk; + return Relay.PersonAuth.of({ + bearer: Effect.fn("PersonAuth.bearer")(function* (httpEffect, { credential }) { + const authId = yield* clerk.verify(Redacted.value(credential)); + return yield* Effect.provideService(httpEffect, Relay.Person, { authId }); + }), + }); + }), +); + +const MeHandlers = HttpApiBuilder.group( + Relay.Api, + "me", + Effect.fn(function* (handlers) { + const accounts = yield* Accounts; + return handlers.handle("get", () => + Effect.gen(function* () { + return yield* accounts.ensure((yield* Relay.Person).authId); + }), + ); + }), +).pipe(Layer.provide(PersonAuthLayer)); + +const WorkspaceHandlers = HttpApiBuilder.group( + Relay.Api, + "workspace", + Effect.fn(function* (handlers) { + const machines = yield* Machines; + const accounts = yield* Accounts; + return handlers + .handle("create", ({ payload }) => + Effect.gen(function* () { + return yield* accounts.createWorkspace((yield* Relay.Person).authId, payload.name); + }), + ) + .handle("approve", ({ payload }) => + Effect.gen(function* () { + return yield* machines.approve((yield* Relay.Person).authId, payload.userCode, payload.workspaceId); + }), + ) + .handle("machines", ({ params }) => + Effect.gen(function* () { + return yield* machines.list((yield* Relay.Person).authId, params.workspaceId); + }), + ) + .handle("pairings", ({ params }) => + Effect.gen(function* () { + return yield* machines.pairings((yield* Relay.Person).authId, params.workspaceId); + }), + ) + .handle("decline", ({ payload }) => + Effect.gen(function* () { + return yield* machines.decline((yield* Relay.Person).authId, payload.userCode, payload.workspaceId); + }), + ) + .handle("remove", ({ params, payload }) => + Effect.gen(function* () { + return yield* machines.remove( + (yield* Relay.Person).authId, + params.workspaceId, + params.machineId, + payload.keyId, + ); + }), + ); + }), +).pipe(Layer.provide(PersonAuthLayer)); + +const MachineHandlers = HttpApiBuilder.group( + Relay.Api, + "machine", + Effect.fn(function* (handlers) { + const machines = yield* Machines; + return handlers + .handle("pair", ({ payload }) => machines.pair(payload.jws)) + .handle("poll", ({ payload }) => machines.poll(payload.jws)) + .handle("heartbeat", ({ payload }) => machines.heartbeat(payload.jws)) + .handle("revoke", ({ payload }) => machines.revoke(payload.jws)); + }), +); + +/** The desktop app's renderer origins: packaged, and an unpackaged run. */ +const desktopOrigins = ["codework://app", "codeworkdev://app"]; + +/** The relay's routes, independent of the runtime that serves them. Requires `SqlClient`. */ +export const routes = Layer.mergeAll( + HttpApiBuilder.layer(Relay.Api).pipe( + Layer.provide([MeHandlers, WorkspaceHandlers, MachineHandlers]), + Layer.provide(Machines.layer), + Layer.provideMerge(Accounts.layer), + Layer.provide(Clerk.layer), + ), + HttpRouter.cors({ + allowedOrigins: desktopOrigins, + allowedMethods: ["GET", "POST"], + // Effect's HTTP client also sends trace context with every request. + allowedHeaders: ["authorization", "content-type", "b3", "traceparent", "tracestate"], + }), +); diff --git a/infra/relay/src/machines.ts b/infra/relay/src/machines.ts new file mode 100644 index 00000000..68fae23a --- /dev/null +++ b/infra/relay/src/machines.ts @@ -0,0 +1,492 @@ +import { Jws, Relay } from "@codeworksh/schema"; +import { Clock, Context, Effect, Layer, Schema } from "effect"; +import { SqlClient } from "effect/sql"; +import { Accounts } from "./accounts.ts"; + +/** How far a signed request's `iat` may be from the relay's clock. */ +const freshness = 60_000; +/** How long a pairing code stays valid, and how often the machine may poll it. */ +const pairingSeconds = 600; +const pollSeconds = 5; +/** A pending connect stays listed and approvable while its machine polled this recently. */ +const waitingSeconds = 20; +/** After approval, how long the machine has to poll and take the link. */ +const claimSeconds = 120; +/** A machine is online while its last heartbeat is younger than this. */ +const leaseSeconds = 90; +/** Unambiguous letters for codes a person reads and types. */ +const alphabet = "BCDFGHJKLMNPQRSTVWXZ"; + +interface MachineRow { + readonly workspaceId: string; + readonly id: string; + readonly source: Relay.MachineInfo["source"]; + readonly localHostName: string; + readonly givenName: string | null; + readonly os: string; + readonly arch: string; + readonly version: string; + readonly ownerId: string; + readonly key: Jws.PublicKey; + readonly keyId: string; + readonly identityKeyId: string; + readonly online: boolean; + readonly lastSeenAt: Date | null; + readonly revokedAt: Date | null; +} + +interface PairingRow { + readonly id: string; + readonly workspaceId: string | null; + readonly machine: Relay.MachineInfo; + readonly key: Jws.PublicKey; + readonly keyId: string; + readonly identityKeyId: string; + readonly status: "pending" | "approved" | "active" | "declined" | "superseded"; + readonly approvedBy: string | null; + readonly connected: Relay.Connected | null; + readonly expired: boolean; +} + +const toMachine = (row: MachineRow) => + new Relay.Machine({ + workspaceId: row.workspaceId, + id: row.id, + source: row.source, + localHostName: row.localHostName, + givenName: row.givenName, + os: row.os, + arch: row.arch, + version: row.version, + keyId: row.keyId, + identityKeyId: row.identityKeyId, + ownerId: row.ownerId, + online: row.online, + lastSeenAt: row.lastSeenAt?.toISOString() ?? null, + }); + +const random = (size: number) => globalThis.crypto.getRandomValues(new Uint8Array(size)); +const userCode = () => { + const letters = Array.from(random(8), (byte) => alphabet[byte % alphabet.length]).join(""); + return `${letters.slice(0, 4)}-${letters.slice(4)}`; +}; +/** A code as people type it, in any case and with or without its dash or spaces, as stored. */ +const typed = (code: string) => { + const letters = code.toUpperCase().replace(/[^A-Z]/g, ""); + return letters.length === 8 ? `${letters.slice(0, 4)}-${letters.slice(4)}` : code.toUpperCase(); +}; + +const invalid = (message: string) => new Relay.Unauthorized({ message }); + +/** Pairings, machine links and their heartbeats. */ +export class Machines extends Context.Service< + Machines, + { + readonly pair: ( + jws: string, + ) => Effect.Effect; + readonly poll: (jws: string) => Effect.Effect; + readonly approve: ( + authId: string, + userCode: string, + workspaceId: string, + ) => Effect.Effect<{ readonly machine: Relay.MachineInfo }, Relay.NotFound | Relay.Forbidden | Relay.Unavailable>; + readonly list: ( + authId: string, + workspaceId: string, + ) => Effect.Effect, Relay.Forbidden | Relay.Unavailable>; + readonly pairings: ( + authId: string, + workspaceId: string, + ) => Effect.Effect, Relay.Forbidden | Relay.Unavailable>; + readonly decline: ( + authId: string, + userCode: string, + workspaceId: string, + ) => Effect.Effect; + readonly remove: ( + authId: string, + workspaceId: string, + machineId: string, + keyId: string, + ) => Effect.Effect; + readonly heartbeat: (jws: string) => Effect.Effect; + readonly revoke: (jws: string) => Effect.Effect; + } +>()("relay/Machines") { + static readonly layer = Layer.effect( + Machines, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const accounts = yield* Accounts; + + const fresh = Effect.fn(function* (iat: number) { + const now = yield* Clock.currentTimeMillis; + if (Math.abs(now - iat) > freshness) return yield* invalid("The request is too old or from the future"); + }); + + const role = (workspaceId: string, accountId: string) => + sql<{ readonly role: typeof Relay.Role.Type }>` + SELECT role FROM member WHERE workspace_id = ${workspaceId} AND account_id = ${accountId} + `.pipe(Effect.map((rows) => rows[0]?.role)); + + const member = Effect.fn(function* (authId: string, workspaceId: string) { + const account = (yield* accounts.ensure(authId)).account; + const memberRole = yield* role(workspaceId, account.id).pipe(Effect.orDie); + if (memberRole === undefined) { + return yield* new Relay.Forbidden({ message: "You are not a member of this workspace" }); + } + return { account, role: memberRole }; + }); + + const machineColumns = sql` + workspace_id, id, source, local_host_name, given_name, os, arch, version, owner_id, key, key_id, + identity_key_id, last_seen_at, revoked_at, coalesce(last_seen_at > now() - make_interval(secs => ${leaseSeconds}), false) AS online + `; + + // A machine request names its key by thumbprint; the key finds the one link it may act on. + const signed = Effect.fn("Machines.signed")(function* ( + jws: string, + claims: Schema.Decoder, + ) { + const header = yield* Jws.peek(jws).pipe(Effect.mapError(() => invalid("Malformed signed request"))); + if (header.kid === undefined) return yield* invalid("The request names no key"); + const [row] = yield* sql`SELECT ${machineColumns} FROM machine WHERE key_id = ${header.kid}`; + if (row === undefined) return yield* new Relay.MachineRevoked({ message: "This machine is not connected" }); + const decoded = yield* Jws.verify(jws, row.key).pipe( + Effect.flatMap(Schema.decodeUnknownEffect(claims)), + Effect.mapError(() => invalid("Invalid signed request")), + ); + yield* fresh(decoded.iat); + if (row.revokedAt !== null) + return yield* new Relay.MachineRevoked({ message: "This machine was disconnected" }); + if ((yield* role(row.workspaceId, row.ownerId)) === undefined) { + return yield* new Relay.MachineRevoked({ message: "The machine's owner left the workspace" }); + } + return { row, claims: decoded }; + }); + + // The home's identity key vouches for a pairing's link key: it signs the link key's thumbprint, so + // a copied public key proves nothing and a binding made for one link can't serve another. + const identity = Effect.fn("Machines.identity")(function* (binding: string, keyId: string) { + const header = yield* Jws.peek(binding).pipe(Effect.mapError(() => invalid("Malformed identity"))); + if (header.jwk === undefined) return yield* invalid("An identity embeds its key"); + const claims = yield* Jws.verify(binding, header.jwk).pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Relay.IdentityClaims)), + Effect.mapError(() => invalid("Invalid identity")), + ); + yield* fresh(claims.iat); + if (claims.keyId !== keyId) return yield* invalid("The identity vouches for another key"); + return yield* Jws.thumbprint(header.jwk).pipe(Effect.orDie); + }); + + const pairingColumns = sql` + id, workspace_id, machine, key, key_id, identity_key_id, approved_by, connected, expires_at < now() AS expired, + CASE WHEN status = 'active' AND NOT EXISTS ( + SELECT 1 FROM machine m WHERE m.key_id = pairing.key_id AND m.revoked_at IS NULL + ) THEN 'superseded' ELSE status END AS status + `; + + // The machine proved it holds the approved key: its link goes live under that key, replacing any + // link the machine had, and every other connect for the same machine and workspace is superseded. + const activate = (pairingId: string) => + sql.withTransaction( + Effect.gen(function* () { + const [pairing] = yield* sql` + SELECT ${pairingColumns} FROM pairing WHERE id = ${pairingId} FOR UPDATE + `; + if (pairing === undefined) return yield* Effect.die(new Error("Pairing vanished")); + if (pairing.status === "active" && pairing.connected !== null) return pairing.connected; + if (pairing.status !== "approved" || pairing.workspaceId === null || pairing.approvedBy === null) { + return undefined; + } + const workspaceId = pairing.workspaceId; + const info = pairing.machine; + // Replacing a live link keeps its owner; a new or revoked one belongs to the approver. + const [row] = yield* sql` + INSERT INTO machine ( + workspace_id, id, source, local_host_name, given_name, os, arch, version, owner_id, key, key_id, + identity_key_id + ) VALUES ( + ${workspaceId}, ${info.id}, ${info.source}, ${info.localHostName}, ${info.givenName}, + ${info.os}, ${info.arch}, ${info.version}, ${pairing.approvedBy}, + ${JSON.stringify(pairing.key)}::jsonb, ${pairing.keyId}, ${pairing.identityKeyId} + ) + ON CONFLICT (workspace_id, id) DO UPDATE SET + source = excluded.source, local_host_name = excluded.local_host_name, + given_name = excluded.given_name, os = excluded.os, arch = excluded.arch, + version = excluded.version, key = excluded.key, key_id = excluded.key_id, + identity_key_id = excluded.identity_key_id, + owner_id = CASE WHEN machine.revoked_at IS NULL THEN machine.owner_id ELSE excluded.owner_id END, + last_seen_at = NULL, revoked_at = NULL + RETURNING ${machineColumns} + `; + if (row === undefined) return yield* Effect.die(new Error("Machine upsert returned no row")); + const [workspace] = yield* sql<{ readonly name: string }>` + SELECT name FROM workspace WHERE id = ${workspaceId} + `; + const [owner] = yield* sql<{ readonly name: string | null }>` + SELECT name FROM account WHERE id = ${row.ownerId} + `; + const connected: Relay.Connected = { + machineId: row.id, + workspace: { id: workspaceId, name: workspace?.name ?? "" }, + owner: { id: row.ownerId, name: owner?.name ?? null }, + }; + yield* sql` + UPDATE pairing SET status = 'active', connected = ${JSON.stringify(connected)}::jsonb + WHERE id = ${pairing.id} + `; + yield* sql` + UPDATE pairing SET status = 'superseded' + WHERE workspace_id = ${workspaceId} AND machine->>'id' = ${info.id} AND id <> ${pairing.id} + AND status IN ('pending', 'approved') + `; + return connected; + }), + ); + + return Machines.of({ + pair: Effect.fn("Machines.pair")( + function* (jws) { + const header = yield* Jws.peek(jws).pipe(Effect.mapError(() => invalid("Malformed signed request"))); + if (header.jwk === undefined) return yield* invalid("A pairing request embeds its key"); + const claims = yield* Jws.verify(jws, header.jwk).pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Relay.PairingClaims)), + Effect.mapError(() => invalid("Invalid signed request")), + ); + yield* fresh(claims.iat); + const keyId = yield* Jws.thumbprint(header.jwk).pipe(Effect.orDie); + const identityKeyId = yield* identity(claims.identity, keyId); + // A key registers once: reused, it would answer for another connect or link. + const taken = yield* sql` + SELECT 1 FROM machine WHERE key_id = ${keyId} UNION ALL SELECT 1 FROM pairing WHERE key_id = ${keyId} + `; + if (taken.length > 0) return yield* invalid("This key is already registered"); + if (claims.workspaceId !== null) { + const workspace = yield* sql`SELECT 1 FROM workspace WHERE id = ${claims.workspaceId}`; + if (workspace.length === 0) return yield* new Relay.NotFound({ message: "No such workspace" }); + } + // Finished and abandoned connects are kept a day after their codes expire, then swept. + yield* sql`DELETE FROM pairing WHERE expires_at < now() - interval '1 day'`; + const code = userCode(); + yield* sql` + INSERT INTO pairing (user_code, workspace_id, machine, key, key_id, identity_key_id, status, expires_at) + VALUES ( + ${code}, ${claims.workspaceId}, ${JSON.stringify(claims.machine)}::jsonb, + ${JSON.stringify(header.jwk)}::jsonb, ${keyId}, ${identityKeyId}, 'pending', + now() + make_interval(secs => ${pairingSeconds}) + ) + `; + return { userCode: code, expiresIn: pairingSeconds, interval: pollSeconds }; + }, + Effect.catchTag("SqlError", Effect.die), + ), + + poll: Effect.fn("Machines.poll")( + function* (jws) { + const header = yield* Jws.peek(jws).pipe(Effect.mapError(() => invalid("Malformed signed request"))); + if (header.kid === undefined) return yield* invalid("The request names no key"); + const [pairing] = yield* sql` + SELECT ${pairingColumns} FROM pairing WHERE key_id = ${header.kid} + `; + if (pairing === undefined) return yield* new Relay.NotFound({ message: "Unknown pairing" }); + const claims = yield* Jws.verify(jws, pairing.key).pipe( + Effect.flatMap(Schema.decodeUnknownEffect(Relay.PollClaims)), + Effect.mapError(() => invalid("Invalid signed request")), + ); + yield* fresh(claims.iat); + switch (pairing.status) { + case "declined": + case "superseded": + return { status: pairing.status } as const; + case "active": + case "approved": { + const connected = + pairing.connected ?? (pairing.expired ? undefined : yield* activate(pairing.id)); + if (connected !== undefined) return { status: "approved", connected } as const; + // Superseded or expired while this poll waited for the row. + const [now] = yield* sql<{ readonly status: PairingRow["status"] }>` + SELECT status FROM pairing WHERE id = ${pairing.id} + `; + return { status: now?.status === "superseded" ? "superseded" : "expired" } as const; + } + case "pending": + if (pairing.expired) return { status: "expired" } as const; + yield* sql`UPDATE pairing SET seen_at = now() WHERE id = ${pairing.id}`; + return { status: "pending" } as const; + } + }, + Effect.catchTag("SqlError", Effect.die), + ), + + approve: Effect.fn("Machines.approve")(function* (authId, code, workspaceId) { + const approver = (yield* accounts.ensure(authId)).account; + return yield* sql + .withTransaction( + Effect.gen(function* () { + const [pairing] = yield* sql<{ + readonly id: string; + readonly workspaceId: string | null; + readonly machine: Relay.MachineInfo; + readonly waiting: boolean; + }>` + SELECT id, workspace_id, machine, + seen_at > now() - make_interval(secs => ${waitingSeconds}) AS waiting + FROM pairing + WHERE user_code = ${typed(code)} AND status = 'pending' AND expires_at > now() + FOR UPDATE + `; + if (pairing === undefined) + return yield* new Relay.NotFound({ message: "Unknown or expired code" }); + if (!pairing.waiting) { + return yield* new Relay.NotFound({ + message: "The machine stopped waiting; run connect on it again", + }); + } + if (pairing.workspaceId !== null && pairing.workspaceId !== workspaceId) { + return yield* new Relay.Forbidden({ + message: "This code was started for another workspace", + }); + } + const approverRole = yield* role(workspaceId, approver.id); + if (approverRole === undefined) { + return yield* new Relay.Forbidden({ message: "You are not a member of this workspace" }); + } + const [existing] = yield* sql<{ readonly ownerId: string }>` + SELECT owner_id FROM machine + WHERE workspace_id = ${workspaceId} AND id = ${pairing.machine.id} AND revoked_at IS NULL + `; + if (existing !== undefined && existing.ownerId !== approver.id && approverRole === "member") { + return yield* new Relay.Forbidden({ + message: "Only the machine's owner or a workspace admin can replace it", + }); + } + yield* sql` + UPDATE pairing SET status = 'approved', approved_by = ${approver.id}, workspace_id = ${workspaceId}, + expires_at = greatest(expires_at, now() + make_interval(secs => ${claimSeconds})) + WHERE id = ${pairing.id} + `; + return { machine: pairing.machine }; + }), + ) + .pipe(Effect.catchTag("SqlError", Effect.die)); + }), + + list: Effect.fn("Machines.list")(function* (authId, workspaceId) { + yield* member(authId, workspaceId); + const rows = yield* sql` + SELECT ${machineColumns} FROM machine + WHERE workspace_id = ${workspaceId} AND revoked_at IS NULL + ORDER BY created_at, id + `.pipe(Effect.orDie); + return rows.map(toMachine); + }), + + // Only connects started for this workspace are listed: one started without a workspace is + // claimed by whoever types its code, so it is never shown to a workspace. A connect whose machine + // stopped polling is gone from the list. + pairings: Effect.fn("Machines.pairings")(function* (authId, workspaceId) { + yield* member(authId, workspaceId); + const rows = yield* sql<{ + readonly userCode: string; + readonly machine: Relay.MachineInfo; + readonly status: "pending" | "approved"; + readonly replaces: boolean; + readonly createdAt: Date; + readonly expiresAt: Date; + }>` + SELECT p.user_code, p.machine, p.status, p.created_at, p.expires_at, + EXISTS ( + SELECT 1 FROM machine m + WHERE m.workspace_id = p.workspace_id AND m.id = p.machine->>'id' AND m.revoked_at IS NULL + ) AS replaces + FROM pairing p + WHERE p.workspace_id = ${workspaceId} AND p.status IN ('pending', 'approved') + AND p.expires_at > now() AND p.seen_at > now() - make_interval(secs => ${waitingSeconds}) + ORDER BY p.created_at, p.id + `.pipe(Effect.orDie); + return rows.map( + (row) => + new Relay.PendingPairing({ + userCode: row.userCode, + machine: row.machine, + status: row.status, + replaces: row.replaces, + createdAt: row.createdAt.toISOString(), + expiresAt: row.expiresAt.toISOString(), + }), + ); + }), + + decline: Effect.fn("Machines.decline")(function* (authId, code, workspaceId) { + yield* member(authId, workspaceId); + const declined = yield* sql<{ readonly id: string }>` + UPDATE pairing SET status = 'declined' + WHERE user_code = ${typed(code)} AND workspace_id = ${workspaceId} + AND status = 'pending' AND expires_at > now() + RETURNING id + `.pipe(Effect.orDie); + if (declined.length === 0) return yield* new Relay.NotFound({ message: "Unknown or expired code" }); + }), + + remove: Effect.fn("Machines.remove")(function* (authId, workspaceId, machineId, keyId) { + const { account, role: memberRole } = yield* member(authId, workspaceId); + const [machine] = yield* sql<{ readonly ownerId: string }>` + SELECT owner_id FROM machine + WHERE workspace_id = ${workspaceId} AND id = ${machineId} AND key_id = ${keyId} AND revoked_at IS NULL + `.pipe(Effect.orDie); + if (machine === undefined) + return yield* new Relay.NotFound({ message: "No such machine in this workspace" }); + if (machine.ownerId !== account.id && memberRole === "member") { + return yield* new Relay.Forbidden({ + message: "Only the machine's owner or a workspace admin can remove it", + }); + } + const removed = yield* sql` + UPDATE machine SET revoked_at = now() + WHERE workspace_id = ${workspaceId} AND id = ${machineId} AND key_id = ${keyId} AND revoked_at IS NULL + RETURNING id + `.pipe(Effect.orDie); + if (removed.length === 0) + return yield* new Relay.NotFound({ message: "This machine link is no longer active" }); + }), + + heartbeat: Effect.fn("Machines.heartbeat")( + function* (jws) { + const { row, claims } = yield* signed(jws, Relay.HeartbeatClaims); + if (claims.workspaceId !== row.workspaceId || claims.machine.id !== row.id) { + return yield* invalid("The request names another machine"); + } + const info = claims.machine; + yield* sql` + UPDATE machine SET last_seen_at = now(), local_host_name = ${info.localHostName}, + given_name = ${info.givenName}, os = ${info.os}, arch = ${info.arch}, version = ${info.version} + WHERE key_id = ${row.keyId} + `; + }, + Effect.catchTag("SqlError", Effect.die), + ), + + revoke: Effect.fn("Machines.revoke")( + function* (jws) { + const { row, claims } = yield* signed(jws, Relay.RevokeClaims); + if (claims.workspaceId !== row.workspaceId || claims.machineId !== row.id) { + return yield* invalid("The request names another machine"); + } + // A jti is kept for twice the freshness window: past that, its iat already refuses a replay. + yield* sql`DELETE FROM assertion WHERE expires_at < now()`; + const accepted = yield* sql` + INSERT INTO assertion (jti, expires_at) + VALUES (${claims.jti}, now() + make_interval(secs => ${(2 * freshness) / 1000})) + ON CONFLICT (jti) DO NOTHING RETURNING jti + `; + if (accepted.length === 0) return yield* invalid("This request was already used"); + yield* sql`UPDATE machine SET revoked_at = now() WHERE key_id = ${row.keyId}`; + }, + Effect.catchTag("SqlError", Effect.die), + ), + }); + }), + ); +} diff --git a/infra/relay/src/main.ts b/infra/relay/src/main.ts new file mode 100644 index 00000000..748f75d5 --- /dev/null +++ b/infra/relay/src/main.ts @@ -0,0 +1,24 @@ +/* @effect-diagnostics nodeBuiltinImport:off -- the Node entry serves the relay locally. */ +import { NodeHttpServer, NodeRuntime } from "@effect/platform-node"; +import { Config, Effect, Layer } from "effect"; +import { HttpRouter } from "effect/http"; +import { createServer } from "node:http"; +import * as Db from "./db.ts"; +import { routes } from "./http.ts"; + +// The relay on Node, for development and the E2E suite: migrates, then serves on PORT (0 picks a free +// port) and logs the address it bound. +const server = Layer.unwrap( + Effect.gen(function* () { + // Int, not Port: Port rejects 0. + const port = yield* Config.Int("PORT").pipe(Config.withDefault(8787)); + return NodeHttpServer.layer(createServer, { host: "127.0.0.1", port }); + }), +); + +const app = HttpRouter.serve(routes).pipe( + Layer.provide(server), + Layer.provide(Layer.effectDiscard(Db.migrate).pipe(Layer.provideMerge(Db.layer))), +); + +Layer.launch(app).pipe(NodeRuntime.runMain); diff --git a/infra/relay/src/migrations.ts b/infra/relay/src/migrations.ts new file mode 100644 index 00000000..064f1a96 --- /dev/null +++ b/infra/relay/src/migrations.ts @@ -0,0 +1,97 @@ +import { Effect } from "effect"; +import { SqlClient } from "effect/sql"; + +// Migrations ship as code (Migrator.fromRecord), keyed "YYYYMMDD<2-digit counter>_(probe: () => Promise, timeout = 20_000): Promise => { + const deadline = Date.now() + timeout; + while (Date.now() < deadline) { + const value = await probe(); + if (value !== undefined) return value; + await new Promise((resolve) => setTimeout(resolve, 500)); + } + throw new Error("timed out"); +}; + +const machineFile = () => JSON.parse(readFileSync(join(home, "machine.json"), "utf8")); + +describe.skipIf(secretKey === undefined)("codework connect", () => { + beforeAll(async () => { + relay = await startRelay(run); + user = await clerkUser(run); + }); + + afterAll(async () => { + for (const child of children) child.kill("SIGKILL"); + await user?.remove(); + relay?.stop(); + rmSync(home, { recursive: true, force: true }); + }); + + it("pairs, heartbeats and disconnects a machine", async () => { + const me = decodeMe(await (await asPerson("/v1/me")).json()); + const workspace = me.workspaces[0]!; + + // Connect: the CLI registers its key and shows a code; a member approves it. + const connect = codework(["connect", "--workspace", workspace.id, "--machine-id", "e2e-box"]); + const connectDone = finished(connect); + const code = await waitForLine(connect, (line) => /code ([A-Z]{4}-[A-Z]{4})/.exec(line)?.[1]); + const approve = await asPerson("/v1/pairings/approve", { + method: "POST", + body: JSON.stringify({ userCode: code, workspaceId: workspace.id }), + }); + const approved = decodeApproved(await approve.json()).machine; + const connected = await connectDone; + const reused = await asPerson("/v1/pairings/approve", { + method: "POST", + body: JSON.stringify({ userCode: code, workspaceId: workspace.id }), + }); + + const file = machineFile(); + const link = file.workspaces[workspace.id]; + const beforeServe = await machines(workspace.id); + + // Serve: its first heartbeat marks the machine online. + const serve = codework(["serve", "--port", "0"]); + const online = await until(async () => (await machines(workspace.id)).find((machine) => machine.online)); + serve.kill("SIGTERM"); + + // A forged heartbeat (wrong key for this kid) is refused. + const forged = await fetch(`${relay.base}/v1/machines/heartbeat`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + jws: `${btoa(JSON.stringify({ alg: "EdDSA", kid: link.keyId })).replace(/=+$/, "")}.e30.AAAA`, + }), + }); + + // Disconnect: the relay revokes the link and the home forgets it. + const disconnected = await finished(codework(["disconnect"])); + const afterDisconnect = await machines(workspace.id); + + const artifact = { + connect: { + exitCode: connected.code, + output: connected.out.replace(code, "").replaceAll(home, ""), + approveStatus: approve.status, + approved: { id: approved.id, source: approved.source }, + reusedCode: { status: reused.status, tag: decodeError(await reused.json())._tag }, + }, + machineFile: { + id: file.id, + source: file.source, + mode: (statSync(join(home, "machine.json")).mode & 0o777).toString(8), + workspaces: Object.keys(file.workspaces).map((id) => (id === workspace.id ? "" : id)), + link: { + name: link.name, + ownerName: link.owner.name, + relay: link.relay === relay.base ? "" : link.relay, + keyKty: link.key.kty, + keyCrv: link.key.crv, + }, + }, + machinesBeforeServe: beforeServe.map((machine) => ({ + id: machine.id, + online: machine.online, + ownerIsApprover: machine.ownerId === me.account.id, + keyIsLinkKey: machine.keyId === link.keyId, + })), + online: { id: online.id, online: online.online, version: online.version.length > 0 }, + forgedHeartbeat: { status: forged.status, tag: decodeError(await forged.json())._tag }, + disconnect: { + exitCode: disconnected.code, + output: disconnected.out, + machineFileWorkspaces: Object.keys(machineFile().workspaces), + machinesAfter: afterDisconnect.length, + revokedRows: Number(relay.psql("SELECT count(*) FROM machine WHERE revoked_at IS NOT NULL")), + }, + }; + await expect(`${JSON.stringify(artifact, null, "\t")}\n`).toMatchFileSnapshot("./__artifacts__/connect.json"); + }); + + it("declines a connect, accepts a code typed without its dash, and removes a machine", async () => { + const me = decodeMe(await (await asPerson("/v1/me")).json()); + const workspace = me.workspaces[0]!; + const pending = async () => + Schema.decodeUnknownSync(Schema.Array(Relay.PendingPairing))( + await (await asPerson(`/v1/workspaces/${workspace.id}/pairings`)).json(), + ); + + // A connect that names the workspace waits in its list; declining it stops the CLI with "declined". + const asked = codework(["connect", "--workspace", workspace.id], { stderr: true }); + const askedDone = finished(asked); + const askedCode = await waitForLine(asked, (line) => /code ([A-Z]{4}-[A-Z]{4})/.exec(line)?.[1]); + const listed = await pending(); + const decline = await asPerson("/v1/pairings/decline", { + method: "POST", + body: JSON.stringify({ userCode: askedCode, workspaceId: workspace.id }), + }); + const declined = await askedDone; + const afterDecline = await pending(); + + // The code as a person may type it: lower case, no dash. + const connect = codework(["connect", "--workspace", workspace.id]); + const connectDone = finished(connect); + const code = await waitForLine(connect, (line) => /code ([A-Z]{4}-[A-Z]{4})/.exec(line)?.[1]); + const approve = await asPerson("/v1/pairings/approve", { + method: "POST", + body: JSON.stringify({ userCode: code.replace("-", "").toLowerCase(), workspaceId: workspace.id }), + }); + const connected = await connectDone; + + // Removed while its server is down, the machine forgets the link on its first heartbeat back. + const { keyId, key } = machineFile().workspaces[workspace.id]; + const removeLink = (expectedKey: string) => + asPerson(`/v1/workspaces/${workspace.id}/machines/e2e-box/remove`, { + method: "POST", + body: JSON.stringify({ keyId: expectedKey }), + }); + const staleRemove = await removeLink("previous-key"); + expect(staleRemove.status).toBe(404); + const remove = await removeLink(keyId); + const poll = await Effect.runPromise(Jws.sign({ op: "pairing.poll", iat: Date.now() }, key, { kid: keyId })); + const retried = await fetch(`${relay.base}/v1/pairings/poll`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ jws: poll }), + }); + const pollResult = Schema.decodeUnknownSync(Relay.PairingStatus)(await retried.json()); + expect(pollResult.status).toBe("superseded"); + const afterRemove = await machines(workspace.id); + const serve = codework(["serve", "--port", "0"]); + const forgotten = await until(async () => + Object.keys(machineFile().workspaces).length === 0 ? true : undefined, + ); + serve.kill("SIGTERM"); + const removedAgain = await removeLink(keyId); + + // Ids that aren't a workspace's fail plainly: before any request, at the relay, and at the wire. + const badWorkspace = await finished(codework(["connect", "--workspace", "typo-123"], { stderr: true })); + const unknownWorkspace = await finished( + codework(["connect", "--workspace", "01a1ead7-0000-7000-8000-000000000000"], { stderr: true }), + ); + const badParam = await asPerson("/v1/workspaces/typo/machines"); + + const artifact = { + decline: { + listed: listed.map((pairing) => ({ + code: pairing.userCode === askedCode ? "" : pairing.userCode, + machine: pairing.machine.id, + status: pairing.status, + replaces: pairing.replaces, + })), + status: decline.status, + exitCode: declined.code, + error: declined.err.trim(), + pendingAfter: afterDecline.length, + }, + typedCode: { + status: approve.status, + exitCode: connected.code, + output: connected.out.replace(code, "").replaceAll(home, ""), + }, + remove: { + status: remove.status, + staleKey: staleRemove.status, + pollAfterRemove: pollResult.status, + machinesAfter: afterRemove.length, + machineFileForgot: forgotten, + again: { status: removedAgain.status, tag: decodeError(await removedAgain.json())._tag }, + }, + badWorkspace: { exitCode: badWorkspace.code, error: badWorkspace.err.trim() }, + unknownWorkspace: { exitCode: unknownWorkspace.code, error: unknownWorkspace.err.trim() }, + badParam: { status: badParam.status }, + }; + await expect(`${JSON.stringify(artifact, null, "\t")}\n`).toMatchFileSnapshot("./__artifacts__/manage.json"); + }); + + it("never links an abandoned connect, and lets one of two competing connects win", async () => { + const me = decodeMe(await (await asPerson("/v1/me")).json()); + const workspace = me.workspaces[0]!; + const approve = (userCode: string) => + asPerson("/v1/pairings/approve", { + method: "POST", + body: JSON.stringify({ userCode, workspaceId: workspace.id }), + }); + const started = async () => { + const child = codework(["connect", "--workspace", workspace.id], { stderr: true }); + const done = finished(child); + const code = await waitForLine(child, (line) => /code ([A-Z]{4}-[A-Z]{4})/.exec(line)?.[1]); + return { child, done, code }; + }; + + // A connect killed while its code is pending, approved anyway before its lease lapses: nobody holds + // its key, so it never links. A second connect approved after it links and supersedes it. + const abandoned = await started(); + abandoned.child.kill("SIGKILL"); + const raceApprove = await approve(abandoned.code); + const kept = await started(); + await approve(kept.code); + const keptDone = await kept.done; + const serve = codework(["serve", "--port", "0"]); + const online = await until(async () => (await machines(workspace.id)).find((machine) => machine.online)); + serve.kill("SIGTERM"); + const link = machineFile().workspaces[workspace.id]; + + // A connect that stops polling drops out of Waiting to Join and its code can't be approved. + const stale = await started(); + stale.child.kill("SIGKILL"); + const listed = Schema.decodeUnknownSync(Schema.Array(Relay.PendingPairing)); + await until(async () => { + const list = listed(await (await asPerson(`/v1/workspaces/${workspace.id}/pairings`)).json()); + return list.some((pairing) => pairing.userCode === stale.code) ? undefined : true; + }, 40_000); + const staleApprove = await approve(stale.code); + + // Two live connects for one machine, both approved: the first to poll links, the other is told. + const [first, second] = await Promise.all([started(), started()]); + await Promise.all([approve(first.code), approve(second.code)]); + const outcomes = (await Promise.all([first.done, second.done])) + .map((result) => ({ exitCode: result.code, error: result.err.trim() })) + .sort((a, b) => (a.exitCode ?? 0) - (b.exitCode ?? 0)); + + const artifact = { + kept: { exitCode: keptDone.code }, + raceApprove: { status: raceApprove.status }, + afterRace: { + online: online.online, + relayKeyIsLocalKey: online.keyId === link.keyId, + machineFileWorkspaces: Object.keys(machineFile().workspaces).length, + }, + stale: { status: staleApprove.status, error: decodeError(await staleApprove.json())._tag }, + competing: outcomes, + }; + await expect(`${JSON.stringify(artifact, null, "\t")}\n`).toMatchFileSnapshot("./__artifacts__/abandon.json"); + }, 150_000); + + it("keeps links made with one relay when the CLI is pointed at another", async () => { + const workspace = decodeMe(await (await asPerson("/v1/me")).json()).workspaces[0]!; + const other = await startRelay(`${run}b`); + try { + // The machine is linked (previous case); its server now runs with new connects aimed elsewhere. + const before = Object.keys(machineFile().workspaces); + const seen = () => + relay.psql( + `SELECT coalesce(max(last_seen_at)::text, '') FROM machine WHERE workspace_id = '${workspace.id}'`, + ); + const seenBefore = seen(); + const serve = codework(["serve", "--port", "0"], { relayUrl: other.base }); + const beat = await until(async () => (seen() > seenBefore ? true : undefined)); + await new Promise((resolve) => setTimeout(resolve, 2_000)); + serve.kill("SIGTERM"); + const artifact = { + linkedBefore: before.length, + heartbeatReachedItsRelay: beat, + linkedAfter: Object.keys(machineFile().workspaces).length, + machinesOnOtherRelay: Number(other.psql("SELECT count(*) FROM machine")), + }; + await expect(`${JSON.stringify(artifact, null, "\t")}\n`).toMatchFileSnapshot("./__artifacts__/relays.json"); + } finally { + other.stop(); + } + }); + it("forgets the local link when a committed revoke loses its reply", async () => { + const workspace = decodeMe(await (await asPerson("/v1/me")).json()).workspaces[0]!; + let revokeStatus: number | undefined; + const gateway = createServer((incoming, outgoing) => { + const upstream = request( + new URL(incoming.url ?? "/", relay.base), + { + method: incoming.method, + headers: incoming.headers, + }, + (response) => { + if (incoming.url === "/v1/machines/revoke") { + revokeStatus = response.statusCode; + response.resume(); + return; + } + outgoing.writeHead(response.statusCode ?? 502, response.headers); + response.pipe(outgoing); + }, + ); + upstream.on("error", () => outgoing.destroy()); + incoming.pipe(upstream); + }); + await new Promise((ready) => gateway.listen(0, "127.0.0.1", ready)); + try { + const connect = codework(["connect", "--workspace", workspace.id], { + relayUrl: `http://127.0.0.1:${(gateway.address() as AddressInfo).port}`, + }); + const done = finished(connect); + const userCode = await waitForLine(connect, (line) => /code ([A-Z]{4}-[A-Z]{4})/.exec(line)?.[1]); + expect( + ( + await asPerson("/v1/pairings/approve", { + method: "POST", + body: JSON.stringify({ userCode, workspaceId: workspace.id }), + }) + ).status, + ).toBe(200); + expect((await done).code).toBe(0); + const result = await finished(codework(["disconnect", "--workspace", workspace.id])); + const artifact = { + revokeStatus, + exitCode: result.code, + localLinkRemoved: machineFile().workspaces[workspace.id] === undefined, + relayLinkRemoved: (await machines(workspace.id)).length === 0, + }; + expect(artifact).toEqual({ revokeStatus: 204, exitCode: 0, localLinkRemoved: true, relayLinkRemoved: true }); + await expect(`${JSON.stringify(artifact, null, "\t")}\n`).toMatchFileSnapshot( + "./__artifacts__/disconnect.json", + ); + } finally { + gateway.close(); + gateway.closeAllConnections(); + } + }, 30_000); + + it("binds every link of a home to one identity, and refuses a binding made for another key", async () => { + const first = decodeMe(await (await asPerson("/v1/me")).json()).workspaces[0]!; + const created = await asPerson("/v1/workspaces", { method: "POST", body: JSON.stringify({ name: "Second" }) }); + const second = Schema.decodeUnknownSync(Relay.Workspace)(await created.json()); + const link = async (workspaceId: string) => { + const connect = codework(["connect", "--workspace", workspaceId]); + const done = finished(connect); + const userCode = await waitForLine(connect, (line) => /code ([A-Z]{4}-[A-Z]{4})/.exec(line)?.[1]); + const approve = await asPerson("/v1/pairings/approve", { + method: "POST", + body: JSON.stringify({ userCode, workspaceId }), + }); + expect(approve.status).toBe(200); + expect((await done).code).toBe(0); + }; + + // One home, two workspaces: two link keys, one identity behind both. + await link(first.id); + await link(second.id); + const file = machineFile(); + const [inFirst] = await machines(first.id); + const [inSecond] = await machines(second.id); + + // Even the home's real identity key can't vouch for a link key its binding doesn't name. + const forger: Relay.MachineInfo = { + id: "e2e-forger", + source: "flag", + localHostName: "forger", + givenName: null, + os: "linux", + arch: "arm64", + version: "0.0.0", + }; + const pair = async (identity: (keyId: string) => Promise) => { + const key = await Effect.runPromise(Jws.generate()); + const keyId = await Effect.runPromise(Jws.thumbprint(Jws.publicOf(key))); + const claims: Relay.PairingClaims = { + op: "pairing.create", + iat: Date.now(), + machine: forger, + workspaceId: first.id, + identity: await identity(keyId), + }; + const response = await fetch(`${relay.base}/v1/pairings`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ jws: await Effect.runPromise(Jws.sign(claims, key, { embed: true })) }), + }); + const body = Schema.decodeUnknownSync(Schema.Struct({ _tag: Schema.String, message: Schema.String }))( + await response.json(), + ); + return { status: response.status, tag: body._tag, message: body.message }; + }; + const bindingFor = (keyId: string) => + Effect.runPromise( + Jws.sign({ op: "identity.bind", iat: Date.now(), keyId }, file.identity.key, { embed: true }), + ); + const replayed = await pair(async () => bindingFor(inFirst!.keyId)); + const malformed = await pair(async () => "not-a-jws"); + + const artifact = { + machineFile: { + identityKty: file.identity.key.kty, + identityCrv: file.identity.key.crv, + identityIsALinkKey: Object.values<{ keyId: string }>(file.workspaces).some( + (entry) => entry.keyId === file.identity.keyId, + ), + }, + links: [inFirst!, inSecond!].map((machine) => ({ + id: machine.id, + workspace: machine.workspaceId === first.id ? "" : "", + identityIsHomeIdentity: machine.identityKeyId === file.identity.keyId, + })), + linkKeysDiffer: inFirst!.keyId !== inSecond!.keyId, + replayedBinding: replayed, + malformedBinding: malformed, + forgedPairings: Number(relay.psql("SELECT count(*) FROM pairing WHERE machine->>'id' = 'e2e-forger'")), + }; + await expect(`${JSON.stringify(artifact, null, "\t")}\n`).toMatchFileSnapshot("./__artifacts__/identity.json"); + }, 60_000); +}); diff --git a/infra/relay/test/me.test.ts b/infra/relay/test/me.test.ts new file mode 100644 index 00000000..60d169a0 --- /dev/null +++ b/infra/relay/test/me.test.ts @@ -0,0 +1,116 @@ +import { Relay } from "@codeworksh/schema"; +import { Schema } from "effect"; +import { generateKeyPairSync } from "node:crypto"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { afterAll, beforeAll, describe, expect, it } from "vite-plus/test"; +import { clerkUser, newRun, secretKey, startRelay } from "./utils.ts"; + +const run = newRun(); +const decodeMe = Schema.decodeUnknownSync(Relay.Me); +const decodeError = Schema.decodeUnknownSync(Schema.Struct({ _tag: Schema.String })); + +let relay: Awaited>; +let user: Awaited>; + +const me = (bearer?: string) => + fetch(`${relay.base}/v1/me`, bearer === undefined ? {} : { headers: { authorization: `Bearer ${bearer}` } }); + +describe.skipIf(secretKey === undefined)("relay /v1/me", () => { + beforeAll(async () => { + relay = await startRelay(run); + user = await clerkUser(run); + }); + + afterAll(async () => { + await user?.remove(); + relay?.stop(); + }); + + it("refuses a session signed by a key the vendor no longer lists", async () => { + const { publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 }); + const keys = [{ ...publicKey.export({ format: "jwk" }), kid: "replacement", alg: "RS256" }]; + const vendor = createServer((_request, response) => { + response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ keys })); + }); + await new Promise((ready) => vendor.listen(0, "127.0.0.1", ready)); + try { + const rotated = await startRelay(`${run}r`, { + CLERK_API_URL: `http://127.0.0.1:${(vendor.address() as AddressInfo).port}`, + }); + try { + const response = await fetch(`${rotated.base}/v1/me`, { + headers: { authorization: `Bearer ${await user.token()}` }, + }); + const result = { status: response.status, tag: decodeError(await response.json())._tag }; + expect(result).toEqual({ status: 401, tag: "Relay.Unauthorized" }); + await expect(`${JSON.stringify(result, null, "\t")}\n`).toMatchFileSnapshot("./__artifacts__/rotated.json"); + } finally { + rotated.stop(); + } + } finally { + vendor.close(); + } + }); + + it("creates one account and default workspace, even for concurrent first calls", async () => { + const missing = await me(); + const forged = await me("not-a-token"); + + const token = await user.token(); + const [first, second] = await Promise.all([me(token), me(token)]); + const again = await me(token); + const bodies = (await Promise.all([first.json(), second.json(), again.json()])).map((json) => decodeMe(json)); + + expect([first.status, second.status, again.status]).toEqual([200, 200, 200]); + expect(bodies[1]).toEqual(bodies[0]); + expect(bodies[2]).toEqual(bodies[0]); + + const body = bodies[0]!; + + // A person who deletes their sign-in and signs up again with the same email is a new account. + await user.remove(); + user = await clerkUser(run); + const resignup = await me(await user.token()); + const resignupBody = resignup.status === 200 ? decodeMe(await resignup.json()) : undefined; + + // With the sign-in vendor out of reach a good token is "try again" (503), not "signed out" (401). + const down = await startRelay(`${run}d`, { CLERK_API_URL: "http://127.0.0.1:9" }); + const vendorDown = await fetch(`${down.base}/v1/me`, { + headers: { authorization: `Bearer ${await user.token()}` }, + }); + const vendorDownForged = await fetch(`${down.base}/v1/me`, { headers: { authorization: "Bearer not-a-token" } }); + const vendorDownBodies = [await vendorDown.json(), await vendorDownForged.json()].map((body) => + decodeError(body), + ); + down.stop(); + + const artifact = { + missingToken: { status: missing.status, tag: decodeError(await missing.json())._tag }, + forgedToken: { status: forged.status, tag: decodeError(await forged.json())._tag }, + me: { + account: { id: "", email: body.account.email.replace(run, ""), name: body.account.name }, + workspaces: body.workspaces.map((workspace, index) => ({ + id: ``, + name: workspace.name, + role: workspace.role, + })), + }, + resignup: { + status: resignup.status, + differentAccount: resignupBody !== undefined && resignupBody.account.id !== body.account.id, + sameEmail: resignupBody?.account.email === body.account.email, + }, + vendorDown: { + token: { status: vendorDown.status, tag: vendorDownBodies[0]!._tag }, + forgedToken: { status: vendorDownForged.status, tag: vendorDownBodies[1]!._tag }, + }, + rows: { + account: Number(relay.psql("SELECT count(*) FROM account")), + workspace: Number(relay.psql("SELECT count(*) FROM workspace")), + member: Number(relay.psql("SELECT count(*) FROM member")), + }, + }; + await expect(`${JSON.stringify(artifact, null, "\t")}\n`).toMatchFileSnapshot("./__artifacts__/me.json"); + }); +}); diff --git a/infra/relay/test/utils.ts b/infra/relay/test/utils.ts new file mode 100644 index 00000000..d53927e9 --- /dev/null +++ b/infra/relay/test/utils.ts @@ -0,0 +1,76 @@ +/* @effect-diagnostics nodeBuiltinImport:off -- the suites spawn the real relay against Docker Postgres. */ +import { createClerkClient } from "@clerk/backend"; +import { type ChildProcess, execFileSync, spawn } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { existsSync } from "node:fs"; +import { createInterface } from "node:readline"; +import { fileURLToPath } from "node:url"; + +export const root = fileURLToPath(new URL("..", import.meta.url)); +const envPath = fileURLToPath(new URL("../../../.env.local", import.meta.url)); +if (existsSync(envPath)) process.loadEnvFile(envPath); +export const secretKey = process.env.CLERK_SECRET_KEY; + +const compose = (args: ReadonlyArray) => + execFileSync("docker", ["compose", ...args], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); + +/** Resolves with the first stdout line `match` accepts; rejects if the process exits first. */ +export const waitForLine = (child: ChildProcess, match: (line: string) => string | undefined) => + new Promise((resolve, reject) => { + child.once("exit", (code) => reject(new Error(`process exited with ${code} before the expected output`))); + createInterface({ input: child.stdout! }).on("line", (line) => { + const found = match(line); + if (found !== undefined) resolve(found); + }); + }); + +/** A relay on a fresh database of the compose Postgres, at a free port; `env` adds to its environment. */ +export const startRelay = async (run: string, env: Record = {}) => { + const database = `relay_e2e_${run}`; + compose(["up", "-d", "--wait"]); + compose(["exec", "-T", "postgres", "psql", "-U", "relay", "-d", "relay", "-c", `CREATE DATABASE ${database}`]); + const server = spawn(process.execPath, ["src/main.ts"], { + cwd: root, + env: { ...process.env, ...env, PORT: "0", DATABASE_URL: `postgres://relay:relay@127.0.0.1:55432/${database}` }, + stdio: ["ignore", "pipe", "inherit"], + }); + const base = await waitForLine(server, (line) => /http:\/\/[\d.]+:\d+/.exec(line)?.[0]); + return { + base, + psql: (query: string) => + compose(["exec", "-T", "postgres", "psql", "-U", "relay", "-d", database, "-tAc", query]).trim(), + stop: () => { + server.kill("SIGKILL"); + compose([ + "exec", + "-T", + "postgres", + "psql", + "-U", + "relay", + "-d", + "relay", + "-c", + `DROP DATABASE IF EXISTS ${database} WITH (FORCE)`, + ]); + }, + }; +}; + +/** A Clerk test user with a session; session tokens live a minute, so each call mints a fresh one. */ +export const clerkUser = async (run: string) => { + const clerk = createClerkClient({ secretKey: secretKey ?? "" }); + const user = await clerk.users.createUser({ + emailAddress: [`relay-e2e-${run}+clerk_test@example.com`], + firstName: "Ada", + lastName: "Lovelace", + password: `Relay-e2e-${randomBytes(12).toString("hex")}`, + }); + const session = await clerk.sessions.createSession({ userId: user.id }); + return { + token: async () => (await clerk.sessions.getToken(session.id)).jwt, + remove: () => clerk.users.deleteUser(user.id), + }; +}; + +export const newRun = () => randomBytes(4).toString("hex"); diff --git a/infra/relay/tsconfig.json b/infra/relay/tsconfig.json new file mode 100644 index 00000000..aa9452c1 --- /dev/null +++ b/infra/relay/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "tsBuildInfoFile": "../../.cache/typescript/relay.tsbuildinfo" + }, + "include": ["src", "test", "vite.config.ts"] +} diff --git a/infra/relay/vite.config.ts b/infra/relay/vite.config.ts new file mode 100644 index 00000000..96bd43b1 --- /dev/null +++ b/infra/relay/vite.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from "vite-plus"; + +export default defineConfig({ + test: { + include: ["test/**/*.test.ts"], + // The suite starts Postgres in Docker and creates a Clerk test user. + testTimeout: 60_000, + hookTimeout: 120_000, + }, +}); diff --git a/packages/codework/package.json b/packages/codework/package.json index cbff6bf3..dd1f904f 100644 --- a/packages/codework/package.json +++ b/packages/codework/package.json @@ -57,6 +57,7 @@ "zod": "4.6.5" }, "devDependencies": { + "@codeworksh/schema": "workspace:*", "@types/node": "catalog:", "bumpp": "^12.3.0", "node-gyp": "^13.0.2" diff --git a/packages/codework/src/cli/cmd/cmd.ts b/packages/codework/src/cli/cmd/cmd.ts index 139eebf3..4deee210 100644 --- a/packages/codework/src/cli/cmd/cmd.ts +++ b/packages/codework/src/cli/cmd/cmd.ts @@ -350,6 +350,36 @@ export const Cmd = Spec.make("codework", { }, ], }), + Spec.make("connect", { + description: "Connect this machine to a workspace", + params: { + workspace: Flag.String("workspace").pipe( + Flag.withDescription("Workspace to connect to; otherwise the approver picks it"), + Flag.optional, + ), + machineId: Flag.String("machine-id").pipe( + Flag.withDescription("Set this home's machine id instead of generating one, e.g. build-box-1"), + Flag.optional, + ), + }, + examples: [ + { command: "codework connect", description: "Show a code to approve in the CodeWork app" }, + { + command: "codework connect --machine-id build-box-1", + description: "Connect with a fixed id, replacing a rebuilt machine's old link", + }, + ], + }), + Spec.make("disconnect", { + description: "Disconnect this machine from a workspace", + params: { + workspace: Flag.String("workspace").pipe( + Flag.withDescription("Workspace to leave; optional when only one is connected"), + Flag.optional, + ), + }, + examples: [{ command: "codework disconnect", description: "Leave the only connected workspace" }], + }), Spec.make("serve", { description: "Start the CodeWork RPC server", params: { diff --git a/packages/codework/src/cli/cmd/handlers/connect.ts b/packages/codework/src/cli/cmd/handlers/connect.ts new file mode 100644 index 00000000..8e882acf --- /dev/null +++ b/packages/codework/src/cli/cmd/handlers/connect.ts @@ -0,0 +1,49 @@ +import { Machine, Relay, shellQuoted } from "@codeworksh/schema"; +import { Effect, Option, Schema } from "effect"; +import * as Runtime from "../../../framework/runtime.ts"; +import * as MachineRelay from "../../../machine/relay.ts"; +import * as Discovery from "../../../server/discovery.ts"; +import { InvalidInputError, reportFailure } from "../../error.ts"; +import { writeOut } from "../../output.ts"; +import * as Service from "../../service.ts"; +import { Cmd } from "../cmd.ts"; + +export default Runtime.handler( + Cmd.commands.connect, + Effect.fn("CLI.connect")( + function* ({ workspace, machineId }) { + const workspaceId = Option.getOrUndefined(workspace); + if (workspaceId !== undefined && !Schema.is(Relay.WorkspaceId)(workspaceId)) { + return yield* new InvalidInputError({ + message: "--workspace must be a Workspace ID; copy it from Settings → Machines in the CodeWork app", + }); + } + const spec = yield* Cmd.spec; + const paths = yield* Service.home(spec); + const connected = yield* MachineRelay.connect({ + home: paths.home, + workspaceId, + machineId: Option.getOrUndefined(machineId), + onCode: (code) => writeOut(`Approve this machine in the CodeWork app with code ${code}\n`), + }); + yield* writeOut(`Connected to ${connected.workspace.name}\n`); + // The workspace sees a machine online while its server runs; say how when it doesn't yet. + if ((yield* Discovery.discover(paths.home)) === undefined) { + const home = Option.match(spec.home, { + onNone: () => "", + onSome: (path) => ` --home ${shellQuoted(path)}`, + }); + yield* writeOut(`It shows online once its server runs: codework service start${home}\n`); + } + }, + Effect.catchReason("HttpClientError", "TransportError", (reason) => + Effect.fail( + new Machine.ConnectError({ + message: `Can't reach CodeWork's servers at ${new URL(reason.request.url).origin}; check your connection, then run connect again`, + }), + ), + ), + Effect.provide(MachineRelay.Client.layer), + Effect.catch(reportFailure), + ), +); diff --git a/packages/codework/src/cli/cmd/handlers/disconnect.ts b/packages/codework/src/cli/cmd/handlers/disconnect.ts new file mode 100644 index 00000000..752053b0 --- /dev/null +++ b/packages/codework/src/cli/cmd/handlers/disconnect.ts @@ -0,0 +1,34 @@ +import { Effect, Option } from "effect"; +import * as Runtime from "../../../framework/runtime.ts"; +import * as File from "../../../machine/file.ts"; +import * as Relay from "../../../machine/relay.ts"; +import { InvalidInputError, reportFailure } from "../../error.ts"; +import { writeOut } from "../../output.ts"; +import * as Service from "../../service.ts"; +import { Cmd } from "../cmd.ts"; + +export default Runtime.handler( + Cmd.commands.disconnect, + Effect.fn("CLI.disconnect")(function* ({ workspace }) { + const paths = yield* Service.home(yield* Cmd.spec); + const connected = Option.match(yield* File.read(paths.home), { + onNone: () => [], + onSome: (machine) => Object.keys(machine.workspaces), + }); + const workspaceId = Option.getOrUndefined(workspace) ?? (connected.length === 1 ? connected[0] : undefined); + if (workspaceId === undefined) { + return yield* new InvalidInputError({ + message: + connected.length === 0 + ? "This machine is not connected to any workspace" + : `Connected to ${connected.length} workspaces; name one with --workspace (${connected.join(", ")})`, + }); + } + const result = yield* Relay.disconnect(paths.home, workspaceId); + yield* writeOut( + result.revoked + ? `Disconnected from ${result.workspace}\n` + : `Disconnected locally from ${result.workspace}. The relay did not confirm. If this machine still appears in Settings → Machines, remove it there.\n`, + ); + }, Effect.catch(reportFailure)), +); diff --git a/packages/codework/src/index.ts b/packages/codework/src/index.ts index c521c6ef..4d677e87 100644 --- a/packages/codework/src/index.ts +++ b/packages/codework/src/index.ts @@ -25,6 +25,8 @@ const Handlers = Runtime.handlers(Cmd, { reconnect: () => import("./cli/cmd/handlers/mcp/reconnect.ts"), disconnect: () => import("./cli/cmd/handlers/mcp/disconnect.ts"), }, + connect: () => import("./cli/cmd/handlers/connect.ts"), + disconnect: () => import("./cli/cmd/handlers/disconnect.ts"), run: () => import("./cli/cmd/handlers/run.ts"), serve: () => import("./cli/cmd/handlers/serve.ts"), service: { diff --git a/packages/codework/src/machine/file.ts b/packages/codework/src/machine/file.ts new file mode 100644 index 00000000..970cc5ca --- /dev/null +++ b/packages/codework/src/machine/file.ts @@ -0,0 +1,135 @@ +import { Jws, Relay } from "@codeworksh/schema"; +import { Effect, FileSystem, Option, Schedule, Schema } from "effect"; +import { uuidv7 } from "uuidv7"; + +/** + * `/machine.json`: who this home is as a machine, and its link to each connected workspace. + * + * It survives restarts (unlike `service.json`, which a server writes and removes) and holds private + * keys, so it is written 0600, atomically, and under a lock shared by `serve` and `codework connect`. + */ +const Link = Schema.Struct({ + name: Schema.String, + owner: Schema.Struct({ id: Schema.String, name: Schema.NullOr(Schema.String) }), + /** The relay the link was made with; heartbeats and disconnect go there. */ + relay: Schema.String, + key: Jws.PrivateKey, + keyId: Schema.String, +}); + +/** One key per home, vouching for each link key, so the relay knows every link of this home is one machine. */ +const Identity = Schema.Struct({ key: Jws.PrivateKey, keyId: Schema.String }); +type Identity = typeof Identity.Type; + +export const Machine = Schema.Struct({ + id: Schema.String, + source: Relay.IdSource, + /** The user's own name for the machine; shown in place of the OS host name when set. */ + givenName: Schema.optional(Schema.String), + // Optional only for homes connected before identities existed; `update` gives every home one. + identity: Schema.optional(Identity), + workspaces: Schema.Record(Schema.String, Link), +}); +export type Machine = typeof Machine.Type; +/** The machine as {@link update} hands it out: always with its identity. */ +type Identified = Machine & { readonly identity: Identity }; + +const json = Schema.fromJsonString(Machine); + +class MachineError extends Schema.TaggedError()("Machine.MachineError", { + message: Schema.String, +}) {} + +const file = (home: string) => `${home}/machine.json`; + +/** The machine as stored, or none before its first run. */ +export const read = Effect.fn("Machine.read")(function* (home: string) { + const fs = yield* FileSystem.FileSystem; + const path = file(home); + if (!(yield* fs.exists(path))) return Option.none(); + const text = yield* fs.readFileString(path); + return Option.some( + yield* Schema.decodeEffect(json)(text).pipe( + Effect.mapError(() => new MachineError({ message: `${path} is not a valid machine file` })), + ), + ); +}); + +// One writer at a time: creating a directory either succeeds or fails, so it serves as a lock. +const locked = (home: string, effect: Effect.Effect) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const lock = `${file(home)}.lock`; + yield* fs.makeDirectory(home, { recursive: true }); + yield* fs.makeDirectory(lock).pipe( + Effect.retry({ schedule: Schedule.spaced("50 millis"), times: 100 }), + Effect.mapError(() => new MachineError({ message: `${lock} is held by another process` })), + ); + return yield* effect.pipe(Effect.ensuring(fs.remove(lock, { recursive: true }).pipe(Effect.ignore))); + }); + +const write = Effect.fn("Machine.write")(function* (home: string, machine: Machine) { + const fs = yield* FileSystem.FileSystem; + const path = file(home); + const temp = `${path}.${uuidv7()}.tmp`; + yield* fs.writeFileString(temp, yield* Schema.encodeEffect(json)(machine), { mode: 0o600 }); + yield* fs.rename(temp, path); +}); + +const newIdentity = Effect.gen(function* () { + const key = yield* Jws.generate(); + return { key, keyId: yield* Jws.thumbprint(Jws.publicOf(key)) } satisfies Identity; +}); + +/** Reads, changes and writes the machine under the lock, creating its identity on first use. */ +export const update = ( + home: string, + options: { readonly machineId?: string | undefined }, + change: (machine: Identified) => Effect.Effect, +) => + locked( + home, + Effect.gen(function* () { + const existing = yield* read(home); + const machine = yield* Option.match(existing, { + onNone: () => Effect.succeed(created(options.machineId)), + onSome: (machine) => + options.machineId === undefined || options.machineId === machine.id + ? Effect.succeed(machine) + : Effect.fail( + new MachineError({ + message: `This home is machine ${machine.id}; its id can't change to ${options.machineId}. Use another --home.`, + }), + ), + }); + const identity = machine.identity ?? (yield* newIdentity); + const next = yield* change({ ...machine, identity }); + yield* write(home, next); + return next; + }), + ); + +const created = (machineId: string | undefined): Machine => + machineId === undefined + ? { id: uuidv7(), source: "generated", workspaces: {} } + : { id: machineId, source: "flag", workspaces: {} }; + +/** Validates a `--machine-id` before anything is written. */ +export const checkId = (machineId: string | undefined) => + machineId === undefined || Schema.is(Relay.MachineId)(machineId) + ? Effect.void + : Effect.fail( + new MachineError({ + message: `--machine-id must be 1-64 lowercase letters, digits or dashes, starting with a letter or digit`, + }), + ); + +/** + * Forgets the link to a workspace, only while it still holds `keyId`: a reconnect that saved a new key in + * the meantime keeps its link. + */ +export const removeLink = (home: string, workspaceId: string, keyId: string) => + update(home, {}, (machine) => { + const { [workspaceId]: link, ...workspaces } = machine.workspaces; + return Effect.succeed(link === undefined || link.keyId !== keyId ? machine : { ...machine, workspaces }); + }); diff --git a/packages/codework/src/machine/heartbeat.ts b/packages/codework/src/machine/heartbeat.ts new file mode 100644 index 00000000..8af75bf6 --- /dev/null +++ b/packages/codework/src/machine/heartbeat.ts @@ -0,0 +1,19 @@ +import { Global } from "@codeworksh/harness/effect"; +import { Effect, Layer, Schedule } from "effect"; +import * as Relay from "./relay.ts"; + +/** + * While the server runs, each connected workspace hears from this machine every 30 seconds; the relay + * shows it online for 90. `machine.json` is read on every beat, so a `codework connect` made while the + * server runs is picked up without a restart. Nothing here is fatal: local work never waits on the relay. + */ +export const layer = Layer.effectDiscard( + Effect.gen(function* () { + const global = yield* Global.Service; + yield* Relay.heartbeat(global.home).pipe( + Effect.catch((error) => Effect.logDebug("Machine heartbeat failed", error)), + Effect.repeat(Schedule.spaced("30 seconds")), + Effect.forkScoped, + ); + }), +); diff --git a/packages/codework/src/machine/relay.ts b/packages/codework/src/machine/relay.ts new file mode 100644 index 00000000..0a0563c3 --- /dev/null +++ b/packages/codework/src/machine/relay.ts @@ -0,0 +1,233 @@ +import { NodeServices } from "@effect/platform-node"; +import { Jws, Machine, Relay } from "@codeworksh/schema"; +import { Clock, Config, Context, Duration, Effect, Layer } from "effect"; +import { FetchHttpClient } from "effect/http"; +import { HttpApiClient } from "effect/http-api"; +import { uuidv7 } from "uuidv7"; +import pkg from "../../package.json" with { type: "json" }; +import { hostName } from "../server/identity.ts"; +import * as File from "./file.ts"; + +/** The relay's typed client at `url`. */ +const at = (url: string) => HttpApiClient.make(Relay.Api, { baseUrl: url }).pipe(Effect.provide(FetchHttpClient.layer)); + +/** + * The relay new connects go to: `CODEWORK_RELAY_URL`, default https://relay.codework.sh. A link keeps + * talking to the relay it was made with, whatever this says later. + */ +export class Client extends Context.Service< + Client, + { readonly url: string; readonly api: HttpApiClient.ForApi } +>()("@codeworksh/cli/machine/relay/Client") { + static readonly layer = Layer.effect( + Client, + Effect.gen(function* () { + const url = yield* Config.String("CODEWORK_RELAY_URL").pipe(Config.withDefault("https://relay.codework.sh")); + return { url, api: yield* at(url) }; + }), + ); +} + +/** What this machine says about itself to the relay. */ +const describe = Effect.fn("Machine.describe")(function* (machine: File.Machine) { + const localHostName = yield* hostName.pipe(Effect.provide(NodeServices.layer)); + return { + id: machine.id, + source: machine.source, + localHostName, + givenName: machine.givenName ?? null, + os: process.platform, + arch: process.arch, + version: pkg.version, + } satisfies Relay.MachineInfo; +}); + +/** This machine and its workspaces, as the desktop app shows them. */ +export const status = Effect.fn("Machine.status")(function* (home: string) { + const stored = yield* File.read(home); + const localHostName = yield* hostName.pipe(Effect.provide(NodeServices.layer)); + if (stored._tag === "None") + return { id: null, localHostName, givenName: null, workspaces: [] } satisfies Machine.Status; + const machine = stored.value; + return { + id: machine.id, + localHostName, + givenName: machine.givenName ?? null, + workspaces: Object.entries(machine.workspaces).map(([id, link]) => ({ id, name: link.name, keyId: link.keyId })), + } satisfies Machine.Status; +}); + +/** + * Names this machine for people: empty clears the name back to the OS's. The relay hears it on the + * next heartbeat. + */ +export const rename = Effect.fn("Machine.rename")(function* (home: string, givenName: string) { + const name = givenName.trim(); + yield* File.update(home, {}, ({ givenName: _previous, ...machine }) => + Effect.succeed(name === "" ? machine : { ...machine, givenName: name }), + ); + return yield* status(home); +}); + +/** + * Pairs this home with a workspace: registers a fresh key with the relay, shows the code a member + * approves, and polls with that key until the relay links it, then saves the link. Each workspace gets + * its own key, and only this process can take the link: a connect that stops is never linked. + */ +export const connect = Effect.fn("Machine.connect")(function* (options: { + readonly home: string; + readonly workspaceId?: string | undefined; + readonly machineId?: string | undefined; + readonly onCode: (userCode: string) => Effect.Effect; +}) { + const client = yield* Client; + yield* File.checkId(options.machineId); + const machine = yield* File.update(options.home, { machineId: options.machineId }, Effect.succeed); + const key = yield* Jws.generate(); + const keyId = yield* Jws.thumbprint(Jws.publicOf(key)); + const iat = yield* Clock.currentTimeMillis; + const binding: Relay.IdentityClaims = { op: "identity.bind", iat, keyId }; + const claims: Relay.PairingClaims = { + op: "pairing.create", + iat, + machine: yield* describe(machine), + workspaceId: options.workspaceId ?? null, + identity: yield* Jws.sign(binding, machine.identity.key, { embed: true }), + }; + const pairing = yield* client.api.machine + .pair({ payload: { jws: yield* Jws.sign(claims, key, { embed: true }) } }) + .pipe( + Effect.catchTag("Relay.NotFound", () => + Effect.fail(new Machine.ConnectError({ message: "No such workspace" })), + ), + ); + yield* options.onCode(pairing.userCode); + + const poll = Effect.gen(function* () { + const claims: Relay.PollClaims = { op: "pairing.poll", iat: yield* Clock.currentTimeMillis }; + return yield* client.api.machine.poll({ payload: { jws: yield* Jws.sign(claims, key, { kid: keyId }) } }); + }).pipe( + // A dropped request or a relay restart doesn't end the connect; the next poll asks again. + Effect.catchTag("HttpClientError", (error) => + Effect.logDebug("Pairing poll failed", error).pipe(Effect.as(undefined)), + ), + ); + let previous = machine; + const deadline = (yield* Clock.currentTimeMillis) + pairing.expiresIn * 1000; + while ((yield* Clock.currentTimeMillis) < deadline) { + yield* Effect.sleep(Duration.seconds(pairing.interval)); + const status = yield* poll; + if (status === undefined) continue; + if (status.status !== "approved") { + if (status.status === "pending") continue; + if (status.status === "expired") break; + return yield* new Machine.ConnectError({ + message: + status.status === "declined" + ? "The connect was declined; run connect again for a new code" + : "Another connect for this machine finished first", + }); + } + const { connected } = status; + // A poll response can arrive after another connect saved a different key. + // Observe that change under the lock, then poll again before replacing it. + const id = connected.workspace.id; + const stored = yield* File.update(options.home, {}, (current) => + Effect.succeed( + current.workspaces[id]?.keyId !== previous.workspaces[id]?.keyId + ? current + : { + ...current, + workspaces: { + ...current.workspaces, + [connected.workspace.id]: { + name: connected.workspace.name, + owner: connected.owner, + relay: client.url, + key, + keyId, + }, + }, + }, + ), + ); + if (stored.workspaces[id]?.keyId === keyId) return connected; + previous = stored; + } + return yield* new Machine.ConnectError({ message: "The code expired before it was approved; run connect again" }); +}); + +/** + * One heartbeat per connected workspace, each to the relay its link was made with, all at once. A link + * the relay refuses as revoked is removed, but only while it still holds the refused key. + */ +export const heartbeat = Effect.fn("Machine.heartbeat")(function* (home: string) { + const stored = yield* File.read(home); + if (stored._tag === "None") return; + const machine = stored.value; + const info = yield* describe(machine); + yield* Effect.forEach( + Object.entries(machine.workspaces), + ([workspaceId, link]) => + Effect.gen(function* () { + const api = yield* at(link.relay); + const claims: Relay.HeartbeatClaims = { + op: "machine.heartbeat", + iat: yield* Clock.currentTimeMillis, + workspaceId, + machine: info, + }; + yield* api.machine.heartbeat({ payload: { jws: yield* Jws.sign(claims, link.key, { kid: link.keyId }) } }); + }).pipe( + Effect.timeout("10 seconds"), + Effect.catchTags({ + "Relay.MachineRevoked": (revoked) => + Effect.logWarning(`Disconnected from ${link.name}: ${revoked.message}`).pipe( + Effect.andThen(File.removeLink(home, workspaceId, link.keyId)), + ), + // Refused but not revoked, most often a clock more than a minute off: worth seeing in the log. + "Relay.Unauthorized": (refused) => + Effect.logWarning(`Heartbeat to ${link.name} refused: ${refused.message}`), + }), + Effect.catch((error) => Effect.logDebug(`Heartbeat to ${link.name} failed`, error)), + ), + { concurrency: "unbounded", discard: true }, + ); +}); + +/** + * Leaves a workspace: asks the link's relay to revoke it, then forgets it locally. The local link is + * removed even when the relay can't be reached; `revoked` says whether it confirmed. + */ +export const disconnect = Effect.fn("Machine.disconnect")(function* ( + home: string, + workspaceId: string, + expectedKeyId?: string, +) { + const stored = yield* File.read(home); + const link = stored._tag === "Some" ? stored.value.workspaces[workspaceId] : undefined; + if (stored._tag === "None" || link === undefined) { + return yield* new Machine.ConnectError({ message: `This machine is not connected to workspace ${workspaceId}` }); + } + if (expectedKeyId !== undefined && link.keyId !== expectedKeyId) + return yield* new Machine.ConnectError({ message: "This machine link has changed" }); + const claims: Relay.RevokeClaims = { + op: "machine.revoke", + iat: yield* Clock.currentTimeMillis, + jti: uuidv7(), + workspaceId, + machineId: stored.value.id, + }; + const revoked = yield* Effect.gen(function* () { + const api = yield* at(link.relay); + yield* api.machine.revoke({ payload: { jws: yield* Jws.sign(claims, link.key, { kid: link.keyId }) } }); + }).pipe( + // Leave time for the local update and fallback before the desktop RPC expires. + Effect.timeout("3 seconds"), + Effect.as(true), + Effect.catchTag("Relay.MachineRevoked", () => Effect.succeed(true)), + Effect.orElseSucceed(() => false), + ); + yield* File.removeLink(home, workspaceId, link.keyId); + return { workspace: link.name, revoked }; +}); diff --git a/packages/codework/src/server/contract.ts b/packages/codework/src/server/contract.ts index 98626f68..50f5c5da 100644 --- a/packages/codework/src/server/contract.ts +++ b/packages/codework/src/server/contract.ts @@ -20,6 +20,7 @@ import { ThreadStore, UsageSchema, } from "@codeworksh/harness/effect"; +import { Machine } from "@codeworksh/schema"; import { Schema } from "effect"; import { Rpc, RpcGroup } from "effect/rpc"; import { EncodingError, EventEnvelope } from "./envelope.ts"; @@ -916,6 +917,32 @@ export const Api = RpcGroup.make( success: McpStatus, error: McpErrors, }), + /** This machine and the workspaces it is connected to. */ + Rpc.make("machine.info", { + payload: {}, + success: Machine.Status, + }), + /** Names this machine for people; an empty name goes back to the OS's. */ + Rpc.make("machine.rename", { + payload: { givenName: Schema.String }, + success: Machine.Status, + }), + /** Leaves a workspace: the relay revokes this machine's link, and the machine forgets it. */ + Rpc.make("machine.disconnect", { + payload: Machine.Disconnect, + success: Machine.Disconnected, + error: Machine.ConnectError, + }), + /** + * Connects this machine to a workspace: the code a member approves, then the link once they have. + * `workspaceId` is the workspace it is meant for; without one the approver picks it. + */ + Rpc.make("machine.connect", { + payload: { workspaceId: Schema.optional(Schema.String) }, + success: Machine.ConnectEvent, + error: Machine.ConnectError, + stream: true, + }), /** The OS home directory, and the folder `host.create` makes projects in. */ Rpc.make("host.info", { payload: {}, diff --git a/packages/codework/src/server/handlers.ts b/packages/codework/src/server/handlers.ts index 8356ccd7..d3c2eadb 100644 --- a/packages/codework/src/server/handlers.ts +++ b/packages/codework/src/server/handlers.ts @@ -2,6 +2,7 @@ import { Model } from "@codeworksh/aikit"; import { Control, DaemonHost, + Global, Event, EventList, EventRegistry, @@ -22,7 +23,10 @@ import { ThreadSchema, ThreadStore, } from "@codeworksh/harness/effect"; -import { DateTime, Effect, Option, Predicate, Schema, Stream } from "effect"; +import { Machine } from "@codeworksh/schema"; +import { DateTime, Effect, Option, Predicate, Queue, Schema, Stream } from "effect"; +import { NodeServices } from "@effect/platform-node"; +import * as MachineRelay from "../machine/relay.ts"; import * as Contract from "./contract.ts"; import { type HistoryEntry, @@ -48,6 +52,8 @@ import * as OAuth from "./oauth.ts"; import * as MessagePart from "./part.ts"; import * as Rows from "./rows.ts"; +const isConnectError = Schema.is(Machine.ConnectError); + const toSandboxInfo = (info: Sandbox.Info): SandboxInfo => ({ id: info.id, driver: info.driver, @@ -282,6 +288,7 @@ export const layer = Contract.Api.toLayer( const host = yield* Host.Service; const clones = yield* Clones.Service; const store = yield* Store.Service; + const global = yield* Global.Service; const mcpControl = (operation: "connect" | "disconnect") => Effect.fnUntraced(function* ({ server, ...ref }: Control.ThreadRef & { readonly server: string }) { return yield* mcp[operation](yield* resolve(ref), server); @@ -625,6 +632,61 @@ export const layer = Contract.Api.toLayer( }), "mcp.connect": mcpControl("connect"), "mcp.disconnect": mcpControl("disconnect"), + "machine.info": () => MachineRelay.status(global.home).pipe(Effect.provide(NodeServices.layer), Effect.orDie), + "machine.rename": ({ givenName }) => + MachineRelay.rename(global.home, givenName).pipe( + // The relay hears the new name now rather than on the next beat; a miss is retried then. + Effect.tap(() => + MachineRelay.heartbeat(global.home).pipe( + Effect.provide(NodeServices.layer), + Effect.ignore, + Effect.forkDetach, + ), + ), + Effect.provide(NodeServices.layer), + Effect.orDie, + ), + "machine.disconnect": ({ workspaceId, keyId }) => + MachineRelay.disconnect(global.home, workspaceId, keyId).pipe( + Effect.flatMap(({ revoked }) => + MachineRelay.status(global.home).pipe(Effect.map((status) => ({ status, revoked }))), + ), + Effect.provide(NodeServices.layer), + Effect.catchIf( + (error) => !isConnectError(error), + (error) => + Effect.fail(new Machine.ConnectError({ message: `Could not disconnect: ${String(error)}` })), + ), + ), + "machine.connect": ({ workspaceId }) => + Stream.callback((queue) => + MachineRelay.connect({ + home: global.home, + workspaceId, + onCode: (userCode) => Queue.offer(queue, { _tag: "Code", userCode }).pipe(Effect.asVoid), + }).pipe( + // The workspace sees it online now rather than on the next beat; a miss is retried then. + Effect.tap(() => + MachineRelay.heartbeat(global.home).pipe( + Effect.provide(NodeServices.layer), + Effect.ignore, + Effect.forkDetach, + ), + ), + Effect.flatMap((connected) => Queue.offer(queue, { _tag: "Connected", connected })), + Effect.andThen(Queue.end(queue)), + Effect.provide([MachineRelay.Client.layer, NodeServices.layer]), + Effect.catch((error) => + Queue.fail( + queue, + isConnectError(error) + ? error + : new Machine.ConnectError({ message: `Could not connect: ${String(error)}` }), + ), + ), + Effect.forkScoped, + ), + ), "host.info": () => Effect.succeed(host.info), "host.browse": ({ path }) => host.browse(path), "host.create": ({ name }) => host.create(name), diff --git a/packages/codework/src/server/identity.ts b/packages/codework/src/server/identity.ts index b547a5c5..882517df 100644 --- a/packages/codework/src/server/identity.ts +++ b/packages/codework/src/server/identity.ts @@ -25,7 +25,8 @@ export class Service extends Context.Service()("@codeworksh/ export const current: Interface = { pid: process.pid, version: pkg.version }; // macOS's computer name is the one Finder and sharing show; its hostname is a mangled copy of it. -const hostName = Effect.gen(function* () { +/** The machine's name as its user knows it, read from the OS; empty when it names nothing. */ +export const hostName = Effect.gen(function* () { if (process.platform !== "darwin") return os.hostname().trim(); const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const computer = yield* spawner diff --git a/packages/codework/src/server/server.ts b/packages/codework/src/server/server.ts index 4f69c207..ee6dad9d 100644 --- a/packages/codework/src/server/server.ts +++ b/packages/codework/src/server/server.ts @@ -6,6 +6,7 @@ import * as NetAddress from "effect/net/NetAddress"; import { RpcSerialization, RpcServer } from "effect/rpc"; /* @effect-diagnostics nodeBuiltinImport:off -- the RPC listener needs a raw node server. */ import { createServer } from "node:http"; +import * as Heartbeat from "../machine/heartbeat.ts"; import * as Clones from "./clones.ts"; import * as Contract from "./contract.ts"; import * as EventFeed from "./feed.ts"; @@ -102,6 +103,7 @@ export const layer = (options: { const app = HttpRouter.serve(rpc, { disableListenLog: true }).pipe( Layer.provideMerge(managedShutdown), Layer.provideMerge(resumeUnfinished), + Layer.provideMerge(Heartbeat.layer), Layer.provide(OAuth.layer(options.harness.home === undefined ? {} : { home: options.harness.home })), Layer.provide(Host.layer), Layer.provide(Clones.layer), diff --git a/packages/schema/package.json b/packages/schema/package.json new file mode 100644 index 00000000..c648ac27 --- /dev/null +++ b/packages/schema/package.json @@ -0,0 +1,19 @@ +{ + "name": "@codeworksh/schema", + "version": "0.0.0", + "private": true, + "description": "Shared wire schemas: the relay API and the signed machine requests. Bundled into its consumers.", + "type": "module", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "effect": "4.0.5" + }, + "devDependencies": { + "typescript": "catalog:" + } +} diff --git a/packages/schema/src/index.ts b/packages/schema/src/index.ts new file mode 100644 index 00000000..44157cc6 --- /dev/null +++ b/packages/schema/src/index.ts @@ -0,0 +1,4 @@ +export { shellQuoted } from "./shell.ts"; +export * as Jws from "./jws.ts"; +export * as Machine from "./machine.ts"; +export * as Relay from "./relay.ts"; diff --git a/packages/schema/src/jws.ts b/packages/schema/src/jws.ts new file mode 100644 index 00000000..42c929c8 --- /dev/null +++ b/packages/schema/src/jws.ts @@ -0,0 +1,103 @@ +import { Effect, Result, Schema } from "effect"; +import { Base64Url } from "effect/encoding"; + +// Compact JWS with Ed25519 (EdDSA) over WebCrypto, so the same code signs on a machine (Node) and +// verifies in the relay (Node or a Worker). + +export const PublicKey = Schema.Struct({ + kty: Schema.Literal("OKP"), + crv: Schema.Literal("Ed25519"), + x: Schema.String, +}); +export type PublicKey = typeof PublicKey.Type; + +export const PrivateKey = Schema.Struct({ ...PublicKey.fields, d: Schema.String }); +export type PrivateKey = typeof PrivateKey.Type; + +export const Header = Schema.Struct({ + alg: Schema.Literal("EdDSA"), + /** The signing key's thumbprint, for a key the verifier already holds. */ + kid: Schema.optional(Schema.String), + /** The signing key itself, for a request that registers it. */ + jwk: Schema.optional(PublicKey), +}); +export type Header = typeof Header.Type; + +export class JwsError extends Schema.TaggedError()("Jws.JwsError", { + reason: Schema.Literals(["malformed", "signature", "crypto"]), +}) {} + +const algorithm = { name: "Ed25519" } as const; +const decodeHeader = Schema.decodeUnknownEffect(Schema.fromJsonString(Header)); +const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown)); +const crypto = (evaluate: () => Promise) => + Effect.tryPromise({ try: evaluate, catch: () => new JwsError({ reason: "crypto" }) }); +const bytes = (part: string) => + Result.match(Base64Url.decode(part), { + onFailure: () => Effect.fail(new JwsError({ reason: "malformed" })), + onSuccess: (decoded) => Effect.succeed(Uint8Array.from(decoded)), + }); + +/** The public half of a private key. */ +export const publicOf = (key: PrivateKey): PublicKey => ({ kty: key.kty, crv: key.crv, x: key.x }); + +/** A fresh Ed25519 keypair as a private JWK; its public half is {@link publicOf}. */ +export const generate = Effect.fn("Jws.generate")(function* () { + const pair = yield* crypto(() => globalThis.crypto.subtle.generateKey("Ed25519", true, ["sign", "verify"])); + if (!("privateKey" in pair)) return yield* new JwsError({ reason: "crypto" }); + const jwk = yield* crypto(() => globalThis.crypto.subtle.exportKey("jwk", pair.privateKey)); + return yield* Schema.decodeUnknownEffect(PrivateKey)(jwk).pipe( + Effect.mapError(() => new JwsError({ reason: "crypto" })), + ); +}); + +/** The RFC 7638 thumbprint of a public key: base64url SHA-256 of its required members, in order. */ +export const thumbprint = Effect.fn("Jws.thumbprint")(function* (key: PublicKey) { + const canonical = `{"crv":"${key.crv}","kty":"${key.kty}","x":"${key.x}"}`; + const digest = yield* crypto(() => globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical))); + return Base64Url.encode(new Uint8Array(digest)); +}); + +/** Signs `claims` with `key`, naming it by `kid` or embedding its public half. */ +export const sign = Effect.fn("Jws.sign")(function* ( + claims: unknown, + key: PrivateKey, + name: { readonly kid: string } | { readonly embed: true }, +) { + const header: Header = "kid" in name ? { alg: "EdDSA", kid: name.kid } : { alg: "EdDSA", jwk: publicOf(key) }; + const input = `${Base64Url.encode(JSON.stringify(header))}.${Base64Url.encode(JSON.stringify(claims))}`; + const signer = yield* crypto(() => globalThis.crypto.subtle.importKey("jwk", key, algorithm, false, ["sign"])); + const signature = yield* crypto(() => + globalThis.crypto.subtle.sign(algorithm, signer, new TextEncoder().encode(input)), + ); + return `${input}.${Base64Url.encode(new Uint8Array(signature))}`; +}); + +const parts = (token: string) => { + const [header, claims, signature, extra] = token.split("."); + return header === undefined || claims === undefined || signature === undefined || extra !== undefined + ? Effect.fail(new JwsError({ reason: "malformed" })) + : Effect.succeed({ header, claims, signature }); +}; + +/** A token's header, read before its signature is checked, to find the key that checks it. */ +export const peek = Effect.fn("Jws.peek")(function* (token: string) { + const { header } = yield* parts(token); + return yield* decodeHeader(new TextDecoder().decode(yield* bytes(header))).pipe( + Effect.mapError(() => new JwsError({ reason: "malformed" })), + ); +}); + +/** Checks `token`'s signature against `key` and returns its claims, still undecoded. */ +export const verify = Effect.fn("Jws.verify")(function* (token: string, key: PublicKey) { + const { header, claims, signature } = yield* parts(token); + const signed = yield* bytes(signature); + const verifier = yield* crypto(() => globalThis.crypto.subtle.importKey("jwk", key, algorithm, false, ["verify"])); + const valid = yield* crypto(() => + globalThis.crypto.subtle.verify(algorithm, verifier, signed, new TextEncoder().encode(`${header}.${claims}`)), + ); + if (!valid) return yield* new JwsError({ reason: "signature" }); + return yield* decodeJson(new TextDecoder().decode(yield* bytes(claims))).pipe( + Effect.mapError(() => new JwsError({ reason: "malformed" })), + ); +}); diff --git a/packages/schema/src/machine.ts b/packages/schema/src/machine.ts new file mode 100644 index 00000000..2c81b583 --- /dev/null +++ b/packages/schema/src/machine.ts @@ -0,0 +1,34 @@ +import { Schema } from "effect"; +import { Connected } from "./relay.ts"; + +// A CodeWork server as a machine: what its clients (the desktop app) see over the CodeWork RPC. + +/** This machine and the workspaces it is connected to, from its `machine.json`. */ +export const Status = Schema.Struct({ + /** None before the machine's first connect gives it an identity. */ + id: Schema.NullOr(Schema.String), + /** The OS's name for the host, read fresh. */ + localHostName: Schema.String, + /** The user's own name for it, shown in place of `localHostName` when set. */ + givenName: Schema.NullOr(Schema.String), + /** Each link with the thumbprint of its key: a relay row under another key is not this machine's. */ + workspaces: Schema.Array(Schema.Struct({ id: Schema.String, name: Schema.String, keyId: Schema.String })), +}); +export type Status = typeof Status.Type; + +export const Disconnect = Schema.Struct({ workspaceId: Schema.String, keyId: Schema.String }); + +/** A disconnect: this machine afterwards, and whether the relay confirmed the link is revoked. */ +export const Disconnected = Schema.Struct({ status: Status, revoked: Schema.Boolean }); +export type Disconnected = typeof Disconnected.Type; + +/** A connect's progress: the code to approve, then the link once a member approved it. */ +export const ConnectEvent = Schema.Union([ + Schema.TaggedStruct("Code", { userCode: Schema.String }), + Schema.TaggedStruct("Connected", { connected: Connected }), +]); +export type ConnectEvent = typeof ConnectEvent.Type; + +export class ConnectError extends Schema.TaggedError()("Machine.ConnectError", { + message: Schema.String, +}) {} diff --git a/packages/schema/src/relay.ts b/packages/schema/src/relay.ts new file mode 100644 index 00000000..8594d0c5 --- /dev/null +++ b/packages/schema/src/relay.ts @@ -0,0 +1,253 @@ +import { Context, Schema } from "effect"; +import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSecurity } from "effect/http-api"; + +// The relay's HTTP API (relay.codework.sh): people call it with an auth-vendor session token, machines +// with requests signed by their own key (see ./jws.ts). The relay implements it; codework is a client. + +export const Role = Schema.Literals(["owner", "admin", "member"]); + +/** A workspace's id, which the relay assigns; anything else is refused at the wire. */ +export const WorkspaceId = Schema.String.check(Schema.isUUID()); + +/** A machine's id: generated (a UUID) or set with `--machine-id`, lowercase letters, digits and dashes. */ +export const MachineId = Schema.String.check(Schema.isPattern(/^[a-z0-9][a-z0-9-]{0,63}$/)); + +export class Account extends Schema.Class("Relay.Account")({ + id: Schema.String, + email: Schema.String, + name: Schema.NullOr(Schema.String), +}) {} + +export class Workspace extends Schema.Class("Relay.Workspace")({ + id: WorkspaceId, + name: Schema.String, + role: Role, +}) {} + +export class Me extends Schema.Class("Relay.Me")({ + account: Account, + workspaces: Schema.Array(Workspace), +}) {} + +/** How a machine got its id: generated on first run, or set with `--machine-id`. */ +export const IdSource = Schema.Literals(["generated", "flag"]); + +/** What a machine says about itself when it pairs and on every heartbeat. */ +export const MachineInfo = Schema.Struct({ + id: MachineId, + source: IdSource, + localHostName: Schema.String, + givenName: Schema.NullOr(Schema.String), + os: Schema.String, + arch: Schema.String, + version: Schema.String, +}); +export type MachineInfo = typeof MachineInfo.Type; + +export class Machine extends Schema.Class("Relay.Machine")({ + ...MachineInfo.fields, + workspaceId: WorkspaceId, + /** The thumbprint of the key the link is live under; a home holds that key for this workspace. */ + keyId: Schema.String, + /** The thumbprint of the home's identity key: links with the same one, in any workspace, are one machine. */ + identityKeyId: Schema.String, + ownerId: Schema.String, + online: Schema.Boolean, + lastSeenAt: Schema.NullOr(Schema.String), +}) {} + +// Signed machine requests: the body carries one compact JWS whose claims name the operation, so a +// signature made for one endpoint is refused by every other. + +export const SignedRequest = Schema.Struct({ jws: Schema.String }); + +export const PairingClaims = Schema.Struct({ + op: Schema.Literal("pairing.create"), + iat: Schema.Number, + machine: MachineInfo, + /** The workspace the connect started from; the approver may pick another when it is null. */ + workspaceId: Schema.NullOr(WorkspaceId), + /** An {@link IdentityClaims} JWS by the home's identity key, naming this request's key. */ + identity: Schema.String, +}); +export type PairingClaims = typeof PairingClaims.Type; + +/** + * A home's identity key vouching for one of its link keys. It embeds the identity key and names the link + * key's thumbprint, so the binding can't be replayed for another link. + */ +export const IdentityClaims = Schema.Struct({ + op: Schema.Literal("identity.bind"), + iat: Schema.Number, + keyId: Schema.String, +}); +export type IdentityClaims = typeof IdentityClaims.Type; + +/** A pairing's poll, signed with the key it registered: only that process learns the outcome. */ +export const PollClaims = Schema.Struct({ + op: Schema.Literal("pairing.poll"), + iat: Schema.Number, +}); +export type PollClaims = typeof PollClaims.Type; + +export const HeartbeatClaims = Schema.Struct({ + op: Schema.Literal("machine.heartbeat"), + iat: Schema.Number, + workspaceId: WorkspaceId, + machine: MachineInfo, +}); +export type HeartbeatClaims = typeof HeartbeatClaims.Type; + +export const RevokeClaims = Schema.Struct({ + op: Schema.Literal("machine.revoke"), + iat: Schema.Number, + /** Used once: a replayed revoke is refused. */ + jti: Schema.String, + workspaceId: WorkspaceId, + machineId: MachineId, +}); +export type RevokeClaims = typeof RevokeClaims.Type; + +export const PairingCreated = Schema.Struct({ + userCode: Schema.String, + expiresIn: Schema.Int, + interval: Schema.Int, +}); + +export const Connected = Schema.Struct({ + machineId: MachineId, + workspace: Schema.Struct({ id: WorkspaceId, name: Schema.String }), + owner: Schema.Struct({ id: Schema.String, name: Schema.NullOr(Schema.String) }), +}); +export type Connected = typeof Connected.Type; + +export const PairingStatus = Schema.Union([ + /** `superseded`: another connect for this machine and workspace was activated first. */ + Schema.Struct({ status: Schema.Literals(["pending", "expired", "declined", "superseded"]) }), + Schema.Struct({ status: Schema.Literal("approved"), connected: Connected }), +]); +export type PairingStatus = typeof PairingStatus.Type; + +export class Unauthorized extends Schema.TaggedError()( + "Relay.Unauthorized", + { message: Schema.String }, + { httpApiStatus: 401 }, +) {} + +/** The relay couldn't check the request just now (its auth vendor is unreachable): try again shortly. */ +export class Unavailable extends Schema.TaggedError()( + "Relay.Unavailable", + { message: Schema.String }, + { httpApiStatus: 503 }, +) {} + +/** The machine's link to the workspace is gone: revoked, replaced, or its owner left. Reconnect to restore it. */ +export class MachineRevoked extends Schema.TaggedError()( + "Relay.MachineRevoked", + { message: Schema.String }, + { httpApiStatus: 401 }, +) {} + +export class Forbidden extends Schema.TaggedError()( + "Relay.Forbidden", + { message: Schema.String }, + { httpApiStatus: 403 }, +) {} + +export class NotFound extends Schema.TaggedError()( + "Relay.NotFound", + { message: Schema.String }, + { httpApiStatus: 404 }, +) {} + +/** A person whose session token the auth vendor verified: only the vendor's subject id. */ +export class Person extends Context.Service()("relay/Person") {} + +/** Verifies a person's bearer session token and provides {@link Person}. */ +export class PersonAuth extends HttpApiMiddleware.Service()( + "relay/PersonAuth", + { + security: { bearer: HttpApiSecurity.bearer }, + error: [Unauthorized, Unavailable], + }, +) {} + +export class MeGroup extends HttpApiGroup.make("me") + .add(HttpApiEndpoint.get("get", "/v1/me", { success: Me })) + .middleware(PersonAuth) {} + +/** A machine that ran `codework connect` for a workspace and waits for a member to approve its code. */ +export class PendingPairing extends Schema.Class("Relay.PendingPairing")({ + userCode: Schema.String, + machine: MachineInfo, + /** `approved`: a member approved it and the machine's next poll links it. */ + status: Schema.Literals(["pending", "approved"]), + /** A machine with this id is already in the workspace; approving replaces its link. */ + replaces: Schema.Boolean, + createdAt: Schema.String, + expiresAt: Schema.String, +}) {} + +export const WorkspaceName = Schema.Trimmed.check(Schema.isNonEmpty(), Schema.isMaxLength(64)); + +/** People create workspaces, and manage pairings and machines in a workspace they belong to. */ +export class WorkspaceGroup extends HttpApiGroup.make("workspace") + .add( + HttpApiEndpoint.post("create", "/v1/workspaces", { + payload: Schema.Struct({ name: WorkspaceName }), + success: Workspace, + }), + /** Approves a code; the machine's next poll links it, so it answers with what the machine said. */ + HttpApiEndpoint.post("approve", "/v1/pairings/approve", { + payload: Schema.Struct({ userCode: Schema.String, workspaceId: WorkspaceId }), + success: Schema.Struct({ machine: MachineInfo }), + error: [NotFound, Forbidden], + }), + HttpApiEndpoint.get("machines", "/v1/workspaces/:workspaceId/machines", { + params: { workspaceId: WorkspaceId }, + success: Schema.Array(Machine), + error: Forbidden, + }), + /** The workspace's pending connects, each with the code its machine shows. */ + HttpApiEndpoint.get("pairings", "/v1/workspaces/:workspaceId/pairings", { + params: { workspaceId: WorkspaceId }, + success: Schema.Array(PendingPairing), + error: Forbidden, + }), + /** Turns a pending connect away; the waiting machine hears it was declined. */ + HttpApiEndpoint.post("decline", "/v1/pairings/decline", { + payload: Schema.Struct({ userCode: Schema.String, workspaceId: WorkspaceId }), + error: [NotFound, Forbidden], + }), + /** Disconnects a machine from the workspace: its owner, or a workspace owner or admin, may. */ + HttpApiEndpoint.post("remove", "/v1/workspaces/:workspaceId/machines/:machineId/remove", { + params: { workspaceId: WorkspaceId, machineId: MachineId }, + payload: Schema.Struct({ keyId: Schema.String }), + error: [NotFound, Forbidden], + }), + ) + .middleware(PersonAuth) {} + +/** Machines authenticate each request with a signature, not a session. */ +export class MachineGroup extends HttpApiGroup.make("machine").add( + HttpApiEndpoint.post("pair", "/v1/pairings", { + payload: SignedRequest, + success: PairingCreated, + error: [Unauthorized, NotFound], + }), + HttpApiEndpoint.post("poll", "/v1/pairings/poll", { + payload: SignedRequest, + success: PairingStatus, + error: [Unauthorized, NotFound], + }), + HttpApiEndpoint.post("heartbeat", "/v1/machines/heartbeat", { + payload: SignedRequest, + error: [Unauthorized, MachineRevoked], + }), + HttpApiEndpoint.post("revoke", "/v1/machines/revoke", { + payload: SignedRequest, + error: [Unauthorized, MachineRevoked], + }), +) {} + +export class Api extends HttpApi.make("relay").add(MeGroup).add(WorkspaceGroup).add(MachineGroup) {} diff --git a/packages/schema/src/shell.ts b/packages/schema/src/shell.ts new file mode 100644 index 00000000..70a41e6d --- /dev/null +++ b/packages/schema/src/shell.ts @@ -0,0 +1,2 @@ +/** A path as one shell word: as is when it needs no quoting, else single-quoted. */ +export const shellQuoted = (path: string) => (/^[\w./~-]+$/.test(path) ? path : `'${path.replaceAll("'", "'\\''")}'`); diff --git a/packages/schema/tsconfig.json b/packages/schema/tsconfig.json new file mode 100644 index 00000000..34bf714e --- /dev/null +++ b/packages/schema/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "lib": ["ES2023", "DOM"], + "tsBuildInfoFile": "../../.cache/typescript/schema.tsbuildinfo" + }, + "include": ["src"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 01f22ea8..84ea70e2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -226,6 +226,9 @@ importers: apps/contract: dependencies: + '@codeworksh/schema': + specifier: workspace:* + version: link:../../packages/schema '@codeworksh/widget': specifier: workspace:* version: link:../widget @@ -239,6 +242,9 @@ importers: apps/desktop: devDependencies: + '@clerk/electron': + specifier: 0.1.10 + version: 0.1.10(@types/react@19.3.0)(electron-store@8.2.0)(electron@44.4.2(supports-color@7.2.0))(preact-render-to-string@6.6.5)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(typescript@7.0.2)(use-sync-external-store@1.7.0(react@19.3.1))(zod@4.6.7) '@types/node': specifier: 'catalog:' version: 26.6.5 @@ -251,6 +257,9 @@ importers: electron-builder: specifier: ^26.15.3 version: 26.15.3(electron-builder-squirrel-windows@26.15.3)(supports-color@7.2.0) + electron-store: + specifier: 8.2.0 + version: 8.2.0 typescript: specifier: 'catalog:' version: 7.0.2 @@ -294,9 +303,15 @@ importers: apps/web: dependencies: + '@clerk/electron': + specifier: 0.1.10 + version: 0.1.10(@types/react@19.3.0)(electron-store@8.2.0)(electron@44.4.2(supports-color@7.2.0))(preact-render-to-string@6.6.5)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(typescript@7.0.2)(use-sync-external-store@1.7.0(react@19.3.1))(zod@4.6.7) '@codeworksh/contract': specifier: workspace:* version: link:../contract + '@codeworksh/schema': + specifier: workspace:* + version: link:../../packages/schema '@codeworksh/widget': specifier: workspace:* version: link:../widget @@ -306,6 +321,9 @@ importers: '@fontsource-variable/inter': specifier: ^5.3.0 version: 5.3.0 + '@fontsource-variable/lilex': + specifier: 5.3.0 + version: 5.3.0 '@legendapp/list': specifier: 3.3.5 version: 3.3.5(patch_hash=6cbdacd8c380d9a5afb9f73d4198dc2cc44be6ef28a955b1183c781469307896)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) @@ -411,6 +429,10 @@ importers: version: 0.3.1(@opentelemetry/api@1.9.1)(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(typescript@7.0.2)(yaml@2.9.1) apps/widget: + dependencies: + '@codeworksh/schema': + specifier: workspace:* + version: link:../../packages/schema devDependencies: '@phosphor-icons/react': specifier: 2.1.10 @@ -493,13 +515,41 @@ importers: version: 26.6.5 alchemy: specifier: 2.0.0-beta.81 - version: 2.0.0-beta.81(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@types/node@26.6.5)(@types/react@19.3.0)(effect@4.0.5)(hono@4.11.4)(typescript@7.0.2)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))(ws@8.22.0) + version: 2.0.0-beta.81(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@effect/sql-pg@4.0.5(effect@4.0.5))(@types/node@26.6.5)(@types/react@19.3.0)(effect@4.0.5)(hono@4.11.4)(typescript@7.0.2)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))(ws@8.22.0) + effect: + specifier: 4.0.5 + version: 4.0.5 + typescript: + specifier: 'catalog:' + version: 7.0.2 + + infra/relay: + dependencies: + '@clerk/backend': + specifier: 3.27.0 + version: 3.27.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@codeworksh/schema': + specifier: workspace:* + version: link:../../packages/schema + '@effect/platform-node': + specifier: 4.0.5 + version: 4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)) + '@effect/sql-pg': + specifier: 4.0.5 + version: 4.0.5(effect@4.0.5) effect: specifier: 4.0.5 version: 4.0.5 + devDependencies: + '@types/node': + specifier: 'catalog:' + version: 26.6.5 typescript: specifier: 'catalog:' version: 7.0.2 + vite-plus: + specifier: 'catalog:' + version: 0.3.1(@opentelemetry/api@1.9.1)(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(typescript@7.0.2)(yaml@2.9.1) packages/aikit: dependencies: @@ -592,6 +642,9 @@ importers: specifier: 4.6.5 version: 4.6.5 devDependencies: + '@codeworksh/schema': + specifier: workspace:* + version: link:../schema '@types/node': specifier: 'catalog:' version: 26.6.5 @@ -719,6 +772,16 @@ importers: specifier: 4.0.5 version: 4.0.5 + packages/schema: + dependencies: + effect: + specifier: 4.0.5 + version: 4.0.5 + devDependencies: + typescript: + specifier: 'catalog:' + version: 7.0.2 + sites/www: dependencies: '@astrojs/markdown-remark': @@ -726,7 +789,7 @@ importers: version: 7.3.3(supports-color@7.2.0) '@astrojs/mdx': specifier: ^8.0.1 - version: 8.1.0(@astrojs/markdown-remark@7.3.3(supports-color@7.2.0))(@astrojs/markdown-satteri@0.4.4)(astro@7.4.0(@astrojs/markdown-remark@7.3.3(supports-color@7.2.0))(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) + version: 8.1.0(@astrojs/markdown-remark@7.3.3(supports-color@7.2.0))(@astrojs/markdown-satteri@0.4.4)(astro@7.4.0(@astrojs/markdown-remark@7.3.3(supports-color@7.2.0))(@types/node@26.6.5)(esbuild@0.28.2)(idb-keyval@6.2.1)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) '@astrojs/react': specifier: ^6.0.6 version: 6.0.6(@types/node@26.6.5)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(esbuild@0.28.2)(jiti@2.7.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(supports-color@7.2.0)(tsx@4.23.15)(yaml@2.9.1) @@ -747,7 +810,7 @@ importers: version: 4.3.3(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) astro: specifier: ^7.3.3 - version: 7.4.0(@astrojs/markdown-remark@7.3.3(supports-color@7.2.0))(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) + version: 7.4.0(@astrojs/markdown-remark@7.3.3(supports-color@7.2.0))(@types/node@26.6.5)(esbuild@0.28.2)(idb-keyval@6.2.1)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) fumadocs-core: specifier: ^16.15.13 version: 16.17.5(@mdx-js/mdx@3.1.1(supports-color@7.2.0))(@modelcontextprotocol/server@2.0.0)(@tanstack/react-router@1.170.44(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/estree-jsx@1.0.5)(@types/hast@3.0.5)(@types/mdast@4.0.4)(@types/react@19.3.0)(lucide-react@1.58.0(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(supports-color@7.2.0)(zod@4.6.7) @@ -772,7 +835,7 @@ importers: devDependencies: '@alchemy.run/cloudflare': specifier: 2.0.0-beta.84 - version: 2.0.0-beta.84(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@types/node@26.6.5)(alchemy@2.0.0-beta.84(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@types/react@19.3.0)(effect@4.0.5)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))(ws@8.22.0))(effect@4.0.5)(typescript@6.0.3)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) + version: 2.0.0-beta.84(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@effect/sql-pg@4.0.5(effect@4.0.5))(@types/node@26.6.5)(alchemy@2.0.0-beta.84(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@types/react@19.3.0)(effect@4.0.5)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))(ws@8.22.0))(effect@4.0.5)(typescript@6.0.3)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) '@astrojs/check': specifier: ^0.9.10 version: 0.9.10(@emnapi/runtime@1.11.3)(prettier@3.9.10)(typescript@6.0.3) @@ -803,6 +866,9 @@ importers: packages: + '@adraffy/ens-normalize@1.11.1': + resolution: {integrity: sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==} + '@agentclientprotocol/sdk@1.5.1': resolution: {integrity: sha512-nSUIrC1fOR9+ppKfx9KdwjBBND2sAPzFHo4yVQrGbXZHnayUYpwL8CDVR5LSxbapY/oKMOzNP0wvwfyx3PS2KA==} peerDependencies: @@ -1288,6 +1354,9 @@ packages: resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==} engines: {node: '>=6.9.0'} + '@base-org/account@2.0.1': + resolution: {integrity: sha512-tySVNx+vd6XEynZL0uvB10uKiwnAfThr8AbKTwILVG86mPbLAhEOInQIk+uDnvpTvfdUhC1Bi5T/46JvFoLZQQ==} + '@blazediff/core@1.9.1': resolution: {integrity: sha512-ehg3jIkYKulZh+8om/O25vkvSsXXwC+skXmyA87FFx6A/45eqOkZsBltMw/TVteb0mloiGT8oGRTcjRAz66zaA==} @@ -1367,6 +1436,50 @@ packages: resolution: {integrity: sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==} engines: {node: '>= 20.12.0'} + '@clerk/backend@3.27.0': + resolution: {integrity: sha512-pmhVVP9EsAOL1rlRU4xR0XSL1BJczxGAJIqv8c+C9fRz7TYzCndGUMSSE/Zg7i2QOA24ExJbEJUiOjILdUL2EQ==} + engines: {node: '>=20.9.0'} + + '@clerk/clerk-js@6.43.1': + resolution: {integrity: sha512-w/T5c4bbHuppHtOC9ws4NncTU0VIURiXhb1dHOE4StUzmsoOfELoLj31ET0cfjMRr8vb4cnj0qN+0HeLV58Ixg==} + engines: {node: '>=20.9.0'} + + '@clerk/electron@0.1.10': + resolution: {integrity: sha512-Erik4s3N/YqVhOcvB3C+V9uhuimUpT6jlDws8rO4PoRDg1WbNoVbGnc/Z7TNSwfZMj+IzvJbpir/za5tX5Bc4w==} + engines: {node: '>=20.9.0'} + peerDependencies: + '@clerk/electron-passkeys': '*' + electron: '>=28' + electron-store: ^8.2.0 + react: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0 + react-dom: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0 + peerDependenciesMeta: + '@clerk/electron-passkeys': + optional: true + electron-store: + optional: true + react-dom: + optional: true + + '@clerk/react@6.18.8': + resolution: {integrity: sha512-4f/9t9x28JbMueJMPNLUsG/f3Kilzubdz1hnjOj4j6HFLmO48R907+ozWdte1t+Vsj1SJooJBqZj/nIU78JvNw==} + engines: {node: '>=20.9.0'} + peerDependencies: + react: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0 + react-dom: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0 + + '@clerk/shared@4.45.1': + resolution: {integrity: sha512-rAGh+U8dSE6Ov1I3mXysIHaGhxx63ET+24kW4gnmApJvrfU8nq9JT9pQOoyzG3X4PQa93aaAsxkck46CynDeHA==} + engines: {node: '>=20.9.0'} + peerDependencies: + react: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0 + react-dom: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0 + peerDependenciesMeta: + react: + optional: true + react-dom: + optional: true + '@cloudflare/unenv-preset@2.16.2': resolution: {integrity: sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ==} peerDependencies: @@ -1439,6 +1552,9 @@ packages: '@cloudflare/workers-types@5.20261016.1': resolution: {integrity: sha512-I8OJdPl3M6TIl9ksU3wtEyWVhSE8E8txJ/vGOv3SkhjcvN8uMjyFmMvRsNOZgzMe5xYFQ0LctmiGqTwR7DbZ6w==} + '@coinbase/wallet-sdk@4.3.7': + resolution: {integrity: sha512-z6e5XDw6EF06RqkeyEa+qD0dZ2ZbLci99vx3zwDY//XO8X7166tqKJrR2XlQnzVmtcUuJtCd5fCvr9Cu6zzX7w==} + '@daytona/analytics-api-client@0.211.2': resolution: {integrity: sha512-tQgIcZcI7REGxkB8kgANzxoE0ZjedgFhWVZe52r76QQp/ZB/MTPqJ8niFRpdQOMw+AvO4S0RFceitiqEcxOetw==} @@ -1589,6 +1705,11 @@ packages: peerDependencies: effect: ^4.0.5 + '@effect/sql-pg@4.0.5': + resolution: {integrity: sha512-F9tG76H+aryhYcp5pvgd+MwWrNltv3XAuLcZSBsOOX6q+PEl+IM4zkQKzx0TF9OsEMH/SQ+3gZRdYWOsDF+vJQ==} + peerDependencies: + effect: ^4.0.5 + '@effect/sql-sqlite-do@4.0.5': resolution: {integrity: sha512-TGlU65ZJJMa81I7EoicQXxhRsJDxDPz6A/PNOPzMYRgmCdLs6EsTTXIkKZ+8apb7pl2o0OKVcrT6i6mGlluyLg==} peerDependencies: @@ -1929,6 +2050,9 @@ packages: '@fontsource-variable/jetbrains-mono@5.3.0': resolution: {integrity: sha512-F32xpS2NsGYoQi2ADSkKTgpJj7ozajsGgDJ8woTnqjmIB+dxDIqImjl4pXZVEExu8UFZ2ndhmX18EBS/hdz3Lw==} + '@fontsource-variable/lilex@5.3.0': + resolution: {integrity: sha512-jbRNwWELe/QiTulFS30gk22dM0IY5WxSuyJKomqcI5KMfeFdZu4BVzTaQubSAdls7b7NshKDqty6ekzEtp7t7A==} + '@fuma-translate/react@1.0.2': resolution: {integrity: sha512-uOiOtBx3nRXR8Nu1GzBf1tApgF1FErDBTHxRIAQeyQdyOoZbrNRN6H4kDCWObY4qyGeGbHydG0DHzgeUgFDMIw==} peerDependencies: @@ -2297,6 +2421,22 @@ packages: hono: optional: true + '@noble/ciphers@1.3.0': + resolution: {integrity: sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==} + engines: {node: ^14.21.3 || >=16} + + '@noble/curves@1.9.1': + resolution: {integrity: sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA==} + engines: {node: ^14.21.3 || >=16} + + '@noble/curves@1.9.7': + resolution: {integrity: sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==} + engines: {node: ^14.21.3 || >=16} + + '@noble/hashes@1.4.0': + resolution: {integrity: sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg==} + engines: {node: '>= 16'} + '@noble/hashes@1.8.0': resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==} engines: {node: ^14.21.3 || >=16} @@ -4603,6 +4743,15 @@ packages: '@rolldown/pluginutils@1.0.1': resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + '@scure/base@1.2.6': + resolution: {integrity: sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg==} + + '@scure/bip32@1.7.0': + resolution: {integrity: sha512-E4FFX/N3f4B80AKWp5dP6ow+flD1LQZo/w8UnLGYZO674jS6YnYeepycOOksv+vLPSpgN35wgKgy+ybfTb2SMw==} + + '@scure/bip39@1.6.0': + resolution: {integrity: sha512-+lF0BbLiJNwVlev4eKelw1WWLaiKXw7sSl8T6FvBlWkdX+94aGJ4o8XjUdlyhTCjd8c+B3KT3JfS8P0bLRNU6A==} + '@shadcn/lint@0.1.5': resolution: {integrity: sha512-EkKJfJqSrx8lHgsxw9m304//l2cc/bHLH1vjZz1KwPBEv5uU+TQY1UHuzs03+/FiydNtAb5NX9sW4VrV/udNfQ==} engines: {node: '>=20.19'} @@ -4732,9 +4881,19 @@ packages: '@socket.io/component-emitter@3.1.2': resolution: {integrity: sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==} + '@stablelib/base64@1.0.1': + resolution: {integrity: sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==} + '@standard-schema/spec@1.1.0': resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + '@stripe/stripe-js@5.6.0': + resolution: {integrity: sha512-w8CEY73X/7tw2KKlL3iOk679V9bWseE4GzNz3zlaYxcTjmcmWOathRb0emgo/QQ3eoNzmq68+2Y2gxluAv3xGw==} + engines: {node: '>=12.16'} + + '@swc/helpers@0.5.21': + resolution: {integrity: sha512-jI/VAmtdjB/RnI8GTnokyX7Ug8c+g+ffD6QRLa6XQewtnGyukKkKSk3wLTM3b5cjt1jNh9x0jfVlagdN2gDKQg==} + '@szmarczak/http-timer@4.0.6': resolution: {integrity: sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==} engines: {node: '>=10'} @@ -4837,6 +4996,9 @@ packages: resolution: {integrity: sha512-w1+YvwmTkwt5n8yUqEH3IWZ9DsmorCZW/EQ3KYHnqEgIkOZpH54NvW6/Epq3Dzb8H0ifIeYX8PExvrNLIH5FIA==} engines: {node: '>=20.19'} + '@tanstack/query-core@5.107.1': + resolution: {integrity: sha512-PSyAik11oQBEVOiVy5hjZWHmoUqOXqK1WYy4v55mcxozEfKaQgpUMsgnXhWjuESzSht8JfzqMS1m6M/9CpNgvg==} + '@tanstack/react-router@1.170.44': resolution: {integrity: sha512-uIIZ3CHU1yWlkMkmbnGFX3WIfZozF+tNrOMMEoM9lo+jzPInCRq80LBqW3DH9ixNHWjB3TM/cNIvr05uGIlP3A==} engines: {node: '>=20.19'} @@ -5406,6 +5568,31 @@ packages: '@vscode/l10n@0.0.18': resolution: {integrity: sha512-KYSIHVmslkaCDyw013pphY+d7x1qV8IZupYfeIfzNA+nsaWHbn5uPuQRvdRFsa9zFzGeudPuoGoZ1Op4jrJXIQ==} + '@wallet-standard/app@1.1.1': + resolution: {integrity: sha512-WDGwoByhP5gwHH01r5EaLgQdLVkACPCdOMQhmhn8rsm10h/siSgTorShzBxrn0ExSPof+Lu+C3TfgqBrPa1xoQ==} + engines: {node: '>=22'} + + '@wallet-standard/base@1.1.1': + resolution: {integrity: sha512-gggIHTtxicF9XFMQ12DkfS6NAG92Ak795JeSA7f2whAQ6Y3AkMWWuCMxSZXG2NIPN42kEaZSNVjqMsJRaJRxMQ==} + engines: {node: '>=22'} + + '@wallet-standard/core@1.1.1': + resolution: {integrity: sha512-5Xmjc6+Oe0hcPfVc5n8F77NVLwx1JVAoCVgQpLyv/43/bhtIif+Gx3WUrDlaSDoM8i2kA2xd6YoFbHCxs+e0zA==} + engines: {node: '>=16'} + + '@wallet-standard/errors@0.1.2': + resolution: {integrity: sha512-oEzKUqJefKby6wcIvaJgrSEe/uNn/rnqkJ0P/85K+h0i5Tdo9E3L22VWq/j5K1e8hHMnZd6LgaIr8m/Wn7X/Ng==} + engines: {node: '>=22'} + hasBin: true + + '@wallet-standard/features@1.1.1': + resolution: {integrity: sha512-aCWYmVeSCGViyEU5k7GMoW8zxE4Gs+C1s1Pp2XLesvSNlnZ4PMES9HUnTB3hl0b3RVj7C61yze3IWyrncqg4MA==} + engines: {node: '>=22'} + + '@wallet-standard/wallet@1.1.1': + resolution: {integrity: sha512-8WiRPaKk/wNNRZhB2eVhpR/JW7/aqTCMoZhgVUCujuzDmxxmGvsosMxdCG4NAdYkoyozAHCX8/xLtlWUn5mNdQ==} + engines: {node: '>=22'} + '@webgpu/types@0.1.74': resolution: {integrity: sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA==} @@ -5578,6 +5765,12 @@ packages: '@yuku-toolchain/types@0.9.5': resolution: {integrity: sha512-KiuLNNgX9uNealaWAR+G3/cMXnRk9x4TY2EkYe/KIag+UPdwiA0RRf1hr1WAxzTP8KGzCTkqUdLPvqh32sEO3w==} + '@zxcvbn-ts/core@3.0.4': + resolution: {integrity: sha512-aQeiT0F09FuJaAqNrxynlAwZ2mW/1MdXakKWNmGM1Qp/VaY6CnB/GfnMS2T8gB2231Esp1/maCWd8vTG4OuShw==} + + '@zxcvbn-ts/language-common@3.0.4': + resolution: {integrity: sha512-viSNNnRYtc7ULXzxrQIVUNwHAPSXRtoIwy/Tq4XQQdIknBzw4vz36lQLF6mvhMlTIlpjoN/Z1GFu/fwiAlUSsw==} + abbrev@4.0.0: resolution: {integrity: sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==} engines: {node: ^20.17.0 || >=22.9.0} @@ -5586,6 +5779,28 @@ packages: resolution: {integrity: sha512-/XrFJgzQQQHpti1raDJC6m4ws6aNktmjBlhk8Fdlk7LwCEuDoieEJJY9OFHjfiFJFFRM2tK+Ky/IsfbbmlMu1w==} engines: {node: ^22.22.2 || ^24.15.0 || >=26.0.0} + abitype@1.2.3: + resolution: {integrity: sha512-Ofer5QUnuUdTFsBRwARMoWKOH1ND5ehwYhJ3OJ/BQO+StkwQjHw0XyVh4vDttzHB7QOFhPHa/o413PJ82gU/Tg==} + peerDependencies: + typescript: '>=5.0.4' + zod: ^3.22.0 || ^4.0.0 + peerDependenciesMeta: + typescript: + optional: true + zod: + optional: true + + abitype@1.3.0: + resolution: {integrity: sha512-fk6Te+bojIFrMvMZrnOO+SxCB+RUksTGOzq/60ZRvs1L+BVzvi2bqt9L3W/17ZLdZsyM1FuYf65P5nlmoiH1Bg==} + peerDependencies: + typescript: '>=5.0.4' + zod: ^3.22.0 || ^4.0.0 + peerDependenciesMeta: + typescript: + optional: true + zod: + optional: true + acorn-jsx@5.3.2: resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} peerDependencies: @@ -5622,6 +5837,9 @@ packages: ajv: optional: true + ajv-formats@2.1.1: + resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==} + ajv-i18n@4.2.0: resolution: {integrity: sha512-v/ei2UkCEeuKNXh8RToiFsUclmU+G57LO1Oo22OagNMENIw+Yb8eMwvHu7Vn9fmkjJyv6XclhJ8TbuigSglPkg==} peerDependencies: @@ -5713,6 +5931,9 @@ packages: ws: optional: true + alien-signals@2.0.6: + resolution: {integrity: sha512-P3TxJSe31bUHBiblg59oU1PpaWPtmxF9GhJ/cB7OkgJ0qN/ifFSKUI25/v8ZhsT+lIG6ac8DpTOplXxORX6F3Q==} + am-i-vibing@0.5.0: resolution: {integrity: sha512-KLcsDhqf1XRrJmJr+9I/C0EX2K+sGrAGZFgkmd84c8TJO9zJBu+/kFInjazu1KfJWFhWDKdRWkpBzEs7s35DVA==} hasBin: true @@ -5817,6 +6038,10 @@ packages: resolution: {integrity: sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==} engines: {node: '>= 4.0.0'} + atomically@1.7.0: + resolution: {integrity: sha512-Xcz9l0z7y9yQ9rdDaxlmaI4uJHf/T8g9hOEzJcsEqX2SjCj4J20uK7+ldkDHMbpJDK76wF7xEIgxc/vSlsfw5w==} + engines: {node: '>=10.12.0'} + aws4@1.13.2: resolution: {integrity: sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==} @@ -5904,6 +6129,9 @@ packages: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} engines: {node: '>=8'} + browser-tabs-lock@1.3.0: + resolution: {integrity: sha512-g6nHaobTiT0eMZ7jh16YpD2kcjAp+PInbiVq3M1x6KKaEIVhT4v9oURNIpZLOZ3LQbQ3XYfNhMAb/9hzNLIWrw==} + browserslist@4.29.3: resolution: {integrity: sha512-1R4kiYKXGViqEN0CnoDrXc1StD9niAwu+j2dukWzrD4bJgsD4lDmEp0CRbc6E/vYJIfTHwPmwyaKtVSudICdPA==} engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} @@ -5988,6 +6216,10 @@ packages: resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} engines: {node: '>=10'} + chalk@5.6.2: + resolution: {integrity: sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==} + engines: {node: ^12.17.0 || ^14.13 || >=16.0.0} + character-entities-html4@2.1.0: resolution: {integrity: sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==} @@ -6046,6 +6278,10 @@ packages: clone-response@1.0.3: resolution: {integrity: sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA==} + clsx@1.2.1: + resolution: {integrity: sha512-EcR6r5a8bj6pu3ycsa/E/cKVGuTgZJZdsyUYHOksG/UHIiKfjxzRxYJpyVBwYaQeOvghal9fcc4PidlgzugAQg==} + engines: {node: '>=6'} + clsx@2.1.1: resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} engines: {node: '>=6'} @@ -6091,6 +6327,10 @@ packages: resolution: {integrity: sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==} engines: {node: '>=16'} + commander@13.1.0: + resolution: {integrity: sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==} + engines: {node: '>=18'} + commander@5.1.0: resolution: {integrity: sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==} engines: {node: '>= 6'} @@ -6117,6 +6357,10 @@ packages: concat-map@0.0.1: resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} + conf@10.2.0: + resolution: {integrity: sha512-8fLl9F04EJqjSqH+QjITQfJF8BrOVaYr1jewVgSRAEWePfxT0sku4w2hrGQ60BC/TNLGQ2pgxNlTbWQmMPFvXg==} + engines: {node: '>=12'} + content-type@2.1.0: resolution: {integrity: sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==} engines: {node: '>=18'} @@ -6138,6 +6382,9 @@ packages: resolution: {integrity: sha512-yuToqVvRrj6pfDXREyQAAv8SkAEk/8GS3jQRTiUMm66TVtBYmqQeoEjL2Lmq8Rpo6271vH76InTChTitEAm65w==} engines: {node: '>=22'} + core-js@3.47.0: + resolution: {integrity: sha512-c3Q2VVkGAUyupsjRnaNX6u8Dq2vAdzm9iuPj5FW0fRxzlxgq9Q39MDq10IvmQSpLgHQNyQzQmOo6bgGHmH3NNg==} + core-util-is@1.0.3: resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==} @@ -6151,6 +6398,10 @@ packages: crossws@0.3.5: resolution: {integrity: sha512-ojKiDvcmByhwa8YYqbQI/hg7MEU0NC03+pSdEq4ZUnZR9xXpwk7E43SMNGkn+JxJGPFtNvQ48+vV2p+P1ml5PA==} + crypto-js@4.2.0: + resolution: {integrity: sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==} + deprecated: Active development of CryptoJS has been discontinued. This library is no longer maintained. + css-select@6.0.0: resolution: {integrity: sha512-rZZVSLle8v0+EY8QAkDWrKhpgt6SA5OtHsgBnsj6ZaLb5dmDVOWUDtQitd9ydxxvEjhewNudS6eTVU7uOyzvXw==} @@ -6182,6 +6433,10 @@ packages: resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==} engines: {node: '>= 12'} + debounce-fn@4.0.0: + resolution: {integrity: sha512-8pYCQiL9Xdcg0UPSD3d+0KMlOjp+KGU5EPwYddgzQ7DATsg4fuUDjQtsYLmWjnk2obnNHgV3vE2Y4jejSOJVBQ==} + engines: {node: '>=10'} + debug@4.4.3: resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} engines: {node: '>=6.0'} @@ -6290,6 +6545,10 @@ packages: domutils@3.2.2: resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==} + dot-prop@6.0.1: + resolution: {integrity: sha512-tE7ztYzXHIeyvc7N+hR3oi7FIbf/NIjVP9hmAt3yMXzrQ072/fpjGLx2GxNxGxUl5V73MEqYzioOMoVhGMJ5cA==} + engines: {node: '>=10'} + dotenv-expand@11.0.7: resolution: {integrity: sha512-zIHwmZPRshsCdpMDyVsqGmgyP0yT8GAgXUnkdAoJisxvf33k7yO6OuoKmcTGuXPWSsm8Oh88nZicRLA9Y0rUeA==} engines: {node: '>=12'} @@ -6335,6 +6594,9 @@ packages: electron-publish@26.15.3: resolution: {integrity: sha512-g/2bn8YTavY4cuS5F+jOS7zmZbXXBV8KZ8yHKfJjFPoKtzBqrpCdNPxBd3tqdBwP7BVd0lGzf7Bk2s0KesWZ4Q==} + electron-store@8.2.0: + resolution: {integrity: sha512-ukLL5Bevdil6oieAOXz3CMy+OgaItMiVBg701MNlG6W5RaC0AHN7rvlqTCmeb6O7jP0Qa1KKYTE0xV0xbhF4Hw==} + electron-to-chromium@1.5.458: resolution: {integrity: sha512-/hIH2gRSmxrf4/X4Nw/t/Wc8PVS22l8/3HnWjWTWsTOM5dsnMUPZF/+u+yr3LqweNuTBJE1rq6qAQzKkZVwMfA==} @@ -6474,6 +6736,9 @@ packages: estree-walker@3.0.3: resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + eventemitter3@5.0.1: + resolution: {integrity: sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==} + eventemitter3@5.0.4: resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==} @@ -6528,6 +6793,9 @@ packages: resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==} engines: {node: '>=8.6.0'} + fast-sha256@1.3.0: + resolution: {integrity: sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==} + fast-string-truncated-width@3.0.3: resolution: {integrity: sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==} @@ -6547,6 +6815,10 @@ packages: resolution: {integrity: sha512-R9iDuNrQYeQut46cn2r2wHKn4HYzVDvDm5J1wW+koZewykv0yuO2HChTYeZtrULyHIDM9cj9TUXloCsueCQUog==} hasBin: true + fastest-levenshtein@1.0.16: + resolution: {integrity: sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==} + engines: {node: '>= 4.9.1'} + fastq@1.20.3: resolution: {integrity: sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==} @@ -6580,6 +6852,10 @@ packages: resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} engines: {node: '>=8'} + find-up@3.0.0: + resolution: {integrity: sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==} + engines: {node: '>=6'} + flattie@1.1.1: resolution: {integrity: sha512-9UbaD6XdAL97+k/n+N7JwX46K/M6Zc6KcFYskrYL8wbBV/Uyk0CTAMY0VT+qiK5PM7AIc9aTWYtq65U7T+aCNQ==} engines: {node: '>=8'} @@ -6821,6 +7097,9 @@ packages: resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} engines: {node: '>= 6'} + glob-to-regexp@0.4.1: + resolution: {integrity: sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==} + glob@13.0.6: resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==} engines: {node: 18 || 20 || >=22} @@ -6994,6 +7273,9 @@ packages: resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==} engines: {node: '>=0.10.0'} + idb-keyval@6.2.1: + resolution: {integrity: sha512-8Sb3veuYCyrZL+VBt9LJfZjLUPWVvqn8tG28VqYNFCo43KHcKuq+b4EiXGeuaLAQWL2YmyDgMp2aSpH9JHsEQg==} + ieee754@1.2.1: resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} @@ -7074,6 +7356,10 @@ packages: resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} engines: {node: '>=0.12.0'} + is-obj@2.0.0: + resolution: {integrity: sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w==} + engines: {node: '>=8'} + is-plain-obj@4.1.0: resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==} engines: {node: '>=12'} @@ -7116,6 +7402,11 @@ packages: peerDependencies: ws: '*' + isows@1.0.7: + resolution: {integrity: sha512-I1fSfDCZL5P0v33sVqeTDSpcstAg/N+wF5HS033mogOVIp4B+oHC7oOCsA3axAbBSGTJ8QubbNmnIRN/h8U7hg==} + peerDependencies: + ws: '*' + jake@10.9.4: resolution: {integrity: sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==} engines: {node: '>=10'} @@ -7134,6 +7425,9 @@ packages: js-base64@3.9.4: resolution: {integrity: sha512-PtOMXpEGuP0RRiRXsjzHzl44dMHxSu2CPvAhinupR1tBa88me+1DPqsobl7eupn5UukjLkln1ZnAOAOXOrYG0Q==} + js-cookie@3.0.8: + resolution: {integrity: sha512-yeJd4aNAdYZQjaon2bpD/Gb0B/omw7HQOsynXXcOiWVCacbBcPlgn8S/d1X6blFSaHao7ozqtW7NZW19xpCtIw==} + js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} @@ -7159,6 +7453,9 @@ packages: json-schema-traverse@1.0.0: resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==} + json-schema-typed@7.0.3: + resolution: {integrity: sha512-7DE8mpG+/fVw+dTpjbxnx47TaMnDfOI1jwft9g1VybltZCduyRQPJPvc+zzKY9WPHxhPWczyFuYa6I8Mw4iU5A==} + json-schema@0.4.0: resolution: {integrity: sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==} @@ -7390,6 +7687,10 @@ packages: resolution: {integrity: sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ==} engines: {node: '>=10'} + locate-path@3.0.0: + resolution: {integrity: sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==} + engines: {node: '>=6'} + lodash.camelcase@4.3.0: resolution: {integrity: sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==} @@ -7665,6 +7966,10 @@ packages: resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==} engines: {node: '>=6'} + mimic-fn@3.1.0: + resolution: {integrity: sha512-Ysbi9uYW9hFyfrThdDEQuykN4Ey6BuwPD2kpI5ES/nFTDn/98yxYNLZJcgUAKPT/mcrLLKaGzJR9YVxJrIdASQ==} + engines: {node: '>=8'} + mimic-response@1.0.1: resolution: {integrity: sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==} engines: {node: '>=4'} @@ -7938,6 +8243,22 @@ packages: resolution: {integrity: sha512-wrAwOeXp1RRMFfQY8Sy7VaGVmPocaLwSFOYCGKSyo8qmJ+/yaafCl5BCA1IQZWqFSRBrKDYFeR9d/VyQzfH/jg==} engines: {node: '>= 6.0'} + ox@0.14.67: + resolution: {integrity: sha512-6v6UlwgsmiyTujZp0aVDuN8uIBAtl/QZadBADFRZ2zp1+CM9TqDzd+rPKJ5PYvWPlCvz8JvoO9dTr42+1PhBhA==} + peerDependencies: + typescript: '>=5.4.0' + peerDependenciesMeta: + typescript: + optional: true + + ox@0.6.9: + resolution: {integrity: sha512-wi5ShvzE4eOcTwQVsIPdFr+8ycyX+5le/96iAJutaZAvCes1J0+RvpEPg5QDPDiaR0XQQAvZVl7AwqQcINuUug==} + peerDependencies: + typescript: '>=5.4.0' + peerDependenciesMeta: + typescript: + optional: true + oxc-parser@0.147.0: resolution: {integrity: sha512-5xaug6t7GfV3BO5Iv+xHW1rmQkDEQ3BEu3L8g3InsvWO5i8CYGc4tCZ2X985QcwWNycFJam+aOns6Nr2XAThTA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -7987,6 +8308,10 @@ packages: resolution: {integrity: sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==} engines: {node: '>=8'} + p-limit@2.3.0: + resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==} + engines: {node: '>=6'} + p-limit@3.1.0: resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} engines: {node: '>=10'} @@ -7995,6 +8320,10 @@ packages: resolution: {integrity: sha512-SKgVvDU5TNIxQ4r30U75BNLC6a+6GOEjngrk/ysM5+Zu3oJuk1SC5ApzIzY/7PjCEjoVPMWJ0zho/4QUiEB7TQ==} engines: {node: '>=20'} + p-locate@3.0.0: + resolution: {integrity: sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==} + engines: {node: '>=6'} + p-map@7.1.1: resolution: {integrity: sha512-6Lh3jQPLthYujSrlw6ccWXBGZTkoTCz27Hd92g79LH/kjAbgoEu0t442cCCNbegPSJsA0lwDX8z0bcKtkpA32g==} engines: {node: '>=18'} @@ -8007,6 +8336,10 @@ packages: resolution: {integrity: sha512-prbX4Z3YszrFNgH+MW5Zoeq3baXrMtP/MQnFeET90UB/GtGcGDQ5Usg9OCy6ETjTTntOw1SL2z9fMPUppN3Guw==} engines: {node: '>=20'} + p-try@2.2.0: + resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==} + engines: {node: '>=6'} + package-manager-detector@1.9.0: resolution: {integrity: sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA==} @@ -8041,6 +8374,10 @@ packages: path-browserify@1.0.1: resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==} + path-exists@3.0.0: + resolution: {integrity: sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==} + engines: {node: '>=4'} + path-expression-matcher@1.6.2: resolution: {integrity: sha512-enSlaiat05iasnzmgNxRj8reFdj3puY2QpNgP1aPIaVfT6nn9ICuPoFlKHk8EN22HcwewshO+mN2DGbkCEOtqQ==} engines: {node: '>=14.0.0'} @@ -8089,6 +8426,10 @@ packages: resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==} engines: {node: '>=16.20.0'} + pkg-up@3.1.0: + resolution: {integrity: sha512-nDywThFk1i4BQK4twPQ6TA4RT8bDY96yeuCVBWL3ePARCiEKDRSrNGbFIgUJpLp+XeIR65v8ra7WuJOFUBtkMA==} + engines: {node: '>=8'} + pkijs@3.4.1: resolution: {integrity: sha512-Oo/NZcSWccq8KyoG7gLE9fnltgHns+pNCjCAp/WmjsUySi+sX7y4z4Xqu4fVb42CDHzRPl33fjzT15V1wvcyhA==} engines: {node: '>=16.0.0'} @@ -8119,6 +8460,17 @@ packages: peerDependencies: preact: '>=10 || >= 11.0.0-0' + preact@10.24.2: + resolution: {integrity: sha512-1cSoF0aCC8uaARATfrlz4VCBqE8LwZwRfLgkxJOQwAlQt6ayTmi0D9OF7nXid1POI5SZidFuG9CnlXbDfLqY/Q==} + + preact@10.29.8: + resolution: {integrity: sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q==} + peerDependencies: + preact-render-to-string: '>=5' + peerDependenciesMeta: + preact-render-to-string: + optional: true + preact@11.0.0-beta.0: resolution: {integrity: sha512-IcODoASASYwJ9kxz7+MJeiJhvLriwSb4y4mHIyxdgaRZp6kPUud7xytrk/6GZw8U3y6EFJaRb5wi9SrEK+8+lg==} @@ -8687,6 +9039,9 @@ packages: stackback@0.0.2: resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + standardwebhooks@1.1.1: + resolution: {integrity: sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==} + stat-mode@1.0.0: resolution: {integrity: sha512-jH9EhtKIjuXZ2cWxmXS8ZP80XyC3iasQxMDV8jzhNJpfDb7VbQLVW4Wvsxz9QZvzV+G4YoSfBUVKDOyxLzi/sg==} engines: {node: '>= 6'} @@ -8923,6 +9278,10 @@ packages: resolution: {integrity: sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==} engines: {node: '>=10'} + type-fest@2.19.0: + resolution: {integrity: sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA==} + engines: {node: '>=12.20'} + typebox@1.4.0: resolution: {integrity: sha512-fn+ul/Cox0pYuGHN2WoehRhHUTJ3aj22Cn56c4AmLxELiwSoO6g2Fg6hpkOKIdCdRc16TN5N47Sdq7KDQIQqgA==} @@ -9230,6 +9589,17 @@ packages: three: optional: true + viem@2.57.20: + resolution: {integrity: sha512-LSvREzKT7xFXpmxW2YFJ/OtcZRkSGLp5zywSgadBf0qQCeqh2+FxHHWyrS2zEG7ZfBWQQvk8HI1i4HPzSMD14g==} + peerDependencies: + mppx: '>=0.17.0' + typescript: '>=5.0.4' + peerDependenciesMeta: + mppx: + optional: true + typescript: + optional: true + vite-plus@0.3.1: resolution: {integrity: sha512-U8KZ3c3mbX0qLfigx9rW2W9J73w9wjdf4s/s91H77ff5afqSYEdZd8Or41Jl99kD42a+UCL3LFXzb5b+bIBCpQ==} engines: {node: ^20.19.0 || ^22.18.0 || >=24.11.0} @@ -9525,6 +9895,18 @@ packages: resolution: {integrity: sha512-dYwyZredl67GyLLIHJnRM3h2PcOmN5SkcgC7eM5DPDEOEl6dLFqVrMg3F1Ea32usj4VSVZtd2H4MtKTNOf6nPg==} engines: {node: ^22.22.2 || ^24.15.0 || >=26.0.0} + ws@8.21.0: + resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + ws@8.21.3: resolution: {integrity: sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==} engines: {node: '>=10.0.0'} @@ -9653,11 +10035,31 @@ packages: zod@4.6.7: resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==} + zustand@5.0.3: + resolution: {integrity: sha512-14fwWQtU3pH4dE0dOpdMiWjddcH+QzKIgk1cl8epwSE7yag43k/AD/m4L6+K7DytAOr9gGBe3/EXj9g7cdostg==} + engines: {node: '>=12.20.0'} + peerDependencies: + '@types/react': '>=18.0.0' + immer: '>=9.0.6' + react: '>=18.0.0' + use-sync-external-store: '>=1.2.0' + peerDependenciesMeta: + '@types/react': + optional: true + immer: + optional: true + react: + optional: true + use-sync-external-store: + optional: true + zwitch@2.0.4: resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==} snapshots: + '@adraffy/ens-normalize@1.11.1': {} + '@agentclientprotocol/sdk@1.5.1(zod@4.6.5)': dependencies: zod: 4.6.5 @@ -9778,12 +10180,12 @@ snapshots: - proxy-agent - typescript - '@alchemy.run/cloudflare@2.0.0-beta.84(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@types/node@26.6.5)(alchemy@2.0.0-beta.84(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@types/react@19.3.0)(effect@4.0.5)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))(ws@8.22.0))(effect@4.0.5)(typescript@6.0.3)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))': + '@alchemy.run/cloudflare@2.0.0-beta.84(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@effect/sql-pg@4.0.5(effect@4.0.5))(@types/node@26.6.5)(alchemy@2.0.0-beta.84(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@types/react@19.3.0)(effect@4.0.5)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))(ws@8.22.0))(effect@4.0.5)(typescript@6.0.3)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))': dependencies: '@alchemy.run/acme': 2.0.0-beta.84(alchemy@2.0.0-beta.84(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@types/react@19.3.0)(effect@4.0.5)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))(ws@8.22.0))(effect@4.0.5) '@alchemy.run/cloudflare-runtime': 2.0.0-beta.84(@distilled.cloud/cloudflare@1.0.0-rc.17(effect@4.0.5))(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@types/node@26.6.5)(effect@4.0.5)(rolldown@1.2.13)(typescript@6.0.3)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) '@alchemy.run/docker': 2.0.0-beta.84(@effect/platform-bun@4.0.5(effect@4.0.5))(alchemy@2.0.0-beta.84(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@types/react@19.3.0)(effect@4.0.5)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))(ws@8.22.0))(effect@4.0.5) - '@alchemy.run/sql': 2.0.0-beta.84(alchemy@2.0.0-beta.84(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@types/react@19.3.0)(effect@4.0.5)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))(ws@8.22.0))(effect@4.0.5) + '@alchemy.run/sql': 2.0.0-beta.84(@effect/sql-pg@4.0.5(effect@4.0.5))(alchemy@2.0.0-beta.84(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@types/react@19.3.0)(effect@4.0.5)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))(ws@8.22.0))(effect@4.0.5) '@distilled.cloud/aws4signer': 1.0.0-rc.17(effect@4.0.5) '@distilled.cloud/cloudflare': 1.0.0-rc.17(effect@4.0.5) '@distilled.cloud/core': 1.0.0-rc.17(effect@4.0.5) @@ -9834,10 +10236,12 @@ snapshots: optionalDependencies: '@types/react': 19.3.0 - '@alchemy.run/sql@2.0.0-beta.84(alchemy@2.0.0-beta.84(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@types/react@19.3.0)(effect@4.0.5)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))(ws@8.22.0))(effect@4.0.5)': + '@alchemy.run/sql@2.0.0-beta.84(@effect/sql-pg@4.0.5(effect@4.0.5))(alchemy@2.0.0-beta.84(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@types/react@19.3.0)(effect@4.0.5)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))(ws@8.22.0))(effect@4.0.5)': dependencies: alchemy: 2.0.0-beta.84(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@types/react@19.3.0)(effect@4.0.5)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))(ws@8.22.0) effect: 4.0.5 + optionalDependencies: + '@effect/sql-pg': 4.0.5(effect@4.0.5) '@astrojs/astro2tsx@0.1.3(@emnapi/runtime@1.11.3)': dependencies: @@ -9990,11 +10394,11 @@ snapshots: github-slugger: 2.0.0 satteri: 0.10.5 - '@astrojs/mdx@8.1.0(@astrojs/markdown-remark@7.3.3(supports-color@7.2.0))(@astrojs/markdown-satteri@0.4.4)(astro@7.4.0(@astrojs/markdown-remark@7.3.3(supports-color@7.2.0))(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))': + '@astrojs/mdx@8.1.0(@astrojs/markdown-remark@7.3.3(supports-color@7.2.0))(@astrojs/markdown-satteri@0.4.4)(astro@7.4.0(@astrojs/markdown-remark@7.3.3(supports-color@7.2.0))(@types/node@26.6.5)(esbuild@0.28.2)(idb-keyval@6.2.1)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))': dependencies: '@astrojs/internal-helpers': 0.13.0 '@astrojs/markdown-satteri': 0.4.4 - astro: 7.4.0(@astrojs/markdown-remark@7.3.3(supports-color@7.2.0))(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) + astro: 7.4.0(@astrojs/markdown-remark@7.3.3(supports-color@7.2.0))(@types/node@26.6.5)(esbuild@0.28.2)(idb-keyval@6.2.1)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) es-module-lexer: 3.0.4 optionalDependencies: '@astrojs/markdown-remark': 7.3.3(supports-color@7.2.0) @@ -10340,6 +10744,27 @@ snapshots: '@babel/helper-string-parser': 7.29.7 '@babel/helper-validator-identifier': 7.29.7 + '@base-org/account@2.0.1(@types/react@19.3.0)(react@19.3.1)(typescript@7.0.2)(use-sync-external-store@1.7.0(react@19.3.1))(zod@4.6.7)': + dependencies: + '@noble/hashes': 1.4.0 + clsx: 1.2.1 + eventemitter3: 5.0.1 + idb-keyval: 6.2.1 + ox: 0.6.9(typescript@7.0.2)(zod@4.6.7) + preact: 10.24.2 + viem: 2.57.20(typescript@7.0.2)(zod@4.6.7) + zustand: 5.0.3(@types/react@19.3.0)(react@19.3.1)(use-sync-external-store@1.7.0(react@19.3.1)) + transitivePeerDependencies: + - '@types/react' + - bufferutil + - immer + - mppx + - react + - typescript + - use-sync-external-store + - utf-8-validate + - zod + '@blazediff/core@1.9.1': {} '@borewit/text-codec@0.2.2': {} @@ -10406,6 +10831,80 @@ snapshots: fast-wrap-ansi: 0.2.2 sisteransi: 1.0.5 + '@clerk/backend@3.27.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@clerk/shared': 4.45.1(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + standardwebhooks: 1.1.1 + transitivePeerDependencies: + - react + - react-dom + + '@clerk/clerk-js@6.43.1(@types/react@19.3.0)(preact-render-to-string@6.6.5)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(typescript@7.0.2)(use-sync-external-store@1.7.0(react@19.3.1))(zod@4.6.7)': + dependencies: + '@base-org/account': 2.0.1(@types/react@19.3.0)(react@19.3.1)(typescript@7.0.2)(use-sync-external-store@1.7.0(react@19.3.1))(zod@4.6.7) + '@clerk/shared': 4.45.1(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@coinbase/wallet-sdk': 4.3.7(preact-render-to-string@6.6.5)(typescript@7.0.2)(zod@4.6.7) + '@stripe/stripe-js': 5.6.0 + '@swc/helpers': 0.5.21 + '@tanstack/query-core': 5.107.1 + '@wallet-standard/core': 1.1.1 + '@zxcvbn-ts/core': 3.0.4 + '@zxcvbn-ts/language-common': 3.0.4 + alien-signals: 2.0.6 + browser-tabs-lock: 1.3.0 + core-js: 3.47.0 + crypto-js: 4.2.0 + dequal: 2.0.3 + transitivePeerDependencies: + - '@types/react' + - bufferutil + - immer + - mppx + - preact-render-to-string + - react + - react-dom + - typescript + - use-sync-external-store + - utf-8-validate + - zod + + '@clerk/electron@0.1.10(@types/react@19.3.0)(electron-store@8.2.0)(electron@44.4.2(supports-color@7.2.0))(preact-render-to-string@6.6.5)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(typescript@7.0.2)(use-sync-external-store@1.7.0(react@19.3.1))(zod@4.6.7)': + dependencies: + '@clerk/clerk-js': 6.43.1(@types/react@19.3.0)(preact-render-to-string@6.6.5)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(typescript@7.0.2)(use-sync-external-store@1.7.0(react@19.3.1))(zod@4.6.7) + '@clerk/react': 6.18.8(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@clerk/shared': 4.45.1(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + electron: 44.4.2(supports-color@7.2.0) + react: 19.3.1 + optionalDependencies: + electron-store: 8.2.0 + react-dom: 19.3.1(react@19.3.1) + transitivePeerDependencies: + - '@types/react' + - bufferutil + - immer + - mppx + - preact-render-to-string + - typescript + - use-sync-external-store + - utf-8-validate + - zod + + '@clerk/react@6.18.8(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@clerk/shared': 4.45.1(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + + '@clerk/shared@4.45.1(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': + dependencies: + '@tanstack/query-core': 5.107.1 + dequal: 2.0.3 + glob-to-regexp: 0.4.1 + js-cookie: 3.0.8 + optionalDependencies: + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + '@cloudflare/unenv-preset@2.16.2(unenv@2.0.0-rc.24)(workerd@1.20260918.1)': dependencies: unenv: 2.0.0-rc.24 @@ -10450,6 +10949,21 @@ snapshots: '@cloudflare/workers-types@5.20261016.1': {} + '@coinbase/wallet-sdk@4.3.7(preact-render-to-string@6.6.5)(typescript@7.0.2)(zod@4.6.7)': + dependencies: + '@noble/hashes': 1.8.0 + clsx: 1.2.1 + eventemitter3: 5.0.4 + preact: 10.29.8(preact-render-to-string@6.6.5) + viem: 2.57.20(typescript@7.0.2)(zod@4.6.7) + transitivePeerDependencies: + - bufferutil + - mppx + - preact-render-to-string + - typescript + - utf-8-validate + - zod + '@daytona/analytics-api-client@0.211.2(debug@4.4.3(supports-color@7.2.0))(supports-color@7.2.0)': dependencies: axios: 1.20.0(debug@4.4.3(supports-color@7.2.0))(supports-color@7.2.0) @@ -10651,6 +11165,10 @@ snapshots: '@cloudflare/workers-types': 5.20261016.1 effect: 4.0.5 + '@effect/sql-pg@4.0.5(effect@4.0.5)': + dependencies: + effect: 4.0.5 + '@effect/sql-sqlite-do@4.0.5(effect@4.0.5)': dependencies: effect: 4.0.5 @@ -10967,6 +11485,8 @@ snapshots: '@fontsource-variable/jetbrains-mono@5.3.0': {} + '@fontsource-variable/lilex@5.3.0': {} + '@fuma-translate/react@1.0.2(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': dependencies: react: 19.3.1 @@ -11315,6 +11835,18 @@ snapshots: optionalDependencies: hono: 4.11.4 + '@noble/ciphers@1.3.0': {} + + '@noble/curves@1.9.1': + dependencies: + '@noble/hashes': 1.8.0 + + '@noble/curves@1.9.7': + dependencies: + '@noble/hashes': 1.8.0 + + '@noble/hashes@1.4.0': {} + '@noble/hashes@1.8.0': {} '@noble/hashes@2.4.0': {} @@ -13243,6 +13775,19 @@ snapshots: '@rolldown/pluginutils@1.0.1': {} + '@scure/base@1.2.6': {} + + '@scure/bip32@1.7.0': + dependencies: + '@noble/curves': 1.9.7 + '@noble/hashes': 1.8.0 + '@scure/base': 1.2.6 + + '@scure/bip39@1.6.0': + dependencies: + '@noble/hashes': 1.8.0 + '@scure/base': 1.2.6 + '@shadcn/lint@0.1.5': dependencies: '@eslint/core': 0.17.0 @@ -13400,8 +13945,16 @@ snapshots: '@socket.io/component-emitter@3.1.2': {} + '@stablelib/base64@1.0.1': {} + '@standard-schema/spec@1.1.0': {} + '@stripe/stripe-js@5.6.0': {} + + '@swc/helpers@0.5.21': + dependencies: + tslib: 2.8.1 + '@szmarczak/http-timer@4.0.6': dependencies: defer-to-connect: 2.0.1 @@ -13483,6 +14036,8 @@ snapshots: '@tanstack/history@1.162.5': {} + '@tanstack/query-core@5.107.1': {} + '@tanstack/react-router@1.170.44(react-dom@19.3.1(react@19.3.1))(react@19.3.1)': dependencies: '@tanstack/history': 1.162.5 @@ -14043,6 +14598,33 @@ snapshots: '@vscode/l10n@0.0.18': {} + '@wallet-standard/app@1.1.1': + dependencies: + '@wallet-standard/base': 1.1.1 + + '@wallet-standard/base@1.1.1': {} + + '@wallet-standard/core@1.1.1': + dependencies: + '@wallet-standard/app': 1.1.1 + '@wallet-standard/base': 1.1.1 + '@wallet-standard/errors': 0.1.2 + '@wallet-standard/features': 1.1.1 + '@wallet-standard/wallet': 1.1.1 + + '@wallet-standard/errors@0.1.2': + dependencies: + chalk: 5.6.2 + commander: 13.1.0 + + '@wallet-standard/features@1.1.1': + dependencies: + '@wallet-standard/base': 1.1.1 + + '@wallet-standard/wallet@1.1.1': + dependencies: + '@wallet-standard/base': 1.1.1 + '@webgpu/types@0.1.74': {} '@workflow/serde@4.1.0': {} @@ -14125,10 +14707,26 @@ snapshots: '@yuku-toolchain/types@0.9.5': {} + '@zxcvbn-ts/core@3.0.4': + dependencies: + fastest-levenshtein: 1.0.16 + + '@zxcvbn-ts/language-common@3.0.4': {} + abbrev@4.0.0: {} abbrev@5.0.0: {} + abitype@1.2.3(typescript@7.0.2)(zod@4.6.7): + optionalDependencies: + typescript: 7.0.2 + zod: 4.6.7 + + abitype@1.3.0(typescript@7.0.2)(zod@4.6.7): + optionalDependencies: + typescript: 7.0.2 + zod: 4.6.7 + acorn-jsx@5.3.2(acorn@8.19.0): dependencies: acorn: 8.19.0 @@ -14156,6 +14754,10 @@ snapshots: optionalDependencies: ajv: 8.20.0 + ajv-formats@2.1.1: + dependencies: + ajv: 8.20.0 + ajv-i18n@4.2.0(ajv@8.20.0): dependencies: ajv: 8.20.0 @@ -14167,7 +14769,7 @@ snapshots: json-schema-traverse: 1.0.0 require-from-string: 2.0.2 - alchemy@2.0.0-beta.81(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@types/node@26.6.5)(@types/react@19.3.0)(effect@4.0.5)(hono@4.11.4)(typescript@7.0.2)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))(ws@8.22.0): + alchemy@2.0.0-beta.81(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@effect/sql-pg@4.0.5(effect@4.0.5))(@types/node@26.6.5)(@types/react@19.3.0)(effect@4.0.5)(hono@4.11.4)(typescript@7.0.2)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1))(ws@8.22.0): dependencies: '@alchemy.run/cloudflare-runtime': 2.0.0-beta.81(@distilled.cloud/cloudflare@1.0.0-rc.13(effect@4.0.5))(@effect/platform-bun@4.0.5(effect@4.0.5))(@effect/platform-node@4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)))(@types/node@26.6.5)(effect@4.0.5)(rolldown@1.2.5)(typescript@7.0.2)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) '@alchemy.run/floci': 2.0.0-beta.81(effect@4.0.5) @@ -14209,6 +14811,7 @@ snapshots: optionalDependencies: '@effect/platform-bun': 4.0.5(effect@4.0.5) '@effect/platform-node': 4.0.5(effect@4.0.5)(redis@6.3.0(@opentelemetry/api@1.9.1)) + '@effect/sql-pg': 4.0.5(effect@4.0.5) vite: 8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) ws: 8.22.0 transitivePeerDependencies: @@ -14242,6 +14845,8 @@ snapshots: - '@types/react' - react-devtools-core + alien-signals@2.0.6: {} + am-i-vibing@0.5.0: dependencies: process-ancestry: 0.1.0 @@ -14343,7 +14948,7 @@ snapshots: astring@1.9.0: {} - astro@7.4.0(@astrojs/markdown-remark@7.3.3(supports-color@7.2.0))(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1): + astro@7.4.0(@astrojs/markdown-remark@7.3.3(supports-color@7.2.0))(@types/node@26.6.5)(esbuild@0.28.2)(idb-keyval@6.2.1)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1): dependencies: '@astrojs/compiler-rs': 0.5.2 '@astrojs/internal-helpers': 0.13.0 @@ -14390,7 +14995,7 @@ snapshots: tinyps: 0.5.0 ultrahtml: 1.7.0 unifont: 1.0.3 - unstorage: 1.17.6 + unstorage: 1.17.6(idb-keyval@6.2.1) verkit: 0.5.0 vite: 8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1) vitefu: 1.1.3(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) @@ -14445,6 +15050,8 @@ snapshots: at-least-node@1.0.0: {} + atomically@1.7.0: {} + aws4@1.13.2: {} axios@1.20.0(debug@4.4.3(supports-color@7.2.0))(supports-color@7.2.0): @@ -14527,6 +15134,10 @@ snapshots: dependencies: fill-range: 7.1.1 + browser-tabs-lock@1.3.0: + dependencies: + lodash: 4.17.21 + browserslist@4.29.3: dependencies: baseline-browser-mapping: 2.11.29 @@ -14647,6 +15258,8 @@ snapshots: ansi-styles: 4.3.0 supports-color: 7.2.0 + chalk@5.6.2: {} + character-entities-html4@2.1.0: {} character-entities-legacy@3.0.0: {} @@ -14705,6 +15318,8 @@ snapshots: dependencies: mimic-response: 1.0.1 + clsx@1.2.1: {} + clsx@2.1.1: {} cmd-shim@9.0.2: {} @@ -14741,6 +15356,8 @@ snapshots: commander@11.1.0: {} + commander@13.1.0: {} + commander@5.1.0: {} commander@6.2.1: {} @@ -14756,6 +15373,19 @@ snapshots: concat-map@0.0.1: {} + conf@10.2.0: + dependencies: + ajv: 8.20.0 + ajv-formats: 2.1.1 + atomically: 1.7.0 + debounce-fn: 4.0.0 + dot-prop: 6.0.1 + env-paths: 2.2.1 + json-schema-typed: 7.0.3 + onetime: 5.1.2 + pkg-up: 3.1.0 + semver: 7.8.5 + content-type@2.1.0: {} content-type@3.1.1: {} @@ -14768,6 +15398,8 @@ snapshots: cookie@2.0.1: {} + core-js@3.47.0: {} + core-util-is@1.0.3: {} cross-dirname@0.1.0: @@ -14783,6 +15415,8 @@ snapshots: dependencies: uncrypto: 0.1.3 + crypto-js@4.2.0: {} + css-select@6.0.0: dependencies: boolbase: 1.0.0 @@ -14813,6 +15447,10 @@ snapshots: data-uri-to-buffer@4.0.1: {} + debounce-fn@4.0.0: + dependencies: + mimic-fn: 3.1.0 + debug@4.4.3(supports-color@7.2.0): dependencies: ms: 2.1.3 @@ -14912,6 +15550,10 @@ snapshots: domelementtype: 2.3.0 domhandler: 5.0.3 + dot-prop@6.0.1: + dependencies: + is-obj: 2.0.0 + dotenv-expand@11.0.7: dependencies: dotenv: 16.6.1 @@ -14981,6 +15623,11 @@ snapshots: transitivePeerDependencies: - supports-color + electron-store@8.2.0: + dependencies: + conf: 10.2.0 + type-fest: 2.19.0 + electron-to-chromium@1.5.458: {} electron-winstaller@5.4.0(supports-color@7.2.0): @@ -15171,6 +15818,8 @@ snapshots: dependencies: '@types/estree': 1.0.9 + eventemitter3@5.0.1: {} + eventemitter3@5.0.4: {} events-universal@1.0.1: @@ -15226,6 +15875,8 @@ snapshots: merge2: 1.4.1 micromatch: 4.0.8 + fast-sha256@1.3.0: {} + fast-string-truncated-width@3.0.3: {} fast-string-width@3.0.2: @@ -15252,6 +15903,8 @@ snapshots: strnum: 2.5.1 xml-naming: 0.3.0 + fastest-levenshtein@1.0.16: {} + fastq@1.20.3: dependencies: reusify: 1.1.0 @@ -15288,6 +15941,10 @@ snapshots: dependencies: to-regex-range: 5.0.1 + find-up@3.0.0: + dependencies: + locate-path: 3.0.0 + flattie@1.1.1: {} fnv1a-64@0.1.2: {} @@ -15526,6 +16183,8 @@ snapshots: dependencies: is-glob: 4.0.3 + glob-to-regexp@0.4.1: {} + glob@13.0.6: dependencies: minimatch: 10.2.6 @@ -15837,6 +16496,8 @@ snapshots: safer-buffer: 2.1.2 optional: true + idb-keyval@6.2.1: {} + ieee754@1.2.1: {} ignore-walk@9.0.0: @@ -15896,6 +16557,8 @@ snapshots: is-number@7.0.0: {} + is-obj@2.0.0: {} + is-plain-obj@4.1.0: {} is-stream@2.0.1: {} @@ -15920,6 +16583,10 @@ snapshots: dependencies: ws: 8.22.0 + isows@1.0.7(ws@8.21.0): + dependencies: + ws: 8.21.0 + jake@10.9.4: dependencies: async: 3.2.6 @@ -15934,6 +16601,8 @@ snapshots: js-base64@3.9.4: {} + js-cookie@3.0.8: {} + js-tokens@4.0.0: {} js-yaml@4.3.2: @@ -15952,6 +16621,8 @@ snapshots: json-schema-traverse@1.0.0: {} + json-schema-typed@7.0.3: {} + json-schema@0.4.0: {} json-stringify-nice@1.1.4: {} @@ -16165,6 +16836,11 @@ snapshots: lilconfig@2.1.0: {} + locate-path@3.0.0: + dependencies: + p-locate: 3.0.0 + path-exists: 3.0.0 + lodash.camelcase@4.3.0: {} lodash@4.17.21: {} @@ -16708,6 +17384,8 @@ snapshots: mimic-fn@2.1.0: {} + mimic-fn@3.1.0: {} + mimic-response@1.0.1: {} mimic-response@3.1.0: {} @@ -16981,6 +17659,35 @@ snapshots: os-paths@4.4.0: {} + ox@0.14.67(typescript@7.0.2)(zod@4.6.7): + dependencies: + '@adraffy/ens-normalize': 1.11.1 + '@noble/ciphers': 1.3.0 + '@noble/curves': 1.9.1 + '@noble/hashes': 1.8.0 + '@scure/bip32': 1.7.0 + '@scure/bip39': 1.6.0 + abitype: 1.2.3(typescript@7.0.2)(zod@4.6.7) + eventemitter3: 5.0.1 + optionalDependencies: + typescript: 7.0.2 + transitivePeerDependencies: + - zod + + ox@0.6.9(typescript@7.0.2)(zod@4.6.7): + dependencies: + '@adraffy/ens-normalize': 1.11.1 + '@noble/curves': 1.9.7 + '@noble/hashes': 1.8.0 + '@scure/bip32': 1.7.0 + '@scure/bip39': 1.6.0 + abitype: 1.3.0(typescript@7.0.2)(zod@4.6.7) + eventemitter3: 5.0.1 + optionalDependencies: + typescript: 7.0.2 + transitivePeerDependencies: + - zod + oxc-parser@0.147.0: dependencies: '@oxc-project/types': 0.147.0 @@ -17134,6 +17841,10 @@ snapshots: p-cancelable@2.1.1: {} + p-limit@2.3.0: + dependencies: + p-try: 2.2.0 + p-limit@3.1.0: dependencies: yocto-queue: 0.1.0 @@ -17142,6 +17853,10 @@ snapshots: dependencies: yocto-queue: 1.2.2 + p-locate@3.0.0: + dependencies: + p-limit: 2.3.0 + p-map@7.1.1: {} p-queue@9.3.5: @@ -17151,6 +17866,8 @@ snapshots: p-timeout@7.0.2: {} + p-try@2.2.0: {} + package-manager-detector@1.9.0: {} pacote@22.0.0(supports-color@7.2.0): @@ -17213,6 +17930,8 @@ snapshots: path-browserify@1.0.1: {} + path-exists@3.0.0: {} + path-expression-matcher@1.6.2: {} path-is-absolute@1.0.1: {} @@ -17244,6 +17963,10 @@ snapshots: pkce-challenge@5.0.1: {} + pkg-up@3.1.0: + dependencies: + find-up: 3.0.0 + pkijs@3.4.1: dependencies: '@noble/hashes': 1.8.0 @@ -17281,6 +18004,12 @@ snapshots: dependencies: preact: 11.0.0-beta.0 + preact@10.24.2: {} + + preact@10.29.8(preact-render-to-string@6.6.5): + optionalDependencies: + preact-render-to-string: 6.6.5(preact@11.0.0-beta.0) + preact@11.0.0-beta.0: {} prebuild-install@7.1.3: @@ -18060,6 +18789,11 @@ snapshots: stackback@0.0.2: {} + standardwebhooks@1.1.1: + dependencies: + '@stablelib/base64': 1.0.1 + fast-sha256: 1.3.0 + stat-mode@1.0.0: {} std-env@3.10.0: {} @@ -18322,6 +19056,8 @@ snapshots: type-fest@0.13.1: optional: true + type-fest@2.19.0: {} + typebox@1.4.0: {} typesafe-path@0.2.2: {} @@ -18475,7 +19211,7 @@ snapshots: rolldown: 1.2.14 vite: '@voidzero-dev/vite-plus-core@0.3.1(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(typescript@7.0.2)(yaml@2.9.1)' - unstorage@1.17.6: + unstorage@1.17.6(idb-keyval@6.2.1): dependencies: anymatch: 3.1.3 chokidar: 5.0.0 @@ -18485,6 +19221,8 @@ snapshots: node-fetch-native: 1.6.7 ofetch: 1.5.1 ufo: 1.6.4 + optionalDependencies: + idb-keyval: 6.2.1 unzipper@0.12.5: dependencies: @@ -18570,6 +19308,23 @@ snapshots: transitivePeerDependencies: - supports-color + viem@2.57.20(typescript@7.0.2)(zod@4.6.7): + dependencies: + '@noble/curves': 1.9.1 + '@noble/hashes': 1.8.0 + '@scure/bip32': 1.7.0 + '@scure/bip39': 1.6.0 + abitype: 1.2.3(typescript@7.0.2)(zod@4.6.7) + isows: 1.0.7(ws@8.21.0) + ox: 0.14.67(typescript@7.0.2)(zod@4.6.7) + ws: 8.21.0 + optionalDependencies: + typescript: 7.0.2 + transitivePeerDependencies: + - bufferutil + - utf-8-validate + - zod + vite-plus@0.3.1(@opentelemetry/api@1.9.1)(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15)(typescript@7.0.2)(yaml@2.9.1): dependencies: '@oxc-project/types': 0.148.0 @@ -18867,6 +19622,8 @@ snapshots: dependencies: signal-exit: 4.1.0 + ws@8.21.0: {} + ws@8.21.3: {} ws@8.22.0: {} @@ -18997,4 +19754,10 @@ snapshots: zod@4.6.7: {} + zustand@5.0.3(@types/react@19.3.0)(react@19.3.1)(use-sync-external-store@1.7.0(react@19.3.1)): + optionalDependencies: + '@types/react': 19.3.0 + react: 19.3.1 + use-sync-external-store: 1.7.0(react@19.3.1) + zwitch@2.0.4: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 6a38a29e..31b1b3cf 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -32,6 +32,9 @@ allowBuilds: workerd: true # electron-builder's Windows installer; the desktop app builds no Windows targets. electron-winstaller: false + # Pulled in by Clerk's browser SDK; their install scripts only print messages. + browser-tabs-lock: false + core-js: false patchedDependencies: "@legendapp/list@3.3.5": patches/@legendapp__list@3.3.5.patch