@open-workspace/email 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (266) hide show
  1. package/README.md +9 -4
  2. package/alchemy/index.ts +130 -2
  3. package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
  4. package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
  5. package/drizzle/mailbox/meta/_journal.json +7 -0
  6. package/drizzle/mailbox/migrations.js +3 -1
  7. package/migrations/0002_after_0_4_2.sql +35 -0
  8. package/migrations/meta/0002_snapshot.json +807 -0
  9. package/migrations/meta/_journal.json +7 -0
  10. package/package.json +23 -7
  11. package/shared/attachment-preview.ts +18 -8
  12. package/shared/folder-order.ts +31 -6
  13. package/shared/mail-headers.ts +3 -3
  14. package/shared/mail-html.ts +25 -0
  15. package/shared/mail-import.ts +0 -7
  16. package/shared/mail-received.ts +4 -4
  17. package/shared/mail-rule-actions.ts +47 -0
  18. package/shared/mail.ts +70 -4
  19. package/shared/office-preview.ts +0 -4
  20. package/shared/pdfjs-assets.ts +1 -3
  21. package/shared/rich-content.ts +35 -0
  22. package/shared/signature.ts +15 -0
  23. package/src/admin/address-auto-reply.tsx +49 -0
  24. package/src/admin/blocked-senders.tsx +86 -66
  25. package/src/admin/forward-destinations.tsx +140 -0
  26. package/src/admin/mail-archive.tsx +134 -0
  27. package/src/admin/team-signature.tsx +90 -0
  28. package/src/client.tsx +130 -16
  29. package/src/mail/attachment-preview-dialog.tsx +13 -5
  30. package/src/mail/auto-reply-banner.tsx +61 -0
  31. package/src/mail/blocked-senders.tsx +124 -91
  32. package/src/mail/compose-window-chrome.tsx +20 -8
  33. package/src/mail/compose-window.tsx +387 -365
  34. package/src/mail/composer-asset-bookmarks.ts +47 -12
  35. package/src/mail/composer-attachment-list.tsx +42 -17
  36. package/src/mail/composer-editor-document.ts +54 -10
  37. package/src/mail/composer-editor.tsx +44 -44
  38. package/src/mail/composer-link-text.ts +42 -0
  39. package/src/mail/composer-recipient-fields.tsx +25 -16
  40. package/src/mail/composer-recipients.ts +62 -16
  41. package/src/mail/composer-session.ts +107 -23
  42. package/src/mail/composer-toolbar.tsx +15 -1
  43. package/src/mail/composer-upload-client.ts +29 -1
  44. package/src/mail/composer-upload-progress.ts +2 -2
  45. package/src/mail/conversation-actions-model.ts +56 -0
  46. package/src/mail/conversation-list.tsx +263 -128
  47. package/src/mail/conversation-loading-skeleton.tsx +165 -90
  48. package/src/mail/conversation-message.tsx +257 -102
  49. package/src/mail/conversation-order.ts +12 -0
  50. package/src/mail/conversation-reply.tsx +313 -189
  51. package/src/mail/conversation-selection-toolbar.tsx +188 -143
  52. package/src/mail/conversation-view.tsx +315 -85
  53. package/src/mail/delivery-indicator.tsx +33 -12
  54. package/src/mail/draft-attachments.ts +194 -0
  55. package/src/mail/email-html-body.tsx +97 -53
  56. package/src/mail/folder-cleanup-bar.tsx +193 -0
  57. package/src/mail/folder-glyph.tsx +5 -0
  58. package/src/mail/folder-manager.tsx +71 -38
  59. package/src/mail/mail-app-bar.tsx +15 -3
  60. package/src/mail/mail-dock.tsx +19 -3
  61. package/src/mail/mail-focus.ts +48 -0
  62. package/src/mail/mail-folders.ts +14 -2
  63. package/src/mail/mail-layout.css +20 -0
  64. package/src/mail/mail-mailbox-sheet.tsx +22 -69
  65. package/src/mail/mail-nav-rail.tsx +7 -4
  66. package/src/mail/mail-nav.tsx +66 -46
  67. package/src/mail/mail-prefetch.ts +30 -9
  68. package/src/mail/mail-primitives.tsx +6 -4
  69. package/src/mail/mail-queries.ts +122 -20
  70. package/src/mail/mail-query-cache.ts +1085 -173
  71. package/src/mail/mail-search-params.ts +35 -0
  72. package/src/mail/mail-shell.tsx +32 -9
  73. package/src/mail/mailbox-ai-settings.tsx +56 -42
  74. package/src/mail/mailbox-realtime.tsx +4 -12
  75. package/src/mail/mailbox-rules.tsx +898 -0
  76. package/src/mail/message-actions.tsx +38 -26
  77. package/src/mail/message-attachments.tsx +20 -12
  78. package/src/mail/message-body.ts +53 -0
  79. package/src/mail/message-format.ts +8 -2
  80. package/src/mail/message-header.tsx +3 -1
  81. package/src/mail/message-translation.tsx +34 -67
  82. package/src/mail/original-message-sheet.tsx +63 -50
  83. package/src/mail/original-message.ts +6 -6
  84. package/src/mail/pane-splitter.tsx +3 -3
  85. package/src/mail/pdf-preview.tsx +70 -62
  86. package/src/mail/plain-message-text.tsx +28 -0
  87. package/src/mail/print-message.ts +31 -36
  88. package/src/mail/reader-pane.tsx +134 -103
  89. package/src/mail/recipient-combobox.tsx +52 -29
  90. package/src/mail/recipient-field-row.tsx +3 -0
  91. package/src/mail/rich-content.ts +128 -0
  92. package/src/mail/sanitize-email-html.ts +53 -32
  93. package/src/mail/sender-actions.tsx +48 -46
  94. package/src/mail/sender-authentication.tsx +1 -1
  95. package/src/mail/sender-dialogs.tsx +67 -43
  96. package/src/mail/sender-security.tsx +9 -10
  97. package/src/mail/signature.ts +43 -0
  98. package/src/mail/translation-html.ts +3 -3
  99. package/src/mail/types.ts +12 -0
  100. package/src/mail/use-composer-attachment-preflight.ts +23 -60
  101. package/src/mail/use-composer-core.ts +286 -0
  102. package/src/mail/use-composer-navigation.ts +120 -0
  103. package/src/mail/use-composer-submission.ts +154 -19
  104. package/src/mail/use-conversation-actions.ts +292 -0
  105. package/src/mail/use-conversation-position.ts +51 -0
  106. package/src/mail/use-conversation-selection.ts +192 -89
  107. package/src/mail/use-draft-autosave.ts +394 -0
  108. package/src/mail/use-drafts.ts +194 -0
  109. package/src/mail/use-mail-controller.ts +754 -213
  110. package/src/mail/use-mail-data.ts +210 -100
  111. package/src/mail/use-mail-safety.ts +19 -38
  112. package/src/mail/use-mail-send.ts +18 -6
  113. package/src/mail/use-pdf-translation.ts +1 -1
  114. package/src/mail/use-reply-cc.ts +61 -0
  115. package/src/mail/use-visible-message-read.ts +128 -64
  116. package/src/pwa/push-key.ts +18 -0
  117. package/src/pwa/push-subscription.ts +88 -26
  118. package/src/settings/auto-reply-editor.tsx +454 -0
  119. package/src/settings/auto-reply-page.tsx +59 -0
  120. package/src/settings/mail-apps-page.tsx +52 -43
  121. package/src/settings/notifications-page.tsx +82 -67
  122. package/src/settings/rich-content-editor.tsx +182 -0
  123. package/src/settings/settings-queries.ts +57 -0
  124. package/src/settings/signature-editor.tsx +142 -0
  125. package/src/settings/signature-page.tsx +70 -0
  126. package/worker/admin/blocked-sender-routes.ts +10 -16
  127. package/worker/backups/eml.ts +185 -0
  128. package/worker/backups/file-parts.ts +140 -0
  129. package/worker/backups/mail-backup.ts +644 -0
  130. package/worker/backups/settings-backup.ts +866 -0
  131. package/worker/backups/stream-eml.ts +73 -0
  132. package/worker/db/schema.ts +89 -5
  133. package/worker/jmap/attachment-blobs.ts +113 -0
  134. package/worker/jmap/blobs.ts +162 -0
  135. package/worker/jmap/draft-content.ts +42 -0
  136. package/worker/jmap/drafts.ts +70 -0
  137. package/worker/jmap/email-body.ts +152 -0
  138. package/worker/jmap/email-methods.ts +1223 -0
  139. package/worker/jmap/eventsource.ts +9 -8
  140. package/worker/jmap/import-methods.ts +205 -0
  141. package/worker/jmap/mailbox-methods.ts +187 -0
  142. package/worker/jmap/method-core.ts +379 -0
  143. package/worker/jmap/methods.ts +108 -1815
  144. package/worker/jmap/push-subscription-methods.ts +373 -0
  145. package/worker/jmap/push-types.ts +46 -2
  146. package/worker/jmap/push.ts +24 -31
  147. package/worker/jmap/routes.ts +144 -153
  148. package/worker/jmap/submission-methods.ts +395 -0
  149. package/worker/mail/access.ts +35 -12
  150. package/worker/mail/ai-classification.ts +2 -2
  151. package/worker/mail/archive-object.ts +96 -0
  152. package/worker/mail/archive-routes.ts +35 -0
  153. package/worker/mail/archive.ts +682 -0
  154. package/worker/mail/auth-headers.ts +48 -40
  155. package/worker/mail/auto-reply-routes.ts +255 -0
  156. package/worker/mail/auto-reply.ts +243 -0
  157. package/worker/mail/bimi.ts +53 -36
  158. package/worker/mail/bootstrap.ts +11 -3
  159. package/worker/mail/capabilities.ts +69 -0
  160. package/worker/mail/classification-signals.ts +1 -1
  161. package/worker/mail/confusables-data.ts +9 -0
  162. package/worker/mail/conversation-cursor.ts +6 -15
  163. package/worker/mail/delivery-events.ts +9 -7
  164. package/worker/mail/delivery-facts.ts +1 -1
  165. package/worker/mail/demo-routes.ts +3 -3
  166. package/worker/mail/doh.ts +3 -3
  167. package/worker/mail/download-links.ts +153 -0
  168. package/worker/mail/downloads.ts +2 -6
  169. package/worker/mail/draft-routes.ts +473 -0
  170. package/worker/mail/draft-sender.ts +54 -0
  171. package/worker/mail/edge-cache.ts +41 -55
  172. package/worker/mail/email-routing.ts +123 -0
  173. package/worker/mail/forward-destinations.ts +114 -0
  174. package/worker/mail/forward-downloads.ts +115 -0
  175. package/worker/mail/forward-html.ts +85 -0
  176. package/worker/mail/header-metadata.ts +2 -5
  177. package/worker/mail/impersonation.ts +102 -101
  178. package/worker/mail/import-routes.ts +29 -82
  179. package/worker/mail/import.ts +130 -0
  180. package/worker/mail/inbound-delivery.ts +6 -5
  181. package/worker/mail/inbound.ts +58 -28
  182. package/worker/mail/ip-intel.ts +8 -17
  183. package/worker/mail/isolate-cache.ts +1 -1
  184. package/worker/mail/mailbox-deletion.ts +33 -12
  185. package/worker/mail/mailbox-directory.ts +39 -65
  186. package/worker/mail/mailing-list.ts +29 -58
  187. package/worker/mail/message-security.ts +3 -3
  188. package/worker/mail/message-view.ts +12 -10
  189. package/worker/mail/office-conversion.ts +3 -5
  190. package/worker/mail/office-preview-container.ts +3 -8
  191. package/worker/mail/outbound-content.ts +139 -65
  192. package/worker/mail/outbound-delivery.ts +20 -17
  193. package/worker/mail/outbound-service.ts +34 -9
  194. package/worker/mail/outbound.ts +146 -75
  195. package/worker/mail/outgoing-context.ts +60 -30
  196. package/worker/mail/participants.ts +10 -15
  197. package/worker/mail/plain-body.ts +39 -0
  198. package/worker/mail/push-endpoint.ts +17 -0
  199. package/worker/mail/push-notifications.ts +53 -62
  200. package/worker/mail/quote-parser.ts +36 -24
  201. package/worker/mail/receive.ts +146 -39
  202. package/worker/mail/recipients.ts +1 -1
  203. package/worker/mail/remote-proxy.ts +3 -3
  204. package/worker/mail/repeat.ts +1 -1
  205. package/worker/mail/reply-plan.ts +124 -26
  206. package/worker/mail/rfc.ts +15 -7
  207. package/worker/mail/rich-content.ts +207 -0
  208. package/worker/mail/routes.ts +696 -304
  209. package/worker/mail/routing.ts +274 -0
  210. package/worker/mail/rules.ts +230 -0
  211. package/worker/mail/safety-routes.ts +88 -86
  212. package/worker/mail/schemas.ts +222 -31
  213. package/worker/mail/search.ts +25 -2
  214. package/worker/mail/security-settings.ts +4 -10
  215. package/worker/mail/send-message.ts +238 -0
  216. package/worker/mail/sender-intel.ts +12 -20
  217. package/worker/mail/signature-routes.ts +201 -0
  218. package/worker/mail/signatures.ts +195 -0
  219. package/worker/mail/spamhaus.ts +28 -16
  220. package/worker/mail/storage-keys.ts +35 -0
  221. package/worker/mail/unsubscribe.ts +19 -41
  222. package/worker/mail/uploads.ts +192 -80
  223. package/worker/mail/webhook-source.ts +3 -2
  224. package/worker/mail/workspace-safety.ts +194 -60
  225. package/worker/mailbox/demo.ts +13 -15
  226. package/worker/mailbox/email-index.ts +65 -35
  227. package/worker/mailbox/folder-model.ts +0 -20
  228. package/worker/mailbox/import-placement.ts +21 -36
  229. package/worker/mailbox/inbound-decision.ts +114 -0
  230. package/worker/mailbox/inbox-counts.ts +45 -25
  231. package/worker/mailbox/index.ts +756 -3201
  232. package/worker/mailbox/jmap-change-log.ts +195 -0
  233. package/worker/mailbox/jmap-email-rows.ts +186 -0
  234. package/worker/mailbox/jmap-mailboxes.ts +116 -0
  235. package/worker/mailbox/jmap-placement.ts +139 -0
  236. package/worker/mailbox/jmap-query-filter.ts +231 -0
  237. package/worker/mailbox/jmap-store.ts +167 -299
  238. package/worker/mailbox/mailbox-auto-reply.ts +301 -0
  239. package/worker/mailbox/mailbox-backup.ts +538 -0
  240. package/worker/mailbox/mailbox-drafts.ts +417 -0
  241. package/worker/mailbox/mailbox-folders.ts +242 -0
  242. package/worker/mailbox/mailbox-import.ts +450 -0
  243. package/worker/mailbox/mailbox-inbound.ts +934 -0
  244. package/worker/mailbox/mailbox-jmap.ts +294 -0
  245. package/worker/mailbox/mailbox-outbound.ts +413 -0
  246. package/worker/mailbox/mailbox-rules.ts +336 -0
  247. package/worker/mailbox/mailbox-senders.ts +294 -0
  248. package/worker/mailbox/mailbox-storage.ts +438 -0
  249. package/worker/mailbox/mailbox-views.ts +891 -0
  250. package/worker/mailbox/model.ts +1 -0
  251. package/worker/mailbox/office-preview-jobs.ts +59 -47
  252. package/worker/mailbox/placement.ts +933 -0
  253. package/worker/mailbox/restore-thread.ts +52 -0
  254. package/worker/mailbox/retention.ts +36 -0
  255. package/worker/mailbox/schema.ts +200 -1
  256. package/worker/mailbox/senders.ts +216 -178
  257. package/worker/mailbox/spam-undo-filing.ts +138 -0
  258. package/worker/mailbox/spam-undo.ts +240 -0
  259. package/worker/mailbox/support.ts +416 -0
  260. package/worker/mcp/mail-action-tools.ts +156 -0
  261. package/worker/mcp/mail-compose-tools.ts +7 -1
  262. package/worker/mcp/mail-safety-tools.ts +4 -4
  263. package/worker/module.ts +23 -4
  264. package/src/mail/use-compose-submission.ts +0 -208
  265. package/src/mail/use-reply-submission.ts +0 -114
  266. package/worker/mail/capped-body.ts +0 -36
@@ -0,0 +1,373 @@
1
+ /** PushSubscription/get and /set (RFC 8620 §7.2). */
2
+ import { inJsonList, createDb } from "@open-workspace/core/module";
3
+ import { waitUntil } from "cloudflare:workers";
4
+ import { and, eq } from "drizzle-orm";
5
+ import { z } from "zod";
6
+
7
+ import { jmapPushSubscriptions } from "../db/schema";
8
+ import { isPublicPushEndpoint } from "../mail/push-endpoint";
9
+ import type { JsonObject, RequestState } from "./method-core";
10
+ import {
11
+ MethodError,
12
+ idList,
13
+ invalidProperties,
14
+ pick,
15
+ properties,
16
+ setObjects,
17
+ setResult,
18
+ utcDate,
19
+ } from "./method-core";
20
+ import {
21
+ newVerificationCode,
22
+ sendVerification,
23
+ subscriptionExpiry,
24
+ } from "./push";
25
+
26
+ // --------------------------------------------------------- push (RFC 8620 §7.2)
27
+
28
+ const MAX_PUSH_SUBSCRIPTIONS = 20;
29
+
30
+ type PushSubscriptionRow = typeof jmapPushSubscriptions.$inferSelect;
31
+
32
+ /** url and keys are never returned (§7.2.1). */
33
+ function pushSubscriptionObject(row: PushSubscriptionRow) {
34
+ return {
35
+ id: row.id,
36
+ deviceClientId: row.deviceClientId,
37
+ verificationCode: row.verifiedAt ? row.verificationCode : null,
38
+ expires: row.expiresAt.toISOString(),
39
+ types: row.typesJson,
40
+ };
41
+ }
42
+
43
+ /** The data types to push; null is all of them. */
44
+ const pushTypes = z.array(z.string()).nullish();
45
+
46
+ /** A PushSubscription create object (RFC 8620 §7.2). */
47
+ const pushSubscriptionCreate = z.object({
48
+ deviceClientId: z.string().min(1),
49
+ url: z
50
+ .url()
51
+ .max(4096)
52
+ .refine(isPublicPushEndpoint, "url must be a public https URL")
53
+ .transform((url) => new URL(url).toString()),
54
+ keys: z.object({ p256dh: z.string(), auth: z.string() }).nullish(),
55
+ verificationCode: z
56
+ .never({ error: "verificationCode is set by update" })
57
+ .optional(),
58
+ expires: utcDate.nullish(),
59
+ types: pushTypes,
60
+ });
61
+
62
+ /** Only these change after a subscription is created. */
63
+ const pushSubscriptionPatch = z.strictObject({
64
+ verificationCode: z.string().optional(),
65
+ expires: utcDate.nullish(),
66
+ types: pushTypes,
67
+ });
68
+
69
+ function ownSubscriptions(state: RequestState) {
70
+ return and(
71
+ eq(jmapPushSubscriptions.userId, state.context.user.id),
72
+ eq(jmapPushSubscriptions.clientId, state.context.clientId)
73
+ );
74
+ }
75
+
76
+ export const pushSubscriptionGetArguments = z.object({
77
+ ids: idList.nullish(),
78
+ properties,
79
+ });
80
+
81
+ export async function pushSubscriptionGet(
82
+ state: RequestState,
83
+ args: z.output<typeof pushSubscriptionGetArguments>
84
+ ) {
85
+ const db = createDb(state.context.env.DB);
86
+ const ids = args.ids ?? null;
87
+
88
+ const rows = ids
89
+ ? await db
90
+ .select()
91
+ .from(jmapPushSubscriptions)
92
+ .where(
93
+ and(
94
+ ownSubscriptions(state),
95
+ inJsonList(jmapPushSubscriptions.id, ids)
96
+ )
97
+ )
98
+ : await db
99
+ .select()
100
+ .from(jmapPushSubscriptions)
101
+ .where(ownSubscriptions(state));
102
+
103
+ const found = new Set(rows.map((row) => row.id));
104
+
105
+ return {
106
+ list: rows.map((row) => pick(pushSubscriptionObject(row), args.properties)),
107
+ notFound: ids ? ids.filter((id) => !found.has(id)) : [],
108
+ };
109
+ }
110
+
111
+ export const pushSubscriptionSetArguments = z.object({
112
+ /** Push subscriptions have no state (§7.2): any given state mismatches. */
113
+ ifInState: z.string().nullish(),
114
+ create: setObjects,
115
+ update: setObjects,
116
+ destroy: idList.nullish(),
117
+ });
118
+
119
+ async function createPushSubscriptions(
120
+ state: RequestState,
121
+ create: JsonObject
122
+ ) {
123
+ const db = createDb(state.context.env.DB);
124
+ const created = new Map<string, JsonObject>();
125
+ const notCreated = new Map<string, JsonObject>();
126
+ const entries = Object.entries(create);
127
+
128
+ if (!entries.length) return { created, notCreated };
129
+
130
+ // The devices with a subscription; a device has one, and a new one replaces it.
131
+ const devices = new Set(
132
+ (
133
+ await db
134
+ .select({ deviceClientId: jmapPushSubscriptions.deviceClientId })
135
+ .from(jmapPushSubscriptions)
136
+ .where(eq(jmapPushSubscriptions.userId, state.context.user.id))
137
+ ).map((row) => row.deviceClientId)
138
+ );
139
+
140
+ const rows: PushSubscriptionRow[] = [];
141
+
142
+ for (const [creationId, input] of entries) {
143
+ const parsed = pushSubscriptionCreate.safeParse(input);
144
+
145
+ if (!parsed.success) {
146
+ notCreated.set(creationId, invalidProperties(parsed.error.issues));
147
+ continue;
148
+ }
149
+
150
+ const subscription = parsed.data;
151
+
152
+ if (subscription.keys && !state.context.vapid) {
153
+ notCreated.set(creationId, {
154
+ type: "invalidProperties",
155
+ properties: ["keys"],
156
+ description: "Web Push is not configured on this server",
157
+ });
158
+ continue;
159
+ }
160
+
161
+ const others =
162
+ devices.size - (devices.has(subscription.deviceClientId) ? 1 : 0);
163
+
164
+ if (others >= MAX_PUSH_SUBSCRIPTIONS) {
165
+ notCreated.set(creationId, {
166
+ type: "overQuota",
167
+ description: `At most ${MAX_PUSH_SUBSCRIPTIONS} push subscriptions`,
168
+ });
169
+ continue;
170
+ }
171
+
172
+ devices.add(subscription.deviceClientId);
173
+
174
+ const row: PushSubscriptionRow = {
175
+ id: crypto.randomUUID(),
176
+ userId: state.context.user.id,
177
+ clientId: state.context.clientId,
178
+ deviceClientId: subscription.deviceClientId,
179
+ url: subscription.url,
180
+ p256dh: subscription.keys?.p256dh ?? null,
181
+ auth: subscription.keys?.auth ?? null,
182
+ verificationCode: newVerificationCode(),
183
+ verifiedAt: null,
184
+ expiresAt: subscriptionExpiry(subscription.expires),
185
+ typesJson: subscription.types ?? null,
186
+ createdAt: new Date(),
187
+ };
188
+
189
+ rows.push(row);
190
+ state.createdIds.set(creationId, row.id);
191
+ created.set(creationId, {
192
+ id: row.id,
193
+ expires: row.expiresAt.toISOString(),
194
+ });
195
+ }
196
+
197
+ // In order: a later subscription for the same device replaces an earlier one.
198
+ const [first, ...rest] = rows.flatMap((row) => [
199
+ db
200
+ .delete(jmapPushSubscriptions)
201
+ .where(
202
+ and(
203
+ eq(jmapPushSubscriptions.userId, row.userId),
204
+ eq(jmapPushSubscriptions.deviceClientId, row.deviceClientId)
205
+ )
206
+ ),
207
+ db.insert(jmapPushSubscriptions).values(row),
208
+ ]);
209
+
210
+ if (first) await db.batch([first, ...rest]);
211
+
212
+ for (const row of rows) {
213
+ waitUntil(
214
+ sendVerification(row, state.context.vapid).catch((error) => {
215
+ console.error(
216
+ "Could not send JMAP push verification",
217
+ error instanceof Error ? error.message : String(error)
218
+ );
219
+ })
220
+ );
221
+ }
222
+
223
+ return { created, notCreated };
224
+ }
225
+
226
+ async function updatePushSubscriptions(
227
+ state: RequestState,
228
+ update: JsonObject
229
+ ) {
230
+ const db = createDb(state.context.env.DB);
231
+ const updated = new Map<string, JsonObject | null>();
232
+ const notUpdated = new Map<string, JsonObject>();
233
+ const entries = Object.entries(update);
234
+
235
+ if (!entries.length) return { updated, notUpdated };
236
+
237
+ const rows = new Map(
238
+ (
239
+ await db
240
+ .select()
241
+ .from(jmapPushSubscriptions)
242
+ .where(
243
+ and(
244
+ ownSubscriptions(state),
245
+ inJsonList(
246
+ jmapPushSubscriptions.id,
247
+ entries.map(([id]) => id)
248
+ )
249
+ )
250
+ )
251
+ ).map((row) => [row.id, row])
252
+ );
253
+
254
+ const changed: Pick<
255
+ PushSubscriptionRow,
256
+ "id" | "verifiedAt" | "expiresAt" | "typesJson"
257
+ >[] = [];
258
+
259
+ for (const [id, input] of entries) {
260
+ const row = rows.get(id);
261
+
262
+ if (!row) {
263
+ notUpdated.set(id, { type: "notFound" });
264
+ continue;
265
+ }
266
+
267
+ const parsed = pushSubscriptionPatch.safeParse(input);
268
+
269
+ if (!parsed.success) {
270
+ notUpdated.set(id, invalidProperties(parsed.error.issues));
271
+ continue;
272
+ }
273
+
274
+ const patch = parsed.data;
275
+
276
+ if (
277
+ patch.verificationCode !== undefined &&
278
+ patch.verificationCode !== row.verificationCode
279
+ ) {
280
+ notUpdated.set(id, {
281
+ type: "invalidProperties",
282
+ properties: ["verificationCode"],
283
+ description: "The verification code does not match",
284
+ });
285
+ continue;
286
+ }
287
+
288
+ const expiresAt =
289
+ patch.expires === undefined
290
+ ? row.expiresAt
291
+ : subscriptionExpiry(patch.expires);
292
+
293
+ changed.push({
294
+ id,
295
+ verifiedAt:
296
+ patch.verificationCode === undefined
297
+ ? row.verifiedAt
298
+ : (row.verifiedAt ?? new Date()),
299
+ expiresAt,
300
+ typesJson: patch.types === undefined ? row.typesJson : patch.types,
301
+ });
302
+
303
+ // The server may shorten the asked expiry; then it says what it chose.
304
+ const askedExpiry = patch.expires ? Date.parse(patch.expires) : null;
305
+
306
+ updated.set(
307
+ id,
308
+ askedExpiry !== null && askedExpiry !== expiresAt.getTime()
309
+ ? { expires: expiresAt.toISOString() }
310
+ : null
311
+ );
312
+ }
313
+
314
+ const [first, ...rest] = changed.map(({ id, ...values }) =>
315
+ db
316
+ .update(jmapPushSubscriptions)
317
+ .set(values)
318
+ .where(eq(jmapPushSubscriptions.id, id))
319
+ );
320
+
321
+ if (first) await db.batch([first, ...rest]);
322
+
323
+ return { updated, notUpdated };
324
+ }
325
+
326
+ export async function pushSubscriptionSet(
327
+ state: RequestState,
328
+ args: z.output<typeof pushSubscriptionSetArguments>
329
+ ) {
330
+ const db = createDb(state.context.env.DB);
331
+
332
+ if (args.ifInState != null) throw new MethodError("stateMismatch");
333
+
334
+ const { created, notCreated } = await createPushSubscriptions(
335
+ state,
336
+ args.create ?? {}
337
+ );
338
+
339
+ const { updated, notUpdated } = await updatePushSubscriptions(
340
+ state,
341
+ args.update ?? {}
342
+ );
343
+
344
+ const destroyIds = args.destroy ?? [];
345
+
346
+ const removed = destroyIds.length
347
+ ? await db
348
+ .delete(jmapPushSubscriptions)
349
+ .where(
350
+ and(
351
+ ownSubscriptions(state),
352
+ inJsonList(jmapPushSubscriptions.id, destroyIds)
353
+ )
354
+ )
355
+ .returning({ id: jmapPushSubscriptions.id })
356
+ : [];
357
+
358
+ const destroyed = new Set(removed.map((row) => row.id));
359
+ const notDestroyed = new Map<string, JsonObject>();
360
+
361
+ for (const id of destroyIds) {
362
+ if (!destroyed.has(id)) notDestroyed.set(id, { type: "notFound" });
363
+ }
364
+
365
+ return {
366
+ created: setResult(created),
367
+ updated: setResult(updated),
368
+ destroyed: destroyed.size ? [...destroyed] : null,
369
+ notCreated: setResult(notCreated),
370
+ notUpdated: setResult(notUpdated),
371
+ notDestroyed: setResult(notDestroyed),
372
+ };
373
+ }
@@ -1,9 +1,11 @@
1
+ import { z } from "zod";
2
+
1
3
  /**
2
4
  * The data types JMAP pushes for a mailbox account, apart from push.ts so
3
5
  * the event stream does not load the Web Push sender.
4
6
  */
5
7
 
6
- /** Data types whose state a mailbox account reports; one state covers them all. */
8
+ /** Data types whose state a mailbox account reports; one state covers them all (EmailDelivery moves only with new mail). */
7
9
  export const JMAP_PUSH_TYPES = [
8
10
  "Email",
9
11
  "Mailbox",
@@ -16,9 +18,51 @@ type JmapPushType = (typeof JMAP_PUSH_TYPES)[number];
16
18
  /** RFC 8620 §7.1: what changed, per account and data type. */
17
19
  export type StateChange = {
18
20
  "@type": "StateChange";
19
- changed: Record<string, Record<JmapPushType, string>>;
21
+ changed: Record<string, Partial<Record<JmapPushType, string>>>;
20
22
  };
21
23
 
24
+ /** A mailbox's move to a new JMAP state, as it tells its streams and push. */
25
+ export const jmapStateMessage = z.object({
26
+ state: z.string().min(1),
27
+ /** New mail arrived (RFC 8621 §1.5: only that moves EmailDelivery). */
28
+ delivered: z.boolean(),
29
+ });
30
+
31
+ export type JmapStateMessage = z.infer<typeof jmapStateMessage>;
32
+
33
+ /** `jmapStateMessage` as a mailbox's socket sends it: JSON text. */
34
+ export const jmapStateSocketMessage = z
35
+ .string()
36
+ .transform((text, context) => {
37
+ try {
38
+ return JSON.parse(text);
39
+ } catch {
40
+ context.addIssue({ code: "custom", message: "Not JSON" });
41
+
42
+ return z.NEVER;
43
+ }
44
+ })
45
+ .pipe(jmapStateMessage);
46
+
47
+ export function stateChange(changed: Record<string, JmapStateMessage>) {
48
+ return {
49
+ "@type": "StateChange",
50
+ changed: Object.fromEntries(
51
+ Object.entries(changed).map(([accountId, { state, delivered }]) => {
52
+ const types: Partial<Record<JmapPushType, string>> = {
53
+ Email: state,
54
+ Mailbox: state,
55
+ Thread: state,
56
+ };
57
+
58
+ if (delivered) types.EmailDelivery = state;
59
+
60
+ return [accountId, types];
61
+ })
62
+ ),
63
+ } satisfies StateChange;
64
+ }
65
+
22
66
  const pushTypeNames: ReadonlySet<string> = new Set(JMAP_PUSH_TYPES);
23
67
 
24
68
  /** Whether a client that asked for `types` (null: all) wants mail changes. */
@@ -3,17 +3,14 @@ import {
3
3
  sendPushNotification,
4
4
  topicFromString,
5
5
  } from "@mmmike/web-push/send";
6
- import {
7
- createDb,
8
- mailboxAccess,
9
- mailboxes,
10
- createId,
11
- } from "@open-workspace/core/module";
12
- import { and, eq, gt, inArray, isNotNull, lte } from "drizzle-orm";
6
+ import { inJsonList, createDb, createId } from "@open-workspace/core/module";
7
+ import { mailboxAccess, mailboxes, users } from "@open-workspace/core/schema";
8
+ import { and, eq, gt, isNotNull, lte } from "drizzle-orm";
13
9
 
14
10
  import { jmapPushSubscriptions } from "../db/schema";
15
- import { wantsMailChanges } from "./push-types";
16
- import type { StateChange } from "./push-types";
11
+ import { isPublicPushEndpoint } from "../mail/push-endpoint";
12
+ import { stateChange, wantsMailChanges } from "./push-types";
13
+ import type { JmapStateMessage, StateChange } from "./push-types";
17
14
 
18
15
  export { JMAP_PUSH_TYPES } from "./push-types";
19
16
 
@@ -38,23 +35,6 @@ type PushVerification = {
38
35
  verificationCode: string;
39
36
  };
40
37
 
41
- export function stateChange(changed: Record<string, string>): StateChange {
42
- return {
43
- "@type": "StateChange",
44
- changed: Object.fromEntries(
45
- Object.entries(changed).map(([accountId, state]) => [
46
- accountId,
47
- {
48
- Email: state,
49
- Mailbox: state,
50
- Thread: state,
51
- EmailDelivery: state,
52
- },
53
- ])
54
- ),
55
- };
56
- }
57
-
58
38
  /** When a subscription expires: as asked (a UTCDate), but within a week. */
59
39
  export function subscriptionExpiry(
60
40
  requested: string | null | undefined,
@@ -79,6 +59,9 @@ export async function postToSubscription(
79
59
  vapid: PushVapid | null,
80
60
  options: { ttl: number; topic?: string }
81
61
  ) {
62
+ // Registered before the rule: gone, as a push service would say.
63
+ if (!isPublicPushEndpoint(subscription.url)) return false;
64
+
82
65
  if (subscription.p256dh && subscription.auth) {
83
66
  if (!vapid) throw new Error("Web Push is not configured");
84
67
 
@@ -105,9 +88,13 @@ export async function postToSubscription(
105
88
  method: "POST",
106
89
  headers,
107
90
  body: JSON.stringify(body),
91
+ // A redirect could lead anywhere the rule refuses.
92
+ redirect: "manual",
108
93
  signal: AbortSignal.timeout(30_000),
109
94
  });
110
95
 
96
+ await response.body?.cancel();
97
+
111
98
  if (response.status === 404 || response.status === 410) return false;
112
99
 
113
100
  if (!response.ok) {
@@ -144,7 +131,7 @@ export async function sendVerification(
144
131
  */
145
132
  export async function deliverJmapStateChange(
146
133
  env: Env,
147
- input: { mailboxId: string; state: string },
134
+ input: { mailboxId: string } & JmapStateMessage,
148
135
  vapid: PushVapid
149
136
  ) {
150
137
  const db = createDb(env.DB);
@@ -161,10 +148,13 @@ export async function deliverJmapStateChange(
161
148
  eq(mailboxAccess.userId, jmapPushSubscriptions.userId)
162
149
  )
163
150
  .innerJoin(mailboxes, eq(mailboxes.id, mailboxAccess.mailboxId))
151
+ // A disabled person keeps their access rows, not their pushes.
152
+ .innerJoin(users, eq(users.id, jmapPushSubscriptions.userId))
164
153
  .where(
165
154
  and(
166
155
  eq(mailboxAccess.mailboxId, input.mailboxId),
167
156
  eq(mailboxes.delivery, "inbox"),
157
+ eq(users.status, "active"),
168
158
  isNotNull(jmapPushSubscriptions.verifiedAt),
169
159
  gt(jmapPushSubscriptions.expiresAt, now)
170
160
  )
@@ -178,13 +168,16 @@ export async function deliverJmapStateChange(
178
168
  try {
179
169
  const delivered = await postToSubscription(
180
170
  subscription,
181
- stateChange({ [input.mailboxId]: input.state }),
171
+ stateChange({ [input.mailboxId]: input }),
182
172
  vapid,
183
173
  {
184
174
  ttl: STATE_CHANGE_TTL_SECONDS,
185
- // A newer state replaces an undelivered older one.
175
+ // A newer state replaces an undelivered older one (RFC 8030
176
+ // §5.4). New mail has a topic of its own: only its push says
177
+ // EmailDelivery moved, and a later plain change mustn't
178
+ // replace it.
186
179
  topic: await topicFromString(
187
- `jmap:${subscription.id}:${input.mailboxId}`
180
+ `jmap:${subscription.id}:${input.mailboxId}${input.delivered ? ":delivery" : ""}`
188
181
  ),
189
182
  }
190
183
  );
@@ -202,6 +195,6 @@ export async function deliverJmapStateChange(
202
195
  if (gone.length) {
203
196
  await db
204
197
  .delete(jmapPushSubscriptions)
205
- .where(inArray(jmapPushSubscriptions.id, gone));
198
+ .where(inJsonList(jmapPushSubscriptions.id, gone));
206
199
  }
207
200
  }