@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
@@ -1,5 +1,9 @@
1
+ import { z } from "zod";
2
+
1
3
  import type { BimiResult, BimiStatus } from "../../shared/mail-sender-intel";
2
- import { isAbortError, type DnsResolver } from "./doh";
4
+ import { readCappedBody } from "./capped-body";
5
+ import { isAbortError } from "./doh";
6
+ import type { DnsResolver } from "./doh";
3
7
  import { assertProxyableRemoteUrl } from "./remote-proxy";
4
8
 
5
9
  /**
@@ -23,7 +27,8 @@ export function bimiLogoPath(domain: string) {
23
27
  /** Strict CSP for serving stored logos: no scripts, no external loads. */
24
28
  export const BIMI_LOGO_HEADERS = {
25
29
  "content-type": "image/svg+xml",
26
- "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
30
+ "content-security-policy":
31
+ "default-src 'none'; style-src 'unsafe-inline'; sandbox",
27
32
  "x-content-type-options": "nosniff",
28
33
  "cross-origin-resource-policy": "same-origin",
29
34
  "cache-control": "private, max-age=86400",
@@ -32,13 +37,20 @@ export const BIMI_LOGO_HEADERS = {
32
37
  /** `v=BIMI1; l=https://…/logo.svg; a=…` → the logo location, or null when declined. */
33
38
  export function parseBimiRecord(value: string) {
34
39
  const tags = new Map<string, string>();
40
+
35
41
  for (const part of value.split(";")) {
36
42
  const index = part.indexOf("=");
37
- if (index < 0) continue;
38
- tags.set(part.slice(0, index).trim().toLocaleLowerCase(), part.slice(index + 1).trim());
43
+
44
+ if (index === -1) continue;
45
+ tags.set(
46
+ part.slice(0, index).trim().toLocaleLowerCase(),
47
+ part.slice(index + 1).trim()
48
+ );
39
49
  }
50
+
40
51
  if (tags.get("v") !== "BIMI1") return null;
41
52
  const location = tags.get("l")?.split(",")[0]?.trim() ?? "";
53
+
42
54
  return { location: location || null };
43
55
  }
44
56
 
@@ -49,47 +61,66 @@ const FORBIDDEN_ELEMENTS =
49
61
  * Conservative SVG Tiny PS check. Rejects anything that could run code or load
50
62
  * another resource; returns the trimmed document, or a reason it was refused.
51
63
  */
52
- export function validateBimiSvg(source: string): { svg: string } | { error: string } {
53
- if (new TextEncoder().encode(source).byteLength > MAX_BIMI_SVG_BYTES) return { error: "The logo is larger than 32 KB" };
64
+ export function validateBimiSvg(
65
+ source: string
66
+ ): { svg: string } | { error: string } {
67
+ if (new TextEncoder().encode(source).byteLength > MAX_BIMI_SVG_BYTES) {
68
+ return { error: "The logo is larger than 32 KB" };
69
+ }
70
+
54
71
  const svg = source.replace(/^/u, "").trim();
55
- const body = svg.replace(/^<\?xml[^>]*\?>\s*/iu, "").replace(/<!--[\s\S]*?-->/gu, "").trim();
56
- if (/<!DOCTYPE|<!ENTITY|<!\[CDATA\[/iu.test(body)) return { error: "The logo declares a DTD, entity or CDATA section" };
57
- if (!/^<svg[\s>]/iu.test(body) || !/<\/svg>\s*$/iu.test(body)) return { error: "The file is not an SVG document" };
58
- if (!/xmlns\s*=\s*["']http:\/\/www\.w3\.org\/2000\/svg["']/u.test(body)) return { error: "The SVG namespace is missing" };
59
- if (FORBIDDEN_ELEMENTS.test(body)) return { error: "The logo contains scripts, links, images or animation" };
60
- if (/\son[a-z]+\s*=/iu.test(body)) return { error: "The logo contains event handlers" };
61
- if (/javascript:|data:|@import/iu.test(body)) return { error: "The logo references executable or embedded content" };
62
- for (const match of body.matchAll(/\b(?:xlink:)?href\s*=\s*["']([^"']*)["']/giu)) {
63
- if (!match[1]!.trim().startsWith("#")) return { error: "The logo references an external resource" };
72
+
73
+ const body = svg
74
+ .replace(/^<\?xml[^>]*\?>\s*/iu, "")
75
+ .replaceAll(/<!--[\s\S]*?-->/gu, "")
76
+ .trim();
77
+
78
+ if (/<!DOCTYPE|<!ENTITY|<!\[CDATA\[/iu.test(body)) {
79
+ return { error: "The logo declares a DTD, entity or CDATA section" };
80
+ }
81
+
82
+ if (!/^<svg[\s>]/iu.test(body) || !/<\/svg>\s*$/iu.test(body)) {
83
+ return { error: "The file is not an SVG document" };
84
+ }
85
+
86
+ if (!/xmlns\s*=\s*["']http:\/\/www\.w3\.org\/2000\/svg["']/u.test(body)) {
87
+ return { error: "The SVG namespace is missing" };
88
+ }
89
+
90
+ if (FORBIDDEN_ELEMENTS.test(body)) {
91
+ return { error: "The logo contains scripts, links, images or animation" };
64
92
  }
93
+
94
+ if (/\son[a-z]+\s*=/iu.test(body)) {
95
+ return { error: "The logo contains event handlers" };
96
+ }
97
+
98
+ if (/javascript:|data:|@import/iu.test(body)) {
99
+ return { error: "The logo references executable or embedded content" };
100
+ }
101
+
102
+ for (const match of body.matchAll(
103
+ /\b(?:xlink:)?href\s*=\s*["']([^"']*)["']/giu
104
+ )) {
105
+ if (!match[1].trim().startsWith("#")) {
106
+ return { error: "The logo references an external resource" };
107
+ }
108
+ }
109
+
65
110
  for (const match of body.matchAll(/url\(\s*['"]?([^'")]*)/giu)) {
66
- if (!match[1]!.trim().startsWith("#")) return { error: "The logo references an external resource" };
111
+ if (!match[1].trim().startsWith("#")) {
112
+ return { error: "The logo references an external resource" };
113
+ }
67
114
  }
115
+
68
116
  return { svg };
69
117
  }
70
118
 
71
119
  async function readCapped(response: Response, limit: number) {
72
- const reader = response.body?.getReader();
73
- if (!reader) return null;
74
- const chunks: Uint8Array[] = [];
75
- let total = 0;
76
- for (;;) {
77
- const { done, value } = await reader.read();
78
- if (done) break;
79
- total += value.byteLength;
80
- if (total > limit) {
81
- await reader.cancel();
82
- return null;
83
- }
84
- chunks.push(value);
85
- }
86
- const bytes = new Uint8Array(total);
87
- let offset = 0;
88
- for (const chunk of chunks) {
89
- bytes.set(chunk, offset);
90
- offset += chunk.byteLength;
91
- }
92
- return new TextDecoder().decode(bytes);
120
+ if (!response.body) return null;
121
+ const bytes = await readCappedBody(response.body, limit);
122
+
123
+ return bytes && new TextDecoder().decode(bytes);
93
124
  }
94
125
 
95
126
  type Lookup = { status: BimiStatus; reason: string | null; svg?: string };
@@ -101,43 +132,93 @@ async function lookup(input: {
101
132
  signal?: AbortSignal;
102
133
  }): Promise<Lookup> {
103
134
  const answer = await input.resolve(`default._bimi.${input.domain}`, "TXT");
135
+
104
136
  if (answer.status === "timeout" || answer.status === "error") {
105
- return { status: "error", reason: "The BIMI record could not be looked up" };
137
+ return {
138
+ status: "error",
139
+ reason: "The BIMI record could not be looked up",
140
+ };
106
141
  }
142
+
107
143
  const record = answer.records.map(parseBimiRecord).find(Boolean);
108
- if (!record) return { status: "none", reason: "The domain publishes no BIMI record" };
109
- if (!record.location) return { status: "none", reason: "The domain declined to show a logo" };
144
+
145
+ if (!record) {
146
+ return { status: "none", reason: "The domain publishes no BIMI record" };
147
+ }
148
+
149
+ if (!record.location) {
150
+ return { status: "none", reason: "The domain declined to show a logo" };
151
+ }
152
+
110
153
  let url: URL;
154
+
111
155
  try {
112
156
  url = assertProxyableRemoteUrl(record.location);
113
157
  } catch {
114
- return { status: "invalid", reason: "The BIMI logo location is not a valid public URL" };
158
+ return {
159
+ status: "invalid",
160
+ reason: "The BIMI logo location is not a valid public URL",
161
+ };
162
+ }
163
+
164
+ if (url.protocol !== "https:") {
165
+ return {
166
+ status: "invalid",
167
+ reason: "The BIMI logo is not served over HTTPS",
168
+ };
115
169
  }
116
- if (url.protocol !== "https:") return { status: "invalid", reason: "The BIMI logo is not served over HTTPS" };
170
+
117
171
  try {
118
172
  const response = await input.fetch(url, {
119
173
  redirect: "manual",
120
174
  headers: { accept: "image/svg+xml" },
121
175
  signal: input.signal,
122
176
  });
123
- if (!response.ok) return { status: "error", reason: `The logo server answered ${response.status}` };
177
+
178
+ if (!response.ok) {
179
+ return {
180
+ status: "error",
181
+ reason: `The logo server answered ${response.status}`,
182
+ };
183
+ }
184
+
124
185
  const declared = Number(response.headers.get("content-length") ?? 0);
125
- if (declared > MAX_BIMI_SVG_BYTES) return { status: "invalid", reason: "The logo is larger than 32 KB" };
186
+
187
+ if (declared > MAX_BIMI_SVG_BYTES) {
188
+ return { status: "invalid", reason: "The logo is larger than 32 KB" };
189
+ }
190
+
126
191
  const text = await readCapped(response, MAX_BIMI_SVG_BYTES);
127
- if (text === null) return { status: "invalid", reason: "The logo is larger than 32 KB" };
192
+
193
+ if (text === null) {
194
+ return { status: "invalid", reason: "The logo is larger than 32 KB" };
195
+ }
196
+
128
197
  const checked = validateBimiSvg(text);
198
+
129
199
  if ("error" in checked) return { status: "invalid", reason: checked.error };
200
+
130
201
  return { status: "ok", reason: null, svg: checked.svg };
131
202
  } catch (error) {
132
- return { status: "error", reason: isAbortError(error) ? "The logo download timed out" : "The logo could not be downloaded" };
203
+ return {
204
+ status: "error",
205
+ reason: isAbortError(error)
206
+ ? "The logo download timed out"
207
+ : "The logo could not be downloaded",
208
+ };
133
209
  }
134
210
  }
135
211
 
136
- /**
137
- * Per-domain logo, cached in R2 for a day (an hour after a failure). The
138
- * From domain's record wins; the organizational domain is the fallback.
139
- */
140
- export async function resolveBimi(input: {
212
+ const BIMI_STATUSES = ["ok", "none", "invalid", "error"] as const;
213
+
214
+ /** What resolveBimi stores beside each cached logo in R2. */
215
+ const CachedBimiMetadata = z.object({
216
+ status: z.enum(BIMI_STATUSES) satisfies z.ZodType<BimiStatus>,
217
+ checkedAt: z.coerce.number(),
218
+ reason: z.string().optional(),
219
+ });
220
+
221
+ type BimiInput = {
141
222
  resolve: DnsResolver;
142
223
  fetch?: typeof fetch;
143
224
  bucket: R2Bucket;
@@ -145,28 +226,74 @@ export async function resolveBimi(input: {
145
226
  orgDomain: string | null;
146
227
  signal?: AbortSignal;
147
228
  now?: number;
148
- }): Promise<BimiResult> {
149
- const now = input.now ?? Date.now();
150
- const domains = [...new Set([input.fromDomain, input.orgDomain].filter((value): value is string => Boolean(value)))];
151
- let last: BimiResult | null = null;
152
- for (const domain of domains) {
153
- const key = bimiObjectKey(domain);
154
- const cached = await input.bucket.head(key).catch(() => null);
155
- const checkedAt = Number(cached?.customMetadata?.checkedAt ?? 0);
156
- const cachedStatus = cached?.customMetadata?.status as BimiStatus | undefined;
157
- const ttl = cachedStatus === "error" ? BIMI_ERROR_TTL_MS : BIMI_CACHE_TTL_MS;
158
- let result: Lookup;
159
- if (cached && cachedStatus && now - checkedAt < ttl) {
160
- result = { status: cachedStatus, reason: cached.customMetadata?.reason || null };
161
- } else {
162
- result = await lookup({ resolve: input.resolve, fetch: input.fetch ?? fetch, domain, signal: input.signal });
163
- await input.bucket.put(key, result.svg ?? "", {
164
- httpMetadata: { contentType: "image/svg+xml" },
165
- customMetadata: { status: result.status, checkedAt: String(now), reason: result.reason ?? "" },
166
- }).catch(() => undefined);
229
+ };
230
+
231
+ /** One domain's logo: the cached outcome while fresh, else a new lookup that is cached. */
232
+ async function domainBimi(
233
+ input: BimiInput,
234
+ domain: string,
235
+ now: number
236
+ ): Promise<BimiResult> {
237
+ const key = bimiObjectKey(domain);
238
+ const cached = await input.bucket.head(key).catch(() => null);
239
+ const metadata = CachedBimiMetadata.safeParse(cached?.customMetadata);
240
+
241
+ if (metadata.success) {
242
+ const { status, checkedAt, reason } = metadata.data;
243
+ const ttl = status === "error" ? BIMI_ERROR_TTL_MS : BIMI_CACHE_TTL_MS;
244
+
245
+ if (now - checkedAt < ttl) {
246
+ return { domain, status, reason: reason || null };
167
247
  }
168
- last = { domain, status: result.status, reason: result.reason };
169
- if (result.status !== "none") return last;
170
248
  }
171
- return last ?? { domain: input.fromDomain, status: "none", reason: "The domain publishes no BIMI record" };
249
+
250
+ const result = await lookup({
251
+ resolve: input.resolve,
252
+ fetch: input.fetch ?? fetch,
253
+ domain,
254
+ signal: input.signal,
255
+ });
256
+
257
+ await input.bucket
258
+ .put(key, result.svg ?? "", {
259
+ httpMetadata: { contentType: "image/svg+xml" },
260
+ customMetadata: {
261
+ status: result.status,
262
+ checkedAt: String(now),
263
+ reason: result.reason ?? "",
264
+ },
265
+ })
266
+ .catch(() => undefined);
267
+
268
+ return { domain, status: result.status, reason: result.reason };
269
+ }
270
+
271
+ /**
272
+ * Per-domain logo, cached in R2 for a day (an hour after a failure). The
273
+ * From domain's record wins; the organizational domain is the fallback.
274
+ */
275
+ export async function resolveBimi(input: BimiInput): Promise<BimiResult> {
276
+ const now = input.now ?? Date.now();
277
+
278
+ const [first, fallback] = [
279
+ ...new Set(
280
+ [input.fromDomain, input.orgDomain].filter((value): value is string =>
281
+ Boolean(value)
282
+ )
283
+ ),
284
+ ];
285
+
286
+ if (!first) {
287
+ return {
288
+ domain: input.fromDomain,
289
+ status: "none",
290
+ reason: "The domain publishes no BIMI record",
291
+ };
292
+ }
293
+
294
+ const primary = await domainBimi(input, first, now);
295
+
296
+ if (primary.status !== "none" || !fallback) return primary;
297
+
298
+ return domainBimi(input, fallback, now);
172
299
  }
@@ -0,0 +1,79 @@
1
+ import type { AppEnv, WorkspaceModule } from "@open-workspace/core/module";
2
+ import { timed } from "@open-workspace/core/module";
3
+ import type { Context } from "hono";
4
+ import { z } from "zod";
5
+
6
+ import { CONVERSATION_PAGE_SIZE } from "../../shared/mail";
7
+ import { parseMailPath } from "../../shared/mail-path";
8
+ import { mailboxStub } from "../mailbox";
9
+ import { mailboxListRowSchema, sessionMailboxListQuery } from "./access";
10
+ import type { MailboxListRow } from "./access";
11
+ import {
12
+ conversationPageView,
13
+ folderListView,
14
+ mailboxListView,
15
+ } from "./routes";
16
+
17
+ /**
18
+ * The mailbox and folder the mail screen at `pathname` opens: the ones in a
19
+ * /mail/... path, or the first mailbox's Inbox at "/". Other screens show none.
20
+ */
21
+ function startupLocation(pathname: string, rows: MailboxListRow[]) {
22
+ if (pathname === "/") {
23
+ return { mailboxId: rows[0]?.id ?? null, folder: "inbox" };
24
+ }
25
+
26
+ const route = parseMailPath(pathname);
27
+
28
+ return {
29
+ mailboxId: route?.mailboxId ?? null,
30
+ folder: route?.folder ?? "inbox",
31
+ };
32
+ }
33
+
34
+ /**
35
+ * Mail's startup data: the mailbox list (with unread counts, read in the
36
+ * session's D1 batch) and, for the mail screen, its mailbox's folders and the
37
+ * first page of the folder in the URL, from one mailbox call. A mailbox the
38
+ * person cannot open or an unknown folder is left out; the screen's own
39
+ * requests report those.
40
+ */
41
+ async function loadMailBootstrap(
42
+ c: Context<AppEnv>,
43
+ input: { pathname: string; search: URLSearchParams; companion: unknown }
44
+ ) {
45
+ // The rows of sessionMailboxListQuery, which core passes on untyped.
46
+ const rows = z.array(mailboxListRowSchema).parse(input.companion);
47
+ const { mailboxId, folder } = startupLocation(input.pathname, rows);
48
+ const access = rows.find((row) => row.id === mailboxId);
49
+
50
+ if (!access) return { ...mailboxListView(rows), mailbox: null };
51
+
52
+ const view = await timed(c, "do", "startup", () =>
53
+ mailboxStub(c.env, access.id).startupView(
54
+ c.get("user").id,
55
+ folder,
56
+ CONVERSATION_PAGE_SIZE
57
+ )
58
+ );
59
+
60
+ return {
61
+ ...mailboxListView(rows),
62
+ mailbox: {
63
+ id: access.id,
64
+ folder,
65
+ folders: folderListView(view.folders),
66
+ conversations: view.conversations
67
+ ? conversationPageView(view.conversations, access.address)
68
+ : null,
69
+ },
70
+ };
71
+ }
72
+
73
+ export type MailBootstrap = Awaited<ReturnType<typeof loadMailBootstrap>>;
74
+
75
+ export const mailBootstrap: NonNullable<WorkspaceModule["bootstrap"]> = {
76
+ companion: ({ db, tokenHash, now }) =>
77
+ sessionMailboxListQuery(db, tokenHash, now),
78
+ load: loadMailBootstrap,
79
+ };
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Reads a body stream to the end, or gives up (cancelling the stream) as soon
3
+ * as it grows past `limit` bytes: a remote server or a client cannot make the
4
+ * Worker buffer more than it allows.
5
+ */
6
+ export async function readCappedBody(
7
+ body: ReadableStream<Uint8Array>,
8
+ limit: number
9
+ ): Promise<Uint8Array | null> {
10
+ let total = 0;
11
+ let exceeded = false;
12
+
13
+ const capped = body.pipeThrough(
14
+ new TransformStream<Uint8Array, Uint8Array>({
15
+ transform(chunk, controller) {
16
+ total += chunk.byteLength;
17
+
18
+ if (total > limit) {
19
+ exceeded = true;
20
+ controller.error(new Error("The body is over the size limit"));
21
+
22
+ return;
23
+ }
24
+
25
+ controller.enqueue(chunk);
26
+ },
27
+ })
28
+ );
29
+
30
+ try {
31
+ return new Uint8Array(await new Response(capped).arrayBuffer());
32
+ } catch (error) {
33
+ if (exceeded) return null;
34
+ throw error;
35
+ }
36
+ }
@@ -1,5 +1,9 @@
1
1
  import type { InboundAuthentication } from "../../shared/mail-authentication";
2
- import type { DeliveryFacts, SecurityWarning, SenderIntel } from "../../shared/mail-sender-intel";
2
+ import type {
3
+ DeliveryFacts,
4
+ SecurityWarning,
5
+ SenderIntel,
6
+ } from "../../shared/mail-sender-intel";
3
7
 
4
8
  /** Compact, model-facing summary of what the receiver measured for a message. */
5
9
  export type ClassificationSignals = {
@@ -23,16 +27,15 @@ export type ClassificationSignals = {
23
27
  } | null;
24
28
  blocklists: {
25
29
  zen: string[];
26
- dbl: Array<{ domain: string; list: string }>;
30
+ dbl: { domain: string; list: string }[];
27
31
  } | null;
28
32
  firstTimeSender: boolean | null;
29
- warnings: Array<SecurityWarning["kind"]>;
33
+ warnings: SecurityWarning["kind"][];
30
34
  /** What people in this mailbox reported about the sender before (counts). */
31
35
  userFeedback: {
32
36
  spamReports: number;
33
- phishingReports: number;
34
37
  notSpam: number;
35
- /** Spam or phishing reports about other addresses at the same domain. */
38
+ /** Spam reports about other addresses at the same domain. */
36
39
  domainReports: number;
37
40
  } | null;
38
41
  /** Who the message was written for, the address it reached, and who forwarded it. */
@@ -46,7 +49,6 @@ export type ClassificationSignals = {
46
49
  /** The same counts from every other mailbox in the workspace. */
47
50
  workspaceFeedback: {
48
51
  spamReports: number;
49
- phishingReports: number;
50
52
  notSpam: number;
51
53
  domainReports: number;
52
54
  reportingMailboxes: number;
@@ -63,17 +65,21 @@ export function classificationSignals(input: {
63
65
  delivery?: DeliveryFacts | null;
64
66
  }): ClassificationSignals {
65
67
  const auth = input.authentication;
66
- const intel = input.intel;
68
+ const { intel } = input;
69
+
67
70
  return {
68
- authentication: auth && auth.verdict !== "unavailable"
69
- ? {
70
- verdict: auth.verdict,
71
- spf: auth.spf?.result ?? null,
72
- dkimAlignedPass: auth.dkim.some((dkim) => dkim.result === "pass" && dkim.aligned),
73
- dmarc: auth.dmarc?.result ?? null,
74
- dmarcPolicy: auth.dmarc?.policy ?? null,
75
- }
76
- : null,
71
+ authentication:
72
+ auth && auth.verdict !== "unavailable"
73
+ ? {
74
+ verdict: auth.verdict,
75
+ spf: auth.spf?.result ?? null,
76
+ dkimAlignedPass: auth.dkim.some(
77
+ (dkim) => dkim.result === "pass" && dkim.aligned
78
+ ),
79
+ dmarc: auth.dmarc?.result ?? null,
80
+ dmarcPolicy: auth.dmarc?.policy ?? null,
81
+ }
82
+ : null,
77
83
  cloudflareSpamScore: auth?.spamScore ?? null,
78
84
  sendingServer: intel?.ip
79
85
  ? {
@@ -90,15 +96,18 @@ export function classificationSignals(input: {
90
96
  blocklists: intel?.spamhaus
91
97
  ? {
92
98
  zen: intel.spamhaus.zen.listings.map((listing) => listing.list),
93
- dbl: intel.spamhaus.dbl.listings.map((listing) => ({ domain: listing.target, list: listing.list })),
99
+ dbl: intel.spamhaus.dbl.listings.map((listing) => ({
100
+ domain: listing.target,
101
+ list: listing.list,
102
+ })),
94
103
  }
95
104
  : null,
96
105
  firstTimeSender: input.firstTimeSender,
97
106
  warnings: input.warnings.map((warning) => warning.kind),
98
- userFeedback: input.feedback
99
- && Object.values(input.feedback).some((count) => count > 0)
100
- ? input.feedback
101
- : null,
107
+ userFeedback:
108
+ input.feedback && Object.values(input.feedback).some((count) => count > 0)
109
+ ? input.feedback
110
+ : null,
102
111
  delivery: input.delivery
103
112
  ? {
104
113
  deliveredTo: input.delivery.deliveredTo,
@@ -108,9 +117,10 @@ export function classificationSignals(input: {
108
117
  forwardedVia: input.delivery.forwardedVia,
109
118
  }
110
119
  : null,
111
- workspaceFeedback: input.workspaceFeedback
112
- && Object.values(input.workspaceFeedback).some((count) => count > 0)
113
- ? input.workspaceFeedback
114
- : null,
120
+ workspaceFeedback:
121
+ input.workspaceFeedback &&
122
+ Object.values(input.workspaceFeedback).some((count) => count > 0)
123
+ ? input.workspaceFeedback
124
+ : null,
115
125
  };
116
126
  }
@@ -1,3 +1,5 @@
1
+ import { z } from "zod";
2
+
1
3
  import type { ConversationCursorPosition } from "../mailbox";
2
4
 
3
5
  const CURSOR_VERSION = 1;
@@ -5,38 +7,47 @@ const CURSOR_VERSION = 1;
5
7
  function toBase64Url(value: string) {
6
8
  const bytes = new TextEncoder().encode(value);
7
9
  const binary = String.fromCharCode(...bytes);
8
- return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
10
+
11
+ return btoa(binary)
12
+ .replaceAll("+", "-")
13
+ .replaceAll("/", "_")
14
+ .replace(/[=]+$/u, "");
9
15
  }
10
16
 
11
17
  function fromBase64Url(value: string) {
12
18
  const base64 = value.replaceAll("-", "+").replaceAll("_", "/");
13
19
  const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
14
- const bytes = Uint8Array.from(atob(padded), (character) => character.charCodeAt(0));
20
+
21
+ const bytes = Uint8Array.from(atob(padded), (character) =>
22
+ character.charCodeAt(0)
23
+ );
24
+
15
25
  return new TextDecoder().decode(bytes);
16
26
  }
17
27
 
18
28
  export function encodeConversationCursor(position: ConversationCursorPosition) {
19
- return toBase64Url(JSON.stringify([
20
- CURSOR_VERSION,
21
- position.timelineAt,
22
- position.emailId,
23
- ]));
29
+ return toBase64Url(
30
+ JSON.stringify([CURSOR_VERSION, position.timelineAt, position.emailId])
31
+ );
24
32
  }
25
33
 
34
+ /** `[version, timelineAt, emailId]`, as encodeConversationCursor writes it. */
35
+ const ConversationCursor = z.tuple([
36
+ z.literal(CURSOR_VERSION),
37
+ z.int(),
38
+ z.string().min(1),
39
+ ]);
40
+
26
41
  export function decodeConversationCursor(value: string) {
27
42
  try {
28
- const decoded: unknown = JSON.parse(fromBase64Url(value));
29
- if (
30
- !Array.isArray(decoded)
31
- || decoded.length !== 3
32
- || decoded[0] !== CURSOR_VERSION
33
- || !Number.isSafeInteger(decoded[1])
34
- || typeof decoded[2] !== "string"
35
- || decoded[2].length === 0
36
- ) {
37
- return null;
38
- }
39
- return { timelineAt: decoded[1], emailId: decoded[2] };
43
+ const decoded = ConversationCursor.safeParse(
44
+ JSON.parse(fromBase64Url(value))
45
+ );
46
+
47
+ if (!decoded.success) return null;
48
+ const [, timelineAt, emailId] = decoded.data;
49
+
50
+ return { timelineAt, emailId };
40
51
  } catch {
41
52
  return null;
42
53
  }