@open-workspace/email 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.
Files changed (221) hide show
  1. package/README.md +22 -22
  2. package/alchemy/index.ts +273 -0
  3. package/drizzle/mailbox/0000_puzzling_dracula.sql +149 -0
  4. package/drizzle/mailbox/0001_mute_jack_flag.sql +12 -0
  5. package/drizzle/mailbox/meta/0000_snapshot.json +1002 -0
  6. package/drizzle/mailbox/meta/0001_snapshot.json +1002 -0
  7. package/drizzle/mailbox/meta/_journal.json +20 -0
  8. package/drizzle/mailbox/migrations.js +12 -0
  9. package/index.ts +3 -1
  10. package/migrations/{0000_email.sql → 0000_dry_moon_knight.sql} +26 -20
  11. package/migrations/meta/0000_snapshot.json +125 -109
  12. package/migrations/meta/_journal.json +2 -2
  13. package/package.json +74 -68
  14. package/shared/attachment-preview.ts +37 -27
  15. package/shared/folder-order.ts +106 -0
  16. package/shared/mail-authentication.ts +8 -3
  17. package/shared/mail-feedback.ts +18 -25
  18. package/shared/mail-headers.ts +114 -39
  19. package/shared/mail-import.ts +38 -0
  20. package/shared/mail-path.ts +42 -0
  21. package/shared/mail-received.ts +174 -31
  22. package/shared/mail-remote.ts +59 -2
  23. package/shared/mail-sender-intel.ts +22 -4
  24. package/shared/mail.ts +77 -28
  25. package/shared/module.ts +33 -0
  26. package/shared/office-preview.ts +14 -2
  27. package/shared/pdfjs-assets.ts +35 -0
  28. package/shared/permissions.ts +73 -0
  29. package/shared/webhooks.ts +41 -0
  30. package/src/admin/blocked-senders.tsx +189 -0
  31. package/src/client.tsx +97 -0
  32. package/src/lib/mail-api.ts +9 -0
  33. package/src/mail/attachment-preview-dialog.tsx +161 -0
  34. package/src/mail/blocked-senders.tsx +138 -0
  35. package/src/mail/compose-window-chrome.tsx +194 -0
  36. package/src/mail/compose-window.tsx +486 -0
  37. package/src/mail/composer-asset-bookmarks.ts +409 -0
  38. package/src/mail/composer-asset.tsx +229 -0
  39. package/src/mail/composer-attachment-list.tsx +138 -0
  40. package/src/mail/composer-editor-document.ts +65 -0
  41. package/src/mail/composer-editor.tsx +284 -0
  42. package/src/mail/composer-linked-attachment-text.ts +12 -0
  43. package/src/mail/composer-recipient-fields.tsx +165 -0
  44. package/src/mail/composer-recipients.ts +208 -0
  45. package/src/mail/composer-session.ts +562 -0
  46. package/src/mail/composer-toolbar.tsx +303 -0
  47. package/src/mail/composer-upload-client.ts +105 -0
  48. package/src/mail/composer-upload-progress.ts +53 -0
  49. package/src/mail/conversation-list.tsx +550 -0
  50. package/src/mail/conversation-loading-skeleton.tsx +119 -0
  51. package/src/mail/conversation-message.tsx +346 -0
  52. package/src/mail/conversation-reply.tsx +470 -0
  53. package/src/mail/conversation-selection-toolbar.tsx +322 -0
  54. package/src/mail/conversation-view.tsx +437 -0
  55. package/src/mail/delivery-indicator.tsx +272 -0
  56. package/src/mail/email-html-body.tsx +203 -0
  57. package/src/mail/folder-glyph.tsx +46 -0
  58. package/src/mail/folder-manager.tsx +532 -0
  59. package/src/mail/format-bytes.ts +7 -0
  60. package/src/mail/mail-app-bar.tsx +253 -0
  61. package/src/mail/mail-background.tsx +12 -0
  62. package/src/mail/mail-dock.tsx +137 -0
  63. package/src/mail/mail-folders.ts +44 -0
  64. package/src/mail/mail-layout.css +236 -0
  65. package/src/mail/mail-location.ts +73 -0
  66. package/src/mail/mail-mailbox-sheet.tsx +275 -0
  67. package/src/mail/mail-nav-rail.tsx +129 -0
  68. package/src/mail/mail-nav.tsx +324 -0
  69. package/src/mail/mail-prefetch.ts +59 -0
  70. package/src/mail/mail-primitives.tsx +66 -0
  71. package/src/mail/mail-queries.ts +209 -0
  72. package/src/mail/mail-query-cache.ts +486 -0
  73. package/src/mail/mail-seed.ts +47 -0
  74. package/src/mail/mail-shell.tsx +126 -0
  75. package/src/mail/mailbox-ai-settings.tsx +185 -0
  76. package/src/mail/mailbox-realtime.tsx +251 -0
  77. package/src/mail/mailbox-route.tsx +15 -0
  78. package/src/mail/message-actions.tsx +353 -0
  79. package/src/mail/message-attachments.tsx +200 -0
  80. package/src/mail/message-format.ts +75 -0
  81. package/src/mail/message-header.tsx +260 -0
  82. package/src/mail/message-translation.tsx +225 -0
  83. package/src/mail/original-message-sheet.tsx +619 -0
  84. package/src/mail/original-message.ts +191 -0
  85. package/src/mail/outbound-notification.ts +53 -0
  86. package/src/mail/pane-splitter.tsx +117 -0
  87. package/src/mail/pdf-preview-toolbar.tsx +152 -0
  88. package/src/mail/pdf-preview.css +44 -0
  89. package/src/mail/pdf-preview.tsx +156 -0
  90. package/src/mail/pdf-translation-layout.ts +95 -0
  91. package/src/mail/print-message.ts +92 -0
  92. package/src/mail/reader-pane.tsx +535 -0
  93. package/src/mail/recipient-combobox.tsx +335 -0
  94. package/src/mail/recipient-field-row.tsx +34 -0
  95. package/src/mail/reply-to-warning.tsx +50 -0
  96. package/src/mail/sanitize-email-html.ts +430 -0
  97. package/src/mail/sender-actions.tsx +149 -0
  98. package/src/mail/sender-authentication.tsx +485 -0
  99. package/src/mail/sender-dialogs.tsx +384 -0
  100. package/src/mail/sender-security.tsx +545 -0
  101. package/src/mail/toolbar-tooltip.tsx +29 -0
  102. package/src/mail/translation-html.ts +49 -0
  103. package/src/mail/translation-language.ts +21 -0
  104. package/src/mail/types.ts +53 -0
  105. package/src/mail/unread-document-indicator.tsx +60 -0
  106. package/src/mail/use-compose-submission.ts +208 -0
  107. package/src/mail/use-composer-attachment-preflight.ts +184 -0
  108. package/src/mail/use-composer-submission.ts +117 -0
  109. package/src/mail/use-conversation-selection.ts +186 -0
  110. package/src/mail/use-mail-controller.ts +427 -0
  111. package/src/mail/use-mail-data.ts +279 -0
  112. package/src/mail/use-mail-safety.ts +155 -0
  113. package/src/mail/use-mail-send.ts +142 -0
  114. package/src/mail/use-pdf-translation-overlay.ts +156 -0
  115. package/src/mail/use-pdf-translation.ts +100 -0
  116. package/src/mail/use-pdf-viewer.ts +215 -0
  117. package/src/mail/use-reply-submission.ts +114 -0
  118. package/src/mail/use-sanitized-email-html.ts +20 -0
  119. package/src/mail/use-visible-message-read.ts +138 -0
  120. package/src/pwa/push-subscription.ts +151 -0
  121. package/src/settings/mail-apps-page.tsx +235 -0
  122. package/src/settings/notifications-page.tsx +291 -0
  123. package/worker/admin/blocked-sender-routes.ts +166 -0
  124. package/worker/admin/schemas.ts +11 -0
  125. package/worker/bindings.d.ts +14 -10
  126. package/worker/db/schema.ts +63 -40
  127. package/worker/jmap/eventsource.ts +84 -16
  128. package/worker/jmap/methods.ts +1630 -524
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +140 -56
  131. package/worker/jmap/routes.ts +366 -105
  132. package/worker/mail/access.ts +258 -21
  133. package/worker/mail/ai-classification.ts +36 -20
  134. package/worker/mail/ai-translation.ts +13 -6
  135. package/worker/mail/auth-headers.ts +395 -137
  136. package/worker/mail/bimi.ts +200 -73
  137. package/worker/mail/bootstrap.ts +79 -0
  138. package/worker/mail/capped-body.ts +36 -0
  139. package/worker/mail/classification-signals.ts +35 -25
  140. package/worker/mail/conversation-cursor.ts +30 -19
  141. package/worker/mail/delivery-events.ts +88 -62
  142. package/worker/mail/delivery-facts.ts +46 -10
  143. package/worker/mail/demo-routes.ts +34 -10
  144. package/worker/mail/doh.ts +62 -23
  145. package/worker/mail/downloads.ts +75 -40
  146. package/worker/mail/edge-cache.ts +155 -0
  147. package/worker/mail/header-metadata.ts +88 -22
  148. package/worker/mail/impersonation.ts +160 -38
  149. package/worker/mail/import-routes.ts +313 -0
  150. package/worker/mail/inbound-delivery.ts +19 -9
  151. package/worker/mail/inbound-threading.ts +18 -8
  152. package/worker/mail/inbound.ts +82 -40
  153. package/worker/mail/ip-intel.ts +110 -27
  154. package/worker/mail/isolate-cache.ts +35 -0
  155. package/worker/mail/link-domains.ts +29 -7
  156. package/worker/mail/mailbox-deletion.ts +10 -4
  157. package/worker/mail/mailbox-directory.ts +16 -6
  158. package/worker/mail/mailing-list.ts +94 -39
  159. package/worker/mail/message-security.ts +90 -15
  160. package/worker/mail/message-view.ts +18 -6
  161. package/worker/mail/office-conversion.ts +31 -9
  162. package/worker/mail/office-preview-container.ts +40 -13
  163. package/worker/mail/office-preview-queue.ts +76 -32
  164. package/worker/mail/org-domain.ts +8 -1
  165. package/worker/mail/outbound-content.ts +71 -26
  166. package/worker/mail/outbound-delivery.ts +31 -17
  167. package/worker/mail/outbound-service.ts +48 -30
  168. package/worker/mail/outbound-threading.ts +30 -17
  169. package/worker/mail/outbound.ts +97 -70
  170. package/worker/mail/outgoing-context.ts +25 -15
  171. package/worker/mail/participants.ts +44 -29
  172. package/worker/mail/push-notifications.ts +271 -173
  173. package/worker/mail/quote-parser.ts +21 -10
  174. package/worker/mail/r2-presigned-urls.ts +31 -25
  175. package/worker/mail/receive.ts +23 -11
  176. package/worker/mail/recipients.ts +6 -1
  177. package/worker/mail/remote-proxy.ts +187 -31
  178. package/worker/mail/remote-routes.ts +87 -0
  179. package/worker/mail/remote-token.ts +104 -0
  180. package/worker/mail/repeat.ts +19 -0
  181. package/worker/mail/reply-plan.ts +62 -33
  182. package/worker/mail/rfc.ts +32 -7
  183. package/worker/mail/routes.ts +870 -541
  184. package/worker/mail/safety-routes.ts +328 -200
  185. package/worker/mail/schemas.ts +84 -105
  186. package/worker/mail/search.ts +1 -0
  187. package/worker/mail/security-settings.ts +41 -9
  188. package/worker/mail/sender-intel.ts +206 -51
  189. package/worker/mail/spamhaus.ts +92 -45
  190. package/worker/mail/unsubscribe.ts +76 -18
  191. package/worker/mail/uploads.ts +126 -93
  192. package/worker/mail/webhook-source.ts +35 -12
  193. package/worker/mail/workspace-safety.ts +97 -38
  194. package/worker/mailbox/demo-html.ts +7 -7
  195. package/worker/mailbox/demo-seed.ts +10 -44
  196. package/worker/mailbox/demo.ts +595 -225
  197. package/worker/mailbox/email-index.ts +53 -0
  198. package/worker/mailbox/folder-model.ts +53 -17
  199. package/worker/mailbox/import-placement.ts +88 -0
  200. package/worker/mailbox/inbox-counts.ts +106 -0
  201. package/worker/mailbox/index.ts +1734 -721
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +8 -6
  204. package/worker/mailbox/office-preview-jobs.ts +56 -25
  205. package/worker/mailbox/schema.ts +87 -66
  206. package/worker/mailbox/senders.ts +176 -70
  207. package/worker/mcp/mail-action-tools.ts +128 -87
  208. package/worker/mcp/mail-compose-tools.ts +133 -82
  209. package/worker/mcp/mail-query-tools.ts +120 -71
  210. package/worker/mcp/mail-safety-tools.ts +321 -248
  211. package/worker/mcp/schemas.ts +43 -0
  212. package/worker/mcp/tools.ts +13 -10
  213. package/worker/module.ts +43 -18
  214. package/worker/sql.d.ts +8 -0
  215. package/alchemy.ts +0 -142
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/shared/mail-rules.ts +0 -156
  218. package/worker/admin/report-routes.ts +0 -164
  219. package/worker/mail/reported-messages.ts +0 -68
  220. package/worker/mailbox/migrations.ts +0 -10
  221. package/worker/mailbox/rules.ts +0 -110
@@ -1,7 +1,8 @@
1
+ import type { AppEnv } from "@open-workspace/core/module";
2
+ import { createId } from "@open-workspace/core/module";
1
3
  import { z } from "zod";
4
+
2
5
  import { MAX_COMPOSER_ATTACHMENT_BYTES } from "../../shared/mail";
3
- import type { AppEnv } from "@open-workspace/core/worker/env.ts";
4
- import { createId } from "@open-workspace/core/worker/lib/ids.ts";
5
6
  import { signR2PutUrl } from "./r2-presigned-urls";
6
7
 
7
8
  type Bindings = AppEnv["Bindings"];
@@ -32,19 +33,21 @@ type UploadMeta = {
32
33
  finalizedAt: number | null;
33
34
  };
34
35
 
35
- const uploadMetaSchema = z.object({
36
- filename: z.string().min(1).max(255),
37
- contentType: z.string().min(1).max(255),
38
- size: z.number().int().positive().max(MAX_COMPOSER_ATTACHMENT_BYTES),
39
- uploadedBy: z.string().min(1),
40
- mailboxId: z.string().min(1),
41
- finalizedAt: z.number().int().nonnegative().nullable(),
42
- }).strict();
36
+ const uploadMetaSchema = z
37
+ .object({
38
+ filename: z.string().min(1).max(255),
39
+ contentType: z.string().min(1).max(255),
40
+ size: z.number().int().positive().max(MAX_COMPOSER_ATTACHMENT_BYTES),
41
+ uploadedBy: z.string().min(1),
42
+ mailboxId: z.string().min(1),
43
+ finalizedAt: z.number().int().nonnegative().nullable(),
44
+ })
45
+ .strict();
43
46
 
44
47
  function composerUploadPrefix(
45
48
  mailboxId: string,
46
49
  userId: string,
47
- uploadId: string,
50
+ uploadId: string
48
51
  ) {
49
52
  return `composer-uploads/${mailboxId}/${userId}/${uploadId}`;
50
53
  }
@@ -52,7 +55,7 @@ function composerUploadPrefix(
52
55
  export function composerUploadKey(
53
56
  mailboxId: string,
54
57
  userId: string,
55
- uploadId: string,
58
+ uploadId: string
56
59
  ) {
57
60
  return `${composerUploadPrefix(mailboxId, userId, uploadId)}/staging`;
58
61
  }
@@ -60,7 +63,7 @@ export function composerUploadKey(
60
63
  export function composerUploadFinalKey(
61
64
  mailboxId: string,
62
65
  userId: string,
63
- uploadId: string,
66
+ uploadId: string
64
67
  ) {
65
68
  return `${composerUploadPrefix(mailboxId, userId, uploadId)}/immutable`;
66
69
  }
@@ -68,7 +71,7 @@ export function composerUploadFinalKey(
68
71
  export function composerUploadMetaKey(
69
72
  mailboxId: string,
70
73
  userId: string,
71
- uploadId: string,
74
+ uploadId: string
72
75
  ) {
73
76
  return `${composerUploadPrefix(mailboxId, userId, uploadId)}/metadata.json`;
74
77
  }
@@ -76,7 +79,7 @@ export function composerUploadMetaKey(
76
79
  function composerUploadKeys(
77
80
  mailboxId: string,
78
81
  userId: string,
79
- uploadId: string,
82
+ uploadId: string
80
83
  ) {
81
84
  return {
82
85
  staging: composerUploadKey(mailboxId, userId, uploadId),
@@ -93,15 +96,18 @@ async function putUploadMeta(input: {
93
96
  await input.env.MAIL_STORAGE.put(
94
97
  input.metadataKey,
95
98
  JSON.stringify(input.meta),
96
- { httpMetadata: { contentType: "application/json" } },
99
+ { httpMetadata: { contentType: "application/json" } }
97
100
  );
98
101
  }
99
102
 
100
103
  async function readUploadMeta(env: Bindings, metadataKey: string) {
101
104
  const object = await env.MAIL_STORAGE.get(metadataKey);
105
+
102
106
  if (!object) return null;
107
+
103
108
  try {
104
109
  const parsed = uploadMetaSchema.safeParse(JSON.parse(await object.text()));
110
+
105
111
  return parsed.success ? parsed.data : null;
106
112
  } catch {
107
113
  return null;
@@ -110,26 +116,26 @@ async function readUploadMeta(env: Bindings, metadataKey: string) {
110
116
 
111
117
  export async function createComposerUploadIntent(input: {
112
118
  env: Bindings;
113
- requestOrigin: string;
114
119
  mailboxId: string;
115
120
  userId: string;
116
121
  filename: string;
117
122
  contentType: string;
118
123
  size: number;
119
- directOnly?: boolean;
120
124
  }): Promise<ComposerUploadIntent> {
121
125
  if (input.size <= 0) {
122
126
  throw new UploadValidationError("Attachment file is empty");
123
127
  }
128
+
124
129
  if (input.size > MAX_COMPOSER_ATTACHMENT_BYTES) {
125
130
  throw new UploadValidationError(
126
- `Attachments are limited to ${Math.floor(MAX_COMPOSER_ATTACHMENT_BYTES / 1_000_000)} MB per message`,
131
+ `Attachments are limited to ${Math.floor(MAX_COMPOSER_ATTACHMENT_BYTES / 1_000_000)} MB per message`
127
132
  );
128
133
  }
129
134
 
130
135
  const id = createId("upl");
131
136
  const keys = composerUploadKeys(input.mailboxId, input.userId, id);
132
137
  const filename = input.filename.trim().slice(0, 255) || "attachment";
138
+
133
139
  const contentType =
134
140
  input.contentType.trim().slice(0, 255) || "application/octet-stream";
135
141
 
@@ -146,38 +152,14 @@ export async function createComposerUploadIntent(input: {
146
152
  },
147
153
  });
148
154
 
149
- const headers = { "content-type": contentType };
150
- const presignedUrl = await signR2PutUrl({
151
- env: input.env,
152
- r2Key: keys.staging,
153
- contentType,
154
- });
155
- if (presignedUrl) {
156
- return {
157
- id,
158
- uploadUrl: presignedUrl,
159
- headers,
160
- filename,
161
- contentType,
162
- size: input.size,
163
- };
164
- }
165
-
166
- if (input.directOnly) {
167
- await input.env.MAIL_STORAGE.delete(keys.metadata);
168
- throw new DirectUploadUnavailableError(
169
- "Direct R2 attachment uploads are not configured",
170
- );
171
- }
172
-
173
- // Local / Deploy without R2 S3 API tokens: same client flow, Worker receives PUT.
174
- const fallback = new URL("/api/mail/uploads/content", input.requestOrigin);
175
- fallback.searchParams.set("mailboxId", input.mailboxId);
176
- fallback.searchParams.set("uploadId", id);
177
155
  return {
178
156
  id,
179
- uploadUrl: fallback.toString(),
180
- headers,
157
+ uploadUrl: await signR2PutUrl({
158
+ env: input.env,
159
+ r2Key: keys.staging,
160
+ contentType,
161
+ }),
162
+ headers: { "content-type": contentType },
181
163
  filename,
182
164
  contentType,
183
165
  size: input.size,
@@ -196,56 +178,66 @@ export async function storeComposerUploadContent(input: {
196
178
  if (!input.body) {
197
179
  throw new UploadValidationError("Attachment body is required");
198
180
  }
181
+
199
182
  const keys = composerUploadKeys(
200
183
  input.mailboxId,
201
184
  input.userId,
202
- input.uploadId,
185
+ input.uploadId
203
186
  );
187
+
204
188
  const meta = assertUploadOwner(
205
189
  await readUploadMeta(input.env, keys.metadata),
206
190
  input.userId,
207
- input.mailboxId,
191
+ input.mailboxId
208
192
  );
193
+
209
194
  if (meta.finalizedAt !== null) {
210
195
  throw new UploadValidationError("Attachment upload is already complete");
211
196
  }
197
+
212
198
  const contentType = (input.contentType || meta.contentType)
213
- .split(";", 1)[0]!
199
+ .split(";", 1)[0]
214
200
  .trim()
215
201
  .toLowerCase();
202
+
216
203
  if (contentType !== meta.contentType.trim().toLowerCase()) {
217
204
  throw new UploadValidationError("Attachment content type does not match");
218
205
  }
206
+
219
207
  if (
220
- input.contentLength !== undefined
221
- && (
222
- !Number.isSafeInteger(input.contentLength)
223
- || input.contentLength !== meta.size
224
- )
208
+ input.contentLength !== undefined &&
209
+ (!Number.isSafeInteger(input.contentLength) ||
210
+ input.contentLength !== meta.size)
225
211
  ) {
226
212
  throw new UploadValidationError("Attachment size does not match");
227
213
  }
228
214
 
229
215
  const sizeState = { mismatch: false };
230
216
  const uploadBody = uploadBodyWithExactSize(input.body, meta.size, sizeState);
217
+
231
218
  const write = input.env.MAIL_STORAGE.put(keys.staging, uploadBody.body, {
232
219
  httpMetadata: { contentType: meta.contentType },
233
220
  });
221
+
234
222
  const results = await Promise.allSettled([
235
223
  write,
236
224
  ...(uploadBody.completion ? [uploadBody.completion] : []),
237
225
  ]);
226
+
238
227
  const failure = results.find(
239
- (result): result is PromiseRejectedResult => result.status === "rejected",
228
+ (result): result is PromiseRejectedResult => result.status === "rejected"
240
229
  );
230
+
241
231
  if (failure || sizeState.mismatch) {
242
232
  await deleteStagingObject(input.env, keys.staging);
243
- if (sizeState.mismatch) {
244
- throw new UploadValidationError("Attachment size does not match");
245
- }
246
- throw failure!.reason;
233
+
234
+ if (failure && !sizeState.mismatch) throw failure.reason;
235
+
236
+ throw new UploadValidationError("Attachment size does not match");
247
237
  }
238
+
248
239
  const stored = await input.env.MAIL_STORAGE.head(keys.staging);
240
+
249
241
  if (!stored || stored.size !== meta.size) {
250
242
  await deleteStagingObject(input.env, keys.staging);
251
243
  throw new UploadValidationError("Attachment size does not match");
@@ -255,41 +247,53 @@ export async function storeComposerUploadContent(input: {
255
247
  function uploadBodyWithExactSize(
256
248
  body: ReadableStream<Uint8Array> | ArrayBuffer | Blob,
257
249
  expectedSize: number,
258
- state: { mismatch: boolean },
250
+ state: { mismatch: boolean }
259
251
  ) {
260
252
  if (body instanceof ArrayBuffer) {
261
253
  if (body.byteLength !== expectedSize) {
262
254
  throw new UploadValidationError("Attachment size does not match");
263
255
  }
256
+
264
257
  return { body, completion: null };
265
258
  }
259
+
266
260
  if (body instanceof Blob) {
267
261
  if (body.size !== expectedSize) {
268
262
  throw new UploadValidationError("Attachment size does not match");
269
263
  }
264
+
270
265
  return { body, completion: null };
271
266
  }
272
267
 
273
268
  const reader = body.getReader();
274
269
  let received = 0;
270
+
275
271
  const bounded = new ReadableStream<Uint8Array>({
276
272
  async pull(controller) {
277
273
  const chunk = await reader.read();
274
+
278
275
  if (chunk.done) {
279
276
  if (received !== expectedSize) state.mismatch = true;
280
277
  controller.close();
278
+
281
279
  return;
282
280
  }
281
+
283
282
  const remaining = expectedSize - received;
283
+
284
284
  if (chunk.value.byteLength > remaining) {
285
285
  state.mismatch = true;
286
+
286
287
  if (remaining > 0) {
287
288
  controller.enqueue(chunk.value.subarray(0, remaining));
288
289
  }
290
+
289
291
  await reader.cancel();
290
292
  controller.close();
293
+
291
294
  return;
292
295
  }
296
+
293
297
  received += chunk.value.byteLength;
294
298
  controller.enqueue(chunk.value);
295
299
  },
@@ -297,7 +301,9 @@ function uploadBodyWithExactSize(
297
301
  return reader.cancel(reason);
298
302
  },
299
303
  });
304
+
300
305
  const fixedLength = new FixedLengthStream(expectedSize);
306
+
301
307
  return {
302
308
  body: fixedLength.readable,
303
309
  completion: bounded.pipeTo(fixedLength.writable),
@@ -307,15 +313,12 @@ function uploadBodyWithExactSize(
307
313
  function assertUploadOwner(
308
314
  meta: UploadMeta | null,
309
315
  userId: string,
310
- mailboxId: string,
316
+ mailboxId: string
311
317
  ) {
312
- if (
313
- !meta
314
- || meta.uploadedBy !== userId
315
- || meta.mailboxId !== mailboxId
316
- ) {
318
+ if (!meta || meta.uploadedBy !== userId || meta.mailboxId !== mailboxId) {
317
319
  throw new UploadValidationError("Attachment upload was not found");
318
320
  }
321
+
319
322
  return meta;
320
323
  }
321
324
 
@@ -328,13 +331,15 @@ export async function loadComposerUploadMetadata(input: {
328
331
  const keys = composerUploadKeys(
329
332
  input.mailboxId,
330
333
  input.userId,
331
- input.uploadId,
334
+ input.uploadId
332
335
  );
336
+
333
337
  const meta = assertUploadOwner(
334
338
  await readUploadMeta(input.env, keys.metadata),
335
339
  input.userId,
336
- input.mailboxId,
340
+ input.mailboxId
337
341
  );
342
+
338
343
  return {
339
344
  id: input.uploadId,
340
345
  r2Key: meta.finalizedAt === null ? keys.staging : keys.immutable,
@@ -354,30 +359,36 @@ export async function finalizeComposerUpload(input: {
354
359
  const keys = composerUploadKeys(
355
360
  input.mailboxId,
356
361
  input.userId,
357
- input.uploadId,
362
+ input.uploadId
358
363
  );
364
+
359
365
  const meta = assertUploadOwner(
360
366
  await readUploadMeta(input.env, keys.metadata),
361
367
  input.userId,
362
- input.mailboxId,
368
+ input.mailboxId
363
369
  );
370
+
364
371
  if (meta.finalizedAt !== null) {
365
372
  const upload = await loadComposerUpload(input);
366
373
  await cleanupStagingAfterFinalization(input, keys.staging);
374
+
367
375
  return upload;
368
376
  }
369
377
 
370
378
  const staging = await input.env.MAIL_STORAGE.get(keys.staging);
379
+
371
380
  if (
372
- !staging
373
- || staging.size <= 0
374
- || staging.size !== meta.size
375
- || staging.size > MAX_COMPOSER_ATTACHMENT_BYTES
381
+ !staging ||
382
+ staging.size <= 0 ||
383
+ staging.size !== meta.size ||
384
+ staging.size > MAX_COMPOSER_ATTACHMENT_BYTES
376
385
  ) {
377
386
  const immutable = await input.env.MAIL_STORAGE.head(keys.immutable);
387
+
378
388
  if (immutable?.size === meta.size) {
379
389
  return completeComposerUploadFinalization(input, keys, meta);
380
390
  }
391
+
381
392
  // Do not delete metadata or the immutable key here: another finalizer may
382
393
  // already hold the valid staging body and be about to seal it.
383
394
  await deleteStagingObject(input.env, keys.staging);
@@ -386,18 +397,25 @@ export async function finalizeComposerUpload(input: {
386
397
 
387
398
  // The client never receives this key. A still-valid presigned staging URL
388
399
  // can be replayed, but it cannot mutate the immutable bytes used for send.
389
- const created = await input.env.MAIL_STORAGE.put(keys.immutable, staging.body, {
390
- httpMetadata: { contentType: meta.contentType },
391
- onlyIf: new Headers({ "if-none-match": "*" }),
392
- });
400
+ const created = await input.env.MAIL_STORAGE.put(
401
+ keys.immutable,
402
+ staging.body,
403
+ {
404
+ httpMetadata: { contentType: meta.contentType },
405
+ onlyIf: new Headers({ "if-none-match": "*" }),
406
+ }
407
+ );
408
+
393
409
  // A concurrent finalizer may win the conditional write. In that case its
394
410
  // first sealed snapshot remains authoritative for this upload id.
395
- const immutable = created
396
- ?? await input.env.MAIL_STORAGE.head(keys.immutable);
411
+ const immutable =
412
+ created ?? (await input.env.MAIL_STORAGE.head(keys.immutable));
413
+
397
414
  if (!immutable || immutable.size !== meta.size) {
398
415
  await deleteStagingObject(input.env, keys.staging);
399
416
  throw new UploadValidationError("Attachment upload is incomplete");
400
417
  }
418
+
401
419
  return completeComposerUploadFinalization(input, keys, meta);
402
420
  }
403
421
 
@@ -410,7 +428,7 @@ async function completeComposerUploadFinalization(
410
428
  defer?: (task: Promise<unknown>) => void;
411
429
  },
412
430
  keys: ReturnType<typeof composerUploadKeys>,
413
- meta: UploadMeta,
431
+ meta: UploadMeta
414
432
  ): Promise<UploadedAttachment> {
415
433
  await putUploadMeta({
416
434
  env: input.env,
@@ -421,6 +439,7 @@ async function completeComposerUploadFinalization(
421
439
  },
422
440
  });
423
441
  await cleanupStagingAfterFinalization(input, keys.staging);
442
+
424
443
  return {
425
444
  id: input.uploadId,
426
445
  r2Key: keys.immutable,
@@ -435,9 +454,10 @@ function cleanupStagingAfterFinalization(
435
454
  env: Bindings;
436
455
  defer?: (task: Promise<unknown>) => void;
437
456
  },
438
- key: string,
457
+ key: string
439
458
  ) {
440
459
  const cleanup = deleteStagingObject(input.env, key);
460
+
441
461
  if (input.defer) input.defer(cleanup);
442
462
  else return cleanup;
443
463
  }
@@ -460,24 +480,30 @@ export async function loadComposerUpload(input: {
460
480
  const keys = composerUploadKeys(
461
481
  input.mailboxId,
462
482
  input.userId,
463
- input.uploadId,
483
+ input.uploadId
464
484
  );
485
+
465
486
  const [object, meta] = await Promise.all([
466
487
  input.env.MAIL_STORAGE.head(keys.immutable),
467
488
  readUploadMeta(input.env, keys.metadata),
468
489
  ]);
469
- if (!object || !meta || typeof meta.finalizedAt !== "number") {
490
+
491
+ if (!object || !meta || meta.finalizedAt === null) {
470
492
  throw new UploadValidationError("Attachment upload was not found");
471
493
  }
494
+
472
495
  if (meta.uploadedBy !== input.userId || meta.mailboxId !== input.mailboxId) {
473
496
  throw new UploadValidationError("Attachment upload was not found");
474
497
  }
498
+
475
499
  if (object.size <= 0 || object.size !== meta.size) {
476
500
  throw new UploadValidationError("Attachment upload is incomplete");
477
501
  }
502
+
478
503
  if (object.size > MAX_COMPOSER_ATTACHMENT_BYTES) {
479
504
  throw new UploadValidationError("Attachment upload is invalid");
480
505
  }
506
+
481
507
  return {
482
508
  id: input.uploadId,
483
509
  r2Key: keys.immutable,
@@ -499,12 +525,18 @@ export async function describeComposerUpload(input: {
499
525
  filename: string;
500
526
  contentType: string;
501
527
  }) {
502
- const keys = composerUploadKeys(input.mailboxId, input.userId, input.uploadId);
528
+ const keys = composerUploadKeys(
529
+ input.mailboxId,
530
+ input.userId,
531
+ input.uploadId
532
+ );
533
+
503
534
  const meta = assertUploadOwner(
504
535
  await readUploadMeta(input.env, keys.metadata),
505
536
  input.userId,
506
- input.mailboxId,
537
+ input.mailboxId
507
538
  );
539
+
508
540
  await putUploadMeta({
509
541
  env: input.env,
510
542
  metadataKey: keys.metadata,
@@ -523,9 +555,11 @@ export async function copyStoredAttachmentToMessage(input: {
523
555
  contentType: string;
524
556
  }) {
525
557
  const source = await input.env.MAIL_STORAGE.get(input.sourceKey);
558
+
526
559
  if (!source?.body) {
527
560
  throw new UploadValidationError("Attachment was not found");
528
561
  }
562
+
529
563
  await input.env.MAIL_STORAGE.put(input.destinationKey, source.body, {
530
564
  httpMetadata: { contentType: input.contentType },
531
565
  });
@@ -533,7 +567,7 @@ export async function copyStoredAttachmentToMessage(input: {
533
567
 
534
568
  async function deleteComposerUploadObjects(
535
569
  env: Bindings,
536
- keys: ReturnType<typeof composerUploadKeys>,
570
+ keys: ReturnType<typeof composerUploadKeys>
537
571
  ) {
538
572
  try {
539
573
  await env.MAIL_STORAGE.delete([
@@ -556,11 +590,10 @@ export async function discardComposerUploads(input: {
556
590
  input.uploadIds.map((uploadId) =>
557
591
  deleteComposerUploadObjects(
558
592
  input.env,
559
- composerUploadKeys(input.mailboxId, input.userId, uploadId),
593
+ composerUploadKeys(input.mailboxId, input.userId, uploadId)
560
594
  )
561
- ),
595
+ )
562
596
  );
563
597
  }
564
598
 
565
599
  export class UploadValidationError extends Error {}
566
- export class DirectUploadUnavailableError extends Error {}
@@ -1,10 +1,16 @@
1
+ import {
2
+ createDb,
3
+ mailboxAddressSql,
4
+ mailboxKind,
5
+ mailboxes,
6
+ } from "@open-workspace/core/module";
7
+ import type { WorkspaceModule } from "@open-workspace/core/module";
1
8
  import { eq } from "drizzle-orm";
2
- import { createDb } from "@open-workspace/core/worker/db/client.ts";
3
- import { mailboxAddressSql, mailboxKind } from "@open-workspace/core/worker/db/mailboxes.ts";
4
- import { domains, mailboxes } from "@open-workspace/core/worker/db/schema.ts";
5
- import { headerAuthentication } from "./header-metadata";
9
+ import { z } from "zod";
10
+
6
11
  import { mailboxStub } from "../mailbox";
7
12
  import type { Email } from "../mailbox/schema";
13
+ import { headerAuthentication } from "./header-metadata";
8
14
 
9
15
  function publicEmail(email: Email, bodyHtml: string | null) {
10
16
  return {
@@ -38,11 +44,26 @@ function publicEmail(email: Email, bodyHtml: string | null) {
38
44
  };
39
45
  }
40
46
 
41
- /** The payload of an email.* webhook event. */
42
- export async function emailWebhookData(env: Env, source: Record<string, unknown>) {
43
- if (typeof source.mailboxId !== "string" || typeof source.messageId !== "string") {
47
+ /** What outbound-service queues as an `EMAIL_WEBHOOK_SOURCE` source. */
48
+ const EmailWebhookSource = z.object({
49
+ mailboxId: z.string(),
50
+ messageId: z.string(),
51
+ });
52
+
53
+ type WebhookSourceBuilder = NonNullable<
54
+ WorkspaceModule["webhookSources"]
55
+ >[string];
56
+
57
+ /** The payload of a mail webhook event, from its `EMAIL_WEBHOOK_SOURCE` source. */
58
+ export const emailWebhookData: WebhookSourceBuilder = async (env, queued) => {
59
+ const parsed = EmailWebhookSource.safeParse(queued);
60
+
61
+ if (!parsed.success) {
44
62
  throw new Error("Email webhook source needs a mailbox and message");
45
63
  }
64
+
65
+ const source = parsed.data;
66
+
46
67
  const [mailbox, email] = await Promise.all([
47
68
  createDb(env.DB)
48
69
  .select({
@@ -52,20 +73,22 @@ export async function emailWebhookData(env: Env, source: Record<string, unknown>
52
73
  ownerUserId: mailboxes.ownerUserId,
53
74
  })
54
75
  .from(mailboxes)
55
- .innerJoin(domains, eq(mailboxes.domainId, domains.id))
56
76
  .where(eq(mailboxes.id, source.mailboxId))
57
77
  .limit(1)
58
- .then((rows) => rows[0]
59
- ? { ...rows[0], kind: mailboxKind(rows[0].ownerUserId) }
60
- : null),
78
+ .then(([row]) =>
79
+ row ? { ...row, kind: mailboxKind(row.ownerUserId) } : null
80
+ ),
61
81
  mailboxStub(env, source.mailboxId).getEmail(source.messageId),
62
82
  ]);
83
+
63
84
  if (!mailbox || !email) throw new Error("Webhook email no longer exists");
85
+
64
86
  const htmlObject = email.bodyHtmlR2Key
65
87
  ? await env.MAIL_STORAGE.get(email.bodyHtmlR2Key)
66
88
  : null;
89
+
67
90
  return {
68
91
  mailbox,
69
92
  email: publicEmail(email, htmlObject ? await htmlObject.text() : null),
70
93
  };
71
- }
94
+ };