@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.
- package/README.md +23 -20
- package/alchemy/index.ts +273 -0
- package/drizzle/mailbox/0000_puzzling_dracula.sql +149 -0
- package/drizzle/mailbox/0001_mute_jack_flag.sql +12 -0
- package/drizzle/mailbox/meta/0000_snapshot.json +1002 -0
- package/drizzle/mailbox/meta/0001_snapshot.json +1002 -0
- package/drizzle/mailbox/meta/_journal.json +20 -0
- package/drizzle/mailbox/migrations.js +12 -0
- package/index.ts +3 -1
- package/migrations/0000_dry_moon_knight.sql +77 -0
- package/migrations/meta/0000_snapshot.json +248 -106
- package/migrations/meta/_journal.json +2 -2
- package/package.json +74 -68
- package/shared/attachment-preview.ts +37 -27
- package/shared/folder-order.ts +106 -0
- package/shared/mail-authentication.ts +8 -3
- package/shared/mail-feedback.ts +18 -25
- package/shared/mail-headers.ts +114 -39
- package/shared/mail-import.ts +38 -0
- package/shared/mail-path.ts +42 -0
- package/shared/mail-received.ts +174 -31
- package/shared/mail-remote.ts +59 -2
- package/shared/mail-sender-intel.ts +22 -4
- package/shared/mail.ts +78 -26
- package/shared/module.ts +33 -0
- package/shared/office-preview.ts +14 -2
- package/shared/pdfjs-assets.ts +35 -0
- package/shared/permissions.ts +73 -0
- package/shared/webhooks.ts +41 -0
- package/src/admin/blocked-senders.tsx +189 -0
- package/src/client.tsx +97 -0
- package/src/lib/mail-api.ts +9 -0
- package/src/mail/attachment-preview-dialog.tsx +161 -0
- package/src/mail/blocked-senders.tsx +138 -0
- package/src/mail/compose-window-chrome.tsx +194 -0
- package/src/mail/compose-window.tsx +486 -0
- package/src/mail/composer-asset-bookmarks.ts +409 -0
- package/src/mail/composer-asset.tsx +229 -0
- package/src/mail/composer-attachment-list.tsx +138 -0
- package/src/mail/composer-editor-document.ts +65 -0
- package/src/mail/composer-editor.tsx +284 -0
- package/src/mail/composer-linked-attachment-text.ts +12 -0
- package/src/mail/composer-recipient-fields.tsx +165 -0
- package/src/mail/composer-recipients.ts +208 -0
- package/src/mail/composer-session.ts +562 -0
- package/src/mail/composer-toolbar.tsx +303 -0
- package/src/mail/composer-upload-client.ts +105 -0
- package/src/mail/composer-upload-progress.ts +53 -0
- package/src/mail/conversation-list.tsx +550 -0
- package/src/mail/conversation-loading-skeleton.tsx +119 -0
- package/src/mail/conversation-message.tsx +346 -0
- package/src/mail/conversation-reply.tsx +470 -0
- package/src/mail/conversation-selection-toolbar.tsx +322 -0
- package/src/mail/conversation-view.tsx +437 -0
- package/src/mail/delivery-indicator.tsx +272 -0
- package/src/mail/email-html-body.tsx +203 -0
- package/src/mail/folder-glyph.tsx +46 -0
- package/src/mail/folder-manager.tsx +532 -0
- package/src/mail/format-bytes.ts +7 -0
- package/src/mail/mail-app-bar.tsx +253 -0
- package/src/mail/mail-background.tsx +12 -0
- package/src/mail/mail-dock.tsx +137 -0
- package/src/mail/mail-folders.ts +44 -0
- package/src/mail/mail-layout.css +236 -0
- package/src/mail/mail-location.ts +73 -0
- package/src/mail/mail-mailbox-sheet.tsx +275 -0
- package/src/mail/mail-nav-rail.tsx +129 -0
- package/src/mail/mail-nav.tsx +324 -0
- package/src/mail/mail-prefetch.ts +59 -0
- package/src/mail/mail-primitives.tsx +66 -0
- package/src/mail/mail-queries.ts +209 -0
- package/src/mail/mail-query-cache.ts +486 -0
- package/src/mail/mail-seed.ts +47 -0
- package/src/mail/mail-shell.tsx +126 -0
- package/src/mail/mailbox-ai-settings.tsx +185 -0
- package/src/mail/mailbox-realtime.tsx +251 -0
- package/src/mail/mailbox-route.tsx +15 -0
- package/src/mail/message-actions.tsx +353 -0
- package/src/mail/message-attachments.tsx +200 -0
- package/src/mail/message-format.ts +75 -0
- package/src/mail/message-header.tsx +260 -0
- package/src/mail/message-translation.tsx +225 -0
- package/src/mail/original-message-sheet.tsx +619 -0
- package/src/mail/original-message.ts +191 -0
- package/src/mail/outbound-notification.ts +53 -0
- package/src/mail/pane-splitter.tsx +117 -0
- package/src/mail/pdf-preview-toolbar.tsx +152 -0
- package/src/mail/pdf-preview.css +44 -0
- package/src/mail/pdf-preview.tsx +156 -0
- package/src/mail/pdf-translation-layout.ts +95 -0
- package/src/mail/print-message.ts +92 -0
- package/src/mail/reader-pane.tsx +535 -0
- package/src/mail/recipient-combobox.tsx +335 -0
- package/src/mail/recipient-field-row.tsx +34 -0
- package/src/mail/reply-to-warning.tsx +50 -0
- package/src/mail/sanitize-email-html.ts +430 -0
- package/src/mail/sender-actions.tsx +149 -0
- package/src/mail/sender-authentication.tsx +485 -0
- package/src/mail/sender-dialogs.tsx +384 -0
- package/src/mail/sender-security.tsx +545 -0
- package/src/mail/toolbar-tooltip.tsx +29 -0
- package/src/mail/translation-html.ts +49 -0
- package/src/mail/translation-language.ts +21 -0
- package/src/mail/types.ts +53 -0
- package/src/mail/unread-document-indicator.tsx +60 -0
- package/src/mail/use-compose-submission.ts +208 -0
- package/src/mail/use-composer-attachment-preflight.ts +184 -0
- package/src/mail/use-composer-submission.ts +117 -0
- package/src/mail/use-conversation-selection.ts +186 -0
- package/src/mail/use-mail-controller.ts +427 -0
- package/src/mail/use-mail-data.ts +279 -0
- package/src/mail/use-mail-safety.ts +155 -0
- package/src/mail/use-mail-send.ts +142 -0
- package/src/mail/use-pdf-translation-overlay.ts +156 -0
- package/src/mail/use-pdf-translation.ts +100 -0
- package/src/mail/use-pdf-viewer.ts +215 -0
- package/src/mail/use-reply-submission.ts +114 -0
- package/src/mail/use-sanitized-email-html.ts +20 -0
- package/src/mail/use-visible-message-read.ts +138 -0
- package/src/pwa/push-subscription.ts +151 -0
- package/src/settings/mail-apps-page.tsx +235 -0
- package/src/settings/notifications-page.tsx +291 -0
- package/worker/admin/blocked-sender-routes.ts +166 -0
- package/worker/admin/schemas.ts +11 -0
- package/worker/bindings.d.ts +14 -10
- package/worker/db/schema.ts +90 -34
- package/worker/jmap/eventsource.ts +169 -0
- package/worker/jmap/methods.ts +1716 -361
- package/worker/jmap/push-types.ts +27 -0
- package/worker/jmap/push.ts +207 -0
- package/worker/jmap/routes.ts +448 -86
- package/worker/mail/access.ts +258 -21
- package/worker/mail/ai-classification.ts +36 -20
- package/worker/mail/ai-translation.ts +13 -6
- package/worker/mail/auth-headers.ts +395 -137
- package/worker/mail/bimi.ts +200 -73
- package/worker/mail/bootstrap.ts +79 -0
- package/worker/mail/capped-body.ts +36 -0
- package/worker/mail/classification-signals.ts +35 -25
- package/worker/mail/conversation-cursor.ts +30 -19
- package/worker/mail/delivery-events.ts +88 -62
- package/worker/mail/delivery-facts.ts +46 -10
- package/worker/mail/demo-routes.ts +34 -10
- package/worker/mail/doh.ts +62 -23
- package/worker/mail/downloads.ts +75 -40
- package/worker/mail/edge-cache.ts +155 -0
- package/worker/mail/header-metadata.ts +84 -52
- package/worker/mail/impersonation.ts +160 -38
- package/worker/mail/import-routes.ts +313 -0
- package/worker/mail/inbound-delivery.ts +19 -9
- package/worker/mail/inbound-threading.ts +18 -8
- package/worker/mail/inbound.ts +82 -40
- package/worker/mail/ip-intel.ts +110 -27
- package/worker/mail/isolate-cache.ts +35 -0
- package/worker/mail/link-domains.ts +29 -7
- package/worker/mail/mailbox-deletion.ts +10 -4
- package/worker/mail/mailbox-directory.ts +16 -6
- package/worker/mail/mailing-list.ts +94 -39
- package/worker/mail/message-security.ts +90 -15
- package/worker/mail/message-view.ts +18 -6
- package/worker/mail/office-conversion.ts +31 -9
- package/worker/mail/office-preview-container.ts +40 -13
- package/worker/mail/office-preview-queue.ts +76 -32
- package/worker/mail/org-domain.ts +8 -1
- package/worker/mail/outbound-content.ts +71 -26
- package/worker/mail/outbound-delivery.ts +31 -17
- package/worker/mail/outbound-service.ts +48 -30
- package/worker/mail/outbound-threading.ts +30 -17
- package/worker/mail/outbound.ts +97 -70
- package/worker/mail/outgoing-context.ts +25 -15
- package/worker/mail/participants.ts +44 -29
- package/worker/mail/push-notifications.ts +283 -171
- package/worker/mail/quote-parser.ts +21 -10
- package/worker/mail/r2-presigned-urls.ts +31 -25
- package/worker/mail/receive.ts +23 -11
- package/worker/mail/recipients.ts +6 -1
- package/worker/mail/remote-proxy.ts +187 -31
- package/worker/mail/remote-routes.ts +87 -0
- package/worker/mail/remote-token.ts +104 -0
- package/worker/mail/repeat.ts +19 -0
- package/worker/mail/reply-plan.ts +62 -33
- package/worker/mail/rfc.ts +32 -7
- package/worker/mail/routes.ts +871 -542
- package/worker/mail/safety-routes.ts +329 -202
- package/worker/mail/schemas.ts +84 -105
- package/worker/mail/search.ts +1 -0
- package/worker/mail/security-settings.ts +41 -9
- package/worker/mail/sender-intel.ts +206 -51
- package/worker/mail/spamhaus.ts +92 -45
- package/worker/mail/unsubscribe.ts +76 -18
- package/worker/mail/uploads.ts +153 -91
- package/worker/mail/webhook-source.ts +35 -12
- package/worker/mail/workspace-safety.ts +97 -38
- package/worker/mailbox/demo-html.ts +7 -7
- package/worker/mailbox/demo-seed.ts +10 -44
- package/worker/mailbox/demo.ts +597 -227
- package/worker/mailbox/email-index.ts +53 -0
- package/worker/mailbox/folder-model.ts +53 -17
- package/worker/mailbox/import-placement.ts +88 -0
- package/worker/mailbox/inbox-counts.ts +106 -0
- package/worker/mailbox/index.ts +1761 -737
- package/worker/mailbox/jmap-store.ts +139 -35
- package/worker/mailbox/model.ts +7 -14
- package/worker/mailbox/office-preview-jobs.ts +56 -25
- package/worker/mailbox/schema.ts +87 -66
- package/worker/mailbox/senders.ts +176 -70
- package/worker/mcp/mail-action-tools.ts +128 -87
- package/worker/mcp/mail-compose-tools.ts +133 -82
- package/worker/mcp/mail-query-tools.ts +120 -71
- package/worker/mcp/mail-safety-tools.ts +321 -248
- package/worker/mcp/schemas.ts +43 -0
- package/worker/mcp/tools.ts +13 -10
- package/worker/module.ts +43 -18
- package/worker/sql.d.ts +8 -0
- package/alchemy.ts +0 -126
- package/containers/office-preview/Dockerfile +0 -10
- package/migrations/0000_email.sql +0 -53
- package/shared/mail-rules.ts +0 -156
- package/worker/admin/report-routes.ts +0 -164
- package/worker/mail/reported-messages.ts +0 -68
- package/worker/mailbox/legacy-migrations.ts +0 -41
- package/worker/mailbox/migrations.ts +0 -10
- package/worker/mailbox/rules.ts +0 -110
package/worker/mail/routes.ts
CHANGED
|
@@ -1,36 +1,60 @@
|
|
|
1
|
+
import {
|
|
2
|
+
oauthScope,
|
|
3
|
+
zValidator,
|
|
4
|
+
requireAuthWith,
|
|
5
|
+
mailboxKind,
|
|
6
|
+
apiError,
|
|
7
|
+
createId,
|
|
8
|
+
normalizeMailboxAddress,
|
|
9
|
+
aiObjectRunner,
|
|
10
|
+
aiFeatureEnabled,
|
|
11
|
+
aiModel,
|
|
12
|
+
timed,
|
|
13
|
+
overRateLimit,
|
|
14
|
+
} from "@open-workspace/core/module";
|
|
15
|
+
import type { AppEnv } from "@open-workspace/core/module";
|
|
16
|
+
import { Hono } from "hono";
|
|
17
|
+
import type { Context } from "hono";
|
|
1
18
|
import { z } from "zod";
|
|
2
|
-
|
|
19
|
+
|
|
3
20
|
import { attachmentPreview } from "../../shared/attachment-preview";
|
|
4
|
-
import { officePreviewKey } from "../../shared/office-preview";
|
|
5
|
-
import { desc, eq } from "drizzle-orm";
|
|
6
|
-
import { Hono } from "hono";
|
|
7
21
|
import {
|
|
8
22
|
baseSubject,
|
|
9
23
|
isComposerInlineImageContentType,
|
|
10
24
|
} from "../../shared/mail";
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
25
|
+
import { remoteImageUrls } from "../../shared/mail-remote";
|
|
26
|
+
import { MAX_TRANSLATION_CHARACTERS } from "../../shared/mail-translation";
|
|
27
|
+
import { officePreviewKey } from "../../shared/office-preview";
|
|
14
28
|
import {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
} from "
|
|
19
|
-
import type { AppEnv } from "@open-workspace/core/worker/env.ts";
|
|
20
|
-
import { apiError } from "@open-workspace/core/worker/lib/http.ts";
|
|
21
|
-
import { createId, normalizeMailboxAddress } from "@open-workspace/core/worker/lib/ids.ts";
|
|
29
|
+
MAIL_ORGANIZE_SCOPE,
|
|
30
|
+
MAIL_READ_SCOPE,
|
|
31
|
+
MAIL_SEND_SCOPE,
|
|
32
|
+
} from "../../shared/permissions";
|
|
22
33
|
import { mailboxStub } from "../mailbox";
|
|
34
|
+
import type { MailboxDO } from "../mailbox";
|
|
23
35
|
import type { Email } from "../mailbox/schema";
|
|
24
|
-
import {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
36
|
+
import {
|
|
37
|
+
accessibleMailbox,
|
|
38
|
+
accessibleMailboxes,
|
|
39
|
+
mailAccessCompanion,
|
|
40
|
+
} from "./access";
|
|
41
|
+
import type { MailboxListRow } from "./access";
|
|
28
42
|
import { translateEmailSegments } from "./ai-translation";
|
|
29
|
-
import {
|
|
43
|
+
import { BIMI_LOGO_HEADERS, bimiLogoPath, bimiObjectKey } from "./bimi";
|
|
30
44
|
import {
|
|
31
45
|
decodeConversationCursor,
|
|
32
46
|
encodeConversationCursor,
|
|
33
47
|
} from "./conversation-cursor";
|
|
48
|
+
import { readStoredBody } from "./edge-cache";
|
|
49
|
+
import {
|
|
50
|
+
headerAuthentication,
|
|
51
|
+
senderIntelPending,
|
|
52
|
+
withSenderIntel,
|
|
53
|
+
} from "./header-metadata";
|
|
54
|
+
import { listMailboxUsersByIds } from "./mailbox-directory";
|
|
55
|
+
import type { SenderHistory } from "./message-security";
|
|
56
|
+
import { emailListKey, emailSecurity, senderStatus } from "./message-view";
|
|
57
|
+
import type { MessageSafetyContext } from "./message-view";
|
|
34
58
|
import {
|
|
35
59
|
ComposerAttachmentLimitError,
|
|
36
60
|
preflightOutgoingAttachments,
|
|
@@ -46,15 +70,10 @@ import {
|
|
|
46
70
|
resolveReplyContext,
|
|
47
71
|
} from "./outgoing-context";
|
|
48
72
|
import { participantLabels } from "./participants";
|
|
73
|
+
import { signR2GetUrl } from "./r2-presigned-urls";
|
|
74
|
+
import { signRemoteToken } from "./remote-token";
|
|
49
75
|
import { buildReplyPlan } from "./reply-plan";
|
|
50
|
-
import { headerAuthentication, withHeaderMetadata, withSenderIntel } from "./header-metadata";
|
|
51
|
-
import { messageSecurity, type SenderHistory } from "./message-security";
|
|
52
|
-
import { BIMI_LOGO_HEADERS, bimiLogoPath, bimiObjectKey } from "./bimi";
|
|
53
|
-
import { storedSenderIntel } from "./sender-intel";
|
|
54
|
-
import { emailListKey, emailSecurity, senderStatus, type MessageSafetyContext } from "./message-view";
|
|
55
|
-
import { workspaceBlockPatterns } from "./workspace-safety";
|
|
56
76
|
import { mailSafetyRoutes } from "./safety-routes";
|
|
57
|
-
import { spamhausDqsKey, workspaceIdentity, type WorkspaceIdentity } from "./security-settings";
|
|
58
77
|
import {
|
|
59
78
|
attachmentPreflightSchema,
|
|
60
79
|
bulkConversationActionSchema,
|
|
@@ -70,48 +89,52 @@ import {
|
|
|
70
89
|
messageTranslationSchema,
|
|
71
90
|
recipientSuggestionQuerySchema,
|
|
72
91
|
renameFolderSchema,
|
|
73
|
-
remoteProxyQuerySchema,
|
|
74
92
|
reorderFoldersSchema,
|
|
75
93
|
replySchema,
|
|
76
94
|
uploadIdSchema,
|
|
77
95
|
} from "./schemas";
|
|
78
|
-
import {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
} from "./remote-proxy";
|
|
82
|
-
import { checkRateLimit } from "@open-workspace/core/worker/lib/rate-limit.ts";
|
|
96
|
+
import { cachedWorkspaceIdentity, spamhausDqsKey } from "./security-settings";
|
|
97
|
+
import type { WorkspaceIdentity } from "./security-settings";
|
|
98
|
+
import { storedSenderIntel } from "./sender-intel";
|
|
83
99
|
import {
|
|
84
100
|
createComposerUploadIntent,
|
|
85
|
-
DirectUploadUnavailableError,
|
|
86
101
|
discardComposerUploads,
|
|
87
102
|
finalizeComposerUpload,
|
|
88
|
-
storeComposerUploadContent,
|
|
89
103
|
UploadValidationError,
|
|
90
104
|
} from "./uploads";
|
|
91
|
-
import {
|
|
105
|
+
import { cachedWorkspaceBlockPatterns } from "./workspace-safety";
|
|
92
106
|
|
|
93
107
|
function mediaType(contentType: string) {
|
|
94
108
|
return contentType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
|
|
95
109
|
}
|
|
96
110
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
}
|
|
111
|
+
/**
|
|
112
|
+
* The range R2 returned. Its runtime object can carry every key of R2Range
|
|
113
|
+
* with the unused ones undefined (`{ offset, length, suffix: undefined }`),
|
|
114
|
+
* so it is parsed rather than narrowed with `in`.
|
|
115
|
+
*/
|
|
116
|
+
const returnedRangeSchema = z.union([
|
|
117
|
+
z.object({ suffix: z.number() }),
|
|
118
|
+
z.object({
|
|
119
|
+
offset: z.number().optional(),
|
|
120
|
+
length: z.number().optional(),
|
|
121
|
+
}),
|
|
122
|
+
]);
|
|
100
123
|
|
|
101
124
|
function returnedObjectRange(object: R2ObjectBody, totalBytes: number) {
|
|
102
125
|
if (!object.range) return { offset: 0, length: totalBytes };
|
|
103
|
-
const
|
|
104
|
-
|
|
105
|
-
|
|
126
|
+
const range = returnedRangeSchema.parse(object.range);
|
|
127
|
+
|
|
128
|
+
if ("suffix" in range) {
|
|
129
|
+
const length = Math.min(range.suffix, totalBytes);
|
|
130
|
+
|
|
106
131
|
return { offset: totalBytes - length, length };
|
|
107
132
|
}
|
|
108
133
|
|
|
109
|
-
const offset =
|
|
134
|
+
const offset = range.offset ?? 0;
|
|
110
135
|
const available = Math.max(0, totalBytes - offset);
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
: undefined;
|
|
114
|
-
const length = Math.min(requestedLength ?? available, available);
|
|
136
|
+
const length = Math.min(range.length ?? available, available);
|
|
137
|
+
|
|
115
138
|
return { offset, length };
|
|
116
139
|
}
|
|
117
140
|
|
|
@@ -124,6 +147,7 @@ function storedObjectResponse(input: {
|
|
|
124
147
|
}) {
|
|
125
148
|
const { object } = input;
|
|
126
149
|
const returnedRange = returnedObjectRange(object, input.totalBytes);
|
|
150
|
+
|
|
127
151
|
const headers = new Headers({
|
|
128
152
|
"accept-ranges": "bytes",
|
|
129
153
|
"cache-control": "private, no-store",
|
|
@@ -132,21 +156,23 @@ function storedObjectResponse(input: {
|
|
|
132
156
|
"content-type": input.contentType,
|
|
133
157
|
"x-content-type-options": "nosniff",
|
|
134
158
|
});
|
|
159
|
+
|
|
135
160
|
if (!input.rangeRequested || !object.range) {
|
|
136
161
|
return new Response(object.body, { headers });
|
|
137
162
|
}
|
|
138
163
|
|
|
139
164
|
headers.set(
|
|
140
165
|
"content-range",
|
|
141
|
-
`bytes ${returnedRange.offset}-${returnedRange.offset + returnedRange.length - 1}/${input.totalBytes}
|
|
166
|
+
`bytes ${returnedRange.offset}-${returnedRange.offset + returnedRange.length - 1}/${input.totalBytes}`
|
|
142
167
|
);
|
|
168
|
+
|
|
143
169
|
return new Response(object.body, { status: 206, headers });
|
|
144
170
|
}
|
|
145
171
|
|
|
146
172
|
function getStoredObject(
|
|
147
173
|
bucket: R2Bucket,
|
|
148
174
|
key: string,
|
|
149
|
-
range: string | undefined
|
|
175
|
+
range: string | undefined
|
|
150
176
|
) {
|
|
151
177
|
return range
|
|
152
178
|
? bucket.get(key, { range: new Headers({ range }) })
|
|
@@ -155,12 +181,17 @@ function getStoredObject(
|
|
|
155
181
|
|
|
156
182
|
/** Our own route for a BIMI logo, when DMARC allowed one for this message. */
|
|
157
183
|
function senderLogoUrl(email: Email) {
|
|
158
|
-
const bimi =
|
|
184
|
+
const bimi =
|
|
185
|
+
email.direction === "incoming"
|
|
186
|
+
? storedSenderIntel(email.senderIntelJson)?.bimi
|
|
187
|
+
: null;
|
|
188
|
+
|
|
159
189
|
return bimi?.status === "ok" ? bimiLogoPath(bimi.domain) : null;
|
|
160
190
|
}
|
|
161
191
|
|
|
162
192
|
function toMessageSummary(email: Email) {
|
|
163
193
|
const from = email.fromJson[0] ?? { address: "unknown@invalid", name: null };
|
|
194
|
+
|
|
164
195
|
return {
|
|
165
196
|
id: email.id,
|
|
166
197
|
conversationId: email.conversationId,
|
|
@@ -183,10 +214,10 @@ function toMessageSummary(email: Email) {
|
|
|
183
214
|
|
|
184
215
|
/** The workspace mailing list a received copy came through, if any. */
|
|
185
216
|
function workspaceListAddress(email: Email) {
|
|
186
|
-
return email.direction === "incoming"
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
217
|
+
return email.direction === "incoming" &&
|
|
218
|
+
email.listPostAddress &&
|
|
219
|
+
email.envelopeTo &&
|
|
220
|
+
normalizeMailboxAddress(email.envelopeTo) === email.listPostAddress
|
|
190
221
|
? email.listPostAddress
|
|
191
222
|
: null;
|
|
192
223
|
}
|
|
@@ -200,12 +231,12 @@ function toMessageDetail(
|
|
|
200
231
|
bodyHtml: string | null,
|
|
201
232
|
readReceipt: {
|
|
202
233
|
isRead: boolean;
|
|
203
|
-
viewedBy:
|
|
234
|
+
viewedBy: {
|
|
204
235
|
userId: string;
|
|
205
236
|
name: string;
|
|
206
237
|
readAt: Date;
|
|
207
|
-
}
|
|
208
|
-
}
|
|
238
|
+
}[];
|
|
239
|
+
}
|
|
209
240
|
) {
|
|
210
241
|
return {
|
|
211
242
|
...toMessageSummary(email),
|
|
@@ -218,9 +249,12 @@ function toMessageDetail(
|
|
|
218
249
|
listId: email.listId,
|
|
219
250
|
viaList: workspaceListAddress(email),
|
|
220
251
|
unsubscription: safety.unsubscriptions[emailListKey(email) ?? ""] ?? null,
|
|
221
|
-
|
|
252
|
+
reported: email.reportLabel !== null,
|
|
222
253
|
screening: email.screeningJson,
|
|
223
|
-
senderIntel:
|
|
254
|
+
senderIntel:
|
|
255
|
+
email.direction === "incoming"
|
|
256
|
+
? storedSenderIntel(email.senderIntelJson)
|
|
257
|
+
: null,
|
|
224
258
|
hasOriginal: Boolean(email.rawMimeR2Key),
|
|
225
259
|
attachments: email.attachmentsJson.map((file) => ({
|
|
226
260
|
id: file.id,
|
|
@@ -239,10 +273,19 @@ function toMessageDetail(
|
|
|
239
273
|
function conversationLabel(ownAddress: string, latest: Email) {
|
|
240
274
|
const labels = participantLabels(
|
|
241
275
|
[...latest.fromJson, ...latest.toJson, ...latest.ccJson],
|
|
242
|
-
ownAddress
|
|
276
|
+
ownAddress
|
|
243
277
|
);
|
|
244
|
-
|
|
278
|
+
|
|
279
|
+
if (!labels.length) {
|
|
280
|
+
return (
|
|
281
|
+
latest.fromJson[0]?.name ||
|
|
282
|
+
latest.fromJson[0]?.address ||
|
|
283
|
+
"Unknown sender"
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
|
|
245
287
|
if (labels.length <= 3) return labels.join(", ");
|
|
288
|
+
|
|
246
289
|
return `${labels.slice(0, 3).join(", ")} +${labels.length - 3}`;
|
|
247
290
|
}
|
|
248
291
|
|
|
@@ -254,18 +297,21 @@ function outboundTransportState(email: Email) {
|
|
|
254
297
|
if (email.transportState === "received") {
|
|
255
298
|
throw new Error("Outgoing message has an inbound transport state");
|
|
256
299
|
}
|
|
300
|
+
|
|
257
301
|
return email.transportState;
|
|
258
302
|
}
|
|
259
303
|
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
304
|
+
/** Keeps `work` running after the response; failures are only logged. */
|
|
305
|
+
function runInBackground(c: Context<AppEnv>, work: Promise<unknown>) {
|
|
306
|
+
const guarded = work.catch((error) =>
|
|
307
|
+
console.error("Background work failed", error)
|
|
308
|
+
);
|
|
309
|
+
|
|
310
|
+
try {
|
|
311
|
+
c.executionCtx.waitUntil(guarded);
|
|
312
|
+
} catch {
|
|
313
|
+
// No execution context (in-process calls): the promise still runs.
|
|
314
|
+
}
|
|
269
315
|
}
|
|
270
316
|
|
|
271
317
|
function outgoingResponse(email: Email, detached: boolean) {
|
|
@@ -277,189 +323,189 @@ function outgoingResponse(email: Email, detached: boolean) {
|
|
|
277
323
|
transportError: email.transportError,
|
|
278
324
|
detached,
|
|
279
325
|
externalizedAttachments: email.attachmentsJson.filter(
|
|
280
|
-
(file) => file.delivery === "download_link"
|
|
326
|
+
(file) => file.delivery === "download_link"
|
|
281
327
|
).length,
|
|
282
328
|
};
|
|
283
329
|
}
|
|
284
330
|
|
|
285
|
-
function outgoingFailure(
|
|
286
|
-
c: Parameters<typeof apiError>[0],
|
|
287
|
-
error: unknown,
|
|
288
|
-
) {
|
|
289
|
-
if (error instanceof DirectUploadUnavailableError) {
|
|
290
|
-
return apiError(c, 503, "UNAVAILABLE", error.message);
|
|
291
|
-
}
|
|
331
|
+
function outgoingFailure(c: Parameters<typeof apiError>[0], cause: unknown) {
|
|
292
332
|
if (
|
|
293
|
-
|
|
294
|
-
|
|
333
|
+
cause instanceof ComposerAttachmentLimitError ||
|
|
334
|
+
cause instanceof UploadValidationError
|
|
295
335
|
) {
|
|
296
|
-
return apiError(c, 400, "BAD_REQUEST",
|
|
336
|
+
return apiError(c, 400, "BAD_REQUEST", cause.message);
|
|
297
337
|
}
|
|
298
|
-
|
|
299
|
-
|
|
338
|
+
|
|
339
|
+
if (cause instanceof OutgoingRequestConflictError) {
|
|
340
|
+
return apiError(c, 409, "CONFLICT", cause.message);
|
|
300
341
|
}
|
|
301
|
-
|
|
302
|
-
|
|
342
|
+
|
|
343
|
+
if (cause instanceof OutgoingContextError) {
|
|
344
|
+
return apiError(c, cause.status, cause.code, cause.message);
|
|
303
345
|
}
|
|
304
|
-
|
|
346
|
+
|
|
347
|
+
throw cause;
|
|
305
348
|
}
|
|
306
349
|
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
isPrimary: mailboxes.isPrimary,
|
|
318
|
-
canSend: mailboxAccess.canSend,
|
|
350
|
+
/**
|
|
351
|
+
* GET /mailboxes without `ok`. Each mailbox's `version` is the change
|
|
352
|
+
* counter its `unreadCount` reflects; see `update:<version>`.
|
|
353
|
+
*/
|
|
354
|
+
export function mailboxListView(rows: MailboxListRow[]) {
|
|
355
|
+
return {
|
|
356
|
+
mailboxes: rows.map(
|
|
357
|
+
({ ownerUserId, isPrimary: _isPrimary, ...mailbox }) => ({
|
|
358
|
+
...mailbox,
|
|
359
|
+
kind: mailboxKind(ownerUserId),
|
|
319
360
|
})
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
.where(eq(mailboxAccess.userId, userId))
|
|
324
|
-
.orderBy(
|
|
325
|
-
mailboxKindOrderSql,
|
|
326
|
-
desc(mailboxes.isPrimary),
|
|
327
|
-
mailboxes.displayName,
|
|
328
|
-
);
|
|
361
|
+
),
|
|
362
|
+
};
|
|
363
|
+
}
|
|
329
364
|
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
365
|
+
/** GET /mailboxes/:id/folders without `ok`. */
|
|
366
|
+
export function folderListView(view: ReturnType<MailboxDO["folderView"]>) {
|
|
367
|
+
return {
|
|
368
|
+
version: view.version,
|
|
369
|
+
folders: view.folders.map((folder) => ({
|
|
370
|
+
id: folder.id,
|
|
371
|
+
name: folder.name,
|
|
372
|
+
kind: folder.kind,
|
|
373
|
+
systemType: folder.systemType,
|
|
374
|
+
/** The folder's place in the mailbox's one order; Inbox is 0. */
|
|
375
|
+
sortOrder: folder.sortOrder,
|
|
376
|
+
totalCount: folder.totalCount,
|
|
377
|
+
unreadCount: folder.unreadCount,
|
|
378
|
+
})),
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** GET /conversations without `ok`. */
|
|
383
|
+
export function conversationPageView(
|
|
384
|
+
page: NonNullable<ReturnType<MailboxDO["listConversations"]>>,
|
|
385
|
+
mailboxAddress: string
|
|
386
|
+
) {
|
|
387
|
+
return {
|
|
388
|
+
version: page.version,
|
|
389
|
+
conversations: page.items.map((item) => ({
|
|
390
|
+
...toMessageSummary(item.email),
|
|
391
|
+
subject: conversationSubject(item.email.subject),
|
|
392
|
+
conversationLabel: conversationLabel(mailboxAddress, item.email),
|
|
393
|
+
messageCount: item.messageCount,
|
|
394
|
+
unreadCount: item.unreadCount,
|
|
395
|
+
isUnread: item.unreadCount > 0,
|
|
396
|
+
hasIncoming: item.hasIncoming,
|
|
397
|
+
})),
|
|
398
|
+
nextCursor: page.next ? encodeConversationCursor(page.next) : null,
|
|
399
|
+
};
|
|
400
|
+
}
|
|
340
401
|
|
|
341
|
-
|
|
402
|
+
export const mailRoutes = new Hono<AppEnv>()
|
|
403
|
+
.use("*", requireAuthWith(mailAccessCompanion))
|
|
404
|
+
.get("/mailboxes", oauthScope(MAIL_READ_SCOPE), async (c) => {
|
|
405
|
+
const rows = await accessibleMailboxes(c);
|
|
406
|
+
|
|
407
|
+
return c.json({ ok: true as const, ...mailboxListView(rows) });
|
|
342
408
|
})
|
|
343
|
-
.get("/mailboxes/:id/realtime", async (c) => {
|
|
409
|
+
.get("/mailboxes/:id/realtime", oauthScope(MAIL_READ_SCOPE), async (c) => {
|
|
344
410
|
if (c.get("authKind") !== "session") {
|
|
345
411
|
return apiError(
|
|
346
412
|
c,
|
|
347
413
|
401,
|
|
348
414
|
"UNAUTHORIZED",
|
|
349
|
-
"A browser session is required for realtime updates"
|
|
415
|
+
"A browser session is required for realtime updates"
|
|
350
416
|
);
|
|
351
417
|
}
|
|
418
|
+
|
|
352
419
|
const origin = c.req.header("origin");
|
|
420
|
+
|
|
353
421
|
if (!origin || origin !== new URL(c.req.url).origin) {
|
|
354
422
|
return apiError(c, 403, "FORBIDDEN", "Cross-origin WebSocket rejected");
|
|
355
423
|
}
|
|
424
|
+
|
|
356
425
|
if (c.req.header("upgrade")?.toLowerCase() !== "websocket") {
|
|
357
426
|
return apiError(c, 426, "UPGRADE_REQUIRED", "WebSocket upgrade required");
|
|
358
427
|
}
|
|
428
|
+
|
|
359
429
|
const mailboxId = c.req.param("id");
|
|
360
430
|
const user = c.get("user");
|
|
361
|
-
|
|
431
|
+
|
|
432
|
+
if (!(await accessibleMailbox(c, mailboxId, "read"))) {
|
|
362
433
|
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
363
434
|
}
|
|
435
|
+
|
|
364
436
|
const headers = new Headers(c.req.raw.headers);
|
|
365
437
|
headers.set("x-openworkspace-user-id", user.id);
|
|
366
438
|
headers.set("x-openworkspace-session-id", c.get("sessionId"));
|
|
367
|
-
headers.set(
|
|
439
|
+
headers.set(
|
|
440
|
+
"x-openworkspace-session-token-hash",
|
|
441
|
+
c.get("sessionTokenHash")
|
|
442
|
+
);
|
|
368
443
|
headers.set(
|
|
369
444
|
"x-openworkspace-visibility",
|
|
370
|
-
c.req.query("visibility") === "hidden" ? "hidden" : "visible"
|
|
445
|
+
c.req.query("visibility") === "hidden" ? "hidden" : "visible"
|
|
371
446
|
);
|
|
447
|
+
|
|
372
448
|
return mailboxStub(c.env, mailboxId).fetch(
|
|
373
|
-
new Request(c.req.raw, { headers })
|
|
449
|
+
new Request(c.req.raw, { headers })
|
|
374
450
|
);
|
|
375
451
|
})
|
|
376
452
|
.post(
|
|
377
453
|
"/uploads",
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
mailboxQuerySchema.extend({
|
|
381
|
-
directOnly: z.literal("true").optional(),
|
|
382
|
-
}),
|
|
383
|
-
),
|
|
454
|
+
oauthScope(MAIL_SEND_SCOPE),
|
|
455
|
+
zValidator("query", mailboxQuerySchema),
|
|
384
456
|
zValidator("json", createUploadSchema),
|
|
385
457
|
async (c) => {
|
|
386
|
-
const { mailboxId
|
|
458
|
+
const { mailboxId } = c.req.valid("query");
|
|
387
459
|
const body = c.req.valid("json");
|
|
388
460
|
const user = c.get("user");
|
|
389
|
-
const access = await accessibleMailbox(c
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
461
|
+
const access = await accessibleMailbox(c, mailboxId, "send");
|
|
462
|
+
|
|
463
|
+
if (!access) {
|
|
464
|
+
return apiError(c, 403, "FORBIDDEN", "Send access is required");
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const rateExceeded = await overRateLimit(
|
|
468
|
+
c,
|
|
469
|
+
"RATE_LIMIT_30",
|
|
470
|
+
"mail-upload",
|
|
471
|
+
user.id
|
|
472
|
+
);
|
|
473
|
+
|
|
474
|
+
if (rateExceeded) {
|
|
400
475
|
return apiError(c, 429, "RATE_LIMITED", "Too many attachment uploads");
|
|
401
476
|
}
|
|
402
477
|
|
|
403
478
|
try {
|
|
404
479
|
const upload = await createComposerUploadIntent({
|
|
405
480
|
env: c.env,
|
|
406
|
-
requestOrigin: new URL(c.req.url).origin,
|
|
407
481
|
mailboxId,
|
|
408
482
|
userId: user.id,
|
|
409
483
|
filename: body.filename,
|
|
410
484
|
contentType: body.contentType,
|
|
411
485
|
size: body.size,
|
|
412
|
-
directOnly: directOnly === "true",
|
|
413
486
|
});
|
|
487
|
+
|
|
414
488
|
return c.json({ ok: true as const, upload }, 201);
|
|
415
489
|
} catch (error) {
|
|
416
490
|
return outgoingFailure(c, error);
|
|
417
491
|
}
|
|
418
|
-
}
|
|
419
|
-
)
|
|
420
|
-
.put(
|
|
421
|
-
"/uploads/content",
|
|
422
|
-
zValidator(
|
|
423
|
-
"query",
|
|
424
|
-
mailboxQuerySchema.extend({
|
|
425
|
-
uploadId: uploadIdSchema,
|
|
426
|
-
}),
|
|
427
|
-
),
|
|
428
|
-
async (c) => {
|
|
429
|
-
const { mailboxId, uploadId } = c.req.valid("query");
|
|
430
|
-
const user = c.get("user");
|
|
431
|
-
const access = await accessibleMailbox(c.env, user.id, mailboxId, "send");
|
|
432
|
-
if (!access) return apiError(c, 403, "FORBIDDEN", "Send access is required");
|
|
433
|
-
try {
|
|
434
|
-
await storeComposerUploadContent({
|
|
435
|
-
env: c.env,
|
|
436
|
-
mailboxId,
|
|
437
|
-
userId: user.id,
|
|
438
|
-
uploadId,
|
|
439
|
-
body: c.req.raw.body,
|
|
440
|
-
contentType: c.req.header("content-type") ?? undefined,
|
|
441
|
-
contentLength: requestContentLength(
|
|
442
|
-
c.req.header("content-length") ?? undefined,
|
|
443
|
-
),
|
|
444
|
-
});
|
|
445
|
-
return c.json({ ok: true as const });
|
|
446
|
-
} catch (error) {
|
|
447
|
-
return outgoingFailure(c, error);
|
|
448
|
-
}
|
|
449
|
-
},
|
|
492
|
+
}
|
|
450
493
|
)
|
|
451
494
|
.post(
|
|
452
495
|
"/uploads/:id/complete",
|
|
496
|
+
oauthScope(MAIL_SEND_SCOPE),
|
|
453
497
|
zValidator("param", z.object({ id: uploadIdSchema })),
|
|
454
498
|
zValidator("query", mailboxQuerySchema),
|
|
455
499
|
async (c) => {
|
|
456
500
|
const { mailboxId } = c.req.valid("query");
|
|
457
501
|
const { id: uploadId } = c.req.valid("param");
|
|
458
502
|
const user = c.get("user");
|
|
459
|
-
const access = await accessibleMailbox(c
|
|
503
|
+
const access = await accessibleMailbox(c, mailboxId, "send");
|
|
504
|
+
|
|
460
505
|
if (!access) {
|
|
461
506
|
return apiError(c, 403, "FORBIDDEN", "Send access is required");
|
|
462
507
|
}
|
|
508
|
+
|
|
463
509
|
try {
|
|
464
510
|
const upload = await finalizeComposerUpload({
|
|
465
511
|
env: c.env,
|
|
@@ -468,23 +514,27 @@ export const mailRoutes = new Hono<AppEnv>()
|
|
|
468
514
|
uploadId,
|
|
469
515
|
defer: (task) => c.executionCtx.waitUntil(task),
|
|
470
516
|
});
|
|
517
|
+
|
|
471
518
|
return c.json({ ok: true as const, upload });
|
|
472
519
|
} catch (error) {
|
|
473
520
|
return outgoingFailure(c, error);
|
|
474
521
|
}
|
|
475
|
-
}
|
|
522
|
+
}
|
|
476
523
|
)
|
|
477
524
|
.delete(
|
|
478
525
|
"/uploads/:id",
|
|
526
|
+
oauthScope(MAIL_SEND_SCOPE),
|
|
479
527
|
zValidator("param", z.object({ id: uploadIdSchema })),
|
|
480
528
|
zValidator("query", mailboxQuerySchema),
|
|
481
529
|
async (c) => {
|
|
482
530
|
const { mailboxId } = c.req.valid("query");
|
|
483
531
|
const user = c.get("user");
|
|
484
|
-
const access = await accessibleMailbox(c
|
|
532
|
+
const access = await accessibleMailbox(c, mailboxId, "send");
|
|
533
|
+
|
|
485
534
|
if (!access) {
|
|
486
535
|
return apiError(c, 403, "FORBIDDEN", "Send access is required");
|
|
487
536
|
}
|
|
537
|
+
|
|
488
538
|
const { id: uploadId } = c.req.valid("param");
|
|
489
539
|
await discardComposerUploads({
|
|
490
540
|
env: c.env,
|
|
@@ -492,65 +542,55 @@ export const mailRoutes = new Hono<AppEnv>()
|
|
|
492
542
|
userId: user.id,
|
|
493
543
|
uploadIds: [uploadId],
|
|
494
544
|
});
|
|
545
|
+
|
|
495
546
|
return c.json({ ok: true as const });
|
|
496
|
-
}
|
|
547
|
+
}
|
|
497
548
|
)
|
|
498
549
|
.get(
|
|
499
550
|
"/mailboxes/:id/recipient-suggestions",
|
|
551
|
+
oauthScope(MAIL_READ_SCOPE),
|
|
500
552
|
zValidator("query", recipientSuggestionQuerySchema),
|
|
501
553
|
async (c) => {
|
|
502
554
|
const mailboxId = c.req.param("id");
|
|
503
|
-
const access = await accessibleMailbox(
|
|
504
|
-
|
|
505
|
-
c.get("user").id,
|
|
506
|
-
mailboxId,
|
|
507
|
-
"read",
|
|
508
|
-
);
|
|
555
|
+
const access = await accessibleMailbox(c, mailboxId, "read");
|
|
556
|
+
|
|
509
557
|
if (!access) {
|
|
510
558
|
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
511
559
|
}
|
|
560
|
+
|
|
512
561
|
const query = c.req.valid("query");
|
|
562
|
+
|
|
513
563
|
return c.json({
|
|
514
564
|
ok: true as const,
|
|
515
565
|
suggestions: await mailboxStub(c.env, mailboxId).suggestRecipients(
|
|
516
566
|
access.address,
|
|
517
567
|
query.q,
|
|
518
|
-
query.limit
|
|
568
|
+
query.limit
|
|
519
569
|
),
|
|
520
570
|
});
|
|
521
|
-
}
|
|
571
|
+
}
|
|
522
572
|
)
|
|
523
|
-
.get("/mailboxes/:id/folders", async (c) => {
|
|
573
|
+
.get("/mailboxes/:id/folders", oauthScope(MAIL_READ_SCOPE), async (c) => {
|
|
524
574
|
const mailboxId = c.req.param("id");
|
|
525
|
-
const access = await accessibleMailbox(
|
|
526
|
-
|
|
527
|
-
c.get("user").id,
|
|
528
|
-
mailboxId,
|
|
529
|
-
"read",
|
|
530
|
-
);
|
|
575
|
+
const access = await accessibleMailbox(c, mailboxId, "read");
|
|
576
|
+
|
|
531
577
|
if (!access) {
|
|
532
578
|
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
533
579
|
}
|
|
534
|
-
|
|
535
|
-
|
|
580
|
+
|
|
581
|
+
const view = await timed(c, "do", "folders", () =>
|
|
582
|
+
mailboxStub(c.env, mailboxId).folderView(c.get("user").id)
|
|
536
583
|
);
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
folders: storedFolders.map((folder) => ({
|
|
540
|
-
id: folder.id,
|
|
541
|
-
name: folder.name,
|
|
542
|
-
kind: folder.kind,
|
|
543
|
-
systemType: folder.systemType,
|
|
544
|
-
totalCount: folder.totalCount,
|
|
545
|
-
unreadCount: folder.unreadCount,
|
|
546
|
-
})),
|
|
547
|
-
});
|
|
584
|
+
|
|
585
|
+
return c.json({ ok: true as const, ...folderListView(view) });
|
|
548
586
|
})
|
|
549
|
-
.get("/mailboxes/:id/ai", async (c) => {
|
|
587
|
+
.get("/mailboxes/:id/ai", oauthScope(MAIL_READ_SCOPE), async (c) => {
|
|
550
588
|
const mailboxId = c.req.param("id");
|
|
551
|
-
|
|
589
|
+
|
|
590
|
+
if (!(await accessibleMailbox(c, mailboxId, "read"))) {
|
|
552
591
|
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
553
592
|
}
|
|
593
|
+
|
|
554
594
|
return c.json({
|
|
555
595
|
ok: true as const,
|
|
556
596
|
settings: await mailboxStub(c.env, mailboxId).getMailboxAiSettings(),
|
|
@@ -558,438 +598,639 @@ export const mailRoutes = new Hono<AppEnv>()
|
|
|
558
598
|
})
|
|
559
599
|
.put(
|
|
560
600
|
"/mailboxes/:id/ai",
|
|
601
|
+
oauthScope(MAIL_ORGANIZE_SCOPE),
|
|
561
602
|
zValidator("json", mailboxAiConfigurationSchema),
|
|
562
603
|
async (c) => {
|
|
563
604
|
const mailboxId = c.req.param("id");
|
|
564
|
-
|
|
605
|
+
|
|
606
|
+
if (!(await accessibleMailbox(c, mailboxId, "read"))) {
|
|
565
607
|
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
566
608
|
}
|
|
609
|
+
|
|
567
610
|
return c.json({
|
|
568
611
|
ok: true as const,
|
|
569
|
-
settings: await mailboxStub(c.env, mailboxId)
|
|
570
|
-
|
|
612
|
+
settings: await mailboxStub(c.env, mailboxId).setMailboxAiConfiguration(
|
|
613
|
+
c.req.valid("json")
|
|
614
|
+
),
|
|
571
615
|
});
|
|
572
|
-
}
|
|
616
|
+
}
|
|
573
617
|
)
|
|
574
618
|
.post(
|
|
575
619
|
"/mailboxes/:id/folders",
|
|
620
|
+
oauthScope(MAIL_ORGANIZE_SCOPE),
|
|
576
621
|
zValidator("json", createFolderSchema),
|
|
577
622
|
async (c) => {
|
|
578
623
|
const mailboxId = c.req.param("id");
|
|
579
|
-
|
|
624
|
+
|
|
625
|
+
if (!(await accessibleMailbox(c, mailboxId, "read"))) {
|
|
580
626
|
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
581
627
|
}
|
|
628
|
+
|
|
582
629
|
const result = await mailboxStub(c.env, mailboxId).createFolder(
|
|
583
630
|
createId("fld"),
|
|
584
|
-
c.req.valid("json").name
|
|
631
|
+
c.req.valid("json").name
|
|
585
632
|
);
|
|
633
|
+
|
|
586
634
|
if (result.status === "conflict") {
|
|
587
635
|
return apiError(c, 409, "CONFLICT", "Folder name already exists");
|
|
588
636
|
}
|
|
637
|
+
|
|
589
638
|
if (result.status === "limit") {
|
|
590
639
|
return apiError(c, 409, "CONFLICT", "Mailbox folder limit reached");
|
|
591
640
|
}
|
|
641
|
+
|
|
592
642
|
if (result.status === "invalid") {
|
|
593
643
|
return apiError(c, 400, "BAD_REQUEST", "Folder name is invalid");
|
|
594
644
|
}
|
|
645
|
+
|
|
595
646
|
return c.json({ ok: true as const, folder: result.folder }, 201);
|
|
596
|
-
}
|
|
647
|
+
}
|
|
597
648
|
)
|
|
598
649
|
.put(
|
|
599
650
|
"/mailboxes/:id/folders/order",
|
|
651
|
+
oauthScope(MAIL_ORGANIZE_SCOPE),
|
|
600
652
|
zValidator("json", reorderFoldersSchema),
|
|
601
653
|
async (c) => {
|
|
602
654
|
const mailboxId = c.req.param("id");
|
|
603
|
-
|
|
655
|
+
|
|
656
|
+
if (!(await accessibleMailbox(c, mailboxId, "read"))) {
|
|
604
657
|
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
605
658
|
}
|
|
659
|
+
|
|
606
660
|
const result = await mailboxStub(c.env, mailboxId).reorderFolders(
|
|
607
|
-
c.req.valid("json").folderIds
|
|
661
|
+
c.req.valid("json").folderIds
|
|
608
662
|
);
|
|
663
|
+
|
|
609
664
|
if (result.status === "conflict") {
|
|
610
665
|
return apiError(
|
|
611
666
|
c,
|
|
612
667
|
409,
|
|
613
668
|
"CONFLICT",
|
|
614
|
-
"Folders changed; refresh and try again"
|
|
669
|
+
"Folders changed; refresh and try again"
|
|
615
670
|
);
|
|
616
671
|
}
|
|
672
|
+
|
|
617
673
|
return c.json({ ok: true as const });
|
|
618
|
-
}
|
|
674
|
+
}
|
|
619
675
|
)
|
|
620
676
|
.patch(
|
|
621
677
|
"/mailboxes/:id/folders/:folderId",
|
|
678
|
+
oauthScope(MAIL_ORGANIZE_SCOPE),
|
|
622
679
|
zValidator("json", renameFolderSchema),
|
|
623
680
|
async (c) => {
|
|
624
681
|
const mailboxId = c.req.param("id");
|
|
625
|
-
|
|
682
|
+
|
|
683
|
+
if (!(await accessibleMailbox(c, mailboxId, "read"))) {
|
|
626
684
|
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
627
685
|
}
|
|
686
|
+
|
|
628
687
|
const result = await mailboxStub(c.env, mailboxId).renameFolder(
|
|
629
688
|
c.req.param("folderId"),
|
|
630
|
-
c.req.valid("json").name
|
|
689
|
+
c.req.valid("json").name
|
|
631
690
|
);
|
|
691
|
+
|
|
632
692
|
if (result.status === "not_found") {
|
|
633
693
|
return apiError(c, 404, "NOT_FOUND", "Folder not found");
|
|
634
694
|
}
|
|
695
|
+
|
|
635
696
|
if (result.status === "conflict") {
|
|
636
697
|
return apiError(c, 409, "CONFLICT", "Folder name already exists");
|
|
637
698
|
}
|
|
699
|
+
|
|
638
700
|
if (result.status === "invalid") {
|
|
639
701
|
return apiError(c, 400, "BAD_REQUEST", "Folder name is invalid");
|
|
640
702
|
}
|
|
703
|
+
|
|
641
704
|
return c.json({ ok: true as const, folder: result.folder });
|
|
642
|
-
},
|
|
643
|
-
)
|
|
644
|
-
.delete("/mailboxes/:id/folders/:folderId", async (c) => {
|
|
645
|
-
const mailboxId = c.req.param("id");
|
|
646
|
-
if (!await accessibleMailbox(c.env, c.get("user").id, mailboxId, "read")) {
|
|
647
|
-
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
648
705
|
}
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
706
|
+
)
|
|
707
|
+
.delete(
|
|
708
|
+
"/mailboxes/:id/folders/:folderId",
|
|
709
|
+
oauthScope(MAIL_ORGANIZE_SCOPE),
|
|
710
|
+
async (c) => {
|
|
711
|
+
const mailboxId = c.req.param("id");
|
|
712
|
+
|
|
713
|
+
if (!(await accessibleMailbox(c, mailboxId, "read"))) {
|
|
714
|
+
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
const result = await mailboxStub(c.env, mailboxId).deleteFolder(
|
|
718
|
+
c.req.param("folderId")
|
|
719
|
+
);
|
|
720
|
+
|
|
721
|
+
if (result.status === "not_found") {
|
|
722
|
+
return apiError(c, 404, "NOT_FOUND", "Folder not found");
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
return c.json({ ok: true as const });
|
|
662
726
|
}
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
727
|
+
)
|
|
728
|
+
.get(
|
|
729
|
+
"/conversations",
|
|
730
|
+
oauthScope(MAIL_READ_SCOPE),
|
|
731
|
+
zValidator("query", conversationListQuerySchema),
|
|
732
|
+
async (c) => {
|
|
733
|
+
const query = c.req.valid("query");
|
|
734
|
+
const access = await accessibleMailbox(c, query.mailboxId, "read");
|
|
735
|
+
|
|
736
|
+
if (!access) {
|
|
737
|
+
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
const cursor = query.cursor
|
|
741
|
+
? decodeConversationCursor(query.cursor)
|
|
742
|
+
: null;
|
|
743
|
+
|
|
744
|
+
if (query.cursor && !cursor) {
|
|
745
|
+
return apiError(
|
|
746
|
+
c,
|
|
747
|
+
400,
|
|
748
|
+
"BAD_REQUEST",
|
|
749
|
+
"Conversation cursor is invalid"
|
|
750
|
+
);
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
const page = await timed(c, "do", "conversations", () =>
|
|
754
|
+
mailboxStub(c.env, query.mailboxId).listConversations(
|
|
755
|
+
c.get("user").id,
|
|
756
|
+
query.folder,
|
|
757
|
+
query.limit,
|
|
758
|
+
cursor,
|
|
759
|
+
query.search,
|
|
760
|
+
query.unreadOnly === "true"
|
|
761
|
+
)
|
|
762
|
+
);
|
|
763
|
+
|
|
764
|
+
if (!page) return apiError(c, 404, "NOT_FOUND", "Folder not found");
|
|
765
|
+
|
|
766
|
+
return c.json({
|
|
767
|
+
ok: true as const,
|
|
768
|
+
...conversationPageView(page, access.address),
|
|
769
|
+
});
|
|
666
770
|
}
|
|
667
|
-
|
|
668
|
-
c.get("user").id,
|
|
669
|
-
query.folder,
|
|
670
|
-
query.limit,
|
|
671
|
-
cursor,
|
|
672
|
-
query.search,
|
|
673
|
-
query.unreadOnly === "true",
|
|
674
|
-
);
|
|
675
|
-
if (!page) return apiError(c, 404, "NOT_FOUND", "Folder not found");
|
|
676
|
-
return c.json({
|
|
677
|
-
ok: true as const,
|
|
678
|
-
conversations: page.items.map((item) => ({
|
|
679
|
-
...toMessageSummary(item.email),
|
|
680
|
-
subject: conversationSubject(item.email.subject),
|
|
681
|
-
conversationLabel: conversationLabel(
|
|
682
|
-
access.address,
|
|
683
|
-
item.email,
|
|
684
|
-
),
|
|
685
|
-
messageCount: item.messageCount,
|
|
686
|
-
unreadCount: item.unreadCount,
|
|
687
|
-
isUnread: item.unreadCount > 0,
|
|
688
|
-
hasIncoming: item.hasIncoming,
|
|
689
|
-
})),
|
|
690
|
-
nextCursor: page.next ? encodeConversationCursor(page.next) : null,
|
|
691
|
-
});
|
|
692
|
-
})
|
|
771
|
+
)
|
|
693
772
|
.patch(
|
|
694
773
|
"/conversations/bulk",
|
|
774
|
+
oauthScope(MAIL_ORGANIZE_SCOPE),
|
|
695
775
|
zValidator("query", mailboxQuerySchema),
|
|
696
776
|
zValidator("json", bulkConversationActionSchema),
|
|
697
777
|
async (c) => {
|
|
698
778
|
const { mailboxId } = c.req.valid("query");
|
|
699
779
|
const user = c.get("user");
|
|
700
|
-
const access = await accessibleMailbox(c
|
|
780
|
+
const access = await accessibleMailbox(c, mailboxId, "read");
|
|
781
|
+
|
|
701
782
|
if (!access) {
|
|
702
783
|
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
703
784
|
}
|
|
785
|
+
|
|
704
786
|
const input = c.req.valid("json");
|
|
705
787
|
const stub = mailboxStub(c.env, mailboxId);
|
|
788
|
+
|
|
706
789
|
if (input.type === "read") {
|
|
707
790
|
const updatedCount = await stub.bulkSetConversationRead(
|
|
708
791
|
user.id,
|
|
709
792
|
input.conversationIds,
|
|
710
|
-
input.isRead
|
|
793
|
+
input.isRead
|
|
711
794
|
);
|
|
795
|
+
|
|
712
796
|
return c.json({ ok: true as const, updatedCount });
|
|
713
797
|
}
|
|
798
|
+
|
|
714
799
|
if (input.type === "update") {
|
|
715
800
|
const updatedCount = await stub.bulkUpdateConversations(
|
|
716
801
|
input.conversationIds,
|
|
717
802
|
input.sourceFolderId,
|
|
718
|
-
input.update
|
|
803
|
+
input.update
|
|
719
804
|
);
|
|
805
|
+
|
|
720
806
|
if (updatedCount === null) {
|
|
721
|
-
return apiError(
|
|
807
|
+
return apiError(
|
|
808
|
+
c,
|
|
809
|
+
404,
|
|
810
|
+
"NOT_FOUND",
|
|
811
|
+
"Source or target folder not found"
|
|
812
|
+
);
|
|
722
813
|
}
|
|
814
|
+
|
|
723
815
|
return c.json({ ok: true as const, updatedCount });
|
|
724
816
|
}
|
|
817
|
+
|
|
725
818
|
if (!access.canSend) {
|
|
726
819
|
return apiError(
|
|
727
820
|
c,
|
|
728
821
|
403,
|
|
729
822
|
"FORBIDDEN",
|
|
730
|
-
"Send access is required to delete conversations permanently"
|
|
823
|
+
"Send access is required to delete conversations permanently"
|
|
731
824
|
);
|
|
732
825
|
}
|
|
733
826
|
|
|
734
827
|
const result = await stub.permanentlyDeleteConversations(
|
|
735
|
-
input.conversationIds
|
|
828
|
+
input.conversationIds
|
|
736
829
|
);
|
|
830
|
+
|
|
737
831
|
if (result.outcome === "not_found") {
|
|
738
832
|
return apiError(c, 404, "NOT_FOUND", "Conversations not found");
|
|
739
833
|
}
|
|
834
|
+
|
|
740
835
|
if (result.outcome === "not_in_trash") {
|
|
741
836
|
return apiError(
|
|
742
837
|
c,
|
|
743
838
|
409,
|
|
744
839
|
"CONFLICT",
|
|
745
|
-
"Only conversations in Trash can be deleted permanently"
|
|
840
|
+
"Only conversations in Trash can be deleted permanently"
|
|
746
841
|
);
|
|
747
842
|
}
|
|
843
|
+
|
|
748
844
|
return c.json({
|
|
749
845
|
ok: true as const,
|
|
750
846
|
updatedCount: result.deletedCount,
|
|
751
847
|
});
|
|
752
|
-
}
|
|
848
|
+
}
|
|
753
849
|
)
|
|
754
850
|
.get(
|
|
755
851
|
"/conversations/:id",
|
|
852
|
+
oauthScope(MAIL_READ_SCOPE),
|
|
756
853
|
zValidator("query", conversationMessagesQuerySchema),
|
|
757
854
|
async (c) => {
|
|
758
855
|
const query = c.req.valid("query");
|
|
759
856
|
const { mailboxId } = query;
|
|
760
857
|
const currentUserId = c.get("user").id;
|
|
761
|
-
const access = await accessibleMailbox(c
|
|
858
|
+
const access = await accessibleMailbox(c, mailboxId, "read");
|
|
859
|
+
|
|
762
860
|
if (!access) {
|
|
763
861
|
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
764
862
|
}
|
|
765
|
-
|
|
863
|
+
|
|
864
|
+
const cursor = query.cursor
|
|
865
|
+
? decodeConversationCursor(query.cursor)
|
|
866
|
+
: null;
|
|
867
|
+
|
|
766
868
|
if (query.cursor && !cursor) {
|
|
767
869
|
return apiError(c, 400, "BAD_REQUEST", "Message cursor is invalid");
|
|
768
870
|
}
|
|
769
|
-
|
|
770
|
-
|
|
871
|
+
|
|
872
|
+
const mailbox = mailboxStub(c.env, mailboxId);
|
|
873
|
+
|
|
874
|
+
// Workspace-wide inputs come from this isolate's cache when it has them,
|
|
875
|
+
// and otherwise load from D1 alongside the mailbox call.
|
|
876
|
+
const workspace = timed(c, "d1", "workspace", () =>
|
|
877
|
+
Promise.all([
|
|
878
|
+
cachedWorkspaceIdentity(c.env.DB),
|
|
879
|
+
cachedWorkspaceBlockPatterns(c.env.DB),
|
|
880
|
+
])
|
|
881
|
+
);
|
|
882
|
+
|
|
883
|
+
workspace.catch(() => undefined);
|
|
884
|
+
|
|
885
|
+
const view = await timed(c, "do", "conversation", () =>
|
|
886
|
+
mailbox.getConversationView(
|
|
771
887
|
c.req.param("id"),
|
|
772
888
|
currentUserId,
|
|
773
889
|
query.limit,
|
|
774
|
-
cursor
|
|
775
|
-
)
|
|
776
|
-
if (!snapshot) return apiError(c, 404, "NOT_FOUND", "Conversation not found");
|
|
777
|
-
const readerIds = [...new Set(
|
|
778
|
-
snapshot.readStates.map((readState) => readState.userId),
|
|
779
|
-
)];
|
|
780
|
-
const readers = await listMailboxUsersByIds(
|
|
781
|
-
c.env.DB,
|
|
782
|
-
mailboxId,
|
|
783
|
-
readerIds,
|
|
890
|
+
cursor
|
|
891
|
+
)
|
|
784
892
|
);
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
893
|
+
|
|
894
|
+
if (!view) return apiError(c, 404, "NOT_FOUND", "Conversation not found");
|
|
895
|
+
const self = c.get("user");
|
|
896
|
+
|
|
897
|
+
const otherReaderIds = [
|
|
898
|
+
...new Set(view.readStates.map((readState) => readState.userId)),
|
|
899
|
+
].filter((userId) => userId !== currentUserId);
|
|
900
|
+
|
|
901
|
+
const [readers, [identity, workspaceBlocks], bodies] = await Promise.all([
|
|
902
|
+
otherReaderIds.length
|
|
903
|
+
? timed(c, "d1", "readers", () =>
|
|
904
|
+
listMailboxUsersByIds(c.env.DB, mailboxId, otherReaderIds)
|
|
905
|
+
)
|
|
906
|
+
: [],
|
|
907
|
+
workspace,
|
|
908
|
+
Promise.all(
|
|
909
|
+
view.messages.map((stored) =>
|
|
910
|
+
stored.bodyHtmlR2Key
|
|
911
|
+
? readStoredBody(c, stored.bodyHtmlR2Key)
|
|
912
|
+
: null
|
|
913
|
+
)
|
|
914
|
+
),
|
|
915
|
+
]);
|
|
916
|
+
|
|
917
|
+
/** One proxy token per remote image URL in the HTML (remote-token.ts). */
|
|
918
|
+
const remoteTokens = async (bodyHtml: string) =>
|
|
919
|
+
Object.fromEntries(
|
|
920
|
+
await Promise.all(
|
|
921
|
+
remoteImageUrls(bodyHtml).map(
|
|
922
|
+
async (url) =>
|
|
923
|
+
[
|
|
924
|
+
url,
|
|
925
|
+
await signRemoteToken(
|
|
926
|
+
c.env.MAIL_REMOTE_KEY,
|
|
927
|
+
currentUserId,
|
|
928
|
+
mailboxId,
|
|
929
|
+
url
|
|
930
|
+
),
|
|
931
|
+
] as const
|
|
932
|
+
)
|
|
933
|
+
)
|
|
934
|
+
);
|
|
935
|
+
|
|
936
|
+
const readerById = new Map([
|
|
937
|
+
[self.id, { id: self.id, name: self.name }],
|
|
938
|
+
...readers.map((reader) => [reader.id, reader] as const),
|
|
939
|
+
]);
|
|
940
|
+
|
|
941
|
+
const readStatesByEmail = new Map<string, typeof view.readStates>();
|
|
942
|
+
|
|
943
|
+
for (const readState of view.readStates) {
|
|
791
944
|
const states = readStatesByEmail.get(readState.emailId) ?? [];
|
|
792
945
|
states.push(readState);
|
|
793
946
|
readStatesByEmail.set(readState.emailId, states);
|
|
794
947
|
}
|
|
795
|
-
|
|
796
|
-
const
|
|
797
|
-
|
|
948
|
+
|
|
949
|
+
const safety: MessageSafetyContext = { ...view.safety, workspaceBlocks };
|
|
950
|
+
|
|
951
|
+
const intelContext = (bodyHtml: string | null) => ({
|
|
952
|
+
bodyHtml,
|
|
953
|
+
workspaceDomains: identity.domains,
|
|
954
|
+
dqsKey: spamhausDqsKey(c.env),
|
|
955
|
+
});
|
|
956
|
+
|
|
957
|
+
// The browser gets the conversation at once and the sender lookups
|
|
958
|
+
// (DNS, up to SENDER_INTEL_BUDGET_MS) from a follow-up request, while
|
|
959
|
+
// they run here in the background; other clients get them inline.
|
|
960
|
+
const inline = c.get("authKind") !== "session";
|
|
961
|
+
const now = Date.now();
|
|
962
|
+
|
|
963
|
+
const messages = await Promise.all(
|
|
964
|
+
view.messages.map(async (stored, index) => {
|
|
965
|
+
const bodyHtml = bodies[index] ?? null;
|
|
966
|
+
let email = stored;
|
|
967
|
+
let intelPending = false;
|
|
968
|
+
|
|
969
|
+
if (senderIntelPending(stored, now)) {
|
|
970
|
+
if (inline) {
|
|
971
|
+
email = await timed(c, "intel", "sender", () =>
|
|
972
|
+
withSenderIntel(c.env, mailbox, stored, intelContext(bodyHtml))
|
|
973
|
+
);
|
|
974
|
+
} else {
|
|
975
|
+
intelPending = true;
|
|
976
|
+
runInBackground(
|
|
977
|
+
c,
|
|
978
|
+
withSenderIntel(c.env, mailbox, stored, intelContext(bodyHtml))
|
|
979
|
+
);
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
const readStates = readStatesByEmail.get(email.id) ?? [];
|
|
984
|
+
|
|
985
|
+
return {
|
|
986
|
+
...toMessageDetail(
|
|
987
|
+
email,
|
|
988
|
+
access.address,
|
|
989
|
+
identity,
|
|
990
|
+
view.history,
|
|
991
|
+
safety,
|
|
992
|
+
bodyHtml,
|
|
993
|
+
{
|
|
994
|
+
isRead: readStates.some(
|
|
995
|
+
(readState) => readState.userId === currentUserId
|
|
996
|
+
),
|
|
997
|
+
viewedBy: readStates.flatMap((readState) => {
|
|
998
|
+
const reader = readerById.get(readState.userId);
|
|
999
|
+
|
|
1000
|
+
return reader
|
|
1001
|
+
? [
|
|
1002
|
+
{
|
|
1003
|
+
userId: reader.id,
|
|
1004
|
+
name: reader.name,
|
|
1005
|
+
readAt: readState.readAt,
|
|
1006
|
+
},
|
|
1007
|
+
]
|
|
1008
|
+
: [];
|
|
1009
|
+
}),
|
|
1010
|
+
}
|
|
1011
|
+
),
|
|
1012
|
+
/**
|
|
1013
|
+
* Sender lookups are still running: `security` lacks their
|
|
1014
|
+
* blocklist warnings until GET /messages/:id/sender-intel answers.
|
|
1015
|
+
*/
|
|
1016
|
+
senderIntelPending: intelPending,
|
|
1017
|
+
/**
|
|
1018
|
+
* For each remote image URL in `bodyHtml`, the token it is
|
|
1019
|
+
* proxied with (GET /api/mail/remote); an image without one is
|
|
1020
|
+
* not shown (remote-token.ts).
|
|
1021
|
+
*/
|
|
1022
|
+
remoteTokens: bodyHtml ? await remoteTokens(bodyHtml) : null,
|
|
1023
|
+
};
|
|
1024
|
+
})
|
|
798
1025
|
);
|
|
799
|
-
|
|
800
|
-
workspaceIdentity(c.env.DB),
|
|
801
|
-
spamhausDqsKey(c.env),
|
|
802
|
-
mailbox.getSenderHistory(senderAddresses),
|
|
803
|
-
mailbox.getMessageSafetyContext(
|
|
804
|
-
senderAddresses,
|
|
805
|
-
snapshot.messages.flatMap((message) => emailListKey(message) ?? []),
|
|
806
|
-
),
|
|
807
|
-
workspaceBlockPatterns(c.env.DB),
|
|
808
|
-
]);
|
|
809
|
-
const safety: MessageSafetyContext = { ...localSafety, workspaceBlocks };
|
|
810
|
-
const messages = await Promise.all(snapshot.messages.map(async (stored) => {
|
|
811
|
-
const object = stored.bodyHtmlR2Key
|
|
812
|
-
? await c.env.MAIL_STORAGE.get(stored.bodyHtmlR2Key)
|
|
813
|
-
: null;
|
|
814
|
-
const bodyHtml = object ? await object.text() : null;
|
|
815
|
-
const email = await withSenderIntel(
|
|
816
|
-
c.env,
|
|
817
|
-
mailbox,
|
|
818
|
-
await withHeaderMetadata(c.env, mailbox, stored),
|
|
819
|
-
{ bodyHtml, workspaceDomains: identity.domains, dqsKey },
|
|
820
|
-
);
|
|
821
|
-
const readStates = readStatesByEmail.get(email.id) ?? [];
|
|
822
|
-
return toMessageDetail(
|
|
823
|
-
email,
|
|
824
|
-
access.address,
|
|
825
|
-
identity,
|
|
826
|
-
history,
|
|
827
|
-
safety,
|
|
828
|
-
bodyHtml,
|
|
829
|
-
{
|
|
830
|
-
isRead: readStates.some(
|
|
831
|
-
(readState) => readState.userId === currentUserId,
|
|
832
|
-
),
|
|
833
|
-
viewedBy: readStates.flatMap((readState) => {
|
|
834
|
-
const reader = readerById.get(readState.userId);
|
|
835
|
-
return reader
|
|
836
|
-
? [{
|
|
837
|
-
userId: reader.id,
|
|
838
|
-
name: reader.name,
|
|
839
|
-
readAt: readState.readAt,
|
|
840
|
-
}]
|
|
841
|
-
: [];
|
|
842
|
-
}),
|
|
843
|
-
},
|
|
844
|
-
);
|
|
845
|
-
}));
|
|
1026
|
+
|
|
846
1027
|
return c.json({
|
|
847
1028
|
ok: true as const,
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
1029
|
+
version: view.version,
|
|
1030
|
+
mailboxState: view.mailboxState,
|
|
1031
|
+
folderId: view.folderId,
|
|
1032
|
+
hasIncoming: view.hasIncoming,
|
|
1033
|
+
hasOutgoing: view.hasOutgoing,
|
|
1034
|
+
messageCount: view.messageCount,
|
|
1035
|
+
unreadCount: view.unreadCount,
|
|
1036
|
+
nextCursor: view.next ? encodeConversationCursor(view.next) : null,
|
|
856
1037
|
messages,
|
|
857
1038
|
});
|
|
858
|
-
}
|
|
1039
|
+
}
|
|
1040
|
+
)
|
|
1041
|
+
.get(
|
|
1042
|
+
"/messages/:id/sender-intel",
|
|
1043
|
+
oauthScope(MAIL_READ_SCOPE),
|
|
1044
|
+
zValidator("query", mailboxQuerySchema),
|
|
1045
|
+
async (c) => {
|
|
1046
|
+
const { mailboxId } = c.req.valid("query");
|
|
1047
|
+
|
|
1048
|
+
if (!(await accessibleMailbox(c, mailboxId, "read"))) {
|
|
1049
|
+
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
const mailbox = mailboxStub(c.env, mailboxId);
|
|
1053
|
+
|
|
1054
|
+
const workspace = timed(c, "d1", "workspace", () =>
|
|
1055
|
+
Promise.all([
|
|
1056
|
+
cachedWorkspaceIdentity(c.env.DB),
|
|
1057
|
+
cachedWorkspaceBlockPatterns(c.env.DB),
|
|
1058
|
+
])
|
|
1059
|
+
);
|
|
1060
|
+
|
|
1061
|
+
workspace.catch(() => undefined);
|
|
1062
|
+
|
|
1063
|
+
const view = await timed(c, "do", "message", () =>
|
|
1064
|
+
mailbox.getMessageSenderView(c.req.param("id"))
|
|
1065
|
+
);
|
|
1066
|
+
|
|
1067
|
+
if (!view || view.email.direction !== "incoming") {
|
|
1068
|
+
return apiError(c, 404, "NOT_FOUND", "Message not found");
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
const stored = view.email;
|
|
1072
|
+
|
|
1073
|
+
const [[identity, workspaceBlocks], bodyHtml] = await Promise.all([
|
|
1074
|
+
workspace,
|
|
1075
|
+
senderIntelPending(stored) && stored.bodyHtmlR2Key
|
|
1076
|
+
? readStoredBody(c, stored.bodyHtmlR2Key)
|
|
1077
|
+
: null,
|
|
1078
|
+
]);
|
|
1079
|
+
|
|
1080
|
+
// Joins the lookup the conversation request started in this isolate.
|
|
1081
|
+
const email = await timed(c, "intel", "sender", () =>
|
|
1082
|
+
withSenderIntel(c.env, mailbox, stored, {
|
|
1083
|
+
bodyHtml,
|
|
1084
|
+
workspaceDomains: identity.domains,
|
|
1085
|
+
dqsKey: spamhausDqsKey(c.env),
|
|
1086
|
+
})
|
|
1087
|
+
);
|
|
1088
|
+
|
|
1089
|
+
const safety: MessageSafetyContext = { ...view.safety, workspaceBlocks };
|
|
1090
|
+
|
|
1091
|
+
return c.json({
|
|
1092
|
+
ok: true as const,
|
|
1093
|
+
senderIntel: storedSenderIntel(email.senderIntelJson),
|
|
1094
|
+
senderIntelPending: false,
|
|
1095
|
+
security: emailSecurity(email, identity, view.history, safety),
|
|
1096
|
+
sender: senderStatus(email, safety),
|
|
1097
|
+
senderLogoUrl: senderLogoUrl(email),
|
|
1098
|
+
});
|
|
1099
|
+
}
|
|
859
1100
|
)
|
|
860
1101
|
.patch(
|
|
861
1102
|
"/messages/:id/read",
|
|
1103
|
+
oauthScope(MAIL_ORGANIZE_SCOPE),
|
|
862
1104
|
zValidator("query", mailboxQuerySchema),
|
|
863
1105
|
zValidator("json", messageReadSchema),
|
|
864
1106
|
async (c) => {
|
|
865
1107
|
const { mailboxId } = c.req.valid("query");
|
|
866
1108
|
const user = c.get("user");
|
|
867
|
-
|
|
1109
|
+
|
|
1110
|
+
if (!(await accessibleMailbox(c, mailboxId, "read"))) {
|
|
868
1111
|
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
869
1112
|
}
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
c.
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
1113
|
+
|
|
1114
|
+
const version = await timed(c, "do", "read", async () => {
|
|
1115
|
+
const updated = await mailboxStub(c.env, mailboxId).setMessageRead(
|
|
1116
|
+
user.id,
|
|
1117
|
+
c.req.param("id"),
|
|
1118
|
+
c.req.valid("json").isRead
|
|
1119
|
+
);
|
|
1120
|
+
|
|
1121
|
+
return updated ? updated.version : null;
|
|
1122
|
+
});
|
|
1123
|
+
|
|
1124
|
+
if (version === null) {
|
|
1125
|
+
return apiError(c, 404, "NOT_FOUND", "Message not found");
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
return c.json({ ok: true as const, version });
|
|
1129
|
+
}
|
|
878
1130
|
)
|
|
879
1131
|
.post(
|
|
880
1132
|
"/messages/:id/translate",
|
|
1133
|
+
oauthScope(MAIL_READ_SCOPE),
|
|
881
1134
|
zValidator("query", mailboxQuerySchema),
|
|
882
1135
|
zValidator("json", messageTranslationSchema),
|
|
883
1136
|
async (c) => {
|
|
884
1137
|
const { mailboxId } = c.req.valid("query");
|
|
885
1138
|
const userId = c.get("user").id;
|
|
886
|
-
|
|
1139
|
+
|
|
1140
|
+
if (!(await accessibleMailbox(c, mailboxId, "read"))) {
|
|
887
1141
|
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
888
1142
|
}
|
|
889
|
-
|
|
890
|
-
|
|
1143
|
+
|
|
1144
|
+
const model = aiFeatureEnabled("translation")
|
|
1145
|
+
? await aiModel(c.env, "translation")
|
|
1146
|
+
: null;
|
|
1147
|
+
|
|
1148
|
+
if (!model) {
|
|
1149
|
+
return apiError(
|
|
1150
|
+
c,
|
|
1151
|
+
409,
|
|
1152
|
+
"CONFLICT",
|
|
1153
|
+
"Translation is not configured for this workspace"
|
|
1154
|
+
);
|
|
891
1155
|
}
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
1156
|
+
|
|
1157
|
+
const limitExceeded = await overRateLimit(
|
|
1158
|
+
c,
|
|
1159
|
+
"RATE_LIMIT_20",
|
|
1160
|
+
"mail-translation",
|
|
1161
|
+
userId
|
|
1162
|
+
);
|
|
1163
|
+
|
|
1164
|
+
if (limitExceeded) {
|
|
1165
|
+
return apiError(
|
|
1166
|
+
c,
|
|
1167
|
+
429,
|
|
1168
|
+
"RATE_LIMITED",
|
|
1169
|
+
"Too many translation requests"
|
|
1170
|
+
);
|
|
901
1171
|
}
|
|
902
|
-
|
|
1172
|
+
|
|
1173
|
+
const message = await mailboxStub(c.env, mailboxId).getEmail(
|
|
1174
|
+
c.req.param("id")
|
|
1175
|
+
);
|
|
1176
|
+
|
|
903
1177
|
if (!message) return apiError(c, 404, "NOT_FOUND", "Message not found");
|
|
904
1178
|
const { language, segments } = c.req.valid("json");
|
|
1179
|
+
|
|
905
1180
|
if (segments.join("").length > MAX_TRANSLATION_CHARACTERS) {
|
|
906
|
-
return apiError(
|
|
1181
|
+
return apiError(
|
|
1182
|
+
c,
|
|
1183
|
+
422,
|
|
1184
|
+
"BAD_REQUEST",
|
|
1185
|
+
"Message is too long to translate"
|
|
1186
|
+
);
|
|
907
1187
|
}
|
|
1188
|
+
|
|
908
1189
|
try {
|
|
909
1190
|
const translations = await translateEmailSegments({
|
|
910
1191
|
segments,
|
|
911
1192
|
language,
|
|
912
|
-
run: aiObjectRunner(
|
|
1193
|
+
run: aiObjectRunner(model),
|
|
913
1194
|
});
|
|
1195
|
+
|
|
914
1196
|
return c.json({ ok: true as const, translations });
|
|
915
1197
|
} catch {
|
|
916
|
-
return apiError(c, 502, "BAD_GATEWAY", "Could not translate this message");
|
|
917
|
-
}
|
|
918
|
-
},
|
|
919
|
-
)
|
|
920
|
-
.get(
|
|
921
|
-
"/remote",
|
|
922
|
-
zValidator("query", remoteProxyQuerySchema),
|
|
923
|
-
async (c) => {
|
|
924
|
-
const { mailboxId, url } = c.req.valid("query");
|
|
925
|
-
if (!await accessibleMailbox(c.env, c.get("user").id, mailboxId, "read")) {
|
|
926
|
-
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
927
|
-
}
|
|
928
|
-
try {
|
|
929
|
-
assertProxyableRemoteUrl(url);
|
|
930
|
-
} catch (error) {
|
|
931
|
-
return apiError(
|
|
932
|
-
c,
|
|
933
|
-
400,
|
|
934
|
-
"BAD_REQUEST",
|
|
935
|
-
error instanceof Error ? error.message : "Remote URL is invalid",
|
|
936
|
-
);
|
|
937
|
-
}
|
|
938
|
-
const limited = await checkRateLimit(c.env.DB, {
|
|
939
|
-
action: "mail-remote-proxy",
|
|
940
|
-
identifier: c.get("user").id,
|
|
941
|
-
limit: 120,
|
|
942
|
-
windowMs: 60_000,
|
|
943
|
-
});
|
|
944
|
-
if (!limited.allowed) {
|
|
945
|
-
return apiError(
|
|
946
|
-
c,
|
|
947
|
-
429,
|
|
948
|
-
"RATE_LIMITED",
|
|
949
|
-
"Too many remote content requests. Try again shortly.",
|
|
950
|
-
);
|
|
951
|
-
}
|
|
952
|
-
try {
|
|
953
|
-
const remote = await fetchProxiedRemoteMedia(url);
|
|
954
|
-
return new Response(remote.body, {
|
|
955
|
-
headers: {
|
|
956
|
-
"cache-control": "private, max-age=3600",
|
|
957
|
-
"content-type": remote.contentType,
|
|
958
|
-
"content-disposition": "inline",
|
|
959
|
-
"cross-origin-resource-policy": "same-origin",
|
|
960
|
-
"x-content-type-options": "nosniff",
|
|
961
|
-
},
|
|
962
|
-
});
|
|
963
|
-
} catch (error) {
|
|
964
1198
|
return apiError(
|
|
965
1199
|
c,
|
|
966
1200
|
502,
|
|
967
1201
|
"BAD_GATEWAY",
|
|
968
|
-
|
|
1202
|
+
"Could not translate this message"
|
|
969
1203
|
);
|
|
970
1204
|
}
|
|
971
|
-
}
|
|
1205
|
+
}
|
|
972
1206
|
)
|
|
973
1207
|
.get(
|
|
974
1208
|
"/messages/:messageId/authentication",
|
|
1209
|
+
oauthScope(MAIL_READ_SCOPE),
|
|
975
1210
|
zValidator("query", mailboxQuerySchema),
|
|
976
1211
|
async (c) => {
|
|
977
1212
|
const { mailboxId } = c.req.valid("query");
|
|
978
|
-
const access = await accessibleMailbox(c
|
|
1213
|
+
const access = await accessibleMailbox(c, mailboxId, "read");
|
|
1214
|
+
|
|
979
1215
|
if (!access) {
|
|
980
1216
|
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
981
1217
|
}
|
|
1218
|
+
|
|
982
1219
|
const mailbox = mailboxStub(c.env, mailboxId);
|
|
983
1220
|
const stored = await mailbox.getEmail(c.req.param("messageId"));
|
|
1221
|
+
|
|
984
1222
|
if (!stored?.rawMimeR2Key || stored.direction !== "incoming") {
|
|
985
1223
|
return apiError(c, 404, "NOT_FOUND", "Original message not found");
|
|
986
1224
|
}
|
|
987
|
-
|
|
1225
|
+
|
|
1226
|
+
const message = stored;
|
|
988
1227
|
const from = message.fromJson[0]?.address ?? "";
|
|
1228
|
+
|
|
989
1229
|
const [identity, history] = await Promise.all([
|
|
990
|
-
|
|
1230
|
+
cachedWorkspaceIdentity(c.env.DB),
|
|
991
1231
|
mailbox.getSenderHistory(from ? [from] : []),
|
|
992
1232
|
]);
|
|
1233
|
+
|
|
993
1234
|
return c.json({
|
|
994
1235
|
ok: true as const,
|
|
995
1236
|
original: {
|
|
@@ -1005,41 +1246,62 @@ export const mailRoutes = new Hono<AppEnv>()
|
|
|
1005
1246
|
security: emailSecurity(message, identity, history),
|
|
1006
1247
|
senderIntel: storedSenderIntel(message.senderIntelJson),
|
|
1007
1248
|
});
|
|
1008
|
-
}
|
|
1249
|
+
}
|
|
1009
1250
|
)
|
|
1010
|
-
.get("/bimi/:domain", async (c) => {
|
|
1251
|
+
.get("/bimi/:domain", oauthScope(MAIL_READ_SCOPE), async (c) => {
|
|
1011
1252
|
const domain = c.req.param("domain").toLocaleLowerCase();
|
|
1012
|
-
|
|
1253
|
+
|
|
1254
|
+
if (
|
|
1255
|
+
!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/u.test(
|
|
1256
|
+
domain
|
|
1257
|
+
)
|
|
1258
|
+
) {
|
|
1013
1259
|
return apiError(c, 400, "BAD_REQUEST", "Domain is invalid");
|
|
1014
1260
|
}
|
|
1261
|
+
|
|
1015
1262
|
const object = await c.env.MAIL_STORAGE.get(bimiObjectKey(domain));
|
|
1016
|
-
|
|
1263
|
+
|
|
1264
|
+
if (
|
|
1265
|
+
!object ||
|
|
1266
|
+
object.customMetadata?.status !== "ok" ||
|
|
1267
|
+
object.size === 0
|
|
1268
|
+
) {
|
|
1017
1269
|
return apiError(c, 404, "NOT_FOUND", "No logo for this domain");
|
|
1018
1270
|
}
|
|
1271
|
+
|
|
1019
1272
|
return new Response(object.body, { headers: BIMI_LOGO_HEADERS });
|
|
1020
1273
|
})
|
|
1021
1274
|
.get(
|
|
1022
1275
|
"/messages/:messageId/original",
|
|
1276
|
+
oauthScope(MAIL_READ_SCOPE),
|
|
1023
1277
|
zValidator("query", mailboxQuerySchema),
|
|
1024
1278
|
async (c) => {
|
|
1025
1279
|
const { mailboxId } = c.req.valid("query");
|
|
1026
|
-
|
|
1280
|
+
|
|
1281
|
+
if (!(await accessibleMailbox(c, mailboxId, "read"))) {
|
|
1027
1282
|
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
1028
1283
|
}
|
|
1029
|
-
|
|
1030
|
-
|
|
1284
|
+
|
|
1285
|
+
const message = await mailboxStub(c.env, mailboxId).getEmail(
|
|
1286
|
+
c.req.param("messageId")
|
|
1287
|
+
);
|
|
1288
|
+
|
|
1031
1289
|
if (!message?.rawMimeR2Key) {
|
|
1032
1290
|
return apiError(c, 404, "NOT_FOUND", "Original message not found");
|
|
1033
1291
|
}
|
|
1292
|
+
|
|
1034
1293
|
const requestedRange = c.req.header("range");
|
|
1294
|
+
|
|
1035
1295
|
const object = await getStoredObject(
|
|
1036
1296
|
c.env.MAIL_STORAGE,
|
|
1037
1297
|
message.rawMimeR2Key,
|
|
1038
|
-
requestedRange
|
|
1298
|
+
requestedRange
|
|
1039
1299
|
);
|
|
1300
|
+
|
|
1040
1301
|
if (!object) {
|
|
1041
1302
|
return apiError(c, 404, "NOT_FOUND", "Original message is missing");
|
|
1042
1303
|
}
|
|
1304
|
+
|
|
1043
1305
|
return storedObjectResponse({
|
|
1044
1306
|
object,
|
|
1045
1307
|
contentDisposition: `inline; filename*=UTF-8''${encodeURIComponent(`${message.id}.eml`)}`,
|
|
@@ -1047,28 +1309,37 @@ export const mailRoutes = new Hono<AppEnv>()
|
|
|
1047
1309
|
totalBytes: object.size,
|
|
1048
1310
|
rangeRequested: Boolean(requestedRange),
|
|
1049
1311
|
});
|
|
1050
|
-
}
|
|
1312
|
+
}
|
|
1051
1313
|
)
|
|
1052
1314
|
.get(
|
|
1053
1315
|
"/messages/:messageId/attachments/:attachmentId",
|
|
1316
|
+
oauthScope(MAIL_READ_SCOPE),
|
|
1054
1317
|
zValidator("query", mailboxQuerySchema),
|
|
1055
1318
|
async (c) => {
|
|
1056
1319
|
const { mailboxId } = c.req.valid("query");
|
|
1057
|
-
|
|
1320
|
+
|
|
1321
|
+
if (!(await accessibleMailbox(c, mailboxId, "read"))) {
|
|
1058
1322
|
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
1059
1323
|
}
|
|
1324
|
+
|
|
1060
1325
|
const file = await mailboxStub(c.env, mailboxId).getAttachment(
|
|
1061
1326
|
c.req.param("messageId"),
|
|
1062
|
-
c.req.param("attachmentId")
|
|
1327
|
+
c.req.param("attachmentId")
|
|
1063
1328
|
);
|
|
1329
|
+
|
|
1064
1330
|
if (!file) return apiError(c, 404, "NOT_FOUND", "Attachment not found");
|
|
1065
1331
|
const requestedRange = c.req.header("range");
|
|
1332
|
+
|
|
1066
1333
|
const object = await getStoredObject(
|
|
1067
1334
|
c.env.MAIL_STORAGE,
|
|
1068
1335
|
file.r2Key,
|
|
1069
|
-
requestedRange
|
|
1336
|
+
requestedRange
|
|
1070
1337
|
);
|
|
1071
|
-
|
|
1338
|
+
|
|
1339
|
+
if (!object) {
|
|
1340
|
+
return apiError(c, 404, "NOT_FOUND", "Attachment data is missing");
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1072
1343
|
return storedObjectResponse({
|
|
1073
1344
|
object,
|
|
1074
1345
|
contentType: file.contentType,
|
|
@@ -1076,35 +1347,66 @@ export const mailRoutes = new Hono<AppEnv>()
|
|
|
1076
1347
|
totalBytes: file.size,
|
|
1077
1348
|
rangeRequested: Boolean(requestedRange),
|
|
1078
1349
|
});
|
|
1079
|
-
}
|
|
1350
|
+
}
|
|
1080
1351
|
)
|
|
1081
1352
|
.get(
|
|
1082
1353
|
"/messages/:messageId/attachments/:attachmentId/preview",
|
|
1354
|
+
oauthScope(MAIL_READ_SCOPE),
|
|
1083
1355
|
zValidator("query", mailboxQuerySchema),
|
|
1084
1356
|
async (c) => {
|
|
1085
1357
|
const { mailboxId } = c.req.valid("query");
|
|
1086
|
-
|
|
1358
|
+
|
|
1359
|
+
if (!(await accessibleMailbox(c, mailboxId, "read"))) {
|
|
1087
1360
|
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
1088
1361
|
}
|
|
1362
|
+
|
|
1089
1363
|
const file = await mailboxStub(c.env, mailboxId).getAttachment(
|
|
1090
1364
|
c.req.param("messageId"),
|
|
1091
|
-
c.req.param("attachmentId")
|
|
1365
|
+
c.req.param("attachmentId")
|
|
1092
1366
|
);
|
|
1367
|
+
|
|
1093
1368
|
if (!file) return apiError(c, 404, "NOT_FOUND", "Attachment not found");
|
|
1094
1369
|
const preview = attachmentPreview(file);
|
|
1370
|
+
|
|
1095
1371
|
if (!preview) {
|
|
1096
|
-
return apiError(
|
|
1372
|
+
return apiError(
|
|
1373
|
+
c,
|
|
1374
|
+
422,
|
|
1375
|
+
"BAD_REQUEST",
|
|
1376
|
+
"Preview is not available for this file"
|
|
1377
|
+
);
|
|
1097
1378
|
}
|
|
1379
|
+
|
|
1098
1380
|
if (file.pdfPreviewStatus === "pending") {
|
|
1099
1381
|
return apiError(c, 409, "NOT_READY", "Preview is being generated");
|
|
1100
1382
|
}
|
|
1383
|
+
|
|
1101
1384
|
if (file.pdfPreviewStatus === "failed") {
|
|
1102
|
-
return apiError(
|
|
1385
|
+
return apiError(
|
|
1386
|
+
c,
|
|
1387
|
+
422,
|
|
1388
|
+
"UNAVAILABLE",
|
|
1389
|
+
"Preview could not be generated"
|
|
1390
|
+
);
|
|
1103
1391
|
}
|
|
1392
|
+
|
|
1104
1393
|
const requestedRange = c.req.header("range");
|
|
1105
|
-
|
|
1106
|
-
const
|
|
1107
|
-
|
|
1394
|
+
|
|
1395
|
+
const previewKey =
|
|
1396
|
+
file.pdfPreviewStatus === "ready"
|
|
1397
|
+
? officePreviewKey(file.r2Key)
|
|
1398
|
+
: file.r2Key;
|
|
1399
|
+
|
|
1400
|
+
const object = await getStoredObject(
|
|
1401
|
+
c.env.MAIL_STORAGE,
|
|
1402
|
+
previewKey,
|
|
1403
|
+
requestedRange
|
|
1404
|
+
);
|
|
1405
|
+
|
|
1406
|
+
if (!object) {
|
|
1407
|
+
return apiError(c, 404, "NOT_FOUND", "Attachment data is missing");
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1108
1410
|
const response = storedObjectResponse({
|
|
1109
1411
|
object,
|
|
1110
1412
|
contentType: preview.contentType,
|
|
@@ -1112,39 +1414,40 @@ export const mailRoutes = new Hono<AppEnv>()
|
|
|
1112
1414
|
totalBytes: object.size,
|
|
1113
1415
|
rangeRequested: Boolean(requestedRange),
|
|
1114
1416
|
});
|
|
1417
|
+
|
|
1115
1418
|
response.headers.set("cross-origin-resource-policy", "same-origin");
|
|
1116
1419
|
response.headers.set("content-security-policy", "frame-ancestors 'self'");
|
|
1420
|
+
|
|
1117
1421
|
return response;
|
|
1118
|
-
}
|
|
1422
|
+
}
|
|
1119
1423
|
)
|
|
1120
1424
|
.get(
|
|
1121
1425
|
"/messages/:messageId/attachments/:attachmentId/download-url",
|
|
1426
|
+
oauthScope(MAIL_READ_SCOPE),
|
|
1122
1427
|
zValidator("query", mailboxQuerySchema),
|
|
1123
1428
|
async (c) => {
|
|
1124
1429
|
const { mailboxId } = c.req.valid("query");
|
|
1125
|
-
|
|
1430
|
+
|
|
1431
|
+
if (!(await accessibleMailbox(c, mailboxId, "read"))) {
|
|
1126
1432
|
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
1127
1433
|
}
|
|
1434
|
+
|
|
1128
1435
|
const file = await mailboxStub(c.env, mailboxId).getAttachment(
|
|
1129
1436
|
c.req.param("messageId"),
|
|
1130
|
-
c.req.param("attachmentId")
|
|
1437
|
+
c.req.param("attachmentId")
|
|
1131
1438
|
);
|
|
1439
|
+
|
|
1132
1440
|
if (!file) return apiError(c, 404, "NOT_FOUND", "Attachment not found");
|
|
1133
|
-
|
|
1441
|
+
|
|
1442
|
+
if (!(await c.env.MAIL_STORAGE.head(file.r2Key))) {
|
|
1134
1443
|
return apiError(c, 404, "NOT_FOUND", "Attachment data is missing");
|
|
1135
1444
|
}
|
|
1445
|
+
|
|
1136
1446
|
const download = await signR2GetUrl({
|
|
1137
1447
|
env: c.env,
|
|
1138
1448
|
r2Key: file.r2Key,
|
|
1139
1449
|
});
|
|
1140
|
-
|
|
1141
|
-
return apiError(
|
|
1142
|
-
c,
|
|
1143
|
-
503,
|
|
1144
|
-
"UNAVAILABLE",
|
|
1145
|
-
"Direct R2 downloads are not configured",
|
|
1146
|
-
);
|
|
1147
|
-
}
|
|
1450
|
+
|
|
1148
1451
|
return c.json({
|
|
1149
1452
|
ok: true as const,
|
|
1150
1453
|
attachment: {
|
|
@@ -1156,31 +1459,36 @@ export const mailRoutes = new Hono<AppEnv>()
|
|
|
1156
1459
|
expiresAt: download.expiresAt,
|
|
1157
1460
|
},
|
|
1158
1461
|
});
|
|
1159
|
-
}
|
|
1462
|
+
}
|
|
1160
1463
|
)
|
|
1161
1464
|
.get(
|
|
1162
1465
|
"/messages/:messageId/attachments/:attachmentId/inline",
|
|
1466
|
+
oauthScope(MAIL_READ_SCOPE),
|
|
1163
1467
|
zValidator("query", mailboxQuerySchema),
|
|
1164
1468
|
async (c) => {
|
|
1165
1469
|
const { mailboxId } = c.req.valid("query");
|
|
1166
|
-
|
|
1470
|
+
|
|
1471
|
+
if (!(await accessibleMailbox(c, mailboxId, "read"))) {
|
|
1167
1472
|
return apiError(c, 403, "FORBIDDEN", "Mailbox access is required");
|
|
1168
1473
|
}
|
|
1474
|
+
|
|
1169
1475
|
const file = await mailboxStub(c.env, mailboxId).getAttachment(
|
|
1170
1476
|
c.req.param("messageId"),
|
|
1171
|
-
c.req.param("attachmentId")
|
|
1477
|
+
c.req.param("attachmentId")
|
|
1172
1478
|
);
|
|
1479
|
+
|
|
1173
1480
|
const contentType = file ? mediaType(file.contentType) : "";
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|| !isComposerInlineImageContentType(contentType)
|
|
1177
|
-
) {
|
|
1481
|
+
|
|
1482
|
+
if (!file?.contentId || !isComposerInlineImageContentType(contentType)) {
|
|
1178
1483
|
return apiError(c, 404, "NOT_FOUND", "Inline image not found");
|
|
1179
1484
|
}
|
|
1485
|
+
|
|
1180
1486
|
const object = await c.env.MAIL_STORAGE.get(file.r2Key);
|
|
1487
|
+
|
|
1181
1488
|
if (!object) {
|
|
1182
1489
|
return apiError(c, 404, "NOT_FOUND", "Inline image data is missing");
|
|
1183
1490
|
}
|
|
1491
|
+
|
|
1184
1492
|
return new Response(object.body, {
|
|
1185
1493
|
headers: {
|
|
1186
1494
|
"cache-control": "private, no-store",
|
|
@@ -1190,69 +1498,75 @@ export const mailRoutes = new Hono<AppEnv>()
|
|
|
1190
1498
|
"x-content-type-options": "nosniff",
|
|
1191
1499
|
},
|
|
1192
1500
|
});
|
|
1193
|
-
}
|
|
1501
|
+
}
|
|
1194
1502
|
)
|
|
1195
1503
|
.post(
|
|
1196
1504
|
"/messages/:id/send-again",
|
|
1505
|
+
oauthScope(MAIL_SEND_SCOPE),
|
|
1197
1506
|
zValidator("query", mailboxQuerySchema),
|
|
1198
1507
|
async (c) => {
|
|
1199
1508
|
const { mailboxId } = c.req.valid("query");
|
|
1200
|
-
const access = await accessibleMailbox(c
|
|
1509
|
+
const access = await accessibleMailbox(c, mailboxId, "send");
|
|
1510
|
+
|
|
1201
1511
|
if (!access) {
|
|
1202
1512
|
return apiError(c, 403, "FORBIDDEN", "Send access is required");
|
|
1203
1513
|
}
|
|
1514
|
+
|
|
1204
1515
|
const stub = mailboxStub(c.env, mailboxId);
|
|
1205
1516
|
const message = await stub.getEmail(c.req.param("id"));
|
|
1517
|
+
|
|
1206
1518
|
if (!message || message.direction !== "outgoing") {
|
|
1207
1519
|
return apiError(c, 404, "NOT_FOUND", "Outgoing message not found");
|
|
1208
1520
|
}
|
|
1521
|
+
|
|
1209
1522
|
const resent = await stub.resendOutgoing(message.id);
|
|
1523
|
+
|
|
1210
1524
|
if (!resent) {
|
|
1211
|
-
return apiError(
|
|
1525
|
+
return apiError(
|
|
1526
|
+
c,
|
|
1527
|
+
409,
|
|
1528
|
+
"CONFLICT",
|
|
1529
|
+
"Only failed or unconfirmed messages can be sent again"
|
|
1530
|
+
);
|
|
1212
1531
|
}
|
|
1532
|
+
|
|
1213
1533
|
deferEmailSentWebhook({
|
|
1214
1534
|
env: c.env,
|
|
1215
1535
|
mailboxId,
|
|
1216
1536
|
email: resent,
|
|
1217
1537
|
defer: (task) => c.executionCtx.waitUntil(task),
|
|
1218
1538
|
});
|
|
1539
|
+
|
|
1219
1540
|
return c.json({
|
|
1220
1541
|
ok: true as const,
|
|
1221
1542
|
messageId: resent.id,
|
|
1222
1543
|
transportState: outboundTransportState(resent),
|
|
1223
1544
|
transportError: resent.transportError,
|
|
1224
1545
|
});
|
|
1225
|
-
}
|
|
1546
|
+
}
|
|
1226
1547
|
)
|
|
1227
1548
|
.post(
|
|
1228
1549
|
"/attachment-preflight",
|
|
1550
|
+
oauthScope(MAIL_SEND_SCOPE),
|
|
1229
1551
|
zValidator("json", attachmentPreflightSchema),
|
|
1230
1552
|
async (c) => {
|
|
1231
1553
|
const input = c.req.valid("json");
|
|
1232
1554
|
const user = c.get("user");
|
|
1233
|
-
const access = await accessibleMailbox(
|
|
1234
|
-
|
|
1235
|
-
user.id,
|
|
1236
|
-
input.mailboxId,
|
|
1237
|
-
"send",
|
|
1238
|
-
);
|
|
1555
|
+
const access = await accessibleMailbox(c, input.mailboxId, "send");
|
|
1556
|
+
|
|
1239
1557
|
if (!access) {
|
|
1240
1558
|
return apiError(c, 403, "FORBIDDEN", "Send access is required");
|
|
1241
1559
|
}
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
429,
|
|
1253
|
-
"RATE_LIMITED",
|
|
1254
|
-
"Too many attachment checks",
|
|
1255
|
-
);
|
|
1560
|
+
|
|
1561
|
+
const rateExceeded = await overRateLimit(
|
|
1562
|
+
c,
|
|
1563
|
+
"RATE_LIMIT_120",
|
|
1564
|
+
"mail-attachment-preflight",
|
|
1565
|
+
`${user.id}:${input.mailboxId}`
|
|
1566
|
+
);
|
|
1567
|
+
|
|
1568
|
+
if (rateExceeded) {
|
|
1569
|
+
return apiError(c, 429, "RATE_LIMITED", "Too many attachment checks");
|
|
1256
1570
|
}
|
|
1257
1571
|
|
|
1258
1572
|
try {
|
|
@@ -1260,12 +1574,14 @@ export const mailRoutes = new Hono<AppEnv>()
|
|
|
1260
1574
|
let related: Email | null = null;
|
|
1261
1575
|
let forwarded: Email | null = null;
|
|
1262
1576
|
let includeRelatedContext = false;
|
|
1577
|
+
|
|
1263
1578
|
if (input.kind === "forward") {
|
|
1264
1579
|
const context = await resolveForwardContext({
|
|
1265
1580
|
env: c.env,
|
|
1266
1581
|
mailboxId: input.mailboxId,
|
|
1267
1582
|
sourceEmailId: input.sourceEmailId,
|
|
1268
1583
|
});
|
|
1584
|
+
|
|
1269
1585
|
forwarded = context.source;
|
|
1270
1586
|
subject = context.subject;
|
|
1271
1587
|
} else if (input.kind === "reply") {
|
|
@@ -1278,10 +1594,12 @@ export const mailRoutes = new Hono<AppEnv>()
|
|
|
1278
1594
|
cc: input.cc,
|
|
1279
1595
|
bcc: input.bcc,
|
|
1280
1596
|
});
|
|
1597
|
+
|
|
1281
1598
|
related = context.source;
|
|
1282
1599
|
subject = context.subject;
|
|
1283
1600
|
includeRelatedContext = context.includeRelatedContext;
|
|
1284
1601
|
}
|
|
1602
|
+
|
|
1285
1603
|
const result = await preflightOutgoingAttachments({
|
|
1286
1604
|
env: c.env,
|
|
1287
1605
|
compose: {
|
|
@@ -1296,54 +1614,63 @@ export const mailRoutes = new Hono<AppEnv>()
|
|
|
1296
1614
|
forwarded,
|
|
1297
1615
|
includeRelatedContext,
|
|
1298
1616
|
});
|
|
1617
|
+
|
|
1299
1618
|
return c.json({ ok: true as const, ...result });
|
|
1300
1619
|
} catch (error) {
|
|
1301
1620
|
return outgoingFailure(c, error);
|
|
1302
1621
|
}
|
|
1303
|
-
}
|
|
1622
|
+
}
|
|
1304
1623
|
)
|
|
1305
|
-
.post(
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
const
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1624
|
+
.post(
|
|
1625
|
+
"/messages",
|
|
1626
|
+
oauthScope(MAIL_SEND_SCOPE),
|
|
1627
|
+
zValidator("json", composeSchema),
|
|
1628
|
+
async (c) => {
|
|
1629
|
+
const input = c.req.valid("json");
|
|
1630
|
+
const access = await accessibleMailbox(c, input.mailboxId, "send");
|
|
1631
|
+
|
|
1632
|
+
if (!access) {
|
|
1633
|
+
return apiError(c, 403, "FORBIDDEN", "Send access is required");
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
try {
|
|
1637
|
+
const submission = await submitOutgoing({
|
|
1638
|
+
env: c.env,
|
|
1639
|
+
requestUrl: c.req.url,
|
|
1640
|
+
compose: {
|
|
1641
|
+
...input,
|
|
1642
|
+
userId: c.get("user").id,
|
|
1643
|
+
},
|
|
1644
|
+
conversationId: createId("conv"),
|
|
1645
|
+
related: null,
|
|
1646
|
+
forwarded: null,
|
|
1647
|
+
includeRelatedContext: false,
|
|
1648
|
+
fromAddress: access.address,
|
|
1649
|
+
fromName: access.displayName,
|
|
1650
|
+
defer: (task) => c.executionCtx.waitUntil(task),
|
|
1651
|
+
});
|
|
1652
|
+
|
|
1653
|
+
return c.json(
|
|
1654
|
+
outgoingResponse(submission.email, false),
|
|
1655
|
+
submission.inserted ? 201 : 200
|
|
1656
|
+
);
|
|
1657
|
+
} catch (error) {
|
|
1658
|
+
return outgoingFailure(c, error);
|
|
1659
|
+
}
|
|
1331
1660
|
}
|
|
1332
|
-
|
|
1661
|
+
)
|
|
1333
1662
|
.post(
|
|
1334
1663
|
"/messages/:id/replies",
|
|
1664
|
+
oauthScope(MAIL_SEND_SCOPE),
|
|
1335
1665
|
zValidator("json", replySchema),
|
|
1336
1666
|
async (c) => {
|
|
1337
1667
|
const input = c.req.valid("json");
|
|
1338
|
-
const access = await accessibleMailbox(
|
|
1339
|
-
|
|
1340
|
-
c.get("user").id,
|
|
1341
|
-
input.mailboxId,
|
|
1342
|
-
"send",
|
|
1343
|
-
);
|
|
1668
|
+
const access = await accessibleMailbox(c, input.mailboxId, "send");
|
|
1669
|
+
|
|
1344
1670
|
if (!access) {
|
|
1345
1671
|
return apiError(c, 403, "FORBIDDEN", "Send access is required");
|
|
1346
1672
|
}
|
|
1673
|
+
|
|
1347
1674
|
try {
|
|
1348
1675
|
const context = await resolveReplyContext({
|
|
1349
1676
|
env: c.env,
|
|
@@ -1354,6 +1681,7 @@ export const mailRoutes = new Hono<AppEnv>()
|
|
|
1354
1681
|
cc: input.cc,
|
|
1355
1682
|
bcc: input.bcc,
|
|
1356
1683
|
});
|
|
1684
|
+
|
|
1357
1685
|
const submission = await submitOutgoing({
|
|
1358
1686
|
env: c.env,
|
|
1359
1687
|
requestUrl: c.req.url,
|
|
@@ -1377,35 +1705,35 @@ export const mailRoutes = new Hono<AppEnv>()
|
|
|
1377
1705
|
fromName: access.displayName,
|
|
1378
1706
|
defer: (task) => c.executionCtx.waitUntil(task),
|
|
1379
1707
|
});
|
|
1708
|
+
|
|
1380
1709
|
return c.json(
|
|
1381
1710
|
outgoingResponse(submission.email, context.detached),
|
|
1382
|
-
submission.inserted ? 201 : 200
|
|
1711
|
+
submission.inserted ? 201 : 200
|
|
1383
1712
|
);
|
|
1384
1713
|
} catch (error) {
|
|
1385
1714
|
return outgoingFailure(c, error);
|
|
1386
1715
|
}
|
|
1387
|
-
}
|
|
1716
|
+
}
|
|
1388
1717
|
)
|
|
1389
1718
|
.post(
|
|
1390
1719
|
"/messages/:id/forward",
|
|
1720
|
+
oauthScope(MAIL_SEND_SCOPE),
|
|
1391
1721
|
zValidator("json", forwardSchema),
|
|
1392
1722
|
async (c) => {
|
|
1393
1723
|
const input = c.req.valid("json");
|
|
1394
|
-
const access = await accessibleMailbox(
|
|
1395
|
-
|
|
1396
|
-
c.get("user").id,
|
|
1397
|
-
input.mailboxId,
|
|
1398
|
-
"send",
|
|
1399
|
-
);
|
|
1724
|
+
const access = await accessibleMailbox(c, input.mailboxId, "send");
|
|
1725
|
+
|
|
1400
1726
|
if (!access) {
|
|
1401
1727
|
return apiError(c, 403, "FORBIDDEN", "Send access is required");
|
|
1402
1728
|
}
|
|
1729
|
+
|
|
1403
1730
|
try {
|
|
1404
1731
|
const context = await resolveForwardContext({
|
|
1405
1732
|
env: c.env,
|
|
1406
1733
|
mailboxId: input.mailboxId,
|
|
1407
1734
|
sourceEmailId: c.req.param("id"),
|
|
1408
1735
|
});
|
|
1736
|
+
|
|
1409
1737
|
const submission = await submitOutgoing({
|
|
1410
1738
|
env: c.env,
|
|
1411
1739
|
requestUrl: c.req.url,
|
|
@@ -1422,13 +1750,14 @@ export const mailRoutes = new Hono<AppEnv>()
|
|
|
1422
1750
|
fromName: access.displayName,
|
|
1423
1751
|
defer: (task) => c.executionCtx.waitUntil(task),
|
|
1424
1752
|
});
|
|
1753
|
+
|
|
1425
1754
|
return c.json(
|
|
1426
1755
|
outgoingResponse(submission.email, false),
|
|
1427
|
-
submission.inserted ? 201 : 200
|
|
1756
|
+
submission.inserted ? 201 : 200
|
|
1428
1757
|
);
|
|
1429
1758
|
} catch (error) {
|
|
1430
1759
|
return outgoingFailure(c, error);
|
|
1431
1760
|
}
|
|
1432
|
-
}
|
|
1761
|
+
}
|
|
1433
1762
|
)
|
|
1434
1763
|
.route("/", mailSafetyRoutes);
|