Repository navigation
Expand file tree
/
Copy pathrun-alchemy-deployment.mjs
More file actions
886 lines (866 loc) · 30.2 KB
/
Copy pathrun-alchemy-deployment.mjs
File metadata and controls
886 lines (866 loc) · 30.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
import { execFileSync, spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import {
existsSync,
mkdirSync,
readFileSync,
rmSync,
writeFileSync,
} from "node:fs";
import { resolve } from "node:path";
import { ApiClient, ConnectionConfig, Template } from "e2b";
import { dxOrbTemplate } from "../deploy/e2b/template.mjs";
import {
assertDockerReady,
orbDockerEnvironment,
} from "../deploy/orb/containers.mjs";
import {
adminCredentialPath,
writeAdminCredentialFile,
} from "../deploy/selfhost/admin-credentials.mjs";
import {
ALCHEMY_CLI,
alchemyCloudflareConnected,
loadAlchemyCloudflareAuth,
runAlchemyCli,
} from "../deploy/selfhost/cloudflare-auth.mjs";
import {
downloadDxdRelease,
loadDxdRelease,
verifyDxdBytes,
} from "../deploy/selfhost/dxd-release.mjs";
import { preflightPortalZone } from "../deploy/selfhost/portals.mjs";
import e2bOrbProfiles from "../packages/domain/e2b-orb-profiles.json" with {
type: "json",
};
import {
assertCleanRevision,
assertDeploymentAccount,
assertDxdChecksum,
assertPostApplyVerification,
assertRequestedStage,
configureHostedDeploymentPolicy,
daemonIngressWorkerName,
deploymentBitbucketOAuth,
deploymentGitHubApp,
deploymentGitStatusArguments,
deploymentPortals,
deploymentSelection,
e2bApiKeyFromEnvironment,
isolatedAlchemyEnvironment,
isolatedDeploymentBuildEnvironment,
loadSelfhostConfig,
orbProvidersValue,
orbWorkerName,
parseDeploymentRevisionArgument,
parseOrbProviders,
portalWorkerName,
prepareDeploymentCredentials,
prepareDeploymentPackage,
reconcileDeploymentMigrationAliases,
resolveCloudflareDatabaseId,
resolveE2BTemplateEvidence,
resourceName,
securePrivateDeploymentState,
selfhostDeploymentShape,
selfhostStage,
writeDeploymentAlchemyProfile,
} from "./alchemy-deployment.mjs";
import { alchemyStage } from "./alchemy-stage.mjs";
import { operatorR2Credentials } from "./attachment-deployment.mjs";
import { buildTarget, GUEST_TARGET } from "./build-dxd.mjs";
import { loadMigrationManifest } from "./migration-manifest.mjs";
const workspaceRoot = resolve(import.meta.dirname, "..");
const operation = process.argv[2];
const target = process.argv[3] ?? "branch";
const hostedPolicy =
target === "selfhost"
? undefined
: JSON.parse(required("DX_PRIVATE_DEPLOYMENT_POLICY"));
if (hostedPolicy !== undefined) configureHostedDeploymentPolicy(hostedPolicy);
const selectedStagingRevision = parseDeploymentRevisionArgument(
process.argv.slice(4),
);
if (!new Set(["deploy", "destroy"]).has(operation))
throw new Error(
"Usage: run-alchemy-deployment.mjs <deploy|destroy> [branch|staging|selfhost] [revision]",
);
if (!new Set(["branch", "staging", "selfhost"]).has(target))
throw new Error("Deployment target must be branch, staging, or selfhost.");
if (
target === "selfhost" &&
operation === "deploy" &&
process.env.DX_DEPLOY_APPROVE !== "1"
)
throw new Error(
"Self-host apply requires DX_DEPLOY_APPROVE=1 after reviewing the noninteractive inputs.",
);
const deploymentBuildEnvironment = isolatedDeploymentBuildEnvironment(
process.env,
);
function required(name) {
const value = process.env[name]?.trim();
if (!value) throw new Error(`${name} is required.`);
return value;
}
const git = (...args) =>
execFileSync("git", args, {
cwd: workspaceRoot,
encoding: "utf8",
}).trim();
const gitStatus = git(
...deploymentGitStatusArguments({
environment: process.env,
target,
workspaceRoot,
}),
);
const branch = git("branch", "--show-current");
const headRevision = git("rev-parse", "HEAD");
let revision = headRevision;
if (target === "staging" && operation === "deploy") {
if (!selectedStagingRevision) revision = "";
else revision = git("rev-parse", `${selectedStagingRevision}^{commit}`);
}
assertCleanRevision({
branch,
gitStatus,
headRevision,
operation,
selectedRevision: revision,
target,
});
// An Alchemy OAuth access token lasts an hour; renew an expired one with the
// profile's refresh token before giving up.
const loadSelfhostCloudflareAuth = () => {
try {
return loadAlchemyCloudflareAuth();
} catch (error) {
if (
!alchemyCloudflareConnected() ||
!runAlchemyCli([
"profile",
"refresh",
"--profile",
"dx-selfhost",
"--provider",
"Cloudflare",
])
)
throw error;
return loadAlchemyCloudflareAuth();
}
};
const selfhostCloudflareAuth =
target === "selfhost" ? loadSelfhostCloudflareAuth() : undefined;
const selfhostConfig =
target === "selfhost"
? loadSelfhostConfig({
environment: {
...process.env,
CLOUDFLARE_ACCOUNT_ID: selfhostCloudflareAuth.accountId,
},
workspaceRoot,
})
: undefined;
const operatorEnvironment = selfhostConfig?.environment ?? process.env;
const stage =
target === "staging"
? "staging"
: target === "selfhost"
? selfhostStage(selfhostConfig.name)
: alchemyStage(branch);
assertRequestedStage({ requested: process.env.DX_DEPLOYMENT_STAGE, stage });
const githubApp =
target === "selfhost" && !selfhostConfig.integrations.includes("github")
? undefined
: deploymentGitHubApp({
target,
operation,
environment: operatorEnvironment,
});
const bitbucketOAuth =
target === "selfhost" && !selfhostConfig.integrations.includes("bitbucket")
? undefined
: deploymentBitbucketOAuth({
target,
operation,
environment: operatorEnvironment,
});
const sarvamApiKey =
target !== "selfhost" || selfhostConfig.integrations.includes("sarvam")
? operatorEnvironment.SARVAM_API_KEY?.trim()
: undefined;
// Search's deployment-scope Exa key. Hosted targets install Search and use
// the operator key when present; self-host only when the installer chose it.
const exaApiKey =
target !== "selfhost" || selfhostConfig.integrations.includes("exa")
? operatorEnvironment.EXA_API_KEY?.trim()
: undefined;
// Attachment bytes move straight between browsers, dxd, and R2 when the
// deployment can mint the bucket-scoped token Core signs URLs with. Alchemy
// OAuth cannot create tokens, so those self-hosts carry the bytes through
// Core instead. Decided here, never at runtime.
// What a self-host deployment manages follows its recorded Cloudflare auth
// and sign-in methods (see selfhostDeploymentShape).
const selfhostShape =
target === "selfhost"
? selfhostDeploymentShape({
signIn: selfhostConfig.signIn,
credentials:
selfhostCloudflareAuth.method === "alchemy-oauth"
? "alchemy-oauth"
: "api-token",
cloudflareAuth: selfhostConfig.cloudflareAuth,
})
: undefined;
const attachmentSigning = selfhostShape?.attachmentSigning ?? "token";
// The operator's R2 API token, for deployments that cannot mint one. The
// deployment holds it, so it is needed only the first time or to rotate it.
const attachmentR2Credentials =
attachmentSigning === "operator" &&
(operatorEnvironment.DX_R2_ACCESS_KEY_ID?.trim() ||
operatorEnvironment.DX_R2_SECRET_ACCESS_KEY?.trim())
? operatorR2Credentials({
accessKeyId: operatorEnvironment.DX_R2_ACCESS_KEY_ID,
secretAccessKey: operatorEnvironment.DX_R2_SECRET_ACCESS_KEY,
})
: undefined;
// Google sign-in's client secret. HeldSecret keeps it across deploys, so it
// is required only the first time google is configured.
const googleClientSecret =
target === "selfhost" && selfhostConfig.signIn.providers.includes("google")
? operatorEnvironment.DX_GOOGLE_CLIENT_SECRET?.trim()
: undefined;
// Previews and staging keep their derived magic link (plus reviewer
// password); an operator OAuth client adds Google for testing it there.
const hostedGoogleClient =
target !== "selfhost" &&
operatorEnvironment.DX_GOOGLE_CLIENT_ID?.trim() &&
operatorEnvironment.DX_GOOGLE_CLIENT_SECRET?.trim()
? {
clientId: operatorEnvironment.DX_GOOGLE_CLIENT_ID.trim(),
clientSecret: operatorEnvironment.DX_GOOGLE_CLIENT_SECRET.trim(),
}
: undefined;
const deploymentSignIn =
selfhostConfig !== undefined
? selfhostConfig.signIn
: hostedGoogleClient === undefined
? undefined
: {
providers: ["magic-link", "email-password", "google"],
admission: "waitlist",
allowedEmailDomains: [],
googleClientId: hostedGoogleClient.clientId,
};
// Orb providers: self-host records them; previews and staging read
// DX_ORB_PROVIDERS (e2b, cloudflare, both, or none; E2B by default).
const orbProviders =
target === "selfhost"
? parseOrbProviders(orbProvidersValue(selfhostConfig.orbProviders))
: parseOrbProviders(process.env.DX_ORB_PROVIDERS?.trim() || "e2b");
const e2bInstalled = orbProviders.includes("e2b");
const cloudflareInstalled = orbProviders.includes("cloudflare");
// Check Docker as the Orb image build will see it, before Cloudflare changes.
if (operation === "deploy" && cloudflareInstalled)
await assertDockerReady(
orbDockerEnvironment({
environment: process.env,
stateDirectory: resolve(workspaceRoot, ".dx/alchemy/docker-preflight"),
}),
);
const deploymentLabel =
target === "staging"
? `Staging · ${revision.slice(0, 12)}`
: target === "selfhost"
? `Self-host · ${selfhostConfig.name} · ${revision.slice(0, 12)}`
: `Branch preview · ${branch} · ${revision.slice(0, 12)}`;
if (
operation === "destroy" &&
target === "staging" &&
process.env.DX_CONFIRM_STAGING_DESTROY !== "staging"
)
throw new Error(
"Staging destroy requires DX_CONFIRM_STAGING_DESTROY=staging after exporting D1.",
);
const credentialsPath = `.dx/alchemy/${stage}/credentials.json`;
const credentialsFile = resolve(workspaceRoot, credentialsPath);
await loadMigrationManifest();
const accountId =
selfhostCloudflareAuth?.accountId ?? required("CLOUDFLARE_ACCOUNT_ID");
if (target !== "selfhost") assertDeploymentAccount(accountId);
const apiToken =
target === "selfhost"
? selfhostCloudflareAuth.headers.Authorization?.replace(/^Bearer /, "")
: required("CLOUDFLARE_API_TOKEN");
if (!apiToken)
throw new Error("Self-host deployment requires OAuth or an API token.");
const cloudflareHeaders =
target === "selfhost"
? selfhostCloudflareAuth.headers
: { Authorization: `Bearer ${apiToken}` };
const cloudflare = async (path) => {
const response = await fetch(`https://api.cloudflare.com/client/v4${path}`, {
headers: cloudflareHeaders,
});
const body = await response.json();
if (!response.ok || body.success !== true)
throw new Error(`Cloudflare preflight read failed (${response.status}).`);
return body.result;
};
// The dxd ingress Worker is served on the account's workers.dev subdomain;
// without one, Core keeps serving daemon ingress itself.
const workersDevSubdomain = await (async () => {
const response = await fetch(
`https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/subdomain`,
{ headers: cloudflareHeaders },
);
if (response.status === 404) return "";
const body = await response.json();
if (!response.ok || body.success !== true)
throw new Error(
`Cloudflare workers.dev preflight read failed (${response.status}).`,
);
const subdomain = body.result?.subdomain ?? "";
if (subdomain !== "" && !/^[a-z0-9][a-z0-9-]{0,62}$/.test(subdomain))
throw new Error("Cloudflare workers.dev subdomain is invalid.");
return subdomain;
})();
// A self-host deployment resolves its origin before selection: either a
// caller-supplied hostname under an active account zone, or the worker's
// workers.dev hostname under the account subdomain.
let selfhostDomain;
let selfhostZone;
if (target === "selfhost") {
if (selfhostConfig.domain !== undefined) {
selfhostDomain = selfhostConfig.domain;
if (selfhostConfig.zone !== undefined) {
const zones = await cloudflare(
`/zones?account.id=${accountId}&name=${selfhostConfig.zone}&status=active`,
);
if (!Array.isArray(zones) || zones.length !== 1)
throw new Error(
`Zone ${selfhostConfig.zone} is not active in this Cloudflare account.`,
);
selfhostZone = selfhostConfig.zone;
} else {
const zones = await cloudflare(
`/zones?account.id=${accountId}&status=active&per_page=100`,
);
const names = (Array.isArray(zones) ? zones : [])
.map((zone) => zone?.name)
.filter(
(name) =>
typeof name === "string" &&
(selfhostDomain === name || selfhostDomain.endsWith(`.${name}`)),
);
if (names.length !== 1)
throw new Error(
`Could not resolve an active zone for ${selfhostDomain} in this Cloudflare account.`,
);
selfhostZone = names[0];
}
} else {
const result = await cloudflare(`/accounts/${accountId}/workers/subdomain`);
const subdomain =
typeof result?.subdomain === "string" ? result.subdomain : undefined;
if (!subdomain)
throw new Error(
"This Cloudflare account has no workers.dev subdomain. Set `domain`/`zone` in deploy.selfhost.json or create the subdomain first.",
);
selfhostDomain = `${resourceName("app", stage)}.${subdomain}.workers.dev`;
}
}
const selection = deploymentSelection({
branch,
stage,
target,
selfhost:
target === "selfhost"
? {
name: selfhostConfig.name,
accountId,
domain: selfhostDomain,
zone: selfhostZone,
}
: undefined,
});
// Portals: hosted targets take the domain and zone ID together; a self-host
// records its domain and resolves the zone in its account. Before planning,
// the zone must be the domain's active apex in this account and the
// credential must hold Zone Read, DNS Edit, and Workers Routes Edit on it.
const portalSettings = deploymentPortals({
domain:
target === "selfhost"
? selfhostConfig.portalDomain
: process.env.DX_DEPLOYMENT_PORTAL_DOMAIN,
zoneId: process.env.DX_DEPLOYMENT_PORTAL_ZONE_ID,
appDomain: selection.domain,
zoneIdOptional: target === "selfhost",
});
const portals =
portalSettings === undefined
? undefined
: await (async () => {
const preflight = await preflightPortalZone({
auth: selfhostCloudflareAuth ?? {
accountId,
headers: cloudflareHeaders,
method: "api-token",
},
portalDomain: portalSettings.domain,
zoneId: portalSettings.zoneId,
});
if (!preflight.editConfirmed)
console.log(
`Portal zone ${portalSettings.domain}: Zone Read, DNS, and Workers Routes are readable; this token cannot read its own policies, so Edit is confirmed at apply.`,
);
return { domain: portalSettings.domain, zoneId: preflight.zoneId };
})();
let dxdBinary;
let dxdChecksum = "0".repeat(64);
let dxdReleaseUrl = "https://destroy.invalid/dxd";
if (operation === "deploy") {
if (
process.env.DX_DXD_RELEASE_URL?.trim() ||
process.env.DX_DXD_RELEASE_SHA256?.trim()
)
throw new Error(
"Deployments package dxd from the selected clean revision; external dxd release settings are not accepted.",
);
if (selfhostConfig?.dxdBinary !== undefined) {
dxdBinary = resolve(workspaceRoot, selfhostConfig.dxdBinary);
if (!existsSync(dxdBinary))
throw new Error(`dxd binary not found: ${selfhostConfig.dxdBinary}`);
} else if (target === "selfhost") {
const release = loadDxdRelease(workspaceRoot);
const bytes = await downloadDxdRelease(release, {
githubToken: process.env.DX_DXD_GITHUB_TOKEN,
});
verifyDxdBytes(bytes, release);
const releaseDirectory = resolve(
workspaceRoot,
`.dx/alchemy/${stage}/dxd-release`,
);
mkdirSync(releaseDirectory, { recursive: true, mode: 0o700 });
dxdBinary = resolve(releaseDirectory, release.asset);
writeFileSync(dxdBinary, bytes, { mode: 0o700 });
} else {
// The same build path as the published release asset: a static musl
// binary linked through zig (scripts/build-dxd.mjs), from any host.
const targetDirectory = resolve(
workspaceRoot,
`.dx/alchemy/${stage}/dxd-target`,
);
rmSync(targetDirectory, { recursive: true, force: true });
dxdBinary = buildTarget(GUEST_TARGET, {
targetDirectory,
environment: deploymentBuildEnvironment,
}).binary;
}
dxdChecksum = createHash("sha256")
.update(readFileSync(dxdBinary))
.digest("hex");
dxdReleaseUrl = `https://${selection.domain}/dxd`;
}
const authEmailFrom =
target === "selfhost"
? selfhostConfig.authEmailFrom
: operation === "deploy"
? hostedPolicy.authEmailFrom
: "destroy@invalid.example";
const packageDirectory = `.dx/alchemy/${stage}/package`;
prepareDeploymentPackage({
operation,
buildPackage: () => {
const result = spawnSync(
process.execPath,
[
"scripts/build-production-package.mjs",
"--output",
packageDirectory,
"--stage",
stage,
"--deployment-label",
deploymentLabel,
"--revision",
revision,
"--target",
target,
"--dxd-sha256",
dxdChecksum,
"--dxd-binary",
dxdBinary,
],
{
cwd: workspaceRoot,
env: deploymentBuildEnvironment,
stdio: "inherit",
},
);
if (result.error) throw result.error;
if (result.status !== 0)
throw new Error(
"Hermetic production-package build or smoke failed before planning.",
);
},
});
securePrivateDeploymentState(resolve(workspaceRoot, ".dx", "alchemy", stage));
const [account, zones, databases] = await Promise.all([
cloudflare(`/accounts/${accountId}`),
target === "selfhost" && authEmailFrom === undefined
? Promise.resolve([{ name: selection.zone ?? "workers.dev" }])
: cloudflare(
`/zones?account.id=${accountId}&name=${selection.zone}&status=active`,
),
cloudflare(
`/accounts/${accountId}/d1/database?name=${encodeURIComponent(selection.databaseName)}&per_page=100`,
),
]);
if (account.id !== accountId || !Array.isArray(zones) || zones.length !== 1)
throw new Error(
target === "selfhost"
? "The Cloudflare account was not found."
: "The exact dx Cloudflare account and zone were not found.",
);
const databaseId = resolveCloudflareDatabaseId(
databases,
selection.databaseName,
);
if (operation === "deploy" && target !== "selfhost")
prepareDeploymentCredentials({
credentialsFile,
databaseId,
environment: operatorEnvironment,
stage,
target,
});
if (databaseId !== undefined) {
await reconcileDeploymentMigrationAliases({
operation,
target,
query: async (sql) => {
const response = await fetch(
`https://api.cloudflare.com/client/v4/accounts/${accountId}/d1/database/${databaseId}/query`,
{
method: "POST",
headers: {
...cloudflareHeaders,
"content-type": "application/json",
},
body: JSON.stringify({ sql }),
},
);
const body = await response.json();
if (!response.ok || body.success !== true)
throw new Error(
`Cloudflare D1 migration preflight failed (${response.status}).`,
);
return body.result?.[0]?.results ?? [];
},
});
}
let e2bApiKey = "destroy-does-not-select-e2b";
let workloadIdentitySigningKeys;
let templateEvidence = {
name: "destroy-does-not-select-e2b",
buildId: "destroy-does-not-select-e2b",
};
const profileTemplateName = (template, templateSuffix) =>
`${template}-${templateSuffix}`;
const buildE2BOrbTemplates = async (templateEvidence, apiKey) => {
const baseTemplate = `${templateEvidence.name}:${templateEvidence.buildId}`;
for (const profile of e2bOrbProfiles) {
await Template.build(
dxOrbTemplate(baseTemplate),
profileTemplateName(templateEvidence.name, profile.templateSuffix),
{
apiKey,
cpuCount: profile.resources.cpuCores,
memoryMB: profile.resources.memoryMb,
},
);
}
};
if (target === "staging" && operation === "destroy")
workloadIdentitySigningKeys = JSON.stringify({
version: 1,
activeKid: "destroy01",
keys: [],
});
if (operation === "deploy" && !e2bInstalled) {
e2bApiKey = "";
templateEvidence = { name: "not-installed", buildId: "not-installed" };
if (target === "staging")
workloadIdentitySigningKeys = required("DX_WORKLOAD_IDENTITY_SIGNING_KEYS");
assertDxdChecksum(dxdChecksum);
} else if (operation === "deploy") {
e2bApiKey =
target === "selfhost"
? process.env.E2B_API_KEY?.trim() || ""
: e2bApiKeyFromEnvironment(process.env);
if (target !== "selfhost" && !e2bApiKey)
throw new Error("E2B_API_KEY (or DX_E2B_API_KEY) is required.");
if (target === "staging")
workloadIdentitySigningKeys = required("DX_WORKLOAD_IDENTITY_SIGNING_KEYS");
assertDxdChecksum(dxdChecksum);
const e2bTemplate =
target === "selfhost"
? "alchemy-held-selfhost-template"
: required("DX_E2B_TEMPLATE");
if (!e2bTemplate)
throw new Error(
target === "selfhost"
? "e2bTemplate is required in deploy.selfhost.json (or DX_E2B_TEMPLATE)."
: "DX_E2B_TEMPLATE is required.",
);
templateEvidence =
target === "selfhost"
? {
name: e2bTemplate,
buildId: "alchemy-held-selfhost-build",
}
: await resolveE2BTemplateEvidence(e2bTemplate, async () => {
const config = new ConnectionConfig({ apiKey: e2bApiKey });
const response = await new ApiClient(config).api.GET("/templates");
if (!response.data)
throw new Error(
`E2B template preflight read failed (${response.response.status}).`,
);
return response.data;
});
if (target !== "selfhost")
await buildE2BOrbTemplates(templateEvidence, e2bApiKey);
}
console.log(`Cloudflare account: ${account.name}`);
console.log(`Git revision: ${revision}`);
console.log(`Deployment target: ${target}`);
console.log(`Alchemy stage: ${stage}`);
console.log(`Worker: ${selection.workerName}`);
console.log(`URL: https://${selection.domain}`);
console.log(`Orb providers: ${orbProviders.join(", ")}`);
console.log(
`Portals: ${portals === undefined ? "off" : `https://t-<thread>-p<port>.${portals.domain} (${portalWorkerName(stage)})`}`,
);
console.log(
`Attachments: direct to R2 (${attachmentSigning === "token" ? "bucket-scoped signing token" : "operator's R2 API token"})`,
);
if (operation === "deploy" && e2bInstalled)
console.log(
`E2B template: ${templateEvidence.name} (${templateEvidence.buildId})`,
);
const authHome =
target === "selfhost" && selfhostCloudflareAuth.method === "alchemy-oauth"
? process.env.HOME
: resolve(workspaceRoot, `.dx/alchemy/${stage}/auth-home`);
if (target !== "selfhost" || selfhostCloudflareAuth.method !== "alchemy-oauth")
writeDeploymentAlchemyProfile(authHome);
const applyStartedFile = resolve(
workspaceRoot,
`.dx/alchemy/${stage}/apply-started`,
);
rmSync(applyStartedFile, { force: true });
const environment = {
...isolatedAlchemyEnvironment(process.env, {
accountId,
apiToken,
authHome,
profile:
target === "selfhost" && selfhostCloudflareAuth.method === "alchemy-oauth"
? "dx-selfhost"
: "dx-deployment",
}),
// Alchemy reads only environment credentials in CI, so an OAuth profile
// deploys outside CI mode.
CI: selfhostCloudflareAuth?.method === "alchemy-oauth" ? "false" : "1",
...(e2bApiKey ? { E2B_API_KEY: e2bApiKey } : {}),
...(githubApp === undefined ? {} : { DX_INTEGRATION_GITHUB_APP: githubApp }),
...(bitbucketOAuth === undefined
? {}
: { DX_INTEGRATION_BITBUCKET_OAUTH: bitbucketOAuth }),
...(sarvamApiKey ? { SARVAM_API_KEY: sarvamApiKey } : {}),
...(exaApiKey ? { EXA_API_KEY: exaApiKey } : {}),
...(attachmentR2Credentials === undefined
? {}
: { DX_ATTACHMENT_R2_CREDENTIALS: attachmentR2Credentials }),
...((googleClientSecret ?? hostedGoogleClient?.clientSecret)
? {
DX_GOOGLE_CLIENT_SECRET:
googleClientSecret ?? hostedGoogleClient?.clientSecret,
}
: {}),
...(deploymentSignIn !== undefined
? { DX_DEPLOYMENT_SIGN_IN: JSON.stringify(deploymentSignIn) }
: {}),
...(process.env.DX_ADMIN_PASSWORD
? { DX_ADMIN_PASSWORD: process.env.DX_ADMIN_PASSWORD }
: {}),
...(workloadIdentitySigningKeys === undefined
? {}
: { DX_WORKLOAD_IDENTITY_SIGNING_KEYS: workloadIdentitySigningKeys }),
DX_ALCHEMY_APPLY_STARTED_FILE: applyStartedFile,
DX_ALCHEMY_OPERATION: operation,
DX_DEPLOYMENT_BRANCH: branch,
DX_DEPLOYMENT_LABEL: deploymentLabel,
...(authEmailFrom === undefined
? {}
: { DX_DEPLOYMENT_AUTH_EMAIL_FROM: authEmailFrom }),
DX_DEPLOYMENT_ENVIRONMENT:
target === "selfhost"
? "selfhost"
: target === "staging"
? "staging"
: "preview",
DX_DEPLOYMENT_DOMAIN: selection.domain,
DX_DEPLOYMENT_ZONE: selection.zone ?? "",
DX_DEPLOYMENT_WORKERS_DEV_SUBDOMAIN: workersDevSubdomain,
...(portals === undefined
? {}
: {
DX_DEPLOYMENT_PORTAL_DOMAIN: portals.domain,
DX_DEPLOYMENT_PORTAL_ZONE_ID: portals.zoneId,
DX_DEPLOYMENT_PORTAL_WORKER_NAME: portalWorkerName(stage),
}),
DX_DEPLOYMENT_DAEMON_INGRESS_NAME: daemonIngressWorkerName(stage),
DX_DEPLOYMENT_NAME: selfhostConfig?.name ?? "",
...(selfhostConfig !== undefined
? { DX_ADMIN_EMAIL: selfhostConfig.environment.DX_ADMIN_EMAIL }
: {}),
...(selfhostConfig !== undefined
? { DX_DEPLOYMENT_INTEGRATIONS: selfhostConfig.integrations.join(",") }
: {}),
...(selfhostConfig !== undefined
? { DX_DEPLOYMENT_PLUGINS: (selfhostConfig.plugins ?? []).join(",") }
: {}),
...(process.env.DX_ADMIN_PASSWORD_RESET === "true"
? { DX_ADMIN_PASSWORD_RESET: "true" }
: {}),
...(selfhostConfig?.allowSignup ? { DX_SIGNUP_ENABLED: "true" } : {}),
...(selfhostConfig?.githubCopilotClientId !== undefined
? { DX_GITHUB_COPILOT_CLIENT_ID: selfhostConfig.githubCopilotClientId }
: {}),
...(selfhostConfig?.modelDeploymentProviders !== undefined
? {
DX_MODEL_DEPLOYMENT_PROVIDERS: selfhostConfig.modelDeploymentProviders,
}
: {}),
...(selfhostConfig?.modelEndpointAllowlist !== undefined
? {
DX_MODEL_ENDPOINT_ALLOWLIST: selfhostConfig.modelEndpointAllowlist,
}
: {}),
...(selfhostConfig !== undefined
? {
DX_MODEL_WORKERS_AI_ENABLED: selfhostConfig.workersAi
? "true"
: "false",
}
: {}),
// Self-host config is authoritative; previews inherit the operator's env.
...(selfhostConfig !== undefined
? {
DX_DEPLOYMENT_WORKER_TRACES:
selfhostConfig.workerTraces === true ? "true" : "false",
}
: {}),
DX_DEPLOYMENT_PACKAGE_DIR: packageDirectory,
DX_DEPLOYMENT_ORIGIN: `https://${selection.domain}`,
DX_DEPLOYMENT_REVISION: revision,
DX_DEPLOYMENT_WORKER_NAME: selection.workerName,
DX_DEPLOYMENT_DATABASE_NAME: selection.databaseName,
DX_DEPLOYMENT_DATABASE_ID: databaseId ?? "",
DX_DEPLOYMENT_BUCKET_NAME: selection.bucketName,
DX_DEPLOYMENT_CREDENTIALS_FILE: credentialsPath,
DX_DEPLOYMENT_BOOTSTRAP_REPOSITORY:
target === "selfhost"
? ""
: JSON.stringify(hostedPolicy.bootstrapRepository),
DX_DEPLOYMENT_ORB_PROVIDERS: orbProvidersValue(orbProviders),
DX_DEPLOYMENT_ATTACHMENT_SIGNING: attachmentSigning,
...(selfhostShape === undefined
? {}
: { DX_DEPLOYMENT_TURNSTILE: String(selfhostShape.turnstile) }),
DX_DEPLOYMENT_ORB_WORKER_NAME: orbWorkerName(stage),
DX_DEPLOYMENT_E2B_TEMPLATE: templateEvidence.name,
DX_DEPLOYMENT_E2B_TEMPLATE_BUILD_ID: templateEvidence.buildId,
DX_DEPLOYMENT_DXD_CHECKSUM: dxdChecksum,
DX_DEPLOYMENT_DXD_RELEASE_URL: dxdReleaseUrl,
DX_DEPLOYMENT_STAGE: stage,
DX_DEPLOYMENT_TARGET: target,
};
const result =
target === "selfhost"
? spawnSync(
process.execPath,
[ALCHEMY_CLI, operation, "alchemy.run.ts", "--stage", stage, "--yes"],
{
cwd: workspaceRoot,
env: environment,
stdio: "inherit",
},
)
: spawnSync(process.execPath, ["scripts/execute-guarded-alchemy.mjs"], {
cwd: workspaceRoot,
env: environment,
stdio: "inherit",
});
if (result.error) throw result.error;
if (result.status !== 0) {
if (target !== "selfhost" && existsSync(applyStartedFile))
throw new Error(
"Alchemy stopped after exact-plan validation and apply began; the stage outcome may be uncertain. Inspect the recorded stage before any retry or cleanup.",
);
throw new Error(
target === "selfhost"
? "Alchemy self-host deployment failed. Inspect its output and recorded stage before retrying."
: "Alchemy stopped before provider writes began.",
);
}
if (operation === "deploy") {
const verification = spawnSync(
process.execPath,
[
target === "selfhost"
? "deploy/selfhost/verify-deployment.mjs"
: "scripts/verify-alchemy-preview.mjs",
],
{
cwd: workspaceRoot,
env: {
DX_PREVIEW_URL: `https://${selection.domain}`,
DX_PREVIEW_DEPLOYMENT_LABEL: deploymentLabel,
DX_PREVIEW_DXD_SHA256: dxdChecksum,
},
stdio: "inherit",
timeout: 180_000,
},
);
assertPostApplyVerification(verification);
if (target === "selfhost") {
const credentials = adminCredentialPath(workspaceRoot);
if (process.env.DX_ADMIN_PASSWORD)
writeAdminCredentialFile({
path: credentials,
url: `https://${selection.domain}`,
email: selfhostConfig.adminEmail,
password: process.env.DX_ADMIN_PASSWORD,
});
console.log("\nSelf-host administrator");
console.log(`URL: https://${selection.domain}`);
console.log(`Login email: ${selfhostConfig.adminEmail}`);
if (selfhostConfig.signIn.providers.includes("email-password")) {
console.log(
`Credential file: ${credentials}${existsSync(credentials) ? "" : " (not present on this machine)"}`,
);
console.log("Reset password: pnpm dx:deploy -- --reset-admin");
}
console.log(`Sign-in: ${selfhostConfig.signIn.providers.join(", ")}`);
if (selfhostConfig.signIn.providers.includes("google"))
console.log(
`Google redirect URI: https://${selection.domain}/api/auth/callback/google`,
);
}
}
rmSync(applyStartedFile, { force: true });
if (operation === "destroy") rmSync(credentialsFile, { force: true });