@open-workspace/email 0.4.2 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) 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-sender-intel.ts +5 -1
  19. package/shared/mail.ts +70 -4
  20. package/shared/office-preview.ts +0 -4
  21. package/shared/pdfjs-assets.ts +1 -3
  22. package/shared/rich-content.ts +35 -0
  23. package/shared/signature.ts +15 -0
  24. package/src/admin/address-auto-reply.tsx +52 -0
  25. package/src/admin/blocked-senders.tsx +86 -66
  26. package/src/admin/forward-destinations.tsx +140 -0
  27. package/src/admin/mail-archive.tsx +134 -0
  28. package/src/admin/team-signature.tsx +90 -0
  29. package/src/client.tsx +130 -16
  30. package/src/mail/attachment-preview-dialog.tsx +13 -5
  31. package/src/mail/auto-reply-banner.tsx +61 -0
  32. package/src/mail/blocked-senders.tsx +124 -91
  33. package/src/mail/compose-window-chrome.tsx +20 -8
  34. package/src/mail/compose-window.tsx +391 -365
  35. package/src/mail/composer-asset-bookmarks.ts +47 -12
  36. package/src/mail/composer-attachment-list.tsx +42 -17
  37. package/src/mail/composer-editor-document.ts +54 -10
  38. package/src/mail/composer-editor.tsx +44 -44
  39. package/src/mail/composer-link-text.ts +42 -0
  40. package/src/mail/composer-recipient-fields.tsx +25 -16
  41. package/src/mail/composer-recipients.ts +62 -16
  42. package/src/mail/composer-session.ts +107 -23
  43. package/src/mail/composer-toolbar.tsx +15 -1
  44. package/src/mail/composer-upload-client.ts +29 -1
  45. package/src/mail/composer-upload-progress.ts +2 -2
  46. package/src/mail/conversation-actions-model.ts +56 -0
  47. package/src/mail/conversation-list.tsx +263 -128
  48. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  49. package/src/mail/conversation-message.tsx +257 -102
  50. package/src/mail/conversation-order.ts +12 -0
  51. package/src/mail/conversation-reply.tsx +313 -189
  52. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  53. package/src/mail/conversation-view.tsx +315 -85
  54. package/src/mail/delivery-indicator.tsx +33 -12
  55. package/src/mail/draft-attachments.ts +194 -0
  56. package/src/mail/email-html-body.tsx +97 -53
  57. package/src/mail/folder-cleanup-bar.tsx +193 -0
  58. package/src/mail/folder-glyph.tsx +5 -0
  59. package/src/mail/folder-manager.tsx +71 -38
  60. package/src/mail/mail-app-bar.tsx +15 -3
  61. package/src/mail/mail-dock.tsx +19 -3
  62. package/src/mail/mail-focus.ts +48 -0
  63. package/src/mail/mail-folders.ts +14 -2
  64. package/src/mail/mail-layout.css +20 -0
  65. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  66. package/src/mail/mail-nav-rail.tsx +7 -4
  67. package/src/mail/mail-nav.tsx +66 -46
  68. package/src/mail/mail-prefetch.ts +30 -9
  69. package/src/mail/mail-primitives.tsx +6 -4
  70. package/src/mail/mail-queries.ts +122 -20
  71. package/src/mail/mail-query-cache.ts +1085 -173
  72. package/src/mail/mail-search-params.ts +35 -0
  73. package/src/mail/mail-shell.tsx +32 -9
  74. package/src/mail/mailbox-ai-settings.tsx +56 -42
  75. package/src/mail/mailbox-realtime.tsx +4 -12
  76. package/src/mail/mailbox-rules.tsx +898 -0
  77. package/src/mail/message-actions.tsx +38 -26
  78. package/src/mail/message-attachments.tsx +20 -12
  79. package/src/mail/message-body.ts +53 -0
  80. package/src/mail/message-format.ts +8 -2
  81. package/src/mail/message-header.tsx +3 -1
  82. package/src/mail/message-translation.tsx +34 -67
  83. package/src/mail/original-message-sheet.tsx +63 -50
  84. package/src/mail/original-message.ts +6 -6
  85. package/src/mail/pane-splitter.tsx +3 -3
  86. package/src/mail/pdf-preview.tsx +70 -62
  87. package/src/mail/plain-message-text.tsx +28 -0
  88. package/src/mail/print-message.ts +31 -36
  89. package/src/mail/reader-pane.tsx +134 -103
  90. package/src/mail/recipient-combobox.tsx +52 -29
  91. package/src/mail/recipient-field-row.tsx +3 -0
  92. package/src/mail/rich-content.ts +128 -0
  93. package/src/mail/sanitize-email-html.ts +53 -32
  94. package/src/mail/sender-actions.tsx +48 -46
  95. package/src/mail/sender-authentication.tsx +1 -1
  96. package/src/mail/sender-dialogs.tsx +67 -43
  97. package/src/mail/sender-security.tsx +12 -11
  98. package/src/mail/signature.ts +43 -0
  99. package/src/mail/translation-html.ts +3 -3
  100. package/src/mail/types.ts +12 -0
  101. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  102. package/src/mail/use-composer-core.ts +286 -0
  103. package/src/mail/use-composer-navigation.ts +120 -0
  104. package/src/mail/use-composer-submission.ts +154 -19
  105. package/src/mail/use-conversation-actions.ts +292 -0
  106. package/src/mail/use-conversation-position.ts +51 -0
  107. package/src/mail/use-conversation-selection.ts +192 -89
  108. package/src/mail/use-draft-autosave.ts +394 -0
  109. package/src/mail/use-drafts.ts +194 -0
  110. package/src/mail/use-mail-controller.ts +758 -213
  111. package/src/mail/use-mail-data.ts +210 -100
  112. package/src/mail/use-mail-safety.ts +19 -38
  113. package/src/mail/use-mail-send.ts +18 -6
  114. package/src/mail/use-pdf-translation.ts +1 -1
  115. package/src/mail/use-reply-cc.ts +61 -0
  116. package/src/mail/use-visible-message-read.ts +128 -64
  117. package/src/pwa/push-key.ts +18 -0
  118. package/src/pwa/push-subscription.ts +88 -26
  119. package/src/settings/auto-reply-editor.tsx +454 -0
  120. package/src/settings/auto-reply-page.tsx +59 -0
  121. package/src/settings/mail-apps-page.tsx +52 -43
  122. package/src/settings/notifications-page.tsx +82 -67
  123. package/src/settings/rich-content-editor.tsx +182 -0
  124. package/src/settings/settings-queries.ts +57 -0
  125. package/src/settings/signature-editor.tsx +142 -0
  126. package/src/settings/signature-page.tsx +70 -0
  127. package/worker/admin/blocked-sender-routes.ts +10 -16
  128. package/worker/backups/eml.ts +185 -0
  129. package/worker/backups/file-parts.ts +140 -0
  130. package/worker/backups/mail-backup.ts +644 -0
  131. package/worker/backups/settings-backup.ts +866 -0
  132. package/worker/backups/stream-eml.ts +73 -0
  133. package/worker/db/schema.ts +89 -5
  134. package/worker/jmap/attachment-blobs.ts +113 -0
  135. package/worker/jmap/blobs.ts +162 -0
  136. package/worker/jmap/draft-content.ts +42 -0
  137. package/worker/jmap/drafts.ts +70 -0
  138. package/worker/jmap/email-body.ts +152 -0
  139. package/worker/jmap/email-methods.ts +1223 -0
  140. package/worker/jmap/eventsource.ts +9 -8
  141. package/worker/jmap/import-methods.ts +205 -0
  142. package/worker/jmap/mailbox-methods.ts +187 -0
  143. package/worker/jmap/method-core.ts +379 -0
  144. package/worker/jmap/methods.ts +119 -1816
  145. package/worker/jmap/push-subscription-methods.ts +373 -0
  146. package/worker/jmap/push-types.ts +46 -2
  147. package/worker/jmap/push.ts +24 -31
  148. package/worker/jmap/routes.ts +144 -153
  149. package/worker/jmap/submission-methods.ts +395 -0
  150. package/worker/mail/access.ts +35 -12
  151. package/worker/mail/ai-classification.ts +2 -2
  152. package/worker/mail/archive-object.ts +96 -0
  153. package/worker/mail/archive-routes.ts +35 -0
  154. package/worker/mail/archive.ts +700 -0
  155. package/worker/mail/auth-headers.ts +57 -43
  156. package/worker/mail/auto-reply-routes.ts +260 -0
  157. package/worker/mail/auto-reply.ts +243 -0
  158. package/worker/mail/bimi.ts +53 -36
  159. package/worker/mail/bootstrap.ts +11 -3
  160. package/worker/mail/capabilities.ts +69 -0
  161. package/worker/mail/classification-signals.ts +1 -1
  162. package/worker/mail/confusables-data.ts +9 -0
  163. package/worker/mail/conversation-cursor.ts +6 -15
  164. package/worker/mail/delivery-events.ts +9 -7
  165. package/worker/mail/delivery-facts.ts +1 -1
  166. package/worker/mail/demo-routes.ts +3 -3
  167. package/worker/mail/doh.ts +3 -3
  168. package/worker/mail/download-links.ts +153 -0
  169. package/worker/mail/downloads.ts +2 -6
  170. package/worker/mail/draft-routes.ts +473 -0
  171. package/worker/mail/draft-sender.ts +54 -0
  172. package/worker/mail/edge-cache.ts +41 -55
  173. package/worker/mail/email-routing.ts +123 -0
  174. package/worker/mail/forward-destinations.ts +114 -0
  175. package/worker/mail/forward-downloads.ts +115 -0
  176. package/worker/mail/forward-html.ts +85 -0
  177. package/worker/mail/header-metadata.ts +2 -5
  178. package/worker/mail/impersonation.ts +102 -101
  179. package/worker/mail/import-routes.ts +29 -82
  180. package/worker/mail/import.ts +130 -0
  181. package/worker/mail/inbound-delivery.ts +6 -5
  182. package/worker/mail/inbound-threading.ts +15 -2
  183. package/worker/mail/inbound.ts +58 -28
  184. package/worker/mail/ip-intel.ts +8 -17
  185. package/worker/mail/isolate-cache.ts +1 -1
  186. package/worker/mail/mailbox-deletion.ts +33 -12
  187. package/worker/mail/mailbox-directory.ts +39 -65
  188. package/worker/mail/mailing-list.ts +29 -58
  189. package/worker/mail/message-security.ts +19 -8
  190. package/worker/mail/message-view.ts +12 -10
  191. package/worker/mail/office-conversion.ts +3 -5
  192. package/worker/mail/office-preview-container.ts +3 -8
  193. package/worker/mail/outbound-content.ts +139 -65
  194. package/worker/mail/outbound-delivery.ts +20 -17
  195. package/worker/mail/outbound-service.ts +34 -9
  196. package/worker/mail/outbound.ts +146 -75
  197. package/worker/mail/outgoing-context.ts +60 -30
  198. package/worker/mail/participants.ts +10 -15
  199. package/worker/mail/plain-body.ts +39 -0
  200. package/worker/mail/push-endpoint.ts +17 -0
  201. package/worker/mail/push-notifications.ts +53 -62
  202. package/worker/mail/quote-parser.ts +36 -24
  203. package/worker/mail/receive.ts +146 -39
  204. package/worker/mail/recipients.ts +1 -1
  205. package/worker/mail/remote-proxy.ts +3 -3
  206. package/worker/mail/repeat.ts +1 -1
  207. package/worker/mail/reply-plan.ts +124 -26
  208. package/worker/mail/rfc.ts +15 -7
  209. package/worker/mail/rich-content.ts +207 -0
  210. package/worker/mail/routes.ts +698 -304
  211. package/worker/mail/routing.ts +274 -0
  212. package/worker/mail/rules.ts +230 -0
  213. package/worker/mail/safety-routes.ts +88 -86
  214. package/worker/mail/schemas.ts +222 -31
  215. package/worker/mail/search.ts +25 -2
  216. package/worker/mail/security-settings.ts +4 -10
  217. package/worker/mail/send-message.ts +238 -0
  218. package/worker/mail/sender-intel.ts +12 -20
  219. package/worker/mail/signature-routes.ts +206 -0
  220. package/worker/mail/signatures.ts +195 -0
  221. package/worker/mail/spamhaus.ts +28 -16
  222. package/worker/mail/storage-keys.ts +35 -0
  223. package/worker/mail/unsubscribe.ts +19 -41
  224. package/worker/mail/uploads.ts +192 -80
  225. package/worker/mail/webhook-source.ts +3 -2
  226. package/worker/mail/workspace-safety.ts +194 -60
  227. package/worker/mailbox/demo.ts +13 -15
  228. package/worker/mailbox/email-index.ts +65 -35
  229. package/worker/mailbox/folder-model.ts +0 -20
  230. package/worker/mailbox/import-placement.ts +21 -36
  231. package/worker/mailbox/inbound-decision.ts +114 -0
  232. package/worker/mailbox/inbox-counts.ts +45 -25
  233. package/worker/mailbox/index.ts +756 -3201
  234. package/worker/mailbox/jmap-change-log.ts +195 -0
  235. package/worker/mailbox/jmap-email-rows.ts +186 -0
  236. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  237. package/worker/mailbox/jmap-placement.ts +139 -0
  238. package/worker/mailbox/jmap-query-filter.ts +231 -0
  239. package/worker/mailbox/jmap-store.ts +167 -299
  240. package/worker/mailbox/mailbox-auto-reply.ts +316 -0
  241. package/worker/mailbox/mailbox-backup.ts +538 -0
  242. package/worker/mailbox/mailbox-drafts.ts +417 -0
  243. package/worker/mailbox/mailbox-folders.ts +242 -0
  244. package/worker/mailbox/mailbox-import.ts +455 -0
  245. package/worker/mailbox/mailbox-inbound.ts +934 -0
  246. package/worker/mailbox/mailbox-jmap.ts +294 -0
  247. package/worker/mailbox/mailbox-outbound.ts +413 -0
  248. package/worker/mailbox/mailbox-rules.ts +336 -0
  249. package/worker/mailbox/mailbox-senders.ts +294 -0
  250. package/worker/mailbox/mailbox-storage.ts +438 -0
  251. package/worker/mailbox/mailbox-views.ts +891 -0
  252. package/worker/mailbox/model.ts +1 -0
  253. package/worker/mailbox/office-preview-jobs.ts +59 -47
  254. package/worker/mailbox/placement.ts +933 -0
  255. package/worker/mailbox/restore-thread.ts +52 -0
  256. package/worker/mailbox/retention.ts +36 -0
  257. package/worker/mailbox/schema.ts +200 -1
  258. package/worker/mailbox/senders.ts +216 -178
  259. package/worker/mailbox/spam-undo-filing.ts +138 -0
  260. package/worker/mailbox/spam-undo.ts +253 -0
  261. package/worker/mailbox/support.ts +416 -0
  262. package/worker/mcp/mail-action-tools.ts +161 -1
  263. package/worker/mcp/mail-compose-tools.ts +7 -1
  264. package/worker/mcp/mail-safety-tools.ts +4 -4
  265. package/worker/module.ts +23 -4
  266. package/src/mail/use-compose-submission.ts +0 -208
  267. package/src/mail/use-reply-submission.ts +0 -114
  268. package/worker/mail/capped-body.ts +0 -36
@@ -0,0 +1,395 @@
1
+ /** Thread/get, Identity/get and EmailSubmission/set: sending drafts. */
2
+ import { z } from "zod";
3
+
4
+ import { composeSchema } from "../mail/schemas";
5
+ import { sendMessage } from "../mail/send-message";
6
+ import { mailboxStub } from "../mailbox";
7
+ import { isStoredDraftId, replySource } from "./drafts";
8
+ import { emailSet } from "./email-methods";
9
+ import type {
10
+ Draft,
11
+ JmapAccount,
12
+ JsonObject,
13
+ RequestState,
14
+ } from "./method-core";
15
+ import {
16
+ MethodError,
17
+ account,
18
+ accountId,
19
+ createdId,
20
+ draftIssue,
21
+ idList,
22
+ invalidProperties,
23
+ setError,
24
+ pick,
25
+ properties,
26
+ setObjects,
27
+ setResult,
28
+ } from "./method-core";
29
+
30
+ // --------------------------------------------------- threads and identities
31
+
32
+ export const threadGetArguments = z.object({ accountId, ids: idList });
33
+
34
+ export async function threadGet(
35
+ state: RequestState,
36
+ args: z.output<typeof threadGetArguments>
37
+ ) {
38
+ const owner = account(state, args.accountId);
39
+
40
+ const result = await mailboxStub(state.context.env, owner.id).jmapThreads(
41
+ args.ids,
42
+ state.context.user.id
43
+ );
44
+
45
+ const threads = new Map(
46
+ result.threads.map((thread) => [thread.id, thread.emailIds])
47
+ );
48
+
49
+ return {
50
+ accountId: owner.id,
51
+ state: result.state,
52
+ list: args.ids.flatMap((id) => {
53
+ const emailIds = threads.get(id);
54
+
55
+ return emailIds ? [{ id, emailIds }] : [];
56
+ }),
57
+ notFound: args.ids.filter((id) => !threads.has(id)),
58
+ };
59
+ }
60
+
61
+ export const identityGetArguments = z.object({
62
+ accountId,
63
+ ids: idList.nullish(),
64
+ properties,
65
+ });
66
+
67
+ export function identityGet(
68
+ state: RequestState,
69
+ args: z.output<typeof identityGetArguments>
70
+ ) {
71
+ const owner = account(state, args.accountId);
72
+
73
+ const list = owner.canSend
74
+ ? [
75
+ {
76
+ id: owner.id,
77
+ name: owner.displayName,
78
+ email: owner.address,
79
+ replyTo: null,
80
+ bcc: null,
81
+ textSignature: "",
82
+ htmlSignature: "",
83
+ mayDelete: false,
84
+ },
85
+ ]
86
+ : [];
87
+
88
+ const ids = args.ids ?? list.map((identity) => identity.id);
89
+
90
+ return {
91
+ accountId: owner.id,
92
+ state: "1",
93
+ list: list.flatMap((identity) =>
94
+ ids.includes(identity.id) ? [pick(identity, args.properties)] : []
95
+ ),
96
+ notFound: ids.filter((id) => id !== owner.id || !owner.canSend),
97
+ };
98
+ }
99
+
100
+ const submissionCreate = z.object({
101
+ emailId: z.string(),
102
+ identityId: z.string().optional(),
103
+ // The transport derives its SMTP envelope from the message headers.
104
+ envelope: z
105
+ .null({ error: "Custom delivery envelopes are not supported" })
106
+ .optional(),
107
+ });
108
+
109
+ export const submissionSetArguments = z.object({
110
+ accountId,
111
+ create: setObjects,
112
+ onSuccessDestroyEmail: z.array(z.string()).nullish(),
113
+ onSuccessUpdateEmail: setObjects,
114
+ });
115
+
116
+ const notADraft = {
117
+ type: "invalidProperties",
118
+ properties: ["emailId"],
119
+ description:
120
+ "Send a draft, or an email created by Email/set earlier in the same request",
121
+ };
122
+
123
+ /** A UUID that `name` always gives (its SHA-256, shaped as a version-5-like UUID). */
124
+ async function stableUuid(name: string) {
125
+ const bytes = new Uint8Array(
126
+ await crypto.subtle.digest("SHA-256", new TextEncoder().encode(name))
127
+ ).slice(0, 16);
128
+
129
+ bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x50;
130
+ bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
131
+ const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0"));
132
+
133
+ return [
134
+ hex.slice(0, 4),
135
+ hex.slice(4, 6),
136
+ hex.slice(6, 8),
137
+ hex.slice(8, 10),
138
+ hex.slice(10, 16),
139
+ ]
140
+ .map((part) => part.join(""))
141
+ .join("-");
142
+ }
143
+
144
+ /**
145
+ * A kept draft as a message to send, checked as the composer's would be.
146
+ * Replies and forwards started in the web app depend on the message they
147
+ * answer, so they are sent from there.
148
+ */
149
+ async function storedDraftMessage(
150
+ state: RequestState,
151
+ owner: JmapAccount,
152
+ id: string
153
+ ) {
154
+ const stored = await mailboxStub(state.context.env, owner.id).getDraft(
155
+ state.context.user.id,
156
+ id
157
+ );
158
+
159
+ if (!stored) return setError(notADraft);
160
+
161
+ if (stored.kind !== "compose") {
162
+ return setError({
163
+ ...notADraft,
164
+ description:
165
+ "Replies and forwards saved in the web app are sent from the web app",
166
+ });
167
+ }
168
+
169
+ const compose = composeSchema.safeParse({
170
+ // The same draft, sent again (a client retrying a slow send), is the
171
+ // same request: it is sent once.
172
+ draftId: stored.id,
173
+ draftVersion: stored.version,
174
+ requestId: await stableUuid(`jmap-draft:${stored.id}:${stored.version}`),
175
+ mailboxId: owner.id,
176
+ to: stored.to,
177
+ cc: stored.cc,
178
+ bcc: stored.bcc,
179
+ replyTo: stored.replyTo ?? undefined,
180
+ subject: stored.subject,
181
+ bodyText: stored.bodyText,
182
+ bodyHtml: stored.bodyHtml ?? undefined,
183
+ attachments: stored.attachments.map((file) => ({
184
+ uploadId: file.uploadId,
185
+ disposition: file.disposition,
186
+ contentId: file.contentId ?? undefined,
187
+ })),
188
+ });
189
+
190
+ if (!compose.success) {
191
+ return setError(
192
+ invalidProperties(compose.error.issues.map(draftIssue), {
193
+ topLevel: true,
194
+ })
195
+ );
196
+ }
197
+
198
+ return {
199
+ draft: {
200
+ accountId: owner.id,
201
+ compose: compose.data,
202
+ answers: { messageIds: [], emailId: stored.sourceEmailId },
203
+ },
204
+ };
205
+ }
206
+
207
+ /**
208
+ * Sends a draft as the account, as the app sends a new message
209
+ * (sendMessage); a failure is the reason it was not sent. A reply joins the
210
+ * conversation it answers from the alias the message came through. The
211
+ * client wrote the quote and any signature: none is added.
212
+ */
213
+ async function sendDraft(
214
+ state: RequestState,
215
+ owner: JmapAccount,
216
+ draft: Draft
217
+ ) {
218
+ try {
219
+ return await sendMessage({
220
+ env: state.context.env,
221
+ requestUrl: state.context.requestUrl,
222
+ sender: state.context.user,
223
+ keepDraft: true,
224
+ mailbox: owner,
225
+ request: {
226
+ kind: "new",
227
+ message: draft.compose,
228
+ answers: await replySource(state, owner, draft.answers),
229
+ },
230
+ });
231
+ } catch (error) {
232
+ return {
233
+ error:
234
+ error instanceof Error
235
+ ? error.message
236
+ : "The message could not be sent",
237
+ };
238
+ }
239
+ }
240
+
241
+ export async function submissionSet(
242
+ state: RequestState,
243
+ args: z.output<typeof submissionSetArguments>,
244
+ callId: string
245
+ ) {
246
+ const owner = account(state, args.accountId);
247
+
248
+ if (!owner.canSend) {
249
+ throw new MethodError("forbidden", "This account cannot send");
250
+ }
251
+
252
+ const created = new Map<string, JsonObject>();
253
+ const notCreated = new Map<string, JsonObject>();
254
+ const sentDrafts = new Map<string, { emailId: string; version?: number }>();
255
+
256
+ for (const [creationId, input] of Object.entries(args.create ?? {})) {
257
+ const parsed = submissionCreate.safeParse(input);
258
+
259
+ if (!parsed.success) {
260
+ notCreated.set(creationId, invalidProperties(parsed.error.issues));
261
+ continue;
262
+ }
263
+
264
+ const submission = parsed.data;
265
+
266
+ const emailId = submission.emailId.startsWith("#")
267
+ ? createdId(state, submission.emailId.slice(1))
268
+ : submission.emailId;
269
+
270
+ const sendable =
271
+ emailId !== undefined && isStoredDraftId(emailId)
272
+ ? // oxlint-disable-next-line eslint/no-await-in-loop -- submissions send mail in the order the client gave them
273
+ await storedDraftMessage(state, owner, emailId)
274
+ : {
275
+ draft:
276
+ emailId === undefined ? undefined : state.drafts.get(emailId),
277
+ };
278
+
279
+ if ("error" in sendable) {
280
+ notCreated.set(creationId, sendable.error);
281
+ continue;
282
+ }
283
+
284
+ const { draft } = sendable;
285
+
286
+ if (emailId === undefined || !draft || draft.accountId !== owner.id) {
287
+ notCreated.set(creationId, notADraft);
288
+ continue;
289
+ }
290
+
291
+ if (
292
+ submission.identityId !== undefined &&
293
+ submission.identityId !== owner.id
294
+ ) {
295
+ notCreated.set(creationId, {
296
+ type: "invalidProperties",
297
+ properties: ["identityId"],
298
+ description: "Unknown identity",
299
+ });
300
+ continue;
301
+ }
302
+
303
+ // oxlint-disable-next-line eslint/no-await-in-loop -- submissions send mail in the order the client gave them
304
+ const sent = await sendDraft(state, owner, draft);
305
+
306
+ if ("error" in sent) {
307
+ notCreated.set(creationId, {
308
+ type: "forbiddenToSend",
309
+ description: sent.error,
310
+ });
311
+ continue;
312
+ }
313
+
314
+ if (sent.email.transportState !== "submitted") {
315
+ notCreated.set(creationId, {
316
+ type: "serverFail",
317
+ description:
318
+ sent.email.transportState === "failed"
319
+ ? sent.email.transportError ||
320
+ "The message could not be prepared for sending"
321
+ : "Submission was not confirmed. Check Sent before trying again.",
322
+ });
323
+ continue;
324
+ }
325
+
326
+ const id = `sub-${sent.email.id}`;
327
+ state.createdIds.set(creationId, id);
328
+ sentDrafts.set(id, { emailId, version: draft.compose.draftVersion });
329
+ created.set(creationId, {
330
+ id,
331
+ threadId: sent.email.conversationId,
332
+ emailId: sent.email.id,
333
+ sendAt: new Date().toISOString(),
334
+ undoStatus: "final",
335
+ });
336
+ }
337
+
338
+ // Follow-ups address submissions. Only a successful submission in this call
339
+ // can name the draft to pass to Email/set.
340
+ const submittedVersions = new Map<string, number>();
341
+
342
+ function submittedDraft(reference: string) {
343
+ const id = reference.startsWith("#")
344
+ ? createdId(state, reference.slice(1))
345
+ : reference;
346
+
347
+ const draft = id === undefined ? undefined : sentDrafts.get(id);
348
+
349
+ if (draft?.version !== undefined) {
350
+ submittedVersions.set(draft.emailId, draft.version);
351
+ }
352
+
353
+ return draft?.emailId;
354
+ }
355
+
356
+ const update = Object.fromEntries(
357
+ Object.entries(args.onSuccessUpdateEmail ?? {}).flatMap(([ref, patch]) => {
358
+ const id = submittedDraft(ref);
359
+
360
+ return id === undefined ? [] : [[id, patch] as const];
361
+ })
362
+ );
363
+
364
+ const destroy = (args.onSuccessDestroyEmail ?? []).flatMap((ref) => {
365
+ const submitted = submittedDraft(ref);
366
+
367
+ return submitted ? [submitted] : [];
368
+ });
369
+
370
+ if (Object.keys(update).length || destroy.length) {
371
+ const result = await emailSet(
372
+ state,
373
+ {
374
+ accountId: owner.id,
375
+ update,
376
+ destroy,
377
+ },
378
+ submittedVersions
379
+ );
380
+
381
+ state.after.push(["Email/set", result, callId]);
382
+ }
383
+
384
+ return {
385
+ accountId: owner.id,
386
+ oldState: "1",
387
+ newState: "1",
388
+ created: setResult(created),
389
+ notCreated: setResult(notCreated),
390
+ updated: null,
391
+ destroyed: null,
392
+ notUpdated: null,
393
+ notDestroyed: null,
394
+ };
395
+ }
@@ -1,8 +1,5 @@
1
1
  import {
2
2
  createDb,
3
- mailboxAccess,
4
- mailboxes,
5
- sessions,
6
3
  mailboxAddressSql,
7
4
  mailboxKind,
8
5
  mailboxKindOrderSql,
@@ -13,11 +10,16 @@ import type {
13
10
  AppEnv,
14
11
  Database,
15
12
  } from "@open-workspace/core/module";
16
- import { and, desc, eq, gt, sql } from "drizzle-orm";
13
+ import {
14
+ mailboxAccess,
15
+ mailboxes,
16
+ sessions,
17
+ } from "@open-workspace/core/schema";
18
+ import { and, desc, eq, gt, isNull, or, sql } from "drizzle-orm";
17
19
  import type { Context } from "hono";
18
20
  import { z } from "zod";
19
21
 
20
- import { mailboxCounts, mailboxReadCounts } from "../db/schema";
22
+ import { mailboxCounts, mailboxReadCounts, signatures } from "../db/schema";
21
23
 
22
24
  const accessColumns = {
23
25
  id: mailboxes.id,
@@ -41,6 +43,11 @@ const listColumns = {
41
43
  version: sql<number>`coalesce(${mailboxCounts.version}, 0)`.as(
42
44
  "counts_version"
43
45
  ),
46
+ signatureUserId: signatures.userId,
47
+ signatureMailboxId: signatures.mailboxId,
48
+ signatureHtml: signatures.html,
49
+ signatureUseOnNew: signatures.useOnNew,
50
+ signatureUseOnReply: signatures.useOnReply,
44
51
  };
45
52
 
46
53
  const inboxCountsJoin = eq(mailboxCounts.mailboxId, mailboxAccess.mailboxId);
@@ -50,6 +57,18 @@ const readCountsJoin = and(
50
57
  eq(mailboxReadCounts.userId, mailboxAccess.userId)
51
58
  );
52
59
 
60
+ /**
61
+ * The signature sending from each mailbox adds: a team address's own, or the
62
+ * listing person's for their own mailbox (signatures.ts, signatureOwner).
63
+ */
64
+ const signatureJoin = or(
65
+ and(isNull(mailboxes.ownerUserId), eq(signatures.mailboxId, mailboxes.id)),
66
+ and(
67
+ eq(mailboxes.ownerUserId, mailboxAccess.userId),
68
+ eq(signatures.userId, mailboxAccess.userId)
69
+ )
70
+ );
71
+
53
72
  const listOrder = [
54
73
  mailboxKindOrderSql,
55
74
  desc(mailboxes.isPrimary),
@@ -70,6 +89,11 @@ export const mailboxListRowSchema = accessRowSchema.extend({
70
89
  isPrimary: z.boolean(),
71
90
  unreadCount: z.number(),
72
91
  version: z.number(),
92
+ signatureUserId: z.string().nullable(),
93
+ signatureMailboxId: z.string().nullable(),
94
+ signatureHtml: z.string().nullable(),
95
+ signatureUseOnNew: z.boolean().nullable(),
96
+ signatureUseOnReply: z.boolean().nullable(),
73
97
  });
74
98
 
75
99
  export type MailboxListRow = z.infer<typeof mailboxListRowSchema>;
@@ -99,6 +123,7 @@ function listQuery(db: Database, userId: string) {
99
123
  .innerJoin(mailboxes, eq(mailboxAccess.mailboxId, mailboxes.id))
100
124
  .leftJoin(mailboxCounts, inboxCountsJoin)
101
125
  .leftJoin(mailboxReadCounts, readCountsJoin)
126
+ .leftJoin(signatures, signatureJoin)
102
127
  .where(eq(mailboxAccess.userId, userId))
103
128
  .orderBy(...listOrder);
104
129
  }
@@ -127,6 +152,7 @@ export function sessionMailboxListQuery(
127
152
  .innerJoin(mailboxes, eq(mailboxAccess.mailboxId, mailboxes.id))
128
153
  .leftJoin(mailboxCounts, inboxCountsJoin)
129
154
  .leftJoin(mailboxReadCounts, readCountsJoin)
155
+ .leftJoin(signatures, signatureJoin)
130
156
  .orderBy(...listOrder);
131
157
  }
132
158
 
@@ -141,10 +167,7 @@ export async function getMailboxAccess(
141
167
  }
142
168
 
143
169
  /** Mailboxes a person can open, personal first, then primary, then by name. */
144
- export function listAccessibleMailboxes(
145
- db: Database,
146
- userId: string
147
- ): Promise<MailboxListRow[]> {
170
+ export function listAccessibleMailboxes(db: Database, userId: string) {
148
171
  return listQuery(db, userId).all();
149
172
  }
150
173
 
@@ -155,14 +178,14 @@ type MailboxTarget = { kind: "list" } | { kind: "mailbox"; mailboxId: string };
155
178
  * routes read it: `/mail/mailboxes` (the list), `/mail/mailboxes/:id/...`, or
156
179
  * a `mailboxId` query parameter.
157
180
  */
158
- function mailboxTarget(c: Context<AppEnv>): MailboxTarget | null {
181
+ function mailboxTarget(c: Context<AppEnv>) {
159
182
  const match = /^(?:\/api)?\/mail\/mailboxes(?:\/([^/]+))?\/?/u.exec(
160
183
  c.req.path
161
184
  );
162
185
 
163
186
  if (match && !match[1]) {
164
187
  return c.req.method === "GET" && /\/mailboxes\/?$/u.test(c.req.path)
165
- ? { kind: "list" }
188
+ ? ({ kind: "list" } satisfies MailboxTarget)
166
189
  : null;
167
190
  }
168
191
 
@@ -174,7 +197,7 @@ function mailboxTarget(c: Context<AppEnv>): MailboxTarget | null {
174
197
  return {
175
198
  kind: "mailbox",
176
199
  mailboxId: match?.[1] ? decodeURIComponent(raw) : raw,
177
- };
200
+ } satisfies MailboxTarget;
178
201
  } catch {
179
202
  return null;
180
203
  }
@@ -56,7 +56,7 @@ export async function classifyInboundEmail(input: {
56
56
  model: string;
57
57
  run: AiObjectRunner;
58
58
  now?: () => number;
59
- }): Promise<EmailAiClassification> {
59
+ }) {
60
60
  const trustedFolderIds = new Set(input.folders.map((folder) => folder.id));
61
61
  const threshold = input.configuration.confidenceThreshold / 100;
62
62
 
@@ -125,7 +125,7 @@ export async function classifyInboundEmail(input: {
125
125
  folderId,
126
126
  folderConfidence: folderId ? parsed.folderConfidence : 0,
127
127
  reason: parsed.reason,
128
- };
128
+ } satisfies EmailAiClassification;
129
129
  } catch (error) {
130
130
  throw new EmailAiClassificationError(
131
131
  "The AI model could not classify the incoming message",
@@ -0,0 +1,96 @@
1
+ import { serializeEml } from "../backups/eml";
2
+
3
+ /** The pure rules of the mail archive (worker/mail/archive.ts). */
4
+
5
+ export type ArchiveDirection = "incoming" | "outgoing";
6
+
7
+ const RETRY_BASE_MS = 5 * 60_000;
8
+ const RETRY_MAX_MS = 6 * 60 * 60_000;
9
+
10
+ /** `<year>/<month>/<direction>/<id>.eml`, by when the message arrived or was sent. */
11
+ export function archiveObjectKey(
12
+ direction: ArchiveDirection,
13
+ id: string,
14
+ at: Date
15
+ ) {
16
+ const month = String(at.getUTCMonth() + 1).padStart(2, "0");
17
+
18
+ return `${at.getUTCFullYear()}/${month}/${direction}/${id}.eml`;
19
+ }
20
+
21
+ /** Where a copy that couldn't be archived right away waits in MAIL_STORAGE. */
22
+ export const ARCHIVE_STAGING_PREFIX = "archive-staging/";
23
+
24
+ export function archiveStagingKey(id: string) {
25
+ return `${ARCHIVE_STAGING_PREFIX}${id}.eml`;
26
+ }
27
+
28
+ /**
29
+ * Whether an open entry is due for another try: a fresh one a minute after
30
+ * it was made (the request that made it is usually copying it), then after
31
+ * 5 minutes, doubling up to 6 hours.
32
+ */
33
+ export function archiveRetryDue(
34
+ entry: { attempts: number; updatedAt: Date },
35
+ now: number
36
+ ) {
37
+ const wait = entry.attempts
38
+ ? Math.min(RETRY_BASE_MS * 2 ** (entry.attempts - 1), RETRY_MAX_MS)
39
+ : 60_000;
40
+
41
+ return now - entry.updatedAt.getTime() >= wait;
42
+ }
43
+
44
+ /**
45
+ * What the workspace hands Email Sending: its structured message, with
46
+ * addresses as plain strings and the sender as a name and address.
47
+ */
48
+ export type SentMessage = EmailMessageBuilder & {
49
+ from: EmailAddress;
50
+ to?: string | string[];
51
+ cc?: string | string[];
52
+ bcc?: string | string[];
53
+ replyTo?: string;
54
+ };
55
+
56
+ function mailAddresses(value: string | string[] | undefined) {
57
+ return [value ?? []].flat().map((address) => ({ address, name: null }));
58
+ }
59
+
60
+ /**
61
+ * A sent message as the archive keeps it: MIME rebuilt from exactly what
62
+ * Email Sending was given (it takes structured fields, not MIME) and the
63
+ * Message-ID it returned. The bytes on the wire, and Cloudflare's DKIM
64
+ * signature, are not in it. The same input always gives the same bytes.
65
+ */
66
+ export function sentEml(
67
+ sent: { id: string; date: Date; messageId: string },
68
+ message: SentMessage
69
+ ) {
70
+ return serializeEml({
71
+ id: sent.id,
72
+ from: [{ address: message.from.email, name: message.from.name || null }],
73
+ to: mailAddresses(message.to),
74
+ cc: mailAddresses(message.cc),
75
+ bcc: mailAddresses(message.bcc),
76
+ replyTo: mailAddresses(message.replyTo),
77
+ subject: message.subject,
78
+ date: sent.date,
79
+ messageId: sent.messageId,
80
+ // Threading headers are among `headers`, written as given.
81
+ inReplyTo: [],
82
+ references: [],
83
+ headers: message.headers,
84
+ text: message.text,
85
+ html: message.html,
86
+ attachments: (message.attachments ?? []).map((attachment) => ({
87
+ disposition: attachment.disposition,
88
+ contentId: attachment.contentId,
89
+ filename: attachment.filename,
90
+ type: attachment.type,
91
+ // SAFETY: every sender passes R2 objects' arrayBuffer() (outbound
92
+ // delivery, auto-reply images); EmailAttachment's type allows more.
93
+ content: attachment.content as ArrayBuffer,
94
+ })),
95
+ });
96
+ }
@@ -0,0 +1,35 @@
1
+ import {
2
+ apiError,
3
+ oauthScope,
4
+ requireAdmin,
5
+ requireAuth,
6
+ } from "@open-workspace/core/module";
7
+ import type { AppEnv } from "@open-workspace/core/module";
8
+ import { WORKSPACE_SCOPE } from "@open-workspace/core/shared";
9
+ import { Hono } from "hono";
10
+
11
+ import { archiveStatus, runArchiveTick } from "./archive";
12
+
13
+ /** Administration → Mail archive, at /api/mail/archive: administrators only, like backups. */
14
+ export const mailArchiveRoutes = new Hono<AppEnv>()
15
+ .use("*", requireAuth)
16
+ .use("*", oauthScope(WORKSPACE_SCOPE))
17
+ .use("*", requireAdmin)
18
+ .get("/", async (c) =>
19
+ c.json({ ok: true as const, ...(await archiveStatus(c.env)) })
20
+ )
21
+ /** Archive now: every open entry, without waiting for its backoff. */
22
+ .post("/run", (c) => {
23
+ if (!c.env.MAIL_ARCHIVE) {
24
+ return apiError(
25
+ c,
26
+ 409,
27
+ "NOT_READY",
28
+ "The mail archive is off: deploy with Email({ archive: { years } })"
29
+ );
30
+ }
31
+
32
+ c.executionCtx.waitUntil(runArchiveTick(c.env, new Date(), true));
33
+
34
+ return c.json({ ok: true as const }, 202);
35
+ });