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 or sign. |
| 2 | import * as NodeCrypto from "node:crypto"; |
| 3 | import * as EffectNodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 4 | import type { |
| 5 | RelayEnvironmentLinkProofPayload, |
| 6 | RelayEnvironmentLinkRequest, |
| 7 | } from "@t3tools/contracts/relay"; |
| 8 | import { RELAY_LINK_PROOF_TYP } from "@t3tools/shared/relayJwt"; |
| 9 | import { describe, expect, it } from "@effect/vitest"; |
| 10 | import * as DateTime from "effect/DateTime"; |
| 11 | import * as Effect from "effect/Effect"; |
| 12 | import * as Layer from "effect/Layer"; |
| 13 | import * as Redacted from "effect/Redacted"; |
| 14 | import * as Result from "effect/Result"; |
| 15 | import * as Schema from "effect/Schema"; |
| 16 | |
| 17 | import * as CloudMintSigner from "../auth/CloudMintSigner.ts"; |
| 18 | import * as DpopProofs from "../auth/DpopProofs.ts"; |
| 19 | import * as RelayTokens from "../auth/RelayTokens.ts"; |
| 20 | import * as RelayDb from "../db.ts"; |
| 21 | import * as EnvironmentCredentials from "./EnvironmentCredentials.ts"; |
| 22 | import * as EnvironmentLinks from "./EnvironmentLinks.ts"; |
| 23 | import * as RelayConfiguration from "../Config.ts"; |
| 24 | import * as EnvironmentLinker from "./EnvironmentLinker.ts"; |
| 25 | import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts"; |
| 26 | |
| 27 | const relayKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { |
| 28 | privateKeyEncoding: { format: "pem", type: "pkcs8" }, |
| 29 | publicKeyEncoding: { format: "pem", type: "spki" }, |
| 30 | }); |
| 31 | const environmentKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { |
| 32 | privateKeyEncoding: { format: "pem", type: "pkcs8" }, |
| 33 | publicKeyEncoding: { format: "pem", type: "spki" }, |
| 34 | }); |
| 35 | const config = RelayConfiguration.RelayConfiguration.of({ |
| 36 | relayIssuer: "https://relay.example.test", |
| 37 | apns: { |
| 38 | environment: "sandbox", |
| 39 | teamId: "team-id", |
| 40 | keyId: "key-id", |
| 41 | privateKey: Redacted.make("private-key"), |
| 42 | bundleId: "com.t3tools.t3code.dev", |
| 43 | }, |
| 44 | apnsDeliveryJobSigningSecret: Redacted.make("job-secret"), |
| 45 | clerkSecretKey: Redacted.make("clerk-secret"), |
| 46 | clerkPublishableKey: "pk_test_test", |
| 47 | clerkJwtAudience: "t3-code-relay", |
| 48 | cloudMintPrivateKey: Redacted.make(relayKeyPair.privateKey), |
| 49 | cloudMintPublicKey: relayKeyPair.publicKey, |
| 50 | managedEndpointBaseDomain: undefined, |
| 51 | managedEndpointNamespace: undefined, |
| 52 | }); |
| 53 | const isEnvironmentLinkProofInvalid = Schema.is(EnvironmentLinker.EnvironmentLinkProofInvalid); |
| 54 | |
| 55 | function signTestJwt(payload: object, typ: string, privateKey: string): string { |
| 56 | const header = Buffer.from(JSON.stringify({ alg: "EdDSA", typ })).toString("base64url"); |
| 57 | const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url"); |
| 58 | const signingInput = `${header}.${encodedPayload}`; |
| 59 | return `${signingInput}.${NodeCrypto.sign(null, Buffer.from(signingInput), privateKey).toString("base64url")}`; |
| 60 | } |
| 61 | |
| 62 | const makeRequest = Effect.gen(function* () { |
| 63 | const now = yield* DateTime.now; |
| 64 | const expiresAt = DateTime.add(now, { minutes: 5 }); |
| 65 | const relayTokens = yield* RelayTokens.RelayTokens; |
| 66 | const challenge = yield* relayTokens.issueLinkChallenge({ |
| 67 | userId: "user_123", |
| 68 | request: { |
| 69 | notificationsEnabled: true, |
| 70 | liveActivitiesEnabled: true, |
| 71 | managedTunnelsEnabled: true, |
| 72 | }, |
| 73 | jti: "challenge-jti", |
| 74 | issuedAtEpochSeconds: Math.floor(now.epochMilliseconds / 1_000), |
| 75 | expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000), |
| 76 | }); |
| 77 | const payload = { |
| 78 | iss: "t3-env:env-link-test", |
| 79 | aud: "https://relay.example.test", |
| 80 | sub: "env-link-test", |
| 81 | jti: "link-proof-jti", |
| 82 | iat: Math.floor(now.epochMilliseconds / 1_000), |
| 83 | exp: Math.floor(expiresAt.epochMilliseconds / 1_000), |
| 84 | challenge, |
| 85 | environmentId: "env-link-test" as RelayEnvironmentLinkProofPayload["environmentId"], |
| 86 | descriptor: { |
| 87 | environmentId: "env-link-test" as RelayEnvironmentLinkProofPayload["environmentId"], |
| 88 | label: "Link Test Environment", |
| 89 | platform: { os: "darwin", arch: "arm64" }, |
| 90 | serverVersion: "0.0.0-test", |
| 91 | capabilities: { repositoryIdentity: true }, |
| 92 | }, |
| 93 | environmentPublicKey: environmentKeyPair.publicKey.trim(), |
| 94 | endpoint: { |
| 95 | httpBaseUrl: "https://env.example.test/", |
| 96 | wsBaseUrl: "wss://env.example.test/", |
| 97 | providerKind: "manual", |
| 98 | }, |
| 99 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 100 | scopes: ["agent_activity_notifications", "managed_tunnels"], |
| 101 | } satisfies RelayEnvironmentLinkProofPayload; |
| 102 | return { |
| 103 | request: { |
| 104 | proof: signTestJwt(payload, RELAY_LINK_PROOF_TYP, environmentKeyPair.privateKey), |
| 105 | notificationsEnabled: true, |
| 106 | liveActivitiesEnabled: true, |
| 107 | managedTunnelsEnabled: false, |
| 108 | } satisfies RelayEnvironmentLinkRequest, |
| 109 | payload, |
| 110 | }; |
| 111 | }); |
| 112 | |
| 113 | function layerTest(input?: { |
| 114 | readonly upsert?: EnvironmentLinks.EnvironmentLinks["Service"]["upsert"]; |
| 115 | readonly getForUser?: EnvironmentLinks.EnvironmentLinks["Service"]["getForUser"]; |
| 116 | readonly prepareDeprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["prepareDeprovision"]; |
| 117 | readonly consume?: DpopProofs.DpopProofReplay["Service"]["consume"]; |
| 118 | readonly deprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["deprovision"]; |
| 119 | }) { |
| 120 | return EnvironmentLinker.layer.pipe( |
| 121 | Layer.provideMerge(RelayTokens.layer.pipe(Layer.provide(CloudMintSigner.layer))), |
| 122 | Layer.provide( |
| 123 | Layer.mergeAll( |
| 124 | RelayConfiguration.layer(config), |
| 125 | Layer.succeed(RelayDb.RelayTransactions, { withTransaction: (effect) => effect }), |
| 126 | Layer.succeed(DpopProofs.DpopProofReplay, { |
| 127 | verifyAndConsume: () => Effect.die("unexpected DPoP proof verification"), |
| 128 | consume: input?.consume ?? (() => Effect.succeed(true)), |
| 129 | pruneExpired: Effect.void, |
| 130 | }), |
| 131 | Layer.succeed(EnvironmentLinks.EnvironmentLinks, { |
| 132 | upsert: input?.upsert ?? (() => Effect.void), |
| 133 | listDeliveryUsersForEnvironment: () => Effect.succeed([]), |
| 134 | listForUser: () => Effect.succeed([]), |
| 135 | getForUser: input?.getForUser ?? (() => Effect.succeed(null)), |
| 136 | findActiveManagedForEnvironment: () => Effect.succeed([]), |
| 137 | updateLiveActivityPreference: () => |
| 138 | Effect.die("unexpected Live Activity preference update"), |
| 139 | setHoldWebhooksWhileOffline: () => Effect.void, |
| 140 | revokeForUser: () => Effect.succeed(false), |
| 141 | }), |
| 142 | Layer.succeed(EnvironmentCredentials.EnvironmentCredentials, { |
| 143 | create: () => Effect.succeed("t3env_credential_secret"), |
| 144 | authenticate: () => Effect.succeedNone, |
| 145 | revokeForEnvironmentPublicKey: () => Effect.succeed(false), |
| 146 | }), |
| 147 | Layer.succeed(ManagedEndpointProvider.ManagedEndpointProvider, { |
| 148 | reconcileOrigin: () => Effect.succeed("ready"), |
| 149 | prepareDeprovision: input?.prepareDeprovision ?? (() => Effect.succeed(null)), |
| 150 | deprovision: input?.deprovision ?? (() => Effect.succeed(true)), |
| 151 | release: () => Effect.succeed(true), |
| 152 | provision: () => |
| 153 | Effect.succeed({ |
| 154 | endpoint: { |
| 155 | httpBaseUrl: "https://managed.example.test/", |
| 156 | wsBaseUrl: "wss://managed.example.test/ws", |
| 157 | providerKind: "cloudflare_tunnel", |
| 158 | }, |
| 159 | runtime: { providerKind: "cloudflare_tunnel", connectorToken: "connector-token" }, |
| 160 | }), |
| 161 | }), |
| 162 | ), |
| 163 | ), |
| 164 | Layer.provideMerge(EffectNodeCrypto.layerSignature), |
| 165 | ); |
| 166 | } |
| 167 | |
| 168 | describe("EnvironmentLinker", () => { |
| 169 | it.effect("uses verified JWT claims when linking an environment", () => { |
| 170 | let persistedEnvironmentId: string | null = null; |
| 171 | return Effect.gen(function* () { |
| 172 | const { request, payload } = yield* makeRequest; |
| 173 | const linker = yield* EnvironmentLinker.EnvironmentLinker; |
| 174 | const result = yield* linker.link({ userId: "user_123", request }); |
| 175 | expect(result.environmentId).toBe(payload.environmentId); |
| 176 | expect(result.environmentCredential).toBe("t3env_credential_secret"); |
| 177 | expect(persistedEnvironmentId).toBe(payload.environmentId); |
| 178 | }).pipe( |
| 179 | Effect.provide( |
| 180 | layerTest({ |
| 181 | upsert: (input) => |
| 182 | Effect.sync(() => { |
| 183 | persistedEnvironmentId = input.proof.environmentId; |
| 184 | }), |
| 185 | }), |
| 186 | ), |
| 187 | ); |
| 188 | }); |
| 189 | |
| 190 | it.effect("links a publish-only environment with a non-secure nominal endpoint", () => { |
| 191 | let persistedEndpoint: string | null = null; |
| 192 | let deprovisionedEnvironmentId: string | null = null; |
| 193 | return Effect.gen(function* () { |
| 194 | const now = yield* DateTime.now; |
| 195 | const expiresAt = DateTime.add(now, { minutes: 5 }); |
| 196 | const relayTokens = yield* RelayTokens.RelayTokens; |
| 197 | const challenge = yield* relayTokens.issueLinkChallenge({ |
| 198 | userId: "user_123", |
| 199 | request: { |
| 200 | notificationsEnabled: true, |
| 201 | liveActivitiesEnabled: true, |
| 202 | managedTunnelsEnabled: false, |
| 203 | }, |
| 204 | jti: "publish-only-challenge-jti", |
| 205 | issuedAtEpochSeconds: Math.floor(now.epochMilliseconds / 1_000), |
| 206 | expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000), |
| 207 | }); |
| 208 | const payload = { |
| 209 | iss: "t3-env:env-link-test", |
| 210 | aud: "https://relay.example.test", |
| 211 | sub: "env-link-test", |
| 212 | jti: "publish-only-proof-jti", |
| 213 | iat: Math.floor(now.epochMilliseconds / 1_000), |
| 214 | exp: Math.floor(expiresAt.epochMilliseconds / 1_000), |
| 215 | challenge, |
| 216 | environmentId: "env-link-test" as RelayEnvironmentLinkProofPayload["environmentId"], |
| 217 | descriptor: { |
| 218 | environmentId: "env-link-test" as RelayEnvironmentLinkProofPayload["environmentId"], |
| 219 | label: "Link Test Environment", |
| 220 | platform: { os: "darwin", arch: "arm64" }, |
| 221 | serverVersion: "0.0.0-test", |
| 222 | capabilities: { repositoryIdentity: true }, |
| 223 | }, |
| 224 | environmentPublicKey: environmentKeyPair.publicKey.trim(), |
| 225 | endpoint: { |
| 226 | httpBaseUrl: "http://127.0.0.1:3773/", |
| 227 | wsBaseUrl: "ws://127.0.0.1:3773/", |
| 228 | providerKind: "manual", |
| 229 | }, |
| 230 | origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, |
| 231 | scopes: ["agent_activity_notifications"], |
| 232 | } satisfies RelayEnvironmentLinkProofPayload; |
| 233 | const request = { |
| 234 | proof: signTestJwt(payload, RELAY_LINK_PROOF_TYP, environmentKeyPair.privateKey), |
| 235 | notificationsEnabled: true, |
| 236 | liveActivitiesEnabled: true, |
| 237 | managedTunnelsEnabled: false, |
| 238 | } satisfies RelayEnvironmentLinkRequest; |
| 239 | const linker = yield* EnvironmentLinker.EnvironmentLinker; |
| 240 | const result = yield* linker.link({ userId: "user_123", request }); |
| 241 | expect(result.environmentCredential).toBe("t3env_credential_secret"); |
| 242 | expect(result.endpointRuntime).toBeNull(); |
| 243 | expect(persistedEndpoint).toBe("http://127.0.0.1:3773/"); |
| 244 | expect(deprovisionedEnvironmentId).toBe("env-link-test"); |
| 245 | }).pipe( |
| 246 | Effect.provide( |
| 247 | layerTest({ |
| 248 | upsert: (input) => |
| 249 | Effect.sync(() => { |
| 250 | persistedEndpoint = input.endpoint.httpBaseUrl; |
| 251 | }), |
| 252 | deprovision: (input) => |
| 253 | Effect.sync(() => { |
| 254 | deprovisionedEnvironmentId = input.environmentId; |
| 255 | return true; |
| 256 | }), |
| 257 | }), |
| 258 | ), |
| 259 | ); |
| 260 | }); |
| 261 | |
| 262 | it.effect("rejects a tampered compact proof before persistence", () => { |
| 263 | let persisted = false; |
| 264 | return Effect.gen(function* () { |
| 265 | const { request } = yield* makeRequest; |
| 266 | const segments = request.proof.split("."); |
| 267 | const signature = segments[2]!; |
| 268 | segments[2] = `${signature.startsWith("A") ? "B" : "A"}${signature.slice(1)}`; |
| 269 | const tampered = { ...request, proof: segments.join(".") }; |
| 270 | const linker = yield* EnvironmentLinker.EnvironmentLinker; |
| 271 | const result = yield* Effect.result(linker.link({ userId: "user_123", request: tampered })); |
| 272 | expect(Result.isFailure(result)).toBe(true); |
| 273 | if (Result.isFailure(result)) { |
| 274 | expect(isEnvironmentLinkProofInvalid(result.failure)).toBe(true); |
| 275 | if (isEnvironmentLinkProofInvalid(result.failure)) { |
| 276 | expect(result.failure).toMatchObject({ |
| 277 | userId: "user_123", |
| 278 | environmentId: "env-link-test", |
| 279 | reason: "invalid_signature_or_scope", |
| 280 | stage: "verify_proof", |
| 281 | cause: { _tag: "RelayJwtError" }, |
| 282 | }); |
| 283 | } |
| 284 | } |
| 285 | expect(persisted).toBe(false); |
| 286 | }).pipe( |
| 287 | Effect.provide( |
| 288 | layerTest({ |
| 289 | upsert: () => |
| 290 | Effect.sync(() => { |
| 291 | persisted = true; |
| 292 | }), |
| 293 | }), |
| 294 | ), |
| 295 | ); |
| 296 | }); |
| 297 | |
| 298 | it.effect("refuses to move an active link to a different environment key", () => { |
| 299 | const touched: Array<string> = []; |
| 300 | const activeLink = (environmentPublicKey: string) => ({ |
| 301 | environmentId: "env-link-test" as RelayEnvironmentLinkProofPayload["environmentId"], |
| 302 | label: "Link Test Environment", |
| 303 | endpoint: { |
| 304 | httpBaseUrl: "https://managed.example.test/", |
| 305 | wsBaseUrl: "wss://managed.example.test/ws", |
| 306 | providerKind: "cloudflare_tunnel" as const, |
| 307 | }, |
| 308 | environmentPublicKey, |
| 309 | linkedAt: "2026-01-01T00:00:00.000Z", |
| 310 | }); |
| 311 | let linkedKey = "another-environment-key"; |
| 312 | return Effect.gen(function* () { |
| 313 | const linker = yield* EnvironmentLinker.EnvironmentLinker; |
| 314 | const refused = yield* linker |
| 315 | .link({ userId: "user_123", request: (yield* makeRequest).request }) |
| 316 | .pipe(Effect.flip); |
| 317 | expect(refused).toMatchObject({ |
| 318 | _tag: "EnvironmentLinkProofInvalid", |
| 319 | reason: "environment_key_mismatch", |
| 320 | }); |
| 321 | expect(touched).toEqual([]); |
| 322 | |
| 323 | linkedKey = environmentKeyPair.publicKey.trim(); |
| 324 | yield* linker.link({ userId: "user_123", request: (yield* makeRequest).request }); |
| 325 | expect(touched).toEqual(["deprovision", "upsert"]); |
| 326 | }).pipe( |
| 327 | Effect.provide( |
| 328 | layerTest({ |
| 329 | getForUser: () => Effect.succeed(activeLink(linkedKey)), |
| 330 | upsert: () => Effect.sync(() => void touched.push("upsert")), |
| 331 | deprovision: () => Effect.sync(() => touched.push("deprovision") > 0), |
| 332 | }), |
| 333 | ), |
| 334 | ); |
| 335 | }); |
| 336 | |
| 337 | it.effect.each([{ managedTunnelsEnabled: true }, { managedTunnelsEnabled: false }])( |
| 338 | "finishes a failed unlink teardown before a new link: %o", |
| 339 | ({ managedTunnelsEnabled }) => { |
| 340 | const touched: Array<string> = []; |
| 341 | let tornDown = false; |
| 342 | return Effect.gen(function* () { |
| 343 | const linker = yield* EnvironmentLinker.EnvironmentLinker; |
| 344 | const link = Effect.gen(function* () { |
| 345 | const { request } = yield* makeRequest; |
| 346 | return yield* linker.link({ |
| 347 | userId: "user_123", |
| 348 | request: { ...request, managedTunnelsEnabled }, |
| 349 | }); |
| 350 | }); |
| 351 | expect((yield* link.pipe(Effect.flip))._tag).toBe("ManagedEndpointDeprovisioningFailed"); |
| 352 | expect(touched).toEqual(["deprovision"]); |
| 353 | |
| 354 | tornDown = true; |
| 355 | yield* link; |
| 356 | expect(touched).toEqual(["deprovision", "deprovision", "upsert"]); |
| 357 | }).pipe( |
| 358 | Effect.provide( |
| 359 | layerTest({ |
| 360 | prepareDeprovision: () => |
| 361 | Effect.succeed({ |
| 362 | userId: "user_123", |
| 363 | environmentId: "env-link-test", |
| 364 | hostname: "managed.example.test", |
| 365 | tunnelId: "left-behind-tunnel", |
| 366 | tunnelName: "left-behind", |
| 367 | dnsRecordId: null, |
| 368 | readyAt: null, |
| 369 | origin: null, |
| 370 | updatedAt: "2026-01-01T00:00:00.000Z", |
| 371 | generation: 1, |
| 372 | tunnelReleasedAt: null, |
| 373 | }), |
| 374 | deprovision: () => Effect.sync(() => touched.push("deprovision") > 0 && tornDown), |
| 375 | upsert: () => Effect.sync(() => void touched.push("upsert")), |
| 376 | }), |
| 377 | ), |
| 378 | ); |
| 379 | }, |
| 380 | ); |
| 381 | |
| 382 | it.effect("rejects replayed JWT ids", () => |
| 383 | Effect.gen(function* () { |
| 384 | const { request } = yield* makeRequest; |
| 385 | const linker = yield* EnvironmentLinker.EnvironmentLinker; |
| 386 | const result = yield* Effect.result(linker.link({ userId: "user_123", request })); |
| 387 | expect(Result.isFailure(result)).toBe(true); |
| 388 | if (Result.isFailure(result)) { |
| 389 | expect(isEnvironmentLinkProofInvalid(result.failure)).toBe(true); |
| 390 | if (isEnvironmentLinkProofInvalid(result.failure)) { |
| 391 | expect(result.failure).toMatchObject({ |
| 392 | userId: "user_123", |
| 393 | environmentId: "env-link-test", |
| 394 | reason: "replayed_nonce", |
| 395 | stage: "consume_proof_nonce", |
| 396 | }); |
| 397 | } |
| 398 | } |
| 399 | }).pipe(Effect.provide(layerTest({ consume: () => Effect.succeed(false) }))), |
| 400 | ); |
| 401 | }); |