The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import { |
| 2 | AuthMcpClientAccess, |
| 3 | AuthMcpRegistrationError, |
| 4 | AuthMcpTokenError, |
| 5 | EnvironmentHttpApi, |
| 6 | EnvironmentId, |
| 7 | type ExecutionEnvironmentCapabilities, |
| 8 | MCP_PEER_LINK_SOFTWARE_ID, |
| 9 | type PeerLink, |
| 10 | type PeerLinkCreateInput, |
| 11 | PeerLinkError, |
| 12 | type PeerLinkName, |
| 13 | type PeerLinkSummary, |
| 14 | } from "@t3tools/contracts"; |
| 15 | import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; |
| 16 | import * as Cause from "effect/Cause"; |
| 17 | import * as Context from "effect/Context"; |
| 18 | import * as Digest from "effect/crypto/Digest"; |
| 19 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 20 | import * as DateTime from "effect/DateTime"; |
| 21 | import * as Duration from "effect/Duration"; |
| 22 | import * as Effect from "effect/Effect"; |
| 23 | import * as Base64Url from "effect/encoding/Base64Url"; |
| 24 | import * as Hex from "effect/encoding/Hex"; |
| 25 | import * as Layer from "effect/Layer"; |
| 26 | import * as Option from "effect/Option"; |
| 27 | import * as Predicate from "effect/Predicate"; |
| 28 | import * as Redacted from "effect/Redacted"; |
| 29 | import * as Result from "effect/Result"; |
| 30 | import * as Schedule from "effect/Schedule"; |
| 31 | import * as Schema from "effect/Schema"; |
| 32 | import * as SqlClient from "effect/sql/SqlClient"; |
| 33 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 34 | import * as HttpClient from "effect/http/HttpClient"; |
| 35 | import * as HttpClientError from "effect/http/HttpClientError"; |
| 36 | import * as HttpApi from "effect/http-api/HttpApi"; |
| 37 | import * as HttpApiClient from "effect/http-api/HttpApiClient"; |
| 38 | import { isLocalLoopbackHost, isTailnetHost } from "@t3tools/shared/hostClassification"; |
| 39 | |
| 40 | import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; |
| 41 | import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; |
| 42 | import * as ServerSettings from "../serverSettings.ts"; |
| 43 | |
| 44 | const PeerHttpApi = HttpApi.make(EnvironmentHttpApi.identifier) |
| 45 | .add(EnvironmentHttpApi.groups.metadata) |
| 46 | .add(EnvironmentHttpApi.groups.mcpOAuth) |
| 47 | .annotateMerge(EnvironmentHttpApi.annotations); |
| 48 | |
| 49 | /** The redirect registered for a link. Nothing ever listens there: the code comes back in the response. */ |
| 50 | const LINK_REDIRECT_URI = "http://127.0.0.1/t3code-peer-link"; |
| 51 | /** |
| 52 | * How long a peer's descriptor or MCP handshake may take before a route counts |
| 53 | * as unreachable. A tailnet or relayed route to a machine that is waking up takes longer. |
| 54 | */ |
| 55 | export const probeTimeout = (origin: string) => |
| 56 | isLocalLoopbackHost(new URL(origin).hostname) ? Duration.seconds(3) : Duration.seconds(10); |
| 57 | /** How long a listing waits on a link's addresses; a real call still gives a waking peer `probeTimeout`. */ |
| 58 | const LIST_PROBE_TIMEOUT = Duration.seconds(3); |
| 59 | |
| 60 | /** Node's TLS verification code in a failed request's cause chain, if any. */ |
| 61 | export const certificateErrorCode = (error: unknown) => { |
| 62 | let current = error; |
| 63 | for (let depth = 0; depth < 6 && Predicate.isObject(current); depth++) { |
| 64 | if ( |
| 65 | Predicate.hasProperty(current, "code") && |
| 66 | typeof current.code === "string" && |
| 67 | /CERT|SELF_SIGNED|UNABLE_TO_(GET|VERIFY)|INVALID_(CA|PURPOSE)|PATH_LENGTH_EXCEEDED|HOSTNAME_MISMATCH/.test( |
| 68 | current.code, |
| 69 | ) |
| 70 | ) |
| 71 | return current.code; |
| 72 | current = Predicate.hasProperty(current, "cause") ? current.cause : undefined; |
| 73 | } |
| 74 | return undefined; |
| 75 | }; |
| 76 | |
| 77 | /** A usable link: where to reach the peer and the token to send there. */ |
| 78 | export interface ResolvedPeerLink { |
| 79 | readonly link: PeerLink; |
| 80 | /** The first address that answered as this peer. */ |
| 81 | readonly url: string; |
| 82 | readonly token: string; |
| 83 | /** What the peer said it can do when it answered. */ |
| 84 | readonly capabilities: ExecutionEnvironmentCapabilities; |
| 85 | } |
| 86 | |
| 87 | /** What a link's session is called in the peer's Connections, before this environment's label. */ |
| 88 | export const LINK_CLIENT_NAME_PREFIX = "T3 Code · "; |
| 89 | |
| 90 | export const LINKED_ENVIRONMENTS_OFF = |
| 91 | "Linked environments is off on this machine. Turn it on in Settings → Labs."; |
| 92 | |
| 93 | /** |
| 94 | * Links from this environment to others. Linking signs this environment in to |
| 95 | * the peer's `/mcp` as an outside agent with a pairing code from the peer, the |
| 96 | * same MCP OAuth flow an outside agent uses, without a browser. The peer's |
| 97 | * session token is kept in the server secret store; the table keeps the rest. |
| 98 | */ |
| 99 | export class PeerLinks extends Context.Service< |
| 100 | PeerLinks, |
| 101 | { |
| 102 | /** Whether the Linked environments beta (Settings → Labs) is on here. */ |
| 103 | readonly enabled: Effect.Effect<boolean>; |
| 104 | readonly link: (input: PeerLinkCreateInput) => Effect.Effect<PeerLink, PeerLinkError>; |
| 105 | /** |
| 106 | * Links like `link`, except that a machine whose link has not expired is |
| 107 | * left as it is, with its pairing code unused. |
| 108 | */ |
| 109 | readonly linkUnlessLinked: ( |
| 110 | input: PeerLinkCreateInput, |
| 111 | ) => Effect.Effect<{ readonly link: PeerLink; readonly alreadyLinked: boolean }, PeerLinkError>; |
| 112 | readonly list: Effect.Effect<ReadonlyArray<PeerLinkSummary>, PeerLinkError>; |
| 113 | /** The unexpired links' names, from what is stored, without asking any peer. */ |
| 114 | readonly names: Effect.Effect<ReadonlyArray<PeerLinkName>, PeerLinkError>; |
| 115 | /** The stored link, without asking the peer whether it answers. */ |
| 116 | readonly get: ( |
| 117 | environmentId: EnvironmentId, |
| 118 | ) => Effect.Effect<Option.Option<PeerLink>, PeerLinkError>; |
| 119 | /** Forgets the link here. The peer still lists the session until it is revoked there. */ |
| 120 | readonly unlink: (environmentId: EnvironmentId) => Effect.Effect<boolean, PeerLinkError>; |
| 121 | /** An address that answers as the linked peer, with its token, ready to call. */ |
| 122 | readonly resolve: ( |
| 123 | environmentId: EnvironmentId, |
| 124 | ) => Effect.Effect<ResolvedPeerLink, PeerLinkError>; |
| 125 | /** Records the outcome of a call, so listing shows whether the peer answered last time. */ |
| 126 | readonly recordOutcome: ( |
| 127 | environmentId: EnvironmentId, |
| 128 | outcome: { readonly error: string | null }, |
| 129 | ) => Effect.Effect<void>; |
| 130 | /** Records a later end the peer gives the link's session: using a link renews it there. */ |
| 131 | readonly recordExpiry: ( |
| 132 | environmentId: EnvironmentId, |
| 133 | expiresAt: DateTime.Utc, |
| 134 | ) => Effect.Effect<void>; |
| 135 | } |
| 136 | >()("t3/peer/PeerLinks") {} |
| 137 | |
| 138 | interface PeerLinkRow { |
| 139 | readonly environment_id: string; |
| 140 | readonly secret_name: string; |
| 141 | readonly label: string; |
| 142 | readonly urls_json: string; |
| 143 | readonly access: string; |
| 144 | readonly linked_at: string; |
| 145 | readonly expires_at: string; |
| 146 | readonly last_reached_at: string | null; |
| 147 | readonly last_error: string | null; |
| 148 | readonly fenced: number; |
| 149 | } |
| 150 | |
| 151 | const decodeUrls = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Array(Schema.String))); |
| 152 | const encodeUrls = Schema.encodeEffect(Schema.fromJsonString(Schema.Array(Schema.String))); |
| 153 | const decodeAccess = Schema.decodeUnknownEffect(AuthMcpClientAccess); |
| 154 | |
| 155 | /** Fails with a fixed storage error that keeps its cause; the log gets the details. */ |
| 156 | const failStorage = (cause: unknown) => |
| 157 | Effect.logWarning("Peer link storage failed", cause).pipe( |
| 158 | Effect.andThen( |
| 159 | Effect.fail( |
| 160 | new PeerLinkError({ |
| 161 | reason: "storage", |
| 162 | message: |
| 163 | "Linked environments could not be read or saved here. The server log has details.", |
| 164 | cause, |
| 165 | }), |
| 166 | ), |
| 167 | ), |
| 168 | ); |
| 169 | |
| 170 | /** |
| 171 | * The base URL a peer is reached at, normalised to its origin. The pairing |
| 172 | * code and then the link's token travel to it, so plain http is accepted only |
| 173 | * where the network already encrypts: this machine, or a Tailscale address. |
| 174 | */ |
| 175 | const peerOrigin = (url: string) => { |
| 176 | const parsed = URL.parse(url); |
| 177 | if (parsed === null || (parsed.protocol !== "https:" && parsed.protocol !== "http:")) { |
| 178 | return Effect.fail( |
| 179 | new PeerLinkError({ |
| 180 | reason: "unreachable", |
| 181 | // Never the address as given: it may hold a username, password or query. |
| 182 | message: "That address is not an http or https address.", |
| 183 | }), |
| 184 | ); |
| 185 | } |
| 186 | if ( |
| 187 | parsed.protocol === "http:" && |
| 188 | !isLocalLoopbackHost(parsed.hostname) && |
| 189 | !isTailnetHost(parsed.hostname) |
| 190 | ) { |
| 191 | return Effect.fail( |
| 192 | new PeerLinkError({ |
| 193 | reason: "unreachable", |
| 194 | message: `${parsed.origin} is plain http, which would send the link's credentials unencrypted. Use its https address, or its Tailscale address.`, |
| 195 | }), |
| 196 | ); |
| 197 | } |
| 198 | return Effect.succeed(parsed.origin); |
| 199 | }; |
| 200 | |
| 201 | /** The system error under a failed connection, such as ECONNREFUSED or ENOTFOUND. */ |
| 202 | const connectionCode = (cause: unknown) => |
| 203 | [cause, Predicate.hasProperty(cause, "cause") ? cause.cause : undefined] |
| 204 | .map((error) => (Predicate.hasProperty(error, "code") ? error.code : undefined)) |
| 205 | .find(Predicate.isString); |
| 206 | |
| 207 | /** Why `origin` did not answer as T3 Code, short enough for a toast. Never echoes a body. */ |
| 208 | const probeFailure = ( |
| 209 | origin: string, |
| 210 | error: HttpClientError.HttpClientError | Schema.SchemaError | Cause.TimeoutError, |
| 211 | timeout: Duration.Duration, |
| 212 | ) => { |
| 213 | const unreachable = (message: string) => new PeerLinkError({ reason: "unreachable", message }); |
| 214 | const certificate = certificateErrorCode(error); |
| 215 | if (certificate !== undefined) { |
| 216 | return unreachable(`${origin} presented a certificate this machine rejected (${certificate}).`); |
| 217 | } |
| 218 | if (Cause.isTimeoutError(error)) { |
| 219 | return unreachable(`${origin} did not answer within ${Duration.toSeconds(timeout)} seconds.`); |
| 220 | } |
| 221 | if (HttpClientError.isHttpClientError(error) && error.reason._tag === "TransportError") { |
| 222 | const code = connectionCode(error.reason.cause); |
| 223 | return unreachable( |
| 224 | code === undefined ? `${origin} did not answer.` : `${origin} did not answer (${code}).`, |
| 225 | ); |
| 226 | } |
| 227 | return new PeerLinkError({ |
| 228 | reason: "not_a_t3_environment", |
| 229 | message: `${origin} answered, but not as a T3 Code environment this version understands.`, |
| 230 | }); |
| 231 | }; |
| 232 | |
| 233 | /** Whether a host is this machine's own loopback. Tests serve their peers there, so they narrow it. */ |
| 234 | export const LoopbackHost = Context.Reference<(host: string) => boolean>( |
| 235 | "t3/peer/PeerLinks/LoopbackHost", |
| 236 | { defaultValue: () => isLocalLoopbackHost }, |
| 237 | ); |
| 238 | |
| 239 | /** Whether a peer holds a linked agent to its limits and keeps its work within its link. */ |
| 240 | const linkLimitsHold = (peer: { readonly capabilities: ExecutionEnvironmentCapabilities }) => |
| 241 | peer.capabilities.mcpModeLimitHeader === true && peer.capabilities.linkFence === true; |
| 242 | |
| 243 | const make = Effect.gen(function* () { |
| 244 | const sql = yield* SqlClient.SqlClient; |
| 245 | const secrets = yield* ServerSecretStore.ServerSecretStore; |
| 246 | const random = yield* SecureRandom.SecureRandom; |
| 247 | const digest = yield* Digest.Digest; |
| 248 | const httpClient = yield* HttpClient.HttpClient; |
| 249 | const environment = yield* ServerEnvironment.ServerEnvironment; |
| 250 | const serverSettings = yield* ServerSettings.ServerSettingsService; |
| 251 | const isOwnLoopback = yield* LoopbackHost; |
| 252 | const enabled = serverSettings.getSettings.pipe( |
| 253 | Effect.map((settings) => settings.linkedEnvironmentsEnabled), |
| 254 | Effect.orElseSucceed(() => false), |
| 255 | ); |
| 256 | |
| 257 | /** A fresh name for one link's token; the row records it. */ |
| 258 | const newSecretName = random.randomBytes(16).pipe( |
| 259 | Effect.map((bytes) => `peer-link-${Hex.encode(bytes)}`), |
| 260 | Effect.orDie, |
| 261 | ); |
| 262 | |
| 263 | // Only the origin `peerOrigin` checked may receive a pairing code or token: |
| 264 | // a redirect could forward them anywhere, including plain http. |
| 265 | const peerHttpClient = HttpClient.transform(httpClient, (response) => |
| 266 | Effect.provideService(response, FetchHttpClient.RequestInit, { redirect: "manual" }), |
| 267 | ); |
| 268 | |
| 269 | const clientFor = (origin: string) => |
| 270 | HttpApiClient.make(PeerHttpApi, { baseUrl: origin }).pipe( |
| 271 | Effect.provideService(HttpClient.HttpClient, peerHttpClient), |
| 272 | ); |
| 273 | |
| 274 | /** The environment answering at `origin`, or why nothing there answers as T3 Code. */ |
| 275 | const probe = (origin: string) => { |
| 276 | const timeout = probeTimeout(origin); |
| 277 | return clientFor(origin).pipe( |
| 278 | Effect.flatMap((client) => client.metadata.descriptor()), |
| 279 | // A brief network drop must not list a live peer as down; the timeout still bounds both tries. |
| 280 | Effect.retry({ |
| 281 | times: 1, |
| 282 | schedule: Schedule.spaced("1 second"), |
| 283 | while: (error) => certificateErrorCode(error) === undefined, |
| 284 | }), |
| 285 | Effect.timeout(timeout), |
| 286 | // No cause: a decode error can carry the response body to the client. |
| 287 | Effect.mapError((error) => probeFailure(origin, error, timeout)), |
| 288 | ); |
| 289 | }; |
| 290 | |
| 291 | /** Whether `url` answers as `environmentId`, counting any failure as no. */ |
| 292 | const answersAs = Effect.fn("PeerLinks.answersAs")(function* ( |
| 293 | url: string, |
| 294 | environmentId: EnvironmentId, |
| 295 | ) { |
| 296 | const found = yield* probe(url).pipe(Effect.option); |
| 297 | return Option.filter(found, (peer) => peer.environmentId === environmentId); |
| 298 | }); |
| 299 | |
| 300 | const toLink = Effect.fn("PeerLinks.toLink")(function* (row: PeerLinkRow) { |
| 301 | return { |
| 302 | environmentId: EnvironmentId.make(row.environment_id), |
| 303 | label: row.label, |
| 304 | urls: yield* decodeUrls(row.urls_json), |
| 305 | access: yield* decodeAccess(row.access), |
| 306 | linkedAt: DateTime.makeUnsafe(row.linked_at), |
| 307 | // Its token predates link fencing, so the peer would not fence its work: |
| 308 | // like an expired link, only a new pairing code brings it back. |
| 309 | expiresAt: DateTime.makeUnsafe(row.fenced === 1 ? row.expires_at : row.linked_at), |
| 310 | lastReachedAt: row.last_reached_at === null ? null : DateTime.makeUnsafe(row.last_reached_at), |
| 311 | lastError: row.last_error, |
| 312 | } satisfies PeerLink; |
| 313 | }, Effect.catch(failStorage)); |
| 314 | |
| 315 | const readRows = sql<PeerLinkRow>` |
| 316 | SELECT * FROM peer_environment_links ORDER BY label, environment_id |
| 317 | `.pipe(NodeSqliteClient.readOnly, Effect.catch(failStorage)); |
| 318 | |
| 319 | const readRow = (environmentId: EnvironmentId) => |
| 320 | sql<PeerLinkRow>` |
| 321 | SELECT * FROM peer_environment_links WHERE environment_id = ${environmentId} |
| 322 | `.pipe( |
| 323 | NodeSqliteClient.readOnly, |
| 324 | Effect.catch(failStorage), |
| 325 | Effect.map((rows) => Option.fromNullishOr(rows[0])), |
| 326 | ); |
| 327 | |
| 328 | /** Signs in to the peer's `/mcp` with a pairing code: register, decide, exchange. */ |
| 329 | const signIn = Effect.fn("PeerLinks.signIn")( |
| 330 | function* (origin: string, input: PeerLinkCreateInput, clientName: string) { |
| 331 | const client = yield* clientFor(origin); |
| 332 | // Only the peer's own refusals are rejections. A dropped connection or |
| 333 | // an answer this version cannot read is classified below. |
| 334 | const registered = yield* client.mcpOAuth |
| 335 | .register({ |
| 336 | payload: { |
| 337 | client_name: clientName, |
| 338 | redirect_uris: [LINK_REDIRECT_URI], |
| 339 | software_id: MCP_PEER_LINK_SOFTWARE_ID, |
| 340 | }, |
| 341 | }) |
| 342 | .pipe( |
| 343 | // A plain Schema.Error has no tag to catch by. |
| 344 | Effect.catchIf(Schema.is(AuthMcpRegistrationError), (error) => |
| 345 | Effect.fail( |
| 346 | new PeerLinkError({ |
| 347 | reason: "pairing_rejected", |
| 348 | message: `The peer refused to register this environment: ${error.message}`, |
| 349 | }), |
| 350 | ), |
| 351 | ), |
| 352 | ); |
| 353 | const verifier = Base64Url.encode(yield* random.randomBytes(32)); |
| 354 | const challenge = Base64Url.encode( |
| 355 | yield* digest.digest(Digest.sha256, new TextEncoder().encode(verifier)).pipe(Effect.orDie), |
| 356 | ); |
| 357 | const state = Base64Url.encode(yield* random.randomBytes(16)); |
| 358 | const resource = `${origin}/mcp`; |
| 359 | const decided = yield* client.mcpOAuth |
| 360 | .decision({ |
| 361 | headers: {}, |
| 362 | payload: { |
| 363 | authorization: { |
| 364 | response_type: "code", |
| 365 | client_id: registered.client_id, |
| 366 | redirect_uri: LINK_REDIRECT_URI, |
| 367 | code_challenge: challenge, |
| 368 | code_challenge_method: "S256", |
| 369 | state: Redacted.make(state), |
| 370 | resource, |
| 371 | }, |
| 372 | decision: { _tag: "pairing-code", access: input.access, code: input.pairingCode }, |
| 373 | }, |
| 374 | }) |
| 375 | .pipe( |
| 376 | Effect.catchTags({ |
| 377 | AuthMcpApprovalError: (error) => |
| 378 | Effect.fail( |
| 379 | new PeerLinkError({ reason: "pairing_rejected", message: error.message }), |
| 380 | ), |
| 381 | }), |
| 382 | ); |
| 383 | const redirect = URL.parse(decided.redirectTo); |
| 384 | if (redirect === null) { |
| 385 | return yield* new PeerLinkError({ |
| 386 | reason: "incompatible", |
| 387 | message: `${origin} answered the sign-in with an address this version cannot read. Update both environments.`, |
| 388 | }); |
| 389 | } |
| 390 | const code = redirect.searchParams.get("code"); |
| 391 | if (code === null || redirect.searchParams.get("state") !== state) { |
| 392 | return yield* new PeerLinkError({ |
| 393 | reason: "pairing_rejected", |
| 394 | message: |
| 395 | redirect.searchParams.get("error_description") ?? |
| 396 | "The peer did not approve the link. Check the pairing code and try again.", |
| 397 | }); |
| 398 | } |
| 399 | return yield* client.mcpOAuth |
| 400 | .token({ |
| 401 | payload: { |
| 402 | grant_type: "authorization_code", |
| 403 | code: Redacted.make(code), |
| 404 | redirect_uri: LINK_REDIRECT_URI, |
| 405 | client_id: registered.client_id, |
| 406 | code_verifier: Redacted.make(verifier), |
| 407 | resource, |
| 408 | }, |
| 409 | }) |
| 410 | .pipe( |
| 411 | Effect.catchIf(Schema.is(AuthMcpTokenError), (error) => |
| 412 | Effect.fail( |
| 413 | new PeerLinkError({ |
| 414 | reason: "pairing_rejected", |
| 415 | message: `The peer refused the sign-in: ${error.message}`, |
| 416 | }), |
| 417 | ), |
| 418 | ), |
| 419 | ); |
| 420 | }, |
| 421 | (effect, origin) => |
| 422 | effect.pipe( |
| 423 | // Endpoint errors are mapped above; what is left is the transport or an |
| 424 | // answer this version cannot decode. |
| 425 | Effect.catchTags({ |
| 426 | SchemaError: (cause) => |
| 427 | Effect.fail( |
| 428 | new PeerLinkError({ |
| 429 | reason: "incompatible", |
| 430 | message: `${origin} answered in a shape this version does not understand. Update both environments.`, |
| 431 | cause, |
| 432 | }), |
| 433 | ), |
| 434 | HttpClientError: (cause) => |
| 435 | Effect.fail( |
| 436 | new PeerLinkError({ |
| 437 | reason: "unreachable", |
| 438 | message: `${origin} stopped answering while linking.`, |
| 439 | cause, |
| 440 | }), |
| 441 | ), |
| 442 | }), |
| 443 | ), |
| 444 | ); |
| 445 | |
| 446 | /** |
| 447 | * The addresses that answer as `environmentId`, in the order given, with |
| 448 | * what the first one answered. Addresses this environment would not send |
| 449 | * credentials to are skipped; when none answers as it, the failure says why |
| 450 | * for each. |
| 451 | */ |
| 452 | const answeringAs = Effect.fn("PeerLinks.answeringAs")(function* ( |
| 453 | urls: ReadonlyArray<string>, |
| 454 | environmentId: EnvironmentId, |
| 455 | name: string, |
| 456 | ) { |
| 457 | const checked = yield* Effect.forEach( |
| 458 | urls, |
| 459 | (url) => |
| 460 | Effect.gen(function* () { |
| 461 | const origin = yield* peerOrigin(url); |
| 462 | // Loopback is this machine, where anything may answer as the one picked. |
| 463 | if (isOwnLoopback(new URL(origin).hostname)) { |
| 464 | return yield* new PeerLinkError({ |
| 465 | reason: "unreachable", |
| 466 | message: `${origin} is this machine, not ${name}.`, |
| 467 | }); |
| 468 | } |
| 469 | const descriptor = yield* probe(origin); |
| 470 | if (descriptor.environmentId !== environmentId) { |
| 471 | return yield* new PeerLinkError({ |
| 472 | reason: "unreachable", |
| 473 | message: `${origin} answered as another environment, ${descriptor.label}.`, |
| 474 | answeredAs: descriptor.label, |
| 475 | }); |
| 476 | } |
| 477 | return { origin, descriptor }; |
| 478 | }).pipe(Effect.result), |
| 479 | { concurrency: "unbounded" }, |
| 480 | ); |
| 481 | const matching = checked.flatMap((result) => |
| 482 | Result.isSuccess(result) ? [result.success] : [], |
| 483 | ); |
| 484 | const first = matching[0]; |
| 485 | if (first === undefined) { |
| 486 | const failures = checked.flatMap((result) => |
| 487 | Result.isFailure(result) ? [result.failure] : [], |
| 488 | ); |
| 489 | const answeredAs = failures.find((failure) => failure.answeredAs !== undefined)?.answeredAs; |
| 490 | return yield* new PeerLinkError({ |
| 491 | reason: "unreachable", |
| 492 | message: `This environment could not reach ${name}: ${failures.map((failure) => failure.message).join(" ")}`, |
| 493 | ...(answeredAs === undefined ? {} : { answeredAs }), |
| 494 | }); |
| 495 | } |
| 496 | // Each address is kept once, even when two spellings share an origin. |
| 497 | const origins = [...new Set(matching.map((found) => found.origin))]; |
| 498 | return { primary: first.origin, peer: first.descriptor, origins }; |
| 499 | }); |
| 500 | |
| 501 | /** The peer at `url`, with every address checked for credentials first. */ |
| 502 | const answeringAt = Effect.fn("PeerLinks.answeringAt")(function* (urls: ReadonlyArray<string>) { |
| 503 | const origins = yield* Effect.forEach(urls, peerOrigin); |
| 504 | const primary = origins[0]!; |
| 505 | return { primary, peer: yield* probe(primary), origins }; |
| 506 | }); |
| 507 | |
| 508 | const linkWith = Effect.fn("PeerLinks.link")(function* ( |
| 509 | input: PeerLinkCreateInput, |
| 510 | keepLinked: boolean, |
| 511 | ) { |
| 512 | if (!(yield* enabled)) { |
| 513 | return yield* new PeerLinkError({ reason: "disabled", message: LINKED_ENVIRONMENTS_OFF }); |
| 514 | } |
| 515 | const urls = [input.url, ...(input.alternateUrls ?? [])]; |
| 516 | // The user picked a machine: link through the addresses that answer as |
| 517 | // it, so one that now answers as another never receives the pairing code. |
| 518 | const { primary, peer, origins } = |
| 519 | input.expectedEnvironmentId === undefined |
| 520 | ? yield* answeringAt(urls) |
| 521 | : yield* answeringAs( |
| 522 | urls, |
| 523 | input.expectedEnvironmentId, |
| 524 | input.expectedLabel ?? input.expectedEnvironmentId, |
| 525 | ); |
| 526 | const row = yield* readRow(peer.environmentId); |
| 527 | const stored = Option.isSome(row) ? yield* toLink(row.value) : undefined; |
| 528 | const current = |
| 529 | stored !== undefined && DateTime.isGreaterThan(stored.expiresAt, yield* DateTime.now) |
| 530 | ? stored |
| 531 | : undefined; |
| 532 | if (keepLinked && current !== undefined) return { link: current, alreadyLinked: true }; |
| 533 | // Anything can answer as a linked machine, so an address alone renews its |
| 534 | // link only where the link already reaches it, and never moves it. |
| 535 | if ( |
| 536 | input.expectedEnvironmentId === undefined && |
| 537 | current !== undefined && |
| 538 | !current.urls.includes(primary) |
| 539 | ) { |
| 540 | return yield* new PeerLinkError({ |
| 541 | reason: "pairing_rejected", |
| 542 | message: `${primary} answers as ${current.label}, which is already linked at another address. If ${current.label} moved, forget that link first.`, |
| 543 | }); |
| 544 | } |
| 545 | const self = yield* environment.getDescriptor; |
| 546 | if (peer.environmentId === self.environmentId) { |
| 547 | return yield* new PeerLinkError({ |
| 548 | reason: "self", |
| 549 | message: "That address is this environment.", |
| 550 | }); |
| 551 | } |
| 552 | if (!linkLimitsHold(peer)) { |
| 553 | return yield* new PeerLinkError({ |
| 554 | reason: "incompatible", |
| 555 | message: `${peer.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`, |
| 556 | }); |
| 557 | } |
| 558 | const issued = yield* signIn(primary, input, `${LINK_CLIENT_NAME_PREFIX}${self.label}`); |
| 559 | const now = yield* DateTime.now; |
| 560 | const linked: PeerLink = { |
| 561 | environmentId: peer.environmentId, |
| 562 | label: peer.label, |
| 563 | urls: origins, |
| 564 | access: input.access, |
| 565 | linkedAt: now, |
| 566 | expiresAt: DateTime.add(now, { seconds: issued.expires_in }), |
| 567 | lastReachedAt: now, |
| 568 | lastError: null, |
| 569 | }; |
| 570 | // The token goes under a name of its own before the row points at it, |
| 571 | // so the row and its token are replaced together. |
| 572 | const secretName = yield* newSecretName; |
| 573 | yield* secrets |
| 574 | .set(secretName, new TextEncoder().encode(issued.access_token)) |
| 575 | .pipe(Effect.catch(failStorage)); |
| 576 | // A token no row names could never be removed. |
| 577 | const previous = yield* Effect.gen(function* () { |
| 578 | const urlsJson = yield* encodeUrls(origins).pipe(Effect.catch(failStorage)); |
| 579 | const previous = yield* readRow(peer.environmentId); |
| 580 | yield* sql` |
| 581 | INSERT INTO peer_environment_links ( |
| 582 | environment_id, secret_name, label, urls_json, access, linked_at, expires_at, |
| 583 | last_reached_at, last_error, fenced |
| 584 | ) VALUES ( |
| 585 | ${linked.environmentId}, ${secretName}, ${linked.label}, ${urlsJson}, ${linked.access}, |
| 586 | ${DateTime.formatIso(linked.linkedAt)}, ${DateTime.formatIso(linked.expiresAt)}, |
| 587 | ${DateTime.formatIso(now)}, NULL, 1 |
| 588 | ) |
| 589 | ON CONFLICT (environment_id) DO UPDATE SET |
| 590 | secret_name = excluded.secret_name, |
| 591 | fenced = excluded.fenced, |
| 592 | label = excluded.label, |
| 593 | urls_json = excluded.urls_json, |
| 594 | access = excluded.access, |
| 595 | linked_at = excluded.linked_at, |
| 596 | expires_at = excluded.expires_at, |
| 597 | last_reached_at = excluded.last_reached_at, |
| 598 | last_error = NULL |
| 599 | `.pipe(Effect.catch(failStorage)); |
| 600 | return previous; |
| 601 | }).pipe(Effect.onError(() => secrets.remove(secretName).pipe(Effect.ignore))); |
| 602 | // Linking again replaces the old token. A racing link may leave its own |
| 603 | // behind; it is unused either way. |
| 604 | if (Option.isSome(previous) && previous.value.secret_name !== secretName) { |
| 605 | yield* secrets.remove(previous.value.secret_name).pipe(Effect.ignore); |
| 606 | } |
| 607 | return { link: linked, alreadyLinked: false }; |
| 608 | }); |
| 609 | |
| 610 | const link: PeerLinks["Service"]["link"] = (input) => |
| 611 | linkWith(input, false).pipe(Effect.map((result) => result.link)); |
| 612 | const linkUnlessLinked: PeerLinks["Service"]["linkUnlessLinked"] = (input) => |
| 613 | linkWith(input, true); |
| 614 | |
| 615 | /** A peer's label follows its machine name, so the link takes the one its own address answers with. */ |
| 616 | const withLabel = (link: PeerLink, label: string) => |
| 617 | label === link.label |
| 618 | ? Effect.succeed(link) |
| 619 | : sql` |
| 620 | UPDATE peer_environment_links SET label = ${label} |
| 621 | WHERE environment_id = ${link.environmentId} |
| 622 | `.pipe(Effect.ignoreCause({ log: true }), Effect.as({ ...link, label })); |
| 623 | |
| 624 | const statusOf = Effect.fn("PeerLinks.statusOf")(function* ( |
| 625 | link: PeerLink, |
| 626 | now: DateTime.Utc, |
| 627 | ): Effect.fn.Return<PeerLinkSummary> { |
| 628 | if (DateTime.isLessThanOrEqualTo(link.expiresAt, now)) return { ...link, status: "expired" }; |
| 629 | // A race over no addresses never settles. |
| 630 | if (link.urls.length === 0) return { ...link, status: "unreachable" }; |
| 631 | const answered = yield* Effect.raceAll( |
| 632 | link.urls.map((url) => |
| 633 | answersAs(url, link.environmentId).pipe(Effect.flatMap(Effect.fromOption)), |
| 634 | ), |
| 635 | ).pipe(Effect.timeoutOption(LIST_PROBE_TIMEOUT), Effect.orElseSucceed(Option.none)); |
| 636 | if (Option.isNone(answered)) return { ...link, status: "unreachable" }; |
| 637 | return { ...(yield* withLabel(link, answered.value.label)), status: "reachable" }; |
| 638 | }); |
| 639 | |
| 640 | const list: PeerLinks["Service"]["list"] = Effect.gen(function* () { |
| 641 | const links = yield* Effect.forEach(yield* readRows, toLink); |
| 642 | const now = yield* DateTime.now; |
| 643 | return yield* Effect.forEach(links, (link) => statusOf(link, now), { |
| 644 | concurrency: "unbounded", |
| 645 | }); |
| 646 | }); |
| 647 | |
| 648 | const names: PeerLinks["Service"]["names"] = Effect.gen(function* () { |
| 649 | const links = yield* Effect.forEach(yield* readRows, toLink); |
| 650 | const now = yield* DateTime.now; |
| 651 | return links.flatMap((link) => |
| 652 | DateTime.isGreaterThan(link.expiresAt, now) |
| 653 | ? [{ environmentId: link.environmentId, label: link.label }] |
| 654 | : [], |
| 655 | ); |
| 656 | }); |
| 657 | |
| 658 | const get: PeerLinks["Service"]["get"] = (environmentId) => |
| 659 | readRow(environmentId).pipe( |
| 660 | Effect.flatMap( |
| 661 | Option.match({ |
| 662 | onNone: () => Effect.succeedNone, |
| 663 | onSome: (row) => Effect.asSome(toLink(row)), |
| 664 | }), |
| 665 | ), |
| 666 | ); |
| 667 | |
| 668 | const unlink: PeerLinks["Service"]["unlink"] = Effect.fn("PeerLinks.unlink")( |
| 669 | function* (environmentId) { |
| 670 | const deleted = yield* sql<{ secret_name: string }>` |
| 671 | DELETE FROM peer_environment_links WHERE environment_id = ${environmentId} |
| 672 | RETURNING secret_name |
| 673 | `.pipe(Effect.catch(failStorage)); |
| 674 | for (const row of deleted) { |
| 675 | yield* secrets.remove(row.secret_name).pipe(Effect.catch(failStorage)); |
| 676 | } |
| 677 | return deleted.length > 0; |
| 678 | }, |
| 679 | ); |
| 680 | |
| 681 | const resolve: PeerLinks["Service"]["resolve"] = Effect.fn("PeerLinks.resolve")( |
| 682 | function* (environmentId) { |
| 683 | const notLinked = new PeerLinkError({ |
| 684 | reason: "unknown_link", |
| 685 | message: `This environment is not linked to ${environmentId}. t3_environment_links lists the linked ones.`, |
| 686 | }); |
| 687 | const row = yield* readRow(environmentId); |
| 688 | if (Option.isNone(row)) return yield* notLinked; |
| 689 | const link = yield* toLink(row.value); |
| 690 | if (DateTime.isLessThanOrEqualTo(link.expiresAt, yield* DateTime.now)) { |
| 691 | return yield* new PeerLinkError({ |
| 692 | reason: "expired", |
| 693 | message: `The link to ${link.label} expired. Link it again with a new pairing code from ${link.label}.`, |
| 694 | }); |
| 695 | } |
| 696 | const stored = yield* secrets.get(row.value.secret_name).pipe(Effect.catch(failStorage)); |
| 697 | if (Option.isNone(stored)) { |
| 698 | // An unlink between the two reads removes the row before its secret. |
| 699 | if (Option.isNone(yield* readRow(environmentId))) return yield* notLinked; |
| 700 | return yield* new PeerLinkError({ |
| 701 | reason: "unknown_link", |
| 702 | message: `The link to ${link.label} lost its credential. Link it again.`, |
| 703 | }); |
| 704 | } |
| 705 | // The token goes only to an address that still answers as this peer, |
| 706 | // so one that now answers as another machine never receives it. The |
| 707 | // addresses race, so a silent one never delays one that answers. |
| 708 | const answered = |
| 709 | link.urls.length === 0 |
| 710 | ? Option.none() |
| 711 | : yield* Effect.raceAll( |
| 712 | link.urls.map((url) => |
| 713 | answersAs(url, environmentId).pipe( |
| 714 | Effect.flatMap(Effect.fromOption), |
| 715 | Effect.map((peer) => ({ url, peer })), |
| 716 | ), |
| 717 | ), |
| 718 | ).pipe(Effect.option); |
| 719 | if (Option.isNone(answered)) { |
| 720 | return yield* new PeerLinkError({ |
| 721 | reason: "unreachable", |
| 722 | message: `${link.label} did not answer at ${link.urls.join(", ")}.`, |
| 723 | }); |
| 724 | } |
| 725 | const { url, peer } = answered.value; |
| 726 | // A link made before the peer had to fence linked work, or a peer moved |
| 727 | // back to such a version, would carry work past those limits. |
| 728 | if (!linkLimitsHold(peer)) { |
| 729 | return yield* new PeerLinkError({ |
| 730 | reason: "incompatible", |
| 731 | message: `${link.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`, |
| 732 | }); |
| 733 | } |
| 734 | return { |
| 735 | link: yield* withLabel(link, peer.label), |
| 736 | url, |
| 737 | token: new TextDecoder().decode(stored.value), |
| 738 | capabilities: peer.capabilities, |
| 739 | }; |
| 740 | }, |
| 741 | ); |
| 742 | |
| 743 | const recordOutcome: PeerLinks["Service"]["recordOutcome"] = (environmentId, outcome) => |
| 744 | DateTime.now.pipe( |
| 745 | Effect.flatMap((now) => |
| 746 | outcome.error === null |
| 747 | ? sql` |
| 748 | UPDATE peer_environment_links |
| 749 | SET last_reached_at = ${DateTime.formatIso(now)}, last_error = NULL |
| 750 | WHERE environment_id = ${environmentId} |
| 751 | ` |
| 752 | : sql` |
| 753 | UPDATE peer_environment_links SET last_error = ${outcome.error} |
| 754 | WHERE environment_id = ${environmentId} |
| 755 | `, |
| 756 | ), |
| 757 | Effect.asVoid, |
| 758 | Effect.ignoreCause({ log: true }), |
| 759 | ); |
| 760 | |
| 761 | const recordExpiry: PeerLinks["Service"]["recordExpiry"] = (environmentId, expiresAt) => |
| 762 | sql` |
| 763 | UPDATE peer_environment_links SET expires_at = ${DateTime.formatIso(expiresAt)} |
| 764 | WHERE environment_id = ${environmentId} AND expires_at < ${DateTime.formatIso(expiresAt)} |
| 765 | `.pipe(Effect.asVoid, Effect.ignoreCause({ log: true })); |
| 766 | |
| 767 | return PeerLinks.of({ |
| 768 | enabled, |
| 769 | link, |
| 770 | linkUnlessLinked, |
| 771 | list, |
| 772 | names, |
| 773 | get, |
| 774 | unlink, |
| 775 | resolve, |
| 776 | recordOutcome, |
| 777 | recordExpiry, |
| 778 | }); |
| 779 | }); |
| 780 | |
| 781 | export const layer = Layer.effect(PeerLinks, make); |