diff --git a/apps/contract/src/contract.ts b/apps/contract/src/contract.ts index b3d3fcae..c7f901f3 100644 --- a/apps/contract/src/contract.ts +++ b/apps/contract/src/contract.ts @@ -433,7 +433,8 @@ export type CliAction = typeof CliAction.Type; /** * A new server. A local one needs a home of its own, since a home names one server; a remote one - * needs its WebSocket URL. A blank or absent `name` is no override. + * needs its WebSocket URL and the token in `/token` of its CodeWork home. A blank or absent + * `name` is no override. */ export const ServerAdd = Schema.Union([ Schema.Struct({ @@ -443,13 +444,18 @@ export const ServerAdd = Schema.Union([ home: Schema.String, args: Schema.String, }), - Schema.Struct({ kind: Schema.Literal("remote"), name: Schema.optionalKey(Schema.String), url: Schema.String }), + Schema.Struct({ + kind: Schema.Literal("remote"), + name: Schema.optionalKey(Schema.String), + url: Schema.String, + token: Schema.String, + }), ]); export type ServerAdd = typeof ServerAdd.Type; /** * Changes to a server; an absent field is left as it is. A `null` path goes back to the one found; - * a blank `name` removes the override; `env` replaces every variable. `url` is for a remote server only, the rest but `name` for a local one. + * a blank `name` removes the override; `env` replaces every variable. `url` and `token` are for a remote server only, the rest but `name` for a local one. */ export const ServerUpdate = Schema.Struct({ id: Schema.String, @@ -459,6 +465,7 @@ export const ServerUpdate = Schema.Struct({ args: Schema.optionalKey(Schema.String), env: Schema.optionalKey(Schema.Array(CliEnvVar)), url: Schema.optionalKey(Schema.String), + token: Schema.optionalKey(Schema.String), }); export type ServerUpdate = typeof ServerUpdate.Type; diff --git a/apps/desktop/src/ipc.ts b/apps/desktop/src/ipc.ts index 74e04584..45fa2e41 100644 --- a/apps/desktop/src/ipc.ts +++ b/apps/desktop/src/ipc.ts @@ -1,4 +1,4 @@ -/** Synchronous IPC: the renderer reads the app server's RPC URL once, at load. */ +/** Synchronous IPC: the renderer reads the app server's RPC URL and token once, at load. */ export const SERVER_CHANNEL = "codework:server"; /** Synchronous IPC: the user's home directory, the folder a new project starts from. */ export const HOME_CHANNEL = "codework:home"; diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 0ff695dc..888eba7a 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -1,11 +1,12 @@ import { exposeClerkBridge } from "@clerk/electron/preload"; import { contextBridge, ipcRenderer } from "electron"; import { HOME_CHANNEL, PICK_FOLDER_CHANNEL, REVEAL_CHANNEL, SERVER_CHANNEL } from "./ipc.ts"; +import type { Endpoint } from "./server.ts"; contextBridge.exposeInMainWorld("desktopBridge", { platform: process.platform, // Main creates the window only after the server is ready, so this is set. - server: ipcRenderer.sendSync(SERVER_CHANNEL) as string, + server: ipcRenderer.sendSync(SERVER_CHANNEL) as Endpoint, home: ipcRenderer.sendSync(HOME_CHANNEL) as string, // On Windows the CodeWork server runs in WSL, which has no use for the Windows paths these deal in. ...(process.platform !== "win32" && { diff --git a/apps/desktop/src/server.ts b/apps/desktop/src/server.ts index e64dceac..d8093956 100644 --- a/apps/desktop/src/server.ts +++ b/apps/desktop/src/server.ts @@ -13,8 +13,14 @@ const ENTRY = app.isPackaged // How long the server gets to stop by itself on quit before it is killed. const STOP_GRACE_MS = 5000; -/** Starts the app server and resolves with its RPC URL once it listens. */ -export function startServer(): Promise { +/** Where the renderer reaches the app server, and the token its door takes. */ +export interface Endpoint { + readonly url: string; + readonly token: string; +} + +/** Starts the app server and resolves with its RPC endpoint once it listens. */ +export function startServer(): Promise { // Electron's own binary in Node mode: no system Node needed, and the child // does not become a second GUI app instance. const child = spawn(process.execPath, [ENTRY], { @@ -56,14 +62,15 @@ export function startServer(): Promise { }); createInterface({ input: child.stdout }).on("line", (line) => { + // The ready line carries the token, so it is the one line never echoed. if (!ready && line.startsWith('{"type":"ready"')) { ready = true; - const { port } = JSON.parse(line) as { port: number }; - const url = `ws://127.0.0.1:${port}/rpc`; + const { port, token } = JSON.parse(line) as { port: number; token: string }; + const endpoint: Endpoint = { url: `ws://127.0.0.1:${port}/rpc`, token }; ipcMain.on(SERVER_CHANNEL, (event) => { - event.returnValue = url; + event.returnValue = endpoint; }); - resolve(url); + resolve(endpoint); return; } console.log(`[server] ${line}`); diff --git a/apps/server/package.json b/apps/server/package.json index 2e7a87c6..5c49f1c4 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -11,6 +11,7 @@ }, "dependencies": { "@codeworksh/contract": "workspace:*", + "@codeworksh/schema": "workspace:*", "@codeworksh/web": "workspace:*", "@codeworksh/widget": "workspace:*", "@effect/platform-node": "4.0.5", diff --git a/apps/server/src/cli.ts b/apps/server/src/cli.ts index c96fc7a4..6c3e0670 100644 --- a/apps/server/src/cli.ts +++ b/apps/server/src/cli.ts @@ -117,9 +117,7 @@ const executableOf = (row: Servers.LocalRow, foundOnce: typeof found) => { export const liveAt = (home: string) => Effect.gen(function* () { const registered = yield* Codework.registrationAt(home); - return Option.isSome(registered) && (yield* Codework.reachable(registered.value.url)) - ? registered - : Option.none(); + return Option.isSome(registered) && (yield* Codework.reachable(registered.value)) ? registered : Option.none(); }); /** @@ -160,7 +158,11 @@ export const statuses = Effect.gen(function* () { yield* servers.list, (row) => Effect.gen(function* () { - if (row.kind === "remote") return row satisfies ServerStatus; + // Its token stays here: the renderer is never sent one. + if (row.kind === "remote") { + const { token: _, ...status } = row; + return status satisfies ServerStatus; + } const home = servers.homeOf(row); const [cli, server] = yield* Effect.all( [executableOf(row, foundOnce), serverAt(home.path, row.isDefault)], diff --git a/apps/server/src/codework.ts b/apps/server/src/codework.ts index 093ede64..54da2254 100644 --- a/apps/server/src/codework.ts +++ b/apps/server/src/codework.ts @@ -7,11 +7,19 @@ import { Socket } from "effect/socket"; /* @effect-diagnostics nodeBuiltinImport:off -- a home's registration is a file path. */ import path from "node:path"; import { CodeworkUnavailable, HostError } from "@codeworksh/contract"; +import { Door } from "@codeworksh/schema"; import { Servers } from "./servers.ts"; /** How a running server advertises itself: `/service.json`, written by `codework serve`. */ const Registration = Schema.fromJsonString( - Schema.Struct({ pid: Schema.Int, version: Schema.String, url: Schema.String, port: Schema.Int }), + Schema.Struct({ + pid: Schema.Int, + version: Schema.String, + url: Schema.String, + port: Schema.Int, + /** The home's token, offered as the socket opens. */ + token: Schema.String, + }), ); /** The server `/service.json` names, read fresh; a missing or unreadable file is none. */ @@ -23,12 +31,34 @@ export const registrationAt = (home: string) => .pipe(Effect.flatMap(Schema.decodeUnknownEffect(Registration)), Effect.option); }); +/** Where a server is reached, and the token its door takes; a remote row without one is refused. */ +interface Target { + readonly url: string; + readonly token: string | undefined; +} + /** - * Whether a server answers at `url`: its WebSocket opens. A registration's pid says nothing here, since - * the server may run on another OS than this app, as one in WSL does for the Windows app. + * A socket to the server `target` reads, read afresh on every open, so its URL and token always + * belong to the same server: a restarted one may have another port. */ -export const reachable = (url: string) => - Socket.makeWebSocket(url, { openTimeout: "2 seconds" }).pipe( +const open = (target: Effect.Effect, options?: { readonly openTimeout?: Duration.Input }) => + Socket.WebSocketConstructor.use((make) => + Socket.fromWebSocket( + Effect.acquireRelease( + Effect.map(target, ({ url, token }) => make(url, Door.protocols(token))), + (ws) => Effect.sync(() => ws.close(1000)), + ), + options, + ), + ); + +/** + * Whether a server lets this app in at `target`: its WebSocket opens. A registration's pid says + * nothing here, since the server may run on another OS than this app, as one in WSL does for the + * Windows app. + */ +export const reachable = (target: Target) => + open(Effect.succeed(target), { openTimeout: "2 seconds" }).pipe( Effect.flatMap((socket) => Effect.scoped(socket.reader)), Effect.isSuccess, Effect.provide(NodeSocket.layerWebSocketConstructor), @@ -66,60 +96,54 @@ const connect = (socket: Layer.Layer) => Layer.orDie, ); +type Found = { readonly url: string; readonly token: string }; + /** - * The URL `registered` reads, waited for until there is one. The socket reads its URL while opening, + * What `registered` reads, waited for until there is one. The socket reads it while opening, * which Effect runs uninterruptibly; waiting there for a server to register would otherwise keep the * app server from ever shutting down. */ -const waitFor = (registered: Effect.Effect>) => +const waitFor = (registered: Effect.Effect>) => registered.pipe( Effect.flatMap(Effect.fromOption), - Effect.map((found) => found.url), Effect.retry(Schedule.spaced("1 second")), Effect.orDie, Effect.interruptible, ); +/** A client of the local server `registered` names, read on every connect. */ +const local = ( + registered: Effect.Effect, never, R>, + wrap: (socket: Socket.Socket) => Effect.Effect = Effect.succeed, +) => + Layer.unwrap( + Effect.gen(function* () { + const found = waitFor(Effect.provideContext(registered, yield* Effect.context())); + return connect(Layer.effect(Socket.Socket, open(found).pipe(Effect.flatMap(wrap)))); + }), + ); + /** * The app's connection to the default server. The registration is read on every connect, so a server * restarted on a new port, a new home or a new default is picked up without restarting this app; * until one is registered, connecting waits. */ -export const layer = connect( - Layer.effect( - Socket.Socket, - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const servers = yield* Servers.Service; - const url = waitFor( - registration.pipe( - Effect.provideService(FileSystem.FileSystem, fs), - Effect.provideService(Servers.Service, servers), - ), - ); - return endOnHomeChange(yield* Socket.makeWebSocket(url), servers.homeChanges); - }), - ), +export const layer = local(registration, (socket) => + Servers.Service.use((servers) => Effect.succeed(endOnHomeChange(socket, servers.homeChanges))), ); /** - * A connection to one machine's server: a remote one at its URL, a local one at what its home - * registers, read on every connect as {@link layer} does. + * A connection to one machine's server: a remote one at its URL with the token stored for it, a local + * one at what its home registers, read on every connect as {@link layer} does. */ export const machine = (row: Servers.Row) => - connect( - Layer.effect( - Socket.Socket, - Effect.gen(function* () { - if (row.kind === "remote") return yield* Socket.makeWebSocket(row.url); - const fs = yield* FileSystem.FileSystem; - const home = (yield* Servers.Service).homeOf(row).path; - return yield* Socket.makeWebSocket( - waitFor(registrationAt(home).pipe(Effect.provideService(FileSystem.FileSystem, fs))), - ); - }), - ), - ); + row.kind === "remote" + ? connect(Layer.effect(Socket.Socket, open(Effect.succeed({ url: row.url, token: row.token ?? undefined })))) + : local( + Effect.gen(function* () { + return yield* registrationAt((yield* Servers.Service).homeOf(row).path); + }), + ); export interface CallOptions { /** How long the server has to answer; 5 seconds unless given. */ diff --git a/apps/server/src/db.ts b/apps/server/src/db.ts index 598a4c7d..022ba416 100644 --- a/apps/server/src/db.ts +++ b/apps/server/src/db.ts @@ -329,6 +329,12 @@ const migrations = { // The one organization the UI uses until auth exists. yield* sql`INSERT INTO organization ${sql.insert({ id: "personal", name: "Personal", createdAt: now, updatedAt: now })}`; }), + + // A remote machine's token, offered as its socket opens; a row from before has none and is refused. + "202611200001_token": Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`ALTER TABLE machine ADD COLUMN token TEXT`; + }), }; const setup = Effect.gen(function* () { diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index e6a981eb..bfddd271 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -8,6 +8,7 @@ import type { Socket } from "node:net"; import path from "node:path"; import { Codework } from "./codework.ts"; import { Contract } from "@codeworksh/contract"; +import { Door } from "@codeworksh/schema"; import { Db } from "./db.ts"; import { Event } from "./event.ts"; import { Handlers } from "./handlers.ts"; @@ -36,15 +37,20 @@ const listener = () => { return server; }; -// The port is chosen by the OS, so the supervisor learns it from this line. -const announceReady = Layer.effectDiscard( - Effect.gen(function* () { - const server = yield* HttpServer.HttpServer; - if (server.address._tag === "UnixPathAddress") return; - const port = server.address.port; - yield* Effect.sync(() => process.stdout.write(`${JSON.stringify({ type: "ready", port })}\n`)); - }), -); +// The port is chosen by the OS and the token made at start, so the supervisor learns both from this +// line; it never logs it. +const announceReady = (token: string) => + Layer.effectDiscard( + Effect.gen(function* () { + const server = yield* HttpServer.HttpServer; + if (server.address._tag === "UnixPathAddress") return; + const port = server.address.port; + yield* Effect.sync(() => process.stdout.write(`${JSON.stringify({ type: "ready", port, token })}\n`)); + }), + ); + +/** The page's origins: the desktop app's scheme, packaged and from the repo. */ +const ORIGINS = ["codework://app", "codeworkdev://app"]; const alive = (pid: number) => Effect.sync(() => { @@ -95,25 +101,30 @@ const rpc = RpcServer.layerHttp({ group: Contract.Api, path: "/rpc", protocol: " Layer.provide(Handlers.layer), ); -// One event log, kv and CodeWork connection for the RPC handlers and the widget backends alike. -export const layer = Layer.mergeAll( - HttpRouter.serve(rpc, { disableListenLog: true }), - Widgets.layer, - exitWithParent, -).pipe( - // The servers' status is checked from launch, so the first page already has it. - Layer.provide( - Layer.mergeAll(Health.layer, Sync.layer).pipe( - Layer.provideMerge(Layer.mergeAll(Event.layer, Kv.layer, Codework.layer)), +// One event log, kv and CodeWork connection for the RPC handlers and the widget backends alike. A +// fresh token per start: only the process that started this one learns it. +export const layer = Layer.unwrap( + Effect.map(Door.make, (token) => + Layer.mergeAll( + HttpRouter.serve(Layer.merge(rpc, Door.layer({ token, origins: ORIGINS })), { disableListenLog: true }), + Widgets.layer, + exitWithParent, + ).pipe( + // The servers' status is checked from launch, so the first page already has it. + Layer.provide( + Layer.mergeAll(Health.layer, Sync.layer).pipe( + Layer.provideMerge(Layer.mergeAll(Event.layer, Kv.layer, Codework.layer)), + ), + ), + // The app's servers decide which one its connection goes to, and the handlers manage them too. + Layer.provideMerge(Servers.layer), + Layer.provideMerge(announceReady(token)), + Layer.provideMerge(NodeHttpServer.layer(listener, { host: "127.0.0.1", port: 0 })), + Layer.provide(RpcSerialization.layerNdjson), + Layer.provide(database), + Layer.provide(NodeServices.layer), ), ), - // The app's servers decide which one its connection goes to, and the handlers manage them too. - Layer.provideMerge(Servers.layer), - Layer.provideMerge(announceReady), - Layer.provideMerge(NodeHttpServer.layer(listener, { host: "127.0.0.1", port: 0 })), - Layer.provide(RpcSerialization.layerNdjson), - Layer.provide(database), - Layer.provide(NodeServices.layer), ); export * as Server from "./server.ts"; diff --git a/apps/server/src/servers.ts b/apps/server/src/servers.ts index 8d54b3c2..944c4337 100644 --- a/apps/server/src/servers.ts +++ b/apps/server/src/servers.ts @@ -4,6 +4,7 @@ import { SqlClient } from "effect/sql"; import os from "node:os"; import path from "node:path"; import { type CliEnvVar, LOCAL_SERVER, type ServerAdd, ServersError, type ServerUpdate } from "@codeworksh/contract"; +import { Door } from "@codeworksh/schema"; /** The same home the CLI resolves: CODEWORK_HOME_DIR, else ~/.codework. Only the built-in server falls back to it. */ export const cliHome = Config.String("CODEWORK_HOME_DIR").pipe( @@ -58,11 +59,13 @@ export interface LocalRow extends Naming { readonly isDefault: boolean; } -/** A remote server as stored: where the app reaches it. */ +/** A remote server as stored: where the app reaches it, and the token its door takes. */ export interface RemoteRow extends Naming { readonly id: string; readonly kind: "remote"; readonly url: string; + /** None on a row added before remote servers took one: it cannot connect until given one. */ + readonly token: string | null; readonly isDefault: boolean; } @@ -84,6 +87,14 @@ const chosenPath = (input: string | null) => return path.normalize(expanded); }); +/** A remote server's token as pasted in Settings. */ +const chosenToken = (input: string) => { + const trimmed = input.trim(); + return Door.isToken(trimmed) + ? Effect.succeed(trimmed) + : Effect.fail(fail("Use the token in `token` in that machine's CodeWork home.")); +}; + /** A remote server's URL typed in Settings: CodeWork answers over a WebSocket. */ const chosenUrl = (input: string) => { const trimmed = input.trim(); @@ -181,16 +192,17 @@ export const layer = Layer.effect( kind: string; env: string; url: string | null; + token: string | null; isDefault: number; } >` - SELECT id, kind, name AS override, host, executable, home, args, env, url, is_default FROM machine ORDER BY pos + SELECT id, kind, name AS override, host, executable, home, args, env, url, token, is_default FROM machine ORDER BY pos `.pipe( Effect.flatMap((rows) => - Effect.forEach(rows, ({ kind, url, env, isDefault, ...row }) => { + Effect.forEach(rows, ({ kind, url, token, env, isDefault, ...row }) => { const naming = { name: nameOf({ kind, url, ...row }), host: row.host, override: row.override }; return kind === "remote" && url !== null - ? Effect.succeed({ id: row.id, kind, ...naming, url, isDefault: isDefault === 1 }) + ? Effect.succeed({ id: row.id, kind, ...naming, url, token, isDefault: isDefault === 1 }) : decodeEnv(env).pipe( Effect.map((env): Row => ({ ...row, @@ -282,7 +294,7 @@ export const layer = Layer.effect( const route = input.kind === "local" ? { executable: yield* chosenCommand(fs, input.executable), home, args: input.args.trim() } - : { url: yield* chosenUrl(input.url) }; + : { url: yield* chosenUrl(input.url), token: yield* chosenToken(input.token) }; yield* transaction( Effect.gen(function* () { if (home !== null) yield* ensureOwnHome(null, home); @@ -312,8 +324,10 @@ export const layer = Layer.effect( if ([patch.executable, patch.home, patch.args, patch.env].some((value) => value !== undefined)) return yield* fail("A remote server has no executable, home, arguments or variables."); if (patch.url !== undefined) fields.url = yield* chosenUrl(patch.url); + if (patch.token !== undefined) fields.token = yield* chosenToken(patch.token); } else { if (patch.url !== undefined) return yield* fail("Only a remote server has a URL."); + if (patch.token !== undefined) return yield* fail("Only a remote server has a token."); if (patch.executable !== undefined) fields.executable = yield* chosenCommand(fs, patch.executable); if (patch.args !== undefined) fields.args = patch.args.trim(); if (patch.env !== undefined) fields.env = JSON.stringify(yield* nextEnv(patch.env, row.env)); diff --git a/apps/server/src/sync.ts b/apps/server/src/sync.ts index 5dab5008..1dd68438 100644 --- a/apps/server/src/sync.ts +++ b/apps/server/src/sync.ts @@ -78,7 +78,7 @@ const unavailable = (machineId: string) => /** The route a connection is made from: a change reconnects the machine. */ const routeOf = (row: Servers.Row) => - row.kind === "remote" ? `remote ${row.url}` : `local ${row.home ?? ""} ${row.executable ?? ""}`; + row.kind === "remote" ? `remote ${row.url} ${row.token}` : `local ${row.home ?? ""} ${row.executable ?? ""}`; /** * Runs `apply` on each batch up to its `Synced`, in order; `onItem` sees every other item as it diff --git a/apps/server/test/__artifacts__/door.json b/apps/server/test/__artifacts__/door.json new file mode 100644 index 00000000..5ef2f393 --- /dev/null +++ b/apps/server/test/__artifacts__/door.json @@ -0,0 +1,33 @@ +{ + "upgrade": { + "no protocol header": 401, + "fixed name only": 401, + "token first": 401, + "wrong token": 401, + "right token, foreign Origin": 403, + "right token, Host evil.example": 403, + "right token, Host localhost": 101, + "right token, Origin codework://app": 101, + "right token, Origin codeworkdev://app": 101, + "right token": 101, + "protocol selected": "codework", + "token in the response": false + }, + "the last start's token": 401, + "right token": { + "synced": true + }, + "wrong token and none": { + "wrong": { + "store_id": null, + "cursor": 0 + }, + "stored": { + "store_id": null, + "cursor": 0 + } + }, + "wrong token, replaced": { + "synced": true + } +} diff --git a/apps/server/test/__artifacts__/schema.json b/apps/server/test/__artifacts__/schema.json index bd1320ae..5241a46e 100644 --- a/apps/server/test/__artifacts__/schema.json +++ b/apps/server/test/__artifacts__/schema.json @@ -70,7 +70,7 @@ "type": "table", "name": "machine", "tbl_name": "machine", - "sql": "CREATE TABLE machine ( id TEXT PRIMARY KEY, kind TEXT NOT NULL, name TEXT, host TEXT, executable TEXT, home TEXT, args TEXT NOT NULL DEFAULT '', env TEXT NOT NULL DEFAULT '[]', url TEXT, namespace TEXT NOT NULL, is_default INTEGER NOT NULL DEFAULT 0, pos INTEGER NOT NULL, store_id TEXT UNIQUE, cursor INTEGER NOT NULL DEFAULT 0, boot TEXT, rollup INTEGER NOT NULL DEFAULT 0, rollup_store TEXT, rollup_boot TEXT, created_at INTEGER NOT NULL )" + "sql": "CREATE TABLE machine ( id TEXT PRIMARY KEY, kind TEXT NOT NULL, name TEXT, host TEXT, executable TEXT, home TEXT, args TEXT NOT NULL DEFAULT '', env TEXT NOT NULL DEFAULT '[]', url TEXT, namespace TEXT NOT NULL, is_default INTEGER NOT NULL DEFAULT 0, pos INTEGER NOT NULL, store_id TEXT UNIQUE, cursor INTEGER NOT NULL DEFAULT 0, boot TEXT, rollup INTEGER NOT NULL DEFAULT 0, rollup_store TEXT, rollup_boot TEXT, created_at INTEGER NOT NULL , token TEXT)" }, { "type": "table", @@ -238,7 +238,8 @@ "rollup": 0, "rollup_store": null, "rollup_boot": null, - "created_at": "