@open-workspace/create 0.4.2 → 0.5.1

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 +302 -72
  10. package/import/directory/google.ts +159 -121
  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 +167 -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 +161 -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 +8 -8
  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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@open-workspace/create",
3
- "version": "0.4.2",
4
- "description": "Create an OpenWorkspace deployment (`bun create @open-workspace`), and import people and mail into one.",
3
+ "version": "0.5.1",
4
+ "description": "Create an OpenWorkspace deployment (`bun create @open-workspace`), and import people, teams, SSO apps and mail.",
5
5
  "homepage": "https://openworkspace.dev",
6
6
  "license": "Apache-2.0",
7
7
  "repository": {
@@ -20,11 +20,22 @@
20
20
  "setup",
21
21
  "module-templates.ts",
22
22
  "import",
23
+ "dist/backup-schema.ts",
24
+ "dist/workspace.ts",
23
25
  "README.md",
24
26
  "LICENSE"
25
27
  ],
26
28
  "type": "module",
29
+ "imports": {
30
+ "#backup-schema": "./dist/backup-schema.ts"
31
+ },
32
+ "exports": {
33
+ "./import/backup-source.ts": "./import/backup-source.ts",
34
+ "./import/cli.ts": "./import/cli.ts",
35
+ "./import/oauth.ts": "./import/oauth.ts"
36
+ },
27
37
  "scripts": {
38
+ "prepack": "mkdir -p dist && cp ../core/shared/backup-schema.ts ../core/shared/workspace.ts dist/",
28
39
  "test": "bun run test:unit",
29
40
  "test:unit": "bun test ./test/unit",
30
41
  "typecheck": "tsc -p tsconfig.json"
package/setup/alchemy.ts CHANGED
@@ -85,7 +85,7 @@ export function projectAlchemy(
85
85
  interactive: boolean;
86
86
  env?: Readonly<Record<string, string | undefined>>;
87
87
  }
88
- ): ProjectAlchemy {
88
+ ) {
89
89
  const env = childEnv(options.env ?? process.env, options);
90
90
 
91
91
  async function helper<T extends { status: string }>(
@@ -159,5 +159,5 @@ export function projectAlchemy(
159
159
  "Cloudflare",
160
160
  ]),
161
161
  deploy: () => onTerminal([process.execPath, "run", "deploy", "--yes"]),
162
- };
162
+ } satisfies ProjectAlchemy;
163
163
  }
package/setup/args.ts CHANGED
@@ -32,6 +32,7 @@ export type CreateOptions = {
32
32
  export const createUsage = `Usage: bun create @open-workspace [name] [options]
33
33
 
34
34
  Writes a project, signs in to Cloudflare with Alchemy, and deploys it.
35
+ After deployment, choose a source for directory, SSO app or mail migration.
35
36
 
36
37
  Options:
37
38
  --account <id or name> Cloudflare account to deploy to
@@ -39,7 +40,7 @@ Options:
39
40
  (default: $ALCHEMY_PROFILE, else "default")
40
41
  --mail-domains <list> Mail domains, primary first, comma-separated:
41
42
  zones in the account
42
- --hostname <host> Where the app is served (default: mail.<primary>)
43
+ --hostname <host> Where the app is served (default: workspace.<primary>)
43
44
  --ai <provider> cloudflare (default), openai, anthropic or none;
44
45
  keys come from OPENAI_API_KEY / ANTHROPIC_API_KEY
45
46
  --no-deploy Write and install the project, but don't deploy
@@ -68,9 +69,7 @@ function isAiChoice(value: string): value is AiChoice {
68
69
  }
69
70
 
70
71
  /** The options, or what's wrong with them. */
71
- export function parseCreateArgs(
72
- args: readonly string[]
73
- ): { options: CreateOptions } | { error: string } {
72
+ export function parseCreateArgs(args: readonly string[]) {
74
73
  let parsed: ReturnType<typeof parse>;
75
74
 
76
75
  try {
@@ -102,20 +101,20 @@ export function parseCreateArgs(
102
101
  return { error: "--mail-domains needs at least one domain" };
103
102
  }
104
103
 
105
- return {
106
- options: {
107
- name: positionals[0],
108
- account: values.account,
109
- profile: values.profile,
110
- mailDomains,
111
- hostname: values.hostname?.trim().toLowerCase(),
112
- ai,
113
- deploy: !values["no-deploy"],
114
- git: !values["no-git"],
115
- yes: values.yes ?? false,
116
- help: values.help ?? false,
117
- },
104
+ const createOptions: CreateOptions = {
105
+ name: positionals[0],
106
+ account: values.account,
107
+ profile: values.profile,
108
+ mailDomains,
109
+ hostname: values.hostname?.trim().toLowerCase(),
110
+ ai,
111
+ deploy: !values["no-deploy"],
112
+ git: !values["no-git"],
113
+ yes: values.yes ?? false,
114
+ help: values.help ?? false,
118
115
  };
116
+
117
+ return { options: createOptions };
119
118
  }
120
119
 
121
120
  function parse(args: readonly string[]) {
@@ -1,5 +1,4 @@
1
- // The few Cloudflare API reads create needs: the accounts a login reaches,
2
- // an account's zones, and a zone's MX records. Authenticated with the
1
+ // Cloudflare account, zone and MX operations for setup. Authenticated with the
3
2
  // credentials Alchemy resolved, so they see what the deploy will.
4
3
  import { z } from "zod";
5
4
 
@@ -10,10 +9,16 @@ export const CLOUDFLARE_API = "https://api.cloudflare.com/client/v4";
10
9
 
11
10
  export type Fetch = (url: string, init: RequestInit) => Promise<Response>;
12
11
 
12
+ type MxBatch =
13
+ | { deletes: Pick<MxRecord, "id">[] }
14
+ | { posts: (Omit<MxRecord, "id"> & { type: "MX" })[] };
15
+
13
16
  export type CloudflareApi = {
14
17
  accounts(): Promise<Account[]>;
15
18
  zones(accountId: string): Promise<Zone[]>;
16
19
  mxRecords(zoneId: string): Promise<MxRecord[]>;
20
+ addMx(zoneId: string, records: MxRecord[]): Promise<void>;
21
+ deleteMx(zoneId: string, records: MxRecord[]): Promise<void>;
17
22
  };
18
23
 
19
24
  export class CloudflareApiError extends Error {
@@ -25,9 +30,12 @@ export class CloudflareApiError extends Error {
25
30
  }
26
31
  }
27
32
 
28
- const envelopeSchema = z.object({
33
+ const statusSchema = z.object({
29
34
  success: z.boolean(),
30
35
  errors: z.array(z.object({ code: z.number(), message: z.string() })),
36
+ });
37
+
38
+ const envelopeSchema = statusSchema.extend({
31
39
  result: z.array(z.unknown()).nullable(),
32
40
  result_info: z
33
41
  .object({ page: z.number(), total_pages: z.number() })
@@ -48,23 +56,30 @@ const zoneSchema = z.object({
48
56
  status: z.string(),
49
57
  });
50
58
 
51
- const mxSchema = z.object({
59
+ export const mxSchema = z.object({
60
+ id: z.string().min(1),
52
61
  name: z.string(),
53
62
  content: z.string(),
54
- priority: z.number().optional(),
63
+ priority: z.number().default(0),
64
+ ttl: z.number().default(1),
65
+ comment: z.string().nullable().optional(),
66
+ tags: z.array(z.string()).optional(),
55
67
  });
56
68
 
57
- function headers(auth: CloudflareAuth): Record<string, string> {
58
- return auth.type === "token"
59
- ? { Authorization: `Bearer ${auth.token}` }
60
- : { "X-Auth-Key": auth.key, "X-Auth-Email": auth.email };
69
+ function headers(auth: CloudflareAuth) {
70
+ const fields: Record<string, string> =
71
+ auth.type === "token"
72
+ ? { Authorization: `Bearer ${auth.token}` }
73
+ : { "X-Auth-Key": auth.key, "X-Auth-Email": auth.email };
74
+
75
+ return fields;
61
76
  }
62
77
 
63
78
  export function cloudflareApi(
64
79
  auth: CloudflareAuth,
65
80
  fetchImpl: Fetch = fetch,
66
81
  base = CLOUDFLARE_API
67
- ): CloudflareApi {
82
+ ) {
68
83
  /** One page of a list endpoint: its items, parsed, and how many pages there are. */
69
84
  async function page<T>(path: string, item: z.ZodType<T>, number: number) {
70
85
  const url = new URL(`${base}${path}`);
@@ -109,6 +124,33 @@ export function cloudflareApi(
109
124
  return [first, ...rest].flatMap((result) => result.items);
110
125
  }
111
126
 
127
+ // Cloudflare applies a DNS batch in a single transaction within the zone.
128
+ async function batchMx(zoneId: string, changes: MxBatch) {
129
+ const response = await fetchImpl(
130
+ `${base}/zones/${encodeURIComponent(zoneId)}/dns_records/batch`,
131
+ {
132
+ method: "POST",
133
+ headers: { ...headers(auth), "content-type": "application/json" },
134
+ body: JSON.stringify(changes),
135
+ }
136
+ );
137
+
138
+ const status = statusSchema.safeParse(
139
+ await response.json().catch(() => null)
140
+ );
141
+
142
+ if (!response.ok || !status.success || !status.data.success) {
143
+ const reason = status.success
144
+ ? status.data.errors.map(({ message }) => message).join("; ")
145
+ : "";
146
+
147
+ throw new CloudflareApiError(
148
+ `Could not update MX records (HTTP ${response.status}). ${reason}`,
149
+ response.status
150
+ );
151
+ }
152
+ }
153
+
112
154
  return {
113
155
  /**
114
156
  * Accounts the login reaches. Memberships list them for a user's OAuth
@@ -140,17 +182,31 @@ export function cloudflareApi(
140
182
  );
141
183
  },
142
184
 
143
- async mxRecords(zoneId) {
144
- const records = await list(
185
+ deleteMx(zoneId, records) {
186
+ return batchMx(zoneId, { deletes: records.map(({ id }) => ({ id })) });
187
+ },
188
+
189
+ addMx(zoneId, records) {
190
+ return batchMx(zoneId, {
191
+ posts: records.map(
192
+ ({ name, content, priority, ttl, comment, tags }) => ({
193
+ type: "MX",
194
+ name,
195
+ content,
196
+ priority,
197
+ ttl,
198
+ comment,
199
+ tags,
200
+ })
201
+ ),
202
+ });
203
+ },
204
+
205
+ mxRecords(zoneId) {
206
+ return list(
145
207
  `/zones/${encodeURIComponent(zoneId)}/dns_records?type=MX&per_page=100`,
146
208
  mxSchema
147
209
  );
148
-
149
- return records.map((record) => ({
150
- name: record.name,
151
- content: record.content,
152
- priority: record.priority ?? 0,
153
- }));
154
210
  },
155
- };
211
+ } satisfies CloudflareApi;
156
212
  }
package/setup/domains.ts CHANGED
@@ -5,7 +5,15 @@ export type Account = { id: string; name: string };
5
5
 
6
6
  export type Zone = { id: string; name: string; status: string };
7
7
 
8
- export type MxRecord = { name: string; content: string; priority: number };
8
+ export type MxRecord = {
9
+ id: string;
10
+ name: string;
11
+ content: string;
12
+ priority: number;
13
+ ttl?: number;
14
+ comment?: string | null;
15
+ tags?: string[];
16
+ };
9
17
 
10
18
  const HOSTNAME =
11
19
  /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/u;
@@ -49,7 +57,7 @@ export function zoneOf(hostname: string, zones: readonly Zone[]) {
49
57
  export function hostnameProblem(hostname: string, zones: readonly Zone[]) {
50
58
  const host = normalizeDomain(hostname);
51
59
 
52
- if (!HOSTNAME.test(host)) return "Use a hostname such as mail.acme.com";
60
+ if (!HOSTNAME.test(host)) return "Use a hostname such as workspace.acme.com";
53
61
 
54
62
  if (!zoneOf(host, zones)) {
55
63
  return `${host} isn't in a zone of this account (${zones.map((zone) => zone.name).join(", ")})`;
@@ -58,9 +66,9 @@ export function hostnameProblem(hostname: string, zones: readonly Zone[]) {
58
66
  return undefined;
59
67
  }
60
68
 
61
- /** The suggested hostname: mail.<primary domain>. */
69
+ /** The suggested hostname: workspace.<primary domain>. */
62
70
  export function suggestedHostname(primary: string) {
63
- return `mail.${primary}`;
71
+ return `workspace.${primary}`;
64
72
  }
65
73
 
66
74
  /**
@@ -90,8 +98,12 @@ export function primaryFirst(domains: readonly string[], primary: string) {
90
98
  }
91
99
 
92
100
  /** MX records that send a zone's mail somewhere other than Cloudflare Email Routing. */
93
- export function foreignMx(records: readonly MxRecord[]) {
94
- return records.filter((record) => !CLOUDFLARE_MX.test(record.content));
101
+ export function foreignMx(records: readonly MxRecord[], domain: string) {
102
+ return records.filter(
103
+ (record) =>
104
+ normalizeDomain(record.name) === normalizeDomain(domain) &&
105
+ !CLOUDFLARE_MX.test(record.content)
106
+ );
95
107
  }
96
108
 
97
109
  /** "acme.com MX 10 aspmx.l.google.com", one line per record. */