@open-workspace/create 0.3.0 → 0.4.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.
- package/README.md +29 -6
- package/create.ts +86 -0
- package/import/args.ts +57 -0
- package/import/cli.ts +432 -0
- package/import/concurrency.ts +52 -0
- package/import/csv.ts +56 -0
- package/import/directory/command.ts +320 -0
- package/import/directory/google.ts +510 -0
- package/import/directory/plan.ts +367 -0
- package/import/gmail.ts +195 -0
- package/import/headers.ts +105 -0
- package/import/imap-command.ts +182 -0
- package/import/imap-source.ts +397 -0
- package/import/invariant.ts +22 -0
- package/import/mbox-source.ts +174 -0
- package/import/mbox.ts +198 -0
- package/import/oauth.ts +423 -0
- package/import/protocol.ts +59 -0
- package/import/uploader.ts +235 -0
- package/import/workspace.ts +218 -0
- package/index.ts +13 -115
- package/module-templates.ts +409 -0
- package/module.ts +105 -0
- package/package.json +18 -6
- package/setup/alchemy-helper.ts +258 -0
- package/setup/alchemy-protocol.ts +63 -0
- package/setup/alchemy.ts +163 -0
- package/setup/args.ts +128 -0
- package/setup/cloudflare-api.ts +156 -0
- package/setup/domains.ts +102 -0
- package/setup/flow.ts +987 -0
- package/setup/ui.ts +146 -0
- package/templates.ts +201 -126
package/import/csv.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** Minimal RFC 4180 CSV: quoted fields with "" escapes, header row handled by the caller. */
|
|
2
|
+
export function parseCsv(text: string): string[][] {
|
|
3
|
+
const rows: string[][] = [];
|
|
4
|
+
let row: string[] = [];
|
|
5
|
+
let field = "";
|
|
6
|
+
let quoted = false;
|
|
7
|
+
|
|
8
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
9
|
+
const char = text.charAt(index);
|
|
10
|
+
|
|
11
|
+
if (quoted) {
|
|
12
|
+
if (char === '"' && text[index + 1] === '"') {
|
|
13
|
+
field += '"';
|
|
14
|
+
index += 1;
|
|
15
|
+
} else if (char === '"') {
|
|
16
|
+
quoted = false;
|
|
17
|
+
} else {
|
|
18
|
+
field += char;
|
|
19
|
+
}
|
|
20
|
+
} else if (char === '"') {
|
|
21
|
+
quoted = true;
|
|
22
|
+
} else if (char === ",") {
|
|
23
|
+
row.push(field);
|
|
24
|
+
field = "";
|
|
25
|
+
} else if (char === "\n" || char === "\r") {
|
|
26
|
+
if (char === "\r" && text[index + 1] === "\n") index += 1;
|
|
27
|
+
row.push(field);
|
|
28
|
+
rows.push(row);
|
|
29
|
+
row = [];
|
|
30
|
+
field = "";
|
|
31
|
+
} else {
|
|
32
|
+
field += char;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (field || row.length) {
|
|
37
|
+
row.push(field);
|
|
38
|
+
rows.push(row);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Blank rows and # comments are dropped.
|
|
42
|
+
return rows.flatMap((cells) => {
|
|
43
|
+
const trimmed = cells.map((cell) => cell.trim());
|
|
44
|
+
const [first = ""] = trimmed;
|
|
45
|
+
|
|
46
|
+
return trimmed.some(Boolean) && !first.startsWith("#") ? [trimmed] : [];
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function csvField(value: string) {
|
|
51
|
+
return /[",\r\n]/u.test(value) ? `"${value.replaceAll('"', '""')}"` : value;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function toCsv(rows: string[][]) {
|
|
55
|
+
return `${rows.map((row) => row.map(csvField).join(",")).join("\n")}\n`;
|
|
56
|
+
}
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
|
|
5
|
+
import { parseCliArgs } from "../args.ts";
|
|
6
|
+
import { commonOptions, connect, UsageError } from "../cli.ts";
|
|
7
|
+
import type { CliDeps } from "../cli.ts";
|
|
8
|
+
import { toCsv } from "../csv.ts";
|
|
9
|
+
import { openInBrowser } from "../oauth.ts";
|
|
10
|
+
import { DIRECTORY_SCOPES } from "../protocol.ts";
|
|
11
|
+
import type { Workspace } from "../workspace.ts";
|
|
12
|
+
import { googleAccessToken, readGoogleDirectory } from "./google.ts";
|
|
13
|
+
import {
|
|
14
|
+
describePlan,
|
|
15
|
+
directorySchema,
|
|
16
|
+
planDirectory,
|
|
17
|
+
workspaceStateSchema,
|
|
18
|
+
} from "./plan.ts";
|
|
19
|
+
import type { Action, Directory, Plan } from "./plan.ts";
|
|
20
|
+
|
|
21
|
+
const HELP = `bunx @open-workspace/create import people --google-credentials <file.json> [--admin admin@acme.com] --workspace https://mail.acme.com
|
|
22
|
+
|
|
23
|
+
Reads users, aliases and groups from Google Workspace (Admin SDK Directory API)
|
|
24
|
+
and creates members with personal mailboxes (aliases as more mailboxes), and
|
|
25
|
+
teams with their group addresses as mailing lists or shared inboxes. Writes
|
|
26
|
+
each new member's invitation link to a CSV.
|
|
27
|
+
|
|
28
|
+
--google-credentials <file> Your service account key (domain-wide delegation; pass --admin)
|
|
29
|
+
or your own Desktop app OAuth client (you sign in as an administrator)
|
|
30
|
+
--admin <email> The super administrator a service account acts as
|
|
31
|
+
--customer <id> The Google Workspace customer ID to read (default my_customer:
|
|
32
|
+
the administrator's own organization)
|
|
33
|
+
--group-settings Also read who may post to each group and which are collaborative inboxes
|
|
34
|
+
(needs the apps.groups.settings scope)
|
|
35
|
+
--groups <list|inbox> What groups that are not collaborative inboxes become (default list)
|
|
36
|
+
--include-suspended Also import suspended users
|
|
37
|
+
--save-directory <file> Keep what Google returned, to re-run with --from-directory
|
|
38
|
+
--from-directory <file> Use a saved directory instead of asking Google
|
|
39
|
+
--invites <file.csv> Where invitation links go (default openworkspace-invitations.csv)
|
|
40
|
+
--dry-run Print the plan and change nothing`;
|
|
41
|
+
|
|
42
|
+
export type ApplyResult = {
|
|
43
|
+
invitations: string[][];
|
|
44
|
+
done: number;
|
|
45
|
+
failed: { action: string; error: string }[];
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const invitationSchema = z.object({
|
|
49
|
+
accessLink: z.object({
|
|
50
|
+
userId: z.string(),
|
|
51
|
+
url: z.string(),
|
|
52
|
+
expiresAt: z.string(),
|
|
53
|
+
}),
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const createdTeamSchema = z.object({ teamId: z.string() });
|
|
57
|
+
|
|
58
|
+
/** Ids of what the plan refers to by address or slug, filled in as earlier actions create them. */
|
|
59
|
+
type ApplyContext = {
|
|
60
|
+
workspace: Workspace;
|
|
61
|
+
userIds: Map<string, string>;
|
|
62
|
+
teamIds: Map<string, string>;
|
|
63
|
+
invitations: string[][];
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
async function applyAction(action: Action, context: ApplyContext) {
|
|
67
|
+
const { workspace, userIds, teamIds } = context;
|
|
68
|
+
|
|
69
|
+
switch (action.kind) {
|
|
70
|
+
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 },
|
|
77
|
+
}
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
userIds.set(action.email, accessLink.userId);
|
|
81
|
+
context.invitations.push([
|
|
82
|
+
action.name,
|
|
83
|
+
action.email,
|
|
84
|
+
accessLink.url,
|
|
85
|
+
accessLink.expiresAt,
|
|
86
|
+
]);
|
|
87
|
+
break;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
case "alias": {
|
|
91
|
+
const ownerUserId = userIds.get(action.ownerEmail);
|
|
92
|
+
|
|
93
|
+
if (!ownerUserId) {
|
|
94
|
+
throw new Error(`${action.ownerEmail} is not in the workspace`);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
await workspace.call("/api/admin/mailboxes", {
|
|
98
|
+
method: "POST",
|
|
99
|
+
body: {
|
|
100
|
+
address: action.address,
|
|
101
|
+
displayName: action.displayName,
|
|
102
|
+
ownerUserId,
|
|
103
|
+
teamId: null,
|
|
104
|
+
},
|
|
105
|
+
});
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
case "team": {
|
|
110
|
+
const members = action.memberEmails.flatMap((email) => {
|
|
111
|
+
const userId = userIds.get(email);
|
|
112
|
+
|
|
113
|
+
return userId ? [{ userId, canSend: true }] : [];
|
|
114
|
+
});
|
|
115
|
+
|
|
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
|
+
);
|
|
130
|
+
|
|
131
|
+
teamIds.set(action.slug, teamId);
|
|
132
|
+
break;
|
|
133
|
+
}
|
|
134
|
+
|
|
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
|
+
}
|
|
141
|
+
|
|
142
|
+
await workspace.call("/api/admin/mailboxes", {
|
|
143
|
+
method: "POST",
|
|
144
|
+
body: {
|
|
145
|
+
address: action.address,
|
|
146
|
+
displayName: action.displayName,
|
|
147
|
+
ownerUserId: null,
|
|
148
|
+
teamId,
|
|
149
|
+
delivery: action.delivery,
|
|
150
|
+
listPosting: action.listPosting,
|
|
151
|
+
},
|
|
152
|
+
});
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
default: {
|
|
157
|
+
const unexpected: never = action;
|
|
158
|
+
throw new Error(`Unknown plan action ${JSON.stringify(unexpected)}`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Carries a plan out through the admin API. Each action stands alone, so a failure skips only it. */
|
|
164
|
+
export async function applyPlan(
|
|
165
|
+
workspace: Workspace,
|
|
166
|
+
plan: Plan,
|
|
167
|
+
log: (line: string) => void
|
|
168
|
+
): Promise<ApplyResult> {
|
|
169
|
+
const state = await workspace.json("/api/admin/state", workspaceStateSchema);
|
|
170
|
+
|
|
171
|
+
const context: ApplyContext = {
|
|
172
|
+
workspace,
|
|
173
|
+
userIds: new Map(
|
|
174
|
+
state.users.flatMap((user) =>
|
|
175
|
+
user.personalEmail ? [[user.personalEmail.toLowerCase(), user.id]] : []
|
|
176
|
+
)
|
|
177
|
+
),
|
|
178
|
+
teamIds: new Map(state.teams.map((team) => [team.slug, team.id])),
|
|
179
|
+
invitations: [["name", "email", "invitation_url", "expires_at"]],
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
const result: ApplyResult = {
|
|
183
|
+
invitations: context.invitations,
|
|
184
|
+
done: 0,
|
|
185
|
+
failed: [],
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
for (const action of plan.actions) {
|
|
189
|
+
const label =
|
|
190
|
+
"email" in action
|
|
191
|
+
? action.email
|
|
192
|
+
: "address" in action
|
|
193
|
+
? action.address
|
|
194
|
+
: action.slug;
|
|
195
|
+
|
|
196
|
+
try {
|
|
197
|
+
// oxlint-disable-next-line eslint/no-await-in-loop -- the plan is ordered: aliases and teams use the ids of members invited before them, team mailboxes the ids of their teams
|
|
198
|
+
await applyAction(action, context);
|
|
199
|
+
result.done += 1;
|
|
200
|
+
log(`done ${action.kind} ${label}`);
|
|
201
|
+
} catch (error) {
|
|
202
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
203
|
+
result.failed.push({ action: `${action.kind} ${label}`, error: message });
|
|
204
|
+
log(`failed ${action.kind} ${label}: ${message}`);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
return result;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export async function peopleCommand(args: string[], deps: CliDeps) {
|
|
212
|
+
const { values } = parseCliArgs({
|
|
213
|
+
args,
|
|
214
|
+
options: {
|
|
215
|
+
...commonOptions,
|
|
216
|
+
"google-credentials": { type: "string" },
|
|
217
|
+
admin: { type: "string" },
|
|
218
|
+
customer: { type: "string" },
|
|
219
|
+
"group-settings": { type: "boolean" },
|
|
220
|
+
groups: { type: "string" },
|
|
221
|
+
"include-suspended": { type: "boolean" },
|
|
222
|
+
"save-directory": { type: "string" },
|
|
223
|
+
"from-directory": { type: "string" },
|
|
224
|
+
invites: { type: "string" },
|
|
225
|
+
},
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
if (values.help) {
|
|
229
|
+
console.log(HELP);
|
|
230
|
+
|
|
231
|
+
return 0;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const log = deps.log ?? ((line: string) => console.error(line));
|
|
235
|
+
const groupDelivery = values.groups ?? "list";
|
|
236
|
+
|
|
237
|
+
if (groupDelivery !== "list" && groupDelivery !== "inbox") {
|
|
238
|
+
throw new UsageError("--groups is list or inbox");
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
let directory: Directory;
|
|
242
|
+
|
|
243
|
+
if (values["from-directory"]) {
|
|
244
|
+
const saved = directorySchema.safeParse(
|
|
245
|
+
JSON.parse(readFileSync(values["from-directory"], "utf-8"))
|
|
246
|
+
);
|
|
247
|
+
|
|
248
|
+
if (!saved.success) {
|
|
249
|
+
throw new UsageError(
|
|
250
|
+
`${values["from-directory"]} is not a directory saved with --save-directory: ${z.prettifyError(saved.error)}`
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
directory = saved.data;
|
|
255
|
+
} else {
|
|
256
|
+
if (!values["google-credentials"]) {
|
|
257
|
+
throw new UsageError("Pass --google-credentials (or --from-directory)");
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const fetchImpl = (input: string, init?: RequestInit) => fetch(input, init);
|
|
261
|
+
|
|
262
|
+
const token = await googleAccessToken({
|
|
263
|
+
credentials: JSON.parse(
|
|
264
|
+
readFileSync(values["google-credentials"], "utf-8")
|
|
265
|
+
),
|
|
266
|
+
admin: values.admin,
|
|
267
|
+
groupSettings: Boolean(values["group-settings"]),
|
|
268
|
+
fetch: fetchImpl,
|
|
269
|
+
openBrowser: deps.openBrowser ?? openInBrowser,
|
|
270
|
+
log,
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
directory = await readGoogleDirectory(token, {
|
|
274
|
+
customer: values.customer,
|
|
275
|
+
groupSettings: Boolean(values["group-settings"]),
|
|
276
|
+
fetch: fetchImpl,
|
|
277
|
+
});
|
|
278
|
+
log(
|
|
279
|
+
`Google: ${directory.users.length} users, ${directory.groups.length} groups`
|
|
280
|
+
);
|
|
281
|
+
|
|
282
|
+
if (values["save-directory"]) {
|
|
283
|
+
writeFileSync(
|
|
284
|
+
values["save-directory"],
|
|
285
|
+
JSON.stringify(directory, null, 2),
|
|
286
|
+
{ mode: 0o600 }
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const workspace = await connect(values, DIRECTORY_SCOPES, deps);
|
|
292
|
+
const state = await workspace.json("/api/admin/state", workspaceStateSchema);
|
|
293
|
+
|
|
294
|
+
const plan = planDirectory(directory, state, {
|
|
295
|
+
includeSuspended: Boolean(values["include-suspended"]),
|
|
296
|
+
groupDelivery,
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
for (const line of describePlan(plan)) log(line);
|
|
300
|
+
|
|
301
|
+
if (values["dry-run"]) {
|
|
302
|
+
log(`Dry run: ${plan.actions.length} changes planned, none made.`);
|
|
303
|
+
|
|
304
|
+
return 0;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const result = await applyPlan(workspace, plan, log);
|
|
308
|
+
const invites = values.invites ?? "openworkspace-invitations.csv";
|
|
309
|
+
|
|
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
|
+
);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
log(`${result.done} changes made, ${result.failed.length} failed.`);
|
|
318
|
+
|
|
319
|
+
return result.failed.length ? 1 : 0;
|
|
320
|
+
}
|