@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
@@ -0,0 +1,291 @@
1
+ import {
2
+ adminPanelClass,
3
+ AdminPanelBody,
4
+ AdminPanelFooter,
5
+ AdminPanelHeader,
6
+ Button,
7
+ Switch,
8
+ useAuth,
9
+ responseJson,
10
+ } from "@open-workspace/core/ui";
11
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
12
+ import { Bell, BellOff, LoaderCircle, Smartphone } from "lucide-react";
13
+ import { toast } from "sonner";
14
+
15
+ import { mailApi } from "../lib/mail-api";
16
+ import {
17
+ currentPushRegistrationStatus,
18
+ disableCurrentPushSubscription,
19
+ enableCurrentPushSubscription,
20
+ } from "../pwa/push-subscription";
21
+
22
+ type DeviceStatus =
23
+ | "loading"
24
+ | "error"
25
+ | "unsupported"
26
+ | "prompt"
27
+ | "denied"
28
+ | "enabled";
29
+
30
+ function deviceStatusCopy(
31
+ status: DeviceStatus,
32
+ configured: boolean,
33
+ configurationError: string | null
34
+ ) {
35
+ if (status === "error") return "Could not check this device. Try again.";
36
+
37
+ if (configurationError) return configurationError;
38
+
39
+ if (!configured) return "Web Push is not configured on this server.";
40
+
41
+ if (status === "unsupported") {
42
+ return "Push is unavailable in this browser. On iPhone or iPad, add the app to the Home Screen first.";
43
+ }
44
+
45
+ if (status === "denied") {
46
+ return "Notifications are blocked in this browser's site settings.";
47
+ }
48
+
49
+ if (status === "enabled") {
50
+ return "This device can notify you when OpenWorkspace is closed.";
51
+ }
52
+
53
+ if (status === "prompt") {
54
+ return "Enable notifications for this browser and device.";
55
+ }
56
+
57
+ return "Checking this device…";
58
+ }
59
+
60
+ export function NotificationsSettings() {
61
+ const client = useQueryClient();
62
+ const userId = useAuth().user?.id;
63
+
64
+ const config = useQuery({
65
+ queryKey: ["push-config"],
66
+ queryFn: async () =>
67
+ responseJson(await mailApi.api.notifications.config.$get()),
68
+ staleTime: 60_000,
69
+ });
70
+
71
+ const preferences = useQuery({
72
+ queryKey: ["notification-preferences"],
73
+ queryFn: async () =>
74
+ responseJson(await mailApi.api.notifications.preferences.$get()),
75
+ });
76
+
77
+ const publicKey = config.data?.publicKey ?? null;
78
+ const deviceStatusKey = ["push-device-status", userId, publicKey] as const;
79
+
80
+ const device = useQuery({
81
+ queryKey: deviceStatusKey,
82
+ enabled: Boolean(config.data?.enabled && publicKey && userId),
83
+ queryFn: () => currentPushRegistrationStatus(),
84
+ });
85
+
86
+ const enable = useMutation({
87
+ mutationFn: async () => {
88
+ if (!publicKey) throw new Error("Web Push is not configured");
89
+
90
+ if (!userId) throw new Error("Sign in is required");
91
+ await enableCurrentPushSubscription(publicKey);
92
+ },
93
+ onSuccess: () => {
94
+ client.setQueryData(deviceStatusKey, "enabled" satisfies DeviceStatus);
95
+ toast.success("Notifications enabled on this device");
96
+ },
97
+ onError: (error) => {
98
+ void client.invalidateQueries({ queryKey: deviceStatusKey });
99
+ toast.error(error.message);
100
+ },
101
+ });
102
+
103
+ const disable = useMutation({
104
+ mutationFn: disableCurrentPushSubscription,
105
+ onSuccess: (removal) => {
106
+ client.setQueryData(deviceStatusKey, "prompt" satisfies DeviceStatus);
107
+
108
+ if (removal.browserUnsubscribed) {
109
+ toast.success("Notifications disabled on this device");
110
+ } else {
111
+ toast.warning(
112
+ "Notifications are disabled; this browser kept an unused subscription."
113
+ );
114
+ }
115
+ },
116
+ onError: (error) => toast.error(error.message),
117
+ });
118
+
119
+ const updatePreference = useMutation({
120
+ mutationFn: async ({
121
+ mailboxId,
122
+ enabled,
123
+ }: {
124
+ mailboxId: string;
125
+ enabled: boolean;
126
+ }) =>
127
+ responseJson(
128
+ await mailApi.api.notifications.preferences[":mailboxId"].$put({
129
+ param: { mailboxId },
130
+ json: { enabled },
131
+ })
132
+ ),
133
+ onSuccess: async () => {
134
+ await client.invalidateQueries({
135
+ queryKey: ["notification-preferences"],
136
+ });
137
+ },
138
+ onError: (error) => toast.error(error.message),
139
+ });
140
+
141
+ const configured = config.data?.enabled ?? false;
142
+
143
+ const deviceStatus: DeviceStatus =
144
+ config.isError || device.isError
145
+ ? "error"
146
+ : config.isLoading || (configured && device.isLoading)
147
+ ? "loading"
148
+ : configured
149
+ ? (device.data ?? "loading")
150
+ : "unsupported";
151
+
152
+ const devicePending =
153
+ config.isLoading ||
154
+ device.isFetching ||
155
+ enable.isPending ||
156
+ disable.isPending;
157
+
158
+ function handleDeviceAction() {
159
+ if (deviceStatus === "error") {
160
+ void (config.isError ? config.refetch() : device.refetch());
161
+
162
+ return;
163
+ }
164
+
165
+ enable.mutate();
166
+ }
167
+
168
+ return (
169
+ <div className={adminPanelClass}>
170
+ <AdminPanelHeader
171
+ Icon={Bell}
172
+ title="Mail notifications"
173
+ description="Alerts for new mail, set for you on this device."
174
+ />
175
+ <AdminPanelBody className="space-y-6">
176
+ <div className="flex flex-col gap-4 sm:flex-row sm:items-center">
177
+ <span className="bg-primary/12 text-primary grid size-11 shrink-0 place-items-center rounded-lg">
178
+ <Smartphone className="size-5" />
179
+ </span>
180
+ <div className="min-w-0 flex-1">
181
+ <p className="text-sm font-semibold">This device</p>
182
+ <p className="text-muted-foreground mt-1 text-xs leading-relaxed">
183
+ {deviceStatusCopy(
184
+ deviceStatus,
185
+ configured,
186
+ config.data?.error ?? null
187
+ )}
188
+ </p>
189
+ </div>
190
+ {deviceStatus === "enabled" ? (
191
+ <Button
192
+ variant="outline"
193
+ disabled={devicePending}
194
+ onClick={() => disable.mutate()}
195
+ >
196
+ {disable.isPending ? (
197
+ <LoaderCircle className="animate-spin" />
198
+ ) : (
199
+ <BellOff />
200
+ )}
201
+ Disable
202
+ </Button>
203
+ ) : (
204
+ <Button
205
+ disabled={
206
+ (deviceStatus !== "error" && !configured) ||
207
+ deviceStatus === "unsupported" ||
208
+ deviceStatus === "denied" ||
209
+ deviceStatus === "loading" ||
210
+ devicePending
211
+ }
212
+ onClick={handleDeviceAction}
213
+ >
214
+ {devicePending ? (
215
+ <LoaderCircle className="animate-spin" />
216
+ ) : (
217
+ <Bell />
218
+ )}
219
+ {deviceStatus === "error" ? "Retry" : "Enable"}
220
+ </Button>
221
+ )}
222
+ </div>
223
+
224
+ <div className="border-border/70 border-t pt-5">
225
+ <p className="text-sm font-semibold">Mailboxes</p>
226
+ <p className="text-muted-foreground mt-1 text-xs">
227
+ Choose which mailboxes may send you new-message notifications.
228
+ </p>
229
+ <div className="divide-border/70 mt-4 divide-y">
230
+ {preferences.isLoading ? (
231
+ <div className="text-muted-foreground flex items-center gap-2 py-4 text-xs">
232
+ <LoaderCircle className="size-4 animate-spin" /> Loading
233
+ mailboxes…
234
+ </div>
235
+ ) : preferences.isError ? (
236
+ <div className="flex items-center justify-between gap-4 py-4">
237
+ <p className="text-destructive text-xs">
238
+ Could not load mailbox preferences.
239
+ </p>
240
+ <Button
241
+ size="sm"
242
+ variant="outline"
243
+ disabled={preferences.isFetching}
244
+ onClick={() => void preferences.refetch()}
245
+ >
246
+ {preferences.isFetching && (
247
+ <LoaderCircle className="animate-spin" />
248
+ )}
249
+ Retry
250
+ </Button>
251
+ </div>
252
+ ) : preferences.data?.preferences.length ? (
253
+ preferences.data.preferences.map((preference) => (
254
+ <label
255
+ key={preference.mailboxId}
256
+ className="flex items-center gap-4 py-3"
257
+ >
258
+ <span className="min-w-0 flex-1">
259
+ <span className="block truncate text-sm font-medium">
260
+ {preference.displayName}
261
+ </span>
262
+ <span className="text-muted-foreground block truncate text-xs">
263
+ {preference.address}
264
+ </span>
265
+ </span>
266
+ <Switch
267
+ checked={preference.enabled}
268
+ disabled={updatePreference.isPending}
269
+ onCheckedChange={(enabled) =>
270
+ updatePreference.mutate({
271
+ mailboxId: preference.mailboxId,
272
+ enabled,
273
+ })
274
+ }
275
+ />
276
+ </label>
277
+ ))
278
+ ) : (
279
+ <p className="text-muted-foreground py-4 text-xs">
280
+ No mailboxes are available for notifications.
281
+ </p>
282
+ )}
283
+ </div>
284
+ </div>
285
+ </AdminPanelBody>
286
+ <AdminPanelFooter className="text-muted-foreground justify-start text-xs">
287
+ You won't be notified about a mailbox while it's open in a tab.
288
+ </AdminPanelFooter>
289
+ </div>
290
+ );
291
+ }
@@ -0,0 +1,166 @@
1
+ import {
2
+ zValidator,
3
+ oauthScope,
4
+ createDb,
5
+ configuredMailDomains,
6
+ mailboxes,
7
+ users,
8
+ apiError,
9
+ requireAuth,
10
+ requirePermission,
11
+ } from "@open-workspace/core/module";
12
+ import type { AppEnv } from "@open-workspace/core/module";
13
+ import { desc, eq } from "drizzle-orm";
14
+ import { Hono } from "hono";
15
+
16
+ import { normalizeBlockPattern } from "../../shared/mail-feedback";
17
+ import {
18
+ BLOCK_SENDERS_SCOPE,
19
+ MANAGE_BLOCKED_SENDERS,
20
+ } from "../../shared/permissions";
21
+ import { blockedSenders } from "../db/schema";
22
+ import { forgetWorkspaceBlockPatterns } from "../mail/workspace-safety";
23
+ import { mailboxStub } from "../mailbox";
24
+ import { workspaceBlockQuerySchema, workspaceBlockSchema } from "./schemas";
25
+
26
+ const MAILBOX_FANOUT = 20;
27
+
28
+ /** Moves existing mail from a newly blocked pattern to Spam in every mailbox. */
29
+ async function moveBlockedMailToSpam(env: Env, pattern: string) {
30
+ const rows = await createDb(env.DB)
31
+ .select({ id: mailboxes.id })
32
+ .from(mailboxes);
33
+
34
+ let conversations = 0;
35
+ let affectedMailboxes = 0;
36
+ let failedMailboxes = 0;
37
+
38
+ for (let index = 0; index < rows.length; index += MAILBOX_FANOUT) {
39
+ // oxlint-disable-next-line eslint/no-await-in-loop -- at most MAILBOX_FANOUT mailboxes at a time, so one block does not wake every mailbox at once
40
+ const results = await Promise.allSettled(
41
+ rows
42
+ .slice(index, index + MAILBOX_FANOUT)
43
+ .map((row) => mailboxStub(env, row.id).moveSenderToSpam(pattern))
44
+ );
45
+
46
+ for (const result of results) {
47
+ if (result.status === "rejected") {
48
+ failedMailboxes += 1;
49
+ console.error(
50
+ `Could not move mail from ${pattern} to Spam`,
51
+ result.reason
52
+ );
53
+ } else if (result.value > 0) {
54
+ conversations += result.value;
55
+ affectedMailboxes += 1;
56
+ }
57
+ }
58
+ }
59
+
60
+ return { conversations, mailboxes: affectedMailboxes, failedMailboxes };
61
+ }
62
+
63
+ /** Workspace-wide sender blocks, managed by members allowed to block senders. */
64
+ export const blockedSenderAdminRoutes = new Hono<AppEnv>()
65
+ .use("*", requireAuth, requirePermission(MANAGE_BLOCKED_SENDERS))
66
+ // An app's token needs this permission's scope (the path, not "*": these
67
+ // routes sit under /admin next to core's).
68
+ .use("/blocked-senders", oauthScope(BLOCK_SENDERS_SCOPE))
69
+ .get("/blocked-senders", async (c) => {
70
+ const rows = await createDb(c.env.DB)
71
+ .select({
72
+ pattern: blockedSenders.pattern,
73
+ createdAt: blockedSenders.createdAt,
74
+ createdByName: users.name,
75
+ })
76
+ .from(blockedSenders)
77
+ .leftJoin(users, eq(users.id, blockedSenders.createdByUserId))
78
+ .orderBy(desc(blockedSenders.createdAt));
79
+
80
+ return c.json({
81
+ ok: true as const,
82
+ blockedSenders: rows.map((row) => ({
83
+ pattern: row.pattern,
84
+ scope: row.pattern.startsWith("@")
85
+ ? ("domain" as const)
86
+ : ("address" as const),
87
+ createdByName: row.createdByName,
88
+ createdAt: row.createdAt,
89
+ })),
90
+ });
91
+ })
92
+ .post(
93
+ "/blocked-senders",
94
+ zValidator("json", workspaceBlockSchema),
95
+ async (c) => {
96
+ const input = c.req.valid("json");
97
+ const pattern = normalizeBlockPattern(input.pattern);
98
+
99
+ if (!pattern) {
100
+ return apiError(
101
+ c,
102
+ 400,
103
+ "BAD_REQUEST",
104
+ "Enter an email address or a domain"
105
+ );
106
+ }
107
+
108
+ const db = createDb(c.env.DB);
109
+ const own = configuredMailDomains();
110
+ const domain = pattern.slice(pattern.lastIndexOf("@") + 1);
111
+
112
+ if (
113
+ own.some(
114
+ (name) =>
115
+ domain === name ||
116
+ domain.endsWith(`.${name}`) ||
117
+ name.endsWith(`.${domain}`)
118
+ )
119
+ ) {
120
+ return apiError(
121
+ c,
122
+ 400,
123
+ "BAD_REQUEST",
124
+ "Workspace mail domains cannot be blocked"
125
+ );
126
+ }
127
+
128
+ await db
129
+ .insert(blockedSenders)
130
+ .values({
131
+ pattern,
132
+ createdByUserId: c.get("user").id,
133
+ createdAt: new Date(),
134
+ })
135
+ .onConflictDoNothing();
136
+ forgetWorkspaceBlockPatterns();
137
+
138
+ const moved = input.moveExisting
139
+ ? await moveBlockedMailToSpam(c.env, pattern)
140
+ : null;
141
+
142
+ return c.json({ ok: true as const, pattern, moved });
143
+ }
144
+ )
145
+ .delete(
146
+ "/blocked-senders",
147
+ zValidator("query", workspaceBlockQuerySchema),
148
+ async (c) => {
149
+ const pattern = normalizeBlockPattern(c.req.valid("query").pattern);
150
+
151
+ const deleted = pattern
152
+ ? await createDb(c.env.DB)
153
+ .delete(blockedSenders)
154
+ .where(eq(blockedSenders.pattern, pattern))
155
+ .returning()
156
+ : [];
157
+
158
+ if (!deleted.length) {
159
+ return apiError(c, 404, "NOT_FOUND", "Blocked sender not found");
160
+ }
161
+
162
+ forgetWorkspaceBlockPatterns();
163
+
164
+ return c.json({ ok: true as const });
165
+ }
166
+ );
@@ -0,0 +1,11 @@
1
+ import { z } from "zod";
2
+
3
+ export const workspaceBlockSchema = z.object({
4
+ pattern: z.string().trim().min(3).max(320),
5
+ /** Also move mail already delivered from the pattern to Spam in every mailbox. */
6
+ moveExisting: z.boolean().default(true),
7
+ });
8
+
9
+ export const workspaceBlockQuerySchema = z.object({
10
+ pattern: z.string().trim().min(3).max(320),
11
+ });
@@ -1,11 +1,15 @@
1
- /** Bindings the mail module needs, on top of core's. */
2
- interface Env {
3
- MAIL_STORAGE: R2Bucket;
4
- EMAIL: SendEmail;
5
- MAILBOX: DurableObjectNamespace<import("./mailbox/index").MailboxDO>;
6
- OFFICE_PREVIEW_CONTAINER: DurableObjectNamespace<
7
- import("./mail/office-preview-container").OfficePreviewContainer
8
- >;
9
- OFFICE_PREVIEWS: Queue;
10
- PUSH_NOTIFICATIONS: Queue;
1
+ import type { EmailEnv } from "../alchemy/index";
2
+ import type { OfficePreviewContainer } from "./mail/office-preview-container";
3
+ import type { MailboxDO } from "./mailbox/index";
4
+
5
+ /** The classes behind the namespaces, which Alchemy's side does not import. */
6
+ type EmailClassBindings = {
7
+ MAILBOX: DurableObjectNamespace<MailboxDO>;
8
+ OFFICE_PREVIEW_CONTAINER: DurableObjectNamespace<OfficePreviewContainer>;
9
+ };
10
+
11
+ declare global {
12
+ /** The mail module's bindings, derived from what `Email()` declares (`EmailEnv`). */
13
+ interface Env
14
+ extends Omit<EmailEnv, keyof EmailClassBindings>, EmailClassBindings {}
11
15
  }
@@ -1,3 +1,4 @@
1
+ import { mailboxes, oidcGrants, users } from "@open-workspace/core/module";
1
2
  import { sql } from "drizzle-orm";
2
3
  import {
3
4
  foreignKey,
@@ -8,8 +9,6 @@ import {
8
9
  text,
9
10
  uniqueIndex,
10
11
  } from "drizzle-orm/sqlite-core";
11
- import { mailboxes, oidcGrants, users } from "@open-workspace/core/worker/db/schema.ts";
12
- import type { ReportSnapshot } from "../../shared/mail-feedback";
13
12
 
14
13
  /** D1 tables of the mail module; core's tables are in @open-workspace/core. */
15
14
 
@@ -30,42 +29,36 @@ export const mailboxNotificationPreferences = sqliteTable(
30
29
  (table) => [
31
30
  primaryKey({ columns: [table.mailboxId, table.userId] }),
32
31
  index("mailbox_notification_preferences_user_idx").on(table.userId),
33
- ],
32
+ ]
34
33
  );
35
34
 
36
- /**
37
- * Messages people reported as phishing, for administrators to review. The
38
- * message itself stays in its mailbox; administrators reach it only through
39
- * the report.
40
- */
41
- export const reportedMessages = sqliteTable(
42
- "reported_messages",
35
+ /** Browsers that get new-mail notifications, one row per device. */
36
+ export const pushSubscriptions = sqliteTable(
37
+ "push_subscriptions",
43
38
  {
44
39
  id: text("id").primaryKey(),
45
- mailboxId: text("mailbox_id")
40
+ userId: text("user_id")
46
41
  .notNull()
47
- .references(() => mailboxes.id, { onDelete: "cascade" }),
48
- emailId: text("email_id").notNull(),
49
- reporterUserId: text("reporter_user_id").references(() => users.id, { onDelete: "set null" }),
50
- senderAddress: text("sender_address").notNull(),
51
- senderDomain: text("sender_domain").notNull(),
52
- subject: text("subject").notNull(),
53
- receivedAt: integer("received_at", { mode: "timestamp_ms" }).notNull(),
54
- snapshotJson: text("snapshot_json", { mode: "json" }).$type<ReportSnapshot>().notNull(),
55
- status: text("status", { enum: ["open", "resolved", "dismissed"] }).notNull().default("open"),
56
- resolvedByUserId: text("resolved_by_user_id").references(() => users.id, { onDelete: "set null" }),
57
- resolvedAt: integer("resolved_at", { mode: "timestamp_ms" }),
58
- createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull(),
42
+ .references(() => users.id, { onDelete: "cascade" }),
43
+ endpoint: text("endpoint").notNull(),
44
+ p256dh: text("p256dh").notNull(),
45
+ auth: text("auth").notNull(),
46
+ createdAt: integer("created_at", { mode: "timestamp_ms" })
47
+ .notNull()
48
+ .default(sql`(unixepoch() * 1000)`),
49
+ updatedAt: integer("updated_at", { mode: "timestamp_ms" })
50
+ .notNull()
51
+ .default(sql`(unixepoch() * 1000)`),
59
52
  },
60
53
  (table) => [
61
- uniqueIndex("reported_messages_email_unique").on(table.mailboxId, table.emailId),
62
- index("reported_messages_status_idx").on(table.status, table.createdAt),
63
- ],
54
+ uniqueIndex("push_subscriptions_endpoint_unique").on(table.endpoint),
55
+ index("push_subscriptions_user_idx").on(table.userId),
56
+ ]
64
57
  );
65
58
 
66
59
  /**
67
60
  * What people said about a sender in each mailbox (one row per message), so
68
- * every mailbox's classifier hears about spam and phishing reported elsewhere.
61
+ * every mailbox's classifier hears about spam reported elsewhere.
69
62
  * Per mailbox and address the latest stance wins: "not spam" replaces reports.
70
63
  */
71
64
  export const senderReports = sqliteTable(
@@ -77,25 +70,23 @@ export const senderReports = sqliteTable(
77
70
  emailId: text("email_id").notNull(),
78
71
  address: text("address").notNull(),
79
72
  domain: text("domain").notNull(),
80
- label: text("label", { enum: ["spam", "phishing", "not_spam"] }).notNull(),
73
+ label: text("label", { enum: ["spam", "not_spam"] }).notNull(),
81
74
  createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull(),
82
75
  },
83
76
  (table) => [
84
77
  primaryKey({ columns: [table.mailboxId, table.emailId] }),
85
78
  index("sender_reports_domain_idx").on(table.domain, table.address),
86
- ],
79
+ ]
87
80
  );
88
81
 
89
82
  /** Workspace-wide sender blocks: an address or `@domain`, applied at ingestion in every mailbox. */
90
- export const blockedSenders = sqliteTable(
91
- "blocked_senders",
92
- {
93
- pattern: text("pattern").primaryKey(),
94
- reportId: text("report_id").references(() => reportedMessages.id, { onDelete: "set null" }),
95
- createdByUserId: text("created_by_user_id").references(() => users.id, { onDelete: "set null" }),
96
- createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull(),
97
- },
98
- );
83
+ export const blockedSenders = sqliteTable("blocked_senders", {
84
+ pattern: text("pattern").primaryKey(),
85
+ createdByUserId: text("created_by_user_id").references(() => users.id, {
86
+ onDelete: "set null",
87
+ }),
88
+ createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull(),
89
+ });
99
90
 
100
91
  /**
101
92
  * JMAP push subscriptions (RFC 8620 §7.2). Each belongs to the OAuth grant
@@ -124,7 +115,39 @@ export const jmapPushSubscriptions = sqliteTable(
124
115
  columns: [table.clientId, table.userId],
125
116
  foreignColumns: [oidcGrants.clientId, oidcGrants.userId],
126
117
  }).onDelete("cascade"),
127
- uniqueIndex("jmap_push_subscriptions_device_unique").on(table.userId, table.deviceClientId),
118
+ uniqueIndex("jmap_push_subscriptions_device_unique").on(
119
+ table.userId,
120
+ table.deviceClientId
121
+ ),
128
122
  index("jmap_push_subscriptions_expires_idx").on(table.expiresAt),
129
- ],
123
+ ]
124
+ );
125
+
126
+ /**
127
+ * Each mailbox's inbox counts, written by its Durable Object whenever its
128
+ * mail changes, so mailbox lists read unread counts from D1 without waking
129
+ * every mailbox. A person's unread count is `incomingCount` less their
130
+ * `mailboxReadCounts.readCount` (no row: nothing read). `version` is the
131
+ * mailbox's change counter the counts reflect.
132
+ */
133
+ export const mailboxCounts = sqliteTable("mailbox_counts", {
134
+ mailboxId: text("mailbox_id")
135
+ .primaryKey()
136
+ .references(() => mailboxes.id, { onDelete: "cascade" }),
137
+ incomingCount: integer("incoming_count").notNull(),
138
+ version: integer("version").notNull(),
139
+ updatedAt: integer("updated_at", { mode: "timestamp_ms" }).notNull(),
140
+ });
141
+
142
+ /** How many of a mailbox's incoming inbox messages each person has read. */
143
+ export const mailboxReadCounts = sqliteTable(
144
+ "mailbox_read_counts",
145
+ {
146
+ mailboxId: text("mailbox_id")
147
+ .notNull()
148
+ .references(() => mailboxes.id, { onDelete: "cascade" }),
149
+ userId: text("user_id").notNull(),
150
+ readCount: integer("read_count").notNull(),
151
+ },
152
+ (table) => [primaryKey({ columns: [table.mailboxId, table.userId] })]
130
153
  );