@open-workspace/email 0.3.0 → 0.4.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 (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
package/shared/mail.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  export {
2
2
  isValidExternalEmailAddress,
3
3
  normalizeExternalEmailAddress,
4
- } from "@open-workspace/core/shared/email-address.ts";
4
+ } from "@open-workspace/core/shared";
5
5
 
6
6
  export const mailboxStates = ["active", "archive", "spam", "trash"] as const;
7
+
7
8
  export type MailboxState = (typeof mailboxStates)[number];
8
9
 
9
10
  export const transportStates = [
@@ -12,6 +13,7 @@ export const transportStates = [
12
13
  "submitted",
13
14
  "failed",
14
15
  ] as const;
16
+
15
17
  export type TransportState = (typeof transportStates)[number];
16
18
 
17
19
  export const replyActionModes = [
@@ -20,6 +22,7 @@ export const replyActionModes = [
20
22
  "continue",
21
23
  "reply_list",
22
24
  ] as const;
25
+
23
26
  export type ReplyActionMode = (typeof replyActionModes)[number];
24
27
 
25
28
  export type ReplyAction = {
@@ -44,6 +47,7 @@ export const deliveryStatuses = [
44
47
  "rejected",
45
48
  "complained",
46
49
  ] as const;
50
+
47
51
  export type DeliveryStatusName = (typeof deliveryStatuses)[number];
48
52
 
49
53
  export type RecipientDeliveryStatus = {
@@ -55,8 +59,37 @@ export type RecipientDeliveryStatus = {
55
59
  detail: string | null;
56
60
  };
57
61
 
62
+ /** Conversations in the first page of a folder's list (and each next one). */
63
+ export const CONVERSATION_PAGE_SIZE = 25;
64
+
65
+ /**
66
+ * The realtime socket's only server message: `update:<version>`, sent when
67
+ * the socket opens and after every change, where `<version>` is the
68
+ * mailbox's change counter. Mail API reads return the counter they reflect,
69
+ * so a client refetches only data older than the announced version.
70
+ * `update:<version>:<bookmark>` also names the D1 bookmark after the
71
+ * mailbox's latest counts write (see `mailbox_counts`): a client that reads
72
+ * counts with it gets them at least as new as the announced version, even
73
+ * from a D1 replica.
74
+ */
58
75
  export const MAILBOX_REALTIME_UPDATE = "update" as const;
59
76
 
77
+ export function mailboxRealtimeUpdate(
78
+ version: number,
79
+ bookmark: string | null
80
+ ) {
81
+ return `${MAILBOX_REALTIME_UPDATE}:${version}${bookmark ? `:${bookmark}` : ""}`;
82
+ }
83
+
84
+ /** The version (and bookmark) a realtime message announces, or null for anything else. */
85
+ export function parseMailboxRealtimeUpdate(message: string) {
86
+ const match = /^update:(\d+)(?::([\w.:-]{1,256}))?$/u.exec(message);
87
+
88
+ return match
89
+ ? { version: Number(match[1]), bookmark: match[2] ?? null }
90
+ : null;
91
+ }
92
+
60
93
  export type MailboxRealtimeClientMessage = "visible" | "hidden";
61
94
 
62
95
  type MailboxPushJobBase = {
@@ -69,16 +102,22 @@ type MailboxPushJobBase = {
69
102
  };
70
103
 
71
104
  export type MailboxPushJob =
72
- | (MailboxPushJobBase & (
73
- | { type: "dispatch" }
74
- | {
75
- type: "deliver";
76
- targetSubscriptionId: string;
77
- mailboxDisplayName: string;
78
- }
79
- ))
105
+ | (MailboxPushJobBase &
106
+ (
107
+ | { type: "dispatch" }
108
+ | {
109
+ type: "deliver";
110
+ targetSubscriptionId: string;
111
+ mailboxDisplayName: string;
112
+ }
113
+ ))
80
114
  /** The mailbox's JMAP state moved; tell JMAP push subscribers. */
81
- | { type: "jmap-state"; mailboxId: string; state: string; occurredAt: number };
115
+ | {
116
+ type: "jmap-state";
117
+ mailboxId: string;
118
+ state: string;
119
+ occurredAt: number;
120
+ };
82
121
 
83
122
  export const MAX_COMPOSER_ATTACHMENT_BYTES = 500_000_000;
84
123
  export const MAX_COMPOSER_ATTACHMENT_COUNT = 10;
@@ -97,8 +136,9 @@ const INLINE_COMPOSER_IMAGE_TYPES = new Set([
97
136
  ]);
98
137
 
99
138
  export function isComposerInlineImageContentType(value: string) {
100
- const mediaType = value.split(";", 1)[0]?.trim().toLocaleLowerCase("en-US")
101
- ?? "";
139
+ const mediaType =
140
+ value.split(";", 1)[0]?.trim().toLocaleLowerCase("en-US") ?? "";
141
+
102
142
  return INLINE_COMPOSER_IMAGE_TYPES.has(mediaType);
103
143
  }
104
144
 
@@ -107,18 +147,21 @@ export function linkedAttachmentTextToken(uploadId: string) {
107
147
  }
108
148
 
109
149
  export function composerAttachmentLimitError(
110
- attachments: ReadonlyArray<{ size: number }>,
150
+ attachments: readonly { size: number }[]
111
151
  ) {
112
152
  if (attachments.length > MAX_COMPOSER_ATTACHMENT_COUNT) {
113
153
  return `Use at most ${MAX_COMPOSER_ATTACHMENT_COUNT} attachments`;
114
154
  }
155
+
115
156
  const totalBytes = attachments.reduce(
116
157
  (total, attachment) => total + attachment.size,
117
- 0,
158
+ 0
118
159
  );
160
+
119
161
  if (totalBytes > MAX_COMPOSER_ATTACHMENT_BYTES) {
120
162
  return `Attachments are limited to ${Math.floor(MAX_COMPOSER_ATTACHMENT_BYTES / 1_000_000)} MB per message`;
121
163
  }
164
+
122
165
  return null;
123
166
  }
124
167
 
@@ -146,31 +189,37 @@ export function attachmentsRequiringDownloadLinks(input: {
146
189
  bodyHtml?: string;
147
190
  attachments: ComposerAttachmentSize[];
148
191
  }) {
149
- const bodyBytes = byteLength(input.subject)
150
- + byteLength(input.bodyText)
151
- + byteLength(input.bodyHtml);
152
- let estimatedBytes = MIME_FIXED_OVERHEAD_BYTES
153
- + base64EncodedSize(bodyBytes)
154
- + input.attachments.reduce(
155
- (total, attachment) => total + base64EncodedSize(attachment.size) + 2_048,
156
- 0,
192
+ const bodyBytes =
193
+ byteLength(input.subject) +
194
+ byteLength(input.bodyText) +
195
+ byteLength(input.bodyHtml);
196
+
197
+ let estimatedBytes =
198
+ MIME_FIXED_OVERHEAD_BYTES +
199
+ base64EncodedSize(bodyBytes) +
200
+ input.attachments.reduce(
201
+ (total, attachment) => total + base64EncodedSize(attachment.size) + 2048,
202
+ 0
157
203
  );
204
+
158
205
  const linked = new Set<string>();
206
+
159
207
  if (estimatedBytes <= EMAIL_SERVICE_MAX_BYTES) return linked;
160
208
 
161
- for (
162
- const attachment of [...input.attachments]
163
- .sort((left, right) => right.size - left.size)
164
- ) {
209
+ for (const attachment of [...input.attachments].sort(
210
+ (left, right) => right.size - left.size
211
+ )) {
165
212
  linked.add(attachment.id);
166
- estimatedBytes -= base64EncodedSize(attachment.size) + 2_048;
213
+ estimatedBytes -= base64EncodedSize(attachment.size) + 2048;
214
+
167
215
  if (estimatedBytes <= EMAIL_SERVICE_MAX_BYTES) break;
168
216
  }
217
+
169
218
  return linked;
170
219
  }
171
220
 
172
221
  export function baseSubject(subject: string) {
173
- return subject.replace(/^(?:(?:re|fwd):\s*)+/giu, "");
222
+ return subject.replaceAll(/^(?:(?:re|fwd):\s*)+/giu, "");
174
223
  }
175
224
 
176
225
  export function replySubject(subject: string) {
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The mail module's id: its `Email()` infrastructure (its migrations are
3
+ * recorded as `modules/email/…`, so it never changes), its server part
4
+ * (`WorkspaceModule.name`, the key of its bootstrap data) and its part of the
5
+ * browser app (`ClientModule.name`).
6
+ */
7
+ export const EMAIL_MODULE = "email";
8
+
9
+ /** Where JMAP is served; `Email()` runs it, and everything under it, on the Worker. */
10
+ export const JMAP_PATH = "/jmap";
11
+
12
+ /**
13
+ * The Durable Object and Container classes index.ts exports, by the binding
14
+ * that names them: the generated Worker entry re-exports them, and the
15
+ * bindings' `className`s and the test Worker's replacements name them here.
16
+ */
17
+ export const emailClasses = {
18
+ MAILBOX: "MailboxDO",
19
+ OFFICE_PREVIEW_CONTAINER: "OfficePreviewContainer",
20
+ } as const;
21
+
22
+ /**
23
+ * The roles of the module's queues: `Email()`'s consumers name them, and
24
+ * `email()` has a handler for each (`WorkspaceModule.queues`).
25
+ */
26
+ export const emailQueueRoles = {
27
+ officePreviews: "office-previews",
28
+ pushNotifications: "push-notifications",
29
+ deliveryEvents: "delivery-events",
30
+ } as const;
31
+
32
+ export type EmailQueueRole =
33
+ (typeof emailQueueRoles)[keyof typeof emailQueueRoles];
@@ -3,12 +3,24 @@ export type PdfPreviewStatus = "pending" | "ready" | "failed";
3
3
  export const MAX_OFFICE_PREVIEW_BYTES = 20 * 1024 * 1024;
4
4
 
5
5
  const OFFICE_EXTENSIONS = new Set([
6
- "doc", "docx", "docm", "xls", "xlsx", "xlsm", "ppt", "pptx", "pptm",
7
- "odt", "ods", "odp", "rtf",
6
+ "doc",
7
+ "docx",
8
+ "docm",
9
+ "xls",
10
+ "xlsx",
11
+ "xlsm",
12
+ "ppt",
13
+ "pptx",
14
+ "pptm",
15
+ "odt",
16
+ "ods",
17
+ "odp",
18
+ "rtf",
8
19
  ]);
9
20
 
10
21
  export function officePreviewExtension(filename: string) {
11
22
  const extension = /\.([^.]+)$/u.exec(filename)?.[1]?.toLowerCase();
23
+
12
24
  return extension && OFFICE_EXTENSIONS.has(extension) ? extension : null;
13
25
  }
14
26
 
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The resources PDF.js requests by filename (CMaps for CJK text, standard
3
+ * fonts, the JPEG 2000 decoder, ICC profiles): `Email()` copies each folder
4
+ * of pdfjs-dist into the browser app at `pdfjsAssetPath(version, folder)`,
5
+ * and the PDF viewer asks for them there.
6
+ */
7
+ export const pdfjsAssetFolders = {
8
+ cMapUrl: "cmaps",
9
+ standardFontDataUrl: "standard_fonts",
10
+ wasmUrl: "wasm",
11
+ iccUrl: "iccs",
12
+ } as const;
13
+
14
+ export type PdfjsAssetFolder =
15
+ (typeof pdfjsAssetFolders)[keyof typeof pdfjsAssetFolders];
16
+
17
+ /** Where a folder of PDF.js `version`'s resources is served, relative to the app's root. */
18
+ export function pdfjsAssetPath(version: string, folder: PdfjsAssetFolder) {
19
+ return `pdfjs/${version}/${folder}`;
20
+ }
21
+
22
+ /** `getDocument`'s options that point PDF.js at its resources. */
23
+ export function pdfjsAssetUrls(
24
+ version: string
25
+ ): Record<keyof typeof pdfjsAssetFolders, string> {
26
+ const url = (folder: PdfjsAssetFolder) =>
27
+ `/${pdfjsAssetPath(version, folder)}/`;
28
+
29
+ return {
30
+ cMapUrl: url(pdfjsAssetFolders.cMapUrl),
31
+ standardFontDataUrl: url(pdfjsAssetFolders.standardFontDataUrl),
32
+ wasmUrl: url(pdfjsAssetFolders.wasmUrl),
33
+ iccUrl: url(pdfjsAssetFolders.iccUrl),
34
+ };
35
+ }
@@ -0,0 +1,73 @@
1
+ import type { PermissionDefinition } from "@open-workspace/core/shared";
2
+
3
+ /** Lets a member block senders and domains for every mailbox in the workspace. */
4
+ export const MANAGE_BLOCKED_SENDERS = "manage_blocked_senders";
5
+
6
+ /** The OAuth scope that hands an app MANAGE_BLOCKED_SENDERS. */
7
+ export const BLOCK_SENDERS_SCOPE = "admin.blocked_senders";
8
+
9
+ /**
10
+ * Lets a member import existing mail into any mailbox in the workspace.
11
+ * Without it, a person may import only into their own personal mailboxes
12
+ * (and an app only with `mail.organize`); see worker/mail/import-routes.ts.
13
+ */
14
+ export const IMPORT_MAIL = "import_mail";
15
+
16
+ /** The OAuth scope that hands an app IMPORT_MAIL. */
17
+ export const IMPORT_MAIL_SCOPE = "admin.import_mail";
18
+
19
+ /** What the mail module lets an administrator hand to a member. */
20
+ export const emailPermissions: PermissionDefinition[] = [
21
+ {
22
+ id: MANAGE_BLOCKED_SENDERS,
23
+ label: "Block senders",
24
+ scope: BLOCK_SENDERS_SCOPE,
25
+ description: "Block senders and domains for the whole workspace.",
26
+ },
27
+ {
28
+ id: IMPORT_MAIL,
29
+ label: "Import mail",
30
+ scope: IMPORT_MAIL_SCOPE,
31
+ description: "Import existing mail into any mailbox in the workspace.",
32
+ },
33
+ ];
34
+
35
+ /**
36
+ * What an app (an MCP client, or a mail app over JMAP) may do with the mail
37
+ * of the mailboxes its person can open. Each only works as far as the
38
+ * person may go themselves.
39
+ */
40
+ export const MAIL_READ_SCOPE = "mail.read";
41
+ export const MAIL_SEND_SCOPE = "mail.send";
42
+ export const MAIL_ORGANIZE_SCOPE = "mail.organize";
43
+
44
+ export const mailScopes = [
45
+ MAIL_READ_SCOPE,
46
+ MAIL_SEND_SCOPE,
47
+ MAIL_ORGANIZE_SCOPE,
48
+ ] as const;
49
+
50
+ /**
51
+ * The mail scopes as the consent screen shows them, under Mail. A
52
+ * self-registered app that asks for nothing may read mail.
53
+ */
54
+ export const mailOauthScopes = {
55
+ group: "mail",
56
+ title: "Mail",
57
+ scopes: [
58
+ {
59
+ id: MAIL_READ_SCOPE,
60
+ label: "Read the mail in the mailboxes you can open",
61
+ byDefault: true,
62
+ },
63
+ {
64
+ id: MAIL_SEND_SCOPE,
65
+ label: "Send mail as you, from the mailboxes you may send from",
66
+ },
67
+ {
68
+ id: MAIL_ORGANIZE_SCOPE,
69
+ label:
70
+ "Organize your mail: mark it read, move it, report spam, and manage folders and senders",
71
+ },
72
+ ],
73
+ };
@@ -0,0 +1,41 @@
1
+ import type { WebhookEventDeclaration } from "@open-workspace/core/shared";
2
+
3
+ /** The webhook events the mail module sends. */
4
+ export const EMAIL_RECEIVED_EVENT = "email.received";
5
+ export const EMAIL_SENT_EVENT = "email.sent";
6
+
7
+ export type EmailWebhookEvent =
8
+ | typeof EMAIL_RECEIVED_EVENT
9
+ | typeof EMAIL_SENT_EVENT;
10
+
11
+ /**
12
+ * The module's events as core offers them (`webhookEvents` on its server and
13
+ * browser halves). Both carry a mailbox's mail.
14
+ */
15
+ export const emailWebhookEvents: Record<
16
+ EmailWebhookEvent,
17
+ WebhookEventDeclaration
18
+ > = {
19
+ [EMAIL_RECEIVED_EVENT]: {
20
+ label: "Email received",
21
+ description: "After spam and AI routing, including text and HTML body.",
22
+ mailboxes: true,
23
+ },
24
+ [EMAIL_SENT_EVENT]: {
25
+ label: "Email sent",
26
+ description: "After an outgoing message is persisted and submitted.",
27
+ mailboxes: true,
28
+ },
29
+ };
30
+
31
+ /** The kind of webhook source the module queues: a message in a mailbox (worker/mail/webhook-source.ts). */
32
+ export const EMAIL_WEBHOOK_SOURCE = "email";
33
+
34
+ /** The stable id of a mail event, so a retried queue message is delivered once. */
35
+ export function emailWebhookEventId(
36
+ eventType: EmailWebhookEvent,
37
+ mailboxId: string,
38
+ messageId: string
39
+ ) {
40
+ return `evt_${eventType.replace(".", "_")}_${mailboxId}_${messageId}`;
41
+ }
@@ -0,0 +1,189 @@
1
+ import {
2
+ Button,
3
+ Checkbox,
4
+ Input,
5
+ Skeleton,
6
+ responseJson,
7
+ adminPanelClass,
8
+ AdminPanelBody,
9
+ AdminPanelHeader,
10
+ } from "@open-workspace/core/ui";
11
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
12
+ import { Building2, LoaderCircle, ShieldBan } from "lucide-react";
13
+ import { useState } from "react";
14
+ import type { FormEvent } from "react";
15
+ import { toast } from "sonner";
16
+
17
+ import { normalizeBlockPattern } from "../../shared/mail-feedback";
18
+ import { mailApi } from "../lib/mail-api";
19
+
20
+ const BLOCKED_SENDERS_KEY = ["admin-blocked-senders"] as const;
21
+
22
+ function formatDate(value: string | Date) {
23
+ return new Intl.DateTimeFormat("en", { dateStyle: "medium" }).format(
24
+ new Date(value)
25
+ );
26
+ }
27
+
28
+ function plural(count: number, one: string, many: string) {
29
+ return `${count} ${count === 1 ? one : many}`;
30
+ }
31
+
32
+ function useWorkspaceBlocks() {
33
+ const client = useQueryClient();
34
+
35
+ const invalidate = () =>
36
+ client.invalidateQueries({ queryKey: BLOCKED_SENDERS_KEY });
37
+
38
+ const list = useQuery({
39
+ queryKey: BLOCKED_SENDERS_KEY,
40
+ queryFn: async () =>
41
+ responseJson(await mailApi.api.admin["blocked-senders"].$get()),
42
+ });
43
+
44
+ const block = useMutation({
45
+ mutationFn: async (input: { pattern: string; moveExisting: boolean }) =>
46
+ responseJson(
47
+ await mailApi.api.admin["blocked-senders"].$post({ json: input })
48
+ ),
49
+ onSuccess: async (result) => {
50
+ const { moved } = result;
51
+ toast.success(`${result.pattern} is blocked for everyone`, {
52
+ description: moved?.conversations
53
+ ? `${plural(moved.conversations, "conversation", "conversations")} moved to Spam in ${plural(moved.mailboxes, "mailbox", "mailboxes")}.`
54
+ : undefined,
55
+ });
56
+
57
+ if (moved?.failedMailboxes) {
58
+ toast.warning(
59
+ `Existing mail could not be moved in ${plural(moved.failedMailboxes, "mailbox", "mailboxes")}.`
60
+ );
61
+ }
62
+
63
+ await invalidate();
64
+ },
65
+ onError: (error) => toast.error(error.message),
66
+ });
67
+
68
+ const unblock = useMutation({
69
+ mutationFn: async (pattern: string) =>
70
+ responseJson(
71
+ await mailApi.api.admin["blocked-senders"].$delete({
72
+ query: { pattern },
73
+ })
74
+ ),
75
+ onSuccess: async (_result, pattern) => {
76
+ toast.success(`${pattern} unblocked`);
77
+ await invalidate();
78
+ },
79
+ onError: (error) => toast.error(error.message),
80
+ });
81
+
82
+ return { list, block, unblock };
83
+ }
84
+
85
+ /** Administration → Blocked senders: addresses and domains blocked for every mailbox. */
86
+ export function BlockedSenders() {
87
+ const { list, block, unblock } = useWorkspaceBlocks();
88
+ const [value, setValue] = useState("");
89
+ const [moveExisting, setMoveExisting] = useState(true);
90
+ const pattern = normalizeBlockPattern(value);
91
+ const items = list.data?.blockedSenders ?? [];
92
+
93
+ function submit(event: FormEvent) {
94
+ event.preventDefault();
95
+
96
+ if (!pattern) return;
97
+ block.mutate({ pattern, moveExisting }, { onSuccess: () => setValue("") });
98
+ }
99
+
100
+ return (
101
+ <div className="max-w-4xl">
102
+ <div className={adminPanelClass}>
103
+ <AdminPanelHeader
104
+ Icon={ShieldBan}
105
+ title="Blocked for everyone"
106
+ description="Mail from these senders goes to Spam in every mailbox. Senders are not notified."
107
+ />
108
+ <AdminPanelBody className="space-y-4">
109
+ <form className="space-y-2.5" onSubmit={submit}>
110
+ <div className="flex gap-2">
111
+ <Input
112
+ aria-label="Address or domain to block for everyone"
113
+ placeholder="name@example.com or example.com"
114
+ value={value}
115
+ onChange={(event) => setValue(event.target.value)}
116
+ />
117
+ <Button
118
+ type="submit"
119
+ variant="destructive"
120
+ disabled={!pattern || block.isPending}
121
+ >
122
+ {block.isPending ? (
123
+ <LoaderCircle className="animate-spin" />
124
+ ) : (
125
+ <ShieldBan />
126
+ )}
127
+ Block
128
+ </Button>
129
+ </div>
130
+ <label className="text-muted-foreground flex items-center gap-2 text-xs">
131
+ <Checkbox
132
+ checked={moveExisting}
133
+ onCheckedChange={(checked) => setMoveExisting(checked === true)}
134
+ />
135
+ Also move mail already delivered from it to Spam
136
+ </label>
137
+ </form>
138
+ {list.isLoading ? (
139
+ <div className="space-y-2">
140
+ <Skeleton className="h-12" />
141
+ <Skeleton className="h-12" />
142
+ </div>
143
+ ) : items.length ? (
144
+ <ul
145
+ aria-label="Senders blocked for everyone"
146
+ className="divide-border/70 border-border divide-y rounded-lg border"
147
+ >
148
+ {items.map((item) => (
149
+ <li
150
+ key={item.pattern}
151
+ className="flex items-center gap-3 px-3.5 py-2.5"
152
+ >
153
+ {item.scope === "domain" ? (
154
+ <Building2 className="text-muted-foreground size-4 shrink-0" />
155
+ ) : (
156
+ <ShieldBan className="text-muted-foreground size-4 shrink-0" />
157
+ )}
158
+ <span className="min-w-0 flex-1">
159
+ <span className="block truncate text-sm font-medium">
160
+ {item.pattern}
161
+ </span>
162
+ <span className="text-muted-foreground block truncate text-xs">
163
+ {item.scope === "domain" ? "Whole domain" : "Address"}
164
+ {" · "}blocked {formatDate(item.createdAt)}
165
+ {item.createdByName ? ` by ${item.createdByName}` : ""}
166
+ </span>
167
+ </span>
168
+ <Button
169
+ size="sm"
170
+ variant="ghost"
171
+ aria-label={`Unblock ${item.pattern}`}
172
+ disabled={unblock.isPending}
173
+ onClick={() => unblock.mutate(item.pattern)}
174
+ >
175
+ Unblock
176
+ </Button>
177
+ </li>
178
+ ))}
179
+ </ul>
180
+ ) : (
181
+ <p className="text-muted-foreground py-6 text-center text-sm">
182
+ No senders are blocked for everyone.
183
+ </p>
184
+ )}
185
+ </AdminPanelBody>
186
+ </div>
187
+ </div>
188
+ );
189
+ }
package/src/client.tsx ADDED
@@ -0,0 +1,97 @@
1
+ import { preloadable } from "@open-workspace/core/ui";
2
+ import type { ClientModule } from "@open-workspace/core/ui";
3
+ import { Bell, Mail, MonitorSmartphone, ShieldBan } from "lucide-react";
4
+ import { lazy } from "react";
5
+
6
+ import { MAIL_ROUTE } from "../shared/mail-path";
7
+ import { EMAIL_MODULE } from "../shared/module";
8
+ import { MANAGE_BLOCKED_SENDERS } from "../shared/permissions";
9
+ import { emailWebhookEvents } from "../shared/webhooks";
10
+ import { prefetchMail } from "./mail/mail-prefetch";
11
+ import { loadSanitizer } from "./mail/mail-queries";
12
+ import { seedMail } from "./mail/mail-seed";
13
+
14
+ import "./mail/mail-layout.css";
15
+
16
+ /** Mail's part of the browser app; `Email()` in alchemy/index.ts points the build here. */
17
+
18
+ const mailboxRoute = preloadable(() =>
19
+ import("./mail/mailbox-route").then((module) => module.MailboxRoute)
20
+ );
21
+
22
+ const mailBackground = preloadable(() =>
23
+ import("./mail/mail-background").then((module) => module.MailBackground)
24
+ );
25
+
26
+ const MailboxRoute = mailboxRoute.Component;
27
+
28
+ const mail: ClientModule = {
29
+ name: EMAIL_MODULE,
30
+ home: { label: "mail", Component: MailboxRoute },
31
+ app: { label: "Mail", Icon: Mail, path: "/" },
32
+ routes: [{ path: MAIL_ROUTE, Component: MailboxRoute }],
33
+ settings: [
34
+ {
35
+ id: "notifications",
36
+ label: "Notifications",
37
+ description: "New mail alerts for this device and your mailboxes.",
38
+ Icon: Bell,
39
+ Component: lazy(() =>
40
+ import("./settings/notifications-page").then((module) => ({
41
+ default: module.NotificationsSettings,
42
+ }))
43
+ ),
44
+ },
45
+ {
46
+ id: "mail-apps",
47
+ label: "Mail apps",
48
+ description: "Connect a JMAP mail app with your account.",
49
+ Icon: MonitorSmartphone,
50
+ Component: lazy(() =>
51
+ import("./settings/mail-apps-page").then((module) => ({
52
+ default: module.MailAppsSettings,
53
+ }))
54
+ ),
55
+ },
56
+ ],
57
+ admin: [
58
+ {
59
+ id: "blocked-senders",
60
+ label: "Blocked senders",
61
+ Icon: ShieldBan,
62
+ permission: MANAGE_BLOCKED_SENDERS,
63
+ title: "Blocked senders",
64
+ description:
65
+ "Addresses and domains blocked for every mailbox in the workspace.",
66
+ Component: lazy(() =>
67
+ import("./admin/blocked-senders").then((module) => ({
68
+ default: module.BlockedSenders,
69
+ }))
70
+ ),
71
+ },
72
+ ],
73
+ webhookEvents: emailWebhookEvents,
74
+ background: mailBackground.Component,
75
+ preload: async () => {
76
+ // Message bodies need the sanitizer (DOMPurify); the screen need not wait for it.
77
+ loadSanitizer().catch(() => undefined);
78
+
79
+ await Promise.all([mailboxRoute.preload(), mailBackground.preload()]);
80
+ },
81
+ seed: seedMail,
82
+ prefetch: prefetchMail,
83
+ afterSignIn: async () => {
84
+ const { syncCurrentPushSubscription } =
85
+ await import("./pwa/push-subscription");
86
+
87
+ await syncCurrentPushSubscription();
88
+ },
89
+ beforeSignOut: async () => {
90
+ const { removePushSubscriptionForSignOut } =
91
+ await import("./pwa/push-subscription");
92
+
93
+ await removePushSubscriptionForSignOut();
94
+ },
95
+ };
96
+
97
+ export default mail;