Repository navigation
Expand file tree
/
Copy pathCloudLink.ts
More file actions
1665 lines (1590 loc) · 62.5 KB
/
Copy pathCloudLink.ts
File metadata and controls
1665 lines (1590 loc) · 62.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createPublicKey.
import * as NodeCrypto from "node:crypto";
import {
AuthStandardClientScopes,
type EnvironmentCloudLinkStateResult,
type EnvironmentCloudPreferencesRequest,
type EnvironmentCloudRelayConfigResult,
} from "@t3tools/contracts";
import {
RelayCloudEnvironmentHealthProofPayload,
type RelayCloudEnvironmentHealthRequest,
RelayCloudMintCredentialProofPayload,
type RelayCloudMintCredentialRequest,
type RelayEnvironmentConfigRequest,
type RelayEnvironmentHealthResponse,
type RelayEnvironmentHealthResponseProofPayload,
type RelayEnvironmentLinkProof,
type RelayEnvironmentLinkProofPayload,
RelayEnvironmentLinkChallengeResponse,
RelayEnvironmentLinkResponse,
type RelayEnvironmentMintResponse,
type RelayEnvironmentMintResponseProofPayload,
type RelayLinkProofRequest,
type RelayManagedEndpointOrigin,
type RelayManagedEndpointRecoveryProofPayload,
RelayManagedEndpointRecoveryRegistrationResponse,
RelayManagedEndpointRecoveryResponse,
type RelayManagedEndpointRuntimeConfig,
RelayOkResponse,
} from "@t3tools/contracts/relay";
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import {
normalizeRelayIssuer,
RELAY_HEALTH_REQUEST_TYP,
RELAY_HEALTH_RESPONSE_TYP,
RELAY_LINK_PROOF_TYP,
RELAY_MANAGED_TUNNEL_RECOVERY_TYP,
RELAY_MINT_REQUEST_TYP,
RELAY_MINT_RESPONSE_TYP,
signRelayJwt,
verifyRelayJwt,
} from "@t3tools/shared/relayJwt";
import { isSecureRelayUrl } from "@t3tools/shared/relayUrl";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import type * as PlatformError from "effect/PlatformError";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import {
HttpClient,
HttpClientRequest,
HttpClientResponse,
type HttpServerRequest,
} from "effect/http";
import type * as HttpClientError from "effect/http/HttpClientError";
import * as HttpServer from "effect/http/HttpServer";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts";
import { makeRelayEnvironmentClient } from "../relay/relayEnvironmentClient.ts";
import {
type CliDesiredLinkMode,
readCliDesiredCloudLink,
readCliDesiredLinkMode,
setCliDesiredCloudLink,
} from "./CliState.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
import {
CLOUD_ENDPOINT_CONFIRMED_ORIGIN,
CLOUD_ENDPOINT_RUNTIME_CONFIG,
CLOUD_LINK_REVOKED,
CLOUD_LINKED_USER_ID,
CLOUD_MINT_PUBLIC_KEY,
decodeConfirmedOrigin,
decodeRuntimeConfig,
encodeConfirmedOriginJson,
encodeEndpointRuntimeConfigJson,
HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET,
PUBLISH_AGENT_ACTIVITY_SECRET,
readRelayConnection,
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
RELAY_ISSUER_SECRET,
RELAY_URL_SECRET,
} from "./config.ts";
import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
import { relayUrlConfig } from "./publicConfig.ts";
import {
filterRelayResponse,
relayRequestError,
type RelayRequestError,
shouldRetryRelayRequest,
} from "./relayResponse.ts";
import {
hasBoundedCloudProofLifetime,
hasExactScope,
hasForwardedAuthorityHeaders,
isAllowedEndpointOrigin,
isSupportedLinkProviderKind,
linkProofScopes,
managedEndpointRuntimeConfigsMatch,
parseManagedEndpointLocalOrigin,
requestAbsoluteUrl,
} from "./linkChecks.ts";
import { desktopUpdateRestartPending, pendingUpdateHandoffExists } from "./updateHandoff.ts";
const CLOUD_MINT_NONCE_PREFIX = "cloud-mint-nonce-";
const CLOUD_MINT_JTI_PREFIX = "cloud-mint-jti-";
const CLOUD_HEALTH_NONCE_PREFIX = "cloud-health-nonce-";
const CLOUD_HEALTH_JTI_PREFIX = "cloud-health-jti-";
export const CLOUD_REPLAY_MARKER_PREFIXES = [
CLOUD_MINT_NONCE_PREFIX,
CLOUD_MINT_JTI_PREFIX,
CLOUD_HEALTH_NONCE_PREFIX,
CLOUD_HEALTH_JTI_PREFIX,
] as const;
const MANAGED_ENDPOINT_PROVISION_REQUEST_TIMEOUT = Duration.minutes(2);
const RELAY_CONFIG_FIELD_MESSAGES = {
relayUrl: "Relay URL must be a secure absolute HTTPS URL.",
relayIssuer: "Relay issuer must be a secure absolute HTTPS URL.",
environmentCredential: "Relay environment credential is required.",
cloudUserId: "Cloud user id is required.",
cloudMintPublicKey: "Cloud mint public key must be a valid Ed25519 public key.",
} as const;
export class CloudLinkRelayConfigInvalidError extends Schema.TaggedError<CloudLinkRelayConfigInvalidError>()(
"CloudLinkRelayConfigInvalidError",
{
field: Schema.Literals([
"relayUrl",
"relayIssuer",
"environmentCredential",
"cloudUserId",
"cloudMintPublicKey",
]),
},
) {
override get message(): string {
return RELAY_CONFIG_FIELD_MESSAGES[this.field];
}
}
export class CloudLinkOriginInvalidError extends Schema.TaggedError<CloudLinkOriginInvalidError>()(
"CloudLinkOriginInvalidError",
{ origin: Schema.Literals(["endpoint", "local"]) },
) {
override get message(): string {
return this.origin === "endpoint"
? "Invalid managed endpoint origin."
: "Could not resolve local environment origin.";
}
}
export class CloudLinkNotLinkedError extends Schema.TaggedError<CloudLinkNotLinkedError>()(
"CloudLinkNotLinkedError",
{},
) {
override get message(): string {
return "Link this environment to T3 Connect first.";
}
}
export class CloudLinkAccountMismatchError extends Schema.TaggedError<CloudLinkAccountMismatchError>()(
"CloudLinkAccountMismatchError",
{},
) {
override get message(): string {
return "This environment is already linked to a different cloud account. Unlink it before switching accounts.";
}
}
export class CloudLinkAuthorizationMissingError extends Schema.TaggedError<CloudLinkAuthorizationMissingError>()(
"CloudLinkAuthorizationMissingError",
{},
) {
override get message(): string {
return "Run `t3 connect link` to authorize this environment.";
}
}
const SignedRelayRequest = Schema.Literals(["health", "mint"]);
export class CloudLinkProofRejectedError extends Schema.TaggedError<CloudLinkProofRejectedError>()(
"CloudLinkProofRejectedError",
{ request: SignedRelayRequest },
) {
override get message(): string {
return `Invalid cloud ${this.request} request.`;
}
}
export class CloudLinkProofReplayedError extends Schema.TaggedError<CloudLinkProofReplayedError>()(
"CloudLinkProofReplayedError",
{ request: SignedRelayRequest },
) {
override get message(): string {
return `Cloud ${this.request} request was already consumed.`;
}
}
export class CloudLinkTunnelSupersededError extends Schema.TaggedError<CloudLinkTunnelSupersededError>()(
"CloudLinkTunnelSupersededError",
{},
) {
override get message(): string {
return "The managed tunnel configuration changed during registration.";
}
}
export class CloudLinkEndpointUnavailableError extends Schema.TaggedError<CloudLinkEndpointUnavailableError>()(
"CloudLinkEndpointUnavailableError",
{
reason: Schema.Literals(["runtime-not-started", "origin-unconfirmed"]),
endpointRuntimeStatus: Schema.Unknown,
},
) {
override get message(): string {
return this.reason === "runtime-not-started"
? "Managed endpoint runtime could not be started."
: "Managed endpoint origin could not be confirmed.";
}
}
const INTERNAL_OPERATION_MESSAGES = {
"relay-url-unconfigured":
"T3CODE_RELAY_URL must be configured as a secure absolute HTTPS origin.",
"generate-link-proof": "Could not generate environment link proof.",
"persist-relay-config": "Could not persist environment relay configuration.",
"register-endpoint-origin": "Could not register the managed endpoint origin.",
"resolve-server-origin": "Could not resolve the local server origin.",
"persist-desired-link": "Could not persist desired T3 Connect link state.",
"sign-recovery-proof": "Could not sign the managed tunnel recovery request.",
"unsupported-recovered-tunnel":
"T3 Connect returned an unsupported managed tunnel configuration.",
"persist-recovered-tunnel": "Could not persist the recovered managed tunnel configuration.",
"read-relay-config": "Could not read environment relay configuration.",
"remove-relay-config": "Could not remove environment relay configuration.",
"update-webhook-settings": "Could not update T3 Connect webhook settings.",
"read-preferences": "Could not read environment cloud preferences.",
"persist-preferences": "Could not persist environment cloud preferences.",
"answer-health": "Could not answer cloud health request.",
"issue-credential": "Could not issue cloud connection credential.",
} as const;
export class CloudLinkInternalError extends Schema.TaggedError<CloudLinkInternalError>()(
"CloudLinkInternalError",
{
operation: Schema.Literals(
Object.keys(INTERNAL_OPERATION_MESSAGES) as [
keyof typeof INTERNAL_OPERATION_MESSAGES,
...Array<keyof typeof INTERNAL_OPERATION_MESSAGES>,
],
),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return INTERNAL_OPERATION_MESSAGES[this.operation];
}
}
const internalError =
(operation: CloudLinkInternalError["operation"]) =>
(cause: unknown): Effect.Effect<never, CloudLinkInternalError> =>
Effect.fail(new CloudLinkInternalError({ operation, cause }));
const isPermanentLinkError = Schema.is(
Schema.Union([
CloudLinkRelayConfigInvalidError,
CloudLinkOriginInvalidError,
CloudLinkNotLinkedError,
CloudLinkAccountMismatchError,
CloudLinkAuthorizationMissingError,
CloudLinkProofRejectedError,
CloudLinkProofReplayedError,
CloudLinkTunnelSupersededError,
]),
);
export const shouldRetryCloudLink = (error: unknown): boolean =>
shouldRetryRelayRequest(error) && !isPermanentLinkError(error);
const rollbackFailed = (cause: unknown) =>
Effect.logWarning("Could not roll back a T3 Connect preference", { cause });
const requireRelayUrl = relayUrlConfig.pipe(
Effect.mapError(
(cause) => new CloudLinkInternalError({ operation: "relay-url-unconfigured", cause }),
),
);
function bytesToString(bytes: Uint8Array): string {
return new TextDecoder().decode(bytes);
}
function stringToBytes(value: string): Uint8Array {
return new TextEncoder().encode(value);
}
export function consumeCloudReplayGuards(input: {
readonly secrets: ServerSecretStore.ServerSecretStore["Service"];
readonly names: ReadonlyArray<string>;
readonly value: Uint8Array;
}) {
return Effect.forEach(
input.names,
(name) =>
input.secrets.create(name, input.value).pipe(
Effect.as(true),
Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>
ServerSecretStore.isSecretAlreadyExistsError(error)
? Effect.succeed(false)
: Effect.fail(error),
),
),
{ concurrency: input.names.length },
).pipe(Effect.map((created) => created.every(Boolean)));
}
function validateCloudMintPublicKey(
publicKey: string,
): Effect.Effect<void, CloudLinkRelayConfigInvalidError> {
const invalid = new CloudLinkRelayConfigInvalidError({ field: "cloudMintPublicKey" });
return Effect.try({
try: () => NodeCrypto.createPublicKey(publicKey.replace(/\\n/g, "\n")),
catch: () => invalid,
}).pipe(
Effect.flatMap((key) =>
key.asymmetricKeyType === "ed25519" ? Effect.void : Effect.fail(invalid),
),
);
}
function invalidRelayConfigField(
payload: RelayEnvironmentConfigRequest,
): CloudLinkRelayConfigInvalidError["field"] | null {
if (!isSecureRelayUrl(payload.relayUrl)) return "relayUrl";
if (payload.relayIssuer !== undefined && !isSecureRelayUrl(payload.relayIssuer)) {
return "relayIssuer";
}
if (payload.environmentCredential.trim().length === 0) return "environmentCredential";
if (payload.cloudUserId.trim().length === 0) return "cloudUserId";
return null;
}
function validateRelayConfigPayload(
payload: RelayEnvironmentConfigRequest,
): Effect.Effect<void, CloudLinkRelayConfigInvalidError> {
const field = invalidRelayConfigField(payload);
return field === null
? Effect.void
: Effect.fail(new CloudLinkRelayConfigInvalidError({ field }));
}
function normalizePemForSignedPayload(value: string): string {
return value.trim();
}
const decodeCloudHealthProof = Schema.decodeUnknownEffect(RelayCloudEnvironmentHealthProofPayload);
const decodeCloudMintProof = Schema.decodeUnknownEffect(RelayCloudMintCredentialProofPayload);
type ManagedTunnelRecoveryProofInput = {
readonly environmentId: RelayManagedEndpointRecoveryProofPayload["environmentId"];
readonly cloudUserId: string;
readonly relayUrl: string;
} & (
| {
readonly action: "register";
readonly tunnelId: string;
readonly origin: RelayManagedEndpointOrigin;
}
| { readonly action: "recover"; readonly origin: RelayManagedEndpointOrigin }
);
export type CloudLinkError =
| CloudLinkAccountMismatchError
| CloudLinkAuthorizationMissingError
| CloudLinkEndpointUnavailableError
| CloudLinkInternalError
| CloudLinkNotLinkedError
| CloudLinkOriginInvalidError
| CloudLinkProofRejectedError
| CloudLinkProofReplayedError
| CloudLinkRelayConfigInvalidError
| CloudLinkTunnelSupersededError;
type CloudLinkBackgroundError =
| CloudLinkEndpointUnavailableError
| CloudLinkInternalError
| CloudLinkOriginInvalidError
| RelayRequestError
| ServerSecretStore.SecretStoreError
| Schema.SchemaError
| PlatformError.PlatformError;
type ManagedTunnelRegistration =
| { readonly status: "not_linked" | "superseded" | "revoked" }
| { readonly status: "recovery_required"; readonly config: RelayManagedEndpointRuntimeConfig }
| {
readonly status: "ready";
readonly endpointRuntimeStatus: ManagedEndpointRuntime.CloudManagedEndpointRuntimeStatus;
};
export class CloudLink extends Context.Service<
CloudLink,
{
/**
* Signs the proof the relay asks for to link this environment. The request
* must reach this server directly on the loopback origin it names.
*/
readonly linkProof: (
request: RelayLinkProofRequest,
httpRequest: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<
RelayEnvironmentLinkProof,
CloudLinkOriginInvalidError | CloudLinkInternalError | EnvironmentAuth.ServerAuthInternalError
>;
readonly applyRelayConfig: (
payload: RelayEnvironmentConfigRequest,
) => Effect.Effect<
EnvironmentCloudRelayConfigResult,
| CloudLinkAccountMismatchError
| CloudLinkEndpointUnavailableError
| CloudLinkInternalError
| CloudLinkOriginInvalidError
| CloudLinkRelayConfigInvalidError
| CloudLinkTunnelSupersededError
| EnvironmentAuth.ServerAuthInternalError
| RelayRequestError
>;
readonly linkState: () => Effect.Effect<
EnvironmentCloudLinkStateResult,
CloudLinkInternalError
>;
readonly unlink: () => Effect.Effect<EnvironmentCloudRelayConfigResult, CloudLinkInternalError>;
readonly updatePreferences: (
input: EnvironmentCloudPreferencesRequest,
) => Effect.Effect<
EnvironmentCloudLinkStateResult,
CloudLinkNotLinkedError | CloudLinkInternalError
>;
readonly answerHealthRequest: (
request: RelayCloudEnvironmentHealthRequest,
) => Effect.Effect<
RelayEnvironmentHealthResponse,
| CloudLinkProofRejectedError
| CloudLinkProofReplayedError
| CloudLinkInternalError
| EnvironmentAuth.ServerAuthInternalError
>;
readonly mintCredential: (
request: RelayCloudMintCredentialRequest,
) => Effect.Effect<
RelayEnvironmentMintResponse,
| CloudLinkProofRejectedError
| CloudLinkProofReplayedError
| CloudLinkInternalError
| EnvironmentAuth.ServerAuthInternalError
>;
readonly reconcileDesiredLink: (
localOrigin: string,
) => Effect.Effect<
CliDesiredLinkMode,
| CloudLinkBackgroundError
| CloudLinkAccountMismatchError
| CloudLinkAuthorizationMissingError
| CloudLinkRelayConfigInvalidError
| EnvironmentAuth.ServerAuthInternalError
| CliTokenManager.CloudCliTokenManagerError
>;
readonly reconcileDesiredLinkIfStillDesired: (
localOrigin: string,
) => Effect.Effect<
CliDesiredLinkMode | null,
| CloudLinkBackgroundError
| CloudLinkAccountMismatchError
| CloudLinkAuthorizationMissingError
| CloudLinkRelayConfigInvalidError
| EnvironmentAuth.ServerAuthInternalError
| CliTokenManager.CloudCliTokenManagerError
>;
readonly registerManagedTunnelRecovery: (
localOrigin: string,
options?: { readonly retryRuntimeFailures?: boolean },
) => Effect.Effect<ManagedTunnelRegistration, CloudLinkBackgroundError>;
readonly recoverManagedTunnel: (
localOrigin: string,
expectedConfig?: RelayManagedEndpointRuntimeConfig,
options?: { readonly retryRuntimeFailures?: boolean },
) => Effect.Effect<boolean, CloudLinkBackgroundError>;
readonly startManagedTunnelIfOriginConfirmed: (
localOrigin: string,
options?: { readonly requireConfirmedOrigin?: boolean },
) => Effect.Effect<
boolean,
| CloudLinkEndpointUnavailableError
| CloudLinkOriginInvalidError
| ServerSecretStore.SecretStoreError
>;
readonly releaseManagedTunnelOnShutdown: () => Effect.Effect<
boolean,
| CloudLinkBackgroundError
| CliTokenManager.CloudCliTokenManagerError
| HttpClientError.HttpClientError
>;
}
>()("t3/cloud/CloudLink") {}
const make = Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
const environment = yield* ServerEnvironment.ServerEnvironment;
const endpointRuntime = yield* ManagedEndpointRuntime.CloudManagedEndpointRuntime;
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const cliTokenManager = yield* CliTokenManager.CloudCliTokenManager;
const httpClient = yield* HttpClient.HttpClient;
const httpServer = yield* HttpServer.HttpServer;
const awarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
const crypto = yield* Crypto.Crypto;
const config = yield* ServerConfig.ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const withSecrets = Effect.provideService(ServerSecretStore.ServerSecretStore, secrets);
const withRuntimeFiles = <A, E>(
effect: Effect.Effect<A, E, ServerConfig.ServerConfig | FileSystem.FileSystem | Path.Path>,
) =>
effect.pipe(
Effect.provideService(ServerConfig.ServerConfig, config),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
);
const validateLinkedCloudUser = (
cloudUserId: string,
): Effect.Effect<void, EnvironmentAuth.ServerAuthInternalError | CloudLinkAccountMismatchError> =>
secrets.get(CLOUD_LINKED_USER_ID).pipe(
Effect.mapError(
(cause) =>
new EnvironmentAuth.ServerAuthLinkedCloudAccountVerificationError({
cause,
}),
),
Effect.flatMap((existing) => {
if (Option.isNone(existing)) {
return Effect.void;
}
const existingCloudUserId = bytesToString(existing.value);
return existingCloudUserId === cloudUserId
? Effect.void
: Effect.fail(new CloudLinkAccountMismatchError({}));
}),
);
const readInstalledCloudUserId: Effect.Effect<string, EnvironmentAuth.ServerAuthInternalError> =
secrets.get(CLOUD_LINKED_USER_ID).pipe(
Effect.mapError(
(cause) =>
new EnvironmentAuth.ServerAuthLinkedCloudAccountReadError({
cause,
}),
),
Effect.flatMap((bytes) =>
Option.isSome(bytes)
? Effect.succeed(bytesToString(bytes.value))
: Effect.fail(new EnvironmentAuth.ServerAuthLinkedCloudAccountMissingError({})),
),
);
const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function* (
request: RelayLinkProofRequest,
requestUrl: string,
) {
const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
if (
!isSupportedLinkProviderKind(request) ||
!isAllowedEndpointOrigin({
origin: request.origin,
requestUrl,
})
) {
return yield* new CloudLinkOriginInvalidError({ origin: "endpoint" });
}
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { minutes: 5 });
const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
const descriptor = yield* environment.getDescriptor;
const payload = {
iss: `t3-env:${descriptor.environmentId}`,
aud: normalizeRelayIssuer(request.relayIssuer),
sub: descriptor.environmentId,
jti: yield* crypto.randomUUIDv4(),
iat: nowSeconds,
exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
challenge: request.challenge,
descriptor,
environmentId: descriptor.environmentId,
environmentPublicKey: normalizePemForSignedPayload(keyPair.publicKey),
endpoint: request.endpoint,
origin: request.origin,
scopes: linkProofScopes(request),
} satisfies RelayEnvironmentLinkProofPayload;
return yield* signRelayJwt({
privateKey: keyPair.privateKey,
typ: RELAY_LINK_PROOF_TYP,
payload,
}).pipe(
Effect.mapError(
(cause) =>
new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({
cause,
}),
),
);
});
const linkProof = Effect.fn("environment.cloud.linkProof")(
function* (request: RelayLinkProofRequest, httpRequest: HttpServerRequest.HttpServerRequest) {
const requestUrl = requestAbsoluteUrl(httpRequest);
if (requestUrl === null || hasForwardedAuthorityHeaders(httpRequest)) {
return yield* new CloudLinkOriginInvalidError({ origin: "endpoint" });
}
const proof = yield* makeCloudLinkProof(request, requestUrl);
return proof satisfies RelayEnvironmentLinkProof;
},
Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("generate-link-proof")),
Effect.catchTags({ PlatformError: internalError("generate-link-proof") }),
);
const activateManagedTunnel = Effect.fn("environment.cloud.activateManagedTunnel")(
function* (input: {
readonly config: RelayManagedEndpointRuntimeConfig;
readonly configJson: string;
readonly origin: RelayManagedEndpointOrigin;
}) {
return yield* endpointRuntime.withLinkStateLock(
Effect.gen(function* () {
const currentConfig = yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG);
if (
Option.isNone(currentConfig) ||
bytesToString(currentConfig.value) !== input.configJson
) {
return null;
}
const status = yield* endpointRuntime.applyConfig(input.config);
if (status.status !== "running") {
return yield* new CloudLinkEndpointUnavailableError({
reason: "runtime-not-started",
endpointRuntimeStatus: status,
});
}
const marker = yield* encodeConfirmedOriginJson({
config: input.config,
origin: input.origin,
});
yield* secrets.set(CLOUD_ENDPOINT_CONFIRMED_ORIGIN, stringToBytes(marker));
return status;
}),
);
},
);
const activateManagedTunnelWithRetry = (
input: {
readonly config: RelayManagedEndpointRuntimeConfig;
readonly configJson: string;
readonly origin: RelayManagedEndpointOrigin;
},
retryRuntimeFailures: boolean,
) => {
const activate = activateManagedTunnel(input);
return retryRuntimeFailures
? activate.pipe(
Effect.retry({
while: (error) =>
error._tag === "CloudLinkEndpointUnavailableError" &&
ManagedEndpointRuntime.isRetryableManagedEndpointRuntimeStatus(
error.endpointRuntimeStatus,
),
schedule: Schedule.exponential("1 second").pipe(
Schedule.modifyDelay(({ duration }) =>
Effect.succeed(Duration.min(duration, Duration.seconds(30))),
),
Schedule.jittered,
),
}),
)
: activate;
};
const startManagedTunnelIfOriginConfirmed = Effect.fn(
"environment.cloud.startManagedCloudTunnelIfOriginConfirmed",
)(function* (localOrigin: string, options?: { readonly requireConfirmedOrigin?: boolean }) {
const requireConfirmedOrigin = options?.requireConfirmedOrigin ?? true;
const parsedOrigin = yield* Effect.try({
try: () => parseManagedEndpointLocalOrigin(localOrigin),
catch: () => new CloudLinkOriginInvalidError({ origin: "local" }),
});
return yield* endpointRuntime.withLinkStateLock(
Effect.gen(function* () {
const [runtimeBytes, markerBytes] = yield* Effect.all([
secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG),
secrets.get(CLOUD_ENDPOINT_CONFIRMED_ORIGIN),
]);
if (Option.isNone(runtimeBytes)) return false;
const config = Option.getOrNull(decodeRuntimeConfig(bytesToString(runtimeBytes.value)));
if (config === null || config.providerKind !== "cloudflare_tunnel") return false;
// With the marker required, only a config the relay already confirmed on
// this port may start. Without it, startup is falling back after the
// relay stayed unreachable: an unconfirmed origin may send traffic to a
// stale port, but that beats no remote access at all.
if (requireConfirmedOrigin) {
if (Option.isNone(markerBytes)) return false;
const marker = Option.getOrNull(decodeConfirmedOrigin(bytesToString(markerBytes.value)));
if (
marker === null ||
!managedEndpointRuntimeConfigsMatch(marker.config, config) ||
marker.origin.localHttpHost !== parsedOrigin.origin.localHttpHost ||
marker.origin.localHttpPort !== parsedOrigin.origin.localHttpPort
) {
return false;
}
}
const status = yield* endpointRuntime.applyConfig(config);
if (status.status !== "running") {
return yield* new CloudLinkEndpointUnavailableError({
reason: "runtime-not-started",
endpointRuntimeStatus: status,
});
}
return true;
}),
);
});
const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(function* (
payload: RelayEnvironmentConfigRequest,
options?: {
readonly lockHeld?: boolean;
readonly confirmedOrigin?: RelayManagedEndpointOrigin;
},
) {
const apply = Effect.gen(function* () {
yield* validateRelayConfigPayload(payload);
yield* validateLinkedCloudUser(payload.cloudUserId);
yield* validateCloudMintPublicKey(payload.cloudMintPublicKey);
// Reject unsupported runtimes before touching the connector so a bad
// payload cannot stop a healthy tunnel on its way to a 503.
if (
payload.endpointRuntime !== null &&
payload.endpointRuntime.providerKind !== "cloudflare_tunnel"
) {
return yield* new CloudLinkEndpointUnavailableError({
reason: "runtime-not-started",
endpointRuntimeStatus: {
status: "unsupported",
providerKind: payload.endpointRuntime.providerKind,
},
});
}
const endpointRuntimeJson = payload.endpointRuntime
? yield* encodeEndpointRuntimeConfigJson(payload.endpointRuntime)
: null;
yield* endpointRuntime.applyConfig(null);
yield* secrets.remove(CLOUD_ENDPOINT_CONFIRMED_ORIGIN);
// The stored runtime config is what reports the link as managed and what
// startup respawns, so drop it first and store it last. A write that
// fails part-way then leaves a link that reads as not managed, and the
// next relink repairs it instead of trusting a stale tunnel config.
yield* secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG);
yield* secrets.set(RELAY_URL_SECRET, stringToBytes(payload.relayUrl));
yield* secrets.set(
RELAY_ISSUER_SECRET,
stringToBytes(payload.relayIssuer ?? payload.relayUrl),
);
yield* secrets.set(CLOUD_LINKED_USER_ID, stringToBytes(payload.cloudUserId));
yield* secrets.set(
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
stringToBytes(payload.environmentCredential),
);
yield* secrets.remove(CLOUD_LINK_REVOKED);
yield* secrets.set(CLOUD_MINT_PUBLIC_KEY, stringToBytes(payload.cloudMintPublicKey));
yield* awarenessRelay.requestCatchUp();
if (endpointRuntimeJson !== null) {
yield* secrets.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, stringToBytes(endpointRuntimeJson));
}
if (payload.endpointRuntime === null || options?.confirmedOrigin === undefined) {
return {
ok: true,
endpointRuntimeStatus: { status: "disabled" },
} satisfies EnvironmentCloudRelayConfigResult;
}
const endpointRuntimeStatus = yield* endpointRuntime.applyConfig(payload.endpointRuntime);
if (endpointRuntimeStatus.status !== "running") {
return yield* new CloudLinkEndpointUnavailableError({
reason: "runtime-not-started",
endpointRuntimeStatus,
});
}
const marker = yield* encodeConfirmedOriginJson({
config: payload.endpointRuntime,
origin: options.confirmedOrigin,
});
yield* secrets.set(CLOUD_ENDPOINT_CONFIRMED_ORIGIN, stringToBytes(marker));
return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;
});
return yield* options?.lockHeld ? apply : endpointRuntime.withLinkStateLock(apply);
});
const relayClientRequest = <A>(input: {
readonly url: string;
readonly token: string;
readonly payload: unknown;
readonly schema: Schema.Decoder<A>;
readonly timeout?: Duration.Input;
}) =>
HttpClientRequest.post(input.url).pipe(
HttpClientRequest.bearerToken(input.token),
HttpClientRequest.bodyJson(input.payload),
Effect.flatMap(httpClient.execute),
Effect.flatMap(filterRelayResponse),
Effect.flatMap(HttpClientResponse.schemaBodyJson(input.schema)),
Effect.timeout(input.timeout ?? "10 seconds"),
Effect.mapError(relayRequestError),
withRelayClientTracing,
);
const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesiredLinkWith")(
function* (localOrigin: string) {
const parsedOrigin = yield* Effect.try({
try: () => parseManagedEndpointLocalOrigin(localOrigin),
catch: () => new CloudLinkOriginInvalidError({ origin: "local" }),
});
const token = yield* cliTokenManager.getExisting.pipe(
Effect.flatMap(
Option.match({
onNone: () => Effect.fail(new CloudLinkAuthorizationMissingError({})),
onSome: Effect.succeed,
}),
),
);
const mode = yield* readCliDesiredLinkMode.pipe(withSecrets);
const managedTunnelsEnabled = mode !== "publish_only";
const relayUrl = yield* requireRelayUrl;
const challenge = yield* relayClientRequest({
url: `${relayUrl}/v1/client/environment-link-challenges`,
token: token.accessToken,
payload: {
notificationsEnabled: true,
liveActivitiesEnabled: true,
managedTunnelsEnabled,
},
schema: RelayEnvironmentLinkChallengeResponse,
});
const proof = yield* makeCloudLinkProof(
{
challenge: challenge.challenge,
relayIssuer: relayUrl,
endpoint: {
httpBaseUrl: parsedOrigin.httpBaseUrl,
wsBaseUrl: parsedOrigin.wsBaseUrl,
providerKind: managedTunnelsEnabled ? "cloudflare_tunnel" : "manual",
},
origin: parsedOrigin.origin,
},
parsedOrigin.httpBaseUrl,
);
const link = yield* relayClientRequest({
url: `${relayUrl}/v1/client/environment-links`,
token: token.accessToken,
payload: {
proof,
notificationsEnabled: true,
liveActivitiesEnabled: true,
managedTunnelsEnabled,
},
schema: RelayEnvironmentLinkResponse,
timeout: MANAGED_ENDPOINT_PROVISION_REQUEST_TIMEOUT,
});
yield* setCliDesiredCloudLink(true, mode).pipe(withSecrets);
yield* applyCloudRelayConfig(
{
relayUrl,
relayIssuer: link.relayIssuer,
cloudUserId: link.cloudUserId,
environmentCredential: link.environmentCredential,
cloudMintPublicKey: link.cloudMintPublicKey,
endpointRuntime: link.endpointRuntime,
},
{
lockHeld: true,
confirmedOrigin: parsedOrigin.origin,
},
);
return mode;
},
Effect.catchIf(ServerSecretStore.isSecretStoreError, internalError("persist-desired-link")),
);
const reconcileDesiredLink = Effect.fn("environment.cloud.reconcileDesiredLink")(function* (
localOrigin: string,
) {
return yield* endpointRuntime.withLinkStateLock(reconcileDesiredCloudLinkWith(localOrigin));
});
const reconcileDesiredLinkIfStillDesired = Effect.fn(
"environment.cloud.reconcileDesiredLinkIfStillDesired",
)(function* (localOrigin: string) {
return yield* endpointRuntime.withLinkStateLock(
Effect.gen(function* () {
if (!(yield* readCliDesiredCloudLink.pipe(withSecrets))) {
return null;
}
return yield* reconcileDesiredCloudLinkWith(localOrigin);
}),
);
});
const makeManagedTunnelRecoveryProof = Effect.fn(
"environment.cloud.makeManagedTunnelRecoveryProof",
)(function* (input: ManagedTunnelRecoveryProofInput) {
const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);
const configuredIssuer = yield* secrets.get(RELAY_ISSUER_SECRET);
const now = yield* DateTime.now;
const issuedAt = Math.floor(now.epochMilliseconds / 1_000);
const claims = {
iss: `t3-env:${input.environmentId}`,
aud: normalizeRelayIssuer(
Option.isSome(configuredIssuer) ? bytesToString(configuredIssuer.value) : input.relayUrl,
),
sub: input.environmentId,
jti: yield* crypto.randomUUIDv4(),
iat: issuedAt,
exp: issuedAt + 60,
environmentId: input.environmentId,
cloudUserId: input.cloudUserId,
};
const payload =
input.action === "register"
? {
...claims,
action: "register" as const,
tunnelId: input.tunnelId,
origin: input.origin,
}
: { ...claims, action: "recover" as const, origin: input.origin };
return yield* signRelayJwt({
privateKey: keyPair.privateKey,
typ: RELAY_MANAGED_TUNNEL_RECOVERY_TYP,
payload,
}).pipe(
Effect.mapError(
(cause) => new CloudLinkInternalError({ operation: "sign-recovery-proof", cause }),
),
);
});
/**
* Nothing stored is removed: the relay also answers 401 for a skewed clock,
* and the next accepted registration clears the mark. Returns false, without
* marking, when a relink replaced the credential while the rejected request
* was in flight.
*/
const markLinkRevoked = (credential: string, cause: RelayRequestError) =>
endpointRuntime.withLinkStateLock(
Effect.gen(function* () {
const current = yield* secrets.get(RELAY_ENVIRONMENT_CREDENTIAL_SECRET);
if (Option.isNone(current) || bytesToString(current.value) !== credential) {
return false;
}
yield* Effect.logWarning(
"T3 Connect no longer accepts this environment's link. Link it again to restore remote access.",
{ cause },
);
yield* secrets.set(CLOUD_LINK_REVOKED, stringToBytes("true"));
return true;
}),
);
const registerManagedTunnelRecovery = Effect.fn(
"environment.cloud.registerManagedCloudTunnelRecovery",
)(function* (localOrigin: string, options?: { readonly retryRuntimeFailures?: boolean }) {
const [runtimeConfig, relayUrl, cloudUserId, environmentCredential] = yield* Effect.all([
secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG),
secrets.get(RELAY_URL_SECRET),
secrets.get(CLOUD_LINKED_USER_ID),
secrets.get(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),
]);