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
1 change: 1 addition & 0 deletions packages/codework/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
},
"optionalDependencies": {
"@daytona/sdk": "^0.211.2",
"@number0/iroh": "1.2.0",
"@vercel/sandbox": "^3.3.0"
},
"engines": {
Expand Down
8 changes: 5 additions & 3 deletions packages/codework/src/cli/cmd/handlers/service/pair.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ import { Cmd } from "../../cmd.ts";
export default Runtime.handler(
Cmd.commands.service.commands.pair,
Effect.fn("CLI.service.pair")(function* () {
const { code, fingerprint } = yield* Effect.flatMap(Client.make, (rpc) => rpc["device.pair"]({})).pipe(
Service.connect(),
);
const { code, fingerprint, endpointId, irohRelayUrl } = yield* Effect.flatMap(Client.make, (rpc) =>
rpc["device.pair"]({}),
).pipe(Service.connect());
yield* writeOut(`${code}\n`);
yield* writeError(`machine key: ${fingerprint}\n`);
yield* writeError(`endpoint id: ${endpointId}\n`);
if (irohRelayUrl !== null) yield* writeError(`iroh relay: ${irohRelayUrl}\n`);
yield* writeError("note: this code gives the computer that uses it full access to this machine\n");
}, Effect.catch(reportFailure)),
);
9 changes: 8 additions & 1 deletion packages/codework/src/machine/heartbeat.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Global } from "@codeworksh/harness/effect";
import { Effect, Layer, Schedule } from "effect";
import * as Door from "../server/door.ts";
import * as Iroh from "../server/iroh.ts";
import * as Relay from "./relay.ts";

/**
Expand All @@ -11,7 +13,12 @@ import * as Relay from "./relay.ts";
export const layer = Layer.effectDiscard(
Effect.gen(function* () {
const global = yield* Global.Service;
yield* Relay.heartbeat(global.home).pipe(
const iroh = yield* Iroh.Service;
const connections = yield* Door.Connections;
yield* Effect.gen(function* () {
const irohRelayUrl = yield* iroh.homeRelayUrl;
yield* Relay.heartbeat(global.home, { irohRelayUrl, onRevoked: connections.endAllActors });
}).pipe(
Effect.catch((error) => Effect.logDebug("Machine heartbeat failed", error)),
Effect.repeat(Schedule.spaced("30 seconds")),
Effect.forkScoped,
Expand Down
9 changes: 7 additions & 2 deletions packages/codework/src/machine/relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,10 @@ const revoke = (
* `MachineRevoked`, clears local `relay` state. If the machine is `leaving`, retries revoke until
* Relay confirms and then clears local `relay` state.
*/
export const heartbeat = Effect.fn("Machine.heartbeat")(function* (home: string) {
export const heartbeat = Effect.fn("Machine.heartbeat")(function* (
home: string,
options: { readonly irohRelayUrl?: string | null; readonly onRevoked?: Effect.Effect<void> } = {},
) {
const stored = yield* File.read(home);
if (stored._tag === "None") return;
const machine = stored.value;
Expand All @@ -174,6 +177,7 @@ export const heartbeat = Effect.fn("Machine.heartbeat")(function* (home: string)
const relayUrl = machine.relay.url;

if (machine.relay.leaving === true) {
if (options.onRevoked !== undefined) yield* options.onRevoked;
const revoked = yield* revoke(identified, relayUrl);
if (revoked) {
yield* File.clearRelay(home, relayUrl).pipe(
Expand All @@ -183,7 +187,7 @@ export const heartbeat = Effect.fn("Machine.heartbeat")(function* (home: string)
return;
}

const info = yield* describe(machine);
const info = yield* describe(machine, options.irohRelayUrl ?? null);
yield* Effect.gen(function* () {
const api = yield* at(relayUrl);
const claims: Relay.HeartbeatClaims = {
Expand All @@ -200,6 +204,7 @@ export const heartbeat = Effect.fn("Machine.heartbeat")(function* (home: string)
"Relay.MachineRevoked": (revoked) =>
Effect.logWarning(`Deregistered from ${relayUrl}: ${revoked.message}`).pipe(
Effect.andThen(File.clearRelay(home, relayUrl)),
Effect.andThen(options.onRevoked ?? Effect.void),
),
// 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 ${relayUrl} refused: ${refused.message}`),
Expand Down
204 changes: 204 additions & 0 deletions packages/codework/src/server/authority.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
import { Global } from "@codeworksh/harness/effect";
import { Actor } from "@codeworksh/schema/actor";
import { Jws } from "@codeworksh/schema/jws";
import { Relay } from "@codeworksh/schema/relay";
import { NodeServices } from "@effect/platform-node";
import { Clock, Context, Duration, Effect, Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { HttpApiClient } from "effect/http-api";
import * as MachineFile from "../machine/file.ts";
import * as Door from "./door.ts";

/** Tunable timings for Relay access checks and negative caching; tests shorten these for fast runs. */
export interface Timings {
readonly refreshInterval: Duration.Input;
readonly answerLife: Duration.Input;
readonly negativeCacheTtl: Duration.Input;
readonly requestTimeout: Duration.Input;
}

const defaultTimings: Timings = {
refreshInterval: "15 seconds",
answerLife: "30 seconds",
negativeCacheTtl: "10 seconds",
requestTimeout: "5 seconds",
};

export const Config = Context.Reference<Timings>("@codeworksh/cli/server/authority/Config", {
defaultValue: () => defaultTimings,
});

export type Decision = { readonly allowed: true; readonly name: string | null } | { readonly allowed: false };

type ProbeResult =
| { readonly _tag: "Allowed"; readonly name: string | null }
| { readonly _tag: "Denied"; readonly cache: boolean }
| { readonly _tag: "Unavailable" };

/**
* The single service on a machine that asks Relay whether an incoming actor may view this machine.
* Enforces local enrollment (`EnrolledOnly`), reserves root id/scope (`NoRootOverRelay`), caches
* recent denials for 10s on admission, refreshes standing answers every 15s, fails closed at 30s,
* and drops local Relay config + all open actor connections immediately on `MachineRevoked`.
*/
export class Service extends Context.Service<
Service,
{
/** Initial admission check for an incoming Iroh `actor` hello. */
readonly admit: (endpoint: string, actor: Actor.ActorRef) => Effect.Effect<Decision>;
/**
* Keeps an admitted actor connection valid by refreshing with Relay at half-life. Ends `key`
* via {@link Door.Connections.end} immediately on denial, unenrollment, `MachineRevoked`, or
* if no fresh `allowed: true` arrives before `answerLife` elapses.
*/
readonly watch: (key: string, endpoint: string, actor: Actor.ActorRef) => Effect.Effect<void>;
}
>()("@codeworksh/cli/server/authority/Service") {}

const isReservedRoot = (actor: Actor.ActorRef) => actor.id === Actor.root.id || actor.scope === Actor.root.scope;

const cacheKey = (endpoint: string, actor: Actor.ActorRef) => `${endpoint}\0${actor.id}\0${actor.scope}`;

export const layer = Layer.effect(
Service,
Effect.gen(function* () {
const global = yield* Global.Service;
const connections = yield* Door.Connections;
const timings = yield* Config;
const refreshMs = Duration.toMillis(timings.refreshInterval);
const lifeMs = Duration.toMillis(timings.answerLife);
const negativeMs = Duration.toMillis(timings.negativeCacheTtl);

// Short-lived negative cache bounding outbound Relay checks if an unauthorized peer loops Hello.
const deniedUntil = new Map<string, number>();

const probe = Effect.fn("Authority.probe")(function* (
endpoint: string,
actor: Actor.ActorRef,
timeout: Duration.Input = timings.requestTimeout,
): Effect.fn.Return<ProbeResult> {
// Machine-side invariant NoRootOverRelay: root id and scope never come through Relay.
if (isReservedRoot(actor)) return { _tag: "Denied", cache: false };

// Machine-side invariant EnrolledOnly: unregistered or locally leaving machines admit no actors.
const stored = yield* MachineFile.read(global.home).pipe(
Effect.provide(NodeServices.layer),
Effect.orElseSucceed(() => ({ _tag: "None" }) as const),
);
if (
stored._tag === "None" ||
stored.value.identity === undefined ||
stored.value.relay === undefined ||
stored.value.relay.leaving === true
) {
return { _tag: "Denied", cache: false };
}
const { identity, relay } = stored.value;
const relayUrl = relay.url;

const claims: Relay.CheckClaims = {
op: "machine.check",
iat: yield* Clock.currentTimeMillis,
endpoint,
actor,
action: "view",
};

return yield* Effect.gen(function* () {
const api = yield* HttpApiClient.make(Relay.Api, { baseUrl: relayUrl }).pipe(
Effect.provide(FetchHttpClient.layer),
);
const jws = yield* Jws.sign(claims, identity.key, { kid: identity.keyId });
const answer = yield* api.machine.check({ payload: { jws } });
return answer.allowed
? ({ _tag: "Allowed", name: answer.name } as const)
: ({ _tag: "Denied", cache: true } as const);
}).pipe(
Effect.timeout(timeout),
Effect.catchTag("Relay.MachineRevoked", (revoked) =>
Effect.logWarning(`Machine revoked at ${relayUrl}: ${revoked.message}`).pipe(
Effect.andThen(
MachineFile.clearRelay(global.home, relayUrl).pipe(
Effect.provide(NodeServices.layer),
Effect.ignore,
),
),
Effect.andThen(connections.endAllActors),
Effect.as({ _tag: "Denied", cache: false } as const),
),
),
Effect.catch((error) =>
Effect.logDebug(`Relay check at ${relayUrl} failed`, error).pipe(
Effect.as({ _tag: "Unavailable" } as const),
),
),
);
});

const rememberDenied = (key: string, now: number) => {
if (deniedUntil.size > 1024) {
for (const [entry, expires] of deniedUntil) if (expires <= now) deniedUntil.delete(entry);
}
deniedUntil.set(key, now + negativeMs);
};

return Service.of({
admit: Effect.fn("Authority.admit")(function* (endpoint, actor) {
if (isReservedRoot(actor)) return { allowed: false };
const now = yield* Clock.currentTimeMillis;
const key = cacheKey(endpoint, actor);
const cached = deniedUntil.get(key);
if (cached !== undefined && cached > now) return { allowed: false };

const result = yield* probe(endpoint, actor);
if (result._tag === "Allowed") {
deniedUntil.delete(key);
return { allowed: true, name: result.name };
}
if (result._tag === "Denied") {
if (result.cache) rememberDenied(key, yield* Clock.currentTimeMillis);
}
return { allowed: false };
}),

watch: Effect.fn("Authority.watch")(function* (connKey, endpoint, actor) {
const requestTimeoutMs = Duration.toMillis(timings.requestTimeout);
const retryGapMs = Math.max(50, Math.floor(refreshMs / 4));
const start = yield* Clock.currentTimeMillis;
let expiresAt = start + lifeMs;
let nextCheckAt = start + refreshMs;
while (connections.find(connKey) !== undefined) {
const now = yield* Clock.currentTimeMillis;
if (now >= expiresAt) {
yield* connections.end(connKey);
return;
}
const waitMs = Math.max(1, Math.min(nextCheckAt, expiresAt) - now);
yield* Effect.sleep(Duration.millis(waitMs));
if (connections.find(connKey) === undefined) return;
const beforeProbe = yield* Clock.currentTimeMillis;
const remaining = expiresAt - beforeProbe;
if (remaining <= 0) {
yield* connections.end(connKey);
return;
}
const result = yield* probe(endpoint, actor, Duration.millis(Math.min(requestTimeoutMs, remaining)));
const after = yield* Clock.currentTimeMillis;
if (result._tag === "Allowed") {
expiresAt = after + lifeMs;
nextCheckAt = after + refreshMs;
continue;
}
if (result._tag === "Denied") {
if (result.cache) rememberDenied(cacheKey(endpoint, actor), after);
yield* connections.end(connKey);
return;
}
// Unavailable (Relay down): do NOT extend expiresAt. Retry sooner if time remains,
// and fail closed once the standing answer's life runs out.
nextCheckAt = after + retryGapMs;
}
}),
});
}),
);
Loading