@open-workspace/create 0.4.1 → 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
@@ -0,0 +1,255 @@
1
+ import { homedir } from "node:os";
2
+ import { resolve } from "node:path";
3
+
4
+ import type { Ui } from "./ui.ts";
5
+
6
+ async function field(ui: Ui, message: string, initialValue?: string) {
7
+ return (
8
+ await ui.text({
9
+ message,
10
+ initialValue,
11
+ validate: (value) =>
12
+ value.trim() && !/[\r\n]/u.test(value) && !value.includes("\u001B")
13
+ ? undefined
14
+ : "Enter a value on one line",
15
+ })
16
+ ).trim();
17
+ }
18
+
19
+ async function file(ui: Ui, message: string) {
20
+ const value = await field(ui, message);
21
+
22
+ return resolve(
23
+ value.startsWith("~/") ? resolve(homedir(), value.slice(2)) : value
24
+ );
25
+ }
26
+
27
+ /** Printed commands must survive a paste into a shell, including paths containing single quotes. */
28
+ function shellWord(value: string) {
29
+ return /^[a-zA-Z0-9_./:@%+=,-]+$/u.test(value)
30
+ ? value
31
+ : `'${value.replaceAll("'", "'\"'\"'")}'`;
32
+ }
33
+
34
+ export async function migrationGuide(ui: Ui, url: string, primary: string) {
35
+ const source = await ui.select({
36
+ message: "Bring people, single sign-on apps or mail from somewhere else?",
37
+ initialValue: "skip",
38
+ options: [
39
+ { value: "skip", label: "Skip for now" },
40
+ {
41
+ value: "entra",
42
+ label: "Microsoft 365 / Entra ID",
43
+ hint: "People, groups and SSO apps",
44
+ },
45
+ { value: "okta", label: "Okta", hint: "People, groups and SSO apps" },
46
+ {
47
+ value: "keycloak",
48
+ label: "Keycloak",
49
+ hint: "Realm export with users and clients",
50
+ },
51
+ {
52
+ value: "google",
53
+ label: "Google Workspace",
54
+ hint: "People, groups and SAML app metadata",
55
+ },
56
+ { value: "csv", label: "CSV directory", hint: "People and groups" },
57
+ {
58
+ value: "saml",
59
+ label: "SAML app metadata",
60
+ hint: "One service provider XML file",
61
+ },
62
+ { value: "fastmail", label: "Fastmail mailbox" },
63
+ { value: "imap", label: "IMAP mailbox" },
64
+ { value: "mbox", label: "Mbox or Google Takeout" },
65
+ { value: "backup", label: "OpenWorkspace backup" },
66
+ ],
67
+ });
68
+
69
+ if (source === "skip") return;
70
+ const commands: string[][] = [];
71
+
72
+ switch (source) {
73
+ case "entra": {
74
+ ui.info(
75
+ "Use an Entra public client with delegated User.Read.All, GroupMember.Read.All, Member.Read.Hidden and Application.Read.All, admin consent and public client flows enabled."
76
+ );
77
+ commands.push([
78
+ "idp",
79
+ "entra",
80
+ "--tenant",
81
+ await field(ui, "Entra directory (tenant) ID"),
82
+ "--client-id",
83
+ await field(ui, "Entra application (client) ID"),
84
+ ]);
85
+ break;
86
+ }
87
+
88
+ case "okta": {
89
+ ui.info(
90
+ "The import asks for a read-only Okta API token unless OKTA_API_TOKEN is set."
91
+ );
92
+ commands.push([
93
+ "idp",
94
+ "okta",
95
+ "--org",
96
+ await field(ui, "Okta organization URL"),
97
+ ]);
98
+ break;
99
+ }
100
+
101
+ case "google": {
102
+ const key = await file(
103
+ ui,
104
+ "Path to the Google service account or Desktop OAuth client JSON"
105
+ );
106
+
107
+ const args = ["people", "--google-credentials", key];
108
+
109
+ if (
110
+ await ui.confirm({
111
+ message: "Is this a service account key?",
112
+ initialValue: false,
113
+ })
114
+ ) {
115
+ args.push(
116
+ "--admin",
117
+ await field(
118
+ ui,
119
+ "Google super administrator email",
120
+ `admin@${primary}`
121
+ )
122
+ );
123
+ }
124
+
125
+ if (
126
+ await ui.confirm({
127
+ message:
128
+ "Import Google group posting rules and collaborative inbox settings? Requires the Groups Settings API.",
129
+ initialValue: false,
130
+ })
131
+ ) {
132
+ args.push("--group-settings");
133
+ }
134
+
135
+ commands.push(args);
136
+
137
+ if (
138
+ await ui.confirm({
139
+ message: "Include an app's SAML service provider metadata?",
140
+ initialValue: false,
141
+ })
142
+ ) {
143
+ commands.push([
144
+ "idp",
145
+ "saml",
146
+ "--file",
147
+ await file(ui, "Path to the app's service provider XML"),
148
+ ]);
149
+ }
150
+
151
+ break;
152
+ }
153
+
154
+ case "keycloak": {
155
+ commands.push([
156
+ "idp",
157
+ source,
158
+ "--file",
159
+ await file(ui, "Path to the realm export JSON including users"),
160
+ ]);
161
+ break;
162
+ }
163
+
164
+ case "csv": {
165
+ ui.info(
166
+ "CSV columns: type,name,email,groups. Use user or group rows and separate group names with semicolons."
167
+ );
168
+ commands.push([
169
+ "idp",
170
+ source,
171
+ "--file",
172
+ await file(ui, "Path to the directory CSV"),
173
+ ]);
174
+ break;
175
+ }
176
+
177
+ case "saml": {
178
+ commands.push([
179
+ "idp",
180
+ source,
181
+ "--file",
182
+ await file(ui, "Path to the app's service provider XML"),
183
+ ]);
184
+ break;
185
+ }
186
+
187
+ case "mbox": {
188
+ commands.push([
189
+ "mbox",
190
+ await file(ui, "Path to an mbox file or extracted Takeout folder"),
191
+ "--into",
192
+ await field(ui, "Destination mailbox address"),
193
+ ]);
194
+ break;
195
+ }
196
+
197
+ case "fastmail":
198
+ case "imap": {
199
+ const host =
200
+ source === "fastmail"
201
+ ? "imap.fastmail.com"
202
+ : await field(ui, "Source IMAP hostname");
203
+
204
+ const user = await field(ui, "Source IMAP username");
205
+ commands.push([
206
+ "imap",
207
+ "--host",
208
+ host,
209
+ "--user",
210
+ user,
211
+ "--into",
212
+ await field(
213
+ ui,
214
+ "Destination mailbox address",
215
+ user.includes("@") ? user : undefined
216
+ ),
217
+ ]);
218
+ break;
219
+ }
220
+
221
+ case "backup": {
222
+ commands.push([
223
+ "backup",
224
+ await file(ui, "Path to the downloaded backup snapshot folder"),
225
+ ]);
226
+ break;
227
+ }
228
+
229
+ default: {
230
+ throw new Error(`Unknown migration source: ${source}`);
231
+ }
232
+ }
233
+
234
+ ui.info(
235
+ "After creating the first administrator, preview the import, then run the import command to apply it."
236
+ );
237
+
238
+ for (const args of commands) {
239
+ const command = [
240
+ "bunx",
241
+ "@open-workspace/create",
242
+ "import",
243
+ ...args,
244
+ "--workspace",
245
+ url,
246
+ ]
247
+ .map(shellWord)
248
+ .join(" ");
249
+
250
+ ui.step("Preview");
251
+ ui.commands(`${command} --dry-run`);
252
+ ui.step("Apply after reviewing the preview");
253
+ ui.commands(command);
254
+ }
255
+ }
@@ -0,0 +1,115 @@
1
+ import { readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ import { z } from "zod";
5
+
6
+ import { projectAlchemy } from "./alchemy.ts";
7
+ import { cloudflareApi, mxSchema } from "./cloudflare-api.ts";
8
+ import type { CloudflareApi } from "./cloudflare-api.ts";
9
+ import { normalizeDomain } from "./domains.ts";
10
+ import type { MxRecord, Zone } from "./domains.ts";
11
+
12
+ const file = "previous-mx.json";
13
+
14
+ const snapshotSchema = z.object({
15
+ accountId: z.string(),
16
+ profile: z.string(),
17
+ zones: z.array(
18
+ z.object({
19
+ zone: z.object({ id: z.string(), name: z.string() }),
20
+ records: z.array(mxSchema),
21
+ })
22
+ ),
23
+ });
24
+
25
+ export function saveMx(
26
+ directory: string,
27
+ accountId: string,
28
+ profile: string,
29
+ zones: { zone: Zone; records: MxRecord[] }[]
30
+ ) {
31
+ writeFileSync(
32
+ join(directory, file),
33
+ JSON.stringify(
34
+ {
35
+ accountId,
36
+ profile,
37
+ zones: zones.filter(({ records }) => records.length),
38
+ },
39
+ null,
40
+ 2
41
+ ),
42
+ { mode: 0o600, flag: "wx" }
43
+ );
44
+ }
45
+
46
+ export function readMx(directory: string) {
47
+ return snapshotSchema.parse(
48
+ JSON.parse(readFileSync(join(directory, file), "utf-8"))
49
+ );
50
+ }
51
+
52
+ export async function restoreMx(
53
+ api: CloudflareApi,
54
+ zones: z.infer<typeof snapshotSchema>["zones"]
55
+ ) {
56
+ for (const { zone, records } of zones) {
57
+ // A partially completed install can leave some zones or records untouched.
58
+ // Restoring only missing targets also makes retrying the command safe.
59
+ // oxlint-disable-next-line no-await-in-loop -- check each zone immediately before updating its DNS
60
+ const existing = (await api.mxRecords(zone.id)).filter(
61
+ (r) => normalizeDomain(r.name) === normalizeDomain(zone.name)
62
+ );
63
+
64
+ const key = (r: MxRecord) => `${r.priority} ${normalizeDomain(r.content)}`;
65
+ const current = new Set(existing.map(key));
66
+ const missing = records.filter((r) => !current.has(key(r)));
67
+
68
+ if (!missing.length) continue;
69
+ const saved = new Set(records.map(key));
70
+
71
+ if (existing.some((r) => !saved.has(key(r)))) {
72
+ throw new Error(
73
+ `Review the current MX records for ${zone.name} before restoring the previous provider. Saved records: ${file}`
74
+ );
75
+ }
76
+
77
+ // oxlint-disable-next-line no-await-in-loop -- stop at the first zone that cannot be restored
78
+ await api.addMx(zone.id, missing);
79
+ }
80
+ }
81
+
82
+ export async function main(args: string[]) {
83
+ const usage =
84
+ "Run bunx @open-workspace/create restore-mx from the generated project directory.";
85
+
86
+ if (args.length) {
87
+ console.log(usage);
88
+
89
+ return args.length === 1 && args[0] === "--help" ? 0 : 2;
90
+ }
91
+
92
+ try {
93
+ const snapshot = readMx(process.cwd());
94
+
95
+ const credentials = await projectAlchemy(process.cwd(), {
96
+ profile: snapshot.profile,
97
+ interactive: false,
98
+ }).credentials();
99
+
100
+ if (credentials.status !== "ok") throw new Error(credentials.message);
101
+
102
+ if (credentials.accountId !== snapshot.accountId) {
103
+ throw new Error("Sign in to the Cloudflare account used during setup.");
104
+ }
105
+
106
+ await restoreMx(cloudflareApi(credentials.auth), snapshot.zones);
107
+ console.log("Previous MX records restored.");
108
+
109
+ return 0;
110
+ } catch (error) {
111
+ console.error(error instanceof Error ? error.message : String(error));
112
+
113
+ return 1;
114
+ }
115
+ }
package/setup/ui.ts CHANGED
@@ -39,6 +39,7 @@ export type Ui = {
39
39
  error(message: string): void;
40
40
  step(message: string): void;
41
41
  note(message: string, title: string): void;
42
+ commands(text: string): void;
42
43
  /** Shows `message` while `work` runs, then `done(result)`. */
43
44
  progress<T>(
44
45
  message: string,
@@ -54,7 +55,7 @@ export class Cancelled extends Error {
54
55
  }
55
56
  }
56
57
 
57
- function answered<T>(value: T | symbol): T {
58
+ function answered<T>(value: T | symbol) {
58
59
  if (p.isCancel(value)) throw new Cancelled();
59
60
 
60
61
  // SAFETY: clack resolves a prompt with its answer or its cancel symbol, ruled out above.
@@ -118,6 +119,8 @@ export const clackUi: Ui = {
118
119
  error: (message) => p.log.error(message),
119
120
  step: (message) => p.log.step(message),
120
121
  note: (message, title) => p.note(message, title),
122
+ // Unadorned shell commands can be copied even if the terminal wraps a line.
123
+ commands: (text) => console.log(text),
121
124
  async progress(message, work, done) {
122
125
  // A spinner's frames are noise in a log: without a terminal, only the outcome is printed.
123
126
  if (!process.stdout.isTTY) {
package/templates.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export type ProjectAnswers = {
2
2
  /** Directory and package name, e.g. "acme-workspace"; the Alchemy stack is named after it. */
3
3
  name: string;
4
- /** Hostname the app is served on, e.g. "mail.acme.com". */
4
+ /** Hostname the app is served on, e.g. "workspace.acme.com". */
5
5
  hostname: string;
6
6
  /** Mail domains, primary first. */
7
7
  mailDomains: string[];
@@ -14,7 +14,7 @@ export type ProjectAnswers = {
14
14
  };
15
15
 
16
16
  export const versions = {
17
- openWorkspace: "0.4.1",
17
+ openWorkspace: "0.5.0",
18
18
  alchemy: "2.0.0-beta.85",
19
19
  effect: "4.1.3",
20
20
  typescript: "7.0.2",
@@ -22,15 +22,14 @@ export const versions = {
22
22
  bun: "1.4.4",
23
23
  };
24
24
 
25
- function stackName(name: string) {
26
- return (
27
- name
28
- .split(/[^a-zA-Z0-9]+/u)
29
- .filter(Boolean)
30
- .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
31
- .join("") || "Workspace"
32
- );
33
- }
25
+ /**
26
+ * The one Alchemy stage of a deployment project, named by every script but
27
+ * `dev`. Alchemy's default, `live_$USER`, would give each person or CI
28
+ * runner that deploys the project a second, empty workspace on the same
29
+ * hostname and mail domains. (Not ALCHEMY_STAGE in `.env`: git ignores the
30
+ * file, and `alchemy dev` reads it too.)
31
+ */
32
+ export const DEPLOY_STAGE = "production";
34
33
 
35
34
  export function packageJson(answers: ProjectAnswers) {
36
35
  return `${JSON.stringify(
@@ -40,10 +39,11 @@ export function packageJson(answers: ProjectAnswers) {
40
39
  type: "module",
41
40
  packageManager: `bun@${versions.bun}`,
42
41
  scripts: {
43
- deploy: "alchemy deploy",
42
+ deploy: `alchemy deploy --stage ${DEPLOY_STAGE}`,
43
+ plan: `alchemy plan --stage ${DEPLOY_STAGE}`,
44
44
  dev: "alchemy dev",
45
- destroy: "alchemy destroy",
46
- logs: "alchemy logs --tail",
45
+ destroy: `alchemy destroy --stage ${DEPLOY_STAGE}`,
46
+ logs: `alchemy logs --tail --stage ${DEPLOY_STAGE}`,
47
47
  },
48
48
  dependencies: {
49
49
  "@open-workspace/core": versions.openWorkspace,
@@ -117,6 +117,7 @@ export function alchemyRunTs(answers: ProjectAnswers) {
117
117
  // The options sit one level deeper here, inside Effect.gen.
118
118
  const ai = aiOption(answers.ai).replaceAll("\n", "\n ");
119
119
 
120
+ // The dash also keeps new stacks distinct from the old alphanumeric names.
120
121
  return `import * as Cloudflare from "@alchemy.run/cloudflare";
121
122
  import * as Alchemy from "alchemy";
122
123
  import * as Effect from "effect/Effect";
@@ -124,7 +125,7 @@ import { OpenWorkspace, providers } from "@open-workspace/core/alchemy";
124
125
  import { Email } from "@open-workspace/email/alchemy";
125
126
 
126
127
  export default Alchemy.Stack(
127
- ${JSON.stringify(stackName(answers.name))},
128
+ ${JSON.stringify(`ow-${answers.name}`)},
128
129
  { providers: providers(), state: Cloudflare.state() },
129
130
  Effect.gen(function* () {
130
131
  // Single sign-on apps can be declared here instead of in the admin UI,
@@ -156,7 +157,7 @@ export default Alchemy.Stack(
156
157
  // \`workspace\` also holds the OIDC and SAML endpoints and certificate, for
157
158
  // wiring up other resources such as a Cloudflare Access login method
158
159
  // (https://openworkspace.dev/docs/sso). The deploy prints only the URL.
159
- return { url: workspace.url };
160
+ return workspace.url;
160
161
  }),
161
162
  );
162
163
  `;
@@ -166,7 +167,7 @@ export const tsconfigJson = `${JSON.stringify(
166
167
  {
167
168
  compilerOptions: {
168
169
  target: "ES2023",
169
- lib: ["ES2023"],
170
+ lib: ["ES2023", "ESNext.TypedArrays"],
170
171
  module: "ESNext",
171
172
  moduleResolution: "Bundler",
172
173
  strict: true,
@@ -184,6 +185,8 @@ export const tsconfigJson = `${JSON.stringify(
184
185
  export const gitignore = `node_modules
185
186
  .alchemy
186
187
  .env
188
+ openworkspace-invitations.csv
189
+ openworkspace-invitations.csv.pending
187
190
  `;
188
191
 
189
192
  function deployTarget(answers: ProjectAnswers) {
@@ -225,6 +228,11 @@ An [OpenWorkspace](https://openworkspace.dev) deployment on your Cloudflare acco
225
228
  bun run deploy
226
229
  \`\`\`
227
230
  ${deployTarget(answers)}
231
+ The workspace is Alchemy stage \`${DEPLOY_STAGE}\`, fixed in the \`deploy\`, \`plan\`,
232
+ \`destroy\` and \`logs\` scripts: whoever runs them, on any machine or in CI,
233
+ changes this one workspace. Use the scripts, not a bare \`alchemy deploy\`: that
234
+ deploys stage \`live_<your user>\`, a second, empty workspace on the same domains.
235
+
228
236
  Open https://${answers.hostname} and create the first administrator with a passkey,
229
237
  using an address on ${answers.mailDomains[0]}.
230
238
 
@@ -248,7 +256,7 @@ passkey, as on the deployed app. Mail from outside doesn't reach it.
248
256
  ## Update
249
257
 
250
258
  \`\`\`sh
251
- bun update @open-workspace/core @open-workspace/email
259
+ bun update --latest @open-workspace/core @open-workspace/email
252
260
  bun run deploy
253
261
  \`\`\`
254
262
  `;