Open History to see the last commit
1// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no generateKeyPairSync or sign.
2import * as NodeCrypto from "node:crypto";
3import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
4
5import {
6 RelayCloudEnvironmentHealthRequest,
7 RelayCloudMintCredentialRequest,
8 RelayCloudEnvironmentHealthProofPayload,
9 RelayCloudMintCredentialProofPayload,
10 RelayEnvironmentHealthResponse,
11 RelayEnvironmentHealthResponseProofPayload,
12 RelayEnvironmentMintResponse,
13 RelayEnvironmentMintResponseProofPayload,
14} from "@t3tools/contracts/relay";
15import { describe, expect, it } from "@effect/vitest";
16import * as DateTime from "effect/DateTime";
17import { RELAY_HEALTH_RESPONSE_TYP, RELAY_MINT_RESPONSE_TYP } from "@t3tools/shared/relayJwt";
18import * as Effect from "effect/Effect";
19import * as Layer from "effect/Layer";
20import * as Redacted from "effect/Redacted";
21import * as Result from "effect/Result";
22import * as Schema from "effect/Schema";
23import * as Tracer from "effect/Tracer";
24import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
25
26import * as EnvironmentLinks from "./EnvironmentLinks.ts";
27import * as RelayConfiguration from "../Config.ts";
28import * as EnvironmentConnector from "./EnvironmentConnector.ts";
29import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
30
31const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {
32 privateKeyEncoding: { format: "pem", type: "pkcs8" },
33 publicKeyEncoding: { format: "pem", type: "spki" },
34});
35
36const environmentKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {
37 privateKeyEncoding: { format: "pem", type: "pkcs8" },
38 publicKeyEncoding: { format: "pem", type: "spki" },
39});
40
41const otherEnvironmentKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {
42 privateKeyEncoding: { format: "pem", type: "pkcs8" },
43 publicKeyEncoding: { format: "pem", type: "spki" },
44});
45
46const decodeHealthRequestBody = Schema.decodeUnknownSync(
47 Schema.fromJsonString(RelayCloudEnvironmentHealthRequest),
48);
49const decodeMintRequestBody = Schema.decodeUnknownSync(
50 Schema.fromJsonString(RelayCloudMintCredentialRequest),
51);
52const isEnvironmentConnectNotAuthorized = Schema.is(
53 EnvironmentConnector.EnvironmentConnectNotAuthorized,
54);
55
56function requestBodyText(request: HttpClientRequest.HttpClientRequest): string {
57 return request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}";
58}
59
60const settings = RelayConfiguration.RelayConfiguration.of({
61 relayIssuer: "https://relay.example.test",
62 apns: {
63 environment: "sandbox",
64 teamId: "team-id",
65 keyId: "key-id",
66 privateKey: Redacted.make("private-key"),
67 bundleId: "com.t3tools.t3code.dev",
68 },
69 apnsDeliveryJobSigningSecret: Redacted.make("job-secret"),
70 clerkSecretKey: Redacted.make("clerk-secret"),
71 clerkPublishableKey: "pk_test_test",
72 clerkJwtAudience: "t3-code-relay",
73 cloudMintPrivateKey: Redacted.make(cloudKeyPair.privateKey),
74 cloudMintPublicKey: cloudKeyPair.publicKey,
75 managedEndpointBaseDomain: "example.test",
76 managedEndpointNamespace: undefined,
77});
78
79function signTestJwt(payload: object, typ: string, privateKey: string): string {
80 const header = Buffer.from(JSON.stringify({ alg: "EdDSA", typ })).toString("base64url");
81 const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url");
82 const input = `${header}.${encodedPayload}`;
83 return `${input}.${NodeCrypto.sign(null, Buffer.from(input), privateKey).toString("base64url")}`;
84}
85
86function decodeRequestProof<T>(proof: string): T {
87 const payload = proof.split(".")[1];
88 if (!payload) throw new Error("Missing JWT payload.");
89 return JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as T;
90}
91
92function signMintResponse(
93 request: RelayCloudMintCredentialRequest,
94 overrides: Partial<RelayEnvironmentMintResponseProofPayload> = {},
95 privateKey = environmentKeyPair.privateKey,
96): RelayEnvironmentMintResponse {
97 const requestProof = decodeRequestProof<RelayCloudMintCredentialProofPayload>(request.proof);
98 const payload = {
99 iss: `t3-env:${requestProof.environmentId}`,
100 aud: "https://relay.example.test",
101 sub: requestProof.environmentId,
102 jti: "mint-response-jti",
103 iat: requestProof.iat,
104 exp: requestProof.exp,
105 environmentId: requestProof.environmentId,
106 clientProofKeyThumbprint: requestProof.clientProofKeyThumbprint,
107 requestNonce: requestProof.nonce,
108 credential: "pairing_credential",
109 ...overrides,
110 } satisfies RelayEnvironmentMintResponseProofPayload;
111 return {
112 credential: payload.credential,
113 expiresAt: DateTime.formatIso(DateTime.makeUnsafe(payload.exp * 1_000)),
114 proof: signTestJwt(payload, RELAY_MINT_RESPONSE_TYP, privateKey),
115 };
116}
117
118function signHealthResponse(
119 request: RelayCloudEnvironmentHealthRequest,
120 privateKey = environmentKeyPair.privateKey,
121 overrides: Partial<RelayEnvironmentHealthResponse> = {},
122 payloadOverrides: Partial<RelayEnvironmentHealthResponseProofPayload> = {},
123): RelayEnvironmentHealthResponse {
124 const requestProof = decodeRequestProof<RelayCloudEnvironmentHealthProofPayload>(request.proof);
125 const payload = {
126 iss: `t3-env:${requestProof.environmentId}`,
127 aud: "https://relay.example.test",
128 sub: requestProof.environmentId,
129 jti: "health-response-jti",
130 iat: requestProof.iat,
131 exp: requestProof.exp,
132 environmentId: requestProof.environmentId,
133 requestNonce: requestProof.nonce,
134 status: "online",
135 descriptor: {
136 environmentId: requestProof.environmentId,
137 label: "Connector Test Environment",
138 platform: { os: "darwin", arch: "arm64" },
139 serverVersion: "0.0.0-test",
140 capabilities: { repositoryIdentity: true },
141 },
142 checkedAt: DateTime.formatIso(DateTime.makeUnsafe(requestProof.iat * 1_000)),
143 ...payloadOverrides,
144 } satisfies RelayEnvironmentHealthResponseProofPayload;
145 return {
146 environmentId: payload.environmentId,
147 status: "online",
148 descriptor: payload.descriptor,
149 checkedAt: payload.checkedAt,
150 proof: signTestJwt(payload, RELAY_HEALTH_RESPONSE_TYP, privateKey),
151 ...overrides,
152 };
153}
154
155function layerConnectorTest(
156 execute: (
157 request: HttpClientRequest.HttpClientRequest,
158 ) => Effect.Effect<HttpClientResponse.HttpClientResponse>,
159 options?: {
160 readonly links?: EnvironmentLinks.EnvironmentLinks["Service"];
161 readonly allocations?: ManagedEndpointAllocations.ManagedEndpointAllocations["Service"];
162 },
163) {
164 return EnvironmentConnector.layer.pipe(
165 Layer.provide(NodeCryptoLayer.layer),
166 Layer.provide(Layer.succeed(EnvironmentLinks.EnvironmentLinks, options?.links ?? makeLinks())),
167 Layer.provide(
168 Layer.succeed(
169 ManagedEndpointAllocations.ManagedEndpointAllocations,
170 options?.allocations ?? makeAllocations(),
171 ),
172 ),
173 Layer.provide(RelayConfiguration.layer(settings)),
174 Layer.provide(Layer.succeed(HttpClient.HttpClient, HttpClient.make(execute))),
175 );
176}
177
178function makeAllocations(
179 allocation: ManagedEndpointAllocations.ManagedEndpointAllocation | null = {
180 userId: "user_123",
181 environmentId: "env-connector-test",
182 hostname: "env.example.test",
183 tunnelId: "tunnel-id",
184 tunnelName: "tunnel-name",
185 dnsRecordId: "dns-record-id",
186 readyAt: "2026-05-25T00:00:00.000Z",
187 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
188 updatedAt: "2026-05-25T00:00:00.000Z",
189 generation: 1,
190 tunnelReleasedAt: null,
191 },
192): ManagedEndpointAllocations.ManagedEndpointAllocations["Service"] {
193 return {
194 getByTunnelName: () => Effect.die("unused getByTunnelName"),
195 get: () => Effect.succeed(allocation),
196 reserve: () => Effect.die("unused"),
197 recordTunnel: () => Effect.die("unused"),
198 recordDns: () => Effect.die("unused"),
199 markReady: () => Effect.die("unused"),
200 enableRecovery: () => Effect.die("unused"),
201 listByTunnelNames: () => Effect.die("unused"),
202 claimRelease: () => Effect.die("unused"),
203 withClaimedTunnel: () => Effect.die("unused"),
204 claimDeprovision: () => Effect.die("unused"),
205 remove: () => Effect.die("unused"),
206 removeClaimed: () => Effect.die("unused"),
207 };
208}
209
210function makeLinks(
211 overrides: Partial<EnvironmentLinks.RelayLinkedEnvironmentRecord> = {},
212): EnvironmentLinks.EnvironmentLinks["Service"] {
213 return {
214 upsert: () => Effect.void,
215 listDeliveryUsersForEnvironment: () => Effect.succeed([]),
216 listForUser: () => Effect.succeed([]),
217 getForUser: () =>
218 Effect.succeed({
219 environmentId: "env-connector-test" as never,
220 label: "Connector Test Environment",
221 endpoint: {
222 httpBaseUrl: "https://env.example.test/",
223 wsBaseUrl: "wss://env.example.test/ws",
224 providerKind: "cloudflare_tunnel",
225 },
226 linkedAt: "2026-05-25T00:00:00.000Z",
227 environmentPublicKey: environmentKeyPair.publicKey,
228 ...overrides,
229 }),
230 findActiveManagedForEnvironment: () => Effect.succeed([]),
231 setHoldWebhooksWhileOffline: () => Effect.void,
232 revokeForUser: () => Effect.succeed(false),
233 };
234}
235
236describe("EnvironmentConnector", () => {
237 it.effect("checks linked environment health through the managed endpoint", () => {
238 const seenUrls: Array<string> = [];
239 const seenProofs: Array<RelayCloudEnvironmentHealthProofPayload> = [];
240 const execute = (request: HttpClientRequest.HttpClientRequest) =>
241 Effect.sync(() => {
242 const healthRequest = decodeHealthRequestBody(requestBodyText(request));
243 seenUrls.push(request.url);
244 seenProofs.push(decodeRequestProof(healthRequest.proof));
245 return HttpClientResponse.fromWeb(
246 request,
247 Response.json(signHealthResponse(healthRequest), { status: 200 }),
248 );
249 });
250
251 return Effect.gen(function* () {
252 const connector = yield* EnvironmentConnector.EnvironmentConnector;
253 const result = yield* connector.status({
254 userId: "user_123",
255 environmentId: "env-connector-test",
256 });
257
258 expect(seenUrls).toEqual(["https://env.example.test/api/t3-connect/health"]);
259 expect(seenProofs[0]).toMatchObject({
260 iss: "https://relay.example.test",
261 aud: "t3-env:env-connector-test",
262 sub: "user_123",
263 environmentId: "env-connector-test",
264 scope: ["environment:status"],
265 });
266 expect(result).toMatchObject({
267 environmentId: "env-connector-test",
268 status: "online",
269 descriptor: {
270 environmentId: "env-connector-test",
271 label: "Connector Test Environment",
272 },
273 });
274 }).pipe(Effect.provide(layerConnectorTest(execute)));
275 });
276
277 it.effect("rejects manual endpoints before sending a health request", () => {
278 let requestCount = 0;
279 const execute = () =>
280 Effect.sync(() => {
281 requestCount += 1;
282 throw new Error("unexpected request");
283 });
284
285 return Effect.gen(function* () {
286 const connector = yield* EnvironmentConnector.EnvironmentConnector;
287 const result = yield* Effect.result(
288 connector.status({
289 userId: "user_123",
290 environmentId: "env-connector-test",
291 }),
292 );
293
294 expect(Result.isFailure(result)).toBe(true);
295 if (Result.isFailure(result)) {
296 expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);
297 if (isEnvironmentConnectNotAuthorized(result.failure)) {
298 expect(result.failure).toMatchObject({
299 operation: "status",
300 reason: "endpoint_provider_not_managed",
301 });
302 }
303 }
304 expect(requestCount).toBe(0);
305 }).pipe(
306 Effect.provide(
307 layerConnectorTest(execute, {
308 links: makeLinks({
309 endpoint: {
310 httpBaseUrl: "https://127.0.0.1/",
311 wsBaseUrl: "wss://127.0.0.1/ws",
312 providerKind: "manual",
313 },
314 }),
315 }),
316 ),
317 );
318 });
319
320 it.effect("rejects stale managed endpoints before sending a mint request", () => {
321 let requestCount = 0;
322 const spans: Array<Tracer.NativeSpan> = [];
323 const tracer = Tracer.make({
324 span: (options) => {
325 const span = new Tracer.NativeSpan(options);
326 spans.push(span);
327 return span;
328 },
329 });
330 const execute = () =>
331 Effect.sync(() => {
332 requestCount += 1;
333 throw new Error("unexpected request");
334 });
335
336 return Effect.gen(function* () {
337 const connector = yield* EnvironmentConnector.EnvironmentConnector;
338 const result = yield* Effect.result(
339 connector.connect({
340 userId: "user_123",
341 environmentId: "env-connector-test",
342 clientProofKeyThumbprint: "client-proof-key-thumbprint",
343 }),
344 );
345
346 expect(Result.isFailure(result)).toBe(true);
347 if (Result.isFailure(result)) {
348 expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);
349 if (isEnvironmentConnectNotAuthorized(result.failure)) {
350 expect(result.failure).toMatchObject({
351 operation: "connect",
352 reason: "managed_endpoint_mismatch",
353 });
354 }
355 }
356 const resolutionSpan = spans.find(
357 (span) => span.name === "relay.environment_connector.resolve_managed_endpoint",
358 );
359 expect(Object.fromEntries(resolutionSpan?.attributes ?? [])).toMatchObject({
360 "relay.authorization.allocation_hostname": "env.example.test",
361 "relay.authorization.allocation_has_ready_at": true,
362 "relay.authorization.allocation_has_tunnel_id": true,
363 "relay.authorization.allocation_has_dns_record_id": true,
364 "relay.authorization.linked_http_base_url": "https://attacker.example.test/",
365 "relay.authorization.linked_ws_base_url": "wss://attacker.example.test/ws",
366 "relay.authorization.resolved_http_base_url": "https://env.example.test/",
367 "relay.authorization.resolved_ws_base_url": "wss://env.example.test/ws",
368 });
369 expect(requestCount).toBe(0);
370 }).pipe(
371 Effect.provide(
372 layerConnectorTest(execute, {
373 links: makeLinks({
374 endpoint: {
375 httpBaseUrl: "https://attacker.example.test/",
376 wsBaseUrl: "wss://attacker.example.test/ws",
377 providerKind: "cloudflare_tunnel",
378 },
379 }),
380 }),
381 ),
382 Effect.provideService(Tracer.Tracer, tracer),
383 );
384 });
385
386 it.effect("rejects unready managed endpoint allocations before sending a request", () => {
387 let requestCount = 0;
388 const execute = () =>
389 Effect.sync(() => {
390 requestCount += 1;
391 throw new Error("unexpected request");
392 });
393
394 return Effect.gen(function* () {
395 const connector = yield* EnvironmentConnector.EnvironmentConnector;
396 const result = yield* Effect.result(
397 connector.status({
398 userId: "user_123",
399 environmentId: "env-connector-test",
400 }),
401 );
402
403 expect(Result.isFailure(result)).toBe(true);
404 if (Result.isFailure(result)) {
405 expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);
406 if (isEnvironmentConnectNotAuthorized(result.failure)) {
407 expect(result.failure).toMatchObject({
408 operation: "status",
409 reason: "managed_endpoint_allocation_not_ready",
410 });
411 }
412 }
413 expect(requestCount).toBe(0);
414 }).pipe(
415 Effect.provide(
416 layerConnectorTest(execute, {
417 allocations: makeAllocations({
418 userId: "user_123",
419 environmentId: "env-connector-test",
420 hostname: "env.example.test",
421 tunnelId: "tunnel-id",
422 tunnelName: "tunnel-name",
423 dnsRecordId: "dns-record-id",
424 readyAt: null,
425 origin: null,
426 updatedAt: "2026-05-25T00:00:00.000Z",
427 generation: 1,
428 tunnelReleasedAt: null,
429 }),
430 }),
431 ),
432 );
433 });
434
435 it.effect("rejects signed health responses with stale checkedAt timestamps", () => {
436 const execute = (request: HttpClientRequest.HttpClientRequest) =>
437 Effect.sync(() => {
438 const healthRequest = decodeHealthRequestBody(requestBodyText(request));
439 return HttpClientResponse.fromWeb(
440 request,
441 Response.json(
442 signHealthResponse(
443 healthRequest,
444 environmentKeyPair.privateKey,
445 {},
446 {
447 checkedAt: "2026-05-24T00:00:00.000Z",
448 },
449 ),
450 { status: 200 },
451 ),
452 );
453 });
454
455 return Effect.gen(function* () {
456 const connector = yield* EnvironmentConnector.EnvironmentConnector;
457 const result = yield* Effect.exit(
458 connector.status({
459 userId: "user_123",
460 environmentId: "env-connector-test",
461 }),
462 );
463
464 expect(result._tag).toBe("Failure");
465 if (result._tag === "Failure") {
466 expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");
467 }
468 }).pipe(Effect.provide(layerConnectorTest(execute)));
469 });
470
471 it.effect("reports a released tunnel as the reason an environment is offline", () => {
472 const execute = (request: HttpClientRequest.HttpClientRequest) =>
473 Effect.succeed(
474 HttpClientResponse.fromWeb(request, new Response("tunnel not found", { status: 530 })),
475 );
476 const allocations = makeAllocations({
477 userId: "user_123",
478 environmentId: "env-connector-test",
479 hostname: "env.example.test",
480 tunnelId: "tunnel-id",
481 tunnelName: "tunnel-name",
482 dnsRecordId: "dns-record-id",
483 readyAt: "2026-05-25T00:00:00.000Z",
484 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
485 updatedAt: "2026-05-25T00:00:00.000Z",
486 generation: 2,
487 tunnelReleasedAt: "2026-05-26T00:00:00.000Z",
488 });
489
490 return Effect.gen(function* () {
491 const connector = yield* EnvironmentConnector.EnvironmentConnector;
492 const result = yield* connector.status({
493 userId: "user_123",
494 environmentId: "env-connector-test",
495 });
496
497 expect(result).toMatchObject({ status: "offline", offlineReason: "tunnel_released" });
498 }).pipe(Effect.provide(layerConnectorTest(execute, { allocations })));
499 });
500
501 it.effect("rejects health responses with a mismatched top-level environment id", () => {
502 const execute = (request: HttpClientRequest.HttpClientRequest) =>
503 Effect.sync(() => {
504 const healthRequest = decodeHealthRequestBody(requestBodyText(request));
505 return HttpClientResponse.fromWeb(
506 request,
507 Response.json(
508 signHealthResponse(healthRequest, environmentKeyPair.privateKey, {
509 environmentId: "other-env" as RelayEnvironmentHealthResponse["environmentId"],
510 }),
511 { status: 200 },
512 ),
513 );
514 });
515
516 return Effect.gen(function* () {
517 const connector = yield* EnvironmentConnector.EnvironmentConnector;
518 const result = yield* Effect.exit(
519 connector.status({
520 userId: "user_123",
521 environmentId: "env-connector-test",
522 }),
523 );
524
525 expect(result._tag).toBe("Failure");
526 if (result._tag === "Failure") {
527 expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");
528 }
529 }).pipe(Effect.provide(layerConnectorTest(execute)));
530 });
531
532 it.effect("rejects health responses with an unsigned top-level descriptor mutation", () => {
533 const execute = (request: HttpClientRequest.HttpClientRequest) =>
534 Effect.sync(() => {
535 const healthRequest = decodeHealthRequestBody(requestBodyText(request));
536 const response = signHealthResponse(healthRequest);
537 return HttpClientResponse.fromWeb(
538 request,
539 Response.json(
540 {
541 ...response,
542 descriptor: {
543 ...response.descriptor,
544 label: "Tampered Environment Label",
545 },
546 } satisfies RelayEnvironmentHealthResponse,
547 { status: 200 },
548 ),
549 );
550 });
551
552 return Effect.gen(function* () {
553 const connector = yield* EnvironmentConnector.EnvironmentConnector;
554 const result = yield* Effect.exit(
555 connector.status({
556 userId: "user_123",
557 environmentId: "env-connector-test",
558 }),
559 );
560
561 expect(result._tag).toBe("Failure");
562 if (result._tag === "Failure") {
563 expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");
564 }
565 }).pipe(Effect.provide(layerConnectorTest(execute)));
566 });
567
568 it.effect("rejects health responses when the linked environment public key is malformed", () => {
569 const execute = (request: HttpClientRequest.HttpClientRequest) =>
570 Effect.sync(() => {
571 const healthRequest = decodeHealthRequestBody(requestBodyText(request));
572 return HttpClientResponse.fromWeb(
573 request,
574 Response.json(signHealthResponse(healthRequest), { status: 200 }),
575 );
576 });
577
578 return Effect.gen(function* () {
579 const connector = yield* EnvironmentConnector.EnvironmentConnector;
580 const result = yield* Effect.exit(
581 connector.status({
582 userId: "user_123",
583 environmentId: "env-connector-test",
584 }),
585 );
586
587 expect(result._tag).toBe("Failure");
588 if (result._tag === "Failure") {
589 expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");
590 }
591 }).pipe(
592 Effect.provide(
593 layerConnectorTest(execute, {
594 links: makeLinks({
595 environmentPublicKey: "not a pem public key",
596 }),
597 }),
598 ),
599 );
600 });
601
602 it.effect("mints a one-time environment credential through the linked endpoint", () => {
603 const seenUrls: Array<string> = [];
604 const seenProofs: Array<RelayCloudMintCredentialProofPayload> = [];
605 const execute = (request: HttpClientRequest.HttpClientRequest) =>
606 Effect.sync(() => {
607 const mintRequest = decodeMintRequestBody(requestBodyText(request));
608 seenUrls.push(request.url);
609 seenProofs.push(decodeRequestProof(mintRequest.proof));
610 return HttpClientResponse.fromWeb(
611 request,
612 Response.json(signMintResponse(mintRequest), { status: 200 }),
613 );
614 });
615
616 return Effect.gen(function* () {
617 const connector = yield* EnvironmentConnector.EnvironmentConnector;
618 const result = yield* connector.connect({
619 userId: "user_123",
620 environmentId: "env-connector-test",
621 clientProofKeyThumbprint: "client-proof-key-thumbprint",
622 deviceId: "device-123",
623 });
624
625 expect(seenUrls).toEqual(["https://env.example.test/api/t3-connect/mint-credential"]);
626 expect(seenProofs[0]).toMatchObject({
627 iss: "https://relay.example.test",
628 aud: "t3-env:env-connector-test",
629 sub: "user_123",
630 environmentId: "env-connector-test",
631 clientProofKeyThumbprint: "client-proof-key-thumbprint",
632 cnf: { jkt: "client-proof-key-thumbprint" },
633 deviceId: "device-123",
634 scope: ["environment:connect"],
635 });
636 expect(result).toMatchObject({
637 environmentId: "env-connector-test",
638 credential: "pairing_credential",
639 endpoint: {
640 httpBaseUrl: "https://env.example.test/",
641 wsBaseUrl: "wss://env.example.test/ws",
642 },
643 });
644 }).pipe(Effect.provide(layerConnectorTest(execute)));
645 });
646
647 it.effect("only accepts mint responses signed by the user's linked environment key", () => {
648 const execute = (request: HttpClientRequest.HttpClientRequest) =>
649 Effect.sync(() => {
650 const mintRequest = decodeMintRequestBody(requestBodyText(request));
651 return HttpClientResponse.fromWeb(
652 request,
653 Response.json(signMintResponse(mintRequest, {}, otherEnvironmentKeyPair.privateKey), {
654 status: 200,
655 }),
656 );
657 });
658
659 return Effect.gen(function* () {
660 const connector = yield* EnvironmentConnector.EnvironmentConnector;
661 const result = yield* Effect.exit(
662 connector.connect({
663 userId: "user_123",
664 environmentId: "env-connector-test",
665 clientProofKeyThumbprint: "client-proof-key-thumbprint",
666 }),
667 );
668
669 expect(result._tag).toBe("Failure");
670 if (result._tag === "Failure") {
671 expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");
672 }
673 }).pipe(Effect.provide(layerConnectorTest(execute)));
674 });
675
676 it.effect("rejects environment mint responses with an overlong credential window", () => {
677 const execute = (request: HttpClientRequest.HttpClientRequest) =>
678 Effect.sync(() => {
679 const mintRequest = decodeMintRequestBody(requestBodyText(request));
680 return HttpClientResponse.fromWeb(
681 request,
682 Response.json(
683 { ...signMintResponse(mintRequest), expiresAt: "2999-01-01T00:00:00.000Z" },
684 { status: 200 },
685 ),
686 );
687 });
688
689 return Effect.gen(function* () {
690 const connector = yield* EnvironmentConnector.EnvironmentConnector;
691 const result = yield* Effect.exit(
692 connector.connect({
693 userId: "user_123",
694 environmentId: "env-connector-test",
695 clientProofKeyThumbprint: "client-proof-key-thumbprint",
696 }),
697 );
698
699 expect(result._tag).toBe("Failure");
700 if (result._tag === "Failure") {
701 expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");
702 }
703 }).pipe(Effect.provide(layerConnectorTest(execute)));
704 });
705});