@open-workspace/email 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/README.md +23 -20
  2. package/alchemy/index.ts +273 -0
  3. package/drizzle/mailbox/0000_puzzling_dracula.sql +149 -0
  4. package/drizzle/mailbox/0001_mute_jack_flag.sql +12 -0
  5. package/drizzle/mailbox/meta/0000_snapshot.json +1002 -0
  6. package/drizzle/mailbox/meta/0001_snapshot.json +1002 -0
  7. package/drizzle/mailbox/meta/_journal.json +20 -0
  8. package/drizzle/mailbox/migrations.js +12 -0
  9. package/index.ts +3 -1
  10. package/migrations/0000_dry_moon_knight.sql +77 -0
  11. package/migrations/meta/0000_snapshot.json +248 -106
  12. package/migrations/meta/_journal.json +2 -2
  13. package/package.json +74 -68
  14. package/shared/attachment-preview.ts +37 -27
  15. package/shared/folder-order.ts +106 -0
  16. package/shared/mail-authentication.ts +8 -3
  17. package/shared/mail-feedback.ts +18 -25
  18. package/shared/mail-headers.ts +114 -39
  19. package/shared/mail-import.ts +38 -0
  20. package/shared/mail-path.ts +42 -0
  21. package/shared/mail-received.ts +174 -31
  22. package/shared/mail-remote.ts +59 -2
  23. package/shared/mail-sender-intel.ts +22 -4
  24. package/shared/mail.ts +78 -26
  25. package/shared/module.ts +33 -0
  26. package/shared/office-preview.ts +14 -2
  27. package/shared/pdfjs-assets.ts +35 -0
  28. package/shared/permissions.ts +73 -0
  29. package/shared/webhooks.ts +41 -0
  30. package/src/admin/blocked-senders.tsx +189 -0
  31. package/src/client.tsx +97 -0
  32. package/src/lib/mail-api.ts +9 -0
  33. package/src/mail/attachment-preview-dialog.tsx +161 -0
  34. package/src/mail/blocked-senders.tsx +138 -0
  35. package/src/mail/compose-window-chrome.tsx +194 -0
  36. package/src/mail/compose-window.tsx +486 -0
  37. package/src/mail/composer-asset-bookmarks.ts +409 -0
  38. package/src/mail/composer-asset.tsx +229 -0
  39. package/src/mail/composer-attachment-list.tsx +138 -0
  40. package/src/mail/composer-editor-document.ts +65 -0
  41. package/src/mail/composer-editor.tsx +284 -0
  42. package/src/mail/composer-linked-attachment-text.ts +12 -0
  43. package/src/mail/composer-recipient-fields.tsx +165 -0
  44. package/src/mail/composer-recipients.ts +208 -0
  45. package/src/mail/composer-session.ts +562 -0
  46. package/src/mail/composer-toolbar.tsx +303 -0
  47. package/src/mail/composer-upload-client.ts +105 -0
  48. package/src/mail/composer-upload-progress.ts +53 -0
  49. package/src/mail/conversation-list.tsx +550 -0
  50. package/src/mail/conversation-loading-skeleton.tsx +119 -0
  51. package/src/mail/conversation-message.tsx +346 -0
  52. package/src/mail/conversation-reply.tsx +470 -0
  53. package/src/mail/conversation-selection-toolbar.tsx +322 -0
  54. package/src/mail/conversation-view.tsx +437 -0
  55. package/src/mail/delivery-indicator.tsx +272 -0
  56. package/src/mail/email-html-body.tsx +203 -0
  57. package/src/mail/folder-glyph.tsx +46 -0
  58. package/src/mail/folder-manager.tsx +532 -0
  59. package/src/mail/format-bytes.ts +7 -0
  60. package/src/mail/mail-app-bar.tsx +253 -0
  61. package/src/mail/mail-background.tsx +12 -0
  62. package/src/mail/mail-dock.tsx +137 -0
  63. package/src/mail/mail-folders.ts +44 -0
  64. package/src/mail/mail-layout.css +236 -0
  65. package/src/mail/mail-location.ts +73 -0
  66. package/src/mail/mail-mailbox-sheet.tsx +275 -0
  67. package/src/mail/mail-nav-rail.tsx +129 -0
  68. package/src/mail/mail-nav.tsx +324 -0
  69. package/src/mail/mail-prefetch.ts +59 -0
  70. package/src/mail/mail-primitives.tsx +66 -0
  71. package/src/mail/mail-queries.ts +209 -0
  72. package/src/mail/mail-query-cache.ts +486 -0
  73. package/src/mail/mail-seed.ts +47 -0
  74. package/src/mail/mail-shell.tsx +126 -0
  75. package/src/mail/mailbox-ai-settings.tsx +185 -0
  76. package/src/mail/mailbox-realtime.tsx +251 -0
  77. package/src/mail/mailbox-route.tsx +15 -0
  78. package/src/mail/message-actions.tsx +353 -0
  79. package/src/mail/message-attachments.tsx +200 -0
  80. package/src/mail/message-format.ts +75 -0
  81. package/src/mail/message-header.tsx +260 -0
  82. package/src/mail/message-translation.tsx +225 -0
  83. package/src/mail/original-message-sheet.tsx +619 -0
  84. package/src/mail/original-message.ts +191 -0
  85. package/src/mail/outbound-notification.ts +53 -0
  86. package/src/mail/pane-splitter.tsx +117 -0
  87. package/src/mail/pdf-preview-toolbar.tsx +152 -0
  88. package/src/mail/pdf-preview.css +44 -0
  89. package/src/mail/pdf-preview.tsx +156 -0
  90. package/src/mail/pdf-translation-layout.ts +95 -0
  91. package/src/mail/print-message.ts +92 -0
  92. package/src/mail/reader-pane.tsx +535 -0
  93. package/src/mail/recipient-combobox.tsx +335 -0
  94. package/src/mail/recipient-field-row.tsx +34 -0
  95. package/src/mail/reply-to-warning.tsx +50 -0
  96. package/src/mail/sanitize-email-html.ts +430 -0
  97. package/src/mail/sender-actions.tsx +149 -0
  98. package/src/mail/sender-authentication.tsx +485 -0
  99. package/src/mail/sender-dialogs.tsx +384 -0
  100. package/src/mail/sender-security.tsx +545 -0
  101. package/src/mail/toolbar-tooltip.tsx +29 -0
  102. package/src/mail/translation-html.ts +49 -0
  103. package/src/mail/translation-language.ts +21 -0
  104. package/src/mail/types.ts +53 -0
  105. package/src/mail/unread-document-indicator.tsx +60 -0
  106. package/src/mail/use-compose-submission.ts +208 -0
  107. package/src/mail/use-composer-attachment-preflight.ts +184 -0
  108. package/src/mail/use-composer-submission.ts +117 -0
  109. package/src/mail/use-conversation-selection.ts +186 -0
  110. package/src/mail/use-mail-controller.ts +427 -0
  111. package/src/mail/use-mail-data.ts +279 -0
  112. package/src/mail/use-mail-safety.ts +155 -0
  113. package/src/mail/use-mail-send.ts +142 -0
  114. package/src/mail/use-pdf-translation-overlay.ts +156 -0
  115. package/src/mail/use-pdf-translation.ts +100 -0
  116. package/src/mail/use-pdf-viewer.ts +215 -0
  117. package/src/mail/use-reply-submission.ts +114 -0
  118. package/src/mail/use-sanitized-email-html.ts +20 -0
  119. package/src/mail/use-visible-message-read.ts +138 -0
  120. package/src/pwa/push-subscription.ts +151 -0
  121. package/src/settings/mail-apps-page.tsx +235 -0
  122. package/src/settings/notifications-page.tsx +291 -0
  123. package/worker/admin/blocked-sender-routes.ts +166 -0
  124. package/worker/admin/schemas.ts +11 -0
  125. package/worker/bindings.d.ts +14 -10
  126. package/worker/db/schema.ts +90 -34
  127. package/worker/jmap/eventsource.ts +169 -0
  128. package/worker/jmap/methods.ts +1716 -361
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +207 -0
  131. package/worker/jmap/routes.ts +448 -86
  132. package/worker/mail/access.ts +258 -21
  133. package/worker/mail/ai-classification.ts +36 -20
  134. package/worker/mail/ai-translation.ts +13 -6
  135. package/worker/mail/auth-headers.ts +395 -137
  136. package/worker/mail/bimi.ts +200 -73
  137. package/worker/mail/bootstrap.ts +79 -0
  138. package/worker/mail/capped-body.ts +36 -0
  139. package/worker/mail/classification-signals.ts +35 -25
  140. package/worker/mail/conversation-cursor.ts +30 -19
  141. package/worker/mail/delivery-events.ts +88 -62
  142. package/worker/mail/delivery-facts.ts +46 -10
  143. package/worker/mail/demo-routes.ts +34 -10
  144. package/worker/mail/doh.ts +62 -23
  145. package/worker/mail/downloads.ts +75 -40
  146. package/worker/mail/edge-cache.ts +155 -0
  147. package/worker/mail/header-metadata.ts +84 -52
  148. package/worker/mail/impersonation.ts +160 -38
  149. package/worker/mail/import-routes.ts +313 -0
  150. package/worker/mail/inbound-delivery.ts +19 -9
  151. package/worker/mail/inbound-threading.ts +18 -8
  152. package/worker/mail/inbound.ts +82 -40
  153. package/worker/mail/ip-intel.ts +110 -27
  154. package/worker/mail/isolate-cache.ts +35 -0
  155. package/worker/mail/link-domains.ts +29 -7
  156. package/worker/mail/mailbox-deletion.ts +10 -4
  157. package/worker/mail/mailbox-directory.ts +16 -6
  158. package/worker/mail/mailing-list.ts +94 -39
  159. package/worker/mail/message-security.ts +90 -15
  160. package/worker/mail/message-view.ts +18 -6
  161. package/worker/mail/office-conversion.ts +31 -9
  162. package/worker/mail/office-preview-container.ts +40 -13
  163. package/worker/mail/office-preview-queue.ts +76 -32
  164. package/worker/mail/org-domain.ts +8 -1
  165. package/worker/mail/outbound-content.ts +71 -26
  166. package/worker/mail/outbound-delivery.ts +31 -17
  167. package/worker/mail/outbound-service.ts +48 -30
  168. package/worker/mail/outbound-threading.ts +30 -17
  169. package/worker/mail/outbound.ts +97 -70
  170. package/worker/mail/outgoing-context.ts +25 -15
  171. package/worker/mail/participants.ts +44 -29
  172. package/worker/mail/push-notifications.ts +283 -171
  173. package/worker/mail/quote-parser.ts +21 -10
  174. package/worker/mail/r2-presigned-urls.ts +31 -25
  175. package/worker/mail/receive.ts +23 -11
  176. package/worker/mail/recipients.ts +6 -1
  177. package/worker/mail/remote-proxy.ts +187 -31
  178. package/worker/mail/remote-routes.ts +87 -0
  179. package/worker/mail/remote-token.ts +104 -0
  180. package/worker/mail/repeat.ts +19 -0
  181. package/worker/mail/reply-plan.ts +62 -33
  182. package/worker/mail/rfc.ts +32 -7
  183. package/worker/mail/routes.ts +871 -542
  184. package/worker/mail/safety-routes.ts +329 -202
  185. package/worker/mail/schemas.ts +84 -105
  186. package/worker/mail/search.ts +1 -0
  187. package/worker/mail/security-settings.ts +41 -9
  188. package/worker/mail/sender-intel.ts +206 -51
  189. package/worker/mail/spamhaus.ts +92 -45
  190. package/worker/mail/unsubscribe.ts +76 -18
  191. package/worker/mail/uploads.ts +153 -91
  192. package/worker/mail/webhook-source.ts +35 -12
  193. package/worker/mail/workspace-safety.ts +97 -38
  194. package/worker/mailbox/demo-html.ts +7 -7
  195. package/worker/mailbox/demo-seed.ts +10 -44
  196. package/worker/mailbox/demo.ts +597 -227
  197. package/worker/mailbox/email-index.ts +53 -0
  198. package/worker/mailbox/folder-model.ts +53 -17
  199. package/worker/mailbox/import-placement.ts +88 -0
  200. package/worker/mailbox/inbox-counts.ts +106 -0
  201. package/worker/mailbox/index.ts +1761 -737
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +7 -14
  204. package/worker/mailbox/office-preview-jobs.ts +56 -25
  205. package/worker/mailbox/schema.ts +87 -66
  206. package/worker/mailbox/senders.ts +176 -70
  207. package/worker/mcp/mail-action-tools.ts +128 -87
  208. package/worker/mcp/mail-compose-tools.ts +133 -82
  209. package/worker/mcp/mail-query-tools.ts +120 -71
  210. package/worker/mcp/mail-safety-tools.ts +321 -248
  211. package/worker/mcp/schemas.ts +43 -0
  212. package/worker/mcp/tools.ts +13 -10
  213. package/worker/module.ts +43 -18
  214. package/worker/sql.d.ts +8 -0
  215. package/alchemy.ts +0 -126
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/migrations/0000_email.sql +0 -53
  218. package/shared/mail-rules.ts +0 -156
  219. package/worker/admin/report-routes.ts +0 -164
  220. package/worker/mail/reported-messages.ts +0 -68
  221. package/worker/mailbox/legacy-migrations.ts +0 -41
  222. package/worker/mailbox/migrations.ts +0 -10
  223. package/worker/mailbox/rules.ts +0 -110
@@ -1,149 +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 { withHeaderMetadata } from "./header-metadata";
15
- import { emailListKey, emailSecurity } from "./message-view";
22
+ import { emailListKey } from "./message-view";
16
23
  import { submitOutgoing } from "./outbound-service";
17
- import { recordReportedMessage, reportSnapshot } from "./reported-messages";
18
24
  import {
19
25
  blockPatternQuerySchema,
20
26
  blockSenderSchema,
21
27
  bulkReportSchema,
22
28
  mailboxQuerySchema,
23
- mailRuleSchema,
24
- reorderRulesSchema,
25
- reportMessageSchema,
26
29
  trustSenderSchema,
27
30
  unsubscribeSchema,
28
31
  } from "./schemas";
29
- import { workspaceIdentity } from "./security-settings";
30
- import { storedSenderIntel } from "./sender-intel";
31
- import { oneClickHost, parseMailtoUnsubscribe, postOneClick } from "./unsubscribe";
32
- import { recordWorkspaceFeedback, workspaceBlockPatterns } from "./workspace-safety";
33
-
34
- async function mailboxAccess(env: Env, userId: string, mailboxId: string) {
35
- return getMailboxAccess(createDb(env.DB), userId, mailboxId);
36
- }
32
+ import {
33
+ oneClickHost,
34
+ parseMailtoUnsubscribe,
35
+ postOneClick,
36
+ } from "./unsubscribe";
37
+ import {
38
+ recordWorkspaceFeedback,
39
+ workspaceBlockPatterns,
40
+ } from "./workspace-safety";
37
41
 
38
42
  function forbidden(c: Context<AppEnv>) {
39
43
  return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
40
44
  }
41
45
 
42
- /** 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. */
43
47
  async function reportOne(input: {
44
48
  env: Env;
45
49
  mailboxId: string;
46
50
  userId: string;
47
51
  email: Email;
48
- kind: ReportKind;
49
52
  }) {
50
- const mailbox = mailboxStub(input.env, input.mailboxId);
51
- 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
+
52
58
  if (!result) return null;
53
59
  const sender = result.email.fromJson[0]?.address;
60
+
54
61
  if (sender) {
55
62
  await recordWorkspaceFeedback(input.env.DB, {
56
63
  mailboxId: input.mailboxId,
57
64
  emailId: result.email.id,
58
65
  address: sender,
59
- label: input.kind,
60
- }).catch((error) => console.error(`Could not share the report for ${result.email.id}`, error));
61
- }
62
- let reportId: string | null = null;
63
- if (input.kind === "phishing") {
64
- const email = await withHeaderMetadata(input.env, mailbox, result.email);
65
- const address = email.fromJson[0]?.address ?? "";
66
- const [identity, history, bodyHtml] = await Promise.all([
67
- workspaceIdentity(input.env.DB),
68
- mailbox.getSenderHistory(address ? [address] : []),
69
- email.bodyHtmlR2Key
70
- ? input.env.MAIL_STORAGE.get(email.bodyHtmlR2Key).then((object) => object?.text() ?? null)
71
- : Promise.resolve(null),
72
- ]);
73
- reportId = await recordReportedMessage(input.env.DB, {
74
- mailboxId: input.mailboxId,
75
- email,
76
- reporterUserId: input.userId,
77
- snapshot: reportSnapshot({
78
- email,
79
- security: emailSecurity(email, identity, history),
80
- intel: storedSenderIntel(email.senderIntelJson),
81
- bodyHtml,
82
- }),
83
- });
66
+ label: "spam",
67
+ }).catch((error) =>
68
+ console.error(`Could not share the report for ${result.email.id}`, error)
69
+ );
84
70
  }
85
- return { moved: result.moved, reportId };
71
+
72
+ return { moved: result.moved };
86
73
  }
87
74
 
88
75
  export const mailSafetyRoutes = new Hono<AppEnv>()
89
76
  .post(
90
77
  "/messages/:id/unsubscribe",
78
+ oauthScope(MAIL_SEND_SCOPE),
91
79
  zValidator("query", mailboxQuerySchema),
92
80
  zValidator("json", unsubscribeSchema),
93
81
  async (c) => {
94
82
  const { mailboxId } = c.req.valid("query");
95
83
  const user = c.get("user");
96
- const access = await mailboxAccess(c.env, user.id, mailboxId);
84
+ const access = await accessibleMailbox(c, mailboxId, "read");
85
+
97
86
  if (!access) return forbidden(c);
98
87
  const mailbox = mailboxStub(c.env, mailboxId);
99
88
  const stored = await mailbox.getEmail(c.req.param("id"));
100
- 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
+
101
94
  // Stored at ingestion from the original; never taken from the client.
102
- const email = await withHeaderMetadata(c.env, mailbox, stored);
95
+ const email = stored;
103
96
  const methods = email.listUnsubscribeJson;
104
97
  const listKey = emailListKey(email);
98
+
105
99
  if (!methods || !listKey || (!methods.httpsUrl && !methods.mailto)) {
106
- 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
+ );
107
106
  }
108
- const limit = await checkRateLimit(c.env.DB, {
109
- action: "mail-unsubscribe",
110
- identifier: user.id,
111
- limit: 20,
112
- windowMs: 60_000,
113
- });
114
- if (!limit.allowed) {
115
- c.header("retry-after", String(limit.retryAfterSeconds));
116
- 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
+ );
117
122
  }
123
+
118
124
  const record = (
119
125
  method: "one_click" | "mailto" | "link",
120
126
  status: "done" | "requested" | "opened" | "failed",
121
127
  target: string | null,
122
- detail: string | null,
123
- ) => 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
+ });
124
139
 
125
140
  if (c.req.valid("json").method === "link") {
126
- if (!methods.httpsUrl) return apiError(c, 409, "CONFLICT", "This message has no unsubscribe page");
127
- const unsubscription = await record("link", "opened", oneClickHost(methods.httpsUrl), null);
128
- 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
+ });
129
164
  }
130
165
 
131
166
  let detail: string | null = null;
167
+
132
168
  if (methods.oneClick && methods.httpsUrl) {
133
- const result = await postOneClick(methods.httpsUrl, oneClickFetcher(c.env));
169
+ const result = await postOneClick(
170
+ methods.httpsUrl,
171
+ oneClickFetcher(c.env)
172
+ );
173
+
134
174
  if (result.ok) {
135
175
  const unsubscription = await record(
136
176
  "one_click",
137
177
  "done",
138
178
  oneClickHost(methods.httpsUrl),
139
- result.redirected ? `Answered ${result.status} instead of 2xx` : null,
179
+ result.redirected
180
+ ? `Answered ${result.status} instead of 2xx`
181
+ : null
140
182
  );
141
- 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
+ });
142
191
  }
192
+
143
193
  detail = result.detail;
144
194
  }
145
195
 
146
- const mailto = methods.mailto ? parseMailtoUnsubscribe(methods.mailto) : null;
196
+ const mailto = methods.mailto
197
+ ? parseMailtoUnsubscribe(methods.mailto)
198
+ : null;
199
+
147
200
  if (mailto && access.canSend) {
148
201
  const submission = await submitOutgoing({
149
202
  env: c.env,
@@ -167,184 +220,258 @@ export const mailSafetyRoutes = new Hono<AppEnv>()
167
220
  fromName: access.displayName,
168
221
  defer: (task) => c.executionCtx.waitUntil(task),
169
222
  });
223
+
170
224
  const failed = submission.email.transportState === "failed";
225
+
171
226
  const unsubscription = await record(
172
227
  "mailto",
173
228
  failed ? "failed" : "requested",
174
229
  mailto.to,
175
- failed ? submission.email.transportError : detail,
230
+ failed ? submission.email.transportError : detail
176
231
  );
232
+
177
233
  if (!failed) {
178
- 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
+ });
179
241
  }
180
- 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";
181
246
  }
247
+
182
248
  if (methods.httpsUrl) {
183
249
  // Opening the page is left to the person, in a new tab, after this answer.
184
- 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
+ });
185
257
  }
258
+
186
259
  if (mailto && !access.canSend) {
187
- 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
+ );
188
266
  }
189
- const unsubscription = await record(methods.oneClick ? "one_click" : "mailto", "failed", null, detail);
190
- return c.json({ ok: true as const, outcome: "failed" as const, unsubscription, url: null, detail });
191
- },
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
+ }
192
283
  )
193
284
  .post(
194
285
  "/messages/:id/report",
286
+ oauthScope(MAIL_ORGANIZE_SCOPE),
195
287
  zValidator("query", mailboxQuerySchema),
196
- zValidator("json", reportMessageSchema),
197
288
  async (c) => {
198
289
  const { mailboxId } = c.req.valid("query");
199
290
  const user = c.get("user");
200
- const access = await mailboxAccess(c.env, user.id, mailboxId);
201
- if (!access) return forbidden(c);
202
- const input = c.req.valid("json");
203
- const email = await mailboxStub(c.env, mailboxId).getEmail(c.req.param("id"));
204
- 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
+
205
302
  const result = await reportOne({
206
303
  env: c.env,
207
304
  mailboxId,
208
305
  userId: user.id,
209
306
  email,
210
- kind: input.kind,
211
307
  });
308
+
212
309
  if (!result) return apiError(c, 404, "NOT_FOUND", "Message not found");
310
+
213
311
  return c.json({ ok: true as const, ...result });
214
- },
312
+ }
215
313
  )
216
314
  .post(
217
315
  "/conversations/report",
316
+ oauthScope(MAIL_ORGANIZE_SCOPE),
218
317
  zValidator("query", mailboxQuerySchema),
219
318
  zValidator("json", bulkReportSchema),
220
319
  async (c) => {
221
320
  const { mailboxId } = c.req.valid("query");
222
321
  const user = c.get("user");
223
- const access = await mailboxAccess(c.env, user.id, mailboxId);
322
+ const access = await accessibleMailbox(c, mailboxId, "read");
323
+
224
324
  if (!access) return forbidden(c);
225
325
  const input = c.req.valid("json");
226
- const messages = await mailboxStub(c.env, mailboxId).latestIncomingEmails(input.conversationIds);
227
- let reported = 0;
228
- for (const email of messages) {
229
- const result = await reportOne({
230
- 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, {
231
363
  mailboxId,
232
- userId: user.id,
233
- email,
234
- kind: input.kind,
235
- });
236
- 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
+ );
237
373
  }
238
- return c.json({ ok: true as const, reportedCount: reported });
239
- },
374
+
375
+ return c.json({ ok: true as const, restored: result.restored });
376
+ }
240
377
  )
241
- .post("/messages/:id/not-spam", zValidator("query", mailboxQuerySchema), async (c) => {
242
- const { mailboxId } = c.req.valid("query");
243
- const user = c.get("user");
244
- if (!await mailboxAccess(c.env, user.id, mailboxId)) return forbidden(c);
245
- const emailId = c.req.param("id");
246
- const result = await mailboxStub(c.env, mailboxId).markNotSpam({ emailId, userId: user.id });
247
- if (!result) return apiError(c, 404, "NOT_FOUND", "Message not found");
248
- if (result.address) {
249
- await recordWorkspaceFeedback(c.env.DB, { mailboxId, emailId, address: result.address, label: "not_spam" })
250
- .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
+ });
251
399
  }
252
- return c.json({ ok: true as const, restored: result.restored });
253
- })
254
- .get("/mailboxes/:id/blocked-senders", async (c) => {
255
- const mailboxId = c.req.param("id");
256
- if (!await mailboxAccess(c.env, c.get("user").id, mailboxId)) return forbidden(c);
257
- const [blocked, workspace] = await Promise.all([
258
- mailboxStub(c.env, mailboxId).listBlockedSenders(),
259
- workspaceBlockPatterns(c.env.DB),
260
- ]);
261
- return c.json({
262
- ok: true as const,
263
- blocked,
264
- workspace: [...workspace].map(([pattern, at]) => ({ pattern, blockedAt: at })),
265
- });
266
- })
267
- .post("/mailboxes/:id/blocked-senders", zValidator("json", blockSenderSchema), async (c) => {
268
- const mailboxId = c.req.param("id");
269
- const access = await mailboxAccess(c.env, c.get("user").id, mailboxId);
270
- if (!access) return forbidden(c);
271
- const input = c.req.valid("json");
272
- const pattern = normalizeBlockPattern(input.pattern);
273
- if (!pattern) return apiError(c, 400, "BAD_REQUEST", "Enter an email address or a domain");
274
- const own = access.address.toLocaleLowerCase();
275
- if (pattern === own || own.endsWith(pattern)) {
276
- 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 });
277
439
  }
278
- const result = await mailboxStub(c.env, mailboxId).blockSender(pattern, input.moveExisting);
279
- return c.json({ ok: true as const, ...result });
280
- })
440
+ )
281
441
  .delete(
282
442
  "/mailboxes/:id/blocked-senders",
443
+ oauthScope(MAIL_ORGANIZE_SCOPE),
283
444
  zValidator("query", blockPatternQuerySchema),
284
445
  async (c) => {
285
446
  const mailboxId = c.req.param("id");
286
- if (!await mailboxAccess(c.env, c.get("user").id, mailboxId)) return forbidden(c);
447
+
448
+ if (!(await accessibleMailbox(c, mailboxId, "read"))) return forbidden(c);
287
449
  const pattern = normalizeBlockPattern(c.req.valid("query").pattern);
288
- if (!pattern || !await mailboxStub(c.env, mailboxId).unblockSender(pattern)) {
450
+
451
+ if (
452
+ !pattern ||
453
+ !(await mailboxStub(c.env, mailboxId).unblockSender(pattern))
454
+ ) {
289
455
  return apiError(c, 404, "NOT_FOUND", "Blocked sender not found");
290
456
  }
457
+
291
458
  return c.json({ ok: true as const });
292
- },
293
- )
294
- .put("/mailboxes/:id/trusted-senders", zValidator("json", trustSenderSchema), async (c) => {
295
- const mailboxId = c.req.param("id");
296
- if (!await mailboxAccess(c.env, c.get("user").id, mailboxId)) return forbidden(c);
297
- const input = c.req.valid("json");
298
- await mailboxStub(c.env, mailboxId).setSenderTrusted(input.address, input.trusted);
299
- return c.json({ ok: true as const });
300
- })
301
- .get("/mailboxes/:id/rules", async (c) => {
302
- const mailboxId = c.req.param("id");
303
- if (!await mailboxAccess(c.env, c.get("user").id, mailboxId)) return forbidden(c);
304
- return c.json({ ok: true as const, rules: await mailboxStub(c.env, mailboxId).listRules() });
305
- })
306
- .post("/mailboxes/:id/rules", zValidator("json", mailRuleSchema), async (c) => {
307
- const mailboxId = c.req.param("id");
308
- if (!await mailboxAccess(c.env, c.get("user").id, mailboxId)) return forbidden(c);
309
- try {
310
- const rule = await mailboxStub(c.env, mailboxId).createRule(c.req.valid("json"));
311
- return c.json({ ok: true as const, rule }, 201);
312
- } catch (error) {
313
- // Errors cross the Durable Object boundary without their class.
314
- if (error instanceof Error && error.message.startsWith(MAIL_RULE_LIMIT_MESSAGE)) {
315
- return apiError(c, 409, "CONFLICT", error.message);
316
- }
317
- throw error;
318
- }
319
- })
320
- .put("/mailboxes/:id/rules/:ruleId", zValidator("json", mailRuleSchema), async (c) => {
321
- const mailboxId = c.req.param("id");
322
- if (!await mailboxAccess(c.env, c.get("user").id, mailboxId)) return forbidden(c);
323
- const rule = await mailboxStub(c.env, mailboxId).updateRule(c.req.param("ruleId"), c.req.valid("json"));
324
- if (!rule) return apiError(c, 404, "NOT_FOUND", "Rule not found");
325
- return c.json({ ok: true as const, rule });
326
- })
327
- .delete("/mailboxes/:id/rules/:ruleId", async (c) => {
328
- const mailboxId = c.req.param("id");
329
- if (!await mailboxAccess(c.env, c.get("user").id, mailboxId)) return forbidden(c);
330
- if (!await mailboxStub(c.env, mailboxId).deleteRule(c.req.param("ruleId"))) {
331
- return apiError(c, 404, "NOT_FOUND", "Rule not found");
332
459
  }
333
- return c.json({ ok: true as const });
334
- })
335
- .put("/mailboxes/:id/rules-order", zValidator("json", reorderRulesSchema), async (c) => {
336
- const mailboxId = c.req.param("id");
337
- if (!await mailboxAccess(c.env, c.get("user").id, mailboxId)) return forbidden(c);
338
- if (!await mailboxStub(c.env, mailboxId).reorderRules(c.req.valid("json").ruleIds)) {
339
- 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 });
340
476
  }
341
- return c.json({ ok: true as const });
342
- })
343
- .post("/mailboxes/:id/rules/:ruleId/apply", async (c) => {
344
- const mailboxId = c.req.param("id");
345
- const user = c.get("user");
346
- if (!await mailboxAccess(c.env, user.id, mailboxId)) return forbidden(c);
347
- const result = await mailboxStub(c.env, mailboxId).applyRuleToExisting(c.req.param("ruleId"), user.id);
348
- if (!result) return apiError(c, 404, "NOT_FOUND", "Rule not found");
349
- return c.json({ ok: true as const, ...result });
350
- });
477
+ );