@open-workspace/create 0.4.2 → 0.5.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.
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 +302 -72
  10. package/import/directory/google.ts +159 -121
  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 +167 -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 +161 -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 +8 -8
  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/README.md CHANGED
@@ -8,7 +8,8 @@ bun create @open-workspace
8
8
 
9
9
  It signs you in to Cloudflare, lets you pick the account, the mail domains and
10
10
  the hostname from your zones, writes the project, starts a git repository and
11
- deploys. It ends with the address to open and create the first administrator.
11
+ deploys. It prints the first sign-in steps and offers migration commands for
12
+ the source you choose.
12
13
  `--help` lists the flags for scripted runs.
13
14
 
14
15
  ## Adding a module
@@ -20,14 +21,17 @@ bunx @open-workspace/create module time-off
20
21
  Writes a module skeleton to `modules/time-off/` in a deployment's directory and
21
22
  adds it to `alchemy.run.ts`.
22
23
 
23
- ## Importing mail and people
24
+ ## Importing people, teams, SSO apps and mail
24
25
 
25
26
  ```sh
26
- bunx @open-workspace/create import mbox ~/Takeout/Mail --workspace https://mail.acme.com --into ada@acme.com
27
+ bunx @open-workspace/create import idp keycloak --file realm.json --workspace https://workspace.acme.com --dry-run
28
+ bunx @open-workspace/create import mbox ~/Takeout/Mail --workspace https://workspace.acme.com --into ada@acme.com
27
29
  ```
28
30
 
29
- Imports mail from an mbox file, a Google Takeout export or an IMAP account, and
30
- people and teams from a Google Workspace directory.
31
+ Import directories from Microsoft Entra ID, Okta, Keycloak, Google Workspace
32
+ or CSV. Supported OIDC and SAML apps are created disabled for administrator
33
+ review. Google SAML apps can be imported individually with service provider
34
+ metadata. Mail imports support mbox, Google Takeout and IMAP.
31
35
 
32
36
  ## Documentation
33
37
 
@@ -0,0 +1,110 @@
1
+ import { z } from "zod";
2
+
3
+ import {
4
+ listPostingPolicies,
5
+ mailboxDeliveries,
6
+ MAX_FORWARD_DESTINATIONS,
7
+ } from "./workspace";
8
+
9
+ const id = z.string().min(1).max(100);
10
+ const name = z.string().min(1).max(500);
11
+ const strings = z.array(z.string().max(2000)).max(100);
12
+
13
+ const accessTeams = z.array(
14
+ z.object({ teamId: id, sentAs: z.string().nullable() })
15
+ );
16
+
17
+ /** core.json as `import backup` sends it back. */
18
+ export const coreBackupSchema = z.object({
19
+ version: z.literal(4),
20
+ people: z.array(
21
+ z.object({
22
+ id,
23
+ name,
24
+ role: z.enum(["admin", "member"]),
25
+ status: z.enum(["invited", "active", "disabled"]),
26
+ permissions: strings,
27
+ })
28
+ ),
29
+ teams: z.array(
30
+ z.object({
31
+ id,
32
+ name,
33
+ slug: name,
34
+ description: z.string().max(2000).nullable(),
35
+ everyone: z.boolean(),
36
+ members: z.array(z.object({ userId: id, canSend: z.boolean() })),
37
+ })
38
+ ),
39
+ addresses: z.array(
40
+ z.object({
41
+ id,
42
+ address: z.string().min(3).max(320),
43
+ displayName: name,
44
+ ownerUserId: id.nullable(),
45
+ teamId: id.nullable(),
46
+ delivery: z.enum(mailboxDeliveries),
47
+ aliasOf: id.nullable(),
48
+ forwardTo: z
49
+ .array(z.string().max(320))
50
+ .max(MAX_FORWARD_DESTINATIONS)
51
+ .nullable(),
52
+ catchAll: z.boolean(),
53
+ listPosting: z.enum(listPostingPolicies),
54
+ isPrimary: z.boolean(),
55
+ })
56
+ ),
57
+ ssoApps: z.object({
58
+ oidc: z.array(
59
+ z.object({
60
+ id,
61
+ name,
62
+ clientType: z.enum(["public", "confidential"]),
63
+ redirectUris: strings,
64
+ postLogoutRedirectUris: strings,
65
+ backchannelLogoutUri: z.string().max(2000).nullable(),
66
+ allowedOrigins: strings,
67
+ allowedScopes: strings,
68
+ trusted: z.boolean(),
69
+ enabled: z.boolean(),
70
+ requirePkce: z.boolean(),
71
+ accessTeams,
72
+ })
73
+ ),
74
+ saml: z.array(
75
+ z.object({
76
+ id,
77
+ name,
78
+ entityId: z.string().min(1).max(2000),
79
+ acsUrl: z.string().min(1).max(2000),
80
+ nameIdFormat: z.enum(["email", "persistent"]),
81
+ emailAttributeName: name,
82
+ nameAttributeName: name,
83
+ groupsAttributeName: name.nullable(),
84
+ signResponse: z.boolean(),
85
+ requireSignedAuthnRequests: z.boolean(),
86
+ spSigningCertificate: z.string().max(20_000).nullable(),
87
+ allowIdpInitiated: z.boolean(),
88
+ firstNameAttributeName: name.nullable(),
89
+ lastNameAttributeName: name.nullable(),
90
+ enabled: z.boolean(),
91
+ accessTeams,
92
+ })
93
+ ),
94
+ }),
95
+ webhooks: z.array(
96
+ z.object({
97
+ id,
98
+ name,
99
+ url: z.string().min(1).max(2000),
100
+ events: strings,
101
+ mailboxIds: strings,
102
+ })
103
+ ),
104
+ branding: z.object({
105
+ name: z.string().max(200).nullable(),
106
+ logo: z.string().max(2_000_000).nullable(),
107
+ }),
108
+ });
109
+
110
+ export type CoreBackup = z.infer<typeof coreBackupSchema>;
@@ -0,0 +1,162 @@
1
+ /** Something an administrator can let a member manage. */
2
+ export type PermissionDefinition = {
3
+ /** Stable id stored with each person, e.g. "manage_people". */
4
+ id: string;
5
+ label: string;
6
+ description: string;
7
+ /**
8
+ * The OAuth scope that lets an app (an MCP client) use this permission
9
+ * for the person, e.g. "admin.people"; see shared/oidc.ts.
10
+ */
11
+ scope: string;
12
+ };
13
+
14
+ /**
15
+ * Parts of the workspace core lets an administrator hand to a member.
16
+ * Modules add theirs (`WorkspaceModule.permissions`). Administrators hold
17
+ * every permission; workspace settings and administrator promotion stay
18
+ * with administrators.
19
+ */
20
+ export const corePermissions = [
21
+ {
22
+ id: "manage_people",
23
+ scope: "admin.people",
24
+ label: "Manage people",
25
+ description:
26
+ "Invite people, edit members and their mailboxes, sign them out, and create recovery links.",
27
+ },
28
+ {
29
+ id: "manage_teams",
30
+ scope: "admin.teams",
31
+ label: "Manage teams",
32
+ description:
33
+ "Create teams, change who is in them, and manage their inboxes and mailing lists.",
34
+ },
35
+ {
36
+ id: "manage_webhooks",
37
+ scope: "admin.webhooks",
38
+ label: "Manage webhooks",
39
+ description: "Send workspace events to external systems.",
40
+ },
41
+ {
42
+ id: "manage_apps",
43
+ scope: "admin.apps",
44
+ label: "Manage SSO apps",
45
+ description:
46
+ "Configure OIDC and SAML applications that sign in with this workspace.",
47
+ },
48
+ ] as const satisfies readonly PermissionDefinition[];
49
+
50
+ export type CorePermission = (typeof corePermissions)[number]["id"];
51
+
52
+ /** A core permission, or one an installed module adds (e.g. "manage_blocked_senders"). */
53
+ export type WorkspacePermission = CorePermission | (string & {});
54
+
55
+ export function hasWorkspacePermission(
56
+ user: {
57
+ role: "admin" | "member";
58
+ permissions: readonly WorkspacePermission[];
59
+ },
60
+ permission: WorkspacePermission
61
+ ) {
62
+ return user.role === "admin" || user.permissions.includes(permission);
63
+ }
64
+
65
+ /**
66
+ * Where an address's mail goes: its own mailbox (inbox), every team member's
67
+ * own mailbox (list, team addresses only), another mailbox (alias), or
68
+ * outside addresses (forward).
69
+ */
70
+ export const mailboxDeliveries = ["inbox", "list", "alias", "forward"] as const;
71
+
72
+ /** Outside addresses one `forward` address may send each message on to. */
73
+ export const MAX_FORWARD_DESTINATIONS = 5;
74
+
75
+ export type MailboxDelivery = (typeof mailboxDeliveries)[number];
76
+
77
+ /** What an alias may deliver into: an address that takes mail itself. */
78
+ const ALIAS_TARGET_DELIVERIES = ["inbox", "list"] as const;
79
+
80
+ /** Whether an alias may deliver into an address delivering this way. */
81
+ export function isAliasTarget(delivery: MailboxDelivery) {
82
+ return ALIAS_TARGET_DELIVERIES.some((target) => target === delivery);
83
+ }
84
+
85
+ export const listPostingPolicies = ["anyone", "workspace", "members"] as const;
86
+
87
+ export type ListPostingPolicy = (typeof listPostingPolicies)[number];
88
+
89
+ export const listPostingCopy: Record<
90
+ ListPostingPolicy,
91
+ { label: string; description: string }
92
+ > = {
93
+ anyone: {
94
+ label: "Anyone",
95
+ description: "Any sender, including people outside the workspace.",
96
+ },
97
+ workspace: {
98
+ label: "Workspace",
99
+ description: "Only verified mail from the workspace's own addresses.",
100
+ },
101
+ members: {
102
+ label: "Members",
103
+ description: "Only verified mail from people on the team.",
104
+ },
105
+ };
106
+
107
+ /**
108
+ * The workspace logo an administrator uploads for the screens around signing
109
+ * in. Raster only: an SVG could carry script.
110
+ */
111
+ export const workspaceLogo = {
112
+ types: ["image/png", "image/jpeg", "image/webp"],
113
+ maxBytes: 1024 * 1024,
114
+ } as const;
115
+
116
+ /** Square sizes the logo is served at, as icons (favicon, Apple touch icon, app and notification icons). */
117
+ export const workspaceIconSizes = [64, 180, 192, 512] as const;
118
+
119
+ export type WorkspaceIconSize = (typeof workspaceIconSizes)[number];
120
+
121
+ /**
122
+ * Where a logo is served by its id, as uploaded or as a square icon of
123
+ * `size` pixels. Every upload gets a new id, so the URL is cacheable for good.
124
+ */
125
+ export function workspaceLogoPath(logoId: string, size?: WorkspaceIconSize) {
126
+ return `/api/workspace-logo/${logoId}${size ? `?size=${size}` : ""}`;
127
+ }
128
+
129
+ /**
130
+ * The current workspace icon at a size, for places that can't read the
131
+ * session check (the page's favicon link, the service worker): it redirects
132
+ * to the current logo's URL, or to the OpenWorkspace icon without a logo.
133
+ */
134
+ export function workspaceIconPath(size: WorkspaceIconSize) {
135
+ return `/api/workspace-logo/icon/${size}`;
136
+ }
137
+
138
+ /** The name an administrator gives the workspace, shown in the app's header and title. */
139
+ export const workspaceName = {
140
+ maxLength: 60,
141
+ } as const;
142
+
143
+ type Account = { role: string; permissions: readonly string[] };
144
+
145
+ /**
146
+ * Why `actor` may not act on `target`'s account (recovery and access links,
147
+ * status, profile, sessions, teams, personal mailboxes), or null if they
148
+ * may. Administrators may act on anyone; anyone else only on members whose
149
+ * permissions they hold themselves, so a delegate never reaches an account
150
+ * more powerful than their own. The server passes effective permissions.
151
+ */
152
+ export function userTargetRefusalReason(actor: Account, target: Account) {
153
+ if (actor.role === "admin") return null;
154
+
155
+ if (target.role === "admin") return "administrator";
156
+
157
+ return target.permissions.every((permission) =>
158
+ actor.permissions.includes(permission)
159
+ )
160
+ ? null
161
+ : "permissions";
162
+ }
@@ -0,0 +1,254 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
+ import { dirname, join, relative, sep } from "node:path";
3
+
4
+ import { z } from "zod";
5
+
6
+ /** A line's object and the line: 25 MiB of mail and room for the line. */
7
+ const MAX_OBJECT_BYTES = 25 * 1024 * 1024;
8
+
9
+ const objectName = /^([0-9a-f]{64})\.[a-z0-9]+$/u;
10
+
11
+ type LinePlace = { sourceId: string; module: string; folder: string };
12
+
13
+ /** One line of a module's part, ready to send. */
14
+ export type BackupLine = LinePlace & {
15
+ ordered: boolean;
16
+ parts: string[];
17
+ bytes: number;
18
+ body: Uint8Array<ArrayBuffer>;
19
+ };
20
+
21
+ /** A line, or why it can't be sent. */
22
+ export type BackupItem =
23
+ | BackupLine
24
+ | (LinePlace & { skipped: string; detail?: string });
25
+
26
+ export function sha256(data: Uint8Array | string) {
27
+ return new Bun.CryptoHasher("sha256").update(data).digest("hex");
28
+ }
29
+
30
+ /** Every .jsonl file under `dir`, sorted. */
31
+ function lineFiles(dir: string) {
32
+ return readdirSync(dir)
33
+ .toSorted()
34
+ .flatMap((entry) => {
35
+ const path = join(dir, entry);
36
+
37
+ if (!statSync(path).isDirectory()) {
38
+ return entry.endsWith(".jsonl") ? [path] : [];
39
+ }
40
+
41
+ const nested: string[] = lineFiles(path);
42
+
43
+ return nested;
44
+ });
45
+ }
46
+
47
+ const partList = z.object({ parts: z.array(z.object({ object: z.string() })) });
48
+
49
+ const emailFiles = z.object({
50
+ file: partList.optional(),
51
+ attachments: z.array(z.object({ file: partList })).optional(),
52
+ });
53
+
54
+ const moduleLine = z.object({
55
+ object: z.string().optional(),
56
+ kind: z.string().optional(),
57
+ });
58
+
59
+ function* snapshotLines(snapshot: string) {
60
+ const modules = readdirSync(snapshot)
61
+ .toSorted()
62
+ .filter((entry) => statSync(join(snapshot, entry)).isDirectory());
63
+
64
+ for (const module of modules) {
65
+ const root = join(snapshot, module);
66
+
67
+ for (const file of lineFiles(root)) {
68
+ const folder = dirname(relative(root, file)).split(sep).join("/");
69
+ const lines = readFileSync(file, "utf-8").split("\n");
70
+
71
+ for (const [index, text] of lines.entries()) {
72
+ if (text.trim()) {
73
+ yield { module, file: relative(root, file), folder, index, text };
74
+ }
75
+ }
76
+ }
77
+ }
78
+ }
79
+
80
+ function lineReferences(text: string, module: string) {
81
+ const json: unknown = JSON.parse(text);
82
+ const { object, kind } = moduleLine.parse(json);
83
+ const files = module === "email" ? emailFiles.parse(json) : {};
84
+
85
+ const parts = new Set(
86
+ [
87
+ ...(files.file?.parts ?? []),
88
+ ...(files.attachments ?? []).flatMap(
89
+ (attachment) => attachment.file.parts
90
+ ),
91
+ ].map((part) => part.object)
92
+ );
93
+
94
+ return { object, kind, parts };
95
+ }
96
+
97
+ function locateObject(dir: string, name: string) {
98
+ const hash = objectName.exec(name)?.[1];
99
+ const path = join(dir, name);
100
+
101
+ if (!hash || !existsSync(path)) return { problem: "missing" };
102
+
103
+ const { size } = statSync(path);
104
+
105
+ if (size > MAX_OBJECT_BYTES) return { problem: "too large" };
106
+
107
+ return { path, hash, size };
108
+ }
109
+
110
+ /** The preflight and the upload check the same bytes against the object name. */
111
+ function checkedBytes(path: string, hash: string) {
112
+ const bytes = readFileSync(path);
113
+
114
+ return sha256(bytes) === hash ? { bytes } : { problem: "damaged" };
115
+ }
116
+
117
+ export function readBackupObject(dir: string, name: string) {
118
+ const object = locateObject(dir, name);
119
+
120
+ if (object.problem !== undefined) {
121
+ return { problem: object.problem, bytes: undefined };
122
+ }
123
+
124
+ return checkedBytes(object.path, object.hash);
125
+ }
126
+
127
+ export function restoreBody(text: string, object?: Uint8Array) {
128
+ const line = new TextEncoder().encode(object ? `${text}\n` : text);
129
+
130
+ if (!object) return line;
131
+ const body = new Uint8Array(line.length + object.length);
132
+ body.set(line);
133
+ body.set(object, line.length);
134
+
135
+ return body;
136
+ }
137
+
138
+ /**
139
+ * Each module's lines in a snapshot, in order, each with its object read
140
+ * from `../objects/` and checked against its hash.
141
+ * @yields {BackupItem} Each line, or why it is skipped.
142
+ */
143
+ export function* backupItems(
144
+ snapshot: string,
145
+ onInvalid?: ((message: string) => void) | null,
146
+ verifyParts = true
147
+ ) {
148
+ const objects = join(snapshot, "..", "objects");
149
+
150
+ for (const { module, file, folder, index, text } of snapshotLines(snapshot)) {
151
+ // An unfinished snapshot may be recopied with a different line in this position.
152
+ const lineHash = sha256(text);
153
+ const sourceId = `${module}/${file}:${index + 1}:${lineHash}`;
154
+ const base = { sourceId, module, folder };
155
+
156
+ let refs: ReturnType<typeof lineReferences>;
157
+
158
+ try {
159
+ refs = lineReferences(text, module);
160
+ } catch (error) {
161
+ const message = `${module}/${file}:${index + 1}: invalid backup line`;
162
+
163
+ if (onInvalid === undefined) throw new Error(message, { cause: error });
164
+ onInvalid?.(message);
165
+ yield { ...base, skipped: "damaged" };
166
+ continue;
167
+ }
168
+
169
+ const parts: string[] = [];
170
+ let partBytes = 0;
171
+ let problem: string | undefined;
172
+ let failedObject = refs.object;
173
+
174
+ for (const part of refs.parts) {
175
+ const partFile = locateObject(objects, part);
176
+ problem = partFile.problem;
177
+
178
+ if (partFile.path && verifyParts) {
179
+ problem = checkedBytes(partFile.path, partFile.hash).problem;
180
+ }
181
+
182
+ if (!partFile.path || problem) {
183
+ failedObject = part;
184
+ break;
185
+ }
186
+
187
+ partBytes += partFile.size;
188
+ parts.push(partFile.path);
189
+ }
190
+
191
+ const object = refs.object
192
+ ? readBackupObject(objects, refs.object)
193
+ : undefined;
194
+
195
+ problem ??= object?.problem;
196
+
197
+ if (problem) {
198
+ yield {
199
+ ...base,
200
+ skipped: problem,
201
+ detail: `${module}/${file}:${index + 1}: ${problem} object ${failedObject}`,
202
+ };
203
+ continue;
204
+ }
205
+
206
+ yield {
207
+ ...base,
208
+ parts,
209
+ bytes:
210
+ partBytes +
211
+ Buffer.byteLength(text) +
212
+ (object?.bytes ? 1 + object.bytes.byteLength : 0),
213
+ ordered: module !== "email" || refs.kind !== undefined,
214
+ get body() {
215
+ return restoreBody(text, object?.bytes);
216
+ },
217
+ };
218
+ }
219
+ }
220
+
221
+ /** Check all local records before restore can create people, mailboxes or apps. */
222
+ export function inspectSnapshot(
223
+ snapshot: string,
224
+ expected: number | undefined,
225
+ log: (line: string) => void
226
+ ) {
227
+ const counts = new Map<string, number>();
228
+ let total = 0;
229
+ let incomplete = false;
230
+
231
+ for (const item of backupItems(snapshot, log)) {
232
+ total++;
233
+
234
+ const key =
235
+ "skipped" in item
236
+ ? `${item.module}: skipped (${item.skipped})`
237
+ : `${item.module}/${item.folder}`;
238
+
239
+ counts.set(key, (counts.get(key) ?? 0) + 1);
240
+
241
+ if ("skipped" in item) {
242
+ // One missing objects directory can affect every message in the snapshot.
243
+ if (counts.get(key) === 1 && "detail" in item) log(item.detail);
244
+ incomplete = true;
245
+ }
246
+ }
247
+
248
+ if (expected !== undefined && total !== expected) {
249
+ log(`Snapshot contains ${total} index records, expected ${expected}.`);
250
+ incomplete = true;
251
+ }
252
+
253
+ return { counts, incomplete };
254
+ }