@open-workspace/email 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 (266) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  4. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  5. package/drizzle/mailbox/meta/_journal.json +7 -0
  6. package/drizzle/mailbox/migrations.js +3 -1
  7. package/migrations/0002_after_0_4_2.sql +35 -0
  8. package/migrations/meta/0002_snapshot.json +807 -0
  9. package/migrations/meta/_journal.json +7 -0
  10. package/package.json +23 -7
  11. package/shared/attachment-preview.ts +18 -8
  12. package/shared/folder-order.ts +31 -6
  13. package/shared/mail-headers.ts +3 -3
  14. package/shared/mail-html.ts +25 -0
  15. package/shared/mail-import.ts +0 -7
  16. package/shared/mail-received.ts +4 -4
  17. package/shared/mail-rule-actions.ts +47 -0
  18. package/shared/mail.ts +70 -4
  19. package/shared/office-preview.ts +0 -4
  20. package/shared/pdfjs-assets.ts +1 -3
  21. package/shared/rich-content.ts +35 -0
  22. package/shared/signature.ts +15 -0
  23. package/src/admin/address-auto-reply.tsx +49 -0
  24. package/src/admin/blocked-senders.tsx +86 -66
  25. package/src/admin/forward-destinations.tsx +140 -0
  26. package/src/admin/mail-archive.tsx +134 -0
  27. package/src/admin/team-signature.tsx +90 -0
  28. package/src/client.tsx +130 -16
  29. package/src/mail/attachment-preview-dialog.tsx +13 -5
  30. package/src/mail/auto-reply-banner.tsx +61 -0
  31. package/src/mail/blocked-senders.tsx +124 -91
  32. package/src/mail/compose-window-chrome.tsx +20 -8
  33. package/src/mail/compose-window.tsx +387 -365
  34. package/src/mail/composer-asset-bookmarks.ts +47 -12
  35. package/src/mail/composer-attachment-list.tsx +42 -17
  36. package/src/mail/composer-editor-document.ts +54 -10
  37. package/src/mail/composer-editor.tsx +44 -44
  38. package/src/mail/composer-link-text.ts +42 -0
  39. package/src/mail/composer-recipient-fields.tsx +25 -16
  40. package/src/mail/composer-recipients.ts +62 -16
  41. package/src/mail/composer-session.ts +107 -23
  42. package/src/mail/composer-toolbar.tsx +15 -1
  43. package/src/mail/composer-upload-client.ts +29 -1
  44. package/src/mail/composer-upload-progress.ts +2 -2
  45. package/src/mail/conversation-actions-model.ts +56 -0
  46. package/src/mail/conversation-list.tsx +263 -128
  47. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  48. package/src/mail/conversation-message.tsx +257 -102
  49. package/src/mail/conversation-order.ts +12 -0
  50. package/src/mail/conversation-reply.tsx +313 -189
  51. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  52. package/src/mail/conversation-view.tsx +315 -85
  53. package/src/mail/delivery-indicator.tsx +33 -12
  54. package/src/mail/draft-attachments.ts +194 -0
  55. package/src/mail/email-html-body.tsx +97 -53
  56. package/src/mail/folder-cleanup-bar.tsx +193 -0
  57. package/src/mail/folder-glyph.tsx +5 -0
  58. package/src/mail/folder-manager.tsx +71 -38
  59. package/src/mail/mail-app-bar.tsx +15 -3
  60. package/src/mail/mail-dock.tsx +19 -3
  61. package/src/mail/mail-focus.ts +48 -0
  62. package/src/mail/mail-folders.ts +14 -2
  63. package/src/mail/mail-layout.css +20 -0
  64. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  65. package/src/mail/mail-nav-rail.tsx +7 -4
  66. package/src/mail/mail-nav.tsx +66 -46
  67. package/src/mail/mail-prefetch.ts +30 -9
  68. package/src/mail/mail-primitives.tsx +6 -4
  69. package/src/mail/mail-queries.ts +122 -20
  70. package/src/mail/mail-query-cache.ts +1085 -173
  71. package/src/mail/mail-search-params.ts +35 -0
  72. package/src/mail/mail-shell.tsx +32 -9
  73. package/src/mail/mailbox-ai-settings.tsx +56 -42
  74. package/src/mail/mailbox-realtime.tsx +4 -12
  75. package/src/mail/mailbox-rules.tsx +898 -0
  76. package/src/mail/message-actions.tsx +38 -26
  77. package/src/mail/message-attachments.tsx +20 -12
  78. package/src/mail/message-body.ts +53 -0
  79. package/src/mail/message-format.ts +8 -2
  80. package/src/mail/message-header.tsx +3 -1
  81. package/src/mail/message-translation.tsx +34 -67
  82. package/src/mail/original-message-sheet.tsx +63 -50
  83. package/src/mail/original-message.ts +6 -6
  84. package/src/mail/pane-splitter.tsx +3 -3
  85. package/src/mail/pdf-preview.tsx +70 -62
  86. package/src/mail/plain-message-text.tsx +28 -0
  87. package/src/mail/print-message.ts +31 -36
  88. package/src/mail/reader-pane.tsx +134 -103
  89. package/src/mail/recipient-combobox.tsx +52 -29
  90. package/src/mail/recipient-field-row.tsx +3 -0
  91. package/src/mail/rich-content.ts +128 -0
  92. package/src/mail/sanitize-email-html.ts +53 -32
  93. package/src/mail/sender-actions.tsx +48 -46
  94. package/src/mail/sender-authentication.tsx +1 -1
  95. package/src/mail/sender-dialogs.tsx +67 -43
  96. package/src/mail/sender-security.tsx +9 -10
  97. package/src/mail/signature.ts +43 -0
  98. package/src/mail/translation-html.ts +3 -3
  99. package/src/mail/types.ts +12 -0
  100. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  101. package/src/mail/use-composer-core.ts +286 -0
  102. package/src/mail/use-composer-navigation.ts +120 -0
  103. package/src/mail/use-composer-submission.ts +154 -19
  104. package/src/mail/use-conversation-actions.ts +292 -0
  105. package/src/mail/use-conversation-position.ts +51 -0
  106. package/src/mail/use-conversation-selection.ts +192 -89
  107. package/src/mail/use-draft-autosave.ts +394 -0
  108. package/src/mail/use-drafts.ts +194 -0
  109. package/src/mail/use-mail-controller.ts +754 -213
  110. package/src/mail/use-mail-data.ts +210 -100
  111. package/src/mail/use-mail-safety.ts +19 -38
  112. package/src/mail/use-mail-send.ts +18 -6
  113. package/src/mail/use-pdf-translation.ts +1 -1
  114. package/src/mail/use-reply-cc.ts +61 -0
  115. package/src/mail/use-visible-message-read.ts +128 -64
  116. package/src/pwa/push-key.ts +18 -0
  117. package/src/pwa/push-subscription.ts +88 -26
  118. package/src/settings/auto-reply-editor.tsx +454 -0
  119. package/src/settings/auto-reply-page.tsx +59 -0
  120. package/src/settings/mail-apps-page.tsx +52 -43
  121. package/src/settings/notifications-page.tsx +82 -67
  122. package/src/settings/rich-content-editor.tsx +182 -0
  123. package/src/settings/settings-queries.ts +57 -0
  124. package/src/settings/signature-editor.tsx +142 -0
  125. package/src/settings/signature-page.tsx +70 -0
  126. package/worker/admin/blocked-sender-routes.ts +10 -16
  127. package/worker/backups/eml.ts +185 -0
  128. package/worker/backups/file-parts.ts +140 -0
  129. package/worker/backups/mail-backup.ts +644 -0
  130. package/worker/backups/settings-backup.ts +866 -0
  131. package/worker/backups/stream-eml.ts +73 -0
  132. package/worker/db/schema.ts +89 -5
  133. package/worker/jmap/attachment-blobs.ts +113 -0
  134. package/worker/jmap/blobs.ts +162 -0
  135. package/worker/jmap/draft-content.ts +42 -0
  136. package/worker/jmap/drafts.ts +70 -0
  137. package/worker/jmap/email-body.ts +152 -0
  138. package/worker/jmap/email-methods.ts +1223 -0
  139. package/worker/jmap/eventsource.ts +9 -8
  140. package/worker/jmap/import-methods.ts +205 -0
  141. package/worker/jmap/mailbox-methods.ts +187 -0
  142. package/worker/jmap/method-core.ts +379 -0
  143. package/worker/jmap/methods.ts +108 -1815
  144. package/worker/jmap/push-subscription-methods.ts +373 -0
  145. package/worker/jmap/push-types.ts +46 -2
  146. package/worker/jmap/push.ts +24 -31
  147. package/worker/jmap/routes.ts +144 -153
  148. package/worker/jmap/submission-methods.ts +395 -0
  149. package/worker/mail/access.ts +35 -12
  150. package/worker/mail/ai-classification.ts +2 -2
  151. package/worker/mail/archive-object.ts +96 -0
  152. package/worker/mail/archive-routes.ts +35 -0
  153. package/worker/mail/archive.ts +682 -0
  154. package/worker/mail/auth-headers.ts +48 -40
  155. package/worker/mail/auto-reply-routes.ts +255 -0
  156. package/worker/mail/auto-reply.ts +243 -0
  157. package/worker/mail/bimi.ts +53 -36
  158. package/worker/mail/bootstrap.ts +11 -3
  159. package/worker/mail/capabilities.ts +69 -0
  160. package/worker/mail/classification-signals.ts +1 -1
  161. package/worker/mail/confusables-data.ts +9 -0
  162. package/worker/mail/conversation-cursor.ts +6 -15
  163. package/worker/mail/delivery-events.ts +9 -7
  164. package/worker/mail/delivery-facts.ts +1 -1
  165. package/worker/mail/demo-routes.ts +3 -3
  166. package/worker/mail/doh.ts +3 -3
  167. package/worker/mail/download-links.ts +153 -0
  168. package/worker/mail/downloads.ts +2 -6
  169. package/worker/mail/draft-routes.ts +473 -0
  170. package/worker/mail/draft-sender.ts +54 -0
  171. package/worker/mail/edge-cache.ts +41 -55
  172. package/worker/mail/email-routing.ts +123 -0
  173. package/worker/mail/forward-destinations.ts +114 -0
  174. package/worker/mail/forward-downloads.ts +115 -0
  175. package/worker/mail/forward-html.ts +85 -0
  176. package/worker/mail/header-metadata.ts +2 -5
  177. package/worker/mail/impersonation.ts +102 -101
  178. package/worker/mail/import-routes.ts +29 -82
  179. package/worker/mail/import.ts +130 -0
  180. package/worker/mail/inbound-delivery.ts +6 -5
  181. package/worker/mail/inbound.ts +58 -28
  182. package/worker/mail/ip-intel.ts +8 -17
  183. package/worker/mail/isolate-cache.ts +1 -1
  184. package/worker/mail/mailbox-deletion.ts +33 -12
  185. package/worker/mail/mailbox-directory.ts +39 -65
  186. package/worker/mail/mailing-list.ts +29 -58
  187. package/worker/mail/message-security.ts +3 -3
  188. package/worker/mail/message-view.ts +12 -10
  189. package/worker/mail/office-conversion.ts +3 -5
  190. package/worker/mail/office-preview-container.ts +3 -8
  191. package/worker/mail/outbound-content.ts +139 -65
  192. package/worker/mail/outbound-delivery.ts +20 -17
  193. package/worker/mail/outbound-service.ts +34 -9
  194. package/worker/mail/outbound.ts +146 -75
  195. package/worker/mail/outgoing-context.ts +60 -30
  196. package/worker/mail/participants.ts +10 -15
  197. package/worker/mail/plain-body.ts +39 -0
  198. package/worker/mail/push-endpoint.ts +17 -0
  199. package/worker/mail/push-notifications.ts +53 -62
  200. package/worker/mail/quote-parser.ts +36 -24
  201. package/worker/mail/receive.ts +146 -39
  202. package/worker/mail/recipients.ts +1 -1
  203. package/worker/mail/remote-proxy.ts +3 -3
  204. package/worker/mail/repeat.ts +1 -1
  205. package/worker/mail/reply-plan.ts +124 -26
  206. package/worker/mail/rfc.ts +15 -7
  207. package/worker/mail/rich-content.ts +207 -0
  208. package/worker/mail/routes.ts +696 -304
  209. package/worker/mail/routing.ts +274 -0
  210. package/worker/mail/rules.ts +230 -0
  211. package/worker/mail/safety-routes.ts +88 -86
  212. package/worker/mail/schemas.ts +222 -31
  213. package/worker/mail/search.ts +25 -2
  214. package/worker/mail/security-settings.ts +4 -10
  215. package/worker/mail/send-message.ts +238 -0
  216. package/worker/mail/sender-intel.ts +12 -20
  217. package/worker/mail/signature-routes.ts +201 -0
  218. package/worker/mail/signatures.ts +195 -0
  219. package/worker/mail/spamhaus.ts +28 -16
  220. package/worker/mail/storage-keys.ts +35 -0
  221. package/worker/mail/unsubscribe.ts +19 -41
  222. package/worker/mail/uploads.ts +192 -80
  223. package/worker/mail/webhook-source.ts +3 -2
  224. package/worker/mail/workspace-safety.ts +194 -60
  225. package/worker/mailbox/demo.ts +13 -15
  226. package/worker/mailbox/email-index.ts +65 -35
  227. package/worker/mailbox/folder-model.ts +0 -20
  228. package/worker/mailbox/import-placement.ts +21 -36
  229. package/worker/mailbox/inbound-decision.ts +114 -0
  230. package/worker/mailbox/inbox-counts.ts +45 -25
  231. package/worker/mailbox/index.ts +756 -3201
  232. package/worker/mailbox/jmap-change-log.ts +195 -0
  233. package/worker/mailbox/jmap-email-rows.ts +186 -0
  234. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  235. package/worker/mailbox/jmap-placement.ts +139 -0
  236. package/worker/mailbox/jmap-query-filter.ts +231 -0
  237. package/worker/mailbox/jmap-store.ts +167 -299
  238. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  239. package/worker/mailbox/mailbox-backup.ts +538 -0
  240. package/worker/mailbox/mailbox-drafts.ts +417 -0
  241. package/worker/mailbox/mailbox-folders.ts +242 -0
  242. package/worker/mailbox/mailbox-import.ts +450 -0
  243. package/worker/mailbox/mailbox-inbound.ts +934 -0
  244. package/worker/mailbox/mailbox-jmap.ts +294 -0
  245. package/worker/mailbox/mailbox-outbound.ts +413 -0
  246. package/worker/mailbox/mailbox-rules.ts +336 -0
  247. package/worker/mailbox/mailbox-senders.ts +294 -0
  248. package/worker/mailbox/mailbox-storage.ts +438 -0
  249. package/worker/mailbox/mailbox-views.ts +891 -0
  250. package/worker/mailbox/model.ts +1 -0
  251. package/worker/mailbox/office-preview-jobs.ts +59 -47
  252. package/worker/mailbox/placement.ts +933 -0
  253. package/worker/mailbox/restore-thread.ts +52 -0
  254. package/worker/mailbox/retention.ts +36 -0
  255. package/worker/mailbox/schema.ts +200 -1
  256. package/worker/mailbox/senders.ts +216 -178
  257. package/worker/mailbox/spam-undo-filing.ts +138 -0
  258. package/worker/mailbox/spam-undo.ts +240 -0
  259. package/worker/mailbox/support.ts +416 -0
  260. package/worker/mcp/mail-action-tools.ts +156 -0
  261. package/worker/mcp/mail-compose-tools.ts +7 -1
  262. package/worker/mcp/mail-safety-tools.ts +4 -4
  263. package/worker/module.ts +23 -4
  264. package/src/mail/use-compose-submission.ts +0 -208
  265. package/src/mail/use-reply-submission.ts +0 -114
  266. package/worker/mail/capped-body.ts +0 -36
@@ -3,8 +3,6 @@ import {
3
3
  createDb,
4
4
  describeIssues,
5
5
  mailboxAddressSql,
6
- mailboxAccess,
7
- mailboxes,
8
6
  overRateLimit,
9
7
  authenticateAccessToken,
10
8
  jmapProtectedResourceMetadataUrl,
@@ -12,13 +10,16 @@ import {
12
10
  oidcIssuer,
13
11
  } from "@open-workspace/core/module";
14
12
  import type { AppEnv } from "@open-workspace/core/module";
13
+ import { mailboxAccess, mailboxes } from "@open-workspace/core/schema";
15
14
  import { and, eq } from "drizzle-orm";
16
15
  import { Hono } from "hono";
17
16
  import type { Context } from "hono";
17
+ import { bodyLimit } from "hono/body-limit";
18
18
 
19
19
  import { MAX_COMPOSER_ATTACHMENT_BYTES } from "../../shared/mail";
20
20
  import { JMAP_PATH } from "../../shared/module";
21
21
  import {
22
+ MAIL_ORGANIZE_SCOPE,
22
23
  MAIL_READ_SCOPE,
23
24
  MAIL_SEND_SCOPE,
24
25
  mailScopes,
@@ -27,19 +28,19 @@ import { vapidConfiguration } from "../mail/push-notifications";
27
28
  import {
28
29
  createComposerUploadIntent,
29
30
  finalizeComposerUpload,
30
- loadComposerUpload,
31
31
  storeComposerUploadContent,
32
32
  UploadValidationError,
33
33
  } from "../mail/uploads";
34
- import { mailboxStub } from "../mailbox";
34
+ import { readJmapBlob } from "./blobs";
35
35
  import { jmapEventStream } from "./eventsource";
36
36
  import {
37
37
  JmapError,
38
+ accountRights,
38
39
  jmapRequestSchema,
39
- runJmapRequest,
40
- UPLOAD_BLOB,
41
- } from "./methods";
42
- import type { JmapAccount, JmapContext } from "./methods";
40
+ sessionState,
41
+ } from "./method-core";
42
+ import type { JmapAccount, JmapContext } from "./method-core";
43
+ import { runJmapRequest } from "./methods";
43
44
 
44
45
  const CAPABILITIES = {
45
46
  "urn:ietf:params:jmap:core": {
@@ -62,7 +63,8 @@ type SessionCapabilities = typeof CAPABILITIES & {
62
63
  };
63
64
 
64
65
  const MAIL_ACCOUNT_CAPABILITY = {
65
- maxMailboxesPerEmail: 1,
66
+ // A folder is a label in the Inbox; sent mail is also where its thread is.
67
+ maxMailboxesPerEmail: 2,
66
68
  maxMailboxDepth: 1,
67
69
  maxSizeMailboxName: 80,
68
70
  maxSizeAttachmentsPerEmail: MAX_COMPOSER_ATTACHMENT_BYTES,
@@ -79,12 +81,12 @@ type AccountCapabilities = {
79
81
  };
80
82
  };
81
83
 
82
- function accountCapabilities(account: JmapAccount) {
84
+ function accountCapabilities(maySubmit: boolean) {
83
85
  const capabilities: AccountCapabilities = {
84
86
  "urn:ietf:params:jmap:mail": MAIL_ACCOUNT_CAPABILITY,
85
87
  };
86
88
 
87
- if (account.canSend) {
89
+ if (maySubmit) {
88
90
  capabilities["urn:ietf:params:jmap:submission"] = {
89
91
  maxDelayedSend: 0,
90
92
  submissionExtensions: {},
@@ -121,10 +123,7 @@ function problem(
121
123
  }
122
124
 
123
125
  /** The mailboxes this person can open; each is a JMAP account. */
124
- export async function jmapAccounts(
125
- env: Env,
126
- userId: string
127
- ): Promise<JmapAccount[]> {
126
+ export async function jmapAccounts(env: Env, userId: string) {
128
127
  const rows = await createDb(env.DB)
129
128
  .select({
130
129
  id: mailboxes.id,
@@ -146,9 +145,9 @@ export async function jmapAccounts(
146
145
  }));
147
146
  }
148
147
 
149
- function sessionObject(
148
+ async function sessionObject(
150
149
  origin: string,
151
- user: { id: string; name: string },
150
+ user: JmapUser,
152
151
  accounts: JmapAccount[],
153
152
  vapidPublicKey: string | null
154
153
  ) {
@@ -157,6 +156,11 @@ function sessionObject(
157
156
  accounts.find((account) => account.isPersonal) ??
158
157
  accounts[0];
159
158
 
159
+ const primarySubmission =
160
+ primary && accountRights(primary, user.scopes).submit
161
+ ? primary
162
+ : accounts.find((account) => accountRights(account, user.scopes).submit);
163
+
160
164
  const capabilities: SessionCapabilities = { ...CAPABILITIES };
161
165
 
162
166
  if (vapidPublicKey) {
@@ -168,28 +172,30 @@ function sessionObject(
168
172
  return {
169
173
  capabilities,
170
174
  accounts: Object.fromEntries(
171
- accounts.map((account) => [
172
- account.id,
173
- {
174
- name: account.address,
175
- isPersonal: account.isPersonal,
176
- isReadOnly: false,
177
- accountCapabilities: accountCapabilities(account),
178
- },
179
- ])
175
+ accounts.map((account) => {
176
+ const rights = accountRights(account, user.scopes);
177
+
178
+ return [
179
+ account.id,
180
+ {
181
+ name: account.address,
182
+ isPersonal: account.isPersonal,
183
+ isReadOnly: !rights.organize && !rights.submit,
184
+ accountCapabilities: accountCapabilities(rights.submit),
185
+ },
186
+ ];
187
+ })
180
188
  ),
181
- primaryAccounts: primary
182
- ? {
183
- "urn:ietf:params:jmap:mail": primary.id,
184
- "urn:ietf:params:jmap:submission": primary.id,
185
- }
186
- : {},
189
+ primaryAccounts: {
190
+ "urn:ietf:params:jmap:mail": primary?.id,
191
+ "urn:ietf:params:jmap:submission": primarySubmission?.id,
192
+ },
187
193
  username: primary?.address ?? user.name,
188
194
  apiUrl: `${origin}${JMAP_PATH}/api`,
189
195
  downloadUrl: `${origin}${JMAP_PATH}/download/{accountId}/{blobId}/{name}?type={type}`,
190
196
  uploadUrl: `${origin}${JMAP_PATH}/upload/{accountId}`,
191
197
  eventSourceUrl: `${origin}${JMAP_PATH}/eventsource?types={types}&closeafter={closeafter}&ping={ping}`,
192
- state: String(accounts.length),
198
+ state: await sessionState(accounts, user.scopes, vapidPublicKey),
193
199
  };
194
200
  }
195
201
 
@@ -295,7 +301,7 @@ export const jmapRoutes = new Hono<JmapEnv>()
295
301
  const vapid = await vapidConfiguration(c.env);
296
302
 
297
303
  return c.json(
298
- sessionObject(
304
+ await sessionObject(
299
305
  new URL(c.req.url).origin,
300
306
  user,
301
307
  await jmapAccounts(c.env, user.id),
@@ -352,7 +358,6 @@ export const jmapRoutes = new Hono<JmapEnv>()
352
358
  vapid: await vapidConfiguration(c.env),
353
359
  accounts: await jmapAccounts(c.env, user.id),
354
360
  requestUrl: c.req.url,
355
- defer: (task) => c.executionCtx.waitUntil(task),
356
361
  };
357
362
 
358
363
  try {
@@ -376,145 +381,132 @@ export const jmapRoutes = new Hono<JmapEnv>()
376
381
  );
377
382
 
378
383
  if (!account) return problem(c, 404, "about:blank", "Account not found");
379
- const blobId = c.req.param("blobId");
380
- const upload = UPLOAD_BLOB.exec(blobId);
381
- const blob = /^(raw|att)~([^~]+)(?:~(.+))?$/u.exec(blobId);
382
- let key: string | null | undefined;
383
-
384
- if (upload) {
385
- key = await loadComposerUpload({
386
- env: c.env,
387
- mailboxId: account.id,
388
- userId: user.id,
389
- uploadId: upload[1],
390
- }).then(
391
- (found) => found.r2Key,
392
- () => null
393
- );
394
- } else if (blob) {
395
- const [, kind, emailId, attachmentId] = blob;
396
- const email = await mailboxStub(c.env, account.id).getEmail(emailId);
397
- key =
398
- kind === "raw"
399
- ? email?.rawMimeR2Key
400
- : email?.attachmentsJson.find(
401
- (attachment) => attachment.id === attachmentId
402
- )?.r2Key;
403
- }
404
-
405
- const object = key ? await c.env.MAIL_STORAGE.get(key) : null;
406
384
 
407
- if (!object) return problem(c, 404, "about:blank", "Blob not found");
385
+ const blob = await readJmapBlob(
386
+ c.env,
387
+ account,
388
+ user.id,
389
+ c.req.param("blobId")
390
+ );
408
391
 
409
- const type =
410
- c.req.query("type") ||
411
- object.httpMetadata?.contentType ||
412
- (blob?.[1] === "raw" ? "message/rfc822" : "application/octet-stream");
392
+ if (!blob) return problem(c, 404, "about:blank", "Blob not found");
413
393
 
414
- return new Response(object.body, {
394
+ return new Response(blob.body, {
415
395
  headers: {
416
- "content-type": type,
396
+ "content-type": c.req.query("type") || blob.type,
417
397
  "content-disposition": `attachment; filename*=UTF-8''${encodeURIComponent(c.req.param("name"))}`,
418
- "cache-control": "private, immutable, max-age=31536000",
398
+ "cache-control": blob.mutable
399
+ ? "private, no-store"
400
+ : "private, immutable, max-age=31536000",
419
401
  },
420
402
  });
421
403
  })
422
- .post(`${JMAP_PATH}/upload/:accountId`, async (c) => {
423
- // Uploads become attachments of mail being sent.
424
- const refused = missingScope(c, MAIL_SEND_SCOPE);
404
+ .post(
405
+ `${JMAP_PATH}/upload/:accountId`,
406
+ // RFC 8620 §6.1: a body over maxSizeUpload is refused with the limit problem.
407
+ bodyLimit({
408
+ maxSize: MAX_COMPOSER_ATTACHMENT_BYTES,
409
+ onError: (c) =>
410
+ problem(
411
+ c,
412
+ 413,
413
+ "urn:ietf:params:jmap:error:limit",
414
+ "The upload is too large"
415
+ ),
416
+ }),
417
+ async (c) => {
418
+ const user = c.get("jmapUser");
425
419
 
426
- if (refused) return refused;
427
- const user = c.get("jmapUser");
420
+ const account = (await jmapAccounts(c.env, user.id)).find(
421
+ (item) => item.id === c.req.param("accountId")
422
+ );
428
423
 
429
- const account = (await jmapAccounts(c.env, user.id)).find(
430
- (item) => item.id === c.req.param("accountId")
431
- );
424
+ // Uploads become attachments of mail being sent, or messages imported
425
+ // into the person's own mailbox (Email/import, like moving mail there).
426
+ const imports =
427
+ account?.isPersonal === true &&
428
+ user.scopes.includes(MAIL_ORGANIZE_SCOPE);
432
429
 
433
- if (!account) return problem(c, 404, "about:blank", "Account not found");
430
+ const refused = imports ? null : missingScope(c, MAIL_SEND_SCOPE);
434
431
 
435
- // Uploads become attachments of sent mail, so they need send access.
436
- if (!account.canSend) {
437
- return problem(c, 403, "about:blank", "This account cannot send");
438
- }
432
+ if (refused) return refused;
439
433
 
440
- const rateExceeded = await overRateLimit(
441
- c,
442
- "RATE_LIMIT_30",
443
- "mail-upload",
444
- user.id
445
- );
434
+ if (!account) return problem(c, 404, "about:blank", "Account not found");
446
435
 
447
- if (rateExceeded) {
448
- return problem(c, 429, "about:blank", "Too many uploads");
449
- }
436
+ if (!imports && !account.canSend) {
437
+ return problem(c, 403, "about:blank", "This account cannot send");
438
+ }
450
439
 
451
- const contentType =
452
- c.req.header("content-type")?.trim() || "application/octet-stream";
440
+ const rateExceeded = await overRateLimit(
441
+ c,
442
+ "RATE_LIMIT_30",
443
+ "mail-upload",
444
+ user.id
445
+ );
453
446
 
454
- const declared = Number(c.req.header("content-length"));
455
- // Without a length, buffer the body to learn it; uploads are bounded anyway.
456
- let body: ReadableStream<Uint8Array> | ArrayBuffer | null = c.req.raw.body;
457
- let size = declared;
447
+ if (rateExceeded) {
448
+ return problem(c, 429, "about:blank", "Too many uploads");
449
+ }
458
450
 
459
- if (!Number.isSafeInteger(declared) || declared < 0) {
460
- body = await c.req.arrayBuffer();
461
- size = body.byteLength;
462
- }
451
+ const contentType =
452
+ c.req.header("content-type")?.trim() || "application/octet-stream";
463
453
 
464
- if (size > MAX_COMPOSER_ATTACHMENT_BYTES) {
465
- return problem(
466
- c,
467
- 413,
468
- "urn:ietf:params:jmap:error:limit",
469
- "The upload is too large"
470
- );
471
- }
454
+ const declared = Number(c.req.header("content-length"));
455
+ // A body of a known length streams to storage; one without was read
456
+ // whole by bodyLimit, and is stored from memory.
457
+ let body: ReadableStream<Uint8Array> | Blob | null = c.req.raw.body;
458
+ let size = declared;
472
459
 
473
- try {
474
- const intent = await createComposerUploadIntent({
475
- env: c.env,
476
- mailboxId: account.id,
477
- userId: user.id,
478
- filename: "upload",
479
- contentType,
480
- size,
481
- });
482
-
483
- await storeComposerUploadContent({
484
- env: c.env,
485
- mailboxId: account.id,
486
- userId: user.id,
487
- uploadId: intent.id,
488
- body,
489
- contentType,
490
- contentLength: size,
491
- });
492
-
493
- const upload = await finalizeComposerUpload({
494
- env: c.env,
495
- mailboxId: account.id,
496
- userId: user.id,
497
- uploadId: intent.id,
498
- defer: (task) => c.executionCtx.waitUntil(task),
499
- });
500
-
501
- return c.json(
502
- {
503
- accountId: account.id,
504
- blobId: `upl~${upload.id}`,
505
- type: upload.contentType,
506
- size: upload.size,
507
- },
508
- 201
509
- );
510
- } catch (error) {
511
- if (error instanceof UploadValidationError) {
512
- return problem(c, 400, "about:blank", error.message);
460
+ if (!Number.isSafeInteger(declared) || declared < 0) {
461
+ body = await c.req.blob();
462
+ size = body.size;
513
463
  }
514
464
 
515
- throw error;
465
+ try {
466
+ const intent = await createComposerUploadIntent({
467
+ env: c.env,
468
+ mailboxId: account.id,
469
+ userId: user.id,
470
+ filename: "upload",
471
+ contentType,
472
+ size,
473
+ });
474
+
475
+ await storeComposerUploadContent({
476
+ env: c.env,
477
+ mailboxId: account.id,
478
+ userId: user.id,
479
+ uploadId: intent.id,
480
+ body,
481
+ contentType,
482
+ contentLength: size,
483
+ });
484
+
485
+ const upload = await finalizeComposerUpload({
486
+ env: c.env,
487
+ mailboxId: account.id,
488
+ userId: user.id,
489
+ uploadId: intent.id,
490
+ });
491
+
492
+ return c.json(
493
+ {
494
+ accountId: account.id,
495
+ blobId: `upl~${upload.id}`,
496
+ type: upload.contentType,
497
+ size: upload.size,
498
+ },
499
+ 201
500
+ );
501
+ } catch (error) {
502
+ if (error instanceof UploadValidationError) {
503
+ return problem(c, 400, "about:blank", error.message);
504
+ }
505
+
506
+ throw error;
507
+ }
516
508
  }
517
- })
509
+ )
518
510
  .get(`${JMAP_PATH}/eventsource`, async (c) => {
519
511
  const refused = missingScope(c, MAIL_READ_SCOPE);
520
512
 
@@ -533,6 +525,5 @@ export const jmapRoutes = new Hono<JmapEnv>()
533
525
  (await jmapIdentity(c, user.token))?.scopes.includes(MAIL_READ_SCOPE)
534
526
  ),
535
527
  currentAccounts: () => jmapAccounts(c.env, user.id),
536
- defer: (task) => c.executionCtx.waitUntil(task),
537
528
  });
538
529
  });