@open-workspace/email 0.3.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 (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,18 +1,28 @@
1
- import { and, eq } from "drizzle-orm";
2
- import { Hono, type Context } from "hono";
3
- import { JMAP_SCOPE } from "@open-workspace/core/shared/oidc.ts";
4
- import { bearerToken } from "@open-workspace/core/worker/auth/middleware.ts";
5
- import { createDb } from "@open-workspace/core/worker/db/client.ts";
6
- import { mailboxAddressSql } from "@open-workspace/core/worker/db/mailboxes.ts";
7
- import { domains, mailboxAccess, mailboxes } from "@open-workspace/core/worker/db/schema.ts";
8
- import type { AppEnv } from "@open-workspace/core/worker/env.ts";
9
- import { checkRateLimit } from "@open-workspace/core/worker/lib/rate-limit.ts";
10
1
  import {
2
+ bearerToken,
3
+ createDb,
4
+ describeIssues,
5
+ mailboxAddressSql,
6
+ mailboxAccess,
7
+ mailboxes,
8
+ overRateLimit,
11
9
  authenticateAccessToken,
12
10
  jmapProtectedResourceMetadataUrl,
13
- } from "@open-workspace/core/worker/oidc/mcp-clients.ts";
11
+ jmapResourceUri,
12
+ oidcIssuer,
13
+ } from "@open-workspace/core/module";
14
+ import type { AppEnv } from "@open-workspace/core/module";
15
+ import { and, eq } from "drizzle-orm";
16
+ import { Hono } from "hono";
17
+ import type { Context } from "hono";
18
+
14
19
  import { MAX_COMPOSER_ATTACHMENT_BYTES } from "../../shared/mail";
15
- import { mailboxStub } from "../mailbox";
20
+ import { JMAP_PATH } from "../../shared/module";
21
+ import {
22
+ MAIL_READ_SCOPE,
23
+ MAIL_SEND_SCOPE,
24
+ mailScopes,
25
+ } from "../../shared/permissions";
16
26
  import { vapidConfiguration } from "../mail/push-notifications";
17
27
  import {
18
28
  createComposerUploadIntent,
@@ -21,8 +31,15 @@ import {
21
31
  storeComposerUploadContent,
22
32
  UploadValidationError,
23
33
  } from "../mail/uploads";
34
+ import { mailboxStub } from "../mailbox";
24
35
  import { jmapEventStream } from "./eventsource";
25
- import { JmapError, runJmapRequest, UPLOAD_BLOB, type JmapAccount, type JmapContext } from "./methods";
36
+ import {
37
+ JmapError,
38
+ jmapRequestSchema,
39
+ runJmapRequest,
40
+ UPLOAD_BLOB,
41
+ } from "./methods";
42
+ import type { JmapAccount, JmapContext } from "./methods";
26
43
 
27
44
  const CAPABILITIES = {
28
45
  "urn:ietf:params:jmap:core": {
@@ -39,15 +56,75 @@ const CAPABILITIES = {
39
56
  "urn:ietf:params:jmap:submission": {},
40
57
  };
41
58
 
42
- type JmapUser = { id: string; name: string; clientId: string; token: string };
43
- type JmapEnv = AppEnv & { Variables: AppEnv["Variables"] & { jmapUser: JmapUser } };
59
+ type SessionCapabilities = typeof CAPABILITIES & {
60
+ /** RFC 9749: push services that require VAPID accept our pushes. */
61
+ "urn:ietf:params:jmap:webpush-vapid"?: { applicationServerKey: string };
62
+ };
63
+
64
+ const MAIL_ACCOUNT_CAPABILITY = {
65
+ maxMailboxesPerEmail: 1,
66
+ maxMailboxDepth: 1,
67
+ maxSizeMailboxName: 80,
68
+ maxSizeAttachmentsPerEmail: MAX_COMPOSER_ATTACHMENT_BYTES,
69
+ emailQuerySortOptions: ["receivedAt", "sentAt"],
70
+ mayCreateTopLevelMailbox: false,
71
+ };
72
+
73
+ type AccountCapabilities = {
74
+ "urn:ietf:params:jmap:mail": typeof MAIL_ACCOUNT_CAPABILITY;
75
+ /** Only accounts the person can send from. */
76
+ "urn:ietf:params:jmap:submission"?: {
77
+ maxDelayedSend: number;
78
+ submissionExtensions: Record<string, never>;
79
+ };
80
+ };
81
+
82
+ function accountCapabilities(account: JmapAccount) {
83
+ const capabilities: AccountCapabilities = {
84
+ "urn:ietf:params:jmap:mail": MAIL_ACCOUNT_CAPABILITY,
85
+ };
86
+
87
+ if (account.canSend) {
88
+ capabilities["urn:ietf:params:jmap:submission"] = {
89
+ maxDelayedSend: 0,
90
+ submissionExtensions: {},
91
+ };
92
+ }
93
+
94
+ return capabilities;
95
+ }
96
+
97
+ const mailScopeNames: ReadonlySet<string> = new Set(mailScopes);
98
+
99
+ type JmapUser = {
100
+ id: string;
101
+ name: string;
102
+ clientId: string;
103
+ token: string;
104
+ /** The token's mail scopes the person may still use. */
105
+ scopes: readonly string[];
106
+ };
107
+
108
+ type JmapEnv = AppEnv & {
109
+ Variables: AppEnv["Variables"] & { jmapUser: JmapUser };
110
+ };
44
111
 
45
- function problem(c: Context, status: 400 | 401 | 403 | 404 | 413 | 429, type: string, detail: string) {
46
- return c.json({ type, status, detail }, status, { "content-type": "application/problem+json" });
112
+ function problem(
113
+ c: Context,
114
+ status: 400 | 401 | 403 | 404 | 413 | 429,
115
+ type: string,
116
+ detail: string
117
+ ) {
118
+ return c.json({ type, status, detail }, status, {
119
+ "content-type": "application/problem+json",
120
+ });
47
121
  }
48
122
 
49
123
  /** The mailboxes this person can open; each is a JMAP account. */
50
- export async function jmapAccounts(env: Env, userId: string): Promise<JmapAccount[]> {
124
+ export async function jmapAccounts(
125
+ env: Env,
126
+ userId: string
127
+ ): Promise<JmapAccount[]> {
51
128
  const rows = await createDb(env.DB)
52
129
  .select({
53
130
  id: mailboxes.id,
@@ -59,8 +136,10 @@ export async function jmapAccounts(env: Env, userId: string): Promise<JmapAccoun
59
136
  })
60
137
  .from(mailboxAccess)
61
138
  .innerJoin(mailboxes, eq(mailboxAccess.mailboxId, mailboxes.id))
62
- .innerJoin(domains, eq(mailboxes.domainId, domains.id))
63
- .where(and(eq(mailboxAccess.userId, userId), eq(mailboxes.delivery, "inbox")));
139
+ .where(
140
+ and(eq(mailboxAccess.userId, userId), eq(mailboxes.delivery, "inbox"))
141
+ );
142
+
64
143
  return rows.map((row) => ({
65
144
  ...row,
66
145
  isPersonal: row.ownerUserId === userId,
@@ -71,129 +150,267 @@ function sessionObject(
71
150
  origin: string,
72
151
  user: { id: string; name: string },
73
152
  accounts: JmapAccount[],
74
- vapidPublicKey: string | null,
153
+ vapidPublicKey: string | null
75
154
  ) {
76
- const primary = accounts.find((account) => account.isPersonal && account.isPrimary)
77
- ?? accounts.find((account) => account.isPersonal)
78
- ?? accounts[0];
155
+ const primary =
156
+ accounts.find((account) => account.isPersonal && account.isPrimary) ??
157
+ accounts.find((account) => account.isPersonal) ??
158
+ accounts[0];
159
+
160
+ const capabilities: SessionCapabilities = { ...CAPABILITIES };
161
+
162
+ if (vapidPublicKey) {
163
+ capabilities["urn:ietf:params:jmap:webpush-vapid"] = {
164
+ applicationServerKey: vapidPublicKey,
165
+ };
166
+ }
167
+
79
168
  return {
80
- capabilities: {
81
- ...CAPABILITIES,
82
- // RFC 9749: push services that require VAPID accept our pushes.
83
- ...(vapidPublicKey ? { "urn:ietf:params:jmap:webpush-vapid": { applicationServerKey: vapidPublicKey } } : {}),
84
- },
85
- accounts: Object.fromEntries(accounts.map((account) => [account.id, {
86
- name: account.address,
87
- isPersonal: account.isPersonal,
88
- isReadOnly: false,
89
- accountCapabilities: {
90
- "urn:ietf:params:jmap:mail": {
91
- maxMailboxesPerEmail: 1,
92
- maxMailboxDepth: 1,
93
- maxSizeMailboxName: 80,
94
- maxSizeAttachmentsPerEmail: MAX_COMPOSER_ATTACHMENT_BYTES,
95
- emailQuerySortOptions: ["receivedAt", "sentAt"],
96
- mayCreateTopLevelMailbox: false,
169
+ capabilities,
170
+ accounts: Object.fromEntries(
171
+ accounts.map((account) => [
172
+ account.id,
173
+ {
174
+ name: account.address,
175
+ isPersonal: account.isPersonal,
176
+ isReadOnly: false,
177
+ accountCapabilities: accountCapabilities(account),
97
178
  },
98
- ...(account.canSend
99
- ? { "urn:ietf:params:jmap:submission": { maxDelayedSend: 0, submissionExtensions: {} } }
100
- : {}),
101
- },
102
- }])),
179
+ ])
180
+ ),
103
181
  primaryAccounts: primary
104
182
  ? {
105
- "urn:ietf:params:jmap:mail": primary.id,
106
- "urn:ietf:params:jmap:submission": primary.id,
107
- }
183
+ "urn:ietf:params:jmap:mail": primary.id,
184
+ "urn:ietf:params:jmap:submission": primary.id,
185
+ }
108
186
  : {},
109
187
  username: primary?.address ?? user.name,
110
- apiUrl: `${origin}/jmap/api`,
111
- downloadUrl: `${origin}/jmap/download/{accountId}/{blobId}/{name}?type={type}`,
112
- uploadUrl: `${origin}/jmap/upload/{accountId}`,
113
- eventSourceUrl: `${origin}/jmap/eventsource?types={types}&closeafter={closeafter}&ping={ping}`,
188
+ apiUrl: `${origin}${JMAP_PATH}/api`,
189
+ downloadUrl: `${origin}${JMAP_PATH}/download/{accountId}/{blobId}/{name}?type={type}`,
190
+ uploadUrl: `${origin}${JMAP_PATH}/upload/{accountId}`,
191
+ eventSourceUrl: `${origin}${JMAP_PATH}/eventsource?types={types}&closeafter={closeafter}&ping={ping}`,
114
192
  state: String(accounts.length),
115
193
  };
116
194
  }
117
195
 
118
- const requireJmapAuth = async (c: Context<JmapEnv>, next: () => Promise<void>) => {
196
+ /** RFC 8707: JMAP accepts only tokens issued for it, at the issuer's origin or this one. */
197
+ function jmapResources(c: Context<JmapEnv>) {
198
+ const origins = new Set([new URL(c.req.url).origin]);
199
+
200
+ try {
201
+ origins.add(new URL(oidcIssuer(c.env)).origin);
202
+ } catch {
203
+ // Without a configured issuer, only this origin.
204
+ }
205
+
206
+ return [...origins].map(jmapResourceUri);
207
+ }
208
+
209
+ /** Who a JMAP token signs in, with its mail scopes; null when it is not good here. */
210
+ async function jmapIdentity(c: Context<JmapEnv>, token: string) {
211
+ const identity = await authenticateAccessToken(
212
+ createDb(c.env.DB),
213
+ token,
214
+ jmapResources(c)
215
+ );
216
+
217
+ if (!identity) return null;
218
+
219
+ return {
220
+ ...identity,
221
+ scopes: identity.scopes.filter((scope) => mailScopeNames.has(scope)),
222
+ };
223
+ }
224
+
225
+ const requireJmapAuth = async (
226
+ c: Context<JmapEnv>,
227
+ next: () => Promise<void>
228
+ ) => {
119
229
  const token = bearerToken(c.req.raw);
120
- const identity = token
121
- ? await authenticateAccessToken(createDb(c.env.DB), token, JMAP_SCOPE)
122
- : null;
123
- if (!identity) {
124
- c.header("www-authenticate", [
125
- `Bearer resource_metadata="${jmapProtectedResourceMetadataUrl(new URL(c.req.url).origin)}"`,
126
- `scope="${JMAP_SCOPE}"`,
127
- ...(token ? ['error="invalid_token"'] : []),
128
- ].join(", "));
129
- return problem(c, 401, "about:blank", token ? "The access token is invalid or expired" : "Sign in with OAuth");
230
+ const identity = token ? await jmapIdentity(c, token) : null;
231
+
232
+ if (!token || !identity) {
233
+ c.header(
234
+ "www-authenticate",
235
+ [
236
+ `Bearer resource_metadata="${jmapProtectedResourceMetadataUrl(new URL(c.req.url).origin)}"`,
237
+ `scope="${mailScopes.join(" ")}"`,
238
+ ...(token ? ['error="invalid_token"'] : []),
239
+ ].join(", ")
240
+ );
241
+
242
+ return problem(
243
+ c,
244
+ 401,
245
+ "about:blank",
246
+ token ? "The access token is invalid or expired" : "Sign in with OAuth"
247
+ );
130
248
  }
131
- c.set("jmapUser", { id: identity.user.id, name: identity.user.name, clientId: identity.clientId, token: token! });
249
+
250
+ if (!identity.scopes.length) {
251
+ c.header(
252
+ "www-authenticate",
253
+ `Bearer error="insufficient_scope", scope="${mailScopes.join(" ")}"`
254
+ );
255
+
256
+ return problem(
257
+ c,
258
+ 403,
259
+ "about:blank",
260
+ "This token was not given access to mail"
261
+ );
262
+ }
263
+
264
+ c.set("jmapUser", {
265
+ id: identity.user.id,
266
+ name: identity.user.name,
267
+ clientId: identity.clientId,
268
+ token,
269
+ scopes: identity.scopes,
270
+ });
132
271
  await next();
133
272
  };
134
273
 
274
+ /** A 403 unless the token holds `scope`. */
275
+ function missingScope(c: Context<JmapEnv>, scope: string) {
276
+ if (c.get("jmapUser").scopes.includes(scope)) return null;
277
+ c.header(
278
+ "www-authenticate",
279
+ `Bearer error="insufficient_scope", scope="${scope}"`
280
+ );
281
+
282
+ return problem(c, 403, "about:blank", `This token was not given ${scope}`);
283
+ }
284
+
135
285
  /**
136
- * JMAP (RFC 8620) for mail (RFC 8621) with OAuth bearer tokens carrying the
137
- * jmap scope. Each mailbox the person can open is a JMAP account.
286
+ * JMAP (RFC 8620) for mail (RFC 8621) with OAuth bearer tokens issued for
287
+ * it, each method allowed by its mail scope (methods.ts). Each mailbox the
288
+ * person can open is a JMAP account.
138
289
  */
139
290
  export const jmapRoutes = new Hono<JmapEnv>()
140
- .get("/.well-known/jmap", (c) => c.redirect("/jmap/session", 302))
141
- .use("/jmap/*", requireJmapAuth)
142
- .get("/jmap/session", async (c) => {
291
+ .get("/.well-known/jmap", (c) => c.redirect(`${JMAP_PATH}/session`, 302))
292
+ .use(`${JMAP_PATH}/*`, requireJmapAuth)
293
+ .get(`${JMAP_PATH}/session`, async (c) => {
143
294
  const user = c.get("jmapUser");
144
295
  const vapid = await vapidConfiguration(c.env);
145
- return c.json(sessionObject(new URL(c.req.url).origin, user, await jmapAccounts(c.env, user.id), vapid?.publicKey ?? null));
296
+
297
+ return c.json(
298
+ sessionObject(
299
+ new URL(c.req.url).origin,
300
+ user,
301
+ await jmapAccounts(c.env, user.id),
302
+ vapid?.publicKey ?? null
303
+ )
304
+ );
146
305
  })
147
- .post("/jmap/api", async (c) => {
148
- if (!c.req.header("content-type")?.toLowerCase().startsWith("application/json")) {
149
- return problem(c, 400, "urn:ietf:params:jmap:error:notJSON", "The request must be JSON");
306
+ .post(`${JMAP_PATH}/api`, async (c) => {
307
+ if (
308
+ !c.req
309
+ .header("content-type")
310
+ ?.toLowerCase()
311
+ .startsWith("application/json")
312
+ ) {
313
+ return problem(
314
+ c,
315
+ 400,
316
+ "urn:ietf:params:jmap:error:notJSON",
317
+ "The request must be JSON"
318
+ );
150
319
  }
320
+
151
321
  let body: unknown;
322
+
152
323
  try {
153
324
  body = await c.req.json();
154
325
  } catch {
155
- return problem(c, 400, "urn:ietf:params:jmap:error:notJSON", "The request is not valid JSON");
326
+ return problem(
327
+ c,
328
+ 400,
329
+ "urn:ietf:params:jmap:error:notJSON",
330
+ "The request is not valid JSON"
331
+ );
332
+ }
333
+
334
+ const request = jmapRequestSchema.safeParse(body);
335
+
336
+ if (!request.success) {
337
+ return problem(
338
+ c,
339
+ 400,
340
+ "urn:ietf:params:jmap:error:notRequest",
341
+ describeIssues(request.error.issues)
342
+ );
156
343
  }
344
+
157
345
  const user = c.get("jmapUser");
346
+
158
347
  const context: JmapContext = {
159
348
  env: c.env,
160
349
  user: { id: user.id, name: user.name },
161
350
  clientId: user.clientId,
351
+ scopes: user.scopes,
162
352
  vapid: await vapidConfiguration(c.env),
163
353
  accounts: await jmapAccounts(c.env, user.id),
164
354
  requestUrl: c.req.url,
165
355
  defer: (task) => c.executionCtx.waitUntil(task),
166
356
  };
357
+
167
358
  try {
168
- return c.json(await runJmapRequest(context, body));
359
+ return c.json(await runJmapRequest(context, request.data));
169
360
  } catch (error) {
170
- if (error instanceof JmapError) return problem(c, 400, error.type, error.message);
361
+ if (error instanceof JmapError) {
362
+ return problem(c, 400, error.type, error.message);
363
+ }
364
+
171
365
  throw error;
172
366
  }
173
367
  })
174
- .get("/jmap/download/:accountId/:blobId/:name", async (c) => {
368
+ .get(`${JMAP_PATH}/download/:accountId/:blobId/:name`, async (c) => {
369
+ const refused = missingScope(c, MAIL_READ_SCOPE);
370
+
371
+ if (refused) return refused;
175
372
  const user = c.get("jmapUser");
176
- const account = (await jmapAccounts(c.env, user.id)).find((item) => item.id === c.req.param("accountId"));
373
+
374
+ const account = (await jmapAccounts(c.env, user.id)).find(
375
+ (item) => item.id === c.req.param("accountId")
376
+ );
377
+
177
378
  if (!account) return problem(c, 404, "about:blank", "Account not found");
178
379
  const blobId = c.req.param("blobId");
179
380
  const upload = UPLOAD_BLOB.exec(blobId);
180
381
  const blob = /^(raw|att)~([^~]+)(?:~(.+))?$/u.exec(blobId);
181
382
  let key: string | null | undefined;
383
+
182
384
  if (upload) {
183
- key = await loadComposerUpload({ env: c.env, mailboxId: account.id, userId: user.id, uploadId: upload[1]! })
184
- .then((found) => found.r2Key, () => null);
385
+ key = await loadComposerUpload({
386
+ env: c.env,
387
+ mailboxId: account.id,
388
+ userId: user.id,
389
+ uploadId: upload[1],
390
+ }).then(
391
+ (found) => found.r2Key,
392
+ () => null
393
+ );
185
394
  } else if (blob) {
186
395
  const [, kind, emailId, attachmentId] = blob;
187
- const email = await mailboxStub(c.env, account.id).getEmail(emailId!);
188
- key = kind === "raw"
189
- ? email?.rawMimeR2Key
190
- : email?.attachmentsJson.find((attachment) => attachment.id === attachmentId)?.r2Key;
396
+ const email = await mailboxStub(c.env, account.id).getEmail(emailId);
397
+ key =
398
+ kind === "raw"
399
+ ? email?.rawMimeR2Key
400
+ : email?.attachmentsJson.find(
401
+ (attachment) => attachment.id === attachmentId
402
+ )?.r2Key;
191
403
  }
404
+
192
405
  const object = key ? await c.env.MAIL_STORAGE.get(key) : null;
406
+
193
407
  if (!object) return problem(c, 404, "about:blank", "Blob not found");
194
- const type = c.req.query("type")
195
- || object.httpMetadata?.contentType
196
- || (blob?.[1] === "raw" ? "message/rfc822" : "application/octet-stream");
408
+
409
+ const type =
410
+ c.req.query("type") ||
411
+ object.httpMetadata?.contentType ||
412
+ (blob?.[1] === "raw" ? "message/rfc822" : "application/octet-stream");
413
+
197
414
  return new Response(object.body, {
198
415
  headers: {
199
416
  "content-type": type,
@@ -202,44 +419,67 @@ export const jmapRoutes = new Hono<JmapEnv>()
202
419
  },
203
420
  });
204
421
  })
205
- .post("/jmap/upload/:accountId", async (c) => {
422
+ .post(`${JMAP_PATH}/upload/:accountId`, async (c) => {
423
+ // Uploads become attachments of mail being sent.
424
+ const refused = missingScope(c, MAIL_SEND_SCOPE);
425
+
426
+ if (refused) return refused;
206
427
  const user = c.get("jmapUser");
207
- const account = (await jmapAccounts(c.env, user.id)).find((item) => item.id === c.req.param("accountId"));
428
+
429
+ const account = (await jmapAccounts(c.env, user.id)).find(
430
+ (item) => item.id === c.req.param("accountId")
431
+ );
432
+
208
433
  if (!account) return problem(c, 404, "about:blank", "Account not found");
434
+
209
435
  // Uploads become attachments of sent mail, so they need send access.
210
- if (!account.canSend) return problem(c, 403, "about:blank", "This account cannot send");
211
- const rate = await checkRateLimit(c.env.DB, {
212
- action: "mail-upload",
213
- identifier: user.id,
214
- limit: 30,
215
- windowMs: 60_000,
216
- });
217
- if (!rate.allowed) {
218
- c.header("retry-after", String(rate.retryAfterSeconds));
436
+ if (!account.canSend) {
437
+ return problem(c, 403, "about:blank", "This account cannot send");
438
+ }
439
+
440
+ const rateExceeded = await overRateLimit(
441
+ c,
442
+ "RATE_LIMIT_30",
443
+ "mail-upload",
444
+ user.id
445
+ );
446
+
447
+ if (rateExceeded) {
219
448
  return problem(c, 429, "about:blank", "Too many uploads");
220
449
  }
221
- const contentType = c.req.header("content-type")?.trim() || "application/octet-stream";
450
+
451
+ const contentType =
452
+ c.req.header("content-type")?.trim() || "application/octet-stream";
453
+
222
454
  const declared = Number(c.req.header("content-length"));
223
455
  // Without a length, buffer the body to learn it; uploads are bounded anyway.
224
456
  let body: ReadableStream<Uint8Array> | ArrayBuffer | null = c.req.raw.body;
225
457
  let size = declared;
458
+
226
459
  if (!Number.isSafeInteger(declared) || declared < 0) {
227
460
  body = await c.req.arrayBuffer();
228
461
  size = body.byteLength;
229
462
  }
463
+
230
464
  if (size > MAX_COMPOSER_ATTACHMENT_BYTES) {
231
- return problem(c, 413, "urn:ietf:params:jmap:error:limit", "The upload is too large");
465
+ return problem(
466
+ c,
467
+ 413,
468
+ "urn:ietf:params:jmap:error:limit",
469
+ "The upload is too large"
470
+ );
232
471
  }
472
+
233
473
  try {
234
474
  const intent = await createComposerUploadIntent({
235
475
  env: c.env,
236
- requestOrigin: new URL(c.req.url).origin,
237
476
  mailboxId: account.id,
238
477
  userId: user.id,
239
478
  filename: "upload",
240
479
  contentType,
241
480
  size,
242
481
  });
482
+
243
483
  await storeComposerUploadContent({
244
484
  env: c.env,
245
485
  mailboxId: account.id,
@@ -249,6 +489,7 @@ export const jmapRoutes = new Hono<JmapEnv>()
249
489
  contentType,
250
490
  contentLength: size,
251
491
  });
492
+
252
493
  const upload = await finalizeComposerUpload({
253
494
  env: c.env,
254
495
  mailboxId: account.id,
@@ -256,14 +497,30 @@ export const jmapRoutes = new Hono<JmapEnv>()
256
497
  uploadId: intent.id,
257
498
  defer: (task) => c.executionCtx.waitUntil(task),
258
499
  });
259
- return c.json({ accountId: account.id, blobId: `upl~${upload.id}`, type: upload.contentType, size: upload.size }, 201);
500
+
501
+ return c.json(
502
+ {
503
+ accountId: account.id,
504
+ blobId: `upl~${upload.id}`,
505
+ type: upload.contentType,
506
+ size: upload.size,
507
+ },
508
+ 201
509
+ );
260
510
  } catch (error) {
261
- if (error instanceof UploadValidationError) return problem(c, 400, "about:blank", error.message);
511
+ if (error instanceof UploadValidationError) {
512
+ return problem(c, 400, "about:blank", error.message);
513
+ }
514
+
262
515
  throw error;
263
516
  }
264
517
  })
265
- .get("/jmap/eventsource", async (c) => {
518
+ .get(`${JMAP_PATH}/eventsource`, async (c) => {
519
+ const refused = missingScope(c, MAIL_READ_SCOPE);
520
+
521
+ if (refused) return refused;
266
522
  const user = c.get("jmapUser");
523
+
267
524
  return jmapEventStream({
268
525
  env: c.env,
269
526
  accounts: await jmapAccounts(c.env, user.id),
@@ -271,7 +528,11 @@ export const jmapRoutes = new Hono<JmapEnv>()
271
528
  closeAfterState: c.req.query("closeafter") === "state",
272
529
  pingSeconds: Number(c.req.query("ping") ?? 0),
273
530
  // The stream outlives the request check; the token is checked again on each ping.
274
- stillAuthorized: async () => Boolean(await authenticateAccessToken(createDb(c.env.DB), user.token, JMAP_SCOPE)),
531
+ stillAuthorized: async () =>
532
+ Boolean(
533
+ (await jmapIdentity(c, user.token))?.scopes.includes(MAIL_READ_SCOPE)
534
+ ),
535
+ currentAccounts: () => jmapAccounts(c.env, user.id),
275
536
  defer: (task) => c.executionCtx.waitUntil(task),
276
537
  });
277
538
  });