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 removeClaimed: () => Effect.die("unused"),
206 };
207}
208
209function makeLinks(
210 overrides: Partial<EnvironmentLinks.RelayLinkedEnvironmentRecord> = {},
211): EnvironmentLinks.EnvironmentLinks["Service"] {
212 return {
213 upsert: () => Effect.void,
214 listDeliveryUsersForEnvironment: () => Effect.succeed([]),
215 listForUser: () => Effect.succeed([]),
216 getForUser: () =>
217 Effect.succeed({
218 environmentId: "env-connector-test" as never,
219 label: "Connector Test Environment",
220 endpoint: {
221 httpBaseUrl: "https://env.example.test/",
222 wsBaseUrl: "wss://env.example.test/ws",
223 providerKind: "cloudflare_tunnel",
224 },
225 linkedAt: "2026-05-25T00:00:00.000Z",
226 environmentPublicKey: environmentKeyPair.publicKey,
227 ...overrides,
228 }),
229 findActiveManagedForEnvironment: () => Effect.succeed([]),
230 setHoldWebhooksWhileOffline: () => Effect.void,
231 revokeForUser: () => Effect.succeed(false),
232 };
233}
234
235describe("EnvironmentConnector", () => {
236 it.effect("checks linked environment health through the managed endpoint", () => {
237 const seenUrls: Array<string> = [];
238 const seenProofs: Array<RelayCloudEnvironmentHealthProofPayload> = [];
239 const execute = (request: HttpClientRequest.HttpClientRequest) =>
240 Effect.sync(() => {
241 const healthRequest = decodeHealthRequestBody(requestBodyText(request));
242 seenUrls.push(request.url);
243 seenProofs.push(decodeRequestProof(healthRequest.proof));
244 return HttpClientResponse.fromWeb(
245 request,
246 Response.json(signHealthResponse(healthRequest), { status: 200 }),
247 );
248 });
249
250 return Effect.gen(function* () {
251 const connector = yield* EnvironmentConnector.EnvironmentConnector;
252 const result = yield* connector.status({
253 userId: "user_123",
254 environmentId: "env-connector-test",
255 });
256
257 expect(seenUrls).toEqual(["https://env.example.test/api/t3-connect/health"]);
258 expect(seenProofs[0]).toMatchObject({
259 iss: "https://relay.example.test",
260 aud: "t3-env:env-connector-test",
261 sub: "user_123",
262 environmentId: "env-connector-test",
263 scope: ["environment:status"],
264 });
265 expect(result).toMatchObject({
266 environmentId: "env-connector-test",
267 status: "online",
268 descriptor: {
269 environmentId: "env-connector-test",
270 label: "Connector Test Environment",
271 },
272 });
273 }).pipe(Effect.provide(layerConnectorTest(execute)));
274 });
275
276 it.effect("rejects manual endpoints before sending a health request", () => {
277 let requestCount = 0;
278 const execute = () =>
279 Effect.sync(() => {
280 requestCount += 1;
281 throw new Error("unexpected request");
282 });
283
284 return Effect.gen(function* () {
285 const connector = yield* EnvironmentConnector.EnvironmentConnector;
286 const result = yield* Effect.result(
287 connector.status({
288 userId: "user_123",
289 environmentId: "env-connector-test",
290 }),
291 );
292
293 expect(Result.isFailure(result)).toBe(true);
294 if (Result.isFailure(result)) {
295 expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);
296 if (isEnvironmentConnectNotAuthorized(result.failure)) {
297 expect(result.failure).toMatchObject({
298 operation: "status",
299 reason: "endpoint_provider_not_managed",
300 });
301 }
302 }
303 expect(requestCount).toBe(0);
304 }).pipe(
305 Effect.provide(
306 layerConnectorTest(execute, {
307 links: makeLinks({
308 endpoint: {
309 httpBaseUrl: "https://127.0.0.1/",
310 wsBaseUrl: "wss://127.0.0.1/ws",
311 providerKind: "manual",
312 },
313 }),
314 }),
315 ),
316 );
317 });
318
319 it.effect("rejects stale managed endpoints before sending a mint request", () => {
320 let requestCount = 0;
321 const spans: Array<Tracer.NativeSpan> = [];
322 const tracer = Tracer.make({
323 span: (options) => {
324 const span = new Tracer.NativeSpan(options);
325 spans.push(span);
326 return span;
327 },
328 });
329 const execute = () =>
330 Effect.sync(() => {
331 requestCount += 1;
332 throw new Error("unexpected request");
333 });
334
335 return Effect.gen(function* () {
336 const connector = yield* EnvironmentConnector.EnvironmentConnector;
337 const result = yield* Effect.result(
338 connector.connect({
339 userId: "user_123",
340 environmentId: "env-connector-test",
341 clientProofKeyThumbprint: "client-proof-key-thumbprint",
342 }),
343 );
344
345 expect(Result.isFailure(result)).toBe(true);
346 if (Result.isFailure(result)) {
347 expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);
348 if (isEnvironmentConnectNotAuthorized(result.failure)) {
349 expect(result.failure).toMatchObject({
350 operation: "connect",
351 reason: "managed_endpoint_mismatch",
352 });
353 }
354 }
355 const resolutionSpan = spans.find(
356 (span) => span.name === "relay.environment_connector.resolve_managed_endpoint",
357 );
358 expect(Object.fromEntries(resolutionSpan?.attributes ?? [])).toMatchObject({
359 "relay.authorization.allocation_hostname": "env.example.test",
360 "relay.authorization.allocation_has_ready_at": true,
361 "relay.authorization.allocation_has_tunnel_id": true,
362 "relay.authorization.allocation_has_dns_record_id": true,
363 "relay.authorization.linked_http_base_url": "https://attacker.example.test/",
364 "relay.authorization.linked_ws_base_url": "wss://attacker.example.test/ws",
365 "relay.authorization.resolved_http_base_url": "https://env.example.test/",
366 "relay.authorization.resolved_ws_base_url": "wss://env.example.test/ws",
367 });
368 expect(requestCount).toBe(0);
369 }).pipe(
370 Effect.provide(
371 layerConnectorTest(execute, {
372 links: makeLinks({
373 endpoint: {
374 httpBaseUrl: "https://attacker.example.test/",
375 wsBaseUrl: "wss://attacker.example.test/ws",
376 providerKind: "cloudflare_tunnel",
377 },
378 }),
379 }),
380 ),
381 Effect.provideService(Tracer.Tracer, tracer),
382 );
383 });
384
385 it.effect("rejects unready managed endpoint allocations before sending a request", () => {
386 let requestCount = 0;
387 const execute = () =>
388 Effect.sync(() => {
389 requestCount += 1;
390 throw new Error("unexpected request");
391 });
392
393 return Effect.gen(function* () {
394 const connector = yield* EnvironmentConnector.EnvironmentConnector;
395 const result = yield* Effect.result(
396 connector.status({
397 userId: "user_123",
398 environmentId: "env-connector-test",
399 }),
400 );
401
402 expect(Result.isFailure(result)).toBe(true);
403 if (Result.isFailure(result)) {
404 expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);
405 if (isEnvironmentConnectNotAuthorized(result.failure)) {
406 expect(result.failure).toMatchObject({
407 operation: "status",
408 reason: "managed_endpoint_allocation_not_ready",
409 });
410 }
411 }
412 expect(requestCount).toBe(0);
413 }).pipe(
414 Effect.provide(
415 layerConnectorTest(execute, {
416 allocations: makeAllocations({
417 userId: "user_123",
418 environmentId: "env-connector-test",
419 hostname: "env.example.test",
420 tunnelId: "tunnel-id",
421 tunnelName: "tunnel-name",
422 dnsRecordId: "dns-record-id",
423 readyAt: null,
424 origin: null,
425 updatedAt: "2026-05-25T00:00:00.000Z",
426 generation: 1,
427 tunnelReleasedAt: null,
428 }),
429 }),
430 ),
431 );
432 });
433
434 it.effect("rejects signed health responses with stale checkedAt timestamps", () => {
435 const execute = (request: HttpClientRequest.HttpClientRequest) =>
436 Effect.sync(() => {
437 const healthRequest = decodeHealthRequestBody(requestBodyText(request));
438 return HttpClientResponse.fromWeb(
439 request,
440 Response.json(
441 signHealthResponse(
442 healthRequest,
443 environmentKeyPair.privateKey,
444 {},
445 {
446 checkedAt: "2026-05-24T00:00:00.000Z",
447 },
448 ),
449 { status: 200 },
450 ),
451 );
452 });
453
454 return Effect.gen(function* () {
455 const connector = yield* EnvironmentConnector.EnvironmentConnector;
456 const result = yield* Effect.exit(
457 connector.status({
458 userId: "user_123",
459 environmentId: "env-connector-test",
460 }),
461 );
462
463 expect(result._tag).toBe("Failure");
464 if (result._tag === "Failure") {
465 expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");
466 }
467 }).pipe(Effect.provide(layerConnectorTest(execute)));
468 });
469
470 it.effect("reports a released tunnel as the reason an environment is offline", () => {
471 const execute = (request: HttpClientRequest.HttpClientRequest) =>
472 Effect.succeed(
473 HttpClientResponse.fromWeb(request, new Response("tunnel not found", { status: 530 })),
474 );
475 const allocations = makeAllocations({
476 userId: "user_123",
477 environmentId: "env-connector-test",
478 hostname: "env.example.test",
479 tunnelId: "tunnel-id",
480 tunnelName: "tunnel-name",
481 dnsRecordId: "dns-record-id",
482 readyAt: "2026-05-25T00:00:00.000Z",
483 origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
484 updatedAt: "2026-05-25T00:00:00.000Z",
485 generation: 2,
486 tunnelReleasedAt: "2026-05-26T00:00:00.000Z",
487 });
488
489 return Effect.gen(function* () {
490 const connector = yield* EnvironmentConnector.EnvironmentConnector;
491 const result = yield* connector.status({
492 userId: "user_123",
493 environmentId: "env-connector-test",
494 });
495
496 expect(result).toMatchObject({ status: "offline", offlineReason: "tunnel_released" });
497 }).pipe(Effect.provide(layerConnectorTest(execute, { allocations })));
498 });
499
500 it.effect("rejects health responses with a mismatched top-level environment id", () => {
501 const execute = (request: HttpClientRequest.HttpClientRequest) =>
502 Effect.sync(() => {
503 const healthRequest = decodeHealthRequestBody(requestBodyText(request));
504 return HttpClientResponse.fromWeb(
505 request,
506 Response.json(
507 signHealthResponse(healthRequest, environmentKeyPair.privateKey, {
508 environmentId: "other-env" as RelayEnvironmentHealthResponse["environmentId"],
509 }),
510 { status: 200 },
511 ),
512 );
513 });
514
515 return Effect.gen(function* () {
516 const connector = yield* EnvironmentConnector.EnvironmentConnector;
517 const result = yield* Effect.exit(
518 connector.status({
519 userId: "user_123",
520 environmentId: "env-connector-test",
521 }),
522 );
523
524 expect(result._tag).toBe("Failure");
525 if (result._tag === "Failure") {
526 expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");
527 }
528 }).pipe(Effect.provide(layerConnectorTest(execute)));
529 });
530
531 it.effect("rejects health responses with an unsigned top-level descriptor mutation", () => {
532 const execute = (request: HttpClientRequest.HttpClientRequest) =>
533 Effect.sync(() => {
534 const healthRequest = decodeHealthRequestBody(requestBodyText(request));
535 const response = signHealthResponse(healthRequest);
536 return HttpClientResponse.fromWeb(
537 request,
538 Response.json(
539 {
540 ...response,
541 descriptor: {
542 ...response.descriptor,
543 label: "Tampered Environment Label",
544 },
545 } satisfies RelayEnvironmentHealthResponse,
546 { status: 200 },
547 ),
548 );
549 });
550
551 return Effect.gen(function* () {
552 const connector = yield* EnvironmentConnector.EnvironmentConnector;
553 const result = yield* Effect.exit(
554 connector.status({
555 userId: "user_123",
556 environmentId: "env-connector-test",
557 }),
558 );
559
560 expect(result._tag).toBe("Failure");
561 if (result._tag === "Failure") {
562 expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");
563 }
564 }).pipe(Effect.provide(layerConnectorTest(execute)));
565 });
566
567 it.effect("rejects health responses when the linked environment public key is malformed", () => {
568 const execute = (request: HttpClientRequest.HttpClientRequest) =>
569 Effect.sync(() => {
570 const healthRequest = decodeHealthRequestBody(requestBodyText(request));
571 return HttpClientResponse.fromWeb(
572 request,
573 Response.json(signHealthResponse(healthRequest), { status: 200 }),
574 );
575 });
576
577 return Effect.gen(function* () {
578 const connector = yield* EnvironmentConnector.EnvironmentConnector;
579 const result = yield* Effect.exit(
580 connector.status({
581 userId: "user_123",
582 environmentId: "env-connector-test",
583 }),
584 );
585
586 expect(result._tag).toBe("Failure");
587 if (result._tag === "Failure") {
588 expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");
589 }
590 }).pipe(
591 Effect.provide(
592 layerConnectorTest(execute, {
593 links: makeLinks({
594 environmentPublicKey: "not a pem public key",
595 }),
596 }),
597 ),
598 );
599 });
600
601 it.effect("mints a one-time environment credential through the linked endpoint", () => {
602 const seenUrls: Array<string> = [];
603 const seenProofs: Array<RelayCloudMintCredentialProofPayload> = [];
604 const execute = (request: HttpClientRequest.HttpClientRequest) =>
605 Effect.sync(() => {
606 const mintRequest = decodeMintRequestBody(requestBodyText(request));
607 seenUrls.push(request.url);
608 seenProofs.push(decodeRequestProof(mintRequest.proof));
609 return HttpClientResponse.fromWeb(
610 request,
611 Response.json(signMintResponse(mintRequest), { status: 200 }),
612 );
613 });
614
615 return Effect.gen(function* () {
616 const connector = yield* EnvironmentConnector.EnvironmentConnector;
617 const result = yield* connector.connect({
618 userId: "user_123",
619 environmentId: "env-connector-test",
620 clientProofKeyThumbprint: "client-proof-key-thumbprint",
621 deviceId: "device-123",
622 });
623
624 expect(seenUrls).toEqual(["https://env.example.test/api/t3-connect/mint-credential"]);
625 expect(seenProofs[0]).toMatchObject({
626 iss: "https://relay.example.test",
627 aud: "t3-env:env-connector-test",
628 sub: "user_123",
629 environmentId: "env-connector-test",
630 clientProofKeyThumbprint: "client-proof-key-thumbprint",
631 cnf: { jkt: "client-proof-key-thumbprint" },
632 deviceId: "device-123",
633 scope: ["environment:connect"],
634 });
635 expect(result).toMatchObject({
636 environmentId: "env-connector-test",
637 credential: "pairing_credential",
638 endpoint: {
639 httpBaseUrl: "https://env.example.test/",
640 wsBaseUrl: "wss://env.example.test/ws",
641 },
642 });
643 }).pipe(Effect.provide(layerConnectorTest(execute)));
644 });
645
646 it.effect("only accepts mint responses signed by the user's linked environment key", () => {
647 const execute = (request: HttpClientRequest.HttpClientRequest) =>
648 Effect.sync(() => {
649 const mintRequest = decodeMintRequestBody(requestBodyText(request));
650 return HttpClientResponse.fromWeb(
651 request,
652 Response.json(signMintResponse(mintRequest, {}, otherEnvironmentKeyPair.privateKey), {
653 status: 200,
654 }),
655 );
656 });
657
658 return Effect.gen(function* () {
659 const connector = yield* EnvironmentConnector.EnvironmentConnector;
660 const result = yield* Effect.exit(
661 connector.connect({
662 userId: "user_123",
663 environmentId: "env-connector-test",
664 clientProofKeyThumbprint: "client-proof-key-thumbprint",
665 }),
666 );
667
668 expect(result._tag).toBe("Failure");
669 if (result._tag === "Failure") {
670 expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");
671 }
672 }).pipe(Effect.provide(layerConnectorTest(execute)));
673 });
674
675 it.effect("rejects environment mint responses with an overlong credential window", () => {
676 const execute = (request: HttpClientRequest.HttpClientRequest) =>
677 Effect.sync(() => {
678 const mintRequest = decodeMintRequestBody(requestBodyText(request));
679 return HttpClientResponse.fromWeb(
680 request,
681 Response.json(
682 { ...signMintResponse(mintRequest), expiresAt: "2999-01-01T00:00:00.000Z" },
683 { status: 200 },
684 ),
685 );
686 });
687
688 return Effect.gen(function* () {
689 const connector = yield* EnvironmentConnector.EnvironmentConnector;
690 const result = yield* Effect.exit(
691 connector.connect({
692 userId: "user_123",
693 environmentId: "env-connector-test",
694 clientProofKeyThumbprint: "client-proof-key-thumbprint",
695 }),
696 );
697
698 expect(result._tag).toBe("Failure");
699 if (result._tag === "Failure") {
700 expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");
701 }
702 }).pipe(Effect.provide(layerConnectorTest(execute)));
703 });
704});