The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync. |
| 2 | import * as NodeCrypto from "node:crypto"; |
| 3 | import { EnvironmentId } from "@t3tools/contracts"; |
| 4 | import { RELAY_MINT_REQUEST_TYP, signRelayJwt } from "@t3tools/shared/relayJwt"; |
| 5 | import { assert, it } from "@effect/vitest"; |
| 6 | import * as DateTime from "effect/DateTime"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Fiber from "effect/Fiber"; |
| 9 | import * as Layer from "effect/Layer"; |
| 10 | import * as Option from "effect/Option"; |
| 11 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 12 | import { HttpClient, HttpServer } from "effect/http"; |
| 13 | import * as NetAddress from "effect/net/NetAddress"; |
| 14 | import * as NodePlatformCrypto from "@effect/platform-node/NodeCrypto"; |
| 15 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 16 | |
| 17 | import * as EnvironmentKeys from "./environmentKeys.ts"; |
| 18 | import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; |
| 19 | import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; |
| 20 | import * as ServerConfig from "../config.ts"; |
| 21 | import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; |
| 22 | import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts"; |
| 23 | import * as CliTokenManager from "./CliTokenManager.ts"; |
| 24 | import * as CloudLink from "./CloudLink.ts"; |
| 25 | import * as ConnectReachability from "./ConnectReachability.ts"; |
| 26 | import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts"; |
| 27 | import { |
| 28 | CLOUD_LINKED_USER_ID, |
| 29 | CLOUD_MINT_PUBLIC_KEY, |
| 30 | HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET, |
| 31 | PUBLISH_AGENT_ACTIVITY_SECRET, |
| 32 | RELAY_ENVIRONMENT_CREDENTIAL_SECRET, |
| 33 | RELAY_URL_SECRET, |
| 34 | } from "./config.ts"; |
| 35 | import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; |
| 36 | import * as ServerSettings from "../serverSettings.ts"; |
| 37 | |
| 38 | const encode = (value: string) => new TextEncoder().encode(value); |
| 39 | |
| 40 | const cloudMintKeys = NodeCrypto.generateKeyPairSync("ed25519", { |
| 41 | privateKeyEncoding: { format: "pem", type: "pkcs8" }, |
| 42 | publicKeyEncoding: { format: "pem", type: "spki" }, |
| 43 | }); |
| 44 | |
| 45 | const withService = <A, E>( |
| 46 | options: { |
| 47 | readonly failHoldWrite?: boolean; |
| 48 | readonly failActivityWrite?: boolean; |
| 49 | readonly relayFails?: boolean; |
| 50 | readonly failActivityRead?: boolean; |
| 51 | readonly failHoldRead?: boolean; |
| 52 | readonly holdFirstRelayCall?: { |
| 53 | readonly started: () => void; |
| 54 | readonly released: Promise<void>; |
| 55 | }; |
| 56 | }, |
| 57 | body: (input: { |
| 58 | readonly preferences: { readonly update: CloudLink.CloudLink["Service"]["updatePreferences"] }; |
| 59 | readonly mintCredential: CloudLink.CloudLink["Service"]["mintCredential"]; |
| 60 | readonly stored: Map<string, Uint8Array>; |
| 61 | readonly relayCalls: Array<boolean>; |
| 62 | readonly connectCredentialRequests: Array< |
| 63 | Parameters<EnvironmentAuth.EnvironmentAuth["Service"]["issueConnectCredential"]>[0] |
| 64 | >; |
| 65 | }) => Effect.Effect<A, E, never>, |
| 66 | ) => |
| 67 | Effect.gen(function* () { |
| 68 | const stored = new Map<string, Uint8Array>([ |
| 69 | [RELAY_URL_SECRET, encode("https://relay.test")], |
| 70 | [RELAY_ENVIRONMENT_CREDENTIAL_SECRET, encode("credential")], |
| 71 | [HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET, encode("false")], |
| 72 | [PUBLISH_AGENT_ACTIVITY_SECRET, encode("false")], |
| 73 | [CLOUD_MINT_PUBLIC_KEY, encode(cloudMintKeys.publicKey)], |
| 74 | [CLOUD_LINKED_USER_ID, encode("cloud-user-1")], |
| 75 | ]); |
| 76 | const relayCalls: Array<boolean> = []; |
| 77 | const connectCredentialRequests: Array< |
| 78 | Parameters<EnvironmentAuth.EnvironmentAuth["Service"]["issueConnectCredential"]>[0] |
| 79 | > = []; |
| 80 | const fetch: typeof globalThis.fetch = Object.assign( |
| 81 | (_input: Parameters<typeof globalThis.fetch>[0], init?: RequestInit) => { |
| 82 | const payload = JSON.parse(String(init?.body)) as { holdWebhooksWhileOffline: boolean }; |
| 83 | relayCalls.push(payload.holdWebhooksWhileOffline); |
| 84 | if (relayCalls.length === 1 && options.holdFirstRelayCall) { |
| 85 | options.holdFirstRelayCall.started(); |
| 86 | return options.holdFirstRelayCall.released.then(() => Response.json(payload)); |
| 87 | } |
| 88 | return options.relayFails |
| 89 | ? Promise.resolve(new Response("unavailable", { status: 503 })) |
| 90 | : Promise.resolve(Response.json(payload)); |
| 91 | }, |
| 92 | { preconnect: () => {} }, |
| 93 | ); |
| 94 | const layerDependencies = Layer.mergeAll( |
| 95 | ServerSettings.ServerSettingsService.layerTest(), |
| 96 | Layer.mock(ServerSecretStore.ServerSecretStore)({ |
| 97 | get: (name) => |
| 98 | (options.failActivityRead && name === PUBLISH_AGENT_ACTIVITY_SECRET) || |
| 99 | (options.failHoldRead && name === HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET) |
| 100 | ? Effect.fail( |
| 101 | new ServerSecretStore.SecretStoreReadError({ |
| 102 | resource: name, |
| 103 | cause: new Error("busy"), |
| 104 | }), |
| 105 | ) |
| 106 | : Effect.succeed(Option.fromNullishOr(stored.get(name))), |
| 107 | set: (name, value) => |
| 108 | (options.failHoldWrite && name === HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET) || |
| 109 | (options.failActivityWrite && name === PUBLISH_AGENT_ACTIVITY_SECRET) |
| 110 | ? Effect.fail( |
| 111 | new ServerSecretStore.SecretStorePersistError({ |
| 112 | resource: name, |
| 113 | cause: new Error("read-only"), |
| 114 | }), |
| 115 | ) |
| 116 | : Effect.sync(() => void stored.set(name, value)), |
| 117 | create: (name, value) => Effect.sync(() => void stored.set(name, value)), |
| 118 | }), |
| 119 | Layer.mock(ServerEnvironment.ServerEnvironment)({ |
| 120 | getEnvironmentId: Effect.succeed(EnvironmentId.make("environment-1")), |
| 121 | }), |
| 122 | Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({ requestCatchUp: () => Effect.void }), |
| 123 | Layer.mock(ManagedEndpointRuntime.CloudManagedEndpointRuntime)({}), |
| 124 | ManagedPolicy.layerTest(), |
| 125 | Layer.mock(ConnectReachability.ConnectReachability)({ |
| 126 | latest: Effect.succeedNone, |
| 127 | }), |
| 128 | Layer.mock(EnvironmentAuth.EnvironmentAuth)({ |
| 129 | issueConnectCredential: (input) => |
| 130 | Effect.sync(() => { |
| 131 | connectCredentialRequests.push(input); |
| 132 | return { credential: "pairing-credential", expiresAt: DateTime.makeUnsafe(120_000) }; |
| 133 | }), |
| 134 | }), |
| 135 | Layer.mock(CliTokenManager.CloudCliTokenManager)({}), |
| 136 | Layer.mock(HttpServer.HttpServer)({ |
| 137 | address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773), |
| 138 | }), |
| 139 | Layer.mock(ServerConfig.ServerConfig)({} as ServerConfig.ServerConfig["Service"]), |
| 140 | Layer.succeed( |
| 141 | HttpClient.HttpClient, |
| 142 | HttpClient.make(() => Effect.die("unused")), |
| 143 | ), |
| 144 | NodeServices.layer, |
| 145 | NodePlatformCrypto.layer, |
| 146 | ); |
| 147 | return yield* Effect.gen(function* () { |
| 148 | const link = yield* CloudLink.CloudLink; |
| 149 | return yield* body({ |
| 150 | preferences: { update: link.updatePreferences }, |
| 151 | mintCredential: link.mintCredential, |
| 152 | stored, |
| 153 | relayCalls, |
| 154 | connectCredentialRequests, |
| 155 | }); |
| 156 | }).pipe( |
| 157 | Effect.provide( |
| 158 | CloudLink.layer.pipe( |
| 159 | // The mocked secret store cannot create a key pair, and no test reads the signature. |
| 160 | Layer.provide( |
| 161 | Layer.mock(EnvironmentKeys.EnvironmentSigningKey)({ |
| 162 | publicKey: "", |
| 163 | sign: () => Effect.succeed("environment-signed-proof"), |
| 164 | }), |
| 165 | ), |
| 166 | Layer.provide(layerDependencies), |
| 167 | ), |
| 168 | ), |
| 169 | Effect.provideService(FetchHttpClient.Fetch, fetch), |
| 170 | ); |
| 171 | }); |
| 172 | |
| 173 | it.effect("tells the relay before saving the hold setting locally", () => |
| 174 | withService({}, ({ preferences, stored, relayCalls }) => |
| 175 | Effect.gen(function* () { |
| 176 | yield* preferences.update({ publishAgentActivity: true, holdWebhooksWhileOffline: true }); |
| 177 | assert.deepEqual(relayCalls, [true]); |
| 178 | assert.equal( |
| 179 | new TextDecoder().decode(stored.get(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET)), |
| 180 | "true", |
| 181 | ); |
| 182 | }), |
| 183 | ), |
| 184 | ); |
| 185 | |
| 186 | it.effect("puts the relay back when the local save fails", () => |
| 187 | withService({ failHoldWrite: true }, ({ preferences, stored, relayCalls }) => |
| 188 | Effect.gen(function* () { |
| 189 | const error = yield* preferences |
| 190 | .update({ publishAgentActivity: true, holdWebhooksWhileOffline: true }) |
| 191 | .pipe(Effect.flip); |
| 192 | assert.deepInclude(error, { |
| 193 | _tag: "CloudLinkInternalError", |
| 194 | operation: "persist-preferences", |
| 195 | }); |
| 196 | assert.deepEqual(relayCalls, [true, false]); |
| 197 | assert.equal( |
| 198 | new TextDecoder().decode(stored.get(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET)), |
| 199 | "false", |
| 200 | ); |
| 201 | }), |
| 202 | ), |
| 203 | ); |
| 204 | |
| 205 | it.effect("leaves the relay untouched when the activity setting can't be saved", () => |
| 206 | withService({ failActivityWrite: true }, ({ preferences, stored, relayCalls }) => |
| 207 | Effect.gen(function* () { |
| 208 | const error = yield* preferences |
| 209 | .update({ publishAgentActivity: true, holdWebhooksWhileOffline: true }) |
| 210 | .pipe(Effect.flip); |
| 211 | assert.deepInclude(error, { |
| 212 | _tag: "CloudLinkInternalError", |
| 213 | operation: "persist-preferences", |
| 214 | }); |
| 215 | assert.deepEqual(relayCalls, []); |
| 216 | assert.equal( |
| 217 | new TextDecoder().decode(stored.get(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET)), |
| 218 | "false", |
| 219 | ); |
| 220 | }), |
| 221 | ), |
| 222 | ); |
| 223 | |
| 224 | it.effect("keeps both settings unchanged when the relay refuses the hold change", () => |
| 225 | withService({ relayFails: true }, ({ preferences, stored }) => |
| 226 | Effect.gen(function* () { |
| 227 | yield* preferences |
| 228 | .update({ publishAgentActivity: true, holdWebhooksWhileOffline: true }) |
| 229 | .pipe(Effect.flip); |
| 230 | assert.equal(new TextDecoder().decode(stored.get(PUBLISH_AGENT_ACTIVITY_SECRET)), "false"); |
| 231 | assert.equal( |
| 232 | new TextDecoder().decode(stored.get(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET)), |
| 233 | "false", |
| 234 | ); |
| 235 | }), |
| 236 | ), |
| 237 | ); |
| 238 | |
| 239 | it.effect("two overlapping updates are applied one after the other", () => { |
| 240 | let release!: () => void; |
| 241 | let started!: () => void; |
| 242 | const released = new Promise<void>((resolve) => { |
| 243 | release = resolve; |
| 244 | }); |
| 245 | const firstAtRelay = new Promise<void>((resolve) => { |
| 246 | started = resolve; |
| 247 | }); |
| 248 | return withService({ holdFirstRelayCall: { started, released } }, ({ preferences, stored }) => |
| 249 | Effect.gen(function* () { |
| 250 | const first = yield* preferences |
| 251 | .update({ publishAgentActivity: true, holdWebhooksWhileOffline: true }) |
| 252 | .pipe(Effect.forkChild); |
| 253 | yield* Effect.promise(() => firstAtRelay); |
| 254 | const second = yield* preferences |
| 255 | .update({ publishAgentActivity: false, holdWebhooksWhileOffline: false }) |
| 256 | .pipe(Effect.forkChild); |
| 257 | yield* Effect.yieldNow; |
| 258 | assert.equal(new TextDecoder().decode(stored.get(PUBLISH_AGENT_ACTIVITY_SECRET)), "true"); |
| 259 | release(); |
| 260 | yield* Fiber.join(first); |
| 261 | yield* Fiber.join(second); |
| 262 | assert.equal(new TextDecoder().decode(stored.get(PUBLISH_AGENT_ACTIVITY_SECRET)), "false"); |
| 263 | assert.equal( |
| 264 | new TextDecoder().decode(stored.get(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET)), |
| 265 | "false", |
| 266 | ); |
| 267 | }), |
| 268 | ); |
| 269 | }); |
| 270 | |
| 271 | it.effect("an update the client walks away from still finishes", () => { |
| 272 | let release!: () => void; |
| 273 | let started!: () => void; |
| 274 | const released = new Promise<void>((resolve) => { |
| 275 | release = resolve; |
| 276 | }); |
| 277 | const atRelay = new Promise<void>((resolve) => { |
| 278 | started = resolve; |
| 279 | }); |
| 280 | return withService({ holdFirstRelayCall: { started, released } }, ({ preferences, stored }) => |
| 281 | Effect.gen(function* () { |
| 282 | const update = yield* preferences |
| 283 | .update({ publishAgentActivity: true, holdWebhooksWhileOffline: true }) |
| 284 | .pipe(Effect.forkChild); |
| 285 | yield* Effect.promise(() => atRelay); |
| 286 | const interrupted = yield* Fiber.interrupt(update).pipe(Effect.forkChild); |
| 287 | yield* Effect.yieldNow; |
| 288 | release(); |
| 289 | yield* Fiber.join(interrupted); |
| 290 | assert.equal(new TextDecoder().decode(stored.get(PUBLISH_AGENT_ACTIVITY_SECRET)), "true"); |
| 291 | assert.equal( |
| 292 | new TextDecoder().decode(stored.get(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET)), |
| 293 | "true", |
| 294 | ); |
| 295 | }), |
| 296 | ); |
| 297 | }); |
| 298 | |
| 299 | it.effect("mints a T3 Connect credential under the host's device approval setting", () => |
| 300 | withService({}, ({ mintCredential, connectCredentialRequests, stored }) => |
| 301 | Effect.gen(function* () { |
| 302 | const before = new Set(stored.keys()); |
| 303 | const proof = yield* signRelayJwt({ |
| 304 | privateKey: cloudMintKeys.privateKey, |
| 305 | typ: RELAY_MINT_REQUEST_TYP, |
| 306 | payload: { |
| 307 | iss: "https://relay.test", |
| 308 | aud: "t3-env:environment-1", |
| 309 | sub: "cloud-user-1", |
| 310 | // Longer than a file name can be, and not one: the marker is named by a digest. |
| 311 | jti: "../mint-jti-1".padEnd(300, "x"), |
| 312 | iat: 0, |
| 313 | exp: 60, |
| 314 | environmentId: "environment-1", |
| 315 | clientProofKeyThumbprint: "client-jkt", |
| 316 | cnf: { jkt: "client-jkt" }, |
| 317 | nonce: "mint-nonce-1", |
| 318 | scope: ["environment:connect"], |
| 319 | }, |
| 320 | }).pipe(Effect.provide(NodePlatformCrypto.layerSignature)); |
| 321 | yield* mintCredential({ proof }); |
| 322 | assert.deepEqual(connectCredentialRequests, [ |
| 323 | { proofKeyThumbprint: "client-jkt", requireApproval: false }, |
| 324 | ]); |
| 325 | const markers = [...stored.keys()].filter((name) => !before.has(name)).toSorted(); |
| 326 | assert.lengthOf(markers, 2); |
| 327 | assert.match(markers[0]!, /^cloud-mint-jti-[0-9a-f]{64}$/); |
| 328 | assert.match(markers[1]!, /^cloud-mint-nonce-[0-9a-f]{64}$/); |
| 329 | }), |
| 330 | ), |
| 331 | ); |
| 332 | |
| 333 | it.effect("unlinks on startup and refuses to link when the policy turns Connect off", () => |
| 334 | Effect.gen(function* () { |
| 335 | const stored = new Map<string, Uint8Array>([ |
| 336 | [CLOUD_LINKED_USER_ID, encode("user-1")], |
| 337 | [RELAY_URL_SECRET, encode("https://relay.test")], |
| 338 | ]); |
| 339 | const appliedConfigs: Array<unknown> = []; |
| 340 | const layerDependencies = Layer.mergeAll( |
| 341 | ServerSettings.ServerSettingsService.layerTest(), |
| 342 | Layer.mock(ServerSecretStore.ServerSecretStore)({ |
| 343 | get: (name) => Effect.succeed(Option.fromNullishOr(stored.get(name))), |
| 344 | set: (name, value) => Effect.sync(() => void stored.set(name, value)), |
| 345 | remove: (name) => Effect.sync(() => void stored.delete(name)), |
| 346 | }), |
| 347 | Layer.mock(ServerEnvironment.ServerEnvironment)({}), |
| 348 | Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({}), |
| 349 | Layer.mock(ManagedEndpointRuntime.CloudManagedEndpointRuntime)({ |
| 350 | withLinkStateLock: (effect) => effect, |
| 351 | applyConfig: (config) => |
| 352 | Effect.sync(() => { |
| 353 | appliedConfigs.push(config); |
| 354 | return { status: "disabled" as const }; |
| 355 | }), |
| 356 | }), |
| 357 | ManagedPolicy.layerTest({ |
| 358 | schemaVersion: 1, |
| 359 | organization: "Example Corp", |
| 360 | limits: { connect: false }, |
| 361 | }), |
| 362 | Layer.mock(ConnectReachability.ConnectReachability)({}), |
| 363 | Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), |
| 364 | Layer.mock(CliTokenManager.CloudCliTokenManager)({}), |
| 365 | Layer.mock(HttpServer.HttpServer)({ |
| 366 | address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773), |
| 367 | }), |
| 368 | Layer.mock(ServerConfig.ServerConfig)({} as ServerConfig.ServerConfig["Service"]), |
| 369 | Layer.succeed( |
| 370 | HttpClient.HttpClient, |
| 371 | HttpClient.make(() => Effect.die("unused")), |
| 372 | ), |
| 373 | NodeServices.layer, |
| 374 | NodePlatformCrypto.layer, |
| 375 | ); |
| 376 | yield* Effect.gen(function* () { |
| 377 | const link = yield* CloudLink.CloudLink; |
| 378 | assert.isFalse(stored.has(CLOUD_LINKED_USER_ID)); |
| 379 | assert.deepEqual(appliedConfigs, [null]); |
| 380 | |
| 381 | const applyError = yield* link.applyRelayConfig({} as never).pipe(Effect.flip); |
| 382 | const mintError = yield* link.mintCredential({} as never).pipe(Effect.flip); |
| 383 | assert.equal(applyError.message, "Example Corp's policy does not allow T3 Connect."); |
| 384 | assert.equal(mintError._tag, "ManagedPolicyRefusedError"); |
| 385 | }).pipe( |
| 386 | Effect.provide( |
| 387 | CloudLink.layer.pipe( |
| 388 | // These tests never sign proofs; the mocked secret store cannot create a key pair. |
| 389 | Layer.provide(Layer.mock(EnvironmentKeys.EnvironmentSigningKey)({ publicKey: "" })), |
| 390 | Layer.provide(layerDependencies), |
| 391 | ), |
| 392 | ), |
| 393 | ); |
| 394 | }), |
| 395 | ); |