@open-workspace/create 0.4.2 → 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
@@ -0,0 +1,159 @@
1
+ import { z } from "zod";
2
+
3
+ import { forEachConcurrent } from "../concurrency.ts";
4
+ import type { Fetch } from "../oauth.ts";
5
+ import { browserOrigins, emptyExport, person, team } from "./model.ts";
6
+ import { readPages } from "./pages.ts";
7
+
8
+ const profile = z.object({
9
+ firstName: z.string().nullish(),
10
+ lastName: z.string().nullish(),
11
+ email: z.string(),
12
+ });
13
+
14
+ const appSchema = z.object({
15
+ id: z.string(),
16
+ label: z.string(),
17
+ signOnMode: z.string(),
18
+ settings: z
19
+ .object({
20
+ signOn: z
21
+ .object({
22
+ audience: z.string().nullish(),
23
+ audienceOverride: z.string().nullish(),
24
+ ssoAcsUrlOverride: z.string().nullish(),
25
+ allowMultipleAcsEndpoints: z.boolean().nullish(),
26
+ ssoAcsUrl: z.string().nullish(),
27
+ })
28
+ .nullish(),
29
+ oauthClient: z
30
+ .object({
31
+ redirect_uris: z.array(z.string()).nullish(),
32
+ post_logout_redirect_uris: z.array(z.string()).nullish(),
33
+ application_type: z.string().nullish(),
34
+ })
35
+ .nullish(),
36
+ })
37
+ .nullish(),
38
+ credentials: z
39
+ .object({
40
+ oauthClient: z
41
+ .object({ token_endpoint_auth_method: z.string().nullish() })
42
+ .nullish(),
43
+ })
44
+ .nullish(),
45
+ });
46
+
47
+ export async function readOkta(org: string, token: string, fetchImpl: Fetch) {
48
+ const origin = new URL(org);
49
+
50
+ if (
51
+ origin.protocol !== "https:" ||
52
+ origin.username ||
53
+ origin.password ||
54
+ origin.pathname !== "/" ||
55
+ origin.search ||
56
+ origin.hash
57
+ ) {
58
+ throw new Error("Enter the HTTPS origin of your Okta organization.");
59
+ }
60
+
61
+ const list = <T>(path: string, schema: z.ZodType<T>) =>
62
+ readPages(
63
+ new URL(`/api/v1/${path}`, origin),
64
+ `SSWS ${token}`,
65
+ schema,
66
+ fetchImpl,
67
+ false
68
+ );
69
+
70
+ const [users, groups, apps] = await Promise.all([
71
+ list(
72
+ "users?limit=200",
73
+ z.object({ id: z.string(), profile, status: z.string() })
74
+ ),
75
+ list(
76
+ "groups?limit=200",
77
+ z.object({
78
+ id: z.string(),
79
+ type: z.string(),
80
+ profile: z.object({ name: z.string() }),
81
+ })
82
+ ),
83
+ list("apps?limit=200", appSchema),
84
+ ]);
85
+
86
+ const result = emptyExport();
87
+ const emails = new Map<string, string>();
88
+
89
+ for (const u of users) {
90
+ emails.set(u.id, u.profile.email);
91
+ result.directory.users.push(
92
+ person(
93
+ u.profile.email,
94
+ [u.profile.firstName, u.profile.lastName].filter(Boolean).join(" "),
95
+ u.status !== "ACTIVE"
96
+ )
97
+ );
98
+ }
99
+
100
+ const entries = groups
101
+ .filter((g) => g.type !== "BUILT_IN")
102
+ .map((g) => {
103
+ const group = team(`okta:${origin.host}:${g.id}`, g.profile.name);
104
+ result.directory.groups.push(group);
105
+
106
+ return { id: g.id, group };
107
+ });
108
+
109
+ await forEachConcurrent(entries, 4, async ({ id, group }) => {
110
+ const members = await list(
111
+ `groups/${encodeURIComponent(id)}/users?limit=200`,
112
+ z.object({ id: z.string() })
113
+ );
114
+
115
+ group.members = members.flatMap((u) => emails.get(u.id) ?? []);
116
+ });
117
+
118
+ for (const app of apps) {
119
+ const oidc = app.settings?.oauthClient;
120
+ const saml = app.settings?.signOn;
121
+
122
+ if (app.signOnMode === "OPENID_CONNECT" && oidc?.redirect_uris?.length) {
123
+ result.apps.push({
124
+ kind: "oidc",
125
+ sourceId: app.id,
126
+ name: app.label,
127
+ redirectUris: oidc.redirect_uris,
128
+ logoutUris: oidc.post_logout_redirect_uris ?? [],
129
+ allowedOrigins:
130
+ oidc.application_type === "browser"
131
+ ? browserOrigins(oidc.redirect_uris)
132
+ : undefined,
133
+ publicClient: app.credentials?.oauthClient?.token_endpoint_auth_method
134
+ ? app.credentials.oauthClient.token_endpoint_auth_method === "none"
135
+ : ["browser", "native"].includes(oidc.application_type ?? ""),
136
+ });
137
+ } else if (
138
+ app.signOnMode === "SAML_2_0" &&
139
+ saml?.audience &&
140
+ saml.ssoAcsUrl &&
141
+ !saml.allowMultipleAcsEndpoints &&
142
+ !saml.audienceOverride &&
143
+ !saml.ssoAcsUrlOverride
144
+ ) {
145
+ result.apps.push({
146
+ kind: "saml",
147
+ name: app.label,
148
+ entityId: saml.audience,
149
+ acsUrl: saml.ssoAcsUrl,
150
+ });
151
+ } else {
152
+ result.skipped.push(
153
+ `${app.label}: no portable ${app.signOnMode} settings`
154
+ );
155
+ }
156
+ }
157
+
158
+ return result;
159
+ }
@@ -0,0 +1,65 @@
1
+ import { z } from "zod";
2
+
3
+ import { readDirectoryPage } from "../directory/read.ts";
4
+ import type { Fetch } from "../oauth.ts";
5
+
6
+ /** Graph's nextLink and Okta's Link header are opaque. Credentials stay on the source origin. */
7
+ export async function readPages<T>(
8
+ url: URL,
9
+ authorization: string,
10
+ item: z.ZodType<T>,
11
+ fetchImpl: Fetch,
12
+ graph: boolean
13
+ ) {
14
+ const entries: T[] = [];
15
+ const { origin } = url;
16
+ let next: URL | undefined = url;
17
+ const seen = new Set<string>();
18
+
19
+ while (next) {
20
+ if (next.origin !== origin || seen.has(next.href)) {
21
+ throw new Error("Invalid directory pagination link");
22
+ }
23
+
24
+ seen.add(next.href);
25
+
26
+ // oxlint-disable-next-line no-await-in-loop -- the response supplies the next URL
27
+ const response = await readDirectoryPage(fetchImpl, next.href, {
28
+ headers: { authorization, accept: "application/json" },
29
+ redirect: "error",
30
+ });
31
+
32
+ if (!response.ok) {
33
+ throw new Error(
34
+ `Reading ${next.pathname} failed (HTTP ${response.status}). Check source permissions or retry later.`
35
+ );
36
+ }
37
+
38
+ // oxlint-disable-next-line no-await-in-loop -- parse this page before reading its continuation
39
+ const body: unknown = await response.json();
40
+
41
+ if (graph) {
42
+ const page = z
43
+ .object({
44
+ value: z.array(item),
45
+ "@odata.nextLink": z.string().optional(),
46
+ })
47
+ .parse(body);
48
+
49
+ entries.push(...page.value);
50
+ next = page["@odata.nextLink"]
51
+ ? new URL(page["@odata.nextLink"])
52
+ : undefined;
53
+ } else {
54
+ entries.push(...z.array(item).parse(body));
55
+
56
+ const href = /<([^>]+)>\s*;\s*rel="next"/u.exec(
57
+ response.headers.get("link") ?? ""
58
+ )?.[1];
59
+
60
+ next = href ? new URL(href, next) : undefined;
61
+ }
62
+ }
63
+
64
+ return entries;
65
+ }
@@ -5,18 +5,18 @@ import { parseCliArgs } from "./args.ts";
5
5
  import {
6
6
  commonOptions,
7
7
  connect,
8
- describeItems,
9
8
  jobs,
10
9
  placementList,
10
+ prepareImportJob,
11
11
  runJob,
12
12
  UsageError,
13
13
  } from "./cli.ts";
14
14
  import type { CliDeps, Job } from "./cli.ts";
15
15
  import { imapSource } from "./imap-source.ts";
16
16
  import type { ImapSourceOptions } from "./imap-source.ts";
17
+ import { ImportPreview } from "./preview.ts";
17
18
  import { MAIL_IMPORT_SCOPES } from "./protocol.ts";
18
- import { ResumeState } from "./uploader.ts";
19
- import type { UploadStats } from "./uploader.ts";
19
+ import type { RunStats } from "./uploader.ts";
20
20
 
21
21
  /**
22
22
  * `import imap`: one account (--user, --into) or many (--map rows of
@@ -79,7 +79,8 @@ export async function imapCommand(args: string[], deps: CliDeps) {
79
79
  ? null
80
80
  : await connect(values, MAIL_IMPORT_SCOPES, deps);
81
81
 
82
- const results: UploadStats[] = [];
82
+ const results: RunStats[] = [];
83
+ let rejectedAccounts = 0;
83
84
 
84
85
  const importAccount = async ({
85
86
  source: user,
@@ -111,16 +112,32 @@ export async function imapCommand(args: string[], deps: CliDeps) {
111
112
  disableAutoIdle: true,
112
113
  });
113
114
 
114
- await client.connect();
115
+ try {
116
+ await client.connect();
117
+ } catch (error) {
118
+ if (
119
+ !(error instanceof Error) ||
120
+ !("authenticationFailed" in error) ||
121
+ error.authenticationFailed !== true
122
+ ) {
123
+ throw error;
124
+ }
125
+
126
+ rejectedAccounts += 1;
127
+ log(`${user} → ${target}: IMAP authentication failed`);
128
+
129
+ return;
130
+ }
115
131
 
116
132
  try {
117
133
  const account = `${host}/${user}`;
118
- const job = `imap-${account}`;
119
134
 
120
- const state = workspace
121
- ? new ResumeState(
122
- values["state-dir"] ?? ".openworkspace-import",
123
- `${new URL(workspace.origin).host}-${(await workspace.importTarget(target)).id}-${job}`
135
+ const destination = workspace
136
+ ? await prepareImportJob(
137
+ workspace,
138
+ target,
139
+ `imap-${account}`,
140
+ values["state-dir"]
124
141
  )
125
142
  : null;
126
143
 
@@ -132,26 +149,27 @@ export async function imapCommand(args: string[], deps: CliDeps) {
132
149
  .filter(Boolean),
133
150
  skip,
134
151
  account,
135
- done: (sourceId) => state?.has(sourceId) ?? false,
152
+ done: (sourceId) => destination?.state.has(sourceId) ?? false,
136
153
  };
137
154
 
138
155
  const source = await imapSource(client, options);
139
156
  log(
140
- `${user}: ${source.total} messages${source.gmail ? " in All Mail (Gmail)" : ""}`
157
+ `${user}: ${source.total === null ? "reading" : source.total} messages${source.gmail ? " in All Mail (Gmail)" : ""}`
141
158
  );
142
159
 
143
- if (!workspace) {
144
- await describeItems(source.items, log, `${user} → ${target}`);
160
+ if (!destination) {
161
+ const preview = new ImportPreview();
162
+
163
+ for await (const item of source.preview) preview.add(item);
164
+ preview.print(log, `${user} → ${target}`);
145
165
 
146
166
  return;
147
167
  }
148
168
 
149
169
  results.push(
150
170
  await runJob({
151
- workspace,
152
- target,
171
+ ...destination,
153
172
  label: user,
154
- job,
155
173
  items: source.items,
156
174
  total: source.total,
157
175
  values,
@@ -168,7 +186,13 @@ export async function imapCommand(args: string[], deps: CliDeps) {
168
186
  await importAccount(job);
169
187
  }
170
188
 
171
- return results.some((stats) => stats.failed) ? 1 : 0;
189
+ if (values.map && rejectedAccounts) {
190
+ log(
191
+ `IMAP authentication failed for ${rejectedAccounts} of ${pairs.length} accounts.`
192
+ );
193
+ }
194
+
195
+ return rejectedAccounts > 0 || results.some((stats) => stats.failed) ? 1 : 0;
172
196
  }
173
197
 
174
198
  async function askPassword(user: string) {