@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,21 +1,49 @@
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
1
  import {
2
+ bearerToken,
3
+ createDb,
4
+ describeIssues,
5
+ mailboxAddressSql,
6
+ mailboxAccess,
7
+ mailboxes,
8
+ overRateLimit,
10
9
  authenticateAccessToken,
11
10
  jmapProtectedResourceMetadataUrl,
12
- } 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
+
19
+ import { MAX_COMPOSER_ATTACHMENT_BYTES } from "../../shared/mail";
20
+ import { JMAP_PATH } from "../../shared/module";
21
+ import {
22
+ MAIL_READ_SCOPE,
23
+ MAIL_SEND_SCOPE,
24
+ mailScopes,
25
+ } from "../../shared/permissions";
26
+ import { vapidConfiguration } from "../mail/push-notifications";
27
+ import {
28
+ createComposerUploadIntent,
29
+ finalizeComposerUpload,
30
+ loadComposerUpload,
31
+ storeComposerUploadContent,
32
+ UploadValidationError,
33
+ } from "../mail/uploads";
13
34
  import { mailboxStub } from "../mailbox";
14
- import { JmapError, runJmapRequest, type JmapAccount, type JmapContext } from "./methods";
35
+ import { jmapEventStream } from "./eventsource";
36
+ import {
37
+ JmapError,
38
+ jmapRequestSchema,
39
+ runJmapRequest,
40
+ UPLOAD_BLOB,
41
+ } from "./methods";
42
+ import type { JmapAccount, JmapContext } from "./methods";
15
43
 
16
44
  const CAPABILITIES = {
17
45
  "urn:ietf:params:jmap:core": {
18
- maxSizeUpload: 0,
46
+ maxSizeUpload: MAX_COMPOSER_ATTACHMENT_BYTES,
19
47
  maxConcurrentUpload: 1,
20
48
  maxSizeRequest: 10_000_000,
21
49
  maxConcurrentRequests: 4,
@@ -28,14 +56,75 @@ const CAPABILITIES = {
28
56
  "urn:ietf:params:jmap:submission": {},
29
57
  };
30
58
 
31
- type JmapEnv = AppEnv & { Variables: AppEnv["Variables"] & { jmapUser: { id: string; name: string } } };
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
+ };
32
86
 
33
- function problem(c: Context, status: 400 | 401 | 403 | 404 | 501, type: string, detail: string) {
34
- return c.json({ type, status, detail }, status, { "content-type": "application/problem+json" });
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
+ };
111
+
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
+ });
35
121
  }
36
122
 
37
123
  /** The mailboxes this person can open; each is a JMAP account. */
38
- async function jmapAccounts(env: Env, userId: string): Promise<JmapAccount[]> {
124
+ export async function jmapAccounts(
125
+ env: Env,
126
+ userId: string
127
+ ): Promise<JmapAccount[]> {
39
128
  const rows = await createDb(env.DB)
40
129
  .select({
41
130
  id: mailboxes.id,
@@ -47,121 +136,281 @@ async function jmapAccounts(env: Env, userId: string): Promise<JmapAccount[]> {
47
136
  })
48
137
  .from(mailboxAccess)
49
138
  .innerJoin(mailboxes, eq(mailboxAccess.mailboxId, mailboxes.id))
50
- .innerJoin(domains, eq(mailboxes.domainId, domains.id))
51
- .where(and(eq(mailboxAccess.userId, userId), eq(mailboxes.delivery, "inbox")));
139
+ .where(
140
+ and(eq(mailboxAccess.userId, userId), eq(mailboxes.delivery, "inbox"))
141
+ );
142
+
52
143
  return rows.map((row) => ({
53
144
  ...row,
54
145
  isPersonal: row.ownerUserId === userId,
55
146
  }));
56
147
  }
57
148
 
58
- function sessionObject(origin: string, user: { id: string; name: string }, accounts: JmapAccount[]) {
59
- const primary = accounts.find((account) => account.isPersonal && account.isPrimary)
60
- ?? accounts.find((account) => account.isPersonal)
61
- ?? accounts[0];
149
+ function sessionObject(
150
+ origin: string,
151
+ user: { id: string; name: string },
152
+ accounts: JmapAccount[],
153
+ vapidPublicKey: string | null
154
+ ) {
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
+
62
168
  return {
63
- capabilities: CAPABILITIES,
64
- accounts: Object.fromEntries(accounts.map((account) => [account.id, {
65
- name: account.address,
66
- isPersonal: account.isPersonal,
67
- isReadOnly: false,
68
- accountCapabilities: {
69
- "urn:ietf:params:jmap:mail": {
70
- maxMailboxesPerEmail: 1,
71
- maxMailboxDepth: 1,
72
- maxSizeMailboxName: 80,
73
- maxSizeAttachmentsPerEmail: 0,
74
- emailQuerySortOptions: ["receivedAt", "sentAt"],
75
- 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),
76
178
  },
77
- ...(account.canSend
78
- ? { "urn:ietf:params:jmap:submission": { maxDelayedSend: 0, submissionExtensions: {} } }
79
- : {}),
80
- },
81
- }])),
179
+ ])
180
+ ),
82
181
  primaryAccounts: primary
83
182
  ? {
84
- "urn:ietf:params:jmap:mail": primary.id,
85
- "urn:ietf:params:jmap:submission": primary.id,
86
- }
183
+ "urn:ietf:params:jmap:mail": primary.id,
184
+ "urn:ietf:params:jmap:submission": primary.id,
185
+ }
87
186
  : {},
88
187
  username: primary?.address ?? user.name,
89
- apiUrl: `${origin}/jmap/api`,
90
- downloadUrl: `${origin}/jmap/download/{accountId}/{blobId}/{name}?type={type}`,
91
- uploadUrl: `${origin}/jmap/upload/{accountId}`,
92
- 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}`,
93
192
  state: String(accounts.length),
94
193
  };
95
194
  }
96
195
 
97
- 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
+ ) => {
98
229
  const token = bearerToken(c.req.raw);
99
- const identity = token
100
- ? await authenticateAccessToken(createDb(c.env.DB), token, JMAP_SCOPE)
101
- : null;
102
- if (!identity) {
103
- c.header("www-authenticate", [
104
- `Bearer resource_metadata="${jmapProtectedResourceMetadataUrl(new URL(c.req.url).origin)}"`,
105
- `scope="${JMAP_SCOPE}"`,
106
- ...(token ? ['error="invalid_token"'] : []),
107
- ].join(", "));
108
- 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
+ );
248
+ }
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
+ );
109
262
  }
110
- c.set("jmapUser", { id: identity.user.id, name: identity.user.name });
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
+ });
111
271
  await next();
112
272
  };
113
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
+
114
285
  /**
115
- * JMAP (RFC 8620) for mail (RFC 8621) with OAuth bearer tokens carrying the
116
- * 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.
117
289
  */
118
290
  export const jmapRoutes = new Hono<JmapEnv>()
119
- .get("/.well-known/jmap", (c) => c.redirect("/jmap/session", 302))
120
- .use("/jmap/*", requireJmapAuth)
121
- .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) => {
122
294
  const user = c.get("jmapUser");
123
- return c.json(sessionObject(new URL(c.req.url).origin, user, await jmapAccounts(c.env, user.id)));
295
+ const vapid = await vapidConfiguration(c.env);
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
+ );
124
305
  })
125
- .post("/jmap/api", async (c) => {
126
- if (!c.req.header("content-type")?.toLowerCase().startsWith("application/json")) {
127
- 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
+ );
128
319
  }
320
+
129
321
  let body: unknown;
322
+
130
323
  try {
131
324
  body = await c.req.json();
132
325
  } catch {
133
- 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
+ );
134
343
  }
344
+
135
345
  const user = c.get("jmapUser");
346
+
136
347
  const context: JmapContext = {
137
348
  env: c.env,
138
- user,
349
+ user: { id: user.id, name: user.name },
350
+ clientId: user.clientId,
351
+ scopes: user.scopes,
352
+ vapid: await vapidConfiguration(c.env),
139
353
  accounts: await jmapAccounts(c.env, user.id),
140
354
  requestUrl: c.req.url,
141
355
  defer: (task) => c.executionCtx.waitUntil(task),
142
356
  };
357
+
143
358
  try {
144
- return c.json(await runJmapRequest(context, body));
359
+ return c.json(await runJmapRequest(context, request.data));
145
360
  } catch (error) {
146
- 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
+
147
365
  throw error;
148
366
  }
149
367
  })
150
- .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;
151
372
  const user = c.get("jmapUser");
152
- 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
+
153
378
  if (!account) return problem(c, 404, "about:blank", "Account not found");
154
- const blob = /^(raw|att)~([^~]+)(?:~(.+))?$/u.exec(c.req.param("blobId"));
155
- if (!blob) return problem(c, 404, "about:blank", "Blob not found");
156
- const [, kind, emailId, attachmentId] = blob;
157
- const stub = mailboxStub(c.env, account.id);
158
- const email = await stub.getEmail(emailId!);
159
- const key = kind === "raw"
160
- ? email?.rawMimeR2Key
161
- : email?.attachmentsJson.find((attachment) => attachment.id === attachmentId)?.r2Key;
379
+ const blobId = c.req.param("blobId");
380
+ const upload = UPLOAD_BLOB.exec(blobId);
381
+ const blob = /^(raw|att)~([^~]+)(?:~(.+))?$/u.exec(blobId);
382
+ let key: string | null | undefined;
383
+
384
+ if (upload) {
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
+ );
394
+ } else if (blob) {
395
+ const [, kind, emailId, attachmentId] = blob;
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;
403
+ }
404
+
162
405
  const object = key ? await c.env.MAIL_STORAGE.get(key) : null;
406
+
163
407
  if (!object) return problem(c, 404, "about:blank", "Blob not found");
164
- const type = c.req.query("type") || (kind === "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
+
165
414
  return new Response(object.body, {
166
415
  headers: {
167
416
  "content-type": type,
@@ -170,7 +419,120 @@ export const jmapRoutes = new Hono<JmapEnv>()
170
419
  },
171
420
  });
172
421
  })
173
- .post("/jmap/upload/:accountId", (c) =>
174
- problem(c, 501, "about:blank", "Uploads are not supported yet; send attachments from the app"))
175
- .get("/jmap/eventsource", (c) =>
176
- problem(c, 501, "about:blank", "Push over EventSource is not supported yet"));
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;
427
+ const user = c.get("jmapUser");
428
+
429
+ const account = (await jmapAccounts(c.env, user.id)).find(
430
+ (item) => item.id === c.req.param("accountId")
431
+ );
432
+
433
+ if (!account) return problem(c, 404, "about:blank", "Account not found");
434
+
435
+ // Uploads become attachments of sent mail, so they need send access.
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) {
448
+ return problem(c, 429, "about:blank", "Too many uploads");
449
+ }
450
+
451
+ const contentType =
452
+ c.req.header("content-type")?.trim() || "application/octet-stream";
453
+
454
+ const declared = Number(c.req.header("content-length"));
455
+ // Without a length, buffer the body to learn it; uploads are bounded anyway.
456
+ let body: ReadableStream<Uint8Array> | ArrayBuffer | null = c.req.raw.body;
457
+ let size = declared;
458
+
459
+ if (!Number.isSafeInteger(declared) || declared < 0) {
460
+ body = await c.req.arrayBuffer();
461
+ size = body.byteLength;
462
+ }
463
+
464
+ if (size > MAX_COMPOSER_ATTACHMENT_BYTES) {
465
+ return problem(
466
+ c,
467
+ 413,
468
+ "urn:ietf:params:jmap:error:limit",
469
+ "The upload is too large"
470
+ );
471
+ }
472
+
473
+ try {
474
+ const intent = await createComposerUploadIntent({
475
+ env: c.env,
476
+ mailboxId: account.id,
477
+ userId: user.id,
478
+ filename: "upload",
479
+ contentType,
480
+ size,
481
+ });
482
+
483
+ await storeComposerUploadContent({
484
+ env: c.env,
485
+ mailboxId: account.id,
486
+ userId: user.id,
487
+ uploadId: intent.id,
488
+ body,
489
+ contentType,
490
+ contentLength: size,
491
+ });
492
+
493
+ const upload = await finalizeComposerUpload({
494
+ env: c.env,
495
+ mailboxId: account.id,
496
+ userId: user.id,
497
+ uploadId: intent.id,
498
+ defer: (task) => c.executionCtx.waitUntil(task),
499
+ });
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
+ );
510
+ } catch (error) {
511
+ if (error instanceof UploadValidationError) {
512
+ return problem(c, 400, "about:blank", error.message);
513
+ }
514
+
515
+ throw error;
516
+ }
517
+ })
518
+ .get(`${JMAP_PATH}/eventsource`, async (c) => {
519
+ const refused = missingScope(c, MAIL_READ_SCOPE);
520
+
521
+ if (refused) return refused;
522
+ const user = c.get("jmapUser");
523
+
524
+ return jmapEventStream({
525
+ env: c.env,
526
+ accounts: await jmapAccounts(c.env, user.id),
527
+ types: c.req.query("types") ?? "*",
528
+ closeAfterState: c.req.query("closeafter") === "state",
529
+ pingSeconds: Number(c.req.query("ping") ?? 0),
530
+ // The stream outlives the request check; the token is checked again on each ping.
531
+ stillAuthorized: async () =>
532
+ Boolean(
533
+ (await jmapIdentity(c, user.token))?.scopes.includes(MAIL_READ_SCOPE)
534
+ ),
535
+ currentAccounts: () => jmapAccounts(c.env, user.id),
536
+ defer: (task) => c.executionCtx.waitUntil(task),
537
+ });
538
+ });