@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,148 +1,202 @@
1
- import { zValidator } from "@hono/zod-validator";
2
- import { Hono, type Context } from "hono";
3
- import { normalizeBlockPattern, type ReportKind } from "../../shared/mail-feedback";
4
- import { createDb } from "@open-workspace/core/worker/db/client.ts";
5
- import type { AppEnv } from "@open-workspace/core/worker/env.ts";
6
- import { apiError } from "@open-workspace/core/worker/lib/http.ts";
7
- import { createId } from "@open-workspace/core/worker/lib/ids.ts";
8
- import { checkRateLimit } from "@open-workspace/core/worker/lib/rate-limit.ts";
1
+ import {
2
+ oauthScope,
3
+ zValidator,
4
+ apiError,
5
+ createId,
6
+ overRateLimit,
7
+ } from "@open-workspace/core/module";
8
+ import type { AppEnv } from "@open-workspace/core/module";
9
+ import { Hono } from "hono";
10
+ import type { Context } from "hono";
11
+
12
+ import { normalizeBlockPattern } from "../../shared/mail-feedback";
13
+ import {
14
+ MAIL_ORGANIZE_SCOPE,
15
+ MAIL_READ_SCOPE,
16
+ MAIL_SEND_SCOPE,
17
+ } from "../../shared/permissions";
9
18
  import { mailboxStub } from "../mailbox";
10
- import { MAIL_RULE_LIMIT_MESSAGE } from "../mailbox/rules";
11
19
  import type { Email } from "../mailbox/schema";
12
- import { getMailboxAccess } from "./access";
20
+ import { accessibleMailbox } from "./access";
13
21
  import { oneClickFetcher } from "./demo-routes";
14
- import { emailListKey, emailSecurity } from "./message-view";
22
+ import { emailListKey } from "./message-view";
15
23
  import { submitOutgoing } from "./outbound-service";
16
- import { recordReportedMessage, reportSnapshot } from "./reported-messages";
17
24
  import {
18
25
  blockPatternQuerySchema,
19
26
  blockSenderSchema,
20
27
  bulkReportSchema,
21
28
  mailboxQuerySchema,
22
- mailRuleSchema,
23
- reorderRulesSchema,
24
- reportMessageSchema,
25
29
  trustSenderSchema,
26
30
  unsubscribeSchema,
27
31
  } from "./schemas";
28
- import { workspaceIdentity } from "./security-settings";
29
- import { storedSenderIntel } from "./sender-intel";
30
- import { oneClickHost, parseMailtoUnsubscribe, postOneClick } from "./unsubscribe";
31
- import { recordWorkspaceFeedback, workspaceBlockPatterns } from "./workspace-safety";
32
-
33
- async function mailboxAccess(env: Env, userId: string, mailboxId: string) {
34
- return getMailboxAccess(createDb(env.DB), userId, mailboxId);
35
- }
32
+ import {
33
+ oneClickHost,
34
+ parseMailtoUnsubscribe,
35
+ postOneClick,
36
+ } from "./unsubscribe";
37
+ import {
38
+ recordWorkspaceFeedback,
39
+ workspaceBlockPatterns,
40
+ } from "./workspace-safety";
36
41
 
37
42
  function forbidden(c: Context<AppEnv>) {
38
43
  return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
39
44
  }
40
45
 
41
- /** Report spam or phishing for one message. Phishing also opens an admin report. */
46
+ /** Report one message as spam: Spam folder, sender feedback here and workspace-wide. */
42
47
  async function reportOne(input: {
43
48
  env: Env;
44
49
  mailboxId: string;
45
50
  userId: string;
46
51
  email: Email;
47
- kind: ReportKind;
48
52
  }) {
49
- const mailbox = mailboxStub(input.env, input.mailboxId);
50
- const result = await mailbox.reportMessage({ emailId: input.email.id, kind: input.kind, userId: input.userId });
53
+ const result = await mailboxStub(input.env, input.mailboxId).reportMessage({
54
+ emailId: input.email.id,
55
+ userId: input.userId,
56
+ });
57
+
51
58
  if (!result) return null;
52
59
  const sender = result.email.fromJson[0]?.address;
60
+
53
61
  if (sender) {
54
62
  await recordWorkspaceFeedback(input.env.DB, {
55
63
  mailboxId: input.mailboxId,
56
64
  emailId: result.email.id,
57
65
  address: sender,
58
- label: input.kind,
59
- }).catch((error) => console.error(`Could not share the report for ${result.email.id}`, error));
60
- }
61
- let reportId: string | null = null;
62
- if (input.kind === "phishing") {
63
- const email = result.email;
64
- const address = email.fromJson[0]?.address ?? "";
65
- const [identity, history, bodyHtml] = await Promise.all([
66
- workspaceIdentity(input.env.DB),
67
- mailbox.getSenderHistory(address ? [address] : []),
68
- email.bodyHtmlR2Key
69
- ? input.env.MAIL_STORAGE.get(email.bodyHtmlR2Key).then((object) => object?.text() ?? null)
70
- : Promise.resolve(null),
71
- ]);
72
- reportId = await recordReportedMessage(input.env.DB, {
73
- mailboxId: input.mailboxId,
74
- email,
75
- reporterUserId: input.userId,
76
- snapshot: reportSnapshot({
77
- email,
78
- security: emailSecurity(email, identity, history),
79
- intel: storedSenderIntel(email.senderIntelJson),
80
- bodyHtml,
81
- }),
82
- });
66
+ label: "spam",
67
+ }).catch((error) =>
68
+ console.error(`Could not share the report for ${result.email.id}`, error)
69
+ );
83
70
  }
84
- return { moved: result.moved, reportId };
71
+
72
+ return { moved: result.moved };
85
73
  }
86
74
 
87
75
  export const mailSafetyRoutes = new Hono<AppEnv>()
88
76
  .post(
89
77
  "/messages/:id/unsubscribe",
78
+ oauthScope(MAIL_SEND_SCOPE),
90
79
  zValidator("query", mailboxQuerySchema),
91
80
  zValidator("json", unsubscribeSchema),
92
81
  async (c) => {
93
82
  const { mailboxId } = c.req.valid("query");
94
83
  const user = c.get("user");
95
- const access = await mailboxAccess(c.env, user.id, mailboxId);
84
+ const access = await accessibleMailbox(c, mailboxId, "read");
85
+
96
86
  if (!access) return forbidden(c);
97
87
  const mailbox = mailboxStub(c.env, mailboxId);
98
88
  const stored = await mailbox.getEmail(c.req.param("id"));
99
- if (!stored || stored.direction !== "incoming") return apiError(c, 404, "NOT_FOUND", "Message not found");
89
+
90
+ if (!stored || stored.direction !== "incoming") {
91
+ return apiError(c, 404, "NOT_FOUND", "Message not found");
92
+ }
93
+
100
94
  // Stored at ingestion from the original; never taken from the client.
101
95
  const email = stored;
102
96
  const methods = email.listUnsubscribeJson;
103
97
  const listKey = emailListKey(email);
98
+
104
99
  if (!methods || !listKey || (!methods.httpsUrl && !methods.mailto)) {
105
- return apiError(c, 409, "CONFLICT", "This message has no unsubscribe option");
100
+ return apiError(
101
+ c,
102
+ 409,
103
+ "CONFLICT",
104
+ "This message has no unsubscribe option"
105
+ );
106
106
  }
107
- const limit = await checkRateLimit(c.env.DB, {
108
- action: "mail-unsubscribe",
109
- identifier: user.id,
110
- limit: 20,
111
- windowMs: 60_000,
112
- });
113
- if (!limit.allowed) {
114
- c.header("retry-after", String(limit.retryAfterSeconds));
115
- return apiError(c, 429, "RATE_LIMITED", "Too many unsubscribe requests");
107
+
108
+ const limitExceeded = await overRateLimit(
109
+ c,
110
+ "RATE_LIMIT_20",
111
+ "mail-unsubscribe",
112
+ user.id
113
+ );
114
+
115
+ if (limitExceeded) {
116
+ return apiError(
117
+ c,
118
+ 429,
119
+ "RATE_LIMITED",
120
+ "Too many unsubscribe requests"
121
+ );
116
122
  }
123
+
117
124
  const record = (
118
125
  method: "one_click" | "mailto" | "link",
119
126
  status: "done" | "requested" | "opened" | "failed",
120
127
  target: string | null,
121
- detail: string | null,
122
- ) => mailbox.recordUnsubscription({ listKey, emailId: email.id, method, status, target, detail, userId: user.id });
128
+ detail: string | null
129
+ ) =>
130
+ mailbox.recordUnsubscription({
131
+ listKey,
132
+ emailId: email.id,
133
+ method,
134
+ status,
135
+ target,
136
+ detail,
137
+ userId: user.id,
138
+ });
123
139
 
124
140
  if (c.req.valid("json").method === "link") {
125
- if (!methods.httpsUrl) return apiError(c, 409, "CONFLICT", "This message has no unsubscribe page");
126
- const unsubscription = await record("link", "opened", oneClickHost(methods.httpsUrl), null);
127
- return c.json({ ok: true as const, outcome: "opened" as const, unsubscription, url: methods.httpsUrl, detail: null });
141
+ if (!methods.httpsUrl) {
142
+ return apiError(
143
+ c,
144
+ 409,
145
+ "CONFLICT",
146
+ "This message has no unsubscribe page"
147
+ );
148
+ }
149
+
150
+ const unsubscription = await record(
151
+ "link",
152
+ "opened",
153
+ oneClickHost(methods.httpsUrl),
154
+ null
155
+ );
156
+
157
+ return c.json({
158
+ ok: true as const,
159
+ outcome: "opened" as const,
160
+ unsubscription,
161
+ url: methods.httpsUrl,
162
+ detail: null,
163
+ });
128
164
  }
129
165
 
130
166
  let detail: string | null = null;
167
+
131
168
  if (methods.oneClick && methods.httpsUrl) {
132
- const result = await postOneClick(methods.httpsUrl, oneClickFetcher(c.env));
169
+ const result = await postOneClick(
170
+ methods.httpsUrl,
171
+ oneClickFetcher(c.env)
172
+ );
173
+
133
174
  if (result.ok) {
134
175
  const unsubscription = await record(
135
176
  "one_click",
136
177
  "done",
137
178
  oneClickHost(methods.httpsUrl),
138
- result.redirected ? `Answered ${result.status} instead of 2xx` : null,
179
+ result.redirected
180
+ ? `Answered ${result.status} instead of 2xx`
181
+ : null
139
182
  );
140
- return c.json({ ok: true as const, outcome: "done" as const, unsubscription, url: null, detail: null });
183
+
184
+ return c.json({
185
+ ok: true as const,
186
+ outcome: "done" as const,
187
+ unsubscription,
188
+ url: null,
189
+ detail: null,
190
+ });
141
191
  }
192
+
142
193
  detail = result.detail;
143
194
  }
144
195
 
145
- const mailto = methods.mailto ? parseMailtoUnsubscribe(methods.mailto) : null;
196
+ const mailto = methods.mailto
197
+ ? parseMailtoUnsubscribe(methods.mailto)
198
+ : null;
199
+
146
200
  if (mailto && access.canSend) {
147
201
  const submission = await submitOutgoing({
148
202
  env: c.env,
@@ -166,184 +220,258 @@ export const mailSafetyRoutes = new Hono<AppEnv>()
166
220
  fromName: access.displayName,
167
221
  defer: (task) => c.executionCtx.waitUntil(task),
168
222
  });
223
+
169
224
  const failed = submission.email.transportState === "failed";
225
+
170
226
  const unsubscription = await record(
171
227
  "mailto",
172
228
  failed ? "failed" : "requested",
173
229
  mailto.to,
174
- failed ? submission.email.transportError : detail,
230
+ failed ? submission.email.transportError : detail
175
231
  );
232
+
176
233
  if (!failed) {
177
- return c.json({ ok: true as const, outcome: "requested" as const, unsubscription, url: null, detail });
234
+ return c.json({
235
+ ok: true as const,
236
+ outcome: "requested" as const,
237
+ unsubscription,
238
+ url: null,
239
+ detail,
240
+ });
178
241
  }
179
- detail = submission.email.transportError ?? "The unsubscribe email could not be sent";
242
+
243
+ detail =
244
+ submission.email.transportError ??
245
+ "The unsubscribe email could not be sent";
180
246
  }
247
+
181
248
  if (methods.httpsUrl) {
182
249
  // Opening the page is left to the person, in a new tab, after this answer.
183
- return c.json({ ok: true as const, outcome: "link" as const, unsubscription: null, url: methods.httpsUrl, detail });
250
+ return c.json({
251
+ ok: true as const,
252
+ outcome: "link" as const,
253
+ unsubscription: null,
254
+ url: methods.httpsUrl,
255
+ detail,
256
+ });
184
257
  }
258
+
185
259
  if (mailto && !access.canSend) {
186
- return apiError(c, 403, "FORBIDDEN", "Unsubscribing by email requires send access to this mailbox");
260
+ return apiError(
261
+ c,
262
+ 403,
263
+ "FORBIDDEN",
264
+ "Unsubscribing by email requires send access to this mailbox"
265
+ );
187
266
  }
188
- const unsubscription = await record(methods.oneClick ? "one_click" : "mailto", "failed", null, detail);
189
- return c.json({ ok: true as const, outcome: "failed" as const, unsubscription, url: null, detail });
190
- },
267
+
268
+ const unsubscription = await record(
269
+ methods.oneClick ? "one_click" : "mailto",
270
+ "failed",
271
+ null,
272
+ detail
273
+ );
274
+
275
+ return c.json({
276
+ ok: true as const,
277
+ outcome: "failed" as const,
278
+ unsubscription,
279
+ url: null,
280
+ detail,
281
+ });
282
+ }
191
283
  )
192
284
  .post(
193
285
  "/messages/:id/report",
286
+ oauthScope(MAIL_ORGANIZE_SCOPE),
194
287
  zValidator("query", mailboxQuerySchema),
195
- zValidator("json", reportMessageSchema),
196
288
  async (c) => {
197
289
  const { mailboxId } = c.req.valid("query");
198
290
  const user = c.get("user");
199
- const access = await mailboxAccess(c.env, user.id, mailboxId);
200
- if (!access) return forbidden(c);
201
- const input = c.req.valid("json");
202
- const email = await mailboxStub(c.env, mailboxId).getEmail(c.req.param("id"));
203
- if (!email || email.direction !== "incoming") return apiError(c, 404, "NOT_FOUND", "Message not found");
291
+
292
+ if (!(await accessibleMailbox(c, mailboxId, "read"))) return forbidden(c);
293
+
294
+ const email = await mailboxStub(c.env, mailboxId).getEmail(
295
+ c.req.param("id")
296
+ );
297
+
298
+ if (!email || email.direction !== "incoming") {
299
+ return apiError(c, 404, "NOT_FOUND", "Message not found");
300
+ }
301
+
204
302
  const result = await reportOne({
205
303
  env: c.env,
206
304
  mailboxId,
207
305
  userId: user.id,
208
306
  email,
209
- kind: input.kind,
210
307
  });
308
+
211
309
  if (!result) return apiError(c, 404, "NOT_FOUND", "Message not found");
310
+
212
311
  return c.json({ ok: true as const, ...result });
213
- },
312
+ }
214
313
  )
215
314
  .post(
216
315
  "/conversations/report",
316
+ oauthScope(MAIL_ORGANIZE_SCOPE),
217
317
  zValidator("query", mailboxQuerySchema),
218
318
  zValidator("json", bulkReportSchema),
219
319
  async (c) => {
220
320
  const { mailboxId } = c.req.valid("query");
221
321
  const user = c.get("user");
222
- const access = await mailboxAccess(c.env, user.id, mailboxId);
322
+ const access = await accessibleMailbox(c, mailboxId, "read");
323
+
223
324
  if (!access) return forbidden(c);
224
325
  const input = c.req.valid("json");
225
- const messages = await mailboxStub(c.env, mailboxId).latestIncomingEmails(input.conversationIds);
226
- let reported = 0;
227
- for (const email of messages) {
228
- const result = await reportOne({
229
- env: c.env,
326
+
327
+ const messages = await mailboxStub(c.env, mailboxId).latestIncomingEmails(
328
+ input.conversationIds
329
+ );
330
+
331
+ // Each report concerns its own message; the mailbox serializes them.
332
+ const results = await Promise.all(
333
+ messages.map((email) =>
334
+ reportOne({ env: c.env, mailboxId, userId: user.id, email })
335
+ )
336
+ );
337
+
338
+ const reported = results.filter(Boolean).length;
339
+
340
+ return c.json({ ok: true as const, reportedCount: reported });
341
+ }
342
+ )
343
+ .post(
344
+ "/messages/:id/not-spam",
345
+ oauthScope(MAIL_ORGANIZE_SCOPE),
346
+ zValidator("query", mailboxQuerySchema),
347
+ async (c) => {
348
+ const { mailboxId } = c.req.valid("query");
349
+ const user = c.get("user");
350
+
351
+ if (!(await accessibleMailbox(c, mailboxId, "read"))) return forbidden(c);
352
+ const emailId = c.req.param("id");
353
+
354
+ const result = await mailboxStub(c.env, mailboxId).markNotSpam({
355
+ emailId,
356
+ userId: user.id,
357
+ });
358
+
359
+ if (!result) return apiError(c, 404, "NOT_FOUND", "Message not found");
360
+
361
+ if (result.address) {
362
+ await recordWorkspaceFeedback(c.env.DB, {
230
363
  mailboxId,
231
- userId: user.id,
232
- email,
233
- kind: input.kind,
234
- });
235
- if (result) reported += 1;
364
+ emailId,
365
+ address: result.address,
366
+ label: "not_spam",
367
+ }).catch((error) =>
368
+ console.error(
369
+ `Could not share the not-spam verdict for ${emailId}`,
370
+ error
371
+ )
372
+ );
236
373
  }
237
- return c.json({ ok: true as const, reportedCount: reported });
238
- },
374
+
375
+ return c.json({ ok: true as const, restored: result.restored });
376
+ }
239
377
  )
240
- .post("/messages/:id/not-spam", zValidator("query", mailboxQuerySchema), async (c) => {
241
- const { mailboxId } = c.req.valid("query");
242
- const user = c.get("user");
243
- if (!await mailboxAccess(c.env, user.id, mailboxId)) return forbidden(c);
244
- const emailId = c.req.param("id");
245
- const result = await mailboxStub(c.env, mailboxId).markNotSpam({ emailId, userId: user.id });
246
- if (!result) return apiError(c, 404, "NOT_FOUND", "Message not found");
247
- if (result.address) {
248
- await recordWorkspaceFeedback(c.env.DB, { mailboxId, emailId, address: result.address, label: "not_spam" })
249
- .catch((error) => console.error(`Could not share the not-spam verdict for ${emailId}`, error));
378
+ .get(
379
+ "/mailboxes/:id/blocked-senders",
380
+ oauthScope(MAIL_READ_SCOPE),
381
+ async (c) => {
382
+ const mailboxId = c.req.param("id");
383
+
384
+ if (!(await accessibleMailbox(c, mailboxId, "read"))) return forbidden(c);
385
+
386
+ const [blocked, workspace] = await Promise.all([
387
+ mailboxStub(c.env, mailboxId).listBlockedSenders(),
388
+ workspaceBlockPatterns(c.env.DB),
389
+ ]);
390
+
391
+ return c.json({
392
+ ok: true as const,
393
+ blocked,
394
+ workspace: [...workspace].map(([pattern, at]) => ({
395
+ pattern,
396
+ blockedAt: at,
397
+ })),
398
+ });
250
399
  }
251
- return c.json({ ok: true as const, restored: result.restored });
252
- })
253
- .get("/mailboxes/:id/blocked-senders", async (c) => {
254
- const mailboxId = c.req.param("id");
255
- if (!await mailboxAccess(c.env, c.get("user").id, mailboxId)) return forbidden(c);
256
- const [blocked, workspace] = await Promise.all([
257
- mailboxStub(c.env, mailboxId).listBlockedSenders(),
258
- workspaceBlockPatterns(c.env.DB),
259
- ]);
260
- return c.json({
261
- ok: true as const,
262
- blocked,
263
- workspace: [...workspace].map(([pattern, at]) => ({ pattern, blockedAt: at })),
264
- });
265
- })
266
- .post("/mailboxes/:id/blocked-senders", zValidator("json", blockSenderSchema), async (c) => {
267
- const mailboxId = c.req.param("id");
268
- const access = await mailboxAccess(c.env, c.get("user").id, mailboxId);
269
- if (!access) return forbidden(c);
270
- const input = c.req.valid("json");
271
- const pattern = normalizeBlockPattern(input.pattern);
272
- if (!pattern) return apiError(c, 400, "BAD_REQUEST", "Enter an email address or a domain");
273
- const own = access.address.toLocaleLowerCase();
274
- if (pattern === own || own.endsWith(pattern)) {
275
- return apiError(c, 400, "BAD_REQUEST", "This mailbox cannot block its own address or domain");
400
+ )
401
+ .post(
402
+ "/mailboxes/:id/blocked-senders",
403
+ oauthScope(MAIL_ORGANIZE_SCOPE),
404
+ zValidator("json", blockSenderSchema),
405
+ async (c) => {
406
+ const mailboxId = c.req.param("id");
407
+ const access = await accessibleMailbox(c, mailboxId, "read");
408
+
409
+ if (!access) return forbidden(c);
410
+ const input = c.req.valid("json");
411
+ const pattern = normalizeBlockPattern(input.pattern);
412
+
413
+ if (!pattern) {
414
+ return apiError(
415
+ c,
416
+ 400,
417
+ "BAD_REQUEST",
418
+ "Enter an email address or a domain"
419
+ );
420
+ }
421
+
422
+ const own = access.address.toLocaleLowerCase();
423
+
424
+ if (pattern === own || own.endsWith(pattern)) {
425
+ return apiError(
426
+ c,
427
+ 400,
428
+ "BAD_REQUEST",
429
+ "This mailbox cannot block its own address or domain"
430
+ );
431
+ }
432
+
433
+ const result = await mailboxStub(c.env, mailboxId).blockSender(
434
+ pattern,
435
+ input.moveExisting
436
+ );
437
+
438
+ return c.json({ ok: true as const, ...result });
276
439
  }
277
- const result = await mailboxStub(c.env, mailboxId).blockSender(pattern, input.moveExisting);
278
- return c.json({ ok: true as const, ...result });
279
- })
440
+ )
280
441
  .delete(
281
442
  "/mailboxes/:id/blocked-senders",
443
+ oauthScope(MAIL_ORGANIZE_SCOPE),
282
444
  zValidator("query", blockPatternQuerySchema),
283
445
  async (c) => {
284
446
  const mailboxId = c.req.param("id");
285
- if (!await mailboxAccess(c.env, c.get("user").id, mailboxId)) return forbidden(c);
447
+
448
+ if (!(await accessibleMailbox(c, mailboxId, "read"))) return forbidden(c);
286
449
  const pattern = normalizeBlockPattern(c.req.valid("query").pattern);
287
- if (!pattern || !await mailboxStub(c.env, mailboxId).unblockSender(pattern)) {
450
+
451
+ if (
452
+ !pattern ||
453
+ !(await mailboxStub(c.env, mailboxId).unblockSender(pattern))
454
+ ) {
288
455
  return apiError(c, 404, "NOT_FOUND", "Blocked sender not found");
289
456
  }
457
+
290
458
  return c.json({ ok: true as const });
291
- },
292
- )
293
- .put("/mailboxes/:id/trusted-senders", zValidator("json", trustSenderSchema), async (c) => {
294
- const mailboxId = c.req.param("id");
295
- if (!await mailboxAccess(c.env, c.get("user").id, mailboxId)) return forbidden(c);
296
- const input = c.req.valid("json");
297
- await mailboxStub(c.env, mailboxId).setSenderTrusted(input.address, input.trusted);
298
- return c.json({ ok: true as const });
299
- })
300
- .get("/mailboxes/:id/rules", async (c) => {
301
- const mailboxId = c.req.param("id");
302
- if (!await mailboxAccess(c.env, c.get("user").id, mailboxId)) return forbidden(c);
303
- return c.json({ ok: true as const, rules: await mailboxStub(c.env, mailboxId).listRules() });
304
- })
305
- .post("/mailboxes/:id/rules", zValidator("json", mailRuleSchema), async (c) => {
306
- const mailboxId = c.req.param("id");
307
- if (!await mailboxAccess(c.env, c.get("user").id, mailboxId)) return forbidden(c);
308
- try {
309
- const rule = await mailboxStub(c.env, mailboxId).createRule(c.req.valid("json"));
310
- return c.json({ ok: true as const, rule }, 201);
311
- } catch (error) {
312
- // Errors cross the Durable Object boundary without their class.
313
- if (error instanceof Error && error.message.startsWith(MAIL_RULE_LIMIT_MESSAGE)) {
314
- return apiError(c, 409, "CONFLICT", error.message);
315
- }
316
- throw error;
317
- }
318
- })
319
- .put("/mailboxes/:id/rules/:ruleId", zValidator("json", mailRuleSchema), async (c) => {
320
- const mailboxId = c.req.param("id");
321
- if (!await mailboxAccess(c.env, c.get("user").id, mailboxId)) return forbidden(c);
322
- const rule = await mailboxStub(c.env, mailboxId).updateRule(c.req.param("ruleId"), c.req.valid("json"));
323
- if (!rule) return apiError(c, 404, "NOT_FOUND", "Rule not found");
324
- return c.json({ ok: true as const, rule });
325
- })
326
- .delete("/mailboxes/:id/rules/:ruleId", async (c) => {
327
- const mailboxId = c.req.param("id");
328
- if (!await mailboxAccess(c.env, c.get("user").id, mailboxId)) return forbidden(c);
329
- if (!await mailboxStub(c.env, mailboxId).deleteRule(c.req.param("ruleId"))) {
330
- return apiError(c, 404, "NOT_FOUND", "Rule not found");
331
459
  }
332
- return c.json({ ok: true as const });
333
- })
334
- .put("/mailboxes/:id/rules-order", zValidator("json", reorderRulesSchema), async (c) => {
335
- const mailboxId = c.req.param("id");
336
- if (!await mailboxAccess(c.env, c.get("user").id, mailboxId)) return forbidden(c);
337
- if (!await mailboxStub(c.env, mailboxId).reorderRules(c.req.valid("json").ruleIds)) {
338
- return apiError(c, 409, "CONFLICT", "Rules changed; refresh and try again");
460
+ )
461
+ .put(
462
+ "/mailboxes/:id/trusted-senders",
463
+ oauthScope(MAIL_ORGANIZE_SCOPE),
464
+ zValidator("json", trustSenderSchema),
465
+ async (c) => {
466
+ const mailboxId = c.req.param("id");
467
+
468
+ if (!(await accessibleMailbox(c, mailboxId, "read"))) return forbidden(c);
469
+ const input = c.req.valid("json");
470
+ await mailboxStub(c.env, mailboxId).setSenderTrusted(
471
+ input.address,
472
+ input.trusted
473
+ );
474
+
475
+ return c.json({ ok: true as const });
339
476
  }
340
- return c.json({ ok: true as const });
341
- })
342
- .post("/mailboxes/:id/rules/:ruleId/apply", async (c) => {
343
- const mailboxId = c.req.param("id");
344
- const user = c.get("user");
345
- if (!await mailboxAccess(c.env, user.id, mailboxId)) return forbidden(c);
346
- const result = await mailboxStub(c.env, mailboxId).applyRuleToExisting(c.req.param("ruleId"), user.id);
347
- if (!result) return apiError(c, 404, "NOT_FOUND", "Rule not found");
348
- return c.json({ ok: true as const, ...result });
349
- });
477
+ );