@open-workspace/create 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +9 -5
  2. package/dist/backup-schema.ts +110 -0
  3. package/dist/workspace.ts +162 -0
  4. package/import/backup-snapshot.ts +254 -0
  5. package/import/backup-source.ts +270 -0
  6. package/import/cli.ts +134 -90
  7. package/import/concurrency.ts +34 -37
  8. package/import/csv.ts +1 -1
  9. package/import/directory/command.ts +293 -72
  10. package/import/directory/google.ts +158 -120
  11. package/import/directory/invitation-file.ts +108 -0
  12. package/import/directory/plan.ts +314 -38
  13. package/import/directory/read.ts +55 -0
  14. package/import/gmail.ts +9 -12
  15. package/import/headers.ts +1 -1
  16. package/import/idp/apps.ts +244 -0
  17. package/import/idp/command.ts +161 -0
  18. package/import/idp/csv.ts +70 -0
  19. package/import/idp/entra.ts +297 -0
  20. package/import/idp/keycloak.ts +250 -0
  21. package/import/idp/model.ts +108 -0
  22. package/import/idp/okta.ts +159 -0
  23. package/import/idp/pages.ts +65 -0
  24. package/import/imap-command.ts +42 -18
  25. package/import/imap-source.ts +245 -220
  26. package/import/invariant.ts +1 -1
  27. package/import/loopback.ts +136 -0
  28. package/import/mbox-source.ts +106 -55
  29. package/import/mbox.ts +1 -1
  30. package/import/oauth.ts +234 -138
  31. package/import/preview.ts +48 -0
  32. package/import/uploader.ts +169 -115
  33. package/import/workspace.ts +78 -15
  34. package/index.ts +3 -0
  35. package/module-templates.ts +9 -12
  36. package/module.ts +1 -5
  37. package/package.json +13 -2
  38. package/setup/alchemy.ts +2 -2
  39. package/setup/args.ts +16 -17
  40. package/setup/cloudflare-api.ts +75 -19
  41. package/setup/domains.ts +18 -6
  42. package/setup/flow.ts +217 -58
  43. package/setup/migration-guide.ts +255 -0
  44. package/setup/mx-recovery.ts +115 -0
  45. package/setup/ui.ts +4 -1
  46. package/templates.ts +26 -18
package/setup/flow.ts CHANGED
@@ -2,9 +2,12 @@
2
2
  // Cloudflare with the project's Alchemy, picks the account, the mail domains
3
3
  // and the hostname from what that login can see, and deploys.
4
4
  import {
5
+ chmodSync,
5
6
  existsSync,
6
- mkdirSync,
7
+ mkdtempSync,
7
8
  readdirSync,
9
+ renameSync,
10
+ rmdirSync,
8
11
  rmSync,
9
12
  writeFileSync,
10
13
  } from "node:fs";
@@ -34,6 +37,8 @@ import {
34
37
  zonesNamed,
35
38
  } from "./domains.ts";
36
39
  import type { Account, MxRecord, Zone } from "./domains.ts";
40
+ import { migrationGuide } from "./migration-guide.ts";
41
+ import { saveMx } from "./mx-recovery.ts";
37
42
  import { Cancelled } from "./ui.ts";
38
43
  import type { Ui } from "./ui.ts";
39
44
 
@@ -83,9 +88,8 @@ type Connection = {
83
88
  export async function runCreate(options: CreateOptions, deps: CreateDeps) {
84
89
  const { ui } = deps;
85
90
 
86
- let project:
87
- | { directory: string; created: boolean; written: boolean }
88
- | undefined;
91
+ let staging: string | undefined;
92
+ let written = false;
89
93
 
90
94
  ui.intro("OpenWorkspace");
91
95
 
@@ -97,16 +101,17 @@ export async function runCreate(options: CreateOptions, deps: CreateDeps) {
97
101
  throw new Stop(`${directory} is not empty.`);
98
102
  }
99
103
 
100
- project = { directory, created: !existsSync(directory), written: false };
104
+ // Work in a private sibling so cancellation can only remove our own files.
105
+ staging = mkdtempSync(join(deps.cwd, `.${name}-`));
101
106
 
102
- await install(name, directory, deps);
107
+ await install(name, staging, deps);
103
108
 
104
- const connection = await connect(directory, options, deps);
109
+ const connection = await connect(staging, options, deps);
105
110
 
106
- const { account, alchemy, credentials } = await bindAccount(
111
+ const { account, credentials } = await bindAccount(
107
112
  connection,
108
113
  name,
109
- directory,
114
+ staging,
110
115
  options,
111
116
  deps
112
117
  );
@@ -135,6 +140,7 @@ export async function runCreate(options: CreateOptions, deps: CreateDeps) {
135
140
  api,
136
141
  options.mailDomains,
137
142
  [],
143
+ options.deploy,
138
144
  deps
139
145
  );
140
146
 
@@ -165,8 +171,19 @@ export async function runCreate(options: CreateOptions, deps: CreateDeps) {
165
171
  },
166
172
  };
167
173
 
168
- writeProject(directory, answers, ai.key, pinnedProfile);
169
- project.written = true;
174
+ writeProject(staging, answers, ai.key, pinnedProfile);
175
+
176
+ if (existsSync(directory)) {
177
+ if (readdirSync(directory).length) {
178
+ throw new Stop(`${directory} is not empty.`);
179
+ }
180
+
181
+ rmdirSync(directory);
182
+ }
183
+
184
+ renameSync(staging, directory);
185
+ staging = undefined;
186
+ written = true;
170
187
  ui.success(`Wrote ${name}/alchemy.run.ts and ${name}/.env`);
171
188
 
172
189
  if (options.git) {
@@ -183,20 +200,28 @@ export async function runCreate(options: CreateOptions, deps: CreateDeps) {
183
200
  }
184
201
  }
185
202
 
203
+ const alchemy = deps.alchemy(directory, credentials.profile);
204
+
186
205
  return await deploy(
187
- { name, hostname, account, primary: mail.domains[0] ?? "", alchemy },
206
+ {
207
+ name,
208
+ hostname,
209
+ account,
210
+ primary: mail.domains[0] ?? "",
211
+ alchemy,
212
+ profile: credentials.profile,
213
+ },
188
214
  {
189
215
  mxBlocked: mail.mxBlocked,
216
+ removeMx: mail.removeMx,
190
217
  missingKey: ai.key && !ai.key.value ? ai.key.name : undefined,
191
218
  },
192
219
  options,
193
220
  deps
194
221
  );
195
222
  } catch (failure) {
196
- if (project && !project.written) discard(project);
197
-
198
223
  if (failure instanceof Cancelled) {
199
- ui.cancel(project?.written ? "Stopped." : "Nothing was created.");
224
+ ui.cancel(written ? "Stopped." : "Nothing was created.");
200
225
 
201
226
  return 1;
202
227
  }
@@ -206,25 +231,14 @@ export async function runCreate(options: CreateOptions, deps: CreateDeps) {
206
231
 
207
232
  if (failure.next) ui.info(failure.next);
208
233
 
209
- ui.cancel(project?.written ? "Stopped." : "Nothing was created.");
234
+ ui.cancel(written ? "Stopped." : "Nothing was created.");
210
235
 
211
236
  return 1;
212
237
  }
213
238
 
214
239
  throw failure;
215
- }
216
- }
217
-
218
- /** Removes what this run put in the project's directory, before the project was complete. */
219
- function discard(project: { directory: string; created: boolean }) {
220
- if (project.created) {
221
- rmSync(project.directory, { recursive: true, force: true });
222
-
223
- return;
224
- }
225
-
226
- for (const entry of readdirSync(project.directory)) {
227
- rmSync(join(project.directory, entry), { recursive: true, force: true });
240
+ } finally {
241
+ if (staging) rmSync(staging, { recursive: true, force: true });
228
242
  }
229
243
  }
230
244
 
@@ -261,7 +275,6 @@ function projectName(options: CreateOptions, deps: CreateDeps) {
261
275
  async function install(name: string, directory: string, deps: CreateDeps) {
262
276
  const answers = { name, hostname: "", mailDomains: [], ai: "none" as const };
263
277
 
264
- mkdirSync(directory, { recursive: true });
265
278
  writeFileSync(join(directory, "package.json"), packageJson(answers));
266
279
  writeFileSync(join(directory, "tsconfig.json"), tsconfigJson);
267
280
  writeFileSync(join(directory, ".gitignore"), gitignore);
@@ -292,7 +305,7 @@ async function connect(
292
305
  directory: string,
293
306
  options: CreateOptions,
294
307
  deps: CreateDeps
295
- ): Promise<Connection> {
308
+ ) {
296
309
  const { ui } = deps;
297
310
  const alchemy = deps.alchemy(directory, options.profile);
298
311
 
@@ -497,11 +510,7 @@ async function bindAccount(
497
510
  directory: string,
498
511
  options: CreateOptions,
499
512
  deps: CreateDeps
500
- ): Promise<{
501
- account: Account;
502
- alchemy: ProjectAlchemy;
503
- credentials: SignedIn;
504
- }> {
513
+ ) {
505
514
  const { ui } = deps;
506
515
  const account = await chooseAccount(connection, options, deps);
507
516
  const { alchemy, credentials } = connection;
@@ -548,8 +557,13 @@ async function bindAccount(
548
557
  initialValue: true,
549
558
  });
550
559
 
551
- // Declined: choose the account again.
552
- if (!proceed) return bindAccount(connection, name, directory, options, deps);
560
+ if (!proceed) {
561
+ if (options.account || connection.accounts.length === 1) {
562
+ throw new Cancelled();
563
+ }
564
+
565
+ return bindAccount(connection, name, directory, options, deps);
566
+ }
553
567
 
554
568
  const alchemyForProject = deps.alchemy(directory, fresh);
555
569
  const signedIn = await signIn(alchemyForProject, fresh, deps);
@@ -642,10 +656,18 @@ async function chooseMailDomains(
642
656
  api: CloudflareApi,
643
657
  requested: string[] | undefined,
644
658
  previous: string[],
659
+ deploying: boolean,
645
660
  deps: CreateDeps
646
- ): Promise<{ domains: string[]; mxBlocked: boolean }> {
661
+ ) {
647
662
  const chosen = await pickMailZones(zones, requested, previous, deps);
648
- const outcome = await settleMx(chosen, zones.length > 1, api, deps);
663
+
664
+ const outcome = await settleMx(
665
+ chosen,
666
+ zones.length > 1,
667
+ deploying,
668
+ api,
669
+ deps
670
+ );
649
671
 
650
672
  if (outcome === "back") {
651
673
  return chooseMailDomains(
@@ -653,6 +675,7 @@ async function chooseMailDomains(
653
675
  api,
654
676
  undefined,
655
677
  chosen.map((zone) => zone.name),
678
+ deploying,
656
679
  deps
657
680
  );
658
681
  }
@@ -660,6 +683,11 @@ async function chooseMailDomains(
660
683
  return {
661
684
  domains: chosen.map((zone) => zone.name),
662
685
  mxBlocked: outcome === "blocked",
686
+ removeMx:
687
+ outcome === "remove"
688
+ ? (backup: BeforeMxDelete) =>
689
+ removeConflictingMx(chosen, api, deps.ui, backup)
690
+ : undefined,
663
691
  };
664
692
  }
665
693
 
@@ -667,9 +695,10 @@ async function chooseMailDomains(
667
695
  async function settleMx(
668
696
  chosen: Zone[],
669
697
  canGoBack: boolean,
698
+ deploying: boolean,
670
699
  api: CloudflareApi,
671
700
  deps: CreateDeps
672
- ): Promise<"clear" | "blocked" | "back"> {
701
+ ) {
673
702
  const { ui } = deps;
674
703
  const verdict = await checkMx(chosen, api, deps);
675
704
 
@@ -680,10 +709,8 @@ async function settleMx(
680
709
  "Another mail provider's MX records are in:",
681
710
  ...verdict.flatMap((entry) => describeMx(entry.records)),
682
711
  "",
683
- "Email Routing adds Cloudflare's own MX records and can't start while these",
684
- "are there, so the deploy would fail. Remove them under DNS → Records in the",
685
- "Cloudflare dashboard (mail stops reaching the old provider), or leave the",
686
- "domain out for now.",
712
+ "Cloudflare Email Routing needs these records removed before deployment.",
713
+ "Removing them stops mail delivery to the old provider.",
687
714
  ].join("\n")
688
715
  );
689
716
 
@@ -692,6 +719,9 @@ async function settleMx(
692
719
  const next = await ui.select({
693
720
  message: "What next?",
694
721
  options: [
722
+ ...(deploying
723
+ ? [{ value: "remove", label: "Remove these MX records when deploying" }]
724
+ : []),
695
725
  { value: "recheck", label: "I removed them: check again" },
696
726
  ...(canGoBack
697
727
  ? [{ value: "back", label: "Choose other mail domains" }]
@@ -704,11 +734,67 @@ async function settleMx(
704
734
  ],
705
735
  });
706
736
 
707
- if (next === "recheck") return settleMx(chosen, canGoBack, api, deps);
737
+ if (next === "recheck") {
738
+ return settleMx(chosen, canGoBack, deploying, api, deps);
739
+ }
740
+
741
+ if (next === "remove") return "remove";
708
742
 
709
743
  return next === "back" ? "back" : "blocked";
710
744
  }
711
745
 
746
+ type BeforeMxDelete = (pending: { zone: Zone; records: MxRecord[] }[]) => void;
747
+
748
+ /** Re-read immediately before asking: the displayed record IDs are the only ones we delete. */
749
+ async function removeConflictingMx(
750
+ zones: Zone[],
751
+ api: CloudflareApi,
752
+ ui: Ui,
753
+ beforeDelete: BeforeMxDelete
754
+ ) {
755
+ const read = () =>
756
+ Promise.all(
757
+ zones.map(async (zone) => ({
758
+ zone,
759
+ records: foreignMx(await api.mxRecords(zone.id), zone.name),
760
+ }))
761
+ );
762
+
763
+ const pending = await read();
764
+ const lines = pending.flatMap((entry) => describeMx(entry.records));
765
+
766
+ if (!lines.length) return true;
767
+ ui.note(lines.join("\n"), "MX records to remove");
768
+
769
+ if (
770
+ !(await ui.confirm({
771
+ message:
772
+ "Delete these MX records now? Mail will stop reaching the old provider.",
773
+ initialValue: false,
774
+ }))
775
+ ) {
776
+ return false;
777
+ }
778
+
779
+ beforeDelete(pending);
780
+
781
+ for (const { zone, records } of pending) {
782
+ if (records.length) {
783
+ // oxlint-disable-next-line no-await-in-loop -- report completed zones and stop on the first failed deletion
784
+ await api.deleteMx(zone.id, records);
785
+ ui.success(`Removed ${records.length} MX record(s) from ${zone.name}`);
786
+ }
787
+ }
788
+
789
+ if ((await read()).some((entry) => entry.records.length)) {
790
+ throw new Error(
791
+ "Conflicting MX records are still present. Check DNS before retrying."
792
+ );
793
+ }
794
+
795
+ return true;
796
+ }
797
+
712
798
  async function pickMailZones(
713
799
  zones: Zone[],
714
800
  requested: string[] | undefined,
@@ -783,7 +869,10 @@ async function checkMx(zones: Zone[], api: CloudflareApi, deps: CreateDeps) {
783
869
  Promise.all(
784
870
  zones.map(async (zone) => {
785
871
  try {
786
- return { zone, records: foreignMx(await api.mxRecords(zone.id)) };
872
+ return {
873
+ zone,
874
+ records: foreignMx(await api.mxRecords(zone.id), zone.name),
875
+ };
787
876
  } catch (failure) {
788
877
  return {
789
878
  zone,
@@ -797,7 +886,9 @@ async function checkMx(zones: Zone[], api: CloudflareApi, deps: CreateDeps) {
797
886
  (checked) =>
798
887
  checked.some((entry) => entry.records.length > 0)
799
888
  ? "Found another mail provider's MX records"
800
- : "No other mail provider's MX records"
889
+ : checked.some((entry) => entry.unreadable)
890
+ ? "Could not verify all MX records"
891
+ : "No other mail provider's MX records"
801
892
  );
802
893
 
803
894
  for (const entry of results) {
@@ -903,12 +994,17 @@ function writeProject(
903
994
  "tsconfig.json": tsconfigJson,
904
995
  ".gitignore": gitignore,
905
996
  "README.md": readme(answers),
906
- ".env": envFile({ aiKey, alchemyProfile }),
907
997
  } satisfies Record<string, string>;
908
998
 
909
999
  for (const [file, content] of Object.entries(files)) {
910
1000
  writeFileSync(join(directory, file), content);
911
1001
  }
1002
+
1003
+ // It may hold the AI provider's key: for its owner only, like every
1004
+ // secret the CLI writes (one already there keeps no wider mode).
1005
+ const env = join(directory, ".env");
1006
+ writeFileSync(env, envFile({ aiKey, alchemyProfile }), { mode: 0o600 });
1007
+ chmodSync(env, 0o600);
912
1008
  }
913
1009
 
914
1010
  async function deploy(
@@ -917,9 +1013,14 @@ async function deploy(
917
1013
  hostname: string;
918
1014
  account: Account;
919
1015
  primary: string;
1016
+ profile: string;
920
1017
  alchemy: ProjectAlchemy;
921
1018
  },
922
- blockers: { mxBlocked: boolean; missingKey: string | undefined },
1019
+ blockers: {
1020
+ mxBlocked: boolean;
1021
+ removeMx?: (backup: BeforeMxDelete) => Promise<boolean>;
1022
+ missingKey: string | undefined;
1023
+ },
923
1024
  options: CreateOptions,
924
1025
  deps: CreateDeps
925
1026
  ) {
@@ -929,7 +1030,7 @@ async function deploy(
929
1030
  const firstAdmin = `create the first administrator with a passkey, on an address at ${target.primary}`;
930
1031
 
931
1032
  const before = [
932
- ...(blockers.mxBlocked
1033
+ ...(blockers.mxBlocked || (blockers.removeMx && blockers.missingKey)
933
1034
  ? ["Remove the other mail provider's MX records from the mail domains."]
934
1035
  : []),
935
1036
  ...(blockers.missingKey ? [`Add ${blockers.missingKey} to .env.`] : []),
@@ -937,7 +1038,7 @@ async function deploy(
937
1038
 
938
1039
  const migrating = () =>
939
1040
  ui.note(
940
- "bunx @open-workspace/create import --help # bring people and mail over from Google Workspace, IMAP or mbox",
1041
+ "bunx @open-workspace/create import --help # bring people, teams, SSO apps and mail into the workspace",
941
1042
  "Migrating?"
942
1043
  );
943
1044
 
@@ -949,7 +1050,7 @@ async function deploy(
949
1050
  migrating();
950
1051
  ui.outro(`Then open ${url} and ${firstAdmin}.`);
951
1052
 
952
- return 0;
1053
+ return options.deploy && !deps.interactive ? 1 : 0;
953
1054
  }
954
1055
 
955
1056
  const now =
@@ -960,19 +1061,61 @@ async function deploy(
960
1061
  }));
961
1062
 
962
1063
  if (!now) {
963
- ui.note(retry, "Deploy when you're ready");
1064
+ ui.note(
1065
+ blockers.removeMx
1066
+ ? `Remove the conflicting MX records before deploying.\n\n${retry}`
1067
+ : retry,
1068
+ "Deploy when you're ready"
1069
+ );
964
1070
  migrating();
965
1071
  ui.outro(`Then open ${url} and ${firstAdmin}.`);
966
1072
 
967
1073
  return 0;
968
1074
  }
969
1075
 
1076
+ let recovery = "";
1077
+
1078
+ function savePreviousMx(pending: Parameters<BeforeMxDelete>[0]) {
1079
+ saveMx(
1080
+ join(deps.cwd, target.name),
1081
+ target.account.id,
1082
+ target.profile,
1083
+ pending
1084
+ );
1085
+ recovery = `cd ${target.name} && bunx @open-workspace/create restore-mx`;
1086
+ ui.note(recovery, "Restore previous MX records if deployment fails");
1087
+ }
1088
+
1089
+ if (blockers.removeMx) {
1090
+ try {
1091
+ if (!(await blockers.removeMx(savePreviousMx))) {
1092
+ ui.note(retry, "Deploy after switching your MX records");
1093
+ ui.outro("Project saved.");
1094
+
1095
+ return 0;
1096
+ }
1097
+ } catch (error) {
1098
+ ui.error(error instanceof Error ? error.message : String(error));
1099
+
1100
+ if (recovery) ui.note(recovery, "Restore previous MX records");
1101
+ ui.note(retry, "Check your DNS records before retrying");
1102
+
1103
+ return 1;
1104
+ }
1105
+ }
1106
+
970
1107
  ui.step(
971
1108
  "Deploying with Alchemy (bun run deploy). The first deploy takes a few minutes."
972
1109
  );
973
1110
 
974
- if (!(await target.alchemy.deploy())) {
975
- ui.error("The deploy failed; Alchemy printed why above.");
1111
+ try {
1112
+ if (!(await target.alchemy.deploy())) {
1113
+ throw new Error("The deploy failed. Alchemy printed why above.");
1114
+ }
1115
+ } catch (error) {
1116
+ ui.error(error instanceof Error ? error.message : String(error));
1117
+
1118
+ if (recovery) ui.note(recovery, "Restore previous MX records");
976
1119
  ui.note(retry, "Fix it, then deploy again");
977
1120
  ui.outro(`Then open ${url} and ${firstAdmin}.`);
978
1121
 
@@ -980,8 +1123,24 @@ async function deploy(
980
1123
  }
981
1124
 
982
1125
  ui.success(`Deployed to ${target.account.name}.`);
983
- migrating();
984
- ui.outro(`Open ${url} and ${firstAdmin}.`);
1126
+ ui.note(
1127
+ `Open ${url}
1128
+ Create the first administrator with an address at ${target.primary} and register a passkey.
1129
+ Then invite your team in Administration → People.`,
1130
+ "Get started"
1131
+ );
1132
+
1133
+ if (deps.interactive) {
1134
+ try {
1135
+ await migrationGuide(ui, url, target.primary);
1136
+ } catch (error) {
1137
+ if (!(error instanceof Cancelled)) throw error;
1138
+ }
1139
+ } else {
1140
+ ui.info("Migration guide: https://openworkspace.dev/docs/migration");
1141
+ }
1142
+
1143
+ ui.outro(`Workspace: ${url}`);
985
1144
 
986
1145
  return 0;
987
1146
  }