@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
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,164 @@ 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
+ const saved = await savedInvitationLink(workspace, action.email);
194
+
195
+ if (!saved) {
196
+ invites.clear();
197
+ throw error;
198
+ }
199
+
200
+ accessLink = saved;
201
+ }
79
202
 
80
203
  userIds.set(action.email, accessLink.userId);
81
- context.invitations.push([
82
- action.name,
83
- action.email,
84
- accessLink.url,
85
- accessLink.expiresAt,
86
- ]);
204
+ invites.finish(action.name, action.email, accessLink);
87
205
  break;
88
206
  }
89
207
 
90
208
  case "alias": {
91
- const ownerUserId = userIds.get(action.ownerEmail);
209
+ if (!context.aliasTargets) {
210
+ const state = await workspace.json(
211
+ "/api/admin/state",
212
+ workspaceStateSchema
213
+ );
92
214
 
93
- if (!ownerUserId) {
94
- throw new Error(`${action.ownerEmail} is not in the workspace`);
215
+ context.aliasTargets = mailboxesByAddress(state.mailboxes);
216
+ }
217
+
218
+ const target = context.aliasTargets.get(action.target);
219
+ const ownerUserId = action.teamId ? null : userIds.get(action.target);
220
+
221
+ if (
222
+ !target ||
223
+ target.ownerUserId !== ownerUserId ||
224
+ target.teamId !== action.teamId
225
+ ) {
226
+ throw new Error(
227
+ `Alias target ${action.target} was not imported for this owner`
228
+ );
95
229
  }
96
230
 
97
231
  await workspace.call("/api/admin/mailboxes", {
@@ -100,52 +234,77 @@ async function applyAction(action: Action, context: ApplyContext) {
100
234
  address: action.address,
101
235
  displayName: action.displayName,
102
236
  ownerUserId,
103
- teamId: null,
237
+ teamId: action.teamId,
238
+ delivery: "alias",
239
+ aliasOf: target.id,
104
240
  },
105
241
  });
106
242
  break;
107
243
  }
108
244
 
109
245
  case "team": {
110
- const members = action.memberEmails.flatMap((email) => {
111
- const userId = userIds.get(email);
246
+ const slices = memberSlices(teamMembers(action, userIds));
247
+ const [first = [], ...rest] = slices;
248
+
249
+ let teamId: string;
250
+ let unsent = rest;
251
+
252
+ try {
253
+ ({ teamId } = await sendWithRetry(() =>
254
+ workspace.json("/api/admin/teams", createdTeamSchema, {
255
+ method: "POST",
256
+ body: {
257
+ importId: action.teamId,
258
+ name: action.name,
259
+ slug: action.slug,
260
+ description: action.description,
261
+ everyone: action.everyone,
262
+ members: first,
263
+ },
264
+ })
265
+ ));
266
+ } catch (error) {
267
+ if (!(error instanceof WorkspaceError) || error.status !== 409) {
268
+ throw error;
269
+ }
112
270
 
113
- return userId ? [{ userId, canSend: true }] : [];
114
- });
271
+ // Only our reproducible ID proves that a lost response created this team.
272
+ const state = await workspace.json(
273
+ "/api/admin/state",
274
+ workspaceStateSchema
275
+ );
115
276
 
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
- );
277
+ if (!state.teams.some((team) => team.id === action.teamId)) throw error;
278
+ teamId = action.teamId;
279
+ unsent = slices;
280
+ }
130
281
 
131
- teamIds.set(action.slug, teamId);
282
+ if (teamId !== action.teamId) {
283
+ throw new Error("Update the workspace before importing teams");
284
+ }
285
+
286
+ await addTeamMembers(workspace, teamId, unsent);
132
287
  break;
133
288
  }
134
289
 
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
- }
290
+ case "team-members": {
291
+ await addTeamMembers(
292
+ workspace,
293
+ action.teamId,
294
+ memberSlices(teamMembers(action, userIds))
295
+ );
296
+ break;
297
+ }
141
298
 
299
+ case "team-mailbox": {
300
+ context.aliasTargets = undefined;
142
301
  await workspace.call("/api/admin/mailboxes", {
143
302
  method: "POST",
144
303
  body: {
145
304
  address: action.address,
146
305
  displayName: action.displayName,
147
306
  ownerUserId: null,
148
- teamId,
307
+ teamId: action.teamId,
149
308
  delivery: action.delivery,
150
309
  listPosting: action.listPosting,
151
310
  },
@@ -161,13 +320,13 @@ async function applyAction(action: Action, context: ApplyContext) {
161
320
  }
162
321
 
163
322
  /** Carries a plan out through the admin API. Each action stands alone, so a failure skips only it. */
164
- export async function applyPlan(
323
+ async function applyPlan(
165
324
  workspace: Workspace,
166
325
  plan: Plan,
326
+ state: WorkspaceState,
327
+ invites: ReturnType<typeof invitationFile> | undefined,
167
328
  log: (line: string) => void
168
- ): Promise<ApplyResult> {
169
- const state = await workspace.json("/api/admin/state", workspaceStateSchema);
170
-
329
+ ) {
171
330
  const context: ApplyContext = {
172
331
  workspace,
173
332
  userIds: new Map(
@@ -175,12 +334,20 @@ export async function applyPlan(
175
334
  user.personalEmail ? [[user.personalEmail.toLowerCase(), user.id]] : []
176
335
  )
177
336
  ),
178
- teamIds: new Map(state.teams.map((team) => [team.slug, team.id])),
179
- invitations: [["name", "email", "invitation_url", "expires_at"]],
337
+ failedTeams: new Set(),
338
+ aliasTargets: mailboxesByAddress(state.mailboxes),
339
+ invites,
180
340
  };
181
341
 
342
+ // Everyone teams have no explicit membership rows to catch a missing invitation.
343
+ const everyoneTeams = new Set([
344
+ ...state.teams.filter((team) => team.everyone).map((team) => team.id),
345
+ ...plan.actions.flatMap((action) =>
346
+ action.kind === "team" && action.everyone ? [action.teamId] : []
347
+ ),
348
+ ]);
349
+
182
350
  const result: ApplyResult = {
183
- invitations: context.invitations,
184
351
  done: 0,
185
352
  failed: [],
186
353
  };
@@ -199,6 +366,16 @@ export async function applyPlan(
199
366
  result.done += 1;
200
367
  log(`done ${action.kind} ${label}`);
201
368
  } catch (error) {
369
+ if (isSignInFailure(error)) throw error;
370
+
371
+ if (action.kind === "invite") {
372
+ for (const id of everyoneTeams) context.failedTeams.add(id);
373
+ }
374
+
375
+ if (action.kind === "team" || action.kind === "team-members") {
376
+ context.failedTeams.add(action.teamId);
377
+ }
378
+
202
379
  const message = error instanceof Error ? error.message : String(error);
203
380
  result.failed.push({ action: `${action.kind} ${label}`, error: message });
204
381
  log(`failed ${action.kind} ${label}: ${message}`);
@@ -247,7 +424,7 @@ export async function peopleCommand(args: string[], deps: CliDeps) {
247
424
 
248
425
  if (!saved.success) {
249
426
  throw new UsageError(
250
- `${values["from-directory"]} is not a directory saved with --save-directory: ${z.prettifyError(saved.error)}`
427
+ `${values["from-directory"]} is invalid or outdated. Export it again with --save-directory: ${z.prettifyError(saved.error)}`
251
428
  );
252
429
  }
253
430
 
@@ -289,11 +466,27 @@ export async function peopleCommand(args: string[], deps: CliDeps) {
289
466
  }
290
467
 
291
468
  const workspace = await connect(values, DIRECTORY_SCOPES, deps);
469
+
292
470
  const state = await workspace.json("/api/admin/state", workspaceStateSchema);
293
471
 
472
+ return importDirectory(directory, workspace, state, values, log);
473
+ }
474
+
475
+ export async function importDirectory(
476
+ directory: Directory,
477
+ workspace: Workspace,
478
+ state: WorkspaceState,
479
+ values: {
480
+ "include-suspended"?: boolean;
481
+ groups?: string;
482
+ "dry-run"?: boolean;
483
+ invites?: string;
484
+ },
485
+ log: (line: string) => void
486
+ ) {
294
487
  const plan = planDirectory(directory, state, {
295
488
  includeSuspended: Boolean(values["include-suspended"]),
296
- groupDelivery,
489
+ groupDelivery: values.groups === "inbox" ? "inbox" : "list",
297
490
  });
298
491
 
299
492
  for (const line of describePlan(plan)) log(line);
@@ -301,20 +494,48 @@ export async function peopleCommand(args: string[], deps: CliDeps) {
301
494
  if (values["dry-run"]) {
302
495
  log(`Dry run: ${plan.actions.length} changes planned, none made.`);
303
496
 
304
- return 0;
497
+ reportSourceErrors(plan, log);
498
+
499
+ return plan.sourceErrors.length ? 1 : 0;
305
500
  }
306
501
 
307
- const result = await applyPlan(workspace, plan, log);
308
- const invites = values.invites ?? "openworkspace-invitations.csv";
502
+ const path = values.invites ?? "openworkspace-invitations.csv";
309
503
 
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
- );
504
+ const invites =
505
+ plan.actions.some((action) => action.kind === "invite") ||
506
+ existsSync(`${path}.pending`)
507
+ ? invitationFile(path, workspace.origin)
508
+ : undefined;
509
+
510
+ const pending = invites?.pending();
511
+
512
+ if (pending && invites) {
513
+ const link = await savedInvitationLink(workspace, pending.email);
514
+
515
+ if (link) invites.finish(pending.name, pending.email, link);
516
+ else invites.clear();
517
+ }
518
+
519
+ const result = await applyPlan(workspace, plan, state, invites, log);
520
+
521
+ if (invites) {
522
+ log(`Invitation links: ${path}. Send each person their one-time link.`);
315
523
  }
316
524
 
317
- log(`${result.done} changes made, ${result.failed.length} failed.`);
525
+ const failed = result.failed.length + plan.sourceErrors.length;
526
+ log(`${result.done} changes made, ${failed} failed.`);
527
+ reportSourceErrors(plan, log);
528
+
529
+ return failed ? 1 : 0;
530
+ }
531
+
532
+ /** These addresses can only be retried by reading current settings from Google. */
533
+ function reportSourceErrors(plan: Plan, log: (line: string) => void) {
534
+ if (!plan.sourceErrors.length) return;
535
+
536
+ log(
537
+ "Incomplete directory. Read the affected groups from Google again to retry:"
538
+ );
318
539
 
319
- return result.failed.length ? 1 : 0;
540
+ for (const { what, reason } of plan.sourceErrors) log(` ${what}: ${reason}`);
320
541
  }