@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/import/csv.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Minimal RFC 4180 CSV: quoted fields with "" escapes, header row handled by the caller. */
2
- export function parseCsv(text: string): string[][] {
2
+ export function parseCsv(text: string) {
3
3
  const rows: string[][] = [];
4
4
  let row: string[] = [];
5
5
  let field = "";
@@ -1,36 +1,46 @@
1
- import { readFileSync, writeFileSync } from "node:fs";
1
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
2
 
3
3
  import { z } from "zod";
4
4
 
5
5
  import { parseCliArgs } from "../args.ts";
6
6
  import { commonOptions, connect, UsageError } from "../cli.ts";
7
7
  import type { CliDeps } from "../cli.ts";
8
- import { toCsv } from "../csv.ts";
9
8
  import { openInBrowser } from "../oauth.ts";
10
9
  import { DIRECTORY_SCOPES } from "../protocol.ts";
10
+ import {
11
+ failureKind,
12
+ isSignInFailure,
13
+ sendWithRetry,
14
+ WorkspaceError,
15
+ } from "../workspace.ts";
11
16
  import type { Workspace } from "../workspace.ts";
12
17
  import { googleAccessToken, readGoogleDirectory } from "./google.ts";
18
+ import { invitationFile } from "./invitation-file.ts";
13
19
  import {
14
20
  describePlan,
15
21
  directorySchema,
16
22
  planDirectory,
17
23
  workspaceStateSchema,
18
24
  } from "./plan.ts";
19
- import type { Action, Directory, Plan } from "./plan.ts";
25
+ import type { Action, Directory, Plan, WorkspaceState } from "./plan.ts";
20
26
 
21
27
  const HELP = `bunx @open-workspace/create import people --google-credentials <file.json> [--admin admin@acme.com] --workspace https://mail.acme.com
22
28
 
23
29
  Reads users, aliases and groups from Google Workspace (Admin SDK Directory API)
24
- and creates members with personal mailboxes (aliases as more mailboxes), and
30
+ and creates members with personal mailboxes (aliases deliver to the primary mailbox), and
25
31
  teams with their group addresses as mailing lists or shared inboxes. Writes
26
32
  each new member's invitation link to a CSV.
27
33
 
34
+ A one-time migration, not a sync: running it again only finishes an
35
+ interrupted run. What exists is left alone; people a team it made is missing
36
+ are added (never anyone disabled here). Later changes in Google don't carry over.
37
+
28
38
  --google-credentials <file> Your service account key (domain-wide delegation; pass --admin)
29
39
  or your own Desktop app OAuth client (you sign in as an administrator)
30
40
  --admin <email> The super administrator a service account acts as
31
41
  --customer <id> The Google Workspace customer ID to read (default my_customer:
32
42
  the administrator's own organization)
33
- --group-settings Also read who may post to each group and which are collaborative inboxes
43
+ --group-settings Read group posting, moderation, send-as and collaborative inbox settings
34
44
  (needs the apps.groups.settings scope)
35
45
  --groups <list|inbox> What groups that are not collaborative inboxes become (default list)
36
46
  --include-suspended Also import suspended users
@@ -39,8 +49,7 @@ each new member's invitation link to a CSV.
39
49
  --invites <file.csv> Where invitation links go (default openworkspace-invitations.csv)
40
50
  --dry-run Print the plan and change nothing`;
41
51
 
42
- export type ApplyResult = {
43
- invitations: string[][];
52
+ type ApplyResult = {
44
53
  done: number;
45
54
  failed: { action: string; error: string }[];
46
55
  };
@@ -59,39 +68,173 @@ const createdTeamSchema = z.object({ teamId: z.string() });
59
68
  type ApplyContext = {
60
69
  workspace: Workspace;
61
70
  userIds: Map<string, string>;
62
- teamIds: Map<string, string>;
63
- invitations: string[][];
71
+ failedTeams: Set<string>;
72
+ aliasTargets?: Map<string, WorkspaceState["mailboxes"][number]>;
73
+ invites?: ReturnType<typeof invitationFile>;
64
74
  };
65
75
 
76
+ function mailboxesByAddress(mailboxes: WorkspaceState["mailboxes"]) {
77
+ return new Map(mailboxes.map((box) => [box.address.toLowerCase(), box]));
78
+ }
79
+
80
+ /** The most members the admin API takes in one team request. */
81
+ const TEAM_MEMBERS_PER_REQUEST = 500;
82
+
83
+ /** A group's members in slices the admin API takes, the first one never empty. */
84
+ function memberSlices<T>(members: T[]) {
85
+ const slices: T[][] = [];
86
+
87
+ for (
88
+ let start = 0;
89
+ start < members.length;
90
+ start += TEAM_MEMBERS_PER_REQUEST
91
+ ) {
92
+ slices.push(members.slice(start, start + TEAM_MEMBERS_PER_REQUEST));
93
+ }
94
+
95
+ return slices;
96
+ }
97
+
98
+ /** Resolve the planned memberships after invitations have supplied their user IDs. */
99
+ function teamMembers(
100
+ action: Extract<Action, { memberEmails: string[] }>,
101
+ userIds: Map<string, string>
102
+ ) {
103
+ return action.memberEmails.map((email) => {
104
+ const userId = userIds.get(email);
105
+
106
+ if (!userId) throw new Error(`Team member ${email} was not imported`);
107
+
108
+ return { userId, canSend: action.canSend };
109
+ });
110
+ }
111
+
112
+ /**
113
+ * Adds members to a team a slice at a time, each request tried again while
114
+ * it may pass; a slice that still fails leaves the team short, and the next
115
+ * run's plan adds who is missing.
116
+ */
117
+ async function addTeamMembers(
118
+ workspace: Workspace,
119
+ teamId: string,
120
+ slices: { userId: string; canSend: boolean }[][]
121
+ ) {
122
+ for (const added of slices) {
123
+ // oxlint-disable-next-line eslint/no-await-in-loop -- one request at a time adds a big group's members in order, each within the API's limit
124
+ await sendWithRetry(() =>
125
+ workspace.call(`/api/admin/teams/${teamId}`, {
126
+ method: "PATCH",
127
+ body: { members: { added, removed: [] } },
128
+ })
129
+ );
130
+ }
131
+ }
132
+
133
+ /**
134
+ * A new invitation link for the person under `email`, if they are here and
135
+ * still invited (their invitation was saved, its answer lost), else null.
136
+ */
137
+ async function savedInvitationLink(workspace: Workspace, email: string) {
138
+ const state = await workspace.json("/api/admin/state", workspaceStateSchema);
139
+
140
+ const person = state.users.find(
141
+ (user) => user.personalEmail?.toLowerCase() === email
142
+ );
143
+
144
+ if (person?.status !== "invited") return null;
145
+
146
+ const { accessLink } = await sendWithRetry(() =>
147
+ workspace.json(
148
+ `/api/admin/users/${encodeURIComponent(person.id)}/access-link`,
149
+ invitationSchema,
150
+ { method: "POST" }
151
+ )
152
+ );
153
+
154
+ return accessLink;
155
+ }
156
+
66
157
  async function applyAction(action: Action, context: ApplyContext) {
67
- const { workspace, userIds, teamIds } = context;
158
+ const { workspace, userIds } = context;
159
+
160
+ if (
161
+ "teamId" in action &&
162
+ action.teamId &&
163
+ context.failedTeams.has(action.teamId)
164
+ ) {
165
+ throw new Error("Team import is incomplete");
166
+ }
68
167
 
69
168
  switch (action.kind) {
70
169
  case "invite": {
71
- const { accessLink } = await workspace.json(
72
- "/api/admin/invitations",
73
- invitationSchema,
74
- {
75
- method: "POST",
76
- body: { name: action.name, email: action.email },
170
+ const { invites } = context;
171
+
172
+ if (!invites) throw new Error("Invitation file was not opened");
173
+ context.aliasTargets = undefined;
174
+ invites.begin(action.name, action.email);
175
+ let accessLink: z.infer<typeof invitationSchema>["accessLink"];
176
+
177
+ try {
178
+ ({ accessLink } = await sendWithRetry(() =>
179
+ workspace.json("/api/admin/invitations", invitationSchema, {
180
+ method: "POST",
181
+ body: { name: action.name, email: action.email },
182
+ })
183
+ ));
184
+ } catch (error) {
185
+ if (failureKind(error) === "fatal") {
186
+ invites.clear();
187
+ throw error;
77
188
  }
78
- );
189
+
190
+ // The invitation may be saved with its answer lost (the request
191
+ // tried again then finds the address taken): someone here under
192
+ // the address, still invited, gets a new link in its place.
193
+ // A failed lookup clears the marker too, or every later invitation
194
+ // in this run would find it; a rerun asks again.
195
+ let saved: Awaited<ReturnType<typeof savedInvitationLink>>;
196
+
197
+ try {
198
+ saved = await savedInvitationLink(workspace, action.email);
199
+ } catch (lookupError) {
200
+ invites.clear();
201
+ throw lookupError;
202
+ }
203
+
204
+ if (!saved) {
205
+ invites.clear();
206
+ throw error;
207
+ }
208
+
209
+ accessLink = saved;
210
+ }
79
211
 
80
212
  userIds.set(action.email, accessLink.userId);
81
- context.invitations.push([
82
- action.name,
83
- action.email,
84
- accessLink.url,
85
- accessLink.expiresAt,
86
- ]);
213
+ invites.finish(action.name, action.email, accessLink);
87
214
  break;
88
215
  }
89
216
 
90
217
  case "alias": {
91
- const ownerUserId = userIds.get(action.ownerEmail);
218
+ if (!context.aliasTargets) {
219
+ const state = await workspace.json(
220
+ "/api/admin/state",
221
+ workspaceStateSchema
222
+ );
92
223
 
93
- if (!ownerUserId) {
94
- throw new Error(`${action.ownerEmail} is not in the workspace`);
224
+ context.aliasTargets = mailboxesByAddress(state.mailboxes);
225
+ }
226
+
227
+ const target = context.aliasTargets.get(action.target);
228
+ const ownerUserId = action.teamId ? null : userIds.get(action.target);
229
+
230
+ if (
231
+ !target ||
232
+ target.ownerUserId !== ownerUserId ||
233
+ target.teamId !== action.teamId
234
+ ) {
235
+ throw new Error(
236
+ `Alias target ${action.target} was not imported for this owner`
237
+ );
95
238
  }
96
239
 
97
240
  await workspace.call("/api/admin/mailboxes", {
@@ -100,52 +243,77 @@ async function applyAction(action: Action, context: ApplyContext) {
100
243
  address: action.address,
101
244
  displayName: action.displayName,
102
245
  ownerUserId,
103
- teamId: null,
246
+ teamId: action.teamId,
247
+ delivery: "alias",
248
+ aliasOf: target.id,
104
249
  },
105
250
  });
106
251
  break;
107
252
  }
108
253
 
109
254
  case "team": {
110
- const members = action.memberEmails.flatMap((email) => {
111
- const userId = userIds.get(email);
255
+ const slices = memberSlices(teamMembers(action, userIds));
256
+ const [first = [], ...rest] = slices;
257
+
258
+ let teamId: string;
259
+ let unsent = rest;
260
+
261
+ try {
262
+ ({ teamId } = await sendWithRetry(() =>
263
+ workspace.json("/api/admin/teams", createdTeamSchema, {
264
+ method: "POST",
265
+ body: {
266
+ importId: action.teamId,
267
+ name: action.name,
268
+ slug: action.slug,
269
+ description: action.description,
270
+ everyone: action.everyone,
271
+ members: first,
272
+ },
273
+ })
274
+ ));
275
+ } catch (error) {
276
+ if (!(error instanceof WorkspaceError) || error.status !== 409) {
277
+ throw error;
278
+ }
112
279
 
113
- return userId ? [{ userId, canSend: true }] : [];
114
- });
280
+ // Only our reproducible ID proves that a lost response created this team.
281
+ const state = await workspace.json(
282
+ "/api/admin/state",
283
+ workspaceStateSchema
284
+ );
115
285
 
116
- const { teamId } = await workspace.json(
117
- "/api/admin/teams",
118
- createdTeamSchema,
119
- {
120
- method: "POST",
121
- body: {
122
- name: action.name,
123
- slug: action.slug,
124
- description: action.description,
125
- everyone: action.everyone,
126
- members,
127
- },
128
- }
129
- );
286
+ if (!state.teams.some((team) => team.id === action.teamId)) throw error;
287
+ teamId = action.teamId;
288
+ unsent = slices;
289
+ }
130
290
 
131
- teamIds.set(action.slug, teamId);
291
+ if (teamId !== action.teamId) {
292
+ throw new Error("Update the workspace before importing teams");
293
+ }
294
+
295
+ await addTeamMembers(workspace, teamId, unsent);
132
296
  break;
133
297
  }
134
298
 
135
- case "team-mailbox": {
136
- const teamId = teamIds.get(action.teamSlug);
137
-
138
- if (!teamId) {
139
- throw new Error(`team ${action.teamSlug} is not in the workspace`);
140
- }
299
+ case "team-members": {
300
+ await addTeamMembers(
301
+ workspace,
302
+ action.teamId,
303
+ memberSlices(teamMembers(action, userIds))
304
+ );
305
+ break;
306
+ }
141
307
 
308
+ case "team-mailbox": {
309
+ context.aliasTargets = undefined;
142
310
  await workspace.call("/api/admin/mailboxes", {
143
311
  method: "POST",
144
312
  body: {
145
313
  address: action.address,
146
314
  displayName: action.displayName,
147
315
  ownerUserId: null,
148
- teamId,
316
+ teamId: action.teamId,
149
317
  delivery: action.delivery,
150
318
  listPosting: action.listPosting,
151
319
  },
@@ -161,13 +329,13 @@ async function applyAction(action: Action, context: ApplyContext) {
161
329
  }
162
330
 
163
331
  /** Carries a plan out through the admin API. Each action stands alone, so a failure skips only it. */
164
- export async function applyPlan(
332
+ async function applyPlan(
165
333
  workspace: Workspace,
166
334
  plan: Plan,
335
+ state: WorkspaceState,
336
+ invites: ReturnType<typeof invitationFile> | undefined,
167
337
  log: (line: string) => void
168
- ): Promise<ApplyResult> {
169
- const state = await workspace.json("/api/admin/state", workspaceStateSchema);
170
-
338
+ ) {
171
339
  const context: ApplyContext = {
172
340
  workspace,
173
341
  userIds: new Map(
@@ -175,12 +343,20 @@ export async function applyPlan(
175
343
  user.personalEmail ? [[user.personalEmail.toLowerCase(), user.id]] : []
176
344
  )
177
345
  ),
178
- teamIds: new Map(state.teams.map((team) => [team.slug, team.id])),
179
- invitations: [["name", "email", "invitation_url", "expires_at"]],
346
+ failedTeams: new Set(),
347
+ aliasTargets: mailboxesByAddress(state.mailboxes),
348
+ invites,
180
349
  };
181
350
 
351
+ // Everyone teams have no explicit membership rows to catch a missing invitation.
352
+ const everyoneTeams = new Set([
353
+ ...state.teams.filter((team) => team.everyone).map((team) => team.id),
354
+ ...plan.actions.flatMap((action) =>
355
+ action.kind === "team" && action.everyone ? [action.teamId] : []
356
+ ),
357
+ ]);
358
+
182
359
  const result: ApplyResult = {
183
- invitations: context.invitations,
184
360
  done: 0,
185
361
  failed: [],
186
362
  };
@@ -199,6 +375,16 @@ export async function applyPlan(
199
375
  result.done += 1;
200
376
  log(`done ${action.kind} ${label}`);
201
377
  } catch (error) {
378
+ if (isSignInFailure(error)) throw error;
379
+
380
+ if (action.kind === "invite") {
381
+ for (const id of everyoneTeams) context.failedTeams.add(id);
382
+ }
383
+
384
+ if (action.kind === "team" || action.kind === "team-members") {
385
+ context.failedTeams.add(action.teamId);
386
+ }
387
+
202
388
  const message = error instanceof Error ? error.message : String(error);
203
389
  result.failed.push({ action: `${action.kind} ${label}`, error: message });
204
390
  log(`failed ${action.kind} ${label}: ${message}`);
@@ -247,7 +433,7 @@ export async function peopleCommand(args: string[], deps: CliDeps) {
247
433
 
248
434
  if (!saved.success) {
249
435
  throw new UsageError(
250
- `${values["from-directory"]} is not a directory saved with --save-directory: ${z.prettifyError(saved.error)}`
436
+ `${values["from-directory"]} is invalid or outdated. Export it again with --save-directory: ${z.prettifyError(saved.error)}`
251
437
  );
252
438
  }
253
439
 
@@ -289,11 +475,27 @@ export async function peopleCommand(args: string[], deps: CliDeps) {
289
475
  }
290
476
 
291
477
  const workspace = await connect(values, DIRECTORY_SCOPES, deps);
478
+
292
479
  const state = await workspace.json("/api/admin/state", workspaceStateSchema);
293
480
 
481
+ return importDirectory(directory, workspace, state, values, log);
482
+ }
483
+
484
+ export async function importDirectory(
485
+ directory: Directory,
486
+ workspace: Workspace,
487
+ state: WorkspaceState,
488
+ values: {
489
+ "include-suspended"?: boolean;
490
+ groups?: string;
491
+ "dry-run"?: boolean;
492
+ invites?: string;
493
+ },
494
+ log: (line: string) => void
495
+ ) {
294
496
  const plan = planDirectory(directory, state, {
295
497
  includeSuspended: Boolean(values["include-suspended"]),
296
- groupDelivery,
498
+ groupDelivery: values.groups === "inbox" ? "inbox" : "list",
297
499
  });
298
500
 
299
501
  for (const line of describePlan(plan)) log(line);
@@ -301,20 +503,48 @@ export async function peopleCommand(args: string[], deps: CliDeps) {
301
503
  if (values["dry-run"]) {
302
504
  log(`Dry run: ${plan.actions.length} changes planned, none made.`);
303
505
 
304
- return 0;
506
+ reportSourceErrors(plan, log);
507
+
508
+ return plan.sourceErrors.length ? 1 : 0;
305
509
  }
306
510
 
307
- const result = await applyPlan(workspace, plan, log);
308
- const invites = values.invites ?? "openworkspace-invitations.csv";
511
+ const path = values.invites ?? "openworkspace-invitations.csv";
309
512
 
310
- if (result.invitations.length > 1) {
311
- writeFileSync(invites, toCsv(result.invitations), { mode: 0o600 });
312
- log(
313
- `${result.invitations.length - 1} invitation links written to ${invites}. Each works once; send each to its person (before you move MX, their old mailbox still works).`
314
- );
513
+ const invites =
514
+ plan.actions.some((action) => action.kind === "invite") ||
515
+ existsSync(`${path}.pending`)
516
+ ? invitationFile(path, workspace.origin)
517
+ : undefined;
518
+
519
+ const pending = invites?.pending();
520
+
521
+ if (pending && invites) {
522
+ const link = await savedInvitationLink(workspace, pending.email);
523
+
524
+ if (link) invites.finish(pending.name, pending.email, link);
525
+ else invites.clear();
526
+ }
527
+
528
+ const result = await applyPlan(workspace, plan, state, invites, log);
529
+
530
+ if (invites) {
531
+ log(`Invitation links: ${path}. Send each person their one-time link.`);
315
532
  }
316
533
 
317
- log(`${result.done} changes made, ${result.failed.length} failed.`);
534
+ const failed = result.failed.length + plan.sourceErrors.length;
535
+ log(`${result.done} changes made, ${failed} failed.`);
536
+ reportSourceErrors(plan, log);
537
+
538
+ return failed ? 1 : 0;
539
+ }
540
+
541
+ /** These addresses can only be retried by reading current settings from Google. */
542
+ function reportSourceErrors(plan: Plan, log: (line: string) => void) {
543
+ if (!plan.sourceErrors.length) return;
544
+
545
+ log(
546
+ "Incomplete directory. Read the affected groups from Google again to retry:"
547
+ );
318
548
 
319
- return result.failed.length ? 1 : 0;
549
+ for (const { what, reason } of plan.sourceErrors) log(` ${what}: ${reason}`);
320
550
  }