Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions apps/contract/src/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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 `<home>/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({
Expand All @@ -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,
Expand All @@ -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;

Expand All @@ -475,6 +478,11 @@ export class ServersError extends Schema.TaggedError<ServersError>()("Server.Ser
message: Schema.String,
}) {}

/** A remote server refused the pairing code: wrong, used or expired. */
export class PairingRefused extends Schema.TaggedError<PairingRefused>()("Server.PairingRefused", {
message: Schema.String,
}) {}

/** The app bus topics the sync publishes on. */
export const syncTopics = {
/** `SyncChanged` after each applied batch; stored. */
Expand Down Expand Up @@ -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", {
Expand Down
6 changes: 3 additions & 3 deletions apps/server/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
32 changes: 28 additions & 4 deletions apps/server/src/codework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: `<home>/service.json`, written by `codework serve`. */
Expand All @@ -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;
Expand All @@ -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 = <R>(target: Effect.Effect<Target, never, R>, options?: { readonly openTimeout?: Duration.Input }) =>
const open = <R>(
target: Effect.Effect<Target, Socket.SocketError, R>,
options?: { readonly openTimeout?: Duration.Input },
) =>
Socket.WebSocketConstructor.use((make) =>
Socket.fromWebSocket(
Effect.acquireRelease(
Expand Down Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`;
Expand Down
8 changes: 5 additions & 3 deletions apps/server/src/health.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
42 changes: 42 additions & 0 deletions apps/server/src/pairing.ts
Original file line number Diff line number Diff line change
@@ -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";
4 changes: 3 additions & 1 deletion apps/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
75 changes: 58 additions & 17 deletions apps/server/src/servers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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;
}
Expand All @@ -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();
Expand Down Expand Up @@ -173,8 +172,10 @@ export class Service extends Context.Service<
readonly watch: Stream.Stream<ReadonlyArray<Row>>;
/** Stores the name a server reports, when it is not the one stored. */
readonly setHost: (id: string, host: string | null) => Effect.Effect<void>;
readonly add: (input: ServerAdd) => Effect.Effect<string, ServersError>;
readonly update: (input: ServerUpdate) => Effect.Effect<void, ServersError>;
readonly add: (input: ServerAdd) => Effect.Effect<string, ServersError | PairingRefused>;
readonly update: (input: ServerUpdate) => Effect.Effect<void, ServersError | PairingRefused>;
/** 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<void>;
readonly remove: (id: string) => Effect.Effect<void, ServersError>;
readonly setDefault: (id: string) => Effect.Effect<void, ServersError>;
}
Expand Down Expand Up @@ -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 = <A, E>(effect: Effect.Effect<A, E>) =>
sql.withTransaction(effect).pipe(Effect.catchTag("SqlError", Effect.die));

Expand All @@ -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);
Expand All @@ -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);
Expand All @@ -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));
Expand All @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Loading