@open-workspace/email 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/README.md +22 -22
  2. package/alchemy/index.ts +273 -0
  3. package/drizzle/mailbox/0000_puzzling_dracula.sql +149 -0
  4. package/drizzle/mailbox/0001_mute_jack_flag.sql +12 -0
  5. package/drizzle/mailbox/meta/0000_snapshot.json +1002 -0
  6. package/drizzle/mailbox/meta/0001_snapshot.json +1002 -0
  7. package/drizzle/mailbox/meta/_journal.json +20 -0
  8. package/drizzle/mailbox/migrations.js +12 -0
  9. package/index.ts +3 -1
  10. package/migrations/{0000_email.sql → 0000_dry_moon_knight.sql} +26 -20
  11. package/migrations/meta/0000_snapshot.json +125 -109
  12. package/migrations/meta/_journal.json +2 -2
  13. package/package.json +74 -68
  14. package/shared/attachment-preview.ts +37 -27
  15. package/shared/folder-order.ts +106 -0
  16. package/shared/mail-authentication.ts +8 -3
  17. package/shared/mail-feedback.ts +18 -25
  18. package/shared/mail-headers.ts +114 -39
  19. package/shared/mail-import.ts +38 -0
  20. package/shared/mail-path.ts +42 -0
  21. package/shared/mail-received.ts +174 -31
  22. package/shared/mail-remote.ts +59 -2
  23. package/shared/mail-sender-intel.ts +22 -4
  24. package/shared/mail.ts +77 -28
  25. package/shared/module.ts +33 -0
  26. package/shared/office-preview.ts +14 -2
  27. package/shared/pdfjs-assets.ts +35 -0
  28. package/shared/permissions.ts +73 -0
  29. package/shared/webhooks.ts +41 -0
  30. package/src/admin/blocked-senders.tsx +189 -0
  31. package/src/client.tsx +97 -0
  32. package/src/lib/mail-api.ts +9 -0
  33. package/src/mail/attachment-preview-dialog.tsx +161 -0
  34. package/src/mail/blocked-senders.tsx +138 -0
  35. package/src/mail/compose-window-chrome.tsx +194 -0
  36. package/src/mail/compose-window.tsx +486 -0
  37. package/src/mail/composer-asset-bookmarks.ts +409 -0
  38. package/src/mail/composer-asset.tsx +229 -0
  39. package/src/mail/composer-attachment-list.tsx +138 -0
  40. package/src/mail/composer-editor-document.ts +65 -0
  41. package/src/mail/composer-editor.tsx +284 -0
  42. package/src/mail/composer-linked-attachment-text.ts +12 -0
  43. package/src/mail/composer-recipient-fields.tsx +165 -0
  44. package/src/mail/composer-recipients.ts +208 -0
  45. package/src/mail/composer-session.ts +562 -0
  46. package/src/mail/composer-toolbar.tsx +303 -0
  47. package/src/mail/composer-upload-client.ts +105 -0
  48. package/src/mail/composer-upload-progress.ts +53 -0
  49. package/src/mail/conversation-list.tsx +550 -0
  50. package/src/mail/conversation-loading-skeleton.tsx +119 -0
  51. package/src/mail/conversation-message.tsx +346 -0
  52. package/src/mail/conversation-reply.tsx +470 -0
  53. package/src/mail/conversation-selection-toolbar.tsx +322 -0
  54. package/src/mail/conversation-view.tsx +437 -0
  55. package/src/mail/delivery-indicator.tsx +272 -0
  56. package/src/mail/email-html-body.tsx +203 -0
  57. package/src/mail/folder-glyph.tsx +46 -0
  58. package/src/mail/folder-manager.tsx +532 -0
  59. package/src/mail/format-bytes.ts +7 -0
  60. package/src/mail/mail-app-bar.tsx +253 -0
  61. package/src/mail/mail-background.tsx +12 -0
  62. package/src/mail/mail-dock.tsx +137 -0
  63. package/src/mail/mail-folders.ts +44 -0
  64. package/src/mail/mail-layout.css +236 -0
  65. package/src/mail/mail-location.ts +73 -0
  66. package/src/mail/mail-mailbox-sheet.tsx +275 -0
  67. package/src/mail/mail-nav-rail.tsx +129 -0
  68. package/src/mail/mail-nav.tsx +324 -0
  69. package/src/mail/mail-prefetch.ts +59 -0
  70. package/src/mail/mail-primitives.tsx +66 -0
  71. package/src/mail/mail-queries.ts +209 -0
  72. package/src/mail/mail-query-cache.ts +486 -0
  73. package/src/mail/mail-seed.ts +47 -0
  74. package/src/mail/mail-shell.tsx +126 -0
  75. package/src/mail/mailbox-ai-settings.tsx +185 -0
  76. package/src/mail/mailbox-realtime.tsx +251 -0
  77. package/src/mail/mailbox-route.tsx +15 -0
  78. package/src/mail/message-actions.tsx +353 -0
  79. package/src/mail/message-attachments.tsx +200 -0
  80. package/src/mail/message-format.ts +75 -0
  81. package/src/mail/message-header.tsx +260 -0
  82. package/src/mail/message-translation.tsx +225 -0
  83. package/src/mail/original-message-sheet.tsx +619 -0
  84. package/src/mail/original-message.ts +191 -0
  85. package/src/mail/outbound-notification.ts +53 -0
  86. package/src/mail/pane-splitter.tsx +117 -0
  87. package/src/mail/pdf-preview-toolbar.tsx +152 -0
  88. package/src/mail/pdf-preview.css +44 -0
  89. package/src/mail/pdf-preview.tsx +156 -0
  90. package/src/mail/pdf-translation-layout.ts +95 -0
  91. package/src/mail/print-message.ts +92 -0
  92. package/src/mail/reader-pane.tsx +535 -0
  93. package/src/mail/recipient-combobox.tsx +335 -0
  94. package/src/mail/recipient-field-row.tsx +34 -0
  95. package/src/mail/reply-to-warning.tsx +50 -0
  96. package/src/mail/sanitize-email-html.ts +430 -0
  97. package/src/mail/sender-actions.tsx +149 -0
  98. package/src/mail/sender-authentication.tsx +485 -0
  99. package/src/mail/sender-dialogs.tsx +384 -0
  100. package/src/mail/sender-security.tsx +545 -0
  101. package/src/mail/toolbar-tooltip.tsx +29 -0
  102. package/src/mail/translation-html.ts +49 -0
  103. package/src/mail/translation-language.ts +21 -0
  104. package/src/mail/types.ts +53 -0
  105. package/src/mail/unread-document-indicator.tsx +60 -0
  106. package/src/mail/use-compose-submission.ts +208 -0
  107. package/src/mail/use-composer-attachment-preflight.ts +184 -0
  108. package/src/mail/use-composer-submission.ts +117 -0
  109. package/src/mail/use-conversation-selection.ts +186 -0
  110. package/src/mail/use-mail-controller.ts +427 -0
  111. package/src/mail/use-mail-data.ts +279 -0
  112. package/src/mail/use-mail-safety.ts +155 -0
  113. package/src/mail/use-mail-send.ts +142 -0
  114. package/src/mail/use-pdf-translation-overlay.ts +156 -0
  115. package/src/mail/use-pdf-translation.ts +100 -0
  116. package/src/mail/use-pdf-viewer.ts +215 -0
  117. package/src/mail/use-reply-submission.ts +114 -0
  118. package/src/mail/use-sanitized-email-html.ts +20 -0
  119. package/src/mail/use-visible-message-read.ts +138 -0
  120. package/src/pwa/push-subscription.ts +151 -0
  121. package/src/settings/mail-apps-page.tsx +235 -0
  122. package/src/settings/notifications-page.tsx +291 -0
  123. package/worker/admin/blocked-sender-routes.ts +166 -0
  124. package/worker/admin/schemas.ts +11 -0
  125. package/worker/bindings.d.ts +14 -10
  126. package/worker/db/schema.ts +63 -40
  127. package/worker/jmap/eventsource.ts +84 -16
  128. package/worker/jmap/methods.ts +1630 -524
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +140 -56
  131. package/worker/jmap/routes.ts +366 -105
  132. package/worker/mail/access.ts +258 -21
  133. package/worker/mail/ai-classification.ts +36 -20
  134. package/worker/mail/ai-translation.ts +13 -6
  135. package/worker/mail/auth-headers.ts +395 -137
  136. package/worker/mail/bimi.ts +200 -73
  137. package/worker/mail/bootstrap.ts +79 -0
  138. package/worker/mail/capped-body.ts +36 -0
  139. package/worker/mail/classification-signals.ts +35 -25
  140. package/worker/mail/conversation-cursor.ts +30 -19
  141. package/worker/mail/delivery-events.ts +88 -62
  142. package/worker/mail/delivery-facts.ts +46 -10
  143. package/worker/mail/demo-routes.ts +34 -10
  144. package/worker/mail/doh.ts +62 -23
  145. package/worker/mail/downloads.ts +75 -40
  146. package/worker/mail/edge-cache.ts +155 -0
  147. package/worker/mail/header-metadata.ts +88 -22
  148. package/worker/mail/impersonation.ts +160 -38
  149. package/worker/mail/import-routes.ts +313 -0
  150. package/worker/mail/inbound-delivery.ts +19 -9
  151. package/worker/mail/inbound-threading.ts +18 -8
  152. package/worker/mail/inbound.ts +82 -40
  153. package/worker/mail/ip-intel.ts +110 -27
  154. package/worker/mail/isolate-cache.ts +35 -0
  155. package/worker/mail/link-domains.ts +29 -7
  156. package/worker/mail/mailbox-deletion.ts +10 -4
  157. package/worker/mail/mailbox-directory.ts +16 -6
  158. package/worker/mail/mailing-list.ts +94 -39
  159. package/worker/mail/message-security.ts +90 -15
  160. package/worker/mail/message-view.ts +18 -6
  161. package/worker/mail/office-conversion.ts +31 -9
  162. package/worker/mail/office-preview-container.ts +40 -13
  163. package/worker/mail/office-preview-queue.ts +76 -32
  164. package/worker/mail/org-domain.ts +8 -1
  165. package/worker/mail/outbound-content.ts +71 -26
  166. package/worker/mail/outbound-delivery.ts +31 -17
  167. package/worker/mail/outbound-service.ts +48 -30
  168. package/worker/mail/outbound-threading.ts +30 -17
  169. package/worker/mail/outbound.ts +97 -70
  170. package/worker/mail/outgoing-context.ts +25 -15
  171. package/worker/mail/participants.ts +44 -29
  172. package/worker/mail/push-notifications.ts +271 -173
  173. package/worker/mail/quote-parser.ts +21 -10
  174. package/worker/mail/r2-presigned-urls.ts +31 -25
  175. package/worker/mail/receive.ts +23 -11
  176. package/worker/mail/recipients.ts +6 -1
  177. package/worker/mail/remote-proxy.ts +187 -31
  178. package/worker/mail/remote-routes.ts +87 -0
  179. package/worker/mail/remote-token.ts +104 -0
  180. package/worker/mail/repeat.ts +19 -0
  181. package/worker/mail/reply-plan.ts +62 -33
  182. package/worker/mail/rfc.ts +32 -7
  183. package/worker/mail/routes.ts +870 -541
  184. package/worker/mail/safety-routes.ts +328 -200
  185. package/worker/mail/schemas.ts +84 -105
  186. package/worker/mail/search.ts +1 -0
  187. package/worker/mail/security-settings.ts +41 -9
  188. package/worker/mail/sender-intel.ts +206 -51
  189. package/worker/mail/spamhaus.ts +92 -45
  190. package/worker/mail/unsubscribe.ts +76 -18
  191. package/worker/mail/uploads.ts +126 -93
  192. package/worker/mail/webhook-source.ts +35 -12
  193. package/worker/mail/workspace-safety.ts +97 -38
  194. package/worker/mailbox/demo-html.ts +7 -7
  195. package/worker/mailbox/demo-seed.ts +10 -44
  196. package/worker/mailbox/demo.ts +595 -225
  197. package/worker/mailbox/email-index.ts +53 -0
  198. package/worker/mailbox/folder-model.ts +53 -17
  199. package/worker/mailbox/import-placement.ts +88 -0
  200. package/worker/mailbox/inbox-counts.ts +106 -0
  201. package/worker/mailbox/index.ts +1734 -721
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +8 -6
  204. package/worker/mailbox/office-preview-jobs.ts +56 -25
  205. package/worker/mailbox/schema.ts +87 -66
  206. package/worker/mailbox/senders.ts +176 -70
  207. package/worker/mcp/mail-action-tools.ts +128 -87
  208. package/worker/mcp/mail-compose-tools.ts +133 -82
  209. package/worker/mcp/mail-query-tools.ts +120 -71
  210. package/worker/mcp/mail-safety-tools.ts +321 -248
  211. package/worker/mcp/schemas.ts +43 -0
  212. package/worker/mcp/tools.ts +13 -10
  213. package/worker/module.ts +43 -18
  214. package/worker/sql.d.ts +8 -0
  215. package/alchemy.ts +0 -142
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/shared/mail-rules.ts +0 -156
  218. package/worker/admin/report-routes.ts +0 -164
  219. package/worker/mail/reported-messages.ts +0 -68
  220. package/worker/mailbox/migrations.ts +0 -10
  221. package/worker/mailbox/rules.ts +0 -110
@@ -3,55 +3,72 @@ import {
3
3
  topicFromString,
4
4
  WebPushError,
5
5
  } from "@mmmike/web-push/send";
6
+ import { createVapidJwt, urlBase64ToUint8Array } from "@mmmike/web-push/vapid";
6
7
  import {
7
- createVapidJwt,
8
- urlBase64ToUint8Array,
9
- } from "@mmmike/web-push/vapid";
10
- import { zValidator } from "@hono/zod-validator";
8
+ zValidator,
9
+ requireSessionAuth,
10
+ createDb,
11
+ mailboxAccess,
12
+ mailboxes,
13
+ users,
14
+ mailboxAddressSql,
15
+ mailboxKindOrderSql,
16
+ apiError,
17
+ createId,
18
+ } from "@open-workspace/core/module";
19
+ import type { Database, AppEnv } from "@open-workspace/core/module";
11
20
  import { and, desc, eq, isNull, or } from "drizzle-orm";
12
21
  import { Hono } from "hono";
13
22
  import { z } from "zod";
23
+
14
24
  import type { MailboxPushJob } from "../../shared/mail";
15
- import { requireSessionAuth } from "@open-workspace/core/worker/auth/middleware.ts";
16
- import { createDb } from "@open-workspace/core/worker/db/client.ts";
17
- import { domains, mailboxAccess, mailboxes, pushSubscriptions, users } from "@open-workspace/core/worker/db/schema.ts";
18
- import { mailboxNotificationPreferences } from "../db/schema";
19
- import { mailboxAddressSql, mailboxKindOrderSql } from "@open-workspace/core/worker/db/mailboxes.ts";
20
- import type { AppEnv, PushBindings } from "@open-workspace/core/worker/env.ts";
21
- import { apiError } from "@open-workspace/core/worker/lib/http.ts";
22
- import { createId } from "@open-workspace/core/worker/lib/ids.ts";
23
- import { mailboxStub } from "../mailbox";
25
+ import { mailPath } from "../../shared/mail-path";
26
+ import {
27
+ mailboxNotificationPreferences,
28
+ pushSubscriptions,
29
+ } from "../db/schema";
24
30
  import { deliverJmapStateChange } from "../jmap/push";
31
+ import { mailboxStub } from "../mailbox";
25
32
  import { getMailboxAccess } from "./access";
26
33
 
27
- export const PUSH_NOTIFICATION_QUEUE = "openworkspace-push-notifications";
28
-
29
34
  const pushSubscriptionSchema = z.object({
30
- endpoint: z.url().max(4_096).refine(
31
- (value) => new URL(value).protocol === "https:",
32
- "Push endpoint must use HTTPS",
33
- ),
35
+ endpoint: z
36
+ .url()
37
+ .max(4096)
38
+ .refine(
39
+ (value) => new URL(value).protocol === "https:",
40
+ "Push endpoint must use HTTPS"
41
+ ),
34
42
  keys: z.object({
35
- p256dh: z.string().min(1).max(512).refine((value) => {
36
- try {
37
- const key = urlBase64ToUint8Array(value);
38
- return key.length === 65 && key[0] === 4;
39
- } catch {
40
- return false;
41
- }
42
- }, "p256dh must be an uncompressed P-256 public key"),
43
- auth: z.string().min(1).max(512).refine((value) => {
44
- try {
45
- return urlBase64ToUint8Array(value).length >= 16;
46
- } catch {
47
- return false;
48
- }
49
- }, "auth must contain at least 16 bytes"),
43
+ p256dh: z
44
+ .string()
45
+ .min(1)
46
+ .max(512)
47
+ .refine((value) => {
48
+ try {
49
+ const key = urlBase64ToUint8Array(value);
50
+
51
+ return key.length === 65 && key[0] === 4;
52
+ } catch {
53
+ return false;
54
+ }
55
+ }, "p256dh must be an uncompressed P-256 public key"),
56
+ auth: z
57
+ .string()
58
+ .min(1)
59
+ .max(512)
60
+ .refine((value) => {
61
+ try {
62
+ return urlBase64ToUint8Array(value).length >= 16;
63
+ } catch {
64
+ return false;
65
+ }
66
+ }, "auth must contain at least 16 bytes"),
50
67
  }),
51
68
  });
52
69
 
53
70
  const subscriptionEndpointSchema = z.object({
54
- endpoint: z.string().url().max(4_096),
71
+ endpoint: z.string().url().max(4096),
55
72
  });
56
73
 
57
74
  const notificationPreferenceSchema = z.object({ enabled: z.boolean() });
@@ -80,7 +97,7 @@ const pushJobSchema = z.discriminatedUnion("type", [
80
97
  }),
81
98
  ]) satisfies z.ZodType<MailboxPushJob>;
82
99
 
83
- const MAX_PUSH_JOB_AGE_MS = 15 * 60 * 1_000;
100
+ const MAX_PUSH_JOB_AGE_MS = 15 * 60 * 1000;
84
101
  const MAX_QUEUE_SEND_BATCH_SIZE = 100;
85
102
 
86
103
  type PushConfiguration = {
@@ -102,55 +119,69 @@ let cachedPushConfiguration: {
102
119
  class RetryablePushError extends Error {
103
120
  constructor(
104
121
  readonly delaySeconds: number,
105
- cause: unknown,
122
+ cause: unknown
106
123
  ) {
107
124
  super("Push delivery should be retried", { cause });
108
125
  }
109
126
  }
110
127
 
111
- function retryDelaySeconds(error: unknown) {
128
+ function retryDelaySeconds(cause: unknown) {
112
129
  if (
113
- error instanceof WebPushError
114
- && error.statusCode !== 408
115
- && error.statusCode !== 429
116
- && error.statusCode < 500
130
+ cause instanceof WebPushError &&
131
+ cause.statusCode !== 408 &&
132
+ cause.statusCode !== 429 &&
133
+ cause.statusCode < 500
117
134
  ) {
118
135
  return null;
119
136
  }
120
- const timedOut = error instanceof DOMException
121
- && (error.name === "AbortError" || error.name === "TimeoutError");
137
+
138
+ const timedOut =
139
+ cause instanceof DOMException &&
140
+ (cause.name === "AbortError" || cause.name === "TimeoutError");
141
+
122
142
  if (
123
- !(error instanceof WebPushError)
124
- && !(error instanceof TypeError)
125
- && !timedOut
143
+ !(cause instanceof WebPushError) &&
144
+ !(cause instanceof TypeError) &&
145
+ !timedOut
126
146
  ) {
127
147
  return null;
128
148
  }
129
- const delayMs = error instanceof WebPushError
130
- ? error.retryAfterMs ?? 30_000
131
- : 30_000;
132
- return Math.max(1, Math.min(12 * 60 * 60, Math.ceil(delayMs / 1_000)));
149
+
150
+ const delayMs =
151
+ cause instanceof WebPushError ? (cause.retryAfterMs ?? 30_000) : 30_000;
152
+
153
+ return Math.max(1, Math.min(12 * 60 * 60, Math.ceil(delayMs / 1000)));
133
154
  }
134
155
 
135
- function pushFailureDetails(error: unknown) {
136
- if (error instanceof WebPushError) {
156
+ function pushFailureDetails(cause: unknown) {
157
+ if (cause instanceof WebPushError) {
137
158
  return {
138
- name: error.name,
139
- message: error.message,
140
- statusCode: error.statusCode,
141
- retryAfterMs: error.retryAfterMs,
159
+ name: cause.name,
160
+ message: cause.message,
161
+ statusCode: cause.statusCode,
162
+ retryAfterMs: cause.retryAfterMs,
142
163
  };
143
164
  }
144
- return error instanceof Error
145
- ? { name: error.name, message: error.message }
146
- : { message: String(error) };
165
+
166
+ return cause instanceof Error
167
+ ? { name: cause.name, message: cause.message }
168
+ : { message: String(cause) };
147
169
  }
148
170
 
149
- function pushConfiguration(env: PushBindings & { IDENTITY_PROVIDER_ORIGIN?: string }) {
171
+ /** The Web Push settings, as push code reads them. */
172
+ export type PushBindings = Pick<
173
+ Env,
174
+ "VAPID_PUBLIC_KEY" | "VAPID_PRIVATE_KEY" | "VAPID_SUBJECT"
175
+ >;
176
+
177
+ function pushConfiguration(
178
+ env: PushBindings & { IDENTITY_PROVIDER_ORIGIN: string }
179
+ ) {
150
180
  const publicKey = env.VAPID_PUBLIC_KEY;
151
181
  const privateKey = env.VAPID_PRIVATE_KEY;
152
182
  // Push services want a contact; the app's own URL is one.
153
183
  const subject = env.VAPID_SUBJECT ?? env.IDENTITY_PROVIDER_ORIGIN;
184
+
154
185
  if (!publicKey || !privateKey || !subject) {
155
186
  return Promise.resolve({
156
187
  configuration: null,
@@ -159,25 +190,36 @@ function pushConfiguration(env: PushBindings & { IDENTITY_PROVIDER_ORIGIN?: stri
159
190
  }
160
191
 
161
192
  const source = `${publicKey}\0${privateKey}\0${subject}`;
193
+
162
194
  if (cachedPushConfiguration?.source === source) {
163
195
  return cachedPushConfiguration.status;
164
196
  }
197
+
165
198
  const configuration = { publicKey, privateKey, subject };
199
+
166
200
  const status = createVapidJwt({
167
201
  audience: "https://push.invalid",
168
202
  expiration: 60,
169
203
  ...configuration,
170
- }).then(() => ({
171
- configuration,
172
- error: null,
173
- })).catch((error: unknown) => {
174
- console.error("Invalid Web Push configuration", pushFailureDetails(error));
175
- return {
176
- configuration: null,
177
- error: "Web Push server configuration is invalid.",
178
- };
179
- });
204
+ })
205
+ .then(() => ({
206
+ configuration,
207
+ error: null,
208
+ }))
209
+ .catch((cause: unknown) => {
210
+ console.error(
211
+ "Invalid Web Push configuration",
212
+ pushFailureDetails(cause)
213
+ );
214
+
215
+ return {
216
+ configuration: null,
217
+ error: "Web Push server configuration is invalid.",
218
+ };
219
+ });
220
+
180
221
  cachedPushConfiguration = { source, status };
222
+
181
223
  return status;
182
224
  }
183
225
 
@@ -185,6 +227,7 @@ export const pushNotificationRoutes = new Hono<AppEnv>()
185
227
  .use("*", requireSessionAuth)
186
228
  .get("/config", async (c) => {
187
229
  const status = await pushConfiguration(c.env);
230
+
188
231
  return c.json({
189
232
  ok: true as const,
190
233
  enabled: Boolean(status.configuration),
@@ -194,6 +237,7 @@ export const pushNotificationRoutes = new Hono<AppEnv>()
194
237
  })
195
238
  .get("/preferences", async (c) => {
196
239
  const userId = c.get("user").id;
240
+
197
241
  const rows = await createDb(c.env.DB)
198
242
  .select({
199
243
  mailboxId: mailboxes.id,
@@ -203,23 +247,26 @@ export const pushNotificationRoutes = new Hono<AppEnv>()
203
247
  })
204
248
  .from(mailboxAccess)
205
249
  .innerJoin(mailboxes, eq(mailboxAccess.mailboxId, mailboxes.id))
206
- .innerJoin(domains, eq(mailboxes.domainId, domains.id))
207
250
  .leftJoin(
208
251
  mailboxNotificationPreferences,
209
252
  and(
210
253
  eq(mailboxNotificationPreferences.mailboxId, mailboxAccess.mailboxId),
211
- eq(mailboxNotificationPreferences.userId, mailboxAccess.userId),
212
- ),
254
+ eq(mailboxNotificationPreferences.userId, mailboxAccess.userId)
255
+ )
213
256
  )
214
257
  .where(eq(mailboxAccess.userId, userId))
215
258
  .orderBy(
216
259
  mailboxKindOrderSql,
217
260
  desc(mailboxes.isPrimary),
218
- mailboxes.displayName,
261
+ mailboxes.displayName
219
262
  );
263
+
220
264
  return c.json({
221
265
  ok: true as const,
222
- preferences: rows.map((row) => ({ ...row, enabled: row.enabled ?? true })),
266
+ preferences: rows.map((row) => ({
267
+ ...row,
268
+ enabled: row.enabled ?? true,
269
+ })),
223
270
  });
224
271
  })
225
272
  .put(
@@ -228,13 +275,20 @@ export const pushNotificationRoutes = new Hono<AppEnv>()
228
275
  async (c) => {
229
276
  const userId = c.get("user").id;
230
277
  const mailboxId = c.req.param("mailboxId");
231
- if (!await getMailboxAccess(createDb(c.env.DB), userId, mailboxId)) {
278
+
279
+ if (!(await getMailboxAccess(createDb(c.env.DB), userId, mailboxId))) {
232
280
  return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
233
281
  }
282
+
234
283
  const now = new Date();
235
284
  await createDb(c.env.DB)
236
285
  .insert(mailboxNotificationPreferences)
237
- .values({ mailboxId, userId, enabled: c.req.valid("json").enabled, updatedAt: now })
286
+ .values({
287
+ mailboxId,
288
+ userId,
289
+ enabled: c.req.valid("json").enabled,
290
+ updatedAt: now,
291
+ })
238
292
  .onConflictDoUpdate({
239
293
  target: [
240
294
  mailboxNotificationPreferences.mailboxId,
@@ -242,8 +296,9 @@ export const pushNotificationRoutes = new Hono<AppEnv>()
242
296
  ],
243
297
  set: { enabled: c.req.valid("json").enabled, updatedAt: now },
244
298
  });
299
+
245
300
  return c.json({ ok: true as const });
246
- },
301
+ }
247
302
  )
248
303
  .put(
249
304
  "/subscriptions",
@@ -271,8 +326,9 @@ export const pushNotificationRoutes = new Hono<AppEnv>()
271
326
  updatedAt: now,
272
327
  },
273
328
  });
329
+
274
330
  return c.json({ ok: true as const });
275
- },
331
+ }
276
332
  )
277
333
  .delete(
278
334
  "/subscriptions",
@@ -280,60 +336,77 @@ export const pushNotificationRoutes = new Hono<AppEnv>()
280
336
  async (c) => {
281
337
  await createDb(c.env.DB)
282
338
  .delete(pushSubscriptions)
283
- .where(and(
284
- eq(pushSubscriptions.userId, c.get("user").id),
285
- eq(pushSubscriptions.endpoint, c.req.valid("json").endpoint),
286
- ));
339
+ .where(
340
+ and(
341
+ eq(pushSubscriptions.userId, c.get("user").id),
342
+ eq(pushSubscriptions.endpoint, c.req.valid("json").endpoint)
343
+ )
344
+ );
345
+
287
346
  return c.json({ ok: true as const });
288
- },
347
+ }
289
348
  );
290
349
 
291
- async function subscriptionsForMailbox(
292
- env: Env & PushBindings,
293
- mailboxId: string,
350
+ /** A person's sessions were all revoked: no device of theirs gets notifications. */
351
+ export async function deleteUserPushSubscriptions(
352
+ db: Database,
353
+ userId: string
294
354
  ) {
355
+ await db
356
+ .delete(pushSubscriptions)
357
+ .where(eq(pushSubscriptions.userId, userId));
358
+ }
359
+
360
+ function subscriptionsForMailbox(env: Env, mailboxId: string) {
295
361
  const db = createDb(env.DB);
296
- return db.select({
297
- id: pushSubscriptions.id,
298
- })
362
+
363
+ return db
364
+ .select({
365
+ id: pushSubscriptions.id,
366
+ })
299
367
  .from(pushSubscriptions)
300
368
  .innerJoin(users, eq(pushSubscriptions.userId, users.id))
301
369
  .innerJoin(
302
370
  mailboxAccess,
303
371
  and(
304
372
  eq(mailboxAccess.userId, pushSubscriptions.userId),
305
- eq(mailboxAccess.mailboxId, mailboxId),
306
- ),
373
+ eq(mailboxAccess.mailboxId, mailboxId)
374
+ )
307
375
  )
308
376
  .leftJoin(
309
377
  mailboxNotificationPreferences,
310
378
  and(
311
379
  eq(mailboxNotificationPreferences.userId, pushSubscriptions.userId),
312
- eq(mailboxNotificationPreferences.mailboxId, mailboxId),
313
- ),
380
+ eq(mailboxNotificationPreferences.mailboxId, mailboxId)
381
+ )
314
382
  )
315
- .where(and(
316
- eq(users.status, "active"),
317
- or(
318
- isNull(mailboxNotificationPreferences.enabled),
319
- eq(mailboxNotificationPreferences.enabled, true),
320
- ),
321
- ));
383
+ .where(
384
+ and(
385
+ eq(users.status, "active"),
386
+ or(
387
+ isNull(mailboxNotificationPreferences.enabled),
388
+ eq(mailboxNotificationPreferences.enabled, true)
389
+ )
390
+ )
391
+ );
322
392
  }
323
393
 
324
394
  async function dispatchPushJob(
325
- env: Env & PushBindings,
326
- job: Extract<MailboxPushJob, { type: "dispatch" }>,
395
+ env: Env,
396
+ job: Extract<MailboxPushJob, { type: "dispatch" }>
327
397
  ) {
328
398
  const db = createDb(env.DB);
399
+
329
400
  const [mailbox, subscriptions] = await Promise.all([
330
- db.select({ displayName: mailboxes.displayName })
401
+ db
402
+ .select({ displayName: mailboxes.displayName })
331
403
  .from(mailboxes)
332
404
  .where(eq(mailboxes.id, job.mailboxId))
333
405
  .limit(1)
334
406
  .then((rows) => rows[0]),
335
407
  subscriptionsForMailbox(env, job.mailboxId),
336
408
  ]);
409
+
337
410
  if (!mailbox || !subscriptions.length) return;
338
411
 
339
412
  const requests: MessageSendRequest<MailboxPushJob>[] = subscriptions.map(
@@ -344,58 +417,68 @@ async function dispatchPushJob(
344
417
  targetSubscriptionId: subscription.id,
345
418
  mailboxDisplayName: mailbox.displayName,
346
419
  },
347
- }),
420
+ })
348
421
  );
349
- for (let index = 0; index < requests.length; index += MAX_QUEUE_SEND_BATCH_SIZE) {
350
- await env.PUSH_NOTIFICATIONS.sendBatch(
351
- requests.slice(index, index + MAX_QUEUE_SEND_BATCH_SIZE),
352
- );
422
+
423
+ const batches: MessageSendRequest<MailboxPushJob>[][] = [];
424
+
425
+ for (
426
+ let index = 0;
427
+ index < requests.length;
428
+ index += MAX_QUEUE_SEND_BATCH_SIZE
429
+ ) {
430
+ batches.push(requests.slice(index, index + MAX_QUEUE_SEND_BATCH_SIZE));
353
431
  }
432
+
433
+ // Each subscription's delivery is its own job, so the batches are independent.
434
+ await Promise.all(
435
+ batches.map((batch) => env.PUSH_NOTIFICATIONS.sendBatch(batch))
436
+ );
354
437
  }
355
438
 
356
- async function targetSubscription(
357
- env: Env & PushBindings,
358
- job: Extract<MailboxPushJob, { type: "deliver" }>,
439
+ function targetSubscription(
440
+ env: Env,
441
+ job: Extract<MailboxPushJob, { type: "deliver" }>
359
442
  ) {
360
- return createDb(env.DB).select({
361
- id: pushSubscriptions.id,
362
- userId: pushSubscriptions.userId,
363
- endpoint: pushSubscriptions.endpoint,
364
- p256dh: pushSubscriptions.p256dh,
365
- auth: pushSubscriptions.auth,
366
- })
443
+ return createDb(env.DB)
444
+ .select({
445
+ id: pushSubscriptions.id,
446
+ userId: pushSubscriptions.userId,
447
+ endpoint: pushSubscriptions.endpoint,
448
+ p256dh: pushSubscriptions.p256dh,
449
+ auth: pushSubscriptions.auth,
450
+ })
367
451
  .from(pushSubscriptions)
368
452
  .innerJoin(users, eq(pushSubscriptions.userId, users.id))
369
453
  .innerJoin(
370
454
  mailboxAccess,
371
455
  and(
372
456
  eq(mailboxAccess.userId, pushSubscriptions.userId),
373
- eq(mailboxAccess.mailboxId, job.mailboxId),
374
- ),
457
+ eq(mailboxAccess.mailboxId, job.mailboxId)
458
+ )
375
459
  )
376
460
  .leftJoin(
377
461
  mailboxNotificationPreferences,
378
462
  and(
379
463
  eq(mailboxNotificationPreferences.userId, pushSubscriptions.userId),
380
- eq(mailboxNotificationPreferences.mailboxId, job.mailboxId),
381
- ),
464
+ eq(mailboxNotificationPreferences.mailboxId, job.mailboxId)
465
+ )
466
+ )
467
+ .where(
468
+ and(
469
+ eq(users.status, "active"),
470
+ or(
471
+ isNull(mailboxNotificationPreferences.enabled),
472
+ eq(mailboxNotificationPreferences.enabled, true)
473
+ ),
474
+ eq(pushSubscriptions.id, job.targetSubscriptionId)
475
+ )
382
476
  )
383
- .where(and(
384
- eq(users.status, "active"),
385
- or(
386
- isNull(mailboxNotificationPreferences.enabled),
387
- eq(mailboxNotificationPreferences.enabled, true),
388
- ),
389
- eq(pushSubscriptions.id, job.targetSubscriptionId),
390
- ))
391
477
  .limit(1)
392
478
  .then((rows) => rows[0]);
393
479
  }
394
480
 
395
- async function removeSubscription(
396
- env: Env & PushBindings,
397
- subscriptionId: string,
398
- ) {
481
+ async function removeSubscription(env: Env, subscriptionId: string) {
399
482
  try {
400
483
  await createDb(env.DB)
401
484
  .delete(pushSubscriptions)
@@ -406,17 +489,20 @@ async function removeSubscription(
406
489
  }
407
490
 
408
491
  async function deliverPushJob(
409
- env: Env & PushBindings,
492
+ env: Env,
410
493
  job: Extract<MailboxPushJob, { type: "deliver" }>,
411
494
  configuration: PushConfiguration,
412
- ageMs: number,
495
+ ageMs: number
413
496
  ) {
414
497
  const subscription = await targetSubscription(env, job);
498
+
415
499
  if (!subscription) return;
500
+
416
501
  const suppressed = await mailboxStub(env, job.mailboxId).shouldSuppressPush(
417
502
  job.messageId,
418
- subscription.userId,
503
+ subscription.userId
419
504
  );
505
+
420
506
  if (suppressed) return;
421
507
 
422
508
  try {
@@ -428,71 +514,83 @@ async function deliverPushJob(
428
514
  {
429
515
  title: `New email in ${job.mailboxDisplayName}`,
430
516
  body: `${job.sender} · ${job.subject || "(no subject)"}`,
431
- url: `/mail/${encodeURIComponent(job.mailboxId)}?folder=inbox&conversation=${encodeURIComponent(job.conversationId)}`,
517
+ url: mailPath(job.mailboxId, "inbox", job.conversationId),
432
518
  tag: `message-${job.messageId}`,
433
519
  },
434
520
  configuration,
435
521
  {
436
- ttl: Math.max(1, Math.ceil((MAX_PUSH_JOB_AGE_MS - ageMs) / 1_000)),
522
+ ttl: Math.max(1, Math.ceil((MAX_PUSH_JOB_AGE_MS - ageMs) / 1000)),
437
523
  urgency: "high",
438
524
  topic: await topicFromString(`message:${job.messageId}`),
439
- },
525
+ }
440
526
  );
527
+
441
528
  if (!delivered) await removeSubscription(env, subscription.id);
442
529
  } catch (error) {
443
530
  const delaySeconds = retryDelaySeconds(error);
531
+
444
532
  if (delaySeconds === null) {
445
533
  console.error(
446
534
  "Push notification delivery was rejected",
447
- pushFailureDetails(error),
535
+ pushFailureDetails(error)
448
536
  );
537
+
449
538
  return;
450
539
  }
540
+
451
541
  throw new RetryablePushError(delaySeconds, error);
452
542
  }
453
543
  }
454
544
 
455
545
  /** The server's VAPID identity, or null when push is not configured. */
456
- export async function vapidConfiguration(env: Env & PushBindings) {
546
+ export async function vapidConfiguration(env: Env) {
457
547
  return (await pushConfiguration(env)).configuration;
458
548
  }
459
549
 
460
- async function processPushJob(env: Env & PushBindings, job: MailboxPushJob) {
550
+ async function processPushJob(env: Env, job: MailboxPushJob) {
461
551
  const ageMs = Math.max(0, Date.now() - job.occurredAt);
552
+
462
553
  if (ageMs >= MAX_PUSH_JOB_AGE_MS) return;
463
- const configuration = (await pushConfiguration(env)).configuration;
554
+ const { configuration } = await pushConfiguration(env);
555
+
464
556
  if (!configuration) return;
465
- if (job.type === "jmap-state") await deliverJmapStateChange(env, job, configuration);
466
- else if (job.type === "dispatch") await dispatchPushJob(env, job);
557
+
558
+ if (job.type === "jmap-state") {
559
+ await deliverJmapStateChange(env, job, configuration);
560
+ } else if (job.type === "dispatch") await dispatchPushJob(env, job);
467
561
  else await deliverPushJob(env, job, configuration, ageMs);
468
562
  }
469
563
 
470
564
  export async function consumePushNotifications(
471
565
  batch: MessageBatch<unknown>,
472
- env: Env & PushBindings,
566
+ env: Env
473
567
  ) {
474
- await Promise.all(batch.messages.map(async (message) => {
475
- const parsed = pushJobSchema.safeParse(message.body);
476
- if (!parsed.success) {
477
- console.error("Ignoring invalid push notification job", parsed.error);
478
- message.ack();
479
- return;
480
- }
481
- try {
482
- await processPushJob(env, parsed.data);
483
- message.ack();
484
- } catch (error) {
485
- console.error(
486
- "Could not deliver push notification job",
487
- pushFailureDetails(
488
- error instanceof RetryablePushError ? error.cause : error,
489
- ),
490
- );
491
- message.retry({
492
- delaySeconds: error instanceof RetryablePushError
493
- ? error.delaySeconds
494
- : 30,
495
- });
496
- }
497
- }));
568
+ await Promise.all(
569
+ batch.messages.map(async (message) => {
570
+ const parsed = pushJobSchema.safeParse(message.body);
571
+
572
+ if (!parsed.success) {
573
+ console.error("Ignoring invalid push notification job", parsed.error);
574
+ message.ack();
575
+
576
+ return;
577
+ }
578
+
579
+ try {
580
+ await processPushJob(env, parsed.data);
581
+ message.ack();
582
+ } catch (error) {
583
+ console.error(
584
+ "Could not deliver push notification job",
585
+ pushFailureDetails(
586
+ error instanceof RetryablePushError ? error.cause : error
587
+ )
588
+ );
589
+ message.retry({
590
+ delaySeconds:
591
+ error instanceof RetryablePushError ? error.delaySeconds : 30,
592
+ });
593
+ }
594
+ })
595
+ );
498
596
  }