@open-workspace/create 0.3.0 → 0.4.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.
- package/README.md +29 -6
- package/create.ts +86 -0
- package/import/args.ts +57 -0
- package/import/cli.ts +432 -0
- package/import/concurrency.ts +52 -0
- package/import/csv.ts +56 -0
- package/import/directory/command.ts +320 -0
- package/import/directory/google.ts +510 -0
- package/import/directory/plan.ts +367 -0
- package/import/gmail.ts +195 -0
- package/import/headers.ts +105 -0
- package/import/imap-command.ts +182 -0
- package/import/imap-source.ts +397 -0
- package/import/invariant.ts +22 -0
- package/import/mbox-source.ts +174 -0
- package/import/mbox.ts +198 -0
- package/import/oauth.ts +423 -0
- package/import/protocol.ts +59 -0
- package/import/uploader.ts +235 -0
- package/import/workspace.ts +218 -0
- package/index.ts +13 -115
- package/module-templates.ts +409 -0
- package/module.ts +105 -0
- package/package.json +18 -6
- package/setup/alchemy-helper.ts +258 -0
- package/setup/alchemy-protocol.ts +63 -0
- package/setup/alchemy.ts +163 -0
- package/setup/args.ts +128 -0
- package/setup/cloudflare-api.ts +156 -0
- package/setup/domains.ts +102 -0
- package/setup/flow.ts +987 -0
- package/setup/ui.ts +146 -0
- package/templates.ts +201 -126
package/import/oauth.ts
ADDED
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Signing in to a workspace the way an MCP client does: self-registration
|
|
9
|
+
* (RFC 7591) with a loopback redirect, the authorization code flow with
|
|
10
|
+
* PKCE, a token for the workspace's /mcp resource (which its /api accepts),
|
|
11
|
+
* and refresh tokens. Tokens are kept in ~/.config/open-workspace so a
|
|
12
|
+
* long or resumed import does not sign in again.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export type Fetch = (input: string, init?: RequestInit) => Promise<Response>;
|
|
16
|
+
|
|
17
|
+
const metadataSchema = z.object({
|
|
18
|
+
issuer: z.string(),
|
|
19
|
+
authorization_endpoint: z.string(),
|
|
20
|
+
token_endpoint: z.string(),
|
|
21
|
+
registration_endpoint: z.string().optional(),
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
type Metadata = z.infer<typeof metadataSchema>;
|
|
25
|
+
|
|
26
|
+
const storedTokenSchema = z.object({
|
|
27
|
+
clientId: z.string(),
|
|
28
|
+
accessToken: z.string(),
|
|
29
|
+
refreshToken: z.string().optional(),
|
|
30
|
+
expiresAt: z.number(),
|
|
31
|
+
scope: z.string(),
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
type StoredToken = z.infer<typeof storedTokenSchema>;
|
|
35
|
+
|
|
36
|
+
const storeSchema = z.record(z.string(), storedTokenSchema);
|
|
37
|
+
|
|
38
|
+
/** An OAuth error response (RFC 6749 section 5.2); every field is optional so any body parses. */
|
|
39
|
+
const oauthErrorSchema = z.object({
|
|
40
|
+
error: z.string().optional(),
|
|
41
|
+
error_description: z.string().optional(),
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
/** A successful token response (RFC 6749 section 5.1). */
|
|
45
|
+
const tokenResponseSchema = z.object({
|
|
46
|
+
access_token: z.string(),
|
|
47
|
+
refresh_token: z.string().optional(),
|
|
48
|
+
expires_in: z.coerce.number().optional(),
|
|
49
|
+
scope: z.string().optional(),
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
type TokenResponse = z.infer<typeof tokenResponseSchema>;
|
|
53
|
+
|
|
54
|
+
const registrationSchema = z.object({ client_id: z.string().min(1) });
|
|
55
|
+
|
|
56
|
+
/** Why the authorization server refused: its error description, its error code, or the HTTP status. */
|
|
57
|
+
async function refusal(response: Response) {
|
|
58
|
+
// A refusal need not have a JSON body; then only the status explains it.
|
|
59
|
+
const body = oauthErrorSchema.safeParse(
|
|
60
|
+
await response.json().catch(() => null)
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
const error = body.success ? body.data : {};
|
|
64
|
+
|
|
65
|
+
return error.error_description ?? error.error ?? response.status;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** A token response, or an error that says why the server refused (`what` names the step). */
|
|
69
|
+
async function tokenResponse(response: Response, what: string) {
|
|
70
|
+
if (!response.ok) {
|
|
71
|
+
throw new Error(`${what}: ${await refusal(response)}`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const body = tokenResponseSchema.safeParse(await response.json());
|
|
75
|
+
|
|
76
|
+
if (!body.success) {
|
|
77
|
+
throw new Error(`${what}: the token response is malformed`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return body.data;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export type TokenSource = {
|
|
84
|
+
/** A current access token. */
|
|
85
|
+
token(): Promise<string>;
|
|
86
|
+
/** A new access token after the workspace refused the last one. */
|
|
87
|
+
refresh(): Promise<string>;
|
|
88
|
+
/** The scopes the workspace granted. */
|
|
89
|
+
readonly scopes: string[];
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
/** An access token given on the command line; it cannot be refreshed. */
|
|
93
|
+
export class StaticToken implements TokenSource {
|
|
94
|
+
constructor(
|
|
95
|
+
private readonly value: string,
|
|
96
|
+
readonly scopes: string[] = []
|
|
97
|
+
) {}
|
|
98
|
+
token() {
|
|
99
|
+
return Promise.resolve(this.value);
|
|
100
|
+
}
|
|
101
|
+
refresh(): Promise<string> {
|
|
102
|
+
return Promise.reject(
|
|
103
|
+
new Error(
|
|
104
|
+
"The access token was refused; pass a new --token or sign in without one"
|
|
105
|
+
)
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function base64Url(bytes: Uint8Array) {
|
|
111
|
+
return Buffer.from(bytes).toString("base64url");
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function pkce() {
|
|
115
|
+
const verifier = base64Url(crypto.getRandomValues(new Uint8Array(32)));
|
|
116
|
+
|
|
117
|
+
const challenge = base64Url(
|
|
118
|
+
new Uint8Array(
|
|
119
|
+
await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))
|
|
120
|
+
)
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
return { verifier, challenge };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function defaultCredentialsPath() {
|
|
127
|
+
return join(
|
|
128
|
+
process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"),
|
|
129
|
+
"open-workspace",
|
|
130
|
+
"credentials.json"
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** 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> {
|
|
136
|
+
try {
|
|
137
|
+
const store = storeSchema.safeParse(
|
|
138
|
+
JSON.parse(readFileSync(path, "utf-8"))
|
|
139
|
+
);
|
|
140
|
+
|
|
141
|
+
return store.success ? store.data : {};
|
|
142
|
+
} catch {
|
|
143
|
+
return {};
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function writeStore(path: string, store: Record<string, StoredToken>) {
|
|
148
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
149
|
+
writeFileSync(path, JSON.stringify(store, null, 2), { mode: 0o600 });
|
|
150
|
+
chmodSync(path, 0o600);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Opens a URL in the default browser, best effort. */
|
|
154
|
+
export function openInBrowser(url: string) {
|
|
155
|
+
const command =
|
|
156
|
+
process.platform === "darwin"
|
|
157
|
+
? ["open", url]
|
|
158
|
+
: process.platform === "win32"
|
|
159
|
+
? ["cmd", "/c", "start", "", url]
|
|
160
|
+
: ["xdg-open", url];
|
|
161
|
+
|
|
162
|
+
try {
|
|
163
|
+
Bun.spawn(command, { stdout: "ignore", stderr: "ignore" });
|
|
164
|
+
} catch {
|
|
165
|
+
// The URL is printed too.
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export type LoginOptions = {
|
|
170
|
+
/** The workspace's origin, e.g. https://mail.acme.com. */
|
|
171
|
+
workspace: string;
|
|
172
|
+
scopes: string[];
|
|
173
|
+
fetch?: Fetch;
|
|
174
|
+
/** Shows the sign-in page; defaults to printing the URL and opening the browser. */
|
|
175
|
+
openBrowser?: (url: string) => void | Promise<void>;
|
|
176
|
+
/** Where tokens are kept; null keeps them in memory only. */
|
|
177
|
+
credentialsPath?: string | null;
|
|
178
|
+
/** Sign in again even with a stored token. */
|
|
179
|
+
fresh?: boolean;
|
|
180
|
+
log?: (message: string) => void;
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
export class OAuthSession implements TokenSource {
|
|
184
|
+
private constructor(
|
|
185
|
+
private stored: StoredToken,
|
|
186
|
+
private readonly metadata: Metadata,
|
|
187
|
+
private readonly resource: string,
|
|
188
|
+
private readonly fetchImpl: Fetch,
|
|
189
|
+
private readonly save: (token: StoredToken) => void
|
|
190
|
+
) {}
|
|
191
|
+
|
|
192
|
+
get scopes() {
|
|
193
|
+
return this.stored.scope.split(/\s+/u).filter(Boolean);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
token() {
|
|
197
|
+
if (Date.now() < this.stored.expiresAt - 30_000) {
|
|
198
|
+
return Promise.resolve(this.stored.accessToken);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return this.refresh();
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async refresh() {
|
|
205
|
+
if (!this.stored.refreshToken) {
|
|
206
|
+
throw new Error("The sign-in expired; run the command again to sign in");
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const response = await this.fetchImpl(this.metadata.token_endpoint, {
|
|
210
|
+
method: "POST",
|
|
211
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
212
|
+
body: new URLSearchParams({
|
|
213
|
+
grant_type: "refresh_token",
|
|
214
|
+
refresh_token: this.stored.refreshToken,
|
|
215
|
+
client_id: this.stored.clientId,
|
|
216
|
+
resource: this.resource,
|
|
217
|
+
}),
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
const body = await tokenResponse(response, "Could not refresh the sign-in");
|
|
221
|
+
this.stored = tokenFrom(this.stored.clientId, body, this.stored);
|
|
222
|
+
this.save(this.stored);
|
|
223
|
+
|
|
224
|
+
return this.stored.accessToken;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** A signed-in session: a stored one that still refreshes, else a browser sign-in. */
|
|
228
|
+
static async login(options: LoginOptions): Promise<OAuthSession> {
|
|
229
|
+
const fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
|
|
230
|
+
const log = options.log ?? ((message) => console.error(message));
|
|
231
|
+
const { origin } = new URL(options.workspace);
|
|
232
|
+
|
|
233
|
+
const metadataResponse = await fetchImpl(
|
|
234
|
+
`${origin}/.well-known/oauth-authorization-server`
|
|
235
|
+
);
|
|
236
|
+
|
|
237
|
+
if (!metadataResponse.ok) {
|
|
238
|
+
throw new Error(
|
|
239
|
+
`${origin} does not look like an OpenWorkspace (no OAuth metadata)`
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const parsedMetadata = metadataSchema.safeParse(
|
|
244
|
+
await metadataResponse.json()
|
|
245
|
+
);
|
|
246
|
+
|
|
247
|
+
if (!parsedMetadata.success) {
|
|
248
|
+
throw new Error(`${origin} published malformed OAuth metadata`);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const metadata = parsedMetadata.data;
|
|
252
|
+
const resource = `${origin}/mcp`;
|
|
253
|
+
const key = `${origin} ${[...options.scopes].sort().join(" ")}`;
|
|
254
|
+
|
|
255
|
+
const path =
|
|
256
|
+
options.credentialsPath === undefined
|
|
257
|
+
? defaultCredentialsPath()
|
|
258
|
+
: options.credentialsPath;
|
|
259
|
+
|
|
260
|
+
const save = (token: StoredToken) => {
|
|
261
|
+
if (path) writeStore(path, { ...readStore(path), [key]: token });
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
const stored = path && !options.fresh ? readStore(path)[key] : undefined;
|
|
265
|
+
|
|
266
|
+
if (stored) {
|
|
267
|
+
const session = new OAuthSession(
|
|
268
|
+
stored,
|
|
269
|
+
metadata,
|
|
270
|
+
resource,
|
|
271
|
+
fetchImpl,
|
|
272
|
+
save
|
|
273
|
+
);
|
|
274
|
+
|
|
275
|
+
try {
|
|
276
|
+
await session.token();
|
|
277
|
+
|
|
278
|
+
return session;
|
|
279
|
+
} catch {
|
|
280
|
+
// Fall through to a new sign-in.
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
if (!metadata.registration_endpoint) {
|
|
285
|
+
throw new Error(`${origin} does not let apps register themselves`);
|
|
286
|
+
}
|
|
287
|
+
|
|
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
|
+
}
|
|
305
|
+
|
|
306
|
+
resolveCode(url.searchParams);
|
|
307
|
+
const failed = url.searchParams.has("error");
|
|
308
|
+
|
|
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
|
+
);
|
|
315
|
+
},
|
|
316
|
+
});
|
|
317
|
+
|
|
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,
|
|
354
|
+
redirect_uri: redirectUri,
|
|
355
|
+
code_challenge: challenge,
|
|
356
|
+
code_challenge_method: "S256",
|
|
357
|
+
scope: options.scopes.join(" "),
|
|
358
|
+
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
|
+
}
|
|
374
|
+
|
|
375
|
+
if (params.get("state") !== state) {
|
|
376
|
+
throw new Error(
|
|
377
|
+
"Sign-in failed: the response does not match this request"
|
|
378
|
+
);
|
|
379
|
+
}
|
|
380
|
+
|
|
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
|
+
}
|
|
386
|
+
|
|
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
|
+
});
|
|
399
|
+
|
|
400
|
+
const body = await tokenResponse(exchanged, "Sign-in failed");
|
|
401
|
+
const token = tokenFrom(client.client_id, body);
|
|
402
|
+
save(token);
|
|
403
|
+
|
|
404
|
+
return new OAuthSession(token, metadata, resource, fetchImpl, save);
|
|
405
|
+
} finally {
|
|
406
|
+
server.stop(true);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function tokenFrom(
|
|
412
|
+
clientId: string,
|
|
413
|
+
body: TokenResponse,
|
|
414
|
+
previous?: StoredToken
|
|
415
|
+
): StoredToken {
|
|
416
|
+
return {
|
|
417
|
+
clientId,
|
|
418
|
+
accessToken: body.access_token,
|
|
419
|
+
refreshToken: body.refresh_token ?? previous?.refreshToken,
|
|
420
|
+
expiresAt: Date.now() + (body.expires_in ?? 600) * 1000,
|
|
421
|
+
scope: body.scope ?? previous?.scope ?? "",
|
|
422
|
+
};
|
|
423
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The workspace's import API (@open-workspace/email, worker/mail/import-routes.ts).
|
|
5
|
+
* Kept here, not imported, so the CLI does not depend on the mail module.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** The largest message the workspace accepts (MAX_IMPORT_MESSAGE_BYTES). */
|
|
9
|
+
export const MAX_IMPORT_MESSAGE_BYTES = 25 * 1024 * 1024;
|
|
10
|
+
|
|
11
|
+
export const placementSchema = z.enum([
|
|
12
|
+
"inbox",
|
|
13
|
+
"archive",
|
|
14
|
+
"spam",
|
|
15
|
+
"trash",
|
|
16
|
+
"sent",
|
|
17
|
+
]);
|
|
18
|
+
|
|
19
|
+
export type Placement = z.infer<typeof placementSchema>;
|
|
20
|
+
|
|
21
|
+
/** One message to import and where it goes. */
|
|
22
|
+
export type ImportItem = {
|
|
23
|
+
/** Stable id at the source; the workspace imports each once. */
|
|
24
|
+
sourceId: string;
|
|
25
|
+
raw: Uint8Array<ArrayBuffer>;
|
|
26
|
+
placement: Placement;
|
|
27
|
+
folder?: string | null;
|
|
28
|
+
seen?: boolean;
|
|
29
|
+
thread?: string;
|
|
30
|
+
receivedAt?: number;
|
|
31
|
+
direction?: "incoming" | "outgoing";
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** A message the reader could not hand over (too large, unreadable). */
|
|
35
|
+
export type SkippedItem = { sourceId: string; skipped: string };
|
|
36
|
+
|
|
37
|
+
export const importTargetSchema = z.object({
|
|
38
|
+
id: z.string(),
|
|
39
|
+
address: z.string(),
|
|
40
|
+
displayName: z.string(),
|
|
41
|
+
kind: z.enum(["personal", "shared"]),
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
export type ImportTarget = z.infer<typeof importTargetSchema>;
|
|
45
|
+
|
|
46
|
+
/** OAuth scopes the CLI asks for: import (own mailboxes, or any), and refresh tokens. */
|
|
47
|
+
export const MAIL_IMPORT_SCOPES = [
|
|
48
|
+
"mail.organize",
|
|
49
|
+
"admin.import_mail",
|
|
50
|
+
"offline_access",
|
|
51
|
+
];
|
|
52
|
+
|
|
53
|
+
/** For the directory import: people, teams and their mailboxes. */
|
|
54
|
+
export const DIRECTORY_SCOPES = [
|
|
55
|
+
"people.read",
|
|
56
|
+
"admin.people",
|
|
57
|
+
"admin.teams",
|
|
58
|
+
"offline_access",
|
|
59
|
+
];
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
import { forEachConcurrent } from "./concurrency.ts";
|
|
5
|
+
import { MAX_IMPORT_MESSAGE_BYTES } from "./protocol.ts";
|
|
6
|
+
import type { ImportItem, SkippedItem } from "./protocol.ts";
|
|
7
|
+
import { WorkspaceError } from "./workspace.ts";
|
|
8
|
+
import type { Workspace } from "./workspace.ts";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* What a run already did, so it can resume: one file of imported source
|
|
12
|
+
* ids (appended as each message lands) and one of failures, per import job.
|
|
13
|
+
* Failed messages are tried again on the next run.
|
|
14
|
+
*/
|
|
15
|
+
export class ResumeState {
|
|
16
|
+
private readonly done = new Set<string>();
|
|
17
|
+
private readonly donePath: string;
|
|
18
|
+
private readonly failedPath: string;
|
|
19
|
+
|
|
20
|
+
constructor(directory: string, job: string) {
|
|
21
|
+
mkdirSync(directory, { recursive: true });
|
|
22
|
+
const name = job.replaceAll(/[^a-zA-Z0-9._@-]+/gu, "_").slice(0, 120);
|
|
23
|
+
this.donePath = join(directory, `${name}.done`);
|
|
24
|
+
this.failedPath = join(directory, `${name}.failed.jsonl`);
|
|
25
|
+
|
|
26
|
+
if (existsSync(this.donePath)) {
|
|
27
|
+
for (const line of readFileSync(this.donePath, "utf-8").split("\n")) {
|
|
28
|
+
if (line) this.done.add(line);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
get size() {
|
|
34
|
+
return this.done.size;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
has(sourceId: string) {
|
|
38
|
+
return this.done.has(sourceId);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
add(sourceId: string) {
|
|
42
|
+
if (this.done.has(sourceId)) return;
|
|
43
|
+
this.done.add(sourceId);
|
|
44
|
+
appendFileSync(this.donePath, `${sourceId}\n`);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
fail(sourceId: string, reason: string) {
|
|
48
|
+
appendFileSync(
|
|
49
|
+
this.failedPath,
|
|
50
|
+
`${JSON.stringify({ sourceId, reason, at: new Date().toISOString() })}\n`
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
get failuresPath() {
|
|
55
|
+
return this.failedPath;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export type UploadStats = {
|
|
60
|
+
/** Messages the source has, when it was counted first. */
|
|
61
|
+
total: number | null;
|
|
62
|
+
seen: number;
|
|
63
|
+
imported: number;
|
|
64
|
+
duplicate: number;
|
|
65
|
+
/** Already imported by an earlier run. */
|
|
66
|
+
resumed: number;
|
|
67
|
+
skipped: number;
|
|
68
|
+
failed: number;
|
|
69
|
+
bytes: number;
|
|
70
|
+
/** Labels that could not become folders (the folder limit, or a system folder's name). */
|
|
71
|
+
folderSkipped: number;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/** Errors worth trying again: the network, rate limits, the server having a bad moment. */
|
|
75
|
+
function retryable(cause: unknown) {
|
|
76
|
+
if (cause instanceof WorkspaceError) {
|
|
77
|
+
return cause.status === 429 || cause.status >= 500;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Errors that end the run: every message would fail the same way. */
|
|
84
|
+
function fatal(cause: unknown) {
|
|
85
|
+
return (
|
|
86
|
+
cause instanceof WorkspaceError && [401, 403, 404].includes(cause.status)
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** What the uploader needs from the workspace; tests give a stand-in. */
|
|
91
|
+
export type ImportDestination = Pick<
|
|
92
|
+
Workspace,
|
|
93
|
+
"importMessage" | "finishImport"
|
|
94
|
+
>;
|
|
95
|
+
|
|
96
|
+
export type UploadOptions = {
|
|
97
|
+
workspace: ImportDestination;
|
|
98
|
+
mailboxId: string;
|
|
99
|
+
items:
|
|
100
|
+
| AsyncIterable<ImportItem | SkippedItem>
|
|
101
|
+
| Iterable<ImportItem | SkippedItem>;
|
|
102
|
+
state: ResumeState;
|
|
103
|
+
/** Requests in flight; a mailbox stores one message at a time, so 2–4 is plenty. */
|
|
104
|
+
concurrency: number;
|
|
105
|
+
total?: number | null;
|
|
106
|
+
retries?: number;
|
|
107
|
+
/** Delay before retry `attempt` (from 1); tests make it short. */
|
|
108
|
+
backoff?: (attempt: number) => number;
|
|
109
|
+
onProgress?: (stats: UploadStats) => void;
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Uploads every item with bounded concurrency, retrying transient failures
|
|
114
|
+
* and recording each result, then announces the batch to the mailbox.
|
|
115
|
+
*/
|
|
116
|
+
export async function upload(options: UploadOptions): Promise<UploadStats> {
|
|
117
|
+
const stats: UploadStats = {
|
|
118
|
+
total: options.total ?? null,
|
|
119
|
+
seen: 0,
|
|
120
|
+
imported: 0,
|
|
121
|
+
duplicate: 0,
|
|
122
|
+
resumed: 0,
|
|
123
|
+
skipped: 0,
|
|
124
|
+
failed: 0,
|
|
125
|
+
bytes: 0,
|
|
126
|
+
folderSkipped: 0,
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
const retries = options.retries ?? 6;
|
|
130
|
+
|
|
131
|
+
const backoff =
|
|
132
|
+
options.backoff ??
|
|
133
|
+
((attempt) => Math.min(30_000, 1000 * 2 ** (attempt - 1)));
|
|
134
|
+
|
|
135
|
+
const progress = () => options.onProgress?.(stats);
|
|
136
|
+
|
|
137
|
+
/** Sends one message, retrying transient failures; a fatal one rejects and ends the run. */
|
|
138
|
+
const send = async (item: ImportItem, attempt = 1): Promise<void> => {
|
|
139
|
+
try {
|
|
140
|
+
const result = await options.workspace.importMessage(
|
|
141
|
+
options.mailboxId,
|
|
142
|
+
item
|
|
143
|
+
);
|
|
144
|
+
|
|
145
|
+
if (result.status === "duplicate") stats.duplicate += 1;
|
|
146
|
+
else {
|
|
147
|
+
stats.imported += 1;
|
|
148
|
+
|
|
149
|
+
if (result.folderSkipped) stats.folderSkipped += 1;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
stats.bytes += item.raw.byteLength;
|
|
153
|
+
options.state.add(item.sourceId);
|
|
154
|
+
} catch (error) {
|
|
155
|
+
if (fatal(error)) throw error;
|
|
156
|
+
|
|
157
|
+
if (!retryable(error) || attempt > retries) {
|
|
158
|
+
stats.failed += 1;
|
|
159
|
+
options.state.fail(
|
|
160
|
+
item.sourceId,
|
|
161
|
+
error instanceof Error ? error.message : String(error)
|
|
162
|
+
);
|
|
163
|
+
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
await Bun.sleep(backoff(attempt));
|
|
168
|
+
|
|
169
|
+
return send(item, attempt + 1);
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const handle = async (item: ImportItem | SkippedItem) => {
|
|
174
|
+
stats.seen += 1;
|
|
175
|
+
|
|
176
|
+
if (options.state.has(item.sourceId)) {
|
|
177
|
+
stats.resumed += 1;
|
|
178
|
+
progress();
|
|
179
|
+
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
if ("skipped" in item) {
|
|
184
|
+
stats.skipped += 1;
|
|
185
|
+
progress();
|
|
186
|
+
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (item.raw.byteLength > MAX_IMPORT_MESSAGE_BYTES) {
|
|
191
|
+
stats.failed += 1;
|
|
192
|
+
options.state.fail(
|
|
193
|
+
item.sourceId,
|
|
194
|
+
`Larger than ${MAX_IMPORT_MESSAGE_BYTES / 1024 / 1024} MiB`
|
|
195
|
+
);
|
|
196
|
+
progress();
|
|
197
|
+
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
try {
|
|
202
|
+
await send(item);
|
|
203
|
+
} finally {
|
|
204
|
+
progress();
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
await forEachConcurrent(options.items, options.concurrency, handle);
|
|
209
|
+
await options.workspace.finishImport(options.mailboxId);
|
|
210
|
+
|
|
211
|
+
return stats;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** A one-line progress report for a terminal. */
|
|
215
|
+
export function progressLine(label: string, stats: UploadStats) {
|
|
216
|
+
const done =
|
|
217
|
+
stats.imported +
|
|
218
|
+
stats.duplicate +
|
|
219
|
+
stats.resumed +
|
|
220
|
+
stats.skipped +
|
|
221
|
+
stats.failed;
|
|
222
|
+
|
|
223
|
+
const of = stats.total === null ? "" : `/${stats.total}`;
|
|
224
|
+
const parts = [`${stats.imported} imported`];
|
|
225
|
+
|
|
226
|
+
if (stats.duplicate) parts.push(`${stats.duplicate} already there`);
|
|
227
|
+
|
|
228
|
+
if (stats.resumed) parts.push(`${stats.resumed} done before`);
|
|
229
|
+
|
|
230
|
+
if (stats.skipped) parts.push(`${stats.skipped} skipped`);
|
|
231
|
+
|
|
232
|
+
if (stats.failed) parts.push(`${stats.failed} failed`);
|
|
233
|
+
|
|
234
|
+
return `${label}: ${done}${of} — ${parts.join(", ")} (${(stats.bytes / 1024 / 1024).toFixed(1)} MiB sent)`;
|
|
235
|
+
}
|