@open-workspace/create 0.2.0 → 0.4.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.
@@ -0,0 +1,510 @@
1
+ import { z } from "zod";
2
+
3
+ import { forEachConcurrent } from "../concurrency.ts";
4
+ import type { Fetch } from "../oauth.ts";
5
+ import type { Directory, DirectoryGroup, DirectoryUser } from "./plan.ts";
6
+
7
+ /**
8
+ * Reading a Google Workspace directory with the Admin SDK Directory API,
9
+ * with credentials the administrator brings (OpenWorkspace ships no Google
10
+ * client): a service account with domain-wide delegation acting as an
11
+ * administrator, or their own OAuth client ("Desktop app") signed in
12
+ * through the browser.
13
+ */
14
+
15
+ export const DIRECTORY_READ_SCOPES = [
16
+ "https://www.googleapis.com/auth/admin.directory.user.readonly",
17
+ "https://www.googleapis.com/auth/admin.directory.group.readonly",
18
+ "https://www.googleapis.com/auth/admin.directory.group.member.readonly",
19
+ ];
20
+
21
+ /** Optional: who may post to each group, and whether it is a collaborative inbox. */
22
+ export const GROUP_SETTINGS_SCOPE =
23
+ "https://www.googleapis.com/auth/apps.groups.settings";
24
+
25
+ const TOKEN_URL = "https://oauth2.googleapis.com/token";
26
+ const AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
27
+ const DIRECTORY = "https://admin.googleapis.com/admin/directory/v1";
28
+ const GROUP_SETTINGS = "https://www.googleapis.com/groups/v1/groups";
29
+
30
+ const serviceAccountKeySchema = z.object({
31
+ type: z.literal("service_account"),
32
+ client_email: z.string(),
33
+ private_key: z.string(),
34
+ token_uri: z.string().optional(),
35
+ });
36
+
37
+ type ServiceAccountKey = z.infer<typeof serviceAccountKeySchema>;
38
+
39
+ const installedClientSchema = z.object({
40
+ installed: z.object({
41
+ client_id: z.string().min(1),
42
+ client_secret: z.string().optional(),
43
+ }),
44
+ });
45
+
46
+ type InstalledClient = z.infer<typeof installedClientSchema>;
47
+
48
+ /** A Google OAuth error; every field is optional so any body parses. */
49
+ const googleErrorSchema = z.object({
50
+ error: z.string().optional(),
51
+ error_description: z.string().optional(),
52
+ });
53
+
54
+ const accessTokenSchema = z.object({ access_token: z.string().min(1) });
55
+
56
+ /** Google's access token, or an error with why it refused (`explain` words it). */
57
+ async function accessToken(
58
+ response: Response,
59
+ explain: (reason: string | number) => string
60
+ ) {
61
+ const json = await response.json().catch(() => null);
62
+ const token = accessTokenSchema.safeParse(json);
63
+
64
+ if (response.ok && token.success) return token.data.access_token;
65
+ const refusal = googleErrorSchema.safeParse(json);
66
+ const error = refusal.success ? refusal.data : {};
67
+
68
+ throw new Error(
69
+ explain(error.error_description ?? error.error ?? response.status)
70
+ );
71
+ }
72
+
73
+ const base64Url = (value: string | Uint8Array) =>
74
+ Buffer.from(value).toString("base64url");
75
+
76
+ /** A service account's token, impersonating `subject` (domain-wide delegation). */
77
+ async function serviceAccountToken(
78
+ key: ServiceAccountKey,
79
+ subject: string,
80
+ scopes: string[],
81
+ fetchImpl: Fetch
82
+ ) {
83
+ const now = Math.floor(Date.now() / 1000);
84
+ const header = base64Url(JSON.stringify({ alg: "RS256", typ: "JWT" }));
85
+
86
+ const claims = base64Url(
87
+ JSON.stringify({
88
+ iss: key.client_email,
89
+ sub: subject,
90
+ scope: scopes.join(" "),
91
+ aud: key.token_uri ?? TOKEN_URL,
92
+ iat: now,
93
+ exp: now + 3600,
94
+ })
95
+ );
96
+
97
+ const der = Buffer.from(
98
+ key.private_key.replaceAll(/-----[^-]+-----|\s/gu, ""),
99
+ "base64"
100
+ );
101
+
102
+ const signingKey = await crypto.subtle.importKey(
103
+ "pkcs8",
104
+ der,
105
+ { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
106
+ false,
107
+ ["sign"]
108
+ );
109
+
110
+ const signature = new Uint8Array(
111
+ await crypto.subtle.sign(
112
+ "RSASSA-PKCS1-v1_5",
113
+ signingKey,
114
+ new TextEncoder().encode(`${header}.${claims}`)
115
+ )
116
+ );
117
+
118
+ const response = await fetchImpl(key.token_uri ?? TOKEN_URL, {
119
+ method: "POST",
120
+ headers: { "content-type": "application/x-www-form-urlencoded" },
121
+ body: new URLSearchParams({
122
+ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
123
+ assertion: `${header}.${claims}.${base64Url(signature)}`,
124
+ }),
125
+ });
126
+
127
+ return accessToken(
128
+ response,
129
+ (reason) =>
130
+ `Google refused the service account (${reason}). Check its domain-wide delegation scopes and that --admin is a super administrator.`
131
+ );
132
+ }
133
+
134
+ /** The administrator signs in with their own Desktop OAuth client, in the browser (loopback, PKCE). */
135
+ async function installedClientToken(
136
+ client: InstalledClient["installed"],
137
+ scopes: string[],
138
+ fetchImpl: Fetch,
139
+ openBrowser: (url: string) => void | Promise<void>,
140
+ log: (message: string) => void
141
+ ) {
142
+ const verifier = base64Url(crypto.getRandomValues(new Uint8Array(32)));
143
+
144
+ const challenge = base64Url(
145
+ new Uint8Array(
146
+ await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))
147
+ )
148
+ );
149
+
150
+ const state = base64Url(crypto.getRandomValues(new Uint8Array(16)));
151
+ let receive!: (params: URLSearchParams) => void;
152
+
153
+ const callback = new Promise<URLSearchParams>((resolve) => {
154
+ receive = resolve;
155
+ });
156
+
157
+ const server = Bun.serve({
158
+ hostname: "127.0.0.1",
159
+ port: 0,
160
+ fetch(request) {
161
+ const url = new URL(request.url);
162
+
163
+ if (url.pathname !== "/") {
164
+ return new Response("Not found", { status: 404 });
165
+ }
166
+
167
+ receive(url.searchParams);
168
+
169
+ return new Response("Signed in to Google. You can close this tab.", {
170
+ headers: { "content-type": "text/plain" },
171
+ });
172
+ },
173
+ });
174
+
175
+ try {
176
+ const redirectUri = `http://127.0.0.1:${server.port}/`;
177
+ const url = new URL(AUTH_URL);
178
+
179
+ for (const [name, value] of Object.entries({
180
+ client_id: client.client_id,
181
+ redirect_uri: redirectUri,
182
+ response_type: "code",
183
+ scope: scopes.join(" "),
184
+ code_challenge: challenge,
185
+ code_challenge_method: "S256",
186
+ state,
187
+ })) {
188
+ url.searchParams.set(name, value);
189
+ }
190
+
191
+ log(`Sign in to Google as an administrator:\n ${url}`);
192
+ await openBrowser(url.toString());
193
+ const params = await callback;
194
+
195
+ const code = params.get("code");
196
+
197
+ if (params.get("state") !== state || !code) {
198
+ throw new Error(
199
+ `Google sign-in failed: ${params.get("error") ?? "no code"}`
200
+ );
201
+ }
202
+
203
+ const form = new URLSearchParams({
204
+ grant_type: "authorization_code",
205
+ code,
206
+ redirect_uri: redirectUri,
207
+ client_id: client.client_id,
208
+ });
209
+
210
+ if (client.client_secret) form.set("client_secret", client.client_secret);
211
+ form.set("code_verifier", verifier);
212
+
213
+ const response = await fetchImpl(TOKEN_URL, {
214
+ method: "POST",
215
+ headers: { "content-type": "application/x-www-form-urlencoded" },
216
+ body: form,
217
+ });
218
+
219
+ return accessToken(
220
+ response,
221
+ (reason) => `Google sign-in failed: ${reason}`
222
+ );
223
+ } finally {
224
+ server.stop(true);
225
+ }
226
+ }
227
+
228
+ export type GoogleCredentialsOptions = {
229
+ /** The JSON Google Cloud gave you (parsed): a service account key, or a Desktop OAuth client. */
230
+ credentials: z.core.util.JSONType;
231
+ /** For a service account: the super administrator it acts as. */
232
+ admin?: string;
233
+ groupSettings: boolean;
234
+ fetch: Fetch;
235
+ openBrowser: (url: string) => void | Promise<void>;
236
+ log: (message: string) => void;
237
+ };
238
+
239
+ export function googleAccessToken(
240
+ options: GoogleCredentialsOptions
241
+ ): Promise<string> {
242
+ const scopes = [
243
+ ...DIRECTORY_READ_SCOPES,
244
+ ...(options.groupSettings ? [GROUP_SETTINGS_SCOPE] : []),
245
+ ];
246
+
247
+ const serviceAccount = serviceAccountKeySchema.safeParse(options.credentials);
248
+
249
+ if (serviceAccount.success) {
250
+ if (!options.admin) {
251
+ return Promise.reject(
252
+ new Error(
253
+ "A service account acts as an administrator: pass --admin admin@your-domain"
254
+ )
255
+ );
256
+ }
257
+
258
+ return serviceAccountToken(
259
+ serviceAccount.data,
260
+ options.admin,
261
+ scopes,
262
+ options.fetch
263
+ );
264
+ }
265
+
266
+ const installed = installedClientSchema.safeParse(options.credentials);
267
+
268
+ if (installed.success) {
269
+ return installedClientToken(
270
+ installed.data.installed,
271
+ scopes,
272
+ options.fetch,
273
+ options.openBrowser,
274
+ options.log
275
+ );
276
+ }
277
+
278
+ return Promise.reject(
279
+ new Error(
280
+ "The Google credentials are neither a service account key nor a Desktop app OAuth client (see https://openworkspace.dev/docs/migration)"
281
+ )
282
+ );
283
+ }
284
+
285
+ /** Every page of a Directory API list: `schema` reads one page, `itemsOf` its items. */
286
+ async function pages<Schema extends z.ZodType, Item>(
287
+ token: string,
288
+ url: URL,
289
+ schema: Schema,
290
+ itemsOf: (page: z.output<Schema>) => Item[] | undefined,
291
+ fetchImpl: Fetch,
292
+ pageToken?: string
293
+ ): Promise<Item[]> {
294
+ if (pageToken) url.searchParams.set("pageToken", pageToken);
295
+
296
+ const response = await fetchImpl(url.toString(), {
297
+ headers: { authorization: `Bearer ${token}` },
298
+ });
299
+
300
+ const json = await response.json();
301
+
302
+ if (!response.ok) {
303
+ const refusal = directoryErrorSchema.safeParse(json);
304
+ const message = refusal.success ? refusal.data.error?.message : undefined;
305
+
306
+ throw new Error(
307
+ `Google Directory API: ${message ?? response.status} (${url.pathname})`
308
+ );
309
+ }
310
+
311
+ const page = schema.safeParse(json);
312
+ const next = nextPageSchema.safeParse(json);
313
+
314
+ if (!page.success) throw unexpectedAnswer(url, page.error);
315
+
316
+ if (!next.success) throw unexpectedAnswer(url, next.error);
317
+
318
+ const items = itemsOf(page.data) ?? [];
319
+ const { nextPageToken } = next.data;
320
+
321
+ if (!nextPageToken) return items;
322
+
323
+ // Each page names the next one, so they are read one after another.
324
+ return [
325
+ ...items,
326
+ ...(await pages(token, url, schema, itemsOf, fetchImpl, nextPageToken)),
327
+ ];
328
+ }
329
+
330
+ function unexpectedAnswer(url: URL, error: z.ZodError) {
331
+ return new Error(
332
+ `Google Directory API: unexpected answer (${url.pathname}): ${z.prettifyError(error)}`
333
+ );
334
+ }
335
+
336
+ const directoryErrorSchema = z.object({
337
+ error: z.object({ message: z.string().optional() }).optional(),
338
+ });
339
+
340
+ const nextPageSchema = z.object({ nextPageToken: z.string().optional() });
341
+
342
+ const googleUserSchema = z.object({
343
+ primaryEmail: z.string(),
344
+ name: z.object({ fullName: z.string().optional() }).optional(),
345
+ aliases: z.array(z.string()).optional(),
346
+ suspended: z.boolean().optional(),
347
+ archived: z.boolean().optional(),
348
+ isAdmin: z.boolean().optional(),
349
+ });
350
+
351
+ const usersPageSchema = z.object({
352
+ users: z.array(googleUserSchema).optional(),
353
+ });
354
+
355
+ const googleGroupSchema = z.object({
356
+ email: z.string(),
357
+ name: z.string().optional(),
358
+ description: z.string().optional(),
359
+ aliases: z.array(z.string()).optional(),
360
+ });
361
+
362
+ const groupsPageSchema = z.object({
363
+ groups: z.array(googleGroupSchema).optional(),
364
+ });
365
+
366
+ const googleMemberSchema = z.object({
367
+ email: z.string().optional(),
368
+ type: z.string().optional(),
369
+ status: z.string().optional(),
370
+ });
371
+
372
+ const membersPageSchema = z.object({
373
+ members: z.array(googleMemberSchema).optional(),
374
+ });
375
+
376
+ /** The Groups Settings API's answer, the parts read here (its booleans are strings). */
377
+ const groupSettingsSchema = z.object({
378
+ whoCanPostMessage: z.string().optional(),
379
+ enableCollaborativeInbox: z.string().optional(),
380
+ });
381
+
382
+ type GroupSettings = z.infer<typeof groupSettingsSchema>;
383
+
384
+ /** Directory API requests in flight while reading groups; well under Google's per-user quota. */
385
+ const GROUP_CONCURRENCY = 4;
386
+
387
+ /** What a group's whoCanPostMessage becomes. */
388
+ export function postingPolicy(
389
+ whoCanPostMessage: string | undefined
390
+ ): DirectoryGroup["posting"] {
391
+ switch (whoCanPostMessage) {
392
+ case "ANYONE_CAN_POST": {
393
+ return "anyone";
394
+ }
395
+
396
+ case "ALL_IN_DOMAIN_CAN_POST": {
397
+ return "workspace";
398
+ }
399
+
400
+ case "ALL_MEMBERS_CAN_POST":
401
+ case "ALL_MANAGERS_CAN_POST":
402
+ case "ALL_OWNERS_CAN_POST":
403
+ case "NONE_CAN_POST": {
404
+ return "members";
405
+ }
406
+
407
+ default: {
408
+ return null;
409
+ }
410
+ }
411
+ }
412
+
413
+ /** Users, aliases, groups and members of the customer `customer` ("my_customer": the signed-in organization). */
414
+ export async function readGoogleDirectory(
415
+ token: string,
416
+ options: { customer?: string; groupSettings: boolean; fetch: Fetch }
417
+ ): Promise<Directory> {
418
+ const customer = options.customer ?? "my_customer";
419
+ const usersUrl = new URL(`${DIRECTORY}/users`);
420
+ usersUrl.searchParams.set("customer", customer);
421
+ usersUrl.searchParams.set("maxResults", "500");
422
+ usersUrl.searchParams.set("projection", "basic");
423
+
424
+ const users = (
425
+ await pages(
426
+ token,
427
+ usersUrl,
428
+ usersPageSchema,
429
+ (page) => page.users,
430
+ options.fetch
431
+ )
432
+ ).map((user): DirectoryUser => ({
433
+ email: user.primaryEmail,
434
+ name: user.name?.fullName ?? user.primaryEmail,
435
+ aliases: user.aliases ?? [],
436
+ suspended: Boolean(user.suspended || user.archived),
437
+ isAdmin: Boolean(user.isAdmin),
438
+ }));
439
+
440
+ const groupsUrl = new URL(`${DIRECTORY}/groups`);
441
+ groupsUrl.searchParams.set("customer", customer);
442
+ groupsUrl.searchParams.set("maxResults", "200");
443
+
444
+ const googleGroups = await pages(
445
+ token,
446
+ groupsUrl,
447
+ groupsPageSchema,
448
+ (page) => page.groups,
449
+ options.fetch
450
+ );
451
+
452
+ const groupSettings = async (email: string): Promise<GroupSettings> => {
453
+ if (!options.groupSettings) return {};
454
+
455
+ const response = await options.fetch(
456
+ `${GROUP_SETTINGS}/${encodeURIComponent(email)}?alt=json`,
457
+ {
458
+ headers: { authorization: `Bearer ${token}` },
459
+ }
460
+ );
461
+
462
+ if (!response.ok) return {};
463
+ const settings = groupSettingsSchema.safeParse(await response.json());
464
+
465
+ return settings.success ? settings.data : {};
466
+ };
467
+
468
+ // Groups are independent of each other: read a few at a time, kept in Google's order.
469
+ const groups: DirectoryGroup[] = [];
470
+
471
+ await forEachConcurrent(
472
+ googleGroups,
473
+ GROUP_CONCURRENCY,
474
+ async (group, index) => {
475
+ const membersUrl = new URL(
476
+ `${DIRECTORY}/groups/${encodeURIComponent(group.email)}/members`
477
+ );
478
+
479
+ membersUrl.searchParams.set("maxResults", "200");
480
+
481
+ const [members, settings] = await Promise.all([
482
+ pages(
483
+ token,
484
+ membersUrl,
485
+ membersPageSchema,
486
+ (page) => page.members,
487
+ options.fetch
488
+ ),
489
+ groupSettings(group.email),
490
+ ]);
491
+
492
+ groups[index] = {
493
+ email: group.email,
494
+ name: group.name ?? group.email,
495
+ description: group.description ?? null,
496
+ aliases: group.aliases ?? [],
497
+ members: members.flatMap((member) => {
498
+ if (member.status === "SUSPENDED") return [];
499
+ const address = member.type === "CUSTOMER" ? "*" : member.email;
500
+
501
+ return address ? [address] : [];
502
+ }),
503
+ sharedInbox: settings.enableCollaborativeInbox === "true",
504
+ posting: postingPolicy(settings.whoCanPostMessage),
505
+ };
506
+ }
507
+ );
508
+
509
+ return { users, groups };
510
+ }