Repository navigation
Expand file tree
/
Copy pathalchemy.run.ts
More file actions
1121 lines (1094 loc) · 42.2 KB
/
Copy pathalchemy.run.ts
File metadata and controls
1121 lines (1094 loc) · 42.2 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
import { Buffer } from "node:buffer";
import {
createECDH,
createHash,
generateKeyPairSync,
randomBytes,
} from "node:crypto";
import { readFileSync } from "node:fs";
import * as Alchemy from "alchemy";
import * as Cloudflare from "alchemy/Cloudflare";
import * as Command from "alchemy/Command";
import * as Output from "alchemy/Output";
import * as Provider from "alchemy/Provider";
import { Stack } from "alchemy/Stack";
import { Config, Effect, Layer, Option, Redacted } from "effect";
import migrationManifest from "./apps/core/migration-manifest.json" with {
type: "json",
};
import productionBindingContract from "./apps/core/production-bindings.json" with {
type: "json",
};
import { SNOOZE_SWEEP_CRON } from "./apps/core/src/notifications/snooze-cron.ts";
import { portalDomainSharesSite } from "./apps/core/src/portals/portal-site.ts";
import {
E2BProfiles,
e2bRecipeHash,
HeldSecret,
OrbContainers,
orbRecipeHash,
selfhostProviders,
} from "./deploy/selfhost/alchemy-resources.ts";
import CLOUDFLARE_ORB_PROFILES from "./packages/domain/cloudflare-orb-profiles.json" with {
type: "json",
};
import E2B_ORB_PROFILES from "./packages/domain/e2b-orb-profiles.json" with {
type: "json",
};
import { decodeGitHubAppDeploymentConfiguration } from "./packages/domain/src/source-control/github-app-configuration.ts";
import {
attachmentBucketCors,
attachmentSigningTokenProps,
} from "./scripts/attachment-deployment.mjs";
type RecordValue<T> = T extends Record<string, infer Value> ? Value : never;
type WorkloadIdentitySigningKey = Alchemy.Resource<
"Dx.WorkloadIdentitySigningKey",
Record<string, never>,
{ keyring: Redacted.Redacted<string> }
>;
const WorkloadIdentitySigningKey = Alchemy.Resource<WorkloadIdentitySigningKey>(
"Dx.WorkloadIdentitySigningKey",
);
const createWorkloadIdentitySigningKeyring = () => {
const keyPair = generateKeyPairSync("rsa", { modulusLength: 2048 });
const kid = randomBytes(12).toString("base64url");
return JSON.stringify({
version: 1,
activeKid: kid,
keys: [
{
kid,
privateKeyPkcs8: keyPair.privateKey.export({
type: "pkcs8",
format: "pem",
}),
publicJwk: {
...keyPair.publicKey.export({ format: "jwk" }),
use: "sig",
alg: "RS256",
kid,
},
},
],
});
};
const workloadIdentitySigningKeyProvider = () =>
Provider.succeed(WorkloadIdentitySigningKey, {
reconcile: ({ output }) =>
Effect.sync(() =>
output?.keyring === undefined
? { keyring: Redacted.make(createWorkloadIdentitySigningKeyring()) }
: output,
),
delete: () => Effect.void,
read: ({ output }) => Effect.succeed(output),
});
const sourceControlSchemaVersion = /^\d{4}/.exec(
migrationManifest.d1.at(-1)?.filename ?? "",
)?.[0];
if (sourceControlSchemaVersion === undefined)
throw new Error("Migration manifest has no source-control schema version.");
const defaultE2BOrbProfile = E2B_ORB_PROFILES.find(
({ id }) => id === "a1.medium",
);
if (defaultE2BOrbProfile === undefined)
throw new Error("The default E2B Orb profile is missing from the catalog.");
const defaultCloudflareOrbProfile = CLOUDFLARE_ORB_PROFILES.find(
({ id }) => id === "cf.standard-2",
);
if (defaultCloudflareOrbProfile === undefined)
throw new Error(
"The default Cloudflare Orb profile is missing from the catalog.",
);
/** What every deployed Orb size offers; see RunnerProfileCatalogConfiguration. */
const deployedOrbCapabilities = [
"git",
"environment-variables",
"internet-access",
"persistent-workspace",
"pause-resume",
] as const;
const cloudflareOrbProfiles = CLOUDFLARE_ORB_PROFILES.map((profile) => ({
...profile,
adapter: "cloudflare",
isolation: "container",
availability: "available",
capabilities: deployedOrbCapabilities,
}));
const productionWorkerBindings = <
Groups extends Record<string, Record<string, unknown>>,
>(
groups: Groups,
): Record<string, RecordValue<RecordValue<Groups>>> => {
const contract = productionBindingContract.bindings
.map(({ name, type }) => ({
name,
type,
}))
.sort((left, right) => left.name.localeCompare(right.name));
const actual = Object.entries(groups)
.flatMap(([type, values]) =>
Object.keys(values).map((name) => ({ name, type })),
)
.sort((left, right) => left.name.localeCompare(right.name));
const required = productionBindingContract.bindings
.filter((binding) => !("optional" in binding && binding.optional))
.map(({ name, type }) => ({ name, type }))
.sort((left, right) => left.name.localeCompare(right.name));
if (
productionBindingContract.version !== 1 ||
new Set(contract.map(({ name }) => name)).size !== contract.length ||
required.some(
(binding) =>
!actual.some(
(candidate) =>
candidate.name === binding.name && candidate.type === binding.type,
),
) ||
actual.some(
(binding) =>
!contract.some(
(candidate) =>
candidate.name === binding.name && candidate.type === binding.type,
),
)
)
throw new Error(
"Alchemy Worker bindings drifted from the production binding contract.",
);
return Object.fromEntries(
productionBindingContract.bindings.flatMap(({ name, type }) =>
Object.hasOwn(groups[type] ?? {}, name)
? [[name, groups[type]?.[name]]]
: [],
),
) as Record<string, RecordValue<RecordValue<Groups>>>;
};
const productionBindingByType = (type: string) => {
const matches = productionBindingContract.bindings.filter(
(binding) => binding.type === type,
);
if (matches.length !== 1)
throw new Error(`Production binding contract must contain one ${type}.`);
return matches[0];
};
const requiredHostedAuthenticationValue = <Value>(
value: Value | undefined,
): Value => {
if (value === undefined)
throw new Error("Hosted authentication resource is unavailable.");
return value;
};
const durableObjectBindingContract = () => {
const contractBindings = productionBindingContract.bindings.filter(
({ type }) => type === "durable-object",
);
const authoredWrangler = JSON.parse(
readFileSync(
new URL("./apps/core/wrangler.jsonc", import.meta.url),
"utf8",
),
) as {
durable_objects?: {
bindings?: Array<{ name: string; class_name: string }>;
};
};
const authoredBindings = authoredWrangler.durable_objects?.bindings ?? [];
const authoredContractNames = contractBindings
.filter(({ provenance }) => provenance === "authored-wrangler")
.map(({ name }) => name)
.sort();
const authoredNames = authoredBindings.map(({ name }) => name).sort();
const generatedBindings = contractBindings.filter(
({ provenance }) => provenance === "generated-flue",
);
const canonicalClasses = migrationManifest.durableObjects.flatMap(
({ newSqliteClasses }) => newSqliteClasses,
);
const authoredClasses = authoredBindings.map(({ class_name }) => class_name);
const generatedClasses = canonicalClasses.filter(
(className) => !authoredClasses.includes(className),
);
if (
JSON.stringify(authoredNames) !== JSON.stringify(authoredContractNames) ||
new Set(canonicalClasses).size !== canonicalClasses.length ||
authoredClasses.some(
(className) => !canonicalClasses.includes(className),
) ||
generatedBindings.length !== 1 ||
generatedClasses.length !== 1
)
throw new Error(
"Production Durable Object bindings do not match Wrangler and migration authorities.",
);
return [
...authoredBindings.map(({ name, class_name: className }) => ({
name,
className,
})),
{ name: generatedBindings[0].name, className: generatedClasses[0] },
];
};
export default Alchemy.Stack(
"dx-cloudflare",
{
providers: Layer.mergeAll(
Cloudflare.providers(),
Command.providers(),
workloadIdentitySigningKeyProvider(),
selfhostProviders(),
),
state: Cloudflare.state(),
},
Effect.gen(function* () {
const stack = yield* Stack;
const configuration = yield* Config.all({
environment: Config.String("DX_DEPLOYMENT_ENVIRONMENT"),
deploymentTarget: Config.String("DX_DEPLOYMENT_TARGET"),
deploymentLabel: Config.String("DX_DEPLOYMENT_LABEL"),
deploymentName: Config.option(
Config.NonEmptyString("DX_DEPLOYMENT_NAME"),
),
adminEmail: Config.option(Config.NonEmptyString("DX_ADMIN_EMAIL")),
adminPassword: Config.option(Config.Redacted("DX_ADMIN_PASSWORD")),
adminPasswordReset: Config.withDefault(
Config.Boolean("DX_ADMIN_PASSWORD_RESET"),
false,
),
integrations: Config.withDefault(
Config.String("DX_DEPLOYMENT_INTEGRATIONS"),
"",
),
origin: Config.String("DX_DEPLOYMENT_ORIGIN"),
authEmailFrom: Config.option(
Config.NonEmptyString("DX_DEPLOYMENT_AUTH_EMAIL_FROM"),
),
revision: Config.String("DX_DEPLOYMENT_REVISION"),
workerName: Config.String("DX_DEPLOYMENT_WORKER_NAME"),
databaseName: Config.String("DX_DEPLOYMENT_DATABASE_NAME"),
bucketName: Config.String("DX_DEPLOYMENT_BUCKET_NAME"),
credentialsFile: Config.String("DX_DEPLOYMENT_CREDENTIALS_FILE"),
bootstrapRepository: Config.withDefault(
Config.String("DX_DEPLOYMENT_BOOTSTRAP_REPOSITORY"),
"",
),
packageDirectory: Config.String("DX_DEPLOYMENT_PACKAGE_DIR"),
e2bTemplate: Config.String("DX_DEPLOYMENT_E2B_TEMPLATE"),
e2bTemplateBuildId: Config.String("DX_DEPLOYMENT_E2B_TEMPLATE_BUILD_ID"),
dxdChecksum: Config.String("DX_DEPLOYMENT_DXD_CHECKSUM"),
dxdReleaseUrl: Config.String("DX_DEPLOYMENT_DXD_RELEASE_URL"),
sourceShallowClone: Config.withDefault(
Config.Boolean("DX_DEPLOYMENT_SOURCE_SHALLOW_CLONE"),
true,
),
workspaceInactivityMs: Config.option(
Config.Number("DX_DEPLOYMENT_WORKSPACE_INACTIVITY_MS"),
),
turnstileTestKeys: Config.withDefault(
Config.Boolean("DX_DEPLOYMENT_TURNSTILE_TEST_KEYS"),
false,
),
// Self-host only: whether magic link needs a Turnstile widget. Hosted
// targets derive it from their sender.
turnstile: Config.option(Config.Boolean("DX_DEPLOYMENT_TURNSTILE")),
e2bApiKey: Config.option(Config.Redacted("E2B_API_KEY")),
githubApp: Config.option(Config.Redacted("DX_INTEGRATION_GITHUB_APP")),
sarvamApiKey: Config.option(Config.Redacted("SARVAM_API_KEY")),
// Where the R2 S3 credentials Core signs attachment URLs with come
// from: "token" deployments mint a bucket-scoped token; "operator"
// self-hosts (Alchemy OAuth, which cannot create tokens) hold the R2
// API token the operator created. Attachments move the same way.
attachmentSigning: Config.withDefault(
Config.Literals(
["token", "operator"] as const,
"DX_DEPLOYMENT_ATTACHMENT_SIGNING",
),
"token",
),
attachmentR2Credentials: Config.option(
Config.Redacted("DX_ATTACHMENT_R2_CREDENTIALS"),
),
cloudflareAccountId: Config.option(
Config.NonEmptyString("CLOUDFLARE_ACCOUNT_ID"),
),
exaApiKey: Config.option(Config.Redacted("EXA_API_KEY")),
// Self-host sign-in providers and admission, validated by the runner.
signIn: Config.option(Config.NonEmptyString("DX_DEPLOYMENT_SIGN_IN")),
googleClientSecret: Config.option(
Config.Redacted("DX_GOOGLE_CLIENT_SECRET"),
),
plugins: Config.withDefault(Config.String("DX_DEPLOYMENT_PLUGINS"), ""),
// Orb providers the deployment offers on its own account: e2b,
// cloudflare, both, or none (people and workspaces connect their own).
orbProviders: Config.withDefault(
Config.String("DX_DEPLOYMENT_ORB_PROVIDERS"),
"e2b",
),
orbWorkerName: Config.option(
Config.NonEmptyString("DX_DEPLOYMENT_ORB_WORKER_NAME"),
),
workloadIdentitySigningKeys: Config.option(
Config.Redacted("DX_WORKLOAD_IDENTITY_SIGNING_KEYS"),
),
bitbucketOAuth: Config.option(
Config.Redacted("DX_INTEGRATION_BITBUCKET_OAUTH"),
),
deploymentZone: Config.option(
Config.NonEmptyString("DX_DEPLOYMENT_ZONE"),
),
workersDevSubdomain: Config.option(
Config.NonEmptyString("DX_DEPLOYMENT_WORKERS_DEV_SUBDOMAIN"),
),
daemonIngressName: Config.withDefault(
Config.NonEmptyString("DX_DEPLOYMENT_DAEMON_INGRESS_NAME"),
"dx-dxd",
),
signupEnabled: Config.withDefault(
Config.Boolean("DX_SIGNUP_ENABLED"),
false,
),
githubCopilotClientId: Config.option(
Config.NonEmptyString("DX_GITHUB_COPILOT_CLIENT_ID"),
),
modelDeploymentProviders: Config.option(
Config.NonEmptyString("DX_MODEL_DEPLOYMENT_PROVIDERS"),
),
modelEndpointAllowlist: Config.option(
Config.NonEmptyString("DX_MODEL_ENDPOINT_ALLOWLIST"),
),
workersAiEnabled: Config.withDefault(
Config.Boolean("DX_MODEL_WORKERS_AI_ENABLED"),
true,
),
workerTraces: Config.withDefault(
Config.Boolean("DX_DEPLOYMENT_WORKER_TRACES"),
false,
),
// Portals: a dedicated zone (never the app's registrable domain) whose
// first-level labels `t-<uuid>-p<port>` serve guest ports. Universal
// SSL covers one wildcard level, so the domain is the zone apex.
portalDomain: Config.option(
Config.NonEmptyString("DX_DEPLOYMENT_PORTAL_DOMAIN"),
),
portalZoneId: Config.option(
Config.NonEmptyString("DX_DEPLOYMENT_PORTAL_ZONE_ID"),
),
// The deployment runner names it within the 63-character script limit.
portalWorkerName: Config.option(
Config.NonEmptyString("DX_DEPLOYMENT_PORTAL_WORKER_NAME"),
),
});
const hostedAuthentication = Option.isSome(configuration.authEmailFrom);
const signIn = Option.isSome(configuration.signIn)
? (JSON.parse(configuration.signIn.value) as {
readonly providers: ReadonlyArray<string>;
readonly admission: string;
readonly allowedEmailDomains: ReadonlyArray<string>;
readonly googleClientId?: string;
readonly termsUrl?: string;
readonly privacyUrl?: string;
})
: undefined;
// Without a recorded signIn, a sender meant magic link only.
const passwordSignIn =
signIn?.providers.includes("email-password") ?? !hostedAuthentication;
const googleSignIn = signIn?.providers.includes("google") ?? false;
const expectedEnvironment =
configuration.deploymentTarget === "branch"
? "preview"
: configuration.deploymentTarget === "staging" ||
configuration.deploymentTarget === "selfhost"
? configuration.deploymentTarget
: undefined;
if (
expectedEnvironment === undefined ||
configuration.environment !== expectedEnvironment
)
return yield* Effect.die(
"DX_DEPLOYMENT_TARGET does not match DX_DEPLOYMENT_ENVIRONMENT.",
);
const authEmailFrom = Option.getOrUndefined(configuration.authEmailFrom);
const selfhost = configuration.environment === "selfhost";
const integrations = new Set(
configuration.integrations.split(",").filter(Boolean),
);
const orbProviders = new Set(
configuration.orbProviders.trim() === "none"
? []
: configuration.orbProviders.split(",").filter(Boolean),
);
if (
(orbProviders.size === 0 &&
configuration.orbProviders.trim() !== "none") ||
[...orbProviders].some(
(provider) => provider !== "e2b" && provider !== "cloudflare",
)
)
return yield* Effect.die(
"DX_DEPLOYMENT_ORB_PROVIDERS must name e2b, cloudflare, both, or none.",
);
const e2bInstalled = orbProviders.has("e2b");
const cloudflareInstalled = orbProviders.has("cloudflare");
const e2bApiKey = !e2bInstalled
? undefined
: selfhost
? (yield* HeldSecret("E2BApiKey", {
value: Option.getOrUndefined(configuration.e2bApiKey),
})).value
: Option.isSome(configuration.e2bApiKey)
? configuration.e2bApiKey.value
: yield* Effect.die("E2B_API_KEY is required.");
const githubApp = selfhost
? integrations.has("github")
? (yield* HeldSecret("GitHubAppSecret", {
value: Option.getOrUndefined(configuration.githubApp),
})).value
: Redacted.make("{}")
: Option.isSome(configuration.githubApp)
? configuration.githubApp.value
: yield* Effect.die("DX_INTEGRATION_GITHUB_APP is required.");
const adminPassword =
selfhost && passwordSignIn
? (yield* HeldSecret("AdminPassword", {
value: Option.getOrUndefined(configuration.adminPassword),
})).value
: undefined;
const bitbucketOAuth =
selfhost && integrations.has("bitbucket")
? (yield* HeldSecret("BitbucketOAuthSecret", {
value: Option.getOrUndefined(configuration.bitbucketOAuth),
})).value
: Option.getOrUndefined(configuration.bitbucketOAuth);
// The Speech plugin's deployment-scope Sarvam key. The self-host
// integration keeps its `sarvam` name and HeldSecret ID.
const sarvamApiKey =
selfhost && integrations.has("sarvam")
? (yield* HeldSecret("SarvamApiKey", {
value: Option.getOrUndefined(configuration.sarvamApiKey),
})).value
: Option.getOrUndefined(configuration.sarvamApiKey);
const googleClientSecret = !googleSignIn
? undefined
: selfhost
? (yield* HeldSecret("GoogleClientSecret", {
value: Option.getOrUndefined(configuration.googleClientSecret),
})).value
: Option.isSome(configuration.googleClientSecret)
? configuration.googleClientSecret.value
: yield* Effect.die("DX_GOOGLE_CLIENT_SECRET is required.");
// Plugin installation is deployment scope. Hosted targets install every
// first-party plugin; self-host installs what `pnpm dx:deploy` recorded.
const installedPlugins = selfhost ? configuration.plugins : "search,speech";
const exaApiKey = selfhost
? integrations.has("exa")
? (yield* HeldSecret("ExaApiKey", {
value: Option.getOrUndefined(configuration.exaApiKey),
})).value
: undefined
: Option.getOrUndefined(configuration.exaApiKey);
const selfhostProfiles =
selfhost && e2bApiKey !== undefined
? yield* E2BProfiles("E2BProfiles", {
apiKey: e2bApiKey,
deploymentName: Option.getOrElse(
configuration.deploymentName,
() => "",
),
recipeHash: yield* Effect.promise(() => e2bRecipeHash()),
} as never)
: undefined;
// Cloudflare Containers runs in this account: the Orb Worker owns one
// container per Thread, and Core binds its namespace across scripts.
const orbContainers = !cloudflareInstalled
? undefined
: Option.isSome(configuration.orbWorkerName)
? yield* OrbContainers("OrbContainers", {
workerName: configuration.orbWorkerName.value,
recipeHash: orbRecipeHash(import.meta.dirname),
})
: yield* Effect.die(
"DX_DEPLOYMENT_ORB_WORKER_NAME is required for Cloudflare Containers.",
);
// Hosted stages run on Containers whenever they install it; a self-host
// keeps E2B first, and a deployment with no provider defaults to an E2B
// size people connect (scripts/alchemy-deployment.mjs checks the same
// rule).
const defaultOrbProfileId =
cloudflareInstalled && !(e2bInstalled && selfhost)
? defaultCloudflareOrbProfile.id
: defaultE2BOrbProfile.id;
const runnerProfileCatalog = (e2bProfiles: ReadonlyArray<unknown>) =>
JSON.stringify({
version: 1,
defaultProfileId: defaultOrbProfileId,
profiles: [
...e2bProfiles,
...(cloudflareInstalled ? cloudflareOrbProfiles : []),
],
});
if (
configuration.turnstileTestKeys &&
configuration.environment !== "preview"
)
return yield* Effect.die(
"DX_DEPLOYMENT_TURNSTILE_TEST_KEYS is restricted to previews.",
);
if (Option.isSome(configuration.workspaceInactivityMs)) {
const inactivityMs = configuration.workspaceInactivityMs.value;
if (configuration.environment !== "preview")
return yield* Effect.die(
"DX_DEPLOYMENT_WORKSPACE_INACTIVITY_MS is restricted to previews.",
);
if (
!Number.isInteger(inactivityMs) ||
inactivityMs < 60_000 ||
inactivityMs > 3_600_000
)
return yield* Effect.die(
"DX_DEPLOYMENT_WORKSPACE_INACTIVITY_MS must be an integer from 60000 through 3600000.",
);
}
if (
!selfhost &&
Redacted.value(githubApp as Redacted.Redacted<string>) !== "{}"
) {
const input = yield* Effect.try({
try: () =>
JSON.parse(Redacted.value(githubApp as Redacted.Redacted<string>)),
catch: () => new Error("Invalid GitHub App configuration JSON."),
}).pipe(Effect.orDie);
yield* decodeGitHubAppDeploymentConfiguration(
input,
configuration.origin,
configuration.environment,
).pipe(Effect.orDie);
}
const deploymentHostname = new URL(configuration.origin).hostname;
const portals = yield* Option.isNone(configuration.portalDomain) &&
Option.isNone(configuration.portalZoneId)
? Effect.succeed(undefined)
: Effect.gen(function* () {
if (
Option.isNone(configuration.portalDomain) ||
Option.isNone(configuration.portalZoneId)
)
return yield* Effect.die(
"DX_DEPLOYMENT_PORTAL_DOMAIN and DX_DEPLOYMENT_PORTAL_ZONE_ID are set together.",
);
const domain = configuration.portalDomain.value.toLowerCase();
// A separate registrable domain: same-site guest pages could set
// cookies dx reads (apps/core/src/portals/portal-site.ts).
if (
!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/.test(
domain,
) ||
portalDomainSharesSite(deploymentHostname, domain)
)
return yield* Effect.die(
"DX_DEPLOYMENT_PORTAL_DOMAIN must be a separate registrable domain from the app.",
);
if (!/^[a-f0-9]{32}$/.test(configuration.portalZoneId.value))
return yield* Effect.die(
"DX_DEPLOYMENT_PORTAL_ZONE_ID must be a Cloudflare zone ID.",
);
return { domain, zoneId: configuration.portalZoneId.value };
});
// A resumed guest's daemon reconnects through a dependency-free Worker on
// the account's workers.dev subdomain. Its isolate starts in milliseconds,
// where the Core bundle's cold start (about a second) otherwise sits on
// every wake. Without a workers.dev subdomain Core serves ingress itself.
const daemonIngressName = configuration.daemonIngressName;
const daemonIngressOrigin = Option.map(
configuration.workersDevSubdomain,
(subdomain) => `https://${daemonIngressName}.${subdomain}.workers.dev/`,
);
const database = yield* Cloudflare.D1.Database("Database", {
name: configuration.databaseName,
migrations: `apps/core/${migrationManifest.d1Directory}`,
});
// Browsers upload attachment parts and read attachments straight from
// R2 through presigned URLs, so the bucket admits this origin.
const bucket = yield* Cloudflare.R2.Bucket("Storage", {
name: configuration.bucketName,
forceDestroy: false,
cors: [attachmentBucketCors(configuration.origin)],
});
// The R2 S3 credentials Core signs attachment URLs with. A deployment
// that can create tokens mints one that can only read and write this
// stage's bucket: the token id is the access key id and the SHA-256 of
// its value is the secret, and destroying the stage deletes it. Alchemy
// OAuth cannot create tokens, so those self-hosts hold the R2 API token
// the operator created instead. Either way attachments move directly.
const attachmentSigning = yield* Effect.gen(function* () {
const accountId = Option.isSome(configuration.cloudflareAccountId)
? configuration.cloudflareAccountId.value
: yield* Effect.die(
"CLOUDFLARE_ACCOUNT_ID is required to sign attachment URLs.",
);
const endpoint = `https://${accountId}.r2.cloudflarestorage.com/${configuration.bucketName}`;
if (configuration.attachmentSigning === "operator")
return {
endpoint,
credentials: (yield* HeldSecret("AttachmentR2Credentials", {
value: Option.getOrUndefined(configuration.attachmentR2Credentials),
})).value,
};
const token = yield* Cloudflare.ApiToken.AccountApiToken(
"AttachmentSigningToken",
attachmentSigningTokenProps(accountId, configuration.bucketName),
);
return {
endpoint,
credentials: Output.map(
Output.all(token.tokenId, token.value),
([tokenId, value]) =>
Redacted.make(
JSON.stringify({
accessKeyId: tokenId,
secretAccessKey: createHash("sha256")
.update(Redacted.value(value))
.digest("hex"),
}),
),
),
};
});
// Turnstile protects magic-link requests. A self-host sender may serve
// notification email alone, which needs no widget; hosted targets always
// offer magic link with their sender.
const turnstileWanted = Option.getOrElse(
configuration.turnstile,
() => hostedAuthentication,
);
// Previews may use Cloudflare's published always-pass test keys instead of
// creating a widget, because the account caps widgets at 20.
const turnstile = !turnstileWanted
? undefined
: configuration.turnstileTestKeys
? {
sitekey: "1x00000000000000000000AA",
secret: "1x0000000000000000000000000000000AA",
}
: yield* Cloudflare.Turnstile.Widget("AccessTurnstile", {
name: `dx access · ${deploymentHostname}`,
domains: [deploymentHostname],
mode: "managed",
});
const email = hostedAuthentication
? yield* Cloudflare.Email.SendEmail("MagicLinkEmail", {
allowedSenderAddresses: [
requiredHostedAuthenticationValue(authEmailFrom),
],
})
: undefined;
const authSecret = yield* Alchemy.Random("BetterAuthSecret", {});
const encryptionSecret = yield* Alchemy.Random("ConfigEncryptionKey", {});
const workloadIdentitySigningKeys = Option.isSome(
configuration.workloadIdentitySigningKeys,
)
? configuration.workloadIdentitySigningKeys.value
: configuration.environment === "staging"
? yield* Effect.die(
"DX_WORKLOAD_IDENTITY_SIGNING_KEYS is required for staging.",
)
: (yield* WorkloadIdentitySigningKey("WorkloadIdentitySigningKey", {}))
.keyring;
// Web Push needs one stable P-256 key pair per deployment: browsers
// subscribe with its public key, so rotating it silently orphans every
// device. The random seed is the private scalar; the public point is
// derived from it, exactly as a push key generator would.
const pushVapidSeed = yield* Alchemy.Random("PushVapidKey", {});
const pushVapidKeys = Output.map(pushVapidSeed.text, (secret) => {
const scalar = Buffer.from(Redacted.value(secret), "hex");
const curve = createECDH("prime256v1");
curve.setPrivateKey(scalar);
return {
publicKey: Redacted.make(curve.getPublicKey().toString("base64url")),
privateKey: Redacted.make(scalar.toString("base64url")),
};
});
const encryptionKeyring = Output.map(encryptionSecret.text, (secret) =>
Redacted.make(
JSON.stringify({
activeVersion: 1,
keys: {
1: Buffer.from(Redacted.value(secret), "hex").toString("base64"),
},
}),
),
);
const d1Binding = productionBindingByType("d1");
const r2Binding = productionBindingByType("r2");
const aiBinding = productionBindingByType("workers-ai");
const durableObjectBindings = Object.fromEntries(
durableObjectBindingContract().map(({ name, className }) => [
name,
Cloudflare.DurableObject(name, { className }),
]),
);
const workerBindings = productionWorkerBindings({
text: {
DX_ENV: configuration.environment,
DX_DEPLOYMENT_TARGET: configuration.deploymentTarget,
DX_RUNTIME_MODE: "deployed",
...(hostedAuthentication
? {
DX_AUTH_EMAIL_FROM:
requiredHostedAuthenticationValue(authEmailFrom),
}
: {}),
...(turnstile === undefined
? {}
: { DX_TURNSTILE_SITE_KEY: turnstile.sitekey }),
DX_AUTH_URL: configuration.origin,
DX_AUTH_TRUSTED_ORIGINS: configuration.origin,
...(portals === undefined ? {} : { DX_PORTAL_DOMAIN: portals.domain }),
DX_ATTACHMENT_R2_ENDPOINT: attachmentSigning.endpoint,
...(e2bInstalled
? {
DX_E2B_TEMPLATE:
selfhostProfiles?.defaultTemplate ??
`${configuration.e2bTemplate}-${defaultE2BOrbProfile.templateSuffix}`,
DX_E2B_TEMPLATE_BUILD_ID:
selfhostProfiles?.defaultBuildId ??
configuration.e2bTemplateBuildId,
DX_E2B_TIMEOUT_MS: "300000",
}
: {}),
...(Option.isSome(configuration.workspaceInactivityMs)
? {
DX_WORKSPACE_INACTIVITY_MS: String(
configuration.workspaceInactivityMs.value,
),
}
: {}),
DX_DEPLOYMENT_REVISION: configuration.revision,
DX_DXD_PUBLIC_URL: Option.getOrElse(
daemonIngressOrigin,
() => configuration.origin,
),
DX_DXD_RELEASE_URL: configuration.dxdReleaseUrl,
DX_DXD_RELEASE_SHA256: configuration.dxdChecksum,
DX_MIGRATION_MANIFEST_VERSION: String(migrationManifest.version),
DX_RUNNER_PROFILE_CATALOG:
selfhostProfiles === undefined
? runnerProfileCatalog(
e2bInstalled
? E2B_ORB_PROFILES.map((profile) => ({
...profile,
adapter: "e2b",
template: `${configuration.e2bTemplate}-${profile.templateSuffix}`,
isolation: "sandbox",
availability: "available",
capabilities: deployedOrbCapabilities,
}))
: cloudflareInstalled
? []
: // No provider: the sizes people's own E2B teams run.
E2B_ORB_PROFILES.map((profile) => ({
...profile,
adapter: "e2b",
template: `dx-orb-${profile.templateSuffix}`,
isolation: "sandbox",
availability: "available",
capabilities: deployedOrbCapabilities,
})),
)
: Output.map(selfhostProfiles.profilesJson, (profilesJson) =>
runnerProfileCatalog(
JSON.parse(profilesJson).map(
(profile: Record<string, unknown>) => ({
...profile,
adapter: "e2b",
isolation: "sandbox",
availability: "available",
capabilities: deployedOrbCapabilities,
}),
),
),
),
DX_SOURCE_CONTROL_SCHEMA_VERSION: sourceControlSchemaVersion,
DX_SOURCE_SHALLOW_CLONE: configuration.sourceShallowClone
? "true"
: "false",
DX_MANAGED_SSH_SIGNING_ENABLED: "true",
...(installedPlugins === ""
? {}
: { DX_INSTALLED_PLUGINS: installedPlugins }),
...(configuration.signupEnabled ? { DX_SIGNUP_ENABLED: "true" } : {}),
...(signIn === undefined
? {}
: {
DX_SIGN_IN_PROVIDERS: signIn.providers.join(","),
DX_SIGN_IN_ADMISSION: signIn.admission,
...(signIn.allowedEmailDomains.length === 0
? {}
: {
DX_SIGN_IN_ALLOWED_EMAIL_DOMAINS:
signIn.allowedEmailDomains.join(","),
}),
...(signIn.googleClientId === undefined
? {}
: { DX_GOOGLE_CLIENT_ID: signIn.googleClientId }),
...(signIn.termsUrl === undefined
? {}
: { DX_TERMS_URL: signIn.termsUrl }),
...(signIn.privacyUrl === undefined
? {}
: { DX_PRIVACY_URL: signIn.privacyUrl }),
}),
...(Option.isSome(configuration.githubCopilotClientId)
? {
DX_GITHUB_COPILOT_CLIENT_ID:
configuration.githubCopilotClientId.value,
}
: {}),
...(Option.isSome(configuration.modelDeploymentProviders)
? {
DX_MODEL_DEPLOYMENT_PROVIDERS:
configuration.modelDeploymentProviders.value,
}
: {}),
...(Option.isSome(configuration.modelEndpointAllowlist)
? {
DX_MODEL_ENDPOINT_ALLOWLIST:
configuration.modelEndpointAllowlist.value,
}
: {}),
...(configuration.workersAiEnabled
? {}
: { DX_MODEL_WORKERS_AI_ENABLED: "false" }),
DX_WORKLOAD_IDENTITY_ISSUER: `${configuration.origin}/api/workload-identity`,
DX_WORKLOAD_IDENTITY_AUDIENCE_POLICIES: JSON.stringify({
version: 1,
// Portable dxd-channel baseline, not an audience allowlist. Recipients
// authorize claims; native-attestation integrations remain disabled.
policies: [],
}),
},
secret: {
BETTER_AUTH_SECRET: authSecret.text,
DX_PUSH_VAPID_PUBLIC_KEY: Output.map(
pushVapidKeys,
({ publicKey }) => publicKey,
),
DX_PUSH_VAPID_PRIVATE_KEY: Output.map(
pushVapidKeys,
({ privateKey }) => privateKey,
),
...(turnstile === undefined
? {}
: { DX_TURNSTILE_SECRET_KEY: turnstile.secret }),
DX_CONFIG_ENCRYPTION_KEYS: encryptionKeyring,
DX_ATTACHMENT_R2_CREDENTIALS: attachmentSigning.credentials,
DX_INTEGRATION_GITHUB_APP: githubApp,
DX_WORKLOAD_IDENTITY_SIGNING_KEYS: workloadIdentitySigningKeys,
...(e2bApiKey === undefined ? {} : { E2B_API_KEY: e2bApiKey }),
...(sarvamApiKey !== undefined ? { SARVAM_API_KEY: sarvamApiKey } : {}),
...(exaApiKey !== undefined ? { EXA_API_KEY: exaApiKey } : {}),
...(googleClientSecret !== undefined
? { DX_GOOGLE_CLIENT_SECRET: googleClientSecret }
: {}),
...(bitbucketOAuth !== undefined
? {
DX_INTEGRATION_BITBUCKET_OAUTH: bitbucketOAuth,
}
: {}),
},
d1: { [d1Binding.name]: database },
r2: { [r2Binding.name]: bucket },
"send-email": hostedAuthentication
? { EMAIL: requiredHostedAuthenticationValue(email) }
: {},
"workers-ai": {
[aiBinding.name]: Cloudflare.Workers.AI(aiBinding.name),
},
"durable-object": {
...durableObjectBindings,
...(orbContainers === undefined
? {}
: {
ORB_CONTAINER: Cloudflare.DurableObject("ORB_CONTAINER", {
className: "OrbContainerObject",
scriptName: orbContainers.workerName,
}),
}),
},
});
const bootstrap = yield* Command.Exec("Bootstrap", {
command: "node scripts/bootstrap-deployment.mjs",
cwd: ".",
env: {
...(selfhost && !passwordSignIn
? {
DX_BOOTSTRAP_ADMIN_EMAIL: Option.getOrElse(
configuration.adminEmail,
() => "",
),
DX_BOOTSTRAP_HOSTED_AUTH: "true",
DX_BOOTSTRAP_STAGE: stack.stage,
}
: selfhost
? {
DX_BOOTSTRAP_ADMIN_EMAIL: Option.getOrElse(
configuration.adminEmail,
() => "",
),
DX_BOOTSTRAP_ADMIN_PASSWORD: adminPassword ?? Redacted.make(""),
DX_BOOTSTRAP_ADMIN_PASSWORD_RESET:
configuration.adminPasswordReset ? "true" : "false",
DX_BOOTSTRAP_STAGE: stack.stage,
}
: {
DX_BOOTSTRAP_CREDENTIALS_FILE: configuration.credentialsFile,
DX_BOOTSTRAP_REPOSITORY: configuration.bootstrapRepository,
}),
DX_BOOTSTRAP_DATABASE_ID: database.databaseId,
DX_BOOTSTRAP_RUNNER_PROFILE_ID: defaultOrbProfileId,
},
memo: false,
timeout: "3 minutes",
});
const deployedWorkerBindings = selfhost
? {
...workerBindings,
DX_ENV: Output.map(
bootstrap.hash.input,
() => configuration.environment,
),
}
: workerBindings;
const worker = yield* Cloudflare.Worker("Worker", {
// Bootstrap admits the configured first user before exposing the Worker.
name: configuration.workerName,
main: `${configuration.packageDirectory}/worker/index.js`,
bundle: false,
compatibility: {
date: "2026-08-20",
flags: ["nodejs_compat", "global_fetch_strictly_public"],
},
version: {
tag: configuration.revision,
message: `Git ${configuration.revision.slice(0, 12)}`,
},
assets: {
directory: `${configuration.packageDirectory}/assets`,
notFoundHandling: "single-page-application",
runWorkerFirst: ["/api/*", "/v1", "/v1/*", "/healthz", "/readyz"],