@open-workspace/email 0.5.1 → 0.6.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 (58) hide show
  1. package/README.md +1 -2
  2. package/alchemy/index.ts +0 -16
  3. package/migrations/0003_after_0_5_2.sql +1 -0
  4. package/migrations/meta/0003_snapshot.json +703 -0
  5. package/migrations/meta/_journal.json +7 -0
  6. package/package.json +36 -35
  7. package/shared/mail.ts +3 -2
  8. package/shared/module.ts +1 -1
  9. package/src/client.tsx +23 -31
  10. package/src/extensions.ts +176 -0
  11. package/src/mail/compose-window-chrome.tsx +5 -10
  12. package/src/mail/compose-window.tsx +13 -2
  13. package/src/mail/composer-asset-bookmarks.ts +3 -3
  14. package/src/mail/composer-attach-button.tsx +106 -0
  15. package/src/mail/composer-editor.tsx +17 -0
  16. package/src/mail/composer-inserts.tsx +186 -0
  17. package/src/mail/composer-toolbar.tsx +3 -0
  18. package/src/mail/conversation-message.tsx +37 -1
  19. package/src/mail/conversation-reply.tsx +5 -10
  20. package/src/mail/mail-mailbox-sheet.tsx +2 -2
  21. package/src/mail/mail-prefetch.ts +1 -1
  22. package/src/mail/message-actions.tsx +30 -0
  23. package/src/mail/message-attachments.tsx +62 -0
  24. package/src/mail/message-panels.tsx +206 -0
  25. package/src/mail/module-extensions.ts +87 -0
  26. package/src/mail/reader-pane.tsx +75 -47
  27. package/src/mail/recipient-combobox.tsx +32 -12
  28. package/src/mail/shared-compose.ts +45 -0
  29. package/src/mail/unread-document-indicator.tsx +4 -3
  30. package/src/mail/use-composer-attachment-preflight.ts +2 -1
  31. package/src/mail/use-composer-core.ts +4 -6
  32. package/src/settings/mail-notifications.tsx +119 -0
  33. package/src/settings/settings-queries.ts +0 -7
  34. package/worker/backups/file-parts.ts +9 -6
  35. package/worker/backups/mail-backup.ts +21 -4
  36. package/worker/backups/settings-backup.ts +56 -24
  37. package/worker/db/schema.ts +0 -36
  38. package/worker/jmap/eventsource.ts +4 -1
  39. package/worker/jmap/method-core.ts +2 -3
  40. package/worker/jmap/push-subscription-methods.ts +5 -2
  41. package/worker/jmap/push.ts +10 -11
  42. package/worker/jmap/routes.ts +10 -49
  43. package/worker/mail/bimi.ts +2 -3
  44. package/worker/mail/person-erasure.ts +58 -0
  45. package/worker/mail/push-notifications.ts +59 -419
  46. package/worker/mail/remote-proxy.ts +3 -206
  47. package/worker/mail/remote-routes.ts +2 -2
  48. package/worker/mail/routes.ts +8 -2
  49. package/worker/mail/uploads.ts +14 -6
  50. package/worker/mail/webhook-source.ts +13 -1
  51. package/worker/mailbox/index.ts +27 -0
  52. package/worker/mailbox/mailbox-drafts.ts +5 -0
  53. package/worker/module-api.ts +239 -0
  54. package/worker/module.ts +11 -7
  55. package/src/pwa/push-key.ts +0 -18
  56. package/src/pwa/push-subscription.ts +0 -213
  57. package/src/settings/notifications-page.tsx +0 -306
  58. package/worker/mail/push-endpoint.ts +0 -17
@@ -0,0 +1,87 @@
1
+ import { moduleExtensions } from "@open-workspace/core/ui";
2
+ import { useQueries } from "@tanstack/react-query";
3
+ import { toast } from "sonner";
4
+
5
+ import type { MessageCard, RecipientSuggestion } from "../extensions";
6
+ import { mailApi } from "../lib/mail-api";
7
+ import type { MessageAttachment } from "./types";
8
+
9
+ /** An attachment's bytes, through the route its download link uses. */
10
+ export async function attachmentContent(
11
+ mailboxId: string,
12
+ messageId: string,
13
+ attachmentId: string
14
+ ) {
15
+ const response = await mailApi.api.mail.messages[":messageId"].attachments[
16
+ ":attachmentId"
17
+ ].$get({ param: { messageId, attachmentId }, query: { mailboxId } });
18
+
19
+ if (!response.ok) {
20
+ throw new Error(`Could not download the attachment (${response.status})`);
21
+ }
22
+
23
+ return response.blob();
24
+ }
25
+
26
+ function baseContentType(contentType: string) {
27
+ return (contentType.split(";")[0] ?? "").trim().toLowerCase();
28
+ }
29
+
30
+ /** Each module card with the message's first part it is for. */
31
+ export function messageCards(attachments: readonly MessageAttachment[]) {
32
+ return moduleExtensions("email.messageCards").flatMap((card: MessageCard) => {
33
+ const types = new Set(card.contentTypes.map(baseContentType));
34
+
35
+ const part = attachments.find((attachment) =>
36
+ types.has(baseContentType(attachment.contentType))
37
+ );
38
+
39
+ return part ? [{ card, part }] : [];
40
+ });
41
+ }
42
+
43
+ /** Runs a module's action, showing its failure. */
44
+ export async function runModuleAction(run: () => void | Promise<void>) {
45
+ try {
46
+ await run();
47
+ } catch (error) {
48
+ toast.error(
49
+ error instanceof Error ? error.message : "The action didn't work"
50
+ );
51
+ }
52
+ }
53
+
54
+ const NO_SUGGESTIONS: RecipientSuggestion[] = [];
55
+
56
+ /**
57
+ * Other modules' recipient suggestions for `query` (`email.recipientSources`),
58
+ * each source on its own: one that fails counts as none, and one that is
59
+ * slow only adds its suggestions when they come.
60
+ */
61
+ export function useSourceSuggestions(query: string, active: boolean) {
62
+ const sources = moduleExtensions("email.recipientSources");
63
+
64
+ const results = useQueries({
65
+ queries: sources.map((source) => ({
66
+ queryKey: ["recipient-source", source.id, query],
67
+ queryFn: async ({ signal }: { signal: AbortSignal }) => {
68
+ try {
69
+ const found = await source.search(query, { signal });
70
+
71
+ return Array.isArray(found) ? found : NO_SUGGESTIONS;
72
+ } catch (error) {
73
+ if (!signal.aborted) {
74
+ console.warn(`Recipient source ${source.id} failed`, error);
75
+ }
76
+
77
+ return NO_SUGGESTIONS;
78
+ }
79
+ },
80
+ enabled: active,
81
+ staleTime: 30_000,
82
+ retry: false,
83
+ })),
84
+ });
85
+
86
+ return results.flatMap((result) => result.data ?? NO_SUGGESTIONS);
87
+ }
@@ -45,6 +45,13 @@ import {
45
45
  import { ConversationView } from "./conversation-view";
46
46
  import { folderShowsUnreadCount, orderedFolders } from "./mail-folders";
47
47
  import { TranslationEnabled } from "./message-body";
48
+ import {
49
+ MessagePanelToggles,
50
+ OpenMessagePanel,
51
+ panelMessage,
52
+ useMessagePanels,
53
+ } from "./message-panels";
54
+ import type { MessagePanels } from "./message-panels";
48
55
  import { useSenderActions } from "./sender-actions";
49
56
  import type { SenderActions } from "./sender-actions";
50
57
  import { ToolbarTooltip } from "./toolbar-tooltip";
@@ -263,10 +270,12 @@ function CommandBar({
263
270
  mail,
264
271
  messages,
265
272
  actions,
273
+ panels,
266
274
  }: {
267
275
  mail: MailController;
268
276
  messages: MessageDetail[];
269
277
  actions: SenderActions;
278
+ panels: MessagePanels;
270
279
  }) {
271
280
  const { conversations, conversationId, conversation } = mail;
272
281
  const pending = !conversation;
@@ -363,6 +372,7 @@ function CommandBar({
363
372
  <MoreMenu mail={mail} messages={messages} actions={actions} />
364
373
 
365
374
  <div className="ml-auto flex items-center gap-0.5 pl-2">
375
+ <MessagePanelToggles panels={panels} disabled={!messages.length} />
366
376
  {index !== -1 && (
367
377
  <span className="text-muted-foreground mr-1.5 hidden text-xs whitespace-nowrap tabular-nums @2xl/reader:inline">
368
378
  {index + 1} of {mail.displayedConversationCount}
@@ -508,58 +518,76 @@ export function ReaderPane({ mail }: { mail: MailController }) {
508
518
  });
509
519
 
510
520
  const messages = useSenderIntel(mailbox?.id, conversationMessages);
521
+ const panels = useMessagePanels(Boolean(conversationId));
522
+ const [reader, setReader] = useState<HTMLDivElement | null>(null);
511
523
 
512
524
  if (!conversationId) return <ReaderPlaceholder mail={mail} />;
513
525
  const pages = conversationQuery.data?.pages;
514
526
 
515
527
  return (
516
- <div className="@container/reader flex min-h-0 flex-1 flex-col">
517
- <CommandBar mail={mail} messages={messages} actions={senderActions} />
518
- {/* One per conversation: it opens at the top, and its reply box and the draft it reopens are that conversation's. */}
519
- <div
520
- key={`${mailbox?.id ?? ""}:${conversationId}`}
521
- className="min-h-0 flex-1 overflow-y-auto"
522
- >
523
- <TranslationEnabled value={conversation?.translationEnabled ?? false}>
524
- <ConversationView
525
- messages={messages}
526
- matchId={mail.matchId}
527
- matchQuoted={mail.matchQuoted}
528
- pinnedId={mail.pinnedId}
529
- openFromDrafts={mail.folder === DRAFTS_FOLDER_ID}
530
- refreshing={conversationQuery.isFetching}
531
- replyDraftSource={conversation?.replyDraftSource ?? null}
532
- replyDraft={
533
- mailbox?.canSend ? (conversation?.replyDraft ?? null) : null
534
- }
535
- messageCount={conversation?.messageCount ?? messages.length}
536
- hasOlderMessages={Boolean(pages?.at(-1)?.nextCursor)}
537
- loadingOlder={conversationQuery.isFetchingNextPage}
538
- olderMessagesError={conversationQuery.isFetchNextPageError}
539
- // The mailbox list confirms the URL's mailbox; until then a failed
540
- // request may just be a stale link about to be redirected.
541
- loading={
542
- !mailbox || (!pages?.length && conversationQuery.isPending)
543
- }
544
- error={
545
- pages?.length || !mailbox
546
- ? undefined
547
- : conversationQuery.error?.message
548
- }
549
- summary={mail.conversations.find(
550
- (item) => item.conversationId === conversationId
551
- )}
552
- mailbox={mailbox}
553
- onRetry={() => void conversationQuery.refetch()}
554
- onLoadOlder={() => void conversationQuery.fetchNextPage()}
555
- onForward={mail.openForward}
556
- onOpenConversation={(id) =>
557
- mail.openConversation(id, "replace", "sent")
558
- }
559
- senderActions={senderActions}
560
- reportable={mail.canReport}
561
- />
562
- </TranslationEnabled>
528
+ <div
529
+ ref={setReader}
530
+ className="@container/reader flex min-h-0 flex-1 flex-col"
531
+ >
532
+ <CommandBar
533
+ mail={mail}
534
+ messages={messages}
535
+ actions={senderActions}
536
+ panels={panels}
537
+ />
538
+ <div className="flex min-h-0 flex-1">
539
+ {/* One per conversation: it opens at the top, and its reply box and the draft it reopens are that conversation's. */}
540
+ <div
541
+ key={`${mailbox?.id ?? ""}:${conversationId}`}
542
+ className="min-h-0 min-w-0 flex-1 overflow-y-auto"
543
+ >
544
+ <TranslationEnabled value={conversation?.translationEnabled ?? false}>
545
+ <ConversationView
546
+ messages={messages}
547
+ matchId={mail.matchId}
548
+ matchQuoted={mail.matchQuoted}
549
+ pinnedId={mail.pinnedId}
550
+ openFromDrafts={mail.folder === DRAFTS_FOLDER_ID}
551
+ refreshing={conversationQuery.isFetching}
552
+ replyDraftSource={conversation?.replyDraftSource ?? null}
553
+ replyDraft={
554
+ mailbox?.canSend ? (conversation?.replyDraft ?? null) : null
555
+ }
556
+ messageCount={conversation?.messageCount ?? messages.length}
557
+ hasOlderMessages={Boolean(pages?.at(-1)?.nextCursor)}
558
+ loadingOlder={conversationQuery.isFetchingNextPage}
559
+ olderMessagesError={conversationQuery.isFetchNextPageError}
560
+ // The mailbox list confirms the URL's mailbox; until then a failed
561
+ // request may just be a stale link about to be redirected.
562
+ loading={
563
+ !mailbox || (!pages?.length && conversationQuery.isPending)
564
+ }
565
+ error={
566
+ pages?.length || !mailbox
567
+ ? undefined
568
+ : conversationQuery.error?.message
569
+ }
570
+ summary={mail.conversations.find(
571
+ (item) => item.conversationId === conversationId
572
+ )}
573
+ mailbox={mailbox}
574
+ onRetry={() => void conversationQuery.refetch()}
575
+ onLoadOlder={() => void conversationQuery.fetchNextPage()}
576
+ onForward={mail.openForward}
577
+ onOpenConversation={(id) =>
578
+ mail.openConversation(id, "replace", "sent")
579
+ }
580
+ senderActions={senderActions}
581
+ reportable={mail.canReport}
582
+ />
583
+ </TranslationEnabled>
584
+ </div>
585
+ <OpenMessagePanel
586
+ panels={panels}
587
+ reader={reader}
588
+ mailboxId={mailbox?.id}
589
+ message={panelMessage(messages)}
590
+ />
563
591
  </div>
564
592
  {senderActions.dialogs}
565
593
  </div>
@@ -29,6 +29,7 @@ import type {
29
29
  RecipientFieldValue,
30
30
  } from "./composer-recipients";
31
31
  import { Monogram } from "./mail-primitives";
32
+ import { useSourceSuggestions } from "./module-extensions";
32
33
  import { useRecipientSuggestions } from "./use-mail-data";
33
34
 
34
35
  /**
@@ -83,27 +84,46 @@ export function RecipientCombobox({
83
84
  focused && !disabled && queryReady
84
85
  );
85
86
 
87
+ const sourceSuggestions = useSourceSuggestions(
88
+ query,
89
+ focused && !disabled && queryReady
90
+ );
91
+
86
92
  const selected = new Set(
87
93
  value.recipients.map((recipient) =>
88
94
  normalizeExternalEmailAddress(recipient.address)
89
95
  )
90
96
  );
91
97
 
92
- const suggestions = (suggestionsQuery.data?.suggestions ?? []).flatMap(
93
- (suggestion) => {
94
- const normalized = normalizeComposerRecipient(suggestion);
98
+ // Mail's suggestions, then other modules' (`email.recipientSources`), each
99
+ // address once whatever its case.
100
+ const listed = new Set<string>();
101
+
102
+ const suggestions = [
103
+ ...(suggestionsQuery.data?.suggestions ?? []),
104
+ ...sourceSuggestions,
105
+ ].flatMap((suggestion) => {
106
+ const normalized = normalizeComposerRecipient({
107
+ address: suggestion.address,
108
+ name: suggestion.name ?? null,
109
+ });
95
110
 
96
- if (
97
- !normalized ||
98
- selected.has(normalized.address) ||
99
- excludedAddresses.has(normalized.address)
100
- ) {
101
- return [];
102
- }
111
+ const key = normalized?.address.toLowerCase();
103
112
 
104
- return [normalized];
113
+ if (
114
+ !normalized ||
115
+ !key ||
116
+ listed.has(key) ||
117
+ selected.has(normalized.address) ||
118
+ excludedAddresses.has(normalized.address)
119
+ ) {
120
+ return [];
105
121
  }
106
- );
122
+
123
+ listed.add(key);
124
+
125
+ return [normalized];
126
+ });
107
127
 
108
128
  const open =
109
129
  !disabled && focused && !dismissed && queryReady && suggestions.length > 0;
@@ -0,0 +1,45 @@
1
+ import type { SharedContent } from "@open-workspace/core/ui";
2
+
3
+ import { newDraftId } from "./use-drafts";
4
+
5
+ /** What the composer opens with from a share: a subject, text and files. */
6
+ export type SharedMessage = { subject: string; text: string; files: File[] };
7
+
8
+ /** Shares waiting for their composer, by its draft id. */
9
+ const waiting = new Map<string, SharedMessage>();
10
+
11
+ /**
12
+ * Mail's "New message" share target: a new message in the home mailbox
13
+ * with the shared title as its subject, the text and link in its body, and
14
+ * the files attached.
15
+ */
16
+ export function composeShared(
17
+ shared: SharedContent,
18
+ app: { navigate: (to: string) => void }
19
+ ) {
20
+ const draftId = newDraftId();
21
+
22
+ const text = [
23
+ shared.text,
24
+ shared.url && !shared.text?.includes(shared.url) ? shared.url : undefined,
25
+ ]
26
+ .filter(Boolean)
27
+ .join("\n");
28
+
29
+ waiting.set(draftId, {
30
+ subject: shared.title ?? "",
31
+ text,
32
+ files: shared.files,
33
+ });
34
+ app.navigate(`/?compose=new-${draftId}`);
35
+ }
36
+
37
+ /** The share a new composer opens with, if it is for one. */
38
+ export function sharedMessage(draftId: string) {
39
+ return waiting.get(draftId);
40
+ }
41
+
42
+ /** The composer took its share. */
43
+ export function forgetSharedMessage(draftId: string) {
44
+ waiting.delete(draftId);
45
+ }
@@ -18,9 +18,10 @@ function updateAppBadge(count: number) {
18
18
  const operation =
19
19
  count > 0 ? navigator.setAppBadge?.(count) : navigator.clearAppBadge?.();
20
20
 
21
- void operation?.catch(() => {
22
- // Badging is optional and can be denied independently of notifications.
23
- });
21
+ // Badging is optional and can be denied independently of notifications.
22
+ void operation?.catch((error) =>
23
+ console.debug("Could not update the app badge", error)
24
+ );
24
25
  }
25
26
 
26
27
  export function UnreadDocumentIndicator() {
@@ -124,8 +124,9 @@ export function useComposerAttachmentPreflight(
124
124
  const resolvePlan = useEffectEvent((signal: AbortSignal) => {
125
125
  if (!hasAttachments || assets.some((asset) => !asset.uploadId)) return;
126
126
  void resolveComposerAttachmentPlan(session, context, assets, signal).catch(
127
- () => {
127
+ (error) => {
128
128
  // Background preflight is advisory. Final submission reports failures.
129
+ if (!signal.aborted) console.warn("Attachment preflight failed", error);
129
130
  }
130
131
  );
131
132
  });
@@ -253,12 +253,10 @@ export function useComposerCore(input: {
253
253
  event.dataTransfer.dropEffect = busy ? "none" : "copy";
254
254
  },
255
255
  onDragLeave: (event: DragEvent<HTMLFormElement>) => {
256
- if (
257
- !(
258
- event.relatedTarget instanceof Node &&
259
- event.currentTarget.contains(event.relatedTarget)
260
- )
261
- ) {
256
+ if (!(
257
+ event.relatedTarget instanceof Node &&
258
+ event.currentTarget.contains(event.relatedTarget)
259
+ )) {
262
260
  setDragging(false);
263
261
  }
264
262
  },
@@ -0,0 +1,119 @@
1
+ import {
2
+ adminPanelClass,
3
+ AdminPanelBody,
4
+ AdminPanelFooter,
5
+ AdminPanelHeader,
6
+ Button,
7
+ DelayedFallback,
8
+ Switch,
9
+ responseJson,
10
+ } from "@open-workspace/core/ui";
11
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
12
+ import { Bell, LoaderCircle } from "lucide-react";
13
+ import { toast } from "sonner";
14
+
15
+ import { mailApi } from "../lib/mail-api";
16
+ import { notificationPreferencesQuery } from "./settings-queries";
17
+
18
+ /** Mail's block on Settings → Notifications: which mailboxes notify the person. */
19
+ export function MailNotifications() {
20
+ const client = useQueryClient();
21
+ const preferences = useQuery(notificationPreferencesQuery);
22
+
23
+ const updatePreference = useMutation({
24
+ mutationFn: async ({
25
+ mailboxId,
26
+ enabled,
27
+ }: {
28
+ mailboxId: string;
29
+ enabled: boolean;
30
+ }) =>
31
+ responseJson(
32
+ await mailApi.api.notifications.preferences[":mailboxId"].$put({
33
+ param: { mailboxId },
34
+ json: { enabled },
35
+ })
36
+ ),
37
+ onSuccess: async () => {
38
+ await client.invalidateQueries({
39
+ queryKey: ["notification-preferences"],
40
+ });
41
+ },
42
+ onError: (error) => toast.error(error.message),
43
+ });
44
+
45
+ return (
46
+ <div className={adminPanelClass}>
47
+ <AdminPanelHeader
48
+ Icon={Bell}
49
+ title="Mail notifications"
50
+ description="Which of your mailboxes alert you to new mail."
51
+ />
52
+ <AdminPanelBody className="py-2">
53
+ <div className="divide-border/70 divide-y">
54
+ <DelayedFallback
55
+ pending={preferences.isLoading}
56
+ fallback={
57
+ <div className="text-muted-foreground flex items-center gap-2 py-4 text-xs">
58
+ <LoaderCircle className="size-4 animate-spin" /> Loading
59
+ mailboxes…
60
+ </div>
61
+ }
62
+ >
63
+ {preferences.isError ? (
64
+ <div className="flex items-center justify-between gap-4 py-4">
65
+ <p className="text-destructive text-xs">
66
+ Could not load mailbox preferences.
67
+ </p>
68
+ <Button
69
+ size="sm"
70
+ variant="outline"
71
+ disabled={preferences.isFetching}
72
+ onClick={() => void preferences.refetch()}
73
+ >
74
+ {preferences.isFetching && (
75
+ <LoaderCircle className="animate-spin" />
76
+ )}
77
+ Retry
78
+ </Button>
79
+ </div>
80
+ ) : preferences.data?.preferences.length ? (
81
+ preferences.data.preferences.map((preference) => (
82
+ <label
83
+ key={preference.mailboxId}
84
+ className="flex items-center gap-4 py-3"
85
+ >
86
+ <span className="min-w-0 flex-1">
87
+ <span className="block truncate text-sm font-medium">
88
+ {preference.displayName}
89
+ </span>
90
+ <span className="text-muted-foreground block truncate text-xs">
91
+ {preference.address}
92
+ </span>
93
+ </span>
94
+ <Switch
95
+ checked={preference.enabled}
96
+ disabled={updatePreference.isPending}
97
+ onCheckedChange={(enabled) =>
98
+ updatePreference.mutate({
99
+ mailboxId: preference.mailboxId,
100
+ enabled,
101
+ })
102
+ }
103
+ />
104
+ </label>
105
+ ))
106
+ ) : (
107
+ <p className="text-muted-foreground py-4 text-xs">
108
+ No mailboxes are available for notifications.
109
+ </p>
110
+ )}
111
+ </DelayedFallback>
112
+ </div>
113
+ </AdminPanelBody>
114
+ <AdminPanelFooter className="text-muted-foreground block text-xs leading-relaxed">
115
+ You won't be notified about a mailbox while it's open in a tab.
116
+ </AdminPanelFooter>
117
+ </div>
118
+ );
119
+ }
@@ -9,13 +9,6 @@ import { mailApi } from "../lib/mail-api";
9
9
  * client.tsx). Kept free of UI imports so the app's entry stays small.
10
10
  */
11
11
 
12
- export const pushConfigQuery = queryOptions({
13
- queryKey: ["push-config"],
14
- queryFn: async () =>
15
- responseJson(await mailApi.api.notifications.config.$get()),
16
- staleTime: 60_000,
17
- });
18
-
19
12
  export const notificationPreferencesQuery = queryOptions({
20
13
  queryKey: ["notification-preferences"],
21
14
  queryFn: async () =>
@@ -1,4 +1,5 @@
1
1
  /* oxlint-disable eslint/no-await-in-loop -- R2 file ranges are read and written in order with bounded memory. */
2
+ import { backupObject } from "@open-workspace/core/module";
2
3
  import type {
3
4
  BackupRestoreItem,
4
5
  BackupSnapshot,
@@ -67,8 +68,10 @@ export async function backupFileParts(
67
68
  throw new Error("Incomplete attachment range");
68
69
  }
69
70
 
70
- const hash = await snapshot.putObject(bytes, binary);
71
- parts.push({ object: `${hash}.bin` });
71
+ // The part's hash is only known once read: a range is one part in memory.
72
+ parts.push({
73
+ object: await snapshot.putObject(await backupObject(bytes), binary),
74
+ });
72
75
  }
73
76
 
74
77
  return { size: head.size, parts };
@@ -87,18 +90,18 @@ const partLine = z.object({
87
90
  export async function stageBackupPart(
88
91
  bucket: R2Bucket,
89
92
  userId: string,
90
- { line, object: bytes }: BackupRestoreItem
93
+ { line, object }: BackupRestoreItem
91
94
  ) {
92
95
  const part = partLine.safeParse(line).data;
93
96
 
94
97
  if (!part) return null;
95
98
 
96
- if (!bytes?.byteLength || bytes.byteLength > PART_BYTES) {
99
+ if (!object || object.size > PART_BYTES) {
97
100
  return { status: "skipped", reason: "damaged" } as const;
98
101
  }
99
102
 
100
- const sha256 = part.object.slice(0, 64);
101
- await bucket.put(stagedPart(userId, part.object), bytes, { sha256 });
103
+ // Core checked the stream against the part's name as R2 took it.
104
+ await bucket.put(stagedPart(userId, part.object), object.body);
102
105
 
103
106
  return { status: "restored" } as const;
104
107
  }
@@ -1,4 +1,5 @@
1
1
  import {
2
+ backupObject,
2
3
  createDb,
3
4
  restoredReaderIds,
4
5
  mailboxAddressSql,
@@ -19,7 +20,10 @@ import {
19
20
  MAX_COMPOSER_ATTACHMENT_COUNT,
20
21
  } from "../../shared/mail";
21
22
  import type { MailboxState } from "../../shared/mail";
22
- import { importPlacements } from "../../shared/mail-import";
23
+ import {
24
+ importPlacements,
25
+ MAX_IMPORT_MESSAGE_BYTES,
26
+ } from "../../shared/mail-import";
23
27
  import { IMPORT_MAIL_SCOPE } from "../../shared/permissions";
24
28
  import {
25
29
  importCopyKey,
@@ -431,7 +435,10 @@ async function messagePage(
431
435
 
432
436
  if (!message) continue;
433
437
  // oxlint-disable-next-line eslint/no-await-in-loop -- see above
434
- sha256 = await snapshot.putObject(message.bytes, EML);
438
+ const object = await backupObject(message.bytes);
439
+ // oxlint-disable-next-line eslint/no-await-in-loop -- see above
440
+ await snapshot.putObject(object, EML);
441
+ ({ sha256 } = object);
435
442
 
436
443
  attachments = [];
437
444
  const files: Record<string, BackupFile> = {};
@@ -545,10 +552,10 @@ export const mailBackup: ModuleBackup = {
545
552
  const piece = await restorePiece(c, item);
546
553
 
547
554
  if (piece) return piece;
548
- const { folder, line, object } = item;
555
+ const { folder, line } = item;
549
556
  const parsed = mailBackupLine.safeParse(line);
550
557
 
551
- if (!parsed.success || !object) {
558
+ if (!parsed.success || !item.object) {
552
559
  return { status: "skipped", reason: "not a message line" };
553
560
  }
554
561
 
@@ -557,6 +564,16 @@ export const mailBackup: ModuleBackup = {
557
564
 
558
565
  if (!mailbox) return { status: "skipped", reason: `no mailbox ${folder}` };
559
566
 
567
+ // Parsing a message needs all of it, and none is larger than mail
568
+ // delivers; a bigger object would only exhaust the Worker's memory.
569
+ if (item.object.size > MAX_IMPORT_MESSAGE_BYTES) {
570
+ return { status: "skipped", reason: "message too large" };
571
+ }
572
+
573
+ const object = new Uint8Array(
574
+ await new Response(item.object.body).arrayBuffer()
575
+ );
576
+
560
577
  const files: StoredAttachment[] = [];
561
578
  const importKey = `backup:${message.id}`;
562
579
  const thread = `backup:${message.thread}`;