diff --git a/apps/contract/src/contract.ts b/apps/contract/src/contract.ts index c7f901f3..675e5ea7 100644 --- a/apps/contract/src/contract.ts +++ b/apps/contract/src/contract.ts @@ -413,6 +413,8 @@ export const RemoteServerStatus = Schema.Struct({ ...ServerNaming, isDefault: Schema.Boolean, url: Schema.String, + /** Whether this app holds a session on it; false once the server refuses it (revoked or lapsed): pair again. */ + paired: Schema.Boolean, }); export type RemoteServerStatus = typeof RemoteServerStatus.Type; @@ -433,8 +435,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 and the token in `/token` of its CodeWork home. A blank or absent - * `name` is no override. + * needs its WebSocket URL and a pairing code from `codework service pair` on that machine. A blank or + * absent `name` is no override. */ export const ServerAdd = Schema.Union([ Schema.Struct({ @@ -448,14 +450,15 @@ export const ServerAdd = Schema.Union([ kind: Schema.Literal("remote"), name: Schema.optionalKey(Schema.String), url: Schema.String, - token: Schema.String, + code: 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` and `token` are 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 `code` are for a remote + * server only, the rest but `name` for a local one; a `code` pairs again, at the new `url` when given. */ export const ServerUpdate = Schema.Struct({ id: Schema.String, @@ -465,7 +468,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), + code: Schema.optionalKey(Schema.String), }); export type ServerUpdate = typeof ServerUpdate.Type; @@ -475,6 +478,11 @@ export class ServersError extends Schema.TaggedError()("Server.Ser message: Schema.String, }) {} +/** A remote server refused the pairing code: wrong, used or expired. */ +export class PairingRefused extends Schema.TaggedError()("Server.PairingRefused", { + message: Schema.String, +}) {} + /** The app bus topics the sync publishes on. */ export const syncTopics = { /** `SyncChanged` after each applied batch; stored. */ @@ -1002,16 +1010,17 @@ export const Api = RpcGroup.make( payload: ServerHealth, success: Schema.Void, }), + /** A remote server is paired with its code before it is stored. */ Rpc.make("servers.add", { payload: ServerAdd, success: Schema.String, - error: ServersError, + error: Schema.Union([ServersError, PairingRefused]), }), /** A new home for the default server reconnects the app at once. */ Rpc.make("servers.update", { payload: ServerUpdate, success: Schema.Void, - error: ServersError, + error: Schema.Union([ServersError, PairingRefused]), }), /** The default server and the built-in one stay. */ Rpc.make("servers.remove", { diff --git a/apps/server/src/cli.ts b/apps/server/src/cli.ts index 6c3e0670..975c7e07 100644 --- a/apps/server/src/cli.ts +++ b/apps/server/src/cli.ts @@ -158,10 +158,10 @@ export const statuses = Effect.gen(function* () { yield* servers.list, (row) => Effect.gen(function* () { - // Its token stays here: the renderer is never sent one. + // Its session token stays here: the renderer is never sent one. if (row.kind === "remote") { - const { token: _, ...status } = row; - return status satisfies ServerStatus; + const { token, ...status } = row; + return { ...status, paired: token !== null } satisfies ServerStatus; } const home = servers.homeOf(row); const [cli, server] = yield* Effect.all( diff --git a/apps/server/src/codework.ts b/apps/server/src/codework.ts index 54da2254..b1d9d036 100644 --- a/apps/server/src/codework.ts +++ b/apps/server/src/codework.ts @@ -8,6 +8,7 @@ import { Socket } from "effect/socket"; import path from "node:path"; import { CodeworkUnavailable, HostError } from "@codeworksh/contract"; import { Door } from "@codeworksh/schema"; +import { Pairing } from "./pairing.ts"; import { Servers } from "./servers.ts"; /** How a running server advertises itself: `/service.json`, written by `codework serve`. */ @@ -31,7 +32,7 @@ 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. */ +/** Where a server is reached, and the credential its door takes: the home's token, or a ticket. */ interface Target { readonly url: string; readonly token: string | undefined; @@ -41,7 +42,10 @@ interface Target { * 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. */ -const open = (target: Effect.Effect, options?: { readonly openTimeout?: Duration.Input }) => +const open = ( + target: Effect.Effect, + options?: { readonly openTimeout?: Duration.Input }, +) => Socket.WebSocketConstructor.use((make) => Socket.fromWebSocket( Effect.acquireRelease( @@ -133,12 +137,32 @@ export const layer = local(registration, (socket) => ); /** - * A connection to one machine's server: a remote one at its URL with the token stored for it, a local + * A remote server's URL with a fresh ticket for the row's session, taken on every connect. A server + * that refuses the session (revoked or lapsed) has it dropped from the row, which ends this connection + * (the sync follows the row), so it waits rather than asking again; so does a row without one. + * Interruptible, as {@link waitFor} is. + */ +const ticketed = (row: Servers.RemoteRow) => + Effect.gen(function* () { + const session = row.token; + if (session === null) return yield* Effect.never; + const ticket = yield* Pairing.ticket(row.url, session).pipe( + Effect.mapError( + (cause) => new Socket.SocketError({ reason: new Socket.SocketOpenError({ kind: "Unknown", cause }) }), + ), + ); + if (ticket !== undefined) return { url: row.url, token: ticket }; + yield* Servers.Service.use((servers) => servers.unpair(row.id, session)); + return yield* Effect.never; + }).pipe(Effect.interruptible); + +/** + * A connection to one machine's server: a remote one at its URL with a ticket per socket, a local * one at what its home registers, read on every connect as {@link layer} does. */ export const machine = (row: Servers.Row) => row.kind === "remote" - ? connect(Layer.effect(Socket.Socket, open(Effect.succeed({ url: row.url, token: row.token ?? undefined })))) + ? connect(Layer.effect(Socket.Socket, open(ticketed(row)))) : local( Effect.gen(function* () { return yield* registrationAt((yield* Servers.Service).homeOf(row).path); diff --git a/apps/server/src/db.ts b/apps/server/src/db.ts index 022ba416..54f1f4cf 100644 --- a/apps/server/src/db.ts +++ b/apps/server/src/db.ts @@ -330,7 +330,7 @@ const migrations = { 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. + // A remote machine's session token, which its pairing gave and each socket's ticket is taken with. "202611200001_token": Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; yield* sql`ALTER TABLE machine ADD COLUMN token TEXT`; diff --git a/apps/server/src/health.ts b/apps/server/src/health.ts index 1ca12248..e11e4982 100644 --- a/apps/server/src/health.ts +++ b/apps/server/src/health.ts @@ -71,10 +71,12 @@ export const layer = Layer.effect( yield* check.pipe(Effect.forkScoped); - // A name a server reports reaches Settings without waiting for the next check; the app's own - // edits are checked by their handlers. + // A name a server reports, or a session it refused, reaches Settings without waiting for the next + // check; the app's own edits are checked by their handlers. yield* servers.watch.pipe( - Stream.map((rows) => rows.map((row) => `${row.id}=${row.host}`).join("\n")), + Stream.map((rows) => + rows.map((row) => `${row.id}=${row.host} ${row.kind === "remote" && row.token === null}`).join("\n"), + ), Stream.changes, Stream.drop(1), Stream.runForEach(() => check), diff --git a/apps/server/src/pairing.ts b/apps/server/src/pairing.ts new file mode 100644 index 00000000..5cdbb8df --- /dev/null +++ b/apps/server/src/pairing.ts @@ -0,0 +1,42 @@ +import { Pairing as Wire } from "@codeworksh/schema"; +import { Effect } from "effect"; +import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; + +/** A remote server's pairing route `path`, beside its socket: the HTTP origin of its WebSocket URL. */ +const at = (url: string, path: string) => { + const { protocol, host } = new URL(url); + return `${protocol === "wss:" ? "https:" : "http:"}//${host}${path}`; +}; + +/** `request`'s answer when 200; none for a refused credential (401); any other answer fails. */ +const send = (request: HttpClientRequest.HttpClientRequest) => + HttpClient.execute(request).pipe( + Effect.flatMap((response) => + response.status === 401 ? Effect.succeed(undefined) : HttpClientResponse.filterStatusOk(response), + ), + Effect.provide(FetchHttpClient.layer), + ); + +/** A session on the server at `url` for a pairing code, under `label`; none when the code is refused. */ +export const exchange = (url: string, code: string, label: string) => + HttpClientRequest.post(at(url, Wire.pairPath)).pipe( + HttpClientRequest.bodyJsonUnsafe({ code, label }), + send, + Effect.flatMap((response) => + response === undefined ? Effect.succeed(undefined) : HttpClientResponse.schemaBodyJson(Wire.Device)(response), + ), + ); + +/** A ticket for one socket to the server at `url`; none once it refuses the session (revoked or lapsed). */ +export const ticket = (url: string, session: string) => + HttpClientRequest.post(at(url, Wire.ticketPath)).pipe( + HttpClientRequest.bearerToken(session), + send, + Effect.flatMap((response) => + response === undefined + ? Effect.succeed(undefined) + : Effect.map(HttpClientResponse.schemaBodyJson(Wire.Ticket)(response), (body) => body.ticket), + ), + ); + +export * as Pairing from "./pairing.ts"; diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index bfddd271..dcaf075e 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -106,7 +106,9 @@ const rpc = RpcServer.layerHttp({ group: Contract.Api, path: "/rpc", protocol: " export const layer = Layer.unwrap( Effect.map(Door.make, (token) => Layer.mergeAll( - HttpRouter.serve(Layer.merge(rpc, Door.layer({ token, origins: ORIGINS })), { disableListenLog: true }), + HttpRouter.serve(Layer.merge(rpc, Door.layer({ admit: Door.token(token), origins: ORIGINS })), { + disableListenLog: true, + }), Widgets.layer, exitWithParent, ).pipe( diff --git a/apps/server/src/servers.ts b/apps/server/src/servers.ts index 944c4337..b5622839 100644 --- a/apps/server/src/servers.ts +++ b/apps/server/src/servers.ts @@ -3,8 +3,15 @@ import { SqlClient } from "effect/sql"; /* @effect-diagnostics nodeBuiltinImport:off -- paths typed in Settings expand against the OS home directory. */ 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"; +import { + type CliEnvVar, + LOCAL_SERVER, + PairingRefused, + type ServerAdd, + ServersError, + type ServerUpdate, +} from "@codeworksh/contract"; +import { Pairing } from "./pairing.ts"; /** 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( @@ -59,12 +66,12 @@ export interface LocalRow extends Naming { readonly isDefault: boolean; } -/** A remote server as stored: where the app reaches it, and the token its door takes. */ +/** A remote server as stored: where the app reaches it, and the session it paired for. */ 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. */ + /** The session token its pairing gave; none once the server refused it, or on a row from before pairing. */ readonly token: string | null; readonly isDefault: boolean; } @@ -87,14 +94,6 @@ 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(); @@ -173,8 +172,10 @@ export class Service extends Context.Service< readonly watch: Stream.Stream>; /** Stores the name a server reports, when it is not the one stored. */ readonly setHost: (id: string, host: string | null) => Effect.Effect; - readonly add: (input: ServerAdd) => Effect.Effect; - readonly update: (input: ServerUpdate) => Effect.Effect; + readonly add: (input: ServerAdd) => Effect.Effect; + readonly update: (input: ServerUpdate) => Effect.Effect; + /** Drops a remote server's session once the server refused it, unless the row paired again since. */ + readonly unpair: (id: string, token: string) => Effect.Effect; readonly remove: (id: string) => Effect.Effect; readonly setDefault: (id: string) => Effect.Effect; } @@ -269,6 +270,22 @@ export const layer = Layer.effect( return trimmed === "" ? null : trimmed; }; + /** A session on the remote server at `url` for the code typed in Settings, named after this computer. */ + const pair = (url: string, code: string) => + Effect.gen(function* () { + const label = ((yield* list).find((row) => row.id === LOCAL_SERVER)?.host ?? os.hostname()).slice(0, 100); + const device = yield* Pairing.exchange(url, code.trim(), label).pipe( + Effect.timeout("10 seconds"), + Effect.mapError(() => fail("Couldn't pair with the server at that URL. Check the URL, then try again.")), + ); + if (device === undefined) + return yield* new PairingRefused({ + message: + "That pairing code was not accepted. Run `codework service pair` on that machine for a new one.", + }); + return device.token; + }); + const transaction = (effect: Effect.Effect) => sql.withTransaction(effect).pipe(Effect.catchTag("SqlError", Effect.die)); @@ -294,7 +311,10 @@ 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), token: yield* chosenToken(input.token) }; + : yield* Effect.gen(function* () { + const url = yield* chosenUrl(input.url); + return { url, token: yield* pair(url, input.code) }; + }); yield* transaction( Effect.gen(function* () { if (home !== null) yield* ensureOwnHome(null, home); @@ -315,6 +335,21 @@ export const layer = Layer.effect( }), update: Effect.fn("Servers.update")(function* ({ id, ...patch }) { + // Paired before the transaction, which would otherwise hold the database through a network call. + const { code } = patch; + const session = + code === undefined + ? undefined + : yield* get(id).pipe( + Effect.flatMap((row) => + row.kind === "remote" + ? Effect.flatMap( + patch.url === undefined ? Effect.succeed(row.url) : chosenUrl(patch.url), + (url) => pair(url, code), + ) + : Effect.fail(fail("Only a remote server has a pairing code.")), + ), + ); yield* transaction( Effect.gen(function* () { const row = yield* get(id); @@ -324,10 +359,9 @@ 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); + if (session !== undefined) fields.token = session; } 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)); @@ -346,6 +380,13 @@ export const layer = Layer.effect( yield* announce; }), + unpair: Effect.fn("Servers.unpair")(function* (id, token) { + const changed = yield* sql` + UPDATE machine SET token = NULL WHERE id = ${id} AND token = ${token} RETURNING id + `.pipe(Effect.orDie); + if (changed.length > 0) yield* announce; + }), + // What was synced from the server goes with it, its rows cascading, except its usage: history. remove: Effect.fn("Servers.remove")(function* (id) { const row = yield* get(id); diff --git a/apps/server/src/sync.ts b/apps/server/src/sync.ts index 1dd68438..df83337c 100644 --- a/apps/server/src/sync.ts +++ b/apps/server/src/sync.ts @@ -489,6 +489,8 @@ export const layer = Layer.effect( /** A machine for as long as it is configured: connected, and reconnected after any drop. */ const follow = (row: Servers.Row) => Effect.gen(function* () { + // Nothing to connect with until it is paired again. + if (row.kind === "remote" && row.token === null) return yield* Effect.never; const context = yield* Layer.build(Codework.machine(row)).pipe( Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Servers.Service, servers), diff --git a/apps/server/test/__artifacts__/door.json b/apps/server/test/__artifacts__/door.json index 5ef2f393..d6307685 100644 --- a/apps/server/test/__artifacts__/door.json +++ b/apps/server/test/__artifacts__/door.json @@ -14,20 +14,75 @@ "token in the response": false }, "the last start's token": 401, - "right token": { + "after the local server restarts": { "synced": true }, - "wrong token and none": { - "wrong": { + "a good code": { + "synced": true, + "status": { + "id": "", + "kind": "remote", + "name": "Scripted", + "host": "Fixture", + "override": "Scripted", + "isDefault": false, + "url": "", + "paired": true + } + }, + "a wrong code": { + "_tag": "Server.PairingRefused", + "message": "That pairing code was not accepted. Run `codework service pair` on that machine for a new one." + }, + "a row from before pairing": { + "row": { "store_id": null, "cursor": 0 }, - "stored": { - "store_id": null, - "cursor": 0 + "status": { + "id": "stored", + "kind": "remote", + "name": "", + "host": null, + "override": null, + "isDefault": false, + "url": "", + "paired": false } }, - "wrong token, replaced": { + "after the machine restarts": { "synced": true + }, + "after device.revoke": { + "session": null, + "status": { + "id": "", + "kind": "remote", + "name": "Scripted", + "host": "Fixture", + "override": "Scripted", + "isDefault": false, + "url": "", + "paired": false + } + }, + "devices": [ + { + "label": "Fixture" + } + ], + "paired again": { + "synced": true, + "status": { + "id": "", + "kind": "remote", + "name": "Scripted", + "host": "Fixture", + "override": "Scripted", + "isDefault": false, + "url": "", + "paired": true + }, + "a new session": true } } diff --git a/apps/server/test/__artifacts__/schema.json b/apps/server/test/__artifacts__/schema.json index 5241a46e..f52905e2 100644 --- a/apps/server/test/__artifacts__/schema.json +++ b/apps/server/test/__artifacts__/schema.json @@ -253,7 +253,7 @@ }, "servers": { "badUrl": "Use a WebSocket URL, such as wss://codework.example.com/rpc.", - "badToken": "Use the token in `token` in that machine's CodeWork home.", + "badCode": "That pairing code was not accepted. Run `codework service pair` on that machine for a new one.", "added": [ { "id": "local", @@ -265,10 +265,11 @@ "id": "", "kind": "remote", "name": "Cloud", - "host": null, + "host": "Fixture", "override": "Cloud", "isDefault": false, - "url": "wss://cloud.example.test/rpc" + "url": "", + "paired": true } ], "updated": [ @@ -282,16 +283,17 @@ "id": "", "kind": "remote", "name": "Cloud tunnel", - "host": null, + "host": "Fixture", "override": "Cloud tunnel", "isDefault": false, - "url": "wss://tunnel.example.test/rpc" + "url": "wss://tunnel.example.test/rpc", + "paired": true } ], "refused": { "localPatch": "A remote server has no executable, home, arguments or variables.", "urlOnLocal": "Only a remote server has a URL.", - "tokenOnLocal": "Only a remote server has a token.", + "codeOnLocal": "Only a remote server has a pairing code.", "defaultRemote": "Cloud tunnel is a remote server.", "serviceRemote": "Cloud tunnel is a remote server." }, @@ -299,7 +301,7 @@ "id": "", "kind": "remote", "name": "Cloud tunnel", - "host": null, + "host": "Fixture", "executable": null, "home": null, "args": "", @@ -308,14 +310,14 @@ "namespace": "codework", "is_default": 0, "pos": 1, - "store_id": null, + "store_id": "", "cursor": 0, - "boot": null, + "boot": "", "rollup": 0, - "rollup_store": null, - "rollup_boot": null, + "rollup_store": "", + "rollup_boot": "", "created_at": "