@open-workspace/email 0.4.1 → 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 (271) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0002_good_komodo.sql +2 -0
  4. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  5. package/drizzle/mailbox/meta/0002_snapshot.json +1017 -0
  6. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  7. package/drizzle/mailbox/meta/_journal.json +14 -0
  8. package/drizzle/mailbox/migrations.js +5 -1
  9. package/migrations/0001_overrated_ricochet.sql +2 -0
  10. package/migrations/0002_after_0_4_2.sql +35 -0
  11. package/migrations/meta/0001_snapshot.json +564 -0
  12. package/migrations/meta/0002_snapshot.json +807 -0
  13. package/migrations/meta/_journal.json +14 -0
  14. package/package.json +23 -7
  15. package/shared/attachment-preview.ts +18 -8
  16. package/shared/folder-order.ts +31 -6
  17. package/shared/mail-headers.ts +3 -3
  18. package/shared/mail-html.ts +25 -0
  19. package/shared/mail-import.ts +0 -7
  20. package/shared/mail-received.ts +4 -4
  21. package/shared/mail-rule-actions.ts +47 -0
  22. package/shared/mail.ts +70 -4
  23. package/shared/office-preview.ts +0 -4
  24. package/shared/pdfjs-assets.ts +1 -3
  25. package/shared/rich-content.ts +35 -0
  26. package/shared/signature.ts +15 -0
  27. package/src/admin/address-auto-reply.tsx +49 -0
  28. package/src/admin/blocked-senders.tsx +86 -66
  29. package/src/admin/forward-destinations.tsx +140 -0
  30. package/src/admin/mail-archive.tsx +134 -0
  31. package/src/admin/team-signature.tsx +90 -0
  32. package/src/client.tsx +130 -16
  33. package/src/mail/attachment-preview-dialog.tsx +13 -5
  34. package/src/mail/auto-reply-banner.tsx +61 -0
  35. package/src/mail/blocked-senders.tsx +124 -91
  36. package/src/mail/compose-window-chrome.tsx +20 -8
  37. package/src/mail/compose-window.tsx +387 -365
  38. package/src/mail/composer-asset-bookmarks.ts +47 -12
  39. package/src/mail/composer-attachment-list.tsx +42 -17
  40. package/src/mail/composer-editor-document.ts +54 -10
  41. package/src/mail/composer-editor.tsx +44 -44
  42. package/src/mail/composer-link-text.ts +42 -0
  43. package/src/mail/composer-recipient-fields.tsx +25 -16
  44. package/src/mail/composer-recipients.ts +62 -16
  45. package/src/mail/composer-session.ts +107 -23
  46. package/src/mail/composer-toolbar.tsx +15 -1
  47. package/src/mail/composer-upload-client.ts +29 -1
  48. package/src/mail/composer-upload-progress.ts +2 -2
  49. package/src/mail/conversation-actions-model.ts +56 -0
  50. package/src/mail/conversation-list.tsx +263 -128
  51. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  52. package/src/mail/conversation-message.tsx +257 -102
  53. package/src/mail/conversation-order.ts +12 -0
  54. package/src/mail/conversation-reply.tsx +313 -189
  55. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  56. package/src/mail/conversation-view.tsx +320 -85
  57. package/src/mail/delivery-indicator.tsx +33 -12
  58. package/src/mail/draft-attachments.ts +194 -0
  59. package/src/mail/email-html-body.tsx +97 -53
  60. package/src/mail/folder-cleanup-bar.tsx +193 -0
  61. package/src/mail/folder-glyph.tsx +5 -0
  62. package/src/mail/folder-manager.tsx +71 -38
  63. package/src/mail/mail-app-bar.tsx +15 -3
  64. package/src/mail/mail-dock.tsx +19 -3
  65. package/src/mail/mail-focus.ts +48 -0
  66. package/src/mail/mail-folders.ts +14 -2
  67. package/src/mail/mail-layout.css +20 -0
  68. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  69. package/src/mail/mail-nav-rail.tsx +7 -4
  70. package/src/mail/mail-nav.tsx +66 -46
  71. package/src/mail/mail-prefetch.ts +30 -9
  72. package/src/mail/mail-primitives.tsx +6 -4
  73. package/src/mail/mail-queries.ts +122 -20
  74. package/src/mail/mail-query-cache.ts +1085 -173
  75. package/src/mail/mail-search-params.ts +35 -0
  76. package/src/mail/mail-shell.tsx +32 -9
  77. package/src/mail/mailbox-ai-settings.tsx +56 -42
  78. package/src/mail/mailbox-realtime.tsx +4 -12
  79. package/src/mail/mailbox-rules.tsx +898 -0
  80. package/src/mail/message-actions.tsx +38 -26
  81. package/src/mail/message-attachments.tsx +20 -12
  82. package/src/mail/message-body.ts +53 -0
  83. package/src/mail/message-format.ts +8 -2
  84. package/src/mail/message-header.tsx +3 -1
  85. package/src/mail/message-translation.tsx +34 -67
  86. package/src/mail/original-message-sheet.tsx +63 -50
  87. package/src/mail/original-message.ts +6 -6
  88. package/src/mail/pane-splitter.tsx +3 -3
  89. package/src/mail/pdf-preview.tsx +70 -62
  90. package/src/mail/plain-message-text.tsx +28 -0
  91. package/src/mail/print-message.ts +31 -36
  92. package/src/mail/reader-pane.tsx +134 -102
  93. package/src/mail/recipient-combobox.tsx +52 -29
  94. package/src/mail/recipient-field-row.tsx +3 -0
  95. package/src/mail/rich-content.ts +128 -0
  96. package/src/mail/sanitize-email-html.ts +57 -33
  97. package/src/mail/sender-actions.tsx +49 -39
  98. package/src/mail/sender-authentication.tsx +1 -1
  99. package/src/mail/sender-dialogs.tsx +67 -43
  100. package/src/mail/sender-security.tsx +9 -10
  101. package/src/mail/signature.ts +43 -0
  102. package/src/mail/translation-html.ts +3 -3
  103. package/src/mail/types.ts +12 -0
  104. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  105. package/src/mail/use-composer-core.ts +286 -0
  106. package/src/mail/use-composer-navigation.ts +120 -0
  107. package/src/mail/use-composer-submission.ts +154 -19
  108. package/src/mail/use-conversation-actions.ts +292 -0
  109. package/src/mail/use-conversation-position.ts +51 -0
  110. package/src/mail/use-conversation-selection.ts +192 -89
  111. package/src/mail/use-draft-autosave.ts +394 -0
  112. package/src/mail/use-drafts.ts +194 -0
  113. package/src/mail/use-mail-controller.ts +754 -213
  114. package/src/mail/use-mail-data.ts +210 -100
  115. package/src/mail/use-mail-safety.ts +19 -38
  116. package/src/mail/use-mail-send.ts +18 -6
  117. package/src/mail/use-pdf-translation.ts +1 -1
  118. package/src/mail/use-reply-cc.ts +61 -0
  119. package/src/mail/use-visible-message-read.ts +128 -64
  120. package/src/pwa/push-key.ts +18 -0
  121. package/src/pwa/push-subscription.ts +88 -26
  122. package/src/settings/auto-reply-editor.tsx +454 -0
  123. package/src/settings/auto-reply-page.tsx +59 -0
  124. package/src/settings/mail-apps-page.tsx +52 -43
  125. package/src/settings/notifications-page.tsx +82 -67
  126. package/src/settings/rich-content-editor.tsx +182 -0
  127. package/src/settings/settings-queries.ts +57 -0
  128. package/src/settings/signature-editor.tsx +142 -0
  129. package/src/settings/signature-page.tsx +70 -0
  130. package/worker/admin/blocked-sender-routes.ts +10 -16
  131. package/worker/backups/eml.ts +185 -0
  132. package/worker/backups/file-parts.ts +140 -0
  133. package/worker/backups/mail-backup.ts +644 -0
  134. package/worker/backups/settings-backup.ts +866 -0
  135. package/worker/backups/stream-eml.ts +73 -0
  136. package/worker/db/schema.ts +98 -2
  137. package/worker/jmap/attachment-blobs.ts +113 -0
  138. package/worker/jmap/blobs.ts +162 -0
  139. package/worker/jmap/draft-content.ts +42 -0
  140. package/worker/jmap/drafts.ts +70 -0
  141. package/worker/jmap/email-body.ts +152 -0
  142. package/worker/jmap/email-methods.ts +1223 -0
  143. package/worker/jmap/eventsource.ts +9 -8
  144. package/worker/jmap/import-methods.ts +205 -0
  145. package/worker/jmap/mailbox-methods.ts +187 -0
  146. package/worker/jmap/method-core.ts +379 -0
  147. package/worker/jmap/methods.ts +108 -1815
  148. package/worker/jmap/push-subscription-methods.ts +373 -0
  149. package/worker/jmap/push-types.ts +46 -2
  150. package/worker/jmap/push.ts +24 -31
  151. package/worker/jmap/routes.ts +144 -153
  152. package/worker/jmap/submission-methods.ts +395 -0
  153. package/worker/mail/access.ts +35 -12
  154. package/worker/mail/ai-classification.ts +2 -2
  155. package/worker/mail/archive-object.ts +96 -0
  156. package/worker/mail/archive-routes.ts +35 -0
  157. package/worker/mail/archive.ts +682 -0
  158. package/worker/mail/auth-headers.ts +48 -40
  159. package/worker/mail/auto-reply-routes.ts +255 -0
  160. package/worker/mail/auto-reply.ts +243 -0
  161. package/worker/mail/bimi.ts +53 -36
  162. package/worker/mail/bootstrap.ts +11 -3
  163. package/worker/mail/capabilities.ts +69 -0
  164. package/worker/mail/classification-signals.ts +1 -1
  165. package/worker/mail/confusables-data.ts +9 -0
  166. package/worker/mail/conversation-cursor.ts +6 -15
  167. package/worker/mail/delivery-events.ts +9 -7
  168. package/worker/mail/delivery-facts.ts +1 -1
  169. package/worker/mail/demo-routes.ts +3 -3
  170. package/worker/mail/doh.ts +3 -3
  171. package/worker/mail/download-links.ts +153 -0
  172. package/worker/mail/downloads.ts +2 -6
  173. package/worker/mail/draft-routes.ts +473 -0
  174. package/worker/mail/draft-sender.ts +54 -0
  175. package/worker/mail/edge-cache.ts +41 -55
  176. package/worker/mail/email-routing.ts +123 -0
  177. package/worker/mail/forward-destinations.ts +114 -0
  178. package/worker/mail/forward-downloads.ts +115 -0
  179. package/worker/mail/forward-html.ts +85 -0
  180. package/worker/mail/header-metadata.ts +2 -5
  181. package/worker/mail/impersonation.ts +102 -101
  182. package/worker/mail/import-routes.ts +29 -82
  183. package/worker/mail/import.ts +130 -0
  184. package/worker/mail/inbound-delivery.ts +6 -5
  185. package/worker/mail/inbound.ts +58 -28
  186. package/worker/mail/ip-intel.ts +8 -17
  187. package/worker/mail/isolate-cache.ts +1 -1
  188. package/worker/mail/mailbox-deletion.ts +33 -12
  189. package/worker/mail/mailbox-directory.ts +39 -65
  190. package/worker/mail/mailing-list.ts +29 -58
  191. package/worker/mail/message-security.ts +3 -3
  192. package/worker/mail/message-view.ts +12 -10
  193. package/worker/mail/office-conversion.ts +3 -5
  194. package/worker/mail/office-preview-container.ts +3 -8
  195. package/worker/mail/outbound-content.ts +139 -65
  196. package/worker/mail/outbound-delivery.ts +20 -17
  197. package/worker/mail/outbound-service.ts +34 -9
  198. package/worker/mail/outbound.ts +146 -75
  199. package/worker/mail/outgoing-context.ts +60 -30
  200. package/worker/mail/participants.ts +10 -15
  201. package/worker/mail/plain-body.ts +39 -0
  202. package/worker/mail/push-endpoint.ts +17 -0
  203. package/worker/mail/push-notifications.ts +87 -43
  204. package/worker/mail/quote-parser.ts +107 -25
  205. package/worker/mail/r2-presigned-urls.ts +7 -0
  206. package/worker/mail/receive.ts +146 -39
  207. package/worker/mail/recipients.ts +1 -1
  208. package/worker/mail/remote-proxy.ts +3 -3
  209. package/worker/mail/repeat.ts +1 -1
  210. package/worker/mail/reply-plan.ts +124 -26
  211. package/worker/mail/rfc.ts +15 -7
  212. package/worker/mail/rich-content.ts +207 -0
  213. package/worker/mail/routes.ts +696 -304
  214. package/worker/mail/routing.ts +274 -0
  215. package/worker/mail/rules.ts +230 -0
  216. package/worker/mail/safety-routes.ts +88 -80
  217. package/worker/mail/schemas.ts +222 -31
  218. package/worker/mail/search.ts +25 -2
  219. package/worker/mail/security-settings.ts +4 -10
  220. package/worker/mail/send-message.ts +238 -0
  221. package/worker/mail/sender-intel.ts +12 -20
  222. package/worker/mail/signature-routes.ts +201 -0
  223. package/worker/mail/signatures.ts +195 -0
  224. package/worker/mail/spamhaus.ts +28 -16
  225. package/worker/mail/storage-keys.ts +35 -0
  226. package/worker/mail/unsubscribe.ts +19 -41
  227. package/worker/mail/uploads.ts +193 -80
  228. package/worker/mail/webhook-source.ts +3 -2
  229. package/worker/mail/workspace-safety.ts +194 -60
  230. package/worker/mailbox/demo.ts +13 -15
  231. package/worker/mailbox/email-index.ts +92 -13
  232. package/worker/mailbox/folder-model.ts +0 -20
  233. package/worker/mailbox/import-placement.ts +21 -36
  234. package/worker/mailbox/inbound-decision.ts +114 -0
  235. package/worker/mailbox/inbox-counts.ts +45 -25
  236. package/worker/mailbox/index.ts +843 -2888
  237. package/worker/mailbox/jmap-change-log.ts +195 -0
  238. package/worker/mailbox/jmap-email-rows.ts +186 -0
  239. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  240. package/worker/mailbox/jmap-placement.ts +139 -0
  241. package/worker/mailbox/jmap-query-filter.ts +231 -0
  242. package/worker/mailbox/jmap-store.ts +167 -299
  243. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  244. package/worker/mailbox/mailbox-backup.ts +538 -0
  245. package/worker/mailbox/mailbox-drafts.ts +417 -0
  246. package/worker/mailbox/mailbox-folders.ts +242 -0
  247. package/worker/mailbox/mailbox-import.ts +450 -0
  248. package/worker/mailbox/mailbox-inbound.ts +934 -0
  249. package/worker/mailbox/mailbox-jmap.ts +294 -0
  250. package/worker/mailbox/mailbox-outbound.ts +413 -0
  251. package/worker/mailbox/mailbox-rules.ts +336 -0
  252. package/worker/mailbox/mailbox-senders.ts +294 -0
  253. package/worker/mailbox/mailbox-storage.ts +438 -0
  254. package/worker/mailbox/mailbox-views.ts +891 -0
  255. package/worker/mailbox/model.ts +1 -0
  256. package/worker/mailbox/office-preview-jobs.ts +59 -47
  257. package/worker/mailbox/placement.ts +933 -0
  258. package/worker/mailbox/restore-thread.ts +52 -0
  259. package/worker/mailbox/retention.ts +36 -0
  260. package/worker/mailbox/schema.ts +211 -1
  261. package/worker/mailbox/senders.ts +216 -178
  262. package/worker/mailbox/spam-undo-filing.ts +138 -0
  263. package/worker/mailbox/spam-undo.ts +240 -0
  264. package/worker/mailbox/support.ts +416 -0
  265. package/worker/mcp/mail-action-tools.ts +156 -0
  266. package/worker/mcp/mail-compose-tools.ts +8 -2
  267. package/worker/mcp/mail-safety-tools.ts +4 -4
  268. package/worker/module.ts +23 -2
  269. package/src/mail/use-compose-submission.ts +0 -208
  270. package/src/mail/use-reply-submission.ts +0 -114
  271. package/worker/mail/capped-body.ts +0 -36
@@ -1,9 +1,5 @@
1
- import {
2
- configuredMailDomains,
3
- createDb,
4
- mailboxes,
5
- users,
6
- } from "@open-workspace/core/module";
1
+ import { configuredMailDomains, createDb } from "@open-workspace/core/module";
2
+ import { mailboxes, users } from "@open-workspace/core/schema";
7
3
  import { inArray, isNotNull } from "drizzle-orm";
8
4
 
9
5
  import { protectedNames } from "./impersonation";
@@ -13,13 +9,11 @@ import { DQS_KEY_PATTERN } from "./spamhaus";
13
9
  /** Workspace-wide inputs for sender checks, read from D1 once per request or delivery. */
14
10
  export type WorkspaceIdentity = {
15
11
  domains: string[];
16
- /** Normalized internal person name → display form. */
12
+ /** Internal person names by confusable skeleton → display form. */
17
13
  names: Map<string, string>;
18
14
  };
19
15
 
20
- export async function workspaceIdentity(
21
- binding: D1Database
22
- ): Promise<WorkspaceIdentity> {
16
+ export async function workspaceIdentity(binding: D1Database) {
23
17
  const db = createDb(binding);
24
18
 
25
19
  const [userRows, mailboxRows] = await db.batch([
@@ -0,0 +1,238 @@
1
+ /**
2
+ * Sending what a person wrote in the app (or an API client): a new
3
+ * message, a reply or a forward, each with its signature, its thread, the
4
+ * address it comes from, and the draft it was written in discarded once
5
+ * sent. The routes, MCP (through them) and JMAP all send this way.
6
+ */
7
+ import { createId } from "@open-workspace/core/module";
8
+ import type { z } from "zod";
9
+
10
+ import { mailboxStub } from "../mailbox";
11
+ import type { Email } from "../mailbox/schema";
12
+ import { submitOutgoing } from "./outbound-service";
13
+ import { shouldDetachOutboundReply } from "./outbound-threading";
14
+ import {
15
+ OutgoingContextError,
16
+ resolveForwardContext,
17
+ resolveReplyContext,
18
+ replySourceContext,
19
+ } from "./outgoing-context";
20
+ import { canReplyFrom } from "./reply-plan";
21
+ import type { composeSchema, forwardSchema, replySchema } from "./schemas";
22
+ import { withSignature } from "./signatures";
23
+
24
+ type Body<S extends z.ZodType> = z.output<S>;
25
+
26
+ export type SendRequest =
27
+ | {
28
+ kind: "new";
29
+ message: Body<typeof composeSchema>;
30
+ /**
31
+ * The message it answers when the caller found it (a JMAP draft names
32
+ * it by Message-ID); otherwise the one its saved draft names.
33
+ */
34
+ answers?: Email | null;
35
+ }
36
+ | {
37
+ kind: "reply";
38
+ sourceEmailId: string;
39
+ message: Body<typeof replySchema>;
40
+ }
41
+ | {
42
+ kind: "forward";
43
+ sourceEmailId: string;
44
+ message: Body<typeof forwardSchema>;
45
+ };
46
+
47
+ /** The address sent from, as `accessibleMailbox` gives it. */
48
+ type SendingMailbox = {
49
+ id: string;
50
+ address: string;
51
+ displayName: string;
52
+ ownerUserId: string | null;
53
+ };
54
+
55
+ /**
56
+ * Sends `request` from `mailbox` as `sender`, once per request id. Whether
57
+ * a reply left its conversation (sent to people outside it) comes back as
58
+ * `detached`. Throws the outgoing errors the routes map to answers.
59
+ */
60
+ export async function sendMessage(input: {
61
+ env: Env;
62
+ requestUrl: string;
63
+ sender: { id: string; name: string };
64
+ keepDraft?: boolean;
65
+ mailbox: SendingMailbox;
66
+ request: SendRequest;
67
+ }) {
68
+ const { env, mailbox, request, sender } = input;
69
+
70
+ const { draftId, draftVersion } = request.message;
71
+
72
+ if ((draftId === undefined) !== (draftVersion === undefined)) {
73
+ throw new OutgoingContextError(
74
+ 400,
75
+ "BAD_REQUEST",
76
+ "Supply both draftId and draftVersion when sending a draft"
77
+ );
78
+ }
79
+
80
+ const common = {
81
+ env,
82
+ requestUrl: input.requestUrl,
83
+ draft:
84
+ draftId && draftVersion
85
+ ? { id: draftId, version: draftVersion, keep: input.keepDraft }
86
+ : undefined,
87
+ };
88
+
89
+ let sent: Awaited<ReturnType<typeof submitOutgoing>>;
90
+ let detached = false;
91
+
92
+ switch (request.kind) {
93
+ case "new": {
94
+ const message = await withSignature({
95
+ env,
96
+ sender,
97
+ mailbox,
98
+ kind: "new",
99
+ message: request.message,
100
+ });
101
+
102
+ // A reply begun in a mail app (and finished here, or sent from it):
103
+ // it names the message it answers, and it threads as replies do.
104
+ const source =
105
+ request.answers === undefined
106
+ ? await draftAnswers(env, mailbox.id, sender.id, draftId)
107
+ : request.answers;
108
+
109
+ const reply = source
110
+ ? await replySourceContext(env.DB, mailbox.id, mailbox.address, source)
111
+ : null;
112
+
113
+ detached = reply
114
+ ? shouldDetachOutboundReply({
115
+ ...reply,
116
+ to: message.to,
117
+ cc: message.cc,
118
+ })
119
+ : false;
120
+ sent = await submitOutgoing({
121
+ ...common,
122
+ compose: { ...message, userId: sender.id },
123
+ conversationId:
124
+ source && !detached ? source.conversationId : createId("conv"),
125
+ related: source,
126
+ forwarded: null,
127
+ includeRelatedContext: false,
128
+ fromAddress: reply?.from?.address ?? mailbox.address,
129
+ fromName: reply?.from?.displayName ?? mailbox.displayName,
130
+ });
131
+ break;
132
+ }
133
+
134
+ case "reply": {
135
+ const reply = await withSignature({
136
+ env,
137
+ sender,
138
+ mailbox,
139
+ kind: "reply",
140
+ message: request.message,
141
+ });
142
+
143
+ const context = await resolveReplyContext({
144
+ env,
145
+ mailboxId: mailbox.id,
146
+ ownAddress: mailbox.address,
147
+ sourceEmailId: request.sourceEmailId,
148
+ mode: reply.mode,
149
+ cc: reply.cc,
150
+ bcc: reply.bcc,
151
+ });
152
+
153
+ detached = context.detached;
154
+ sent = await submitOutgoing({
155
+ ...common,
156
+ compose: {
157
+ requestId: reply.requestId,
158
+ draftId: reply.draftId,
159
+ draftVersion: reply.draftVersion,
160
+ mailboxId: reply.mailboxId,
161
+ userId: sender.id,
162
+ ...context.recipients,
163
+ subject: context.subject,
164
+ bodyText: reply.bodyText,
165
+ bodyHtml: reply.bodyHtml,
166
+ attachments: reply.attachments,
167
+ inlineImages: reply.inlineImages,
168
+ },
169
+ conversationId: detached
170
+ ? createId("conv")
171
+ : context.source.conversationId,
172
+ related: context.source,
173
+ forwarded: null,
174
+ includeRelatedContext: context.includeRelatedContext,
175
+ // Mail that came through an alias is answered from that alias.
176
+ fromAddress: context.from?.address ?? mailbox.address,
177
+ fromName: context.from?.displayName ?? mailbox.displayName,
178
+ });
179
+ break;
180
+ }
181
+
182
+ case "forward": {
183
+ const message = await withSignature({
184
+ env,
185
+ sender,
186
+ mailbox,
187
+ kind: "reply",
188
+ message: request.message,
189
+ });
190
+
191
+ const context = await resolveForwardContext({
192
+ env,
193
+ mailboxId: mailbox.id,
194
+ sourceEmailId: request.sourceEmailId,
195
+ });
196
+
197
+ sent = await submitOutgoing({
198
+ ...common,
199
+ compose: {
200
+ ...message,
201
+ userId: sender.id,
202
+ subject: context.subject,
203
+ },
204
+ conversationId: createId("conv"),
205
+ related: null,
206
+ forwarded: context.source,
207
+ includeRelatedContext: false,
208
+ fromAddress: mailbox.address,
209
+ fromName: mailbox.displayName,
210
+ });
211
+ break;
212
+ }
213
+
214
+ default: {
215
+ const unexpected: never = request;
216
+ throw new Error(`Unknown message kind ${JSON.stringify(unexpected)}`);
217
+ }
218
+ }
219
+
220
+ return { ...sent, detached };
221
+ }
222
+
223
+ /** The message a new message's draft answers, if it names one that can be answered. */
224
+ async function draftAnswers(
225
+ env: Env,
226
+ mailboxId: string,
227
+ userId: string,
228
+ draftId: string | undefined
229
+ ) {
230
+ if (!draftId) return null;
231
+ const stub = mailboxStub(env, mailboxId);
232
+ const draft = await stub.getDraft(userId, draftId);
233
+
234
+ if (draft?.kind !== "compose" || !draft.sourceEmailId) return null;
235
+ const source = await stub.getEmail(draft.sourceEmailId);
236
+
237
+ return source && canReplyFrom(source) ? source : null;
238
+ }
@@ -96,17 +96,11 @@ const memory = new Map<string, { intel: IpIntel; expiresAt: number }>();
96
96
  * Isolate memory first, then the colo-local Cache API under a synthetic URL.
97
97
  * Both are best effort: a failing cache never fails ingestion.
98
98
  */
99
- export function defaultIntelCache(): IntelCache {
99
+ export function defaultIntelCache() {
100
100
  const request = (ip: string) =>
101
101
  new Request(`${CACHE_ORIGIN}/ip/v1/${encodeURIComponent(ip)}`);
102
102
 
103
- const open = async () => {
104
- try {
105
- return await caches.open("openworkspace:sender-intel");
106
- } catch {
107
- return null;
108
- }
109
- };
103
+ const open = () => caches.open("openworkspace:sender-intel");
110
104
 
111
105
  return {
112
106
  async get(ip) {
@@ -115,7 +109,7 @@ export function defaultIntelCache(): IntelCache {
115
109
  if (hit && hit.expiresAt > Date.now()) return hit.intel;
116
110
 
117
111
  try {
118
- const response = await (await open())?.match(request(ip));
112
+ const response = await (await open()).match(request(ip));
119
113
 
120
114
  if (!response) return null;
121
115
  const cached = IpIntelSchema.safeParse(await response.json());
@@ -137,7 +131,7 @@ export function defaultIntelCache(): IntelCache {
137
131
  try {
138
132
  await (
139
133
  await open()
140
- )?.put(
134
+ ).put(
141
135
  request(ip),
142
136
  Response.json(intel, {
143
137
  headers: { "cache-control": `max-age=${ttlSeconds}` },
@@ -147,10 +141,10 @@ export function defaultIntelCache(): IntelCache {
147
141
  // Best effort only.
148
142
  }
149
143
  },
150
- };
144
+ } satisfies IntelCache;
151
145
  }
152
146
 
153
- function skippedIpIntel(status: LookupStatus): IpIntel {
147
+ function skippedIpIntel(status: LookupStatus) {
154
148
  return {
155
149
  ptr: { status, names: [], confirmed: null, fcrdns: null, generic: null },
156
150
  network: {
@@ -161,7 +155,7 @@ function skippedIpIntel(status: LookupStatus): IpIntel {
161
155
  country: null,
162
156
  registry: null,
163
157
  },
164
- };
158
+ } satisfies IpIntel;
165
159
  }
166
160
 
167
161
  /** Resolves to `fallback` once the deadline passes, even if the work ignores the abort signal. */
@@ -169,8 +163,8 @@ function withDeadline<T>(
169
163
  work: Promise<T>,
170
164
  signal: AbortSignal,
171
165
  fallback: () => T
172
- ): Promise<T> {
173
- return new Promise((resolve) => {
166
+ ) {
167
+ return new Promise<T>((resolve) => {
174
168
  const onAbort = () => resolve(fallback());
175
169
 
176
170
  if (signal.aborted) {
@@ -216,7 +210,7 @@ export async function collectSenderIntel(input: {
216
210
  cache?: IntelCache;
217
211
  budgetMs?: number;
218
212
  now?: number;
219
- }): Promise<SenderIntel> {
213
+ }) {
220
214
  const now = input.now ?? Date.now();
221
215
  const signal = AbortSignal.timeout(input.budgetMs ?? SENDER_INTEL_BUDGET_MS);
222
216
 
@@ -315,7 +309,7 @@ export async function collectSenderIntel(input: {
315
309
  heloMatchesPtr: heloMatchesPtr(auth?.helo ?? null, ipIntel.ptr),
316
310
  spamhaus,
317
311
  bimi,
318
- };
312
+ } satisfies SenderIntel;
319
313
  }
320
314
 
321
315
  /** Lazy fills skip persisting a result where every attempted lookup failed. */
@@ -335,9 +329,7 @@ export function senderIntelWorthStoring(intel: SenderIntel) {
335
329
  }
336
330
 
337
331
  /** A message's stored sender intelligence, or null when absent or of another version. */
338
- export function storedSenderIntel(
339
- value: SenderIntel | null | undefined
340
- ): SenderIntel | null {
332
+ export function storedSenderIntel(value: SenderIntel | null | undefined) {
341
333
  const parsed = SenderIntelSchema.safeParse(value);
342
334
 
343
335
  return parsed.success ? parsed.data : null;
@@ -0,0 +1,201 @@
1
+ import {
2
+ apiError,
3
+ can,
4
+ createDb,
5
+ oauthScope,
6
+ requirePermission,
7
+ zValidator,
8
+ } from "@open-workspace/core/module";
9
+ import type { AppEnv } from "@open-workspace/core/module";
10
+ import { mailboxes } from "@open-workspace/core/schema";
11
+ import { and, eq, isNull } from "drizzle-orm";
12
+ import { Hono } from "hono";
13
+ import type { Context } from "hono";
14
+ import type { z } from "zod";
15
+
16
+ import { MAIL_ORGANIZE_SCOPE, MAIL_READ_SCOPE } from "../../shared/permissions";
17
+ import { signatures } from "../db/schema";
18
+ import { accessibleMailbox } from "./access";
19
+ import {
20
+ deleteRichImages,
21
+ isEmptyRichContent,
22
+ storeRichImages,
23
+ } from "./rich-content";
24
+ import { signatureSchema } from "./schemas";
25
+ import {
26
+ loadSignature,
27
+ ownerColumn,
28
+ ownerId,
29
+ signatureImagePrefix,
30
+ } from "./signatures";
31
+ import type { Signature, SignatureOwner } from "./signatures";
32
+ import { UploadValidationError } from "./uploads";
33
+
34
+ function signatureView(owner: SignatureOwner, signature: Signature | null) {
35
+ return {
36
+ ok: true as const,
37
+ signature: signature && {
38
+ ownerId: ownerId(owner),
39
+ html: signature.html,
40
+ images: signature.images,
41
+ useOnNew: signature.useOnNew,
42
+ useOnReply: signature.useOnReply,
43
+ },
44
+ };
45
+ }
46
+
47
+ /**
48
+ * Saves the HTML as given (the editor's own output; recipients sanitize mail
49
+ * on display), with its images stored under the owner's signature prefix
50
+ * (rich-content.ts). Images no longer in the signature are deleted.
51
+ */
52
+ async function saveSignature(
53
+ c: Context<AppEnv>,
54
+ owner: SignatureOwner,
55
+ input: z.infer<typeof signatureSchema>
56
+ ) {
57
+ const prefix = signatureImagePrefix(ownerId(owner));
58
+ const db = createDb(c.env.DB);
59
+
60
+ if (isEmptyRichContent(input)) {
61
+ await db.delete(signatures).where(ownerColumn(owner));
62
+ await deleteRichImages(c.env.MAIL_STORAGE, prefix);
63
+
64
+ return null;
65
+ }
66
+
67
+ const images = await storeRichImages({
68
+ env: c.env,
69
+ userId: c.get("user").id,
70
+ prefix,
71
+ previous: (await loadSignature(c.env, owner))?.images ?? [],
72
+ content: input,
73
+ });
74
+
75
+ const signature = {
76
+ html: input.html,
77
+ text: input.text,
78
+ images,
79
+ useOnNew: input.useOnNew,
80
+ useOnReply: input.useOnReply,
81
+ };
82
+
83
+ const values = { ...signature, updatedAt: new Date() };
84
+
85
+ await db
86
+ .insert(signatures)
87
+ .values({ ...owner, ...values })
88
+ .onConflictDoUpdate({
89
+ target: "userId" in owner ? signatures.userId : signatures.mailboxId,
90
+ set: values,
91
+ });
92
+
93
+ await deleteRichImages(
94
+ c.env.MAIL_STORAGE,
95
+ prefix,
96
+ new Set(images.map((image) => image.contentId))
97
+ );
98
+
99
+ return signature;
100
+ }
101
+
102
+ async function saveResponse(
103
+ c: Context<AppEnv>,
104
+ owner: SignatureOwner,
105
+ input: z.infer<typeof signatureSchema>
106
+ ) {
107
+ try {
108
+ return c.json(signatureView(owner, await saveSignature(c, owner, input)));
109
+ } catch (error) {
110
+ if (error instanceof UploadValidationError) {
111
+ return apiError(c, 400, "BAD_REQUEST", error.message);
112
+ }
113
+
114
+ throw error;
115
+ }
116
+ }
117
+
118
+ async function isTeamAddress(env: Env, mailboxId: string) {
119
+ const [row] = await createDb(env.DB)
120
+ .select({ id: mailboxes.id })
121
+ .from(mailboxes)
122
+ .where(and(eq(mailboxes.id, mailboxId), isNull(mailboxes.ownerUserId)))
123
+ .limit(1);
124
+
125
+ return Boolean(row);
126
+ }
127
+
128
+ /**
129
+ * The signed-in person's own signature, and team addresses' signatures for
130
+ * people who manage teams (Administration → Teams). Mounted under /mail.
131
+ */
132
+ export const signatureRoutes = new Hono<AppEnv>()
133
+ .get("/signature", oauthScope(MAIL_READ_SCOPE), async (c) => {
134
+ const owner = { userId: c.get("user").id };
135
+
136
+ return c.json(signatureView(owner, await loadSignature(c.env, owner)));
137
+ })
138
+ .put(
139
+ "/signature",
140
+ oauthScope(MAIL_ORGANIZE_SCOPE),
141
+ zValidator("json", signatureSchema),
142
+ (c) => saveResponse(c, { userId: c.get("user").id }, c.req.valid("json"))
143
+ )
144
+ .get(
145
+ "/team-signatures/:mailboxId",
146
+ requirePermission("manage_teams"),
147
+ async (c) => {
148
+ const owner = { mailboxId: c.req.param("mailboxId") };
149
+
150
+ if (!(await isTeamAddress(c.env, owner.mailboxId))) {
151
+ return apiError(c, 404, "NOT_FOUND", "Team address not found");
152
+ }
153
+
154
+ return c.json(signatureView(owner, await loadSignature(c.env, owner)));
155
+ }
156
+ )
157
+ .put(
158
+ "/team-signatures/:mailboxId",
159
+ requirePermission("manage_teams"),
160
+ zValidator("json", signatureSchema),
161
+ async (c) => {
162
+ const owner = { mailboxId: c.req.param("mailboxId") };
163
+
164
+ if (!(await isTeamAddress(c.env, owner.mailboxId))) {
165
+ return apiError(c, 404, "NOT_FOUND", "Team address not found");
166
+ }
167
+
168
+ return saveResponse(c, owner, c.req.valid("json"));
169
+ }
170
+ )
171
+ .get(
172
+ "/signature-images/:ownerId/:contentId",
173
+ oauthScope(MAIL_READ_SCOPE),
174
+ async (c) => {
175
+ const { ownerId: owner, contentId } = c.req.param();
176
+
177
+ // The person's own, a mailbox they can read (a team's), or any team
178
+ // address's for people who edit them.
179
+ const allowed =
180
+ owner === c.get("user").id ||
181
+ Boolean(await accessibleMailbox(c, owner, "read")) ||
182
+ (can(c, "manage_teams") && (await isTeamAddress(c.env, owner)));
183
+
184
+ const object = allowed
185
+ ? await c.env.MAIL_STORAGE.get(
186
+ `${signatureImagePrefix(owner)}${contentId}`
187
+ )
188
+ : null;
189
+
190
+ if (!object) return apiError(c, 404, "NOT_FOUND", "Image not found");
191
+
192
+ return new Response(object.body, {
193
+ headers: {
194
+ "content-type":
195
+ object.httpMetadata?.contentType ?? "application/octet-stream",
196
+ "cache-control": "private, max-age=300",
197
+ "x-content-type-options": "nosniff",
198
+ },
199
+ });
200
+ }
201
+ );