@open-workspace/email 0.2.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 (223) hide show
  1. package/README.md +23 -20
  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_dry_moon_knight.sql +77 -0
  11. package/migrations/meta/0000_snapshot.json +248 -106
  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 +78 -26
  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 +90 -34
  127. package/worker/jmap/eventsource.ts +169 -0
  128. package/worker/jmap/methods.ts +1716 -361
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +207 -0
  131. package/worker/jmap/routes.ts +448 -86
  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 +84 -52
  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 +283 -171
  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 +871 -542
  184. package/worker/mail/safety-routes.ts +329 -202
  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 +153 -91
  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 +597 -227
  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 +1761 -737
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +7 -14
  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 -126
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/migrations/0000_email.sql +0 -53
  218. package/shared/mail-rules.ts +0 -156
  219. package/worker/admin/report-routes.ts +0 -164
  220. package/worker/mail/reported-messages.ts +0 -68
  221. package/worker/mailbox/legacy-migrations.ts +0 -41
  222. package/worker/mailbox/migrations.ts +0 -10
  223. package/worker/mailbox/rules.ts +0 -110
@@ -3,54 +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";
25
+ import { mailPath } from "../../shared/mail-path";
26
+ import {
27
+ mailboxNotificationPreferences,
28
+ pushSubscriptions,
29
+ } from "../db/schema";
30
+ import { deliverJmapStateChange } from "../jmap/push";
23
31
  import { mailboxStub } from "../mailbox";
24
32
  import { getMailboxAccess } from "./access";
25
33
 
26
- export const PUSH_NOTIFICATION_QUEUE = "openworkspace-push-notifications";
27
-
28
34
  const pushSubscriptionSchema = z.object({
29
- endpoint: z.url().max(4_096).refine(
30
- (value) => new URL(value).protocol === "https:",
31
- "Push endpoint must use HTTPS",
32
- ),
35
+ endpoint: z
36
+ .url()
37
+ .max(4096)
38
+ .refine(
39
+ (value) => new URL(value).protocol === "https:",
40
+ "Push endpoint must use HTTPS"
41
+ ),
33
42
  keys: z.object({
34
- p256dh: z.string().min(1).max(512).refine((value) => {
35
- try {
36
- const key = urlBase64ToUint8Array(value);
37
- return key.length === 65 && key[0] === 4;
38
- } catch {
39
- return false;
40
- }
41
- }, "p256dh must be an uncompressed P-256 public key"),
42
- auth: z.string().min(1).max(512).refine((value) => {
43
- try {
44
- return urlBase64ToUint8Array(value).length >= 16;
45
- } catch {
46
- return false;
47
- }
48
- }, "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"),
49
67
  }),
50
68
  });
51
69
 
52
70
  const subscriptionEndpointSchema = z.object({
53
- endpoint: z.string().url().max(4_096),
71
+ endpoint: z.string().url().max(4096),
54
72
  });
55
73
 
56
74
  const notificationPreferenceSchema = z.object({ enabled: z.boolean() });
@@ -65,6 +83,12 @@ const pushJobBaseSchema = z.object({
65
83
  });
66
84
 
67
85
  const pushJobSchema = z.discriminatedUnion("type", [
86
+ z.object({
87
+ type: z.literal("jmap-state"),
88
+ mailboxId: z.string().min(1),
89
+ state: z.string().min(1).max(100),
90
+ occurredAt: z.number().int().nonnegative(),
91
+ }),
68
92
  pushJobBaseSchema.extend({ type: z.literal("dispatch") }),
69
93
  pushJobBaseSchema.extend({
70
94
  type: z.literal("deliver"),
@@ -73,7 +97,7 @@ const pushJobSchema = z.discriminatedUnion("type", [
73
97
  }),
74
98
  ]) satisfies z.ZodType<MailboxPushJob>;
75
99
 
76
- const MAX_PUSH_JOB_AGE_MS = 15 * 60 * 1_000;
100
+ const MAX_PUSH_JOB_AGE_MS = 15 * 60 * 1000;
77
101
  const MAX_QUEUE_SEND_BATCH_SIZE = 100;
78
102
 
79
103
  type PushConfiguration = {
@@ -95,54 +119,69 @@ let cachedPushConfiguration: {
95
119
  class RetryablePushError extends Error {
96
120
  constructor(
97
121
  readonly delaySeconds: number,
98
- cause: unknown,
122
+ cause: unknown
99
123
  ) {
100
124
  super("Push delivery should be retried", { cause });
101
125
  }
102
126
  }
103
127
 
104
- function retryDelaySeconds(error: unknown) {
128
+ function retryDelaySeconds(cause: unknown) {
105
129
  if (
106
- error instanceof WebPushError
107
- && error.statusCode !== 408
108
- && error.statusCode !== 429
109
- && error.statusCode < 500
130
+ cause instanceof WebPushError &&
131
+ cause.statusCode !== 408 &&
132
+ cause.statusCode !== 429 &&
133
+ cause.statusCode < 500
110
134
  ) {
111
135
  return null;
112
136
  }
113
- const timedOut = error instanceof DOMException
114
- && (error.name === "AbortError" || error.name === "TimeoutError");
137
+
138
+ const timedOut =
139
+ cause instanceof DOMException &&
140
+ (cause.name === "AbortError" || cause.name === "TimeoutError");
141
+
115
142
  if (
116
- !(error instanceof WebPushError)
117
- && !(error instanceof TypeError)
118
- && !timedOut
143
+ !(cause instanceof WebPushError) &&
144
+ !(cause instanceof TypeError) &&
145
+ !timedOut
119
146
  ) {
120
147
  return null;
121
148
  }
122
- const delayMs = error instanceof WebPushError
123
- ? error.retryAfterMs ?? 30_000
124
- : 30_000;
125
- 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)));
126
154
  }
127
155
 
128
- function pushFailureDetails(error: unknown) {
129
- if (error instanceof WebPushError) {
156
+ function pushFailureDetails(cause: unknown) {
157
+ if (cause instanceof WebPushError) {
130
158
  return {
131
- name: error.name,
132
- message: error.message,
133
- statusCode: error.statusCode,
134
- retryAfterMs: error.retryAfterMs,
159
+ name: cause.name,
160
+ message: cause.message,
161
+ statusCode: cause.statusCode,
162
+ retryAfterMs: cause.retryAfterMs,
135
163
  };
136
164
  }
137
- return error instanceof Error
138
- ? { name: error.name, message: error.message }
139
- : { message: String(error) };
165
+
166
+ return cause instanceof Error
167
+ ? { name: cause.name, message: cause.message }
168
+ : { message: String(cause) };
140
169
  }
141
170
 
142
- function pushConfiguration(env: PushBindings) {
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
+ ) {
143
180
  const publicKey = env.VAPID_PUBLIC_KEY;
144
181
  const privateKey = env.VAPID_PRIVATE_KEY;
145
- const subject = env.VAPID_SUBJECT;
182
+ // Push services want a contact; the app's own URL is one.
183
+ const subject = env.VAPID_SUBJECT ?? env.IDENTITY_PROVIDER_ORIGIN;
184
+
146
185
  if (!publicKey || !privateKey || !subject) {
147
186
  return Promise.resolve({
148
187
  configuration: null,
@@ -151,25 +190,36 @@ function pushConfiguration(env: PushBindings) {
151
190
  }
152
191
 
153
192
  const source = `${publicKey}\0${privateKey}\0${subject}`;
193
+
154
194
  if (cachedPushConfiguration?.source === source) {
155
195
  return cachedPushConfiguration.status;
156
196
  }
197
+
157
198
  const configuration = { publicKey, privateKey, subject };
199
+
158
200
  const status = createVapidJwt({
159
201
  audience: "https://push.invalid",
160
202
  expiration: 60,
161
203
  ...configuration,
162
- }).then(() => ({
163
- configuration,
164
- error: null,
165
- })).catch((error: unknown) => {
166
- console.error("Invalid Web Push configuration", pushFailureDetails(error));
167
- return {
168
- configuration: null,
169
- error: "Web Push server configuration is invalid.",
170
- };
171
- });
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
+
172
221
  cachedPushConfiguration = { source, status };
222
+
173
223
  return status;
174
224
  }
175
225
 
@@ -177,6 +227,7 @@ export const pushNotificationRoutes = new Hono<AppEnv>()
177
227
  .use("*", requireSessionAuth)
178
228
  .get("/config", async (c) => {
179
229
  const status = await pushConfiguration(c.env);
230
+
180
231
  return c.json({
181
232
  ok: true as const,
182
233
  enabled: Boolean(status.configuration),
@@ -186,6 +237,7 @@ export const pushNotificationRoutes = new Hono<AppEnv>()
186
237
  })
187
238
  .get("/preferences", async (c) => {
188
239
  const userId = c.get("user").id;
240
+
189
241
  const rows = await createDb(c.env.DB)
190
242
  .select({
191
243
  mailboxId: mailboxes.id,
@@ -195,23 +247,26 @@ export const pushNotificationRoutes = new Hono<AppEnv>()
195
247
  })
196
248
  .from(mailboxAccess)
197
249
  .innerJoin(mailboxes, eq(mailboxAccess.mailboxId, mailboxes.id))
198
- .innerJoin(domains, eq(mailboxes.domainId, domains.id))
199
250
  .leftJoin(
200
251
  mailboxNotificationPreferences,
201
252
  and(
202
253
  eq(mailboxNotificationPreferences.mailboxId, mailboxAccess.mailboxId),
203
- eq(mailboxNotificationPreferences.userId, mailboxAccess.userId),
204
- ),
254
+ eq(mailboxNotificationPreferences.userId, mailboxAccess.userId)
255
+ )
205
256
  )
206
257
  .where(eq(mailboxAccess.userId, userId))
207
258
  .orderBy(
208
259
  mailboxKindOrderSql,
209
260
  desc(mailboxes.isPrimary),
210
- mailboxes.displayName,
261
+ mailboxes.displayName
211
262
  );
263
+
212
264
  return c.json({
213
265
  ok: true as const,
214
- preferences: rows.map((row) => ({ ...row, enabled: row.enabled ?? true })),
266
+ preferences: rows.map((row) => ({
267
+ ...row,
268
+ enabled: row.enabled ?? true,
269
+ })),
215
270
  });
216
271
  })
217
272
  .put(
@@ -220,13 +275,20 @@ export const pushNotificationRoutes = new Hono<AppEnv>()
220
275
  async (c) => {
221
276
  const userId = c.get("user").id;
222
277
  const mailboxId = c.req.param("mailboxId");
223
- if (!await getMailboxAccess(createDb(c.env.DB), userId, mailboxId)) {
278
+
279
+ if (!(await getMailboxAccess(createDb(c.env.DB), userId, mailboxId))) {
224
280
  return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
225
281
  }
282
+
226
283
  const now = new Date();
227
284
  await createDb(c.env.DB)
228
285
  .insert(mailboxNotificationPreferences)
229
- .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
+ })
230
292
  .onConflictDoUpdate({
231
293
  target: [
232
294
  mailboxNotificationPreferences.mailboxId,
@@ -234,8 +296,9 @@ export const pushNotificationRoutes = new Hono<AppEnv>()
234
296
  ],
235
297
  set: { enabled: c.req.valid("json").enabled, updatedAt: now },
236
298
  });
299
+
237
300
  return c.json({ ok: true as const });
238
- },
301
+ }
239
302
  )
240
303
  .put(
241
304
  "/subscriptions",
@@ -263,8 +326,9 @@ export const pushNotificationRoutes = new Hono<AppEnv>()
263
326
  updatedAt: now,
264
327
  },
265
328
  });
329
+
266
330
  return c.json({ ok: true as const });
267
- },
331
+ }
268
332
  )
269
333
  .delete(
270
334
  "/subscriptions",
@@ -272,60 +336,77 @@ export const pushNotificationRoutes = new Hono<AppEnv>()
272
336
  async (c) => {
273
337
  await createDb(c.env.DB)
274
338
  .delete(pushSubscriptions)
275
- .where(and(
276
- eq(pushSubscriptions.userId, c.get("user").id),
277
- eq(pushSubscriptions.endpoint, c.req.valid("json").endpoint),
278
- ));
339
+ .where(
340
+ and(
341
+ eq(pushSubscriptions.userId, c.get("user").id),
342
+ eq(pushSubscriptions.endpoint, c.req.valid("json").endpoint)
343
+ )
344
+ );
345
+
279
346
  return c.json({ ok: true as const });
280
- },
347
+ }
281
348
  );
282
349
 
283
- async function subscriptionsForMailbox(
284
- env: Env & PushBindings,
285
- 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
286
354
  ) {
355
+ await db
356
+ .delete(pushSubscriptions)
357
+ .where(eq(pushSubscriptions.userId, userId));
358
+ }
359
+
360
+ function subscriptionsForMailbox(env: Env, mailboxId: string) {
287
361
  const db = createDb(env.DB);
288
- return db.select({
289
- id: pushSubscriptions.id,
290
- })
362
+
363
+ return db
364
+ .select({
365
+ id: pushSubscriptions.id,
366
+ })
291
367
  .from(pushSubscriptions)
292
368
  .innerJoin(users, eq(pushSubscriptions.userId, users.id))
293
369
  .innerJoin(
294
370
  mailboxAccess,
295
371
  and(
296
372
  eq(mailboxAccess.userId, pushSubscriptions.userId),
297
- eq(mailboxAccess.mailboxId, mailboxId),
298
- ),
373
+ eq(mailboxAccess.mailboxId, mailboxId)
374
+ )
299
375
  )
300
376
  .leftJoin(
301
377
  mailboxNotificationPreferences,
302
378
  and(
303
379
  eq(mailboxNotificationPreferences.userId, pushSubscriptions.userId),
304
- eq(mailboxNotificationPreferences.mailboxId, mailboxId),
305
- ),
380
+ eq(mailboxNotificationPreferences.mailboxId, mailboxId)
381
+ )
306
382
  )
307
- .where(and(
308
- eq(users.status, "active"),
309
- or(
310
- isNull(mailboxNotificationPreferences.enabled),
311
- eq(mailboxNotificationPreferences.enabled, true),
312
- ),
313
- ));
383
+ .where(
384
+ and(
385
+ eq(users.status, "active"),
386
+ or(
387
+ isNull(mailboxNotificationPreferences.enabled),
388
+ eq(mailboxNotificationPreferences.enabled, true)
389
+ )
390
+ )
391
+ );
314
392
  }
315
393
 
316
394
  async function dispatchPushJob(
317
- env: Env & PushBindings,
318
- job: Extract<MailboxPushJob, { type: "dispatch" }>,
395
+ env: Env,
396
+ job: Extract<MailboxPushJob, { type: "dispatch" }>
319
397
  ) {
320
398
  const db = createDb(env.DB);
399
+
321
400
  const [mailbox, subscriptions] = await Promise.all([
322
- db.select({ displayName: mailboxes.displayName })
401
+ db
402
+ .select({ displayName: mailboxes.displayName })
323
403
  .from(mailboxes)
324
404
  .where(eq(mailboxes.id, job.mailboxId))
325
405
  .limit(1)
326
406
  .then((rows) => rows[0]),
327
407
  subscriptionsForMailbox(env, job.mailboxId),
328
408
  ]);
409
+
329
410
  if (!mailbox || !subscriptions.length) return;
330
411
 
331
412
  const requests: MessageSendRequest<MailboxPushJob>[] = subscriptions.map(
@@ -336,58 +417,68 @@ async function dispatchPushJob(
336
417
  targetSubscriptionId: subscription.id,
337
418
  mailboxDisplayName: mailbox.displayName,
338
419
  },
339
- }),
420
+ })
340
421
  );
341
- for (let index = 0; index < requests.length; index += MAX_QUEUE_SEND_BATCH_SIZE) {
342
- await env.PUSH_NOTIFICATIONS.sendBatch(
343
- requests.slice(index, index + MAX_QUEUE_SEND_BATCH_SIZE),
344
- );
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));
345
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
+ );
346
437
  }
347
438
 
348
- async function targetSubscription(
349
- env: Env & PushBindings,
350
- job: Extract<MailboxPushJob, { type: "deliver" }>,
439
+ function targetSubscription(
440
+ env: Env,
441
+ job: Extract<MailboxPushJob, { type: "deliver" }>
351
442
  ) {
352
- return createDb(env.DB).select({
353
- id: pushSubscriptions.id,
354
- userId: pushSubscriptions.userId,
355
- endpoint: pushSubscriptions.endpoint,
356
- p256dh: pushSubscriptions.p256dh,
357
- auth: pushSubscriptions.auth,
358
- })
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
+ })
359
451
  .from(pushSubscriptions)
360
452
  .innerJoin(users, eq(pushSubscriptions.userId, users.id))
361
453
  .innerJoin(
362
454
  mailboxAccess,
363
455
  and(
364
456
  eq(mailboxAccess.userId, pushSubscriptions.userId),
365
- eq(mailboxAccess.mailboxId, job.mailboxId),
366
- ),
457
+ eq(mailboxAccess.mailboxId, job.mailboxId)
458
+ )
367
459
  )
368
460
  .leftJoin(
369
461
  mailboxNotificationPreferences,
370
462
  and(
371
463
  eq(mailboxNotificationPreferences.userId, pushSubscriptions.userId),
372
- eq(mailboxNotificationPreferences.mailboxId, job.mailboxId),
373
- ),
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
+ )
374
476
  )
375
- .where(and(
376
- eq(users.status, "active"),
377
- or(
378
- isNull(mailboxNotificationPreferences.enabled),
379
- eq(mailboxNotificationPreferences.enabled, true),
380
- ),
381
- eq(pushSubscriptions.id, job.targetSubscriptionId),
382
- ))
383
477
  .limit(1)
384
478
  .then((rows) => rows[0]);
385
479
  }
386
480
 
387
- async function removeSubscription(
388
- env: Env & PushBindings,
389
- subscriptionId: string,
390
- ) {
481
+ async function removeSubscription(env: Env, subscriptionId: string) {
391
482
  try {
392
483
  await createDb(env.DB)
393
484
  .delete(pushSubscriptions)
@@ -398,17 +489,20 @@ async function removeSubscription(
398
489
  }
399
490
 
400
491
  async function deliverPushJob(
401
- env: Env & PushBindings,
492
+ env: Env,
402
493
  job: Extract<MailboxPushJob, { type: "deliver" }>,
403
494
  configuration: PushConfiguration,
404
- ageMs: number,
495
+ ageMs: number
405
496
  ) {
406
497
  const subscription = await targetSubscription(env, job);
498
+
407
499
  if (!subscription) return;
500
+
408
501
  const suppressed = await mailboxStub(env, job.mailboxId).shouldSuppressPush(
409
502
  job.messageId,
410
- subscription.userId,
503
+ subscription.userId
411
504
  );
505
+
412
506
  if (suppressed) return;
413
507
 
414
508
  try {
@@ -420,65 +514,83 @@ async function deliverPushJob(
420
514
  {
421
515
  title: `New email in ${job.mailboxDisplayName}`,
422
516
  body: `${job.sender} · ${job.subject || "(no subject)"}`,
423
- url: `/mail/${encodeURIComponent(job.mailboxId)}?folder=inbox&conversation=${encodeURIComponent(job.conversationId)}`,
517
+ url: mailPath(job.mailboxId, "inbox", job.conversationId),
424
518
  tag: `message-${job.messageId}`,
425
519
  },
426
520
  configuration,
427
521
  {
428
- 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)),
429
523
  urgency: "high",
430
524
  topic: await topicFromString(`message:${job.messageId}`),
431
- },
525
+ }
432
526
  );
527
+
433
528
  if (!delivered) await removeSubscription(env, subscription.id);
434
529
  } catch (error) {
435
530
  const delaySeconds = retryDelaySeconds(error);
531
+
436
532
  if (delaySeconds === null) {
437
533
  console.error(
438
534
  "Push notification delivery was rejected",
439
- pushFailureDetails(error),
535
+ pushFailureDetails(error)
440
536
  );
537
+
441
538
  return;
442
539
  }
540
+
443
541
  throw new RetryablePushError(delaySeconds, error);
444
542
  }
445
543
  }
446
544
 
447
- async function processPushJob(env: Env & PushBindings, job: MailboxPushJob) {
545
+ /** The server's VAPID identity, or null when push is not configured. */
546
+ export async function vapidConfiguration(env: Env) {
547
+ return (await pushConfiguration(env)).configuration;
548
+ }
549
+
550
+ async function processPushJob(env: Env, job: MailboxPushJob) {
448
551
  const ageMs = Math.max(0, Date.now() - job.occurredAt);
552
+
449
553
  if (ageMs >= MAX_PUSH_JOB_AGE_MS) return;
450
- const configuration = (await pushConfiguration(env)).configuration;
554
+ const { configuration } = await pushConfiguration(env);
555
+
451
556
  if (!configuration) return;
452
- 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);
453
561
  else await deliverPushJob(env, job, configuration, ageMs);
454
562
  }
455
563
 
456
564
  export async function consumePushNotifications(
457
565
  batch: MessageBatch<unknown>,
458
- env: Env & PushBindings,
566
+ env: Env
459
567
  ) {
460
- await Promise.all(batch.messages.map(async (message) => {
461
- const parsed = pushJobSchema.safeParse(message.body);
462
- if (!parsed.success) {
463
- console.error("Ignoring invalid push notification job", parsed.error);
464
- message.ack();
465
- return;
466
- }
467
- try {
468
- await processPushJob(env, parsed.data);
469
- message.ack();
470
- } catch (error) {
471
- console.error(
472
- "Could not deliver push notification job",
473
- pushFailureDetails(
474
- error instanceof RetryablePushError ? error.cause : error,
475
- ),
476
- );
477
- message.retry({
478
- delaySeconds: error instanceof RetryablePushError
479
- ? error.delaySeconds
480
- : 30,
481
- });
482
- }
483
- }));
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
+ );
484
596
  }