@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
@@ -0,0 +1,244 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ import { z } from "zod";
4
+
5
+ import { failureKind, WorkspaceError } from "../workspace.ts";
6
+ import type { Workspace } from "../workspace.ts";
7
+ import type { ImportedApp } from "./model.ts";
8
+
9
+ export async function metadataApp(
10
+ workspace: Workspace,
11
+ path: string,
12
+ log: (line: string) => void
13
+ ) {
14
+ const { draft } = await workspace.json(
15
+ "/api/admin/saml-applications/parse-metadata",
16
+ z.object({
17
+ draft: z.object({
18
+ name: z.string().nullish(),
19
+ entityId: z.string(),
20
+ acsUrl: z.string(),
21
+ nameIdFormat: z.enum(["email", "persistent"]).nullable(),
22
+ requireSignedAuthnRequests: z.boolean(),
23
+ spSigningCertificate: z.string().nullable(),
24
+ warnings: z.array(z.string()),
25
+ }),
26
+ }),
27
+ { method: "POST", body: { xml: readFileSync(path, "utf-8") } }
28
+ );
29
+
30
+ for (const warning of draft.warnings) log(warning);
31
+
32
+ return {
33
+ kind: "saml",
34
+ name: (draft.name || draft.entityId).slice(0, 80),
35
+ entityId: draft.entityId,
36
+ acsUrl: draft.acsUrl,
37
+ nameIdFormat: draft.nameIdFormat ?? "email",
38
+ requireSignedAuthnRequests: draft.requireSignedAuthnRequests,
39
+ spSigningCertificate: draft.spSigningCertificate,
40
+ } satisfies ImportedApp;
41
+ }
42
+
43
+ type AppPlan = { apps: ImportedApp[]; rejected: string[] };
44
+
45
+ export const appStateSchema = z.object({
46
+ oidcClients: z.array(z.object({ name: z.string() })),
47
+ samlApplications: z.array(z.object({ entityId: z.string() })),
48
+ });
49
+
50
+ /** Provider assignments and policies require review. Every imported app starts disabled with no access teams. */
51
+ export async function planApps(
52
+ workspace: Workspace,
53
+ apps: ImportedApp[],
54
+ state: z.infer<typeof appStateSchema>,
55
+ log: (line: string) => void
56
+ ) {
57
+ const plan: AppPlan = {
58
+ apps: [],
59
+ rejected: [],
60
+ };
61
+
62
+ if (!apps.length) return plan;
63
+
64
+ const clients = new Set(state.oidcClients.map((c) => c.name));
65
+ const entities = new Set(state.samlApplications.map((a) => a.entityId));
66
+
67
+ for (const source of apps) {
68
+ let name = source.name.trim().slice(0, 80);
69
+
70
+ if (source.kind === "oidc") {
71
+ const id =
72
+ source.sourceId.length <= 40
73
+ ? source.sourceId
74
+ : new Bun.CryptoHasher("sha256")
75
+ .update(source.sourceId)
76
+ .digest("hex")
77
+ .slice(0, 16);
78
+
79
+ name = `${name.slice(0, 77 - id.length)} (${id})`;
80
+ }
81
+
82
+ const app = {
83
+ ...source,
84
+ name: name.length < 2 ? `${name || "SSO"} app` : name,
85
+ };
86
+
87
+ if (
88
+ app.kind === "oidc" &&
89
+ [...app.redirectUris, ...(app.logoutUris ?? [])].some((uri) =>
90
+ uri.includes("*")
91
+ )
92
+ ) {
93
+ log(
94
+ `Skipped ${app.name}: configure exact redirect URLs before importing`
95
+ );
96
+ continue;
97
+ }
98
+
99
+ const known = app.kind === "oidc" ? clients : entities;
100
+ const key = app.kind === "oidc" ? app.name : app.entityId;
101
+
102
+ if (known.has(key)) {
103
+ log(
104
+ `Skipped ${app.name}: ${app.kind === "oidc" ? "OIDC name" : "SAML entity ID"} already in use`
105
+ );
106
+ continue;
107
+ }
108
+
109
+ // A dedicated read-only endpoint also fails safely against an older workspace.
110
+ const request = registration(app);
111
+
112
+ try {
113
+ // oxlint-disable-next-line no-await-in-loop -- validate in source order
114
+ await workspace.call(`${request.path}/validate`, {
115
+ method: "POST",
116
+ body: request.body,
117
+ });
118
+ } catch (error) {
119
+ if (
120
+ error instanceof WorkspaceError &&
121
+ (error.status === 400 || error.status === 422)
122
+ ) {
123
+ plan.rejected.push(`${app.name}: ${error.message}`);
124
+ continue;
125
+ }
126
+
127
+ throw new Error(
128
+ `${app.name}: ${error instanceof Error ? error.message : String(error)}`,
129
+ { cause: error }
130
+ );
131
+ }
132
+
133
+ known.add(key);
134
+ plan.apps.push(app);
135
+ }
136
+
137
+ return plan;
138
+ }
139
+
140
+ export async function importApps(
141
+ workspace: Workspace,
142
+ plan: AppPlan,
143
+ dryRun: boolean,
144
+ log: (line: string) => void
145
+ ) {
146
+ for (const reason of plan.rejected) log(`Skipped ${reason}`);
147
+ let failures = plan.rejected.length;
148
+
149
+ if (!plan.apps.length) return failures;
150
+
151
+ for (const app of plan.apps) {
152
+ log(
153
+ `${dryRun ? "Would create" : "Creating"} disabled ${app.kind.toUpperCase()} app: ${app.name}`
154
+ );
155
+
156
+ if (app.kind === "saml" && app.nameIdWarning) log(` ${app.nameIdWarning}`);
157
+
158
+ if (dryRun) {
159
+ if (app.kind === "oidc") {
160
+ log(
161
+ ` ${app.publicClient ? "Public" : "Confidential"} client · Redirect: ${app.redirectUris.join(", ")}`
162
+ );
163
+
164
+ if (app.allowedOrigins?.length) {
165
+ log(` Browser origins: ${app.allowedOrigins.join(", ")}`);
166
+ }
167
+
168
+ if (app.logoutUris?.length) {
169
+ log(` Post-logout redirect: ${app.logoutUris.join(", ")}`);
170
+ }
171
+
172
+ if (app.backchannelLogoutUri) {
173
+ log(` Back-channel logout: ${app.backchannelLogoutUri}`);
174
+ }
175
+ } else {
176
+ log(
177
+ ` Entity ID: ${app.entityId} · ACS: ${app.acsUrl} · NameID: ${app.nameIdFormat ?? "email"}`
178
+ );
179
+ }
180
+
181
+ continue;
182
+ }
183
+
184
+ const request = registration(app);
185
+
186
+ try {
187
+ // oxlint-disable-next-line no-await-in-loop -- register in source order
188
+ await workspace.call(request.path, {
189
+ method: "POST",
190
+ body: request.body,
191
+ });
192
+ } catch (error) {
193
+ if (failureKind(error) !== "item") throw error;
194
+ failures++;
195
+ log(
196
+ `${app.name}: ${error instanceof Error ? error.message : String(error)}`
197
+ );
198
+ }
199
+ }
200
+
201
+ log(
202
+ "In Administration → Single sign-on apps, review access teams, claims and signing settings. Update each app's issuer, certificate or client ID. Generate a new secret for confidential clients before enabling them."
203
+ );
204
+
205
+ return failures;
206
+ }
207
+
208
+ function registration(app: ImportedApp) {
209
+ const base = { name: app.name, accessTeams: [], enabled: false };
210
+
211
+ if (app.kind === "oidc") {
212
+ return {
213
+ path: "/api/admin/oidc-clients",
214
+ body: {
215
+ ...base,
216
+ clientType: app.publicClient ? "public" : "confidential",
217
+ redirectUris: app.redirectUris,
218
+ postLogoutRedirectUris: app.logoutUris ?? [],
219
+ backchannelLogoutUri: app.backchannelLogoutUri,
220
+ allowedOrigins: app.allowedOrigins ?? [],
221
+ allowedScopes: ["openid", "profile", "email"],
222
+ requirePkce: true,
223
+ trusted: false,
224
+ },
225
+ };
226
+ }
227
+
228
+ return {
229
+ path: "/api/admin/saml-applications",
230
+ body: {
231
+ ...base,
232
+ entityId: app.entityId,
233
+ acsUrl: app.acsUrl,
234
+ nameIdFormat: app.nameIdFormat ?? "email",
235
+ emailAttributeName: "email",
236
+ nameAttributeName: "name",
237
+ groupsAttributeName: null,
238
+ signResponse: true,
239
+ requireSignedAuthnRequests: app.requireSignedAuthnRequests ?? false,
240
+ spSigningCertificate: app.spSigningCertificate ?? null,
241
+ allowIdpInitiated: false,
242
+ },
243
+ };
244
+ }
@@ -0,0 +1,161 @@
1
+ import * as p from "@clack/prompts";
2
+
3
+ import { parseCliArgs } from "../args.ts";
4
+ import { commonOptions, connect, UsageError } from "../cli.ts";
5
+ import type { CliDeps } from "../cli.ts";
6
+ import { importDirectory } from "../directory/command.ts";
7
+ import { workspaceStateSchema } from "../directory/plan.ts";
8
+ import { DIRECTORY_SCOPES } from "../protocol.ts";
9
+ import { appStateSchema, importApps, metadataApp, planApps } from "./apps.ts";
10
+ import { readDirectoryCsv } from "./csv.ts";
11
+ import { graphSignIn, readEntra } from "./entra.ts";
12
+ import { readKeycloak } from "./keycloak.ts";
13
+ import { readOkta } from "./okta.ts";
14
+
15
+ const HELP = `bunx @open-workspace/create import idp <source> --workspace <url> [--dry-run]
16
+ entra --tenant <directory ID> --client-id <public client ID>
17
+ okta --org <HTTPS origin> (OKTA_API_TOKEN or a hidden prompt)
18
+ keycloak --file <realm export including users>
19
+ csv --file <directory.csv> (header: type,name,email,groups)
20
+ saml --file <service provider metadata XML>
21
+
22
+ Invites people, creates teams and imports supported SSO apps disabled. Existing apps are skipped.
23
+ See https://openworkspace.dev/docs/migration for source permissions and the SSO cutover.`;
24
+
25
+ export async function idpCommand(args: string[], deps: CliDeps) {
26
+ const [source, ...rest] = args;
27
+
28
+ if (!source || ["--help", "-h"].includes(source)) {
29
+ console.log(HELP);
30
+
31
+ return source ? 0 : 1;
32
+ }
33
+
34
+ const { values } = parseCliArgs({
35
+ args: rest,
36
+ options: {
37
+ ...commonOptions,
38
+ file: { type: "string" },
39
+ org: { type: "string" },
40
+ tenant: { type: "string" },
41
+ "client-id": { type: "string" },
42
+ invites: { type: "string" },
43
+ },
44
+ });
45
+
46
+ if (values.help) {
47
+ console.log(HELP);
48
+
49
+ return 0;
50
+ }
51
+
52
+ const log = deps.log ?? console.error;
53
+ const fetchImpl = deps.fetch ?? fetch;
54
+ const dry = Boolean(values["dry-run"]);
55
+
56
+ const filename = () => {
57
+ if (!values.file) throw new UsageError("Pass --file");
58
+
59
+ return values.file;
60
+ };
61
+
62
+ if (source === "saml") {
63
+ const path = filename();
64
+
65
+ const workspace = await connect(
66
+ values,
67
+ ["people.read", "admin.apps", "offline_access"],
68
+ deps
69
+ );
70
+
71
+ const app = await metadataApp(workspace, path, log);
72
+ const state = await workspace.json("/api/admin/state", appStateSchema);
73
+ const planned = await planApps(workspace, [app], state, log);
74
+ const failures = await importApps(workspace, planned, dry, log);
75
+
76
+ return failures ? 1 : 0;
77
+ }
78
+
79
+ async function readSource() {
80
+ switch (source) {
81
+ case "csv": {
82
+ return readDirectoryCsv(filename());
83
+ }
84
+
85
+ case "keycloak": {
86
+ return readKeycloak(filename());
87
+ }
88
+
89
+ case "entra": {
90
+ const client = values["client-id"];
91
+
92
+ if (!values.tenant || !client) {
93
+ throw new UsageError(
94
+ "Pass --tenant and --client-id for the Entra public client"
95
+ );
96
+ }
97
+
98
+ const token = await graphSignIn(values.tenant, client, fetchImpl, log);
99
+
100
+ return readEntra(values.tenant, token, fetchImpl);
101
+ }
102
+
103
+ case "okta": {
104
+ if (!values.org) {
105
+ throw new UsageError("Pass --org https://your-organization.okta.com");
106
+ }
107
+
108
+ let token = process.env.OKTA_API_TOKEN;
109
+
110
+ if (!token) {
111
+ if (!process.stdin.isTTY) throw new UsageError("Set OKTA_API_TOKEN");
112
+
113
+ const entered = await p.password({
114
+ message: `Read-only API token for ${values.org}`,
115
+ });
116
+
117
+ if (p.isCancel(entered) || !entered) {
118
+ throw new UsageError("An Okta API token is required");
119
+ }
120
+
121
+ token = entered;
122
+ }
123
+
124
+ return readOkta(values.org, token, fetchImpl);
125
+ }
126
+
127
+ default: {
128
+ throw new UsageError(HELP);
129
+ }
130
+ }
131
+ }
132
+
133
+ const result = await readSource();
134
+
135
+ for (const skipped of result.skipped) log(`Skipped ${skipped}`);
136
+
137
+ const scopes = result.apps.length
138
+ ? [...DIRECTORY_SCOPES, "admin.apps"]
139
+ : DIRECTORY_SCOPES;
140
+
141
+ const workspace = await connect(values, scopes, deps);
142
+
143
+ const state = await workspace.json(
144
+ "/api/admin/state",
145
+ workspaceStateSchema.extend(appStateSchema.shape)
146
+ );
147
+
148
+ const planned = await planApps(workspace, result.apps, state, log);
149
+
150
+ const failed = await importDirectory(
151
+ result.directory,
152
+ workspace,
153
+ state,
154
+ values,
155
+ log
156
+ );
157
+
158
+ const appFailures = await importApps(workspace, planned, dry, log);
159
+
160
+ return failed || appFailures ? 1 : 0;
161
+ }
@@ -0,0 +1,70 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ import { z } from "zod";
4
+
5
+ import { parseCsv } from "../csv.ts";
6
+ import { emptyExport, person, team } from "./model.ts";
7
+
8
+ /** Each row names the groups it belongs to. Group names refer to explicit group rows. */
9
+ export function readDirectoryCsv(path: string) {
10
+ const [header, ...rows] = parseCsv(
11
+ readFileSync(path, "utf-8").replace(/^\uFEFF/u, "")
12
+ );
13
+
14
+ if (header?.join(",") !== "type,name,email,groups") {
15
+ throw new Error("Expected CSV header: type,name,email,groups");
16
+ }
17
+
18
+ const result = emptyExport();
19
+ const groups = new Map<string, ReturnType<typeof team>>();
20
+ const members: { id: string; parents: string[] }[] = [];
21
+ const emails = new Set<string>();
22
+
23
+ for (const [index, row] of rows.entries()) {
24
+ const [type, name, email = "", parents = ""] = row;
25
+
26
+ if (row.length !== 4 || !name || !["user", "group"].includes(type ?? "")) {
27
+ throw new Error(
28
+ `Invalid type, name or field count on CSV row ${index + 2}`
29
+ );
30
+ }
31
+
32
+ if (
33
+ (type === "user" || email) &&
34
+ (!z.email().safeParse(email).success || emails.has(email.toLowerCase()))
35
+ ) {
36
+ throw new Error(`Invalid or duplicate email on CSV row ${index + 2}`);
37
+ }
38
+
39
+ if (email) emails.add(email.toLowerCase());
40
+ let id = email;
41
+
42
+ if (type === "user") result.directory.users.push(person(email, name));
43
+ else {
44
+ if (groups.has(name)) throw new Error(`Duplicate CSV group: ${name}`);
45
+ const group = team(`csv:${name}`, name, email);
46
+ id = group.key ?? group.email;
47
+ groups.set(name, group);
48
+ result.directory.groups.push(group);
49
+ }
50
+
51
+ members.push({
52
+ id,
53
+ parents: parents
54
+ .split(";")
55
+ .map((v) => v.trim())
56
+ .filter(Boolean),
57
+ });
58
+ }
59
+
60
+ for (const { id, parents } of members) {
61
+ for (const parent of parents) {
62
+ const group = groups.get(parent);
63
+
64
+ if (!group) throw new Error(`Unknown CSV group: ${parent}`);
65
+ group.members.push(id);
66
+ }
67
+ }
68
+
69
+ return result;
70
+ }