@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/oauth.ts CHANGED
@@ -1,9 +1,20 @@
1
- import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
1
+ import {
2
+ chmodSync,
3
+ closeSync,
4
+ mkdirSync,
5
+ openSync,
6
+ readFileSync,
7
+ rmSync,
8
+ statSync,
9
+ writeFileSync,
10
+ } from "node:fs";
2
11
  import { homedir } from "node:os";
3
12
  import { dirname, join } from "node:path";
4
13
 
5
14
  import { z } from "zod";
6
15
 
16
+ import { loopbackSignIn } from "./loopback.ts";
17
+
7
18
  /**
8
19
  * Signing in to a workspace the way an MCP client does: self-registration
9
20
  * (RFC 7591) with a loopback redirect, the authorization code flow with
@@ -19,6 +30,7 @@ const metadataSchema = z.object({
19
30
  authorization_endpoint: z.string(),
20
31
  token_endpoint: z.string(),
21
32
  registration_endpoint: z.string().optional(),
33
+ scopes_supported: z.array(z.string()).optional(),
22
34
  });
23
35
 
24
36
  type Metadata = z.infer<typeof metadataSchema>;
@@ -80,11 +92,22 @@ async function tokenResponse(response: Response, what: string) {
80
92
  return body.data;
81
93
  }
82
94
 
95
+ /** The sign-in can't go on (a refused token that can't be refreshed): every request would fail, so the run ends. */
96
+ export class SignInError extends Error {
97
+ constructor(message: string) {
98
+ super(message);
99
+ this.name = "SignInError";
100
+ }
101
+ }
102
+
83
103
  export type TokenSource = {
84
104
  /** A current access token. */
85
105
  token(): Promise<string>;
86
- /** A new access token after the workspace refused the last one. */
87
- refresh(): Promise<string>;
106
+ /**
107
+ * A new access token after the workspace refused `rejected`; when
108
+ * another request refreshed it since, the newer one.
109
+ */
110
+ refresh(rejected?: string): Promise<string>;
88
111
  /** The scopes the workspace granted. */
89
112
  readonly scopes: string[];
90
113
  };
@@ -98,29 +121,61 @@ export class StaticToken implements TokenSource {
98
121
  token() {
99
122
  return Promise.resolve(this.value);
100
123
  }
101
- refresh(): Promise<string> {
124
+ refresh() {
102
125
  return Promise.reject(
103
- new Error(
126
+ new SignInError(
104
127
  "The access token was refused; pass a new --token or sign in without one"
105
128
  )
106
129
  );
107
130
  }
108
131
  }
109
132
 
110
- function base64Url(bytes: Uint8Array) {
111
- return Buffer.from(bytes).toString("base64url");
112
- }
133
+ /** Where a session keeps its token, read again before each refresh. */
134
+ type TokenStore = {
135
+ load(): StoredToken | undefined;
136
+ save(token: StoredToken): void;
137
+ /** Runs `task` while no other process refreshes from this store. */
138
+ locked<T>(task: () => Promise<T>): Promise<T>;
139
+ };
113
140
 
114
- async function pkce() {
115
- const verifier = base64Url(crypto.getRandomValues(new Uint8Array(32)));
141
+ /** A lock older than this was left by a process that ended mid-refresh. */
142
+ const STALE_LOCK_MS = 60_000;
116
143
 
117
- const challenge = base64Url(
118
- new Uint8Array(
119
- await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))
120
- )
121
- );
144
+ const existsError = z.object({ code: z.literal("EEXIST") });
145
+
146
+ /**
147
+ * Runs `task` holding `<path>.lock`, which only one process can create
148
+ * (O_EXCL): two imports refreshing at once would both send the same
149
+ * refresh token, and the workspace takes the second use as theft.
150
+ */
151
+ async function withFileLock<T>(path: string, task: () => Promise<T>) {
152
+ const lock = `${path}.lock`;
153
+ mkdirSync(dirname(path), { recursive: true });
122
154
 
123
- return { verifier, challenge };
155
+ for (;;) {
156
+ try {
157
+ closeSync(openSync(lock, "wx", 0o600));
158
+ break;
159
+ } catch (error) {
160
+ if (!existsError.safeParse(error).success) throw error;
161
+ }
162
+
163
+ const heldSince = statSync(lock, { throwIfNoEntry: false })?.mtimeMs;
164
+
165
+ if (heldSince !== undefined && Date.now() - heldSince > STALE_LOCK_MS) {
166
+ rmSync(lock, { force: true });
167
+ continue;
168
+ }
169
+
170
+ // oxlint-disable-next-line eslint/no-await-in-loop -- waits for the other process's refresh
171
+ await Bun.sleep(25);
172
+ }
173
+
174
+ try {
175
+ return await task();
176
+ } finally {
177
+ rmSync(lock, { force: true });
178
+ }
124
179
  }
125
180
 
126
181
  export function defaultCredentialsPath() {
@@ -132,7 +187,7 @@ export function defaultCredentialsPath() {
132
187
  }
133
188
 
134
189
  /** The stored tokens; a missing, unreadable or malformed file is an empty store (tokens are only a cache). */
135
- function readStore(path: string): Record<string, StoredToken> {
190
+ function readStore(path: string) {
136
191
  try {
137
192
  const store = storeSchema.safeParse(
138
193
  JSON.parse(readFileSync(path, "utf-8"))
@@ -156,7 +211,8 @@ export function openInBrowser(url: string) {
156
211
  process.platform === "darwin"
157
212
  ? ["open", url]
158
213
  : process.platform === "win32"
159
- ? ["cmd", "/c", "start", "", url]
214
+ ? // Not through cmd: its parser splits the URL at "&".
215
+ ["rundll32", "url.dll,FileProtocolHandler", url]
160
216
  : ["xdg-open", url];
161
217
 
162
218
  try {
@@ -170,6 +226,8 @@ export type LoginOptions = {
170
226
  /** The workspace's origin, e.g. https://mail.acme.com. */
171
227
  workspace: string;
172
228
  scopes: string[];
229
+ /** Module permissions to request only when the destination advertises them. */
230
+ optionalScopes?: string[];
173
231
  fetch?: Fetch;
174
232
  /** Shows the sign-in page; defaults to printing the URL and opening the browser. */
175
233
  openBrowser?: (url: string) => void | Promise<void>;
@@ -186,13 +244,16 @@ export class OAuthSession implements TokenSource {
186
244
  private readonly metadata: Metadata,
187
245
  private readonly resource: string,
188
246
  private readonly fetchImpl: Fetch,
189
- private readonly save: (token: StoredToken) => void
247
+ private readonly store: TokenStore
190
248
  ) {}
191
249
 
192
250
  get scopes() {
193
251
  return this.stored.scope.split(/\s+/u).filter(Boolean);
194
252
  }
195
253
 
254
+ /** The refresh in flight, which every request that needs one shares. */
255
+ private refreshing: Promise<string> | null = null;
256
+
196
257
  token() {
197
258
  if (Date.now() < this.stored.expiresAt - 30_000) {
198
259
  return Promise.resolve(this.stored.accessToken);
@@ -201,9 +262,48 @@ export class OAuthSession implements TokenSource {
201
262
  return this.refresh();
202
263
  }
203
264
 
204
- async refresh() {
265
+ /**
266
+ * One refresh at a time: the workspace rotates the refresh token and
267
+ * takes a second use of the old one as theft, ending the whole sign-in.
268
+ */
269
+ refresh(rejected?: string) {
270
+ if (rejected !== undefined && rejected !== this.stored.accessToken) {
271
+ return Promise.resolve(this.stored.accessToken);
272
+ }
273
+
274
+ // Another process refreshing from the same store waits for the lock,
275
+ // then reads what this one saved.
276
+ this.refreshing ??= this.store
277
+ .locked(() => this.exchange(rejected))
278
+ .finally(() => {
279
+ this.refreshing = null;
280
+ });
281
+
282
+ return this.refreshing;
283
+ }
284
+
285
+ private async exchange(rejected?: string) {
286
+ // Another import signed in with the same stored sign-in may have
287
+ // refreshed it since: its refresh token is the one that works now (the
288
+ // old one, used again, would end the sign-in for both), and its access
289
+ // token may still do.
290
+ const latest = this.store.load();
291
+
292
+ if (latest && latest.refreshToken !== this.stored.refreshToken) {
293
+ this.stored = latest;
294
+
295
+ if (
296
+ latest.accessToken !== rejected &&
297
+ Date.now() < latest.expiresAt - 30_000
298
+ ) {
299
+ return latest.accessToken;
300
+ }
301
+ }
302
+
205
303
  if (!this.stored.refreshToken) {
206
- throw new Error("The sign-in expired; run the command again to sign in");
304
+ throw new SignInError(
305
+ "The sign-in expired; run the command again to sign in"
306
+ );
207
307
  }
208
308
 
209
309
  const response = await this.fetchImpl(this.metadata.token_endpoint, {
@@ -217,15 +317,23 @@ export class OAuthSession implements TokenSource {
217
317
  }),
218
318
  });
219
319
 
320
+ // The workspace's own refusal ends the sign-in; a bad moment (a 5xx,
321
+ // the network) may pass, and the request that needed it is retried.
322
+ if (response.status >= 400 && response.status < 500) {
323
+ throw new SignInError(
324
+ `Could not refresh the sign-in: ${await refusal(response)}; run the command again to sign in`
325
+ );
326
+ }
327
+
220
328
  const body = await tokenResponse(response, "Could not refresh the sign-in");
221
329
  this.stored = tokenFrom(this.stored.clientId, body, this.stored);
222
- this.save(this.stored);
330
+ this.store.save(this.stored);
223
331
 
224
332
  return this.stored.accessToken;
225
333
  }
226
334
 
227
335
  /** A signed-in session: a stored one that still refreshes, else a browser sign-in. */
228
- static async login(options: LoginOptions): Promise<OAuthSession> {
336
+ static async login(options: LoginOptions) {
229
337
  const fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
230
338
  const log = options.log ?? ((message) => console.error(message));
231
339
  const { origin } = new URL(options.workspace);
@@ -249,19 +357,46 @@ export class OAuthSession implements TokenSource {
249
357
  }
250
358
 
251
359
  const metadata = parsedMetadata.data;
360
+
361
+ // Its endpoints are the workspace's own: the browser opens one, and a
362
+ // URL elsewhere (another host, file:) is never followed.
363
+ const elsewhere = [
364
+ metadata.authorization_endpoint,
365
+ metadata.token_endpoint,
366
+ metadata.registration_endpoint,
367
+ ].find((endpoint) => endpoint && URL.parse(endpoint)?.origin !== origin);
368
+
369
+ if (elsewhere) {
370
+ throw new Error(
371
+ `${origin} published an OAuth endpoint elsewhere (${elsewhere})`
372
+ );
373
+ }
374
+
252
375
  const resource = `${origin}/mcp`;
253
- const key = `${origin} ${[...options.scopes].sort().join(" ")}`;
376
+
377
+ const scopes = [
378
+ ...options.scopes,
379
+ ...(options.optionalScopes ?? []).filter((scope) =>
380
+ metadata.scopes_supported?.includes(scope)
381
+ ),
382
+ ];
383
+
384
+ const key = `${origin} ${scopes.toSorted().join(" ")}`;
254
385
 
255
386
  const path =
256
387
  options.credentialsPath === undefined
257
388
  ? defaultCredentialsPath()
258
389
  : options.credentialsPath;
259
390
 
260
- const save = (token: StoredToken) => {
261
- if (path) writeStore(path, { ...readStore(path), [key]: token });
391
+ const store: TokenStore = {
392
+ load: () => (path ? readStore(path)[key] : undefined),
393
+ save: (token) => {
394
+ if (path) writeStore(path, { ...readStore(path), [key]: token });
395
+ },
396
+ locked: (task) => (path ? withFileLock(path, task) : task()),
262
397
  };
263
398
 
264
- const stored = path && !options.fresh ? readStore(path)[key] : undefined;
399
+ const stored = options.fresh ? undefined : store.load();
265
400
 
266
401
  if (stored) {
267
402
  const session = new OAuthSession(
@@ -269,7 +404,7 @@ export class OAuthSession implements TokenSource {
269
404
  metadata,
270
405
  resource,
271
406
  fetchImpl,
272
- save
407
+ store
273
408
  );
274
409
 
275
410
  try {
@@ -281,138 +416,99 @@ export class OAuthSession implements TokenSource {
281
416
  }
282
417
  }
283
418
 
284
- if (!metadata.registration_endpoint) {
419
+ const registrationEndpoint = metadata.registration_endpoint;
420
+
421
+ if (!registrationEndpoint) {
285
422
  throw new Error(`${origin} does not let apps register themselves`);
286
423
  }
287
424
 
288
- const { verifier, challenge } = await pkce();
289
- const state = base64Url(crypto.getRandomValues(new Uint8Array(16)));
290
- let resolveCode!: (value: URLSearchParams) => void;
291
-
292
- const callback = new Promise<URLSearchParams>((resolve) => {
293
- resolveCode = resolve;
294
- });
295
-
296
- const server = Bun.serve({
297
- hostname: "127.0.0.1",
298
- port: 0,
299
- fetch(request) {
300
- const url = new URL(request.url);
301
-
302
- if (url.pathname !== "/callback") {
303
- return new Response("Not found", { status: 404 });
304
- }
425
+ let clientId = "";
426
+
427
+ const { code, redirectUri, verifier } = await loopbackSignIn({
428
+ what: "Sign-in",
429
+ path: "/callback",
430
+ issuer: metadata.issuer,
431
+ prompt: `Sign in to ${origin} in your browser:`,
432
+ openBrowser: options.openBrowser ?? openInBrowser,
433
+ log,
434
+ // The importer registers itself for this redirect, then asks.
435
+ authorizeUrl: async (redirect) => {
436
+ clientId = await registerImporter(
437
+ fetchImpl,
438
+ registrationEndpoint,
439
+ redirect,
440
+ scopes
441
+ );
305
442
 
306
- resolveCode(url.searchParams);
307
- const failed = url.searchParams.has("error");
443
+ const url = new URL(metadata.authorization_endpoint);
444
+ url.searchParams.set("client_id", clientId);
445
+ url.searchParams.set("scope", scopes.join(" "));
446
+ url.searchParams.set("resource", resource);
308
447
 
309
- return new Response(
310
- failed
311
- ? "Sign-in was not completed. You can close this tab."
312
- : "Signed in. You can close this tab and return to the terminal.",
313
- { headers: { "content-type": "text/plain; charset=utf-8" } }
314
- );
448
+ return url;
315
449
  },
316
450
  });
317
451
 
318
- try {
319
- const redirectUri = `http://127.0.0.1:${server.port}/callback`;
320
-
321
- const registration = await fetchImpl(metadata.registration_endpoint, {
322
- method: "POST",
323
- headers: { "content-type": "application/json" },
324
- body: JSON.stringify({
325
- client_name: "OpenWorkspace import",
326
- redirect_uris: [redirectUri],
327
- scope: options.scopes.join(" "),
328
- }),
329
- });
330
-
331
- if (!registration.ok) {
332
- throw new Error(
333
- `Could not register the importer: ${await refusal(registration)}`
334
- );
335
- }
336
-
337
- const registered = registrationSchema.safeParse(
338
- await registration.json()
339
- );
340
-
341
- if (!registered.success) {
342
- throw new Error(
343
- `Could not register the importer: ${registration.status} without a client_id`
344
- );
345
- }
346
-
347
- const client = registered.data;
348
-
349
- const authorize = new URL(metadata.authorization_endpoint);
350
-
351
- for (const [name, value] of Object.entries({
352
- response_type: "code",
353
- client_id: client.client_id,
452
+ const exchanged = await fetchImpl(metadata.token_endpoint, {
453
+ method: "POST",
454
+ headers: { "content-type": "application/x-www-form-urlencoded" },
455
+ body: new URLSearchParams({
456
+ grant_type: "authorization_code",
457
+ code,
354
458
  redirect_uri: redirectUri,
355
- code_challenge: challenge,
356
- code_challenge_method: "S256",
357
- scope: options.scopes.join(" "),
459
+ code_verifier: verifier,
460
+ client_id: clientId,
358
461
  resource,
359
- state,
360
- })) {
361
- authorize.searchParams.set(name, value);
362
- }
363
-
364
- log(`Sign in to ${origin} in your browser:\n ${authorize}`);
365
- await (options.openBrowser ?? openInBrowser)(authorize.toString());
366
-
367
- const params = await callback;
368
-
369
- if (params.get("error")) {
370
- throw new Error(
371
- `Sign-in failed: ${params.get("error_description") ?? params.get("error")}`
372
- );
373
- }
462
+ }),
463
+ });
374
464
 
375
- if (params.get("state") !== state) {
376
- throw new Error(
377
- "Sign-in failed: the response does not match this request"
378
- );
379
- }
465
+ const body = await tokenResponse(exchanged, "Sign-in failed");
466
+ const token = tokenFrom(clientId, body);
467
+ store.save(token);
380
468
 
381
- if (params.get("iss") && params.get("iss") !== metadata.issuer) {
382
- throw new Error(
383
- "Sign-in failed: the response came from another issuer"
384
- );
385
- }
469
+ return new OAuthSession(token, metadata, resource, fetchImpl, store);
470
+ }
471
+ }
386
472
 
387
- const exchanged = await fetchImpl(metadata.token_endpoint, {
388
- method: "POST",
389
- headers: { "content-type": "application/x-www-form-urlencoded" },
390
- body: new URLSearchParams({
391
- grant_type: "authorization_code",
392
- code: params.get("code") ?? "",
393
- redirect_uri: redirectUri,
394
- code_verifier: verifier,
395
- client_id: client.client_id,
396
- resource,
397
- }),
398
- });
473
+ /** Registers the importer (RFC 7591) for `redirectUri`; its client id. */
474
+ async function registerImporter(
475
+ fetchImpl: Fetch,
476
+ endpoint: string,
477
+ redirectUri: string,
478
+ scopes: string[]
479
+ ) {
480
+ const registration = await fetchImpl(endpoint, {
481
+ method: "POST",
482
+ headers: { "content-type": "application/json" },
483
+ body: JSON.stringify({
484
+ client_name: "OpenWorkspace import",
485
+ redirect_uris: [redirectUri],
486
+ scope: scopes.join(" "),
487
+ }),
488
+ });
489
+
490
+ if (!registration.ok) {
491
+ throw new Error(
492
+ `Could not register the importer: ${await refusal(registration)}`
493
+ );
494
+ }
399
495
 
400
- const body = await tokenResponse(exchanged, "Sign-in failed");
401
- const token = tokenFrom(client.client_id, body);
402
- save(token);
496
+ const registered = registrationSchema.safeParse(await registration.json());
403
497
 
404
- return new OAuthSession(token, metadata, resource, fetchImpl, save);
405
- } finally {
406
- server.stop(true);
407
- }
498
+ if (!registered.success) {
499
+ throw new Error(
500
+ `Could not register the importer: ${registration.status} without a client_id`
501
+ );
408
502
  }
503
+
504
+ return registered.data.client_id;
409
505
  }
410
506
 
411
507
  function tokenFrom(
412
508
  clientId: string,
413
509
  body: TokenResponse,
414
510
  previous?: StoredToken
415
- ): StoredToken {
511
+ ) {
416
512
  return {
417
513
  clientId,
418
514
  accessToken: body.access_token,
@@ -0,0 +1,48 @@
1
+ import type { ImportItem } from "./protocol.ts";
2
+
3
+ type PreviewItem =
4
+ | Pick<ImportItem, "placement" | "folder" | "seen">
5
+ | { skipped: string };
6
+
7
+ function addCount(map: Map<string, number>, key: string, count = 1) {
8
+ map.set(key, (map.get(key) ?? 0) + count);
9
+ }
10
+
11
+ /** The dry-run report needs counts, even when the mailbox spans several files. */
12
+ export class ImportPreview {
13
+ private readonly places = new Map<string, number>();
14
+ private readonly folders = new Map<string, number>();
15
+ private readonly skipped = new Map<string, number>();
16
+ private unread = 0;
17
+ private count = 0;
18
+
19
+ add(item: PreviewItem) {
20
+ this.count += 1;
21
+
22
+ if ("skipped" in item) {
23
+ addCount(this.skipped, item.skipped);
24
+
25
+ return;
26
+ }
27
+
28
+ addCount(this.places, item.placement);
29
+ this.addFolder(item.folder);
30
+
31
+ if (!item.seen) this.unread += 1;
32
+ }
33
+
34
+ addFolder(folder: string | null | undefined, count = 1) {
35
+ if (folder) addCount(this.folders, folder, count);
36
+ }
37
+
38
+ print(log: (message: string) => void, label: string) {
39
+ const list = (map: Map<string, number>) =>
40
+ [...map].map(([name, n]) => `${name} ${n}`).join(", ") || "none";
41
+
42
+ log(`${label}: ${this.count} messages`);
43
+ log(` places: ${list(this.places)}`);
44
+ log(` folders: ${list(this.folders)}`);
45
+ log(` unread: ${this.unread}`);
46
+ log(` skipped: ${list(this.skipped)}`);
47
+ }
48
+ }