@open-workspace/email 0.4.1 → 0.5.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 +9 -4
- package/alchemy/index.ts +130 -2
- package/drizzle/mailbox/0002_good_komodo.sql +2 -0
- package/drizzle/mailbox/0003_after_0_4_2.sql +180 -0
- package/drizzle/mailbox/meta/0002_snapshot.json +1017 -0
- package/drizzle/mailbox/meta/0003_snapshot.json +1507 -0
- package/drizzle/mailbox/meta/_journal.json +14 -0
- package/drizzle/mailbox/migrations.js +5 -1
- package/migrations/0001_overrated_ricochet.sql +2 -0
- package/migrations/0002_after_0_4_2.sql +35 -0
- package/migrations/meta/0001_snapshot.json +564 -0
- package/migrations/meta/0002_snapshot.json +807 -0
- package/migrations/meta/_journal.json +14 -0
- package/package.json +23 -7
- package/shared/attachment-preview.ts +18 -8
- package/shared/folder-order.ts +31 -6
- package/shared/mail-headers.ts +3 -3
- package/shared/mail-html.ts +25 -0
- package/shared/mail-import.ts +0 -7
- package/shared/mail-received.ts +4 -4
- package/shared/mail-rule-actions.ts +47 -0
- package/shared/mail.ts +70 -4
- package/shared/office-preview.ts +0 -4
- package/shared/pdfjs-assets.ts +1 -3
- package/shared/rich-content.ts +35 -0
- package/shared/signature.ts +15 -0
- package/src/admin/address-auto-reply.tsx +49 -0
- package/src/admin/blocked-senders.tsx +86 -66
- package/src/admin/forward-destinations.tsx +140 -0
- package/src/admin/mail-archive.tsx +134 -0
- package/src/admin/team-signature.tsx +90 -0
- package/src/client.tsx +130 -16
- package/src/mail/attachment-preview-dialog.tsx +13 -5
- package/src/mail/auto-reply-banner.tsx +61 -0
- package/src/mail/blocked-senders.tsx +124 -91
- package/src/mail/compose-window-chrome.tsx +20 -8
- package/src/mail/compose-window.tsx +387 -365
- package/src/mail/composer-asset-bookmarks.ts +47 -12
- package/src/mail/composer-attachment-list.tsx +42 -17
- package/src/mail/composer-editor-document.ts +54 -10
- package/src/mail/composer-editor.tsx +44 -44
- package/src/mail/composer-link-text.ts +42 -0
- package/src/mail/composer-recipient-fields.tsx +25 -16
- package/src/mail/composer-recipients.ts +62 -16
- package/src/mail/composer-session.ts +107 -23
- package/src/mail/composer-toolbar.tsx +15 -1
- package/src/mail/composer-upload-client.ts +29 -1
- package/src/mail/composer-upload-progress.ts +2 -2
- package/src/mail/conversation-actions-model.ts +56 -0
- package/src/mail/conversation-list.tsx +263 -128
- package/src/mail/conversation-loading-skeleton.tsx +165 -90
- package/src/mail/conversation-message.tsx +257 -102
- package/src/mail/conversation-order.ts +12 -0
- package/src/mail/conversation-reply.tsx +313 -189
- package/src/mail/conversation-selection-toolbar.tsx +188 -143
- package/src/mail/conversation-view.tsx +320 -85
- package/src/mail/delivery-indicator.tsx +33 -12
- package/src/mail/draft-attachments.ts +194 -0
- package/src/mail/email-html-body.tsx +97 -53
- package/src/mail/folder-cleanup-bar.tsx +193 -0
- package/src/mail/folder-glyph.tsx +5 -0
- package/src/mail/folder-manager.tsx +71 -38
- package/src/mail/mail-app-bar.tsx +15 -3
- package/src/mail/mail-dock.tsx +19 -3
- package/src/mail/mail-focus.ts +48 -0
- package/src/mail/mail-folders.ts +14 -2
- package/src/mail/mail-layout.css +20 -0
- package/src/mail/mail-mailbox-sheet.tsx +22 -69
- package/src/mail/mail-nav-rail.tsx +7 -4
- package/src/mail/mail-nav.tsx +66 -46
- package/src/mail/mail-prefetch.ts +30 -9
- package/src/mail/mail-primitives.tsx +6 -4
- package/src/mail/mail-queries.ts +122 -20
- package/src/mail/mail-query-cache.ts +1085 -173
- package/src/mail/mail-search-params.ts +35 -0
- package/src/mail/mail-shell.tsx +32 -9
- package/src/mail/mailbox-ai-settings.tsx +56 -42
- package/src/mail/mailbox-realtime.tsx +4 -12
- package/src/mail/mailbox-rules.tsx +898 -0
- package/src/mail/message-actions.tsx +38 -26
- package/src/mail/message-attachments.tsx +20 -12
- package/src/mail/message-body.ts +53 -0
- package/src/mail/message-format.ts +8 -2
- package/src/mail/message-header.tsx +3 -1
- package/src/mail/message-translation.tsx +34 -67
- package/src/mail/original-message-sheet.tsx +63 -50
- package/src/mail/original-message.ts +6 -6
- package/src/mail/pane-splitter.tsx +3 -3
- package/src/mail/pdf-preview.tsx +70 -62
- package/src/mail/plain-message-text.tsx +28 -0
- package/src/mail/print-message.ts +31 -36
- package/src/mail/reader-pane.tsx +134 -102
- package/src/mail/recipient-combobox.tsx +52 -29
- package/src/mail/recipient-field-row.tsx +3 -0
- package/src/mail/rich-content.ts +128 -0
- package/src/mail/sanitize-email-html.ts +57 -33
- package/src/mail/sender-actions.tsx +49 -39
- package/src/mail/sender-authentication.tsx +1 -1
- package/src/mail/sender-dialogs.tsx +67 -43
- package/src/mail/sender-security.tsx +9 -10
- package/src/mail/signature.ts +43 -0
- package/src/mail/translation-html.ts +3 -3
- package/src/mail/types.ts +12 -0
- package/src/mail/use-composer-attachment-preflight.ts +23 -60
- package/src/mail/use-composer-core.ts +286 -0
- package/src/mail/use-composer-navigation.ts +120 -0
- package/src/mail/use-composer-submission.ts +154 -19
- package/src/mail/use-conversation-actions.ts +292 -0
- package/src/mail/use-conversation-position.ts +51 -0
- package/src/mail/use-conversation-selection.ts +192 -89
- package/src/mail/use-draft-autosave.ts +394 -0
- package/src/mail/use-drafts.ts +194 -0
- package/src/mail/use-mail-controller.ts +754 -213
- package/src/mail/use-mail-data.ts +210 -100
- package/src/mail/use-mail-safety.ts +19 -38
- package/src/mail/use-mail-send.ts +18 -6
- package/src/mail/use-pdf-translation.ts +1 -1
- package/src/mail/use-reply-cc.ts +61 -0
- package/src/mail/use-visible-message-read.ts +128 -64
- package/src/pwa/push-key.ts +18 -0
- package/src/pwa/push-subscription.ts +88 -26
- package/src/settings/auto-reply-editor.tsx +454 -0
- package/src/settings/auto-reply-page.tsx +59 -0
- package/src/settings/mail-apps-page.tsx +52 -43
- package/src/settings/notifications-page.tsx +82 -67
- package/src/settings/rich-content-editor.tsx +182 -0
- package/src/settings/settings-queries.ts +57 -0
- package/src/settings/signature-editor.tsx +142 -0
- package/src/settings/signature-page.tsx +70 -0
- package/worker/admin/blocked-sender-routes.ts +10 -16
- package/worker/backups/eml.ts +185 -0
- package/worker/backups/file-parts.ts +140 -0
- package/worker/backups/mail-backup.ts +644 -0
- package/worker/backups/settings-backup.ts +866 -0
- package/worker/backups/stream-eml.ts +73 -0
- package/worker/db/schema.ts +98 -2
- package/worker/jmap/attachment-blobs.ts +113 -0
- package/worker/jmap/blobs.ts +162 -0
- package/worker/jmap/draft-content.ts +42 -0
- package/worker/jmap/drafts.ts +70 -0
- package/worker/jmap/email-body.ts +152 -0
- package/worker/jmap/email-methods.ts +1223 -0
- package/worker/jmap/eventsource.ts +9 -8
- package/worker/jmap/import-methods.ts +205 -0
- package/worker/jmap/mailbox-methods.ts +187 -0
- package/worker/jmap/method-core.ts +379 -0
- package/worker/jmap/methods.ts +108 -1815
- package/worker/jmap/push-subscription-methods.ts +373 -0
- package/worker/jmap/push-types.ts +46 -2
- package/worker/jmap/push.ts +24 -31
- package/worker/jmap/routes.ts +144 -153
- package/worker/jmap/submission-methods.ts +395 -0
- package/worker/mail/access.ts +35 -12
- package/worker/mail/ai-classification.ts +2 -2
- package/worker/mail/archive-object.ts +96 -0
- package/worker/mail/archive-routes.ts +35 -0
- package/worker/mail/archive.ts +682 -0
- package/worker/mail/auth-headers.ts +48 -40
- package/worker/mail/auto-reply-routes.ts +255 -0
- package/worker/mail/auto-reply.ts +243 -0
- package/worker/mail/bimi.ts +53 -36
- package/worker/mail/bootstrap.ts +11 -3
- package/worker/mail/capabilities.ts +69 -0
- package/worker/mail/classification-signals.ts +1 -1
- package/worker/mail/confusables-data.ts +9 -0
- package/worker/mail/conversation-cursor.ts +6 -15
- package/worker/mail/delivery-events.ts +9 -7
- package/worker/mail/delivery-facts.ts +1 -1
- package/worker/mail/demo-routes.ts +3 -3
- package/worker/mail/doh.ts +3 -3
- package/worker/mail/download-links.ts +153 -0
- package/worker/mail/downloads.ts +2 -6
- package/worker/mail/draft-routes.ts +473 -0
- package/worker/mail/draft-sender.ts +54 -0
- package/worker/mail/edge-cache.ts +41 -55
- package/worker/mail/email-routing.ts +123 -0
- package/worker/mail/forward-destinations.ts +114 -0
- package/worker/mail/forward-downloads.ts +115 -0
- package/worker/mail/forward-html.ts +85 -0
- package/worker/mail/header-metadata.ts +2 -5
- package/worker/mail/impersonation.ts +102 -101
- package/worker/mail/import-routes.ts +29 -82
- package/worker/mail/import.ts +130 -0
- package/worker/mail/inbound-delivery.ts +6 -5
- package/worker/mail/inbound.ts +58 -28
- package/worker/mail/ip-intel.ts +8 -17
- package/worker/mail/isolate-cache.ts +1 -1
- package/worker/mail/mailbox-deletion.ts +33 -12
- package/worker/mail/mailbox-directory.ts +39 -65
- package/worker/mail/mailing-list.ts +29 -58
- package/worker/mail/message-security.ts +3 -3
- package/worker/mail/message-view.ts +12 -10
- package/worker/mail/office-conversion.ts +3 -5
- package/worker/mail/office-preview-container.ts +3 -8
- package/worker/mail/outbound-content.ts +139 -65
- package/worker/mail/outbound-delivery.ts +20 -17
- package/worker/mail/outbound-service.ts +34 -9
- package/worker/mail/outbound.ts +146 -75
- package/worker/mail/outgoing-context.ts +60 -30
- package/worker/mail/participants.ts +10 -15
- package/worker/mail/plain-body.ts +39 -0
- package/worker/mail/push-endpoint.ts +17 -0
- package/worker/mail/push-notifications.ts +87 -43
- package/worker/mail/quote-parser.ts +107 -25
- package/worker/mail/r2-presigned-urls.ts +7 -0
- package/worker/mail/receive.ts +146 -39
- package/worker/mail/recipients.ts +1 -1
- package/worker/mail/remote-proxy.ts +3 -3
- package/worker/mail/repeat.ts +1 -1
- package/worker/mail/reply-plan.ts +124 -26
- package/worker/mail/rfc.ts +15 -7
- package/worker/mail/rich-content.ts +207 -0
- package/worker/mail/routes.ts +696 -304
- package/worker/mail/routing.ts +274 -0
- package/worker/mail/rules.ts +230 -0
- package/worker/mail/safety-routes.ts +88 -80
- package/worker/mail/schemas.ts +222 -31
- package/worker/mail/search.ts +25 -2
- package/worker/mail/security-settings.ts +4 -10
- package/worker/mail/send-message.ts +238 -0
- package/worker/mail/sender-intel.ts +12 -20
- package/worker/mail/signature-routes.ts +201 -0
- package/worker/mail/signatures.ts +195 -0
- package/worker/mail/spamhaus.ts +28 -16
- package/worker/mail/storage-keys.ts +35 -0
- package/worker/mail/unsubscribe.ts +19 -41
- package/worker/mail/uploads.ts +193 -80
- package/worker/mail/webhook-source.ts +3 -2
- package/worker/mail/workspace-safety.ts +194 -60
- package/worker/mailbox/demo.ts +13 -15
- package/worker/mailbox/email-index.ts +92 -13
- package/worker/mailbox/folder-model.ts +0 -20
- package/worker/mailbox/import-placement.ts +21 -36
- package/worker/mailbox/inbound-decision.ts +114 -0
- package/worker/mailbox/inbox-counts.ts +45 -25
- package/worker/mailbox/index.ts +843 -2888
- package/worker/mailbox/jmap-change-log.ts +195 -0
- package/worker/mailbox/jmap-email-rows.ts +186 -0
- package/worker/mailbox/jmap-mailboxes.ts +116 -0
- package/worker/mailbox/jmap-placement.ts +139 -0
- package/worker/mailbox/jmap-query-filter.ts +231 -0
- package/worker/mailbox/jmap-store.ts +167 -299
- package/worker/mailbox/mailbox-auto-reply.ts +301 -0
- package/worker/mailbox/mailbox-backup.ts +538 -0
- package/worker/mailbox/mailbox-drafts.ts +417 -0
- package/worker/mailbox/mailbox-folders.ts +242 -0
- package/worker/mailbox/mailbox-import.ts +450 -0
- package/worker/mailbox/mailbox-inbound.ts +934 -0
- package/worker/mailbox/mailbox-jmap.ts +294 -0
- package/worker/mailbox/mailbox-outbound.ts +413 -0
- package/worker/mailbox/mailbox-rules.ts +336 -0
- package/worker/mailbox/mailbox-senders.ts +294 -0
- package/worker/mailbox/mailbox-storage.ts +438 -0
- package/worker/mailbox/mailbox-views.ts +891 -0
- package/worker/mailbox/model.ts +1 -0
- package/worker/mailbox/office-preview-jobs.ts +59 -47
- package/worker/mailbox/placement.ts +933 -0
- package/worker/mailbox/restore-thread.ts +52 -0
- package/worker/mailbox/retention.ts +36 -0
- package/worker/mailbox/schema.ts +211 -1
- package/worker/mailbox/senders.ts +216 -178
- package/worker/mailbox/spam-undo-filing.ts +138 -0
- package/worker/mailbox/spam-undo.ts +240 -0
- package/worker/mailbox/support.ts +416 -0
- package/worker/mcp/mail-action-tools.ts +156 -0
- package/worker/mcp/mail-compose-tools.ts +8 -2
- package/worker/mcp/mail-safety-tools.ts +4 -4
- package/worker/module.ts +23 -2
- package/src/mail/use-compose-submission.ts +0 -208
- package/src/mail/use-reply-submission.ts +0 -114
- package/worker/mail/capped-body.ts +0 -36
package/worker/jmap/methods.ts
CHANGED
|
@@ -1,1807 +1,64 @@
|
|
|
1
|
-
|
|
2
|
-
createDb,
|
|
3
|
-
describeIssues,
|
|
4
|
-
issueProperties,
|
|
5
|
-
} from "@open-workspace/core/module";
|
|
6
|
-
import type { Issue } from "@open-workspace/core/module";
|
|
7
|
-
import { and, eq, inArray } from "drizzle-orm";
|
|
1
|
+
/** JMAP's methods by name, and running one request's method calls in order. */
|
|
8
2
|
import { z } from "zod";
|
|
9
3
|
|
|
10
|
-
import { MAX_COMPOSER_ATTACHMENT_COUNT } from "../../shared/mail";
|
|
11
4
|
import {
|
|
12
5
|
MAIL_ORGANIZE_SCOPE,
|
|
13
6
|
MAIL_READ_SCOPE,
|
|
14
7
|
MAIL_SEND_SCOPE,
|
|
15
8
|
} from "../../shared/permissions";
|
|
16
|
-
import { jmapPushSubscriptions } from "../db/schema";
|
|
17
|
-
import { submitOutgoing } from "../mail/outbound-service";
|
|
18
|
-
import { composeSchema } from "../mail/schemas";
|
|
19
|
-
import { describeComposerUpload, UploadValidationError } from "../mail/uploads";
|
|
20
9
|
import { mailboxStub } from "../mailbox";
|
|
21
|
-
import type { JmapEmailFilter, JmapMailboxRow } from "../mailbox/jmap-store";
|
|
22
|
-
import type { Email } from "../mailbox/schema";
|
|
23
10
|
import {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
requestUrl: string;
|
|
55
|
-
defer: (task: Promise<unknown>) => void;
|
|
56
|
-
};
|
|
57
|
-
|
|
58
|
-
type Json = z.core.util.JSONType;
|
|
59
|
-
|
|
60
|
-
type JsonObject = Record<string, Json>;
|
|
61
|
-
|
|
62
|
-
/** RFC 8620 §3.3: a request is the capabilities it uses and its method calls. */
|
|
63
|
-
export const jmapRequestSchema = z.object({
|
|
64
|
-
using: z.array(z.string()),
|
|
65
|
-
methodCalls: z.array(
|
|
66
|
-
z.tuple([z.string(), z.record(z.string(), z.json()), z.string()])
|
|
67
|
-
),
|
|
68
|
-
createdIds: z.record(z.string(), z.string()).optional(),
|
|
69
|
-
});
|
|
70
|
-
|
|
71
|
-
export type JmapRequest = z.output<typeof jmapRequestSchema>;
|
|
72
|
-
|
|
73
|
-
type Invocation = [string, JsonObject, string];
|
|
74
|
-
|
|
75
|
-
/** A request-level error (RFC 8620 §3.6.1), answered as a problem document. */
|
|
76
|
-
export class JmapError extends Error {
|
|
77
|
-
constructor(
|
|
78
|
-
readonly type: string,
|
|
79
|
-
message: string
|
|
80
|
-
) {
|
|
81
|
-
super(message);
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/** The method-level errors (RFC 8620 §3.6.2, RFC 8621) these methods answer with. */
|
|
86
|
-
const methodErrorTypes = z.enum([
|
|
87
|
-
"accountNotFound",
|
|
88
|
-
"cannotCalculateChanges",
|
|
89
|
-
"forbidden",
|
|
90
|
-
"invalidArguments",
|
|
91
|
-
"invalidResultReference",
|
|
92
|
-
"requestTooLarge",
|
|
93
|
-
"stateMismatch",
|
|
94
|
-
"unknownMethod",
|
|
95
|
-
"unsupportedFilter",
|
|
96
|
-
"unsupportedSort",
|
|
97
|
-
]);
|
|
98
|
-
|
|
99
|
-
type MethodErrorType = z.output<typeof methodErrorTypes>;
|
|
100
|
-
|
|
101
|
-
/** A method-level error, answered in place of the method's response. */
|
|
102
|
-
class MethodError extends Error {
|
|
103
|
-
constructor(
|
|
104
|
-
readonly type: MethodErrorType,
|
|
105
|
-
message?: string
|
|
106
|
-
) {
|
|
107
|
-
super(message ?? type);
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/** Uploaded blobs are named after their upload: `upl~<upload id>`. */
|
|
112
|
-
export const UPLOAD_BLOB = /^upl~(upl_[a-f0-9]{32})$/u;
|
|
113
|
-
|
|
114
|
-
/** An attachment of a draft: bytes from /jmap/upload. */
|
|
115
|
-
type DraftAttachment = {
|
|
116
|
-
uploadId: string;
|
|
117
|
-
name: string;
|
|
118
|
-
type: string;
|
|
119
|
-
disposition: "attachment" | "inline";
|
|
120
|
-
contentId: string | undefined;
|
|
121
|
-
};
|
|
122
|
-
|
|
123
|
-
/**
|
|
124
|
-
* A draft from Email/set create; it lives only for the request that sends
|
|
125
|
-
* it. It holds the message as the mail app's composer would send it.
|
|
126
|
-
*/
|
|
127
|
-
type Draft = {
|
|
128
|
-
accountId: string;
|
|
129
|
-
compose: z.output<typeof composeSchema>;
|
|
130
|
-
attachments: DraftAttachment[];
|
|
131
|
-
};
|
|
132
|
-
|
|
133
|
-
/** The Email property a composer field comes from. */
|
|
134
|
-
function draftProperty(field: string) {
|
|
135
|
-
if (field === "bodyText") return "textBody";
|
|
136
|
-
|
|
137
|
-
if (field === "bodyHtml") return "htmlBody";
|
|
138
|
-
|
|
139
|
-
return field;
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/**
|
|
143
|
-
* A composer issue, at the Email property it is about. Issues about the
|
|
144
|
-
* message as a whole are about its recipients.
|
|
145
|
-
*/
|
|
146
|
-
function draftIssue(issue: Issue): Issue {
|
|
147
|
-
const [field = "to", ...rest] = issue.path;
|
|
148
|
-
|
|
149
|
-
return { ...issue, path: [draftProperty(String(field)), ...rest] };
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
type RequestState = {
|
|
153
|
-
context: JmapContext;
|
|
154
|
-
responses: Invocation[];
|
|
155
|
-
createdIds: Map<string, string>;
|
|
156
|
-
drafts: Map<string, Draft>;
|
|
157
|
-
/** Responses a method adds after its own, e.g. an implicit Email/set. */
|
|
158
|
-
after: Invocation[];
|
|
159
|
-
};
|
|
160
|
-
|
|
161
|
-
/** Arrays and objects are the JSON values a pointer steps into. */
|
|
162
|
-
function isJsonObject(value: Json): value is JsonObject {
|
|
163
|
-
return Object(value) === value && !Array.isArray(value);
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
// ---------------------------------------------------------------- references
|
|
167
|
-
|
|
168
|
-
/** RFC 8620 §3.7: a JSON Pointer where `*` maps over an array. */
|
|
169
|
-
function evaluatePointer(value: Json, path: string): Json {
|
|
170
|
-
if (path === "") return value;
|
|
171
|
-
|
|
172
|
-
const [head = "", ...rest] = path
|
|
173
|
-
.slice(1)
|
|
174
|
-
.split("/")
|
|
175
|
-
.map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
|
|
176
|
-
|
|
177
|
-
const tail = rest.length ? `/${rest.join("/")}` : "";
|
|
178
|
-
|
|
179
|
-
if (Array.isArray(value)) {
|
|
180
|
-
if (head === "*") {
|
|
181
|
-
return value.flatMap((item) => {
|
|
182
|
-
const result = evaluatePointer(item, tail);
|
|
183
|
-
|
|
184
|
-
return Array.isArray(result) ? result : [result];
|
|
185
|
-
});
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
const item = /^\d+$/u.test(head) ? value[Number(head)] : undefined;
|
|
189
|
-
|
|
190
|
-
if (item !== undefined) return evaluatePointer(item, tail);
|
|
191
|
-
} else if (isJsonObject(value) && Object.hasOwn(value, head)) {
|
|
192
|
-
const property = value[head];
|
|
193
|
-
|
|
194
|
-
if (property !== undefined) return evaluatePointer(property, tail);
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
throw new MethodError(
|
|
198
|
-
"invalidResultReference",
|
|
199
|
-
`Path ${path} does not resolve`
|
|
200
|
-
);
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
const resultReference = z.object({
|
|
204
|
-
resultOf: z.string(),
|
|
205
|
-
name: z.string(),
|
|
206
|
-
path: z.string(),
|
|
207
|
-
});
|
|
208
|
-
|
|
209
|
-
function resolveReferences(state: RequestState, args: JsonObject) {
|
|
210
|
-
const resolved: JsonObject = {};
|
|
211
|
-
|
|
212
|
-
for (const [key, value] of Object.entries(args)) {
|
|
213
|
-
if (!key.startsWith("#")) {
|
|
214
|
-
resolved[key] = value;
|
|
215
|
-
continue;
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
const name = key.slice(1);
|
|
219
|
-
|
|
220
|
-
if (Object.hasOwn(args, name)) {
|
|
221
|
-
throw new MethodError(
|
|
222
|
-
"invalidArguments",
|
|
223
|
-
`Both ${name} and #${name} given`
|
|
224
|
-
);
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
const reference = resultReference.safeParse(value);
|
|
228
|
-
|
|
229
|
-
if (!reference.success) {
|
|
230
|
-
throw new MethodError(
|
|
231
|
-
"invalidResultReference",
|
|
232
|
-
describeIssues(reference.error.issues)
|
|
233
|
-
);
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
const { resultOf, name: methodName, path } = reference.data;
|
|
237
|
-
|
|
238
|
-
const source = state.responses.find(
|
|
239
|
-
([response, , callId]) => callId === resultOf && response === methodName
|
|
240
|
-
);
|
|
241
|
-
|
|
242
|
-
if (!source) {
|
|
243
|
-
throw new MethodError(
|
|
244
|
-
"invalidResultReference",
|
|
245
|
-
`No ${methodName} result for ${resultOf}`
|
|
246
|
-
);
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
resolved[name] = evaluatePointer(source[1], path);
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
return resolved;
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
// ---------------------------------------------------------------- arguments
|
|
256
|
-
|
|
257
|
-
/**
|
|
258
|
-
* Adds an issue that answers the method with `type` instead of
|
|
259
|
-
* invalidArguments: the arguments are well formed, but ask for something
|
|
260
|
-
* this server does not do.
|
|
261
|
-
*/
|
|
262
|
-
function methodIssue(
|
|
263
|
-
context: z.RefinementCtx,
|
|
264
|
-
type: MethodErrorType,
|
|
265
|
-
message: string
|
|
266
|
-
) {
|
|
267
|
-
context.addIssue({ code: "custom", message, params: { methodError: type } });
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
/** The method error an issue asks for, from `methodIssue`. */
|
|
271
|
-
function issueMethodError(issue: Issue) {
|
|
272
|
-
if (issue.code !== "custom") return null;
|
|
273
|
-
const type = methodErrorTypes.safeParse(issue.params?.methodError);
|
|
274
|
-
|
|
275
|
-
return type.success ? type.data : null;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
/** A method's arguments, or the method error that answers them (RFC 8620 §3.6.2). */
|
|
279
|
-
function parseArguments<Schema extends z.ZodType>(
|
|
280
|
-
schema: Schema,
|
|
281
|
-
args: JsonObject
|
|
282
|
-
): z.output<Schema> {
|
|
283
|
-
const parsed = schema.safeParse(args);
|
|
284
|
-
|
|
285
|
-
if (parsed.success) return parsed.data;
|
|
286
|
-
const { issues } = parsed.error;
|
|
287
|
-
|
|
288
|
-
for (const issue of issues) {
|
|
289
|
-
const type = issueMethodError(issue);
|
|
290
|
-
|
|
291
|
-
if (type) throw new MethodError(type, issue.message);
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
throw new MethodError("invalidArguments", describeIssues(issues));
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
const accountId = z.string();
|
|
298
|
-
|
|
299
|
-
/** Ids of objects to fetch or change; more than a request may hold is requestTooLarge. */
|
|
300
|
-
const idList = z.array(z.string()).superRefine((ids, context) => {
|
|
301
|
-
if (ids.length > MAX_OBJECTS) {
|
|
302
|
-
methodIssue(context, "requestTooLarge", `At most ${MAX_OBJECTS} ids`);
|
|
303
|
-
}
|
|
304
|
-
});
|
|
305
|
-
|
|
306
|
-
const properties = z.array(z.string()).nullish();
|
|
307
|
-
|
|
308
|
-
/** RFC 8620 §1.4 UTCDate; an offset is accepted too. */
|
|
309
|
-
const utcDate = z.iso.datetime({ offset: true });
|
|
310
|
-
|
|
311
|
-
/** Objects to create or patches to apply, each checked on its own (SetError per id). */
|
|
312
|
-
const setObjects = z.record(z.string(), z.json()).nullish();
|
|
313
|
-
|
|
314
|
-
const changesArguments = z.object({ accountId, sinceState: z.string() });
|
|
315
|
-
|
|
316
|
-
/** A SetError for an object whose properties failed `issues` (RFC 8620 §5.3). */
|
|
317
|
-
function invalidProperties(
|
|
318
|
-
issues: readonly Issue[],
|
|
319
|
-
options: { topLevel?: boolean } = {}
|
|
320
|
-
) {
|
|
321
|
-
const names = issueProperties(issues, options);
|
|
322
|
-
|
|
323
|
-
for (const issue of issues) {
|
|
324
|
-
if (issue.code === "unrecognized_keys") names.push(...issue.keys);
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
return {
|
|
328
|
-
type: "invalidProperties",
|
|
329
|
-
properties: [...new Set(names)],
|
|
330
|
-
description: describeIssues(issues),
|
|
331
|
-
};
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
/** The `created`/`updated`/`not…` map of a /set response: null when empty. */
|
|
335
|
-
function setResult<Value extends Json>(entries: Map<string, Value>) {
|
|
336
|
-
return entries.size ? Object.fromEntries(entries) : null;
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
// ------------------------------------------------------------------ helpers
|
|
340
|
-
|
|
341
|
-
/** The id a creation id stands for. */
|
|
342
|
-
function createdId(state: RequestState, creationId: string) {
|
|
343
|
-
return state.createdIds.get(creationId);
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
function account(state: RequestState, id: string) {
|
|
347
|
-
const found = state.context.accounts.find((item) => item.id === id);
|
|
348
|
-
|
|
349
|
-
if (!found) throw new MethodError("accountNotFound");
|
|
350
|
-
|
|
351
|
-
return found;
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
function pick<Value extends Json>(
|
|
355
|
-
object: Record<string, Value>,
|
|
356
|
-
wanted: readonly string[] | null | undefined
|
|
357
|
-
) {
|
|
358
|
-
if (!wanted) return object;
|
|
359
|
-
|
|
360
|
-
return Object.fromEntries(
|
|
361
|
-
Object.entries(object).filter(
|
|
362
|
-
([key]) => key === "id" || wanted.includes(key)
|
|
363
|
-
)
|
|
364
|
-
);
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
/** We cannot list changes, only say whether anything changed. */
|
|
368
|
-
function changes(owner: JmapAccount, sinceState: string, state: string) {
|
|
369
|
-
if (sinceState !== state) throw new MethodError("cannotCalculateChanges");
|
|
370
|
-
|
|
371
|
-
return {
|
|
372
|
-
accountId: owner.id,
|
|
373
|
-
oldState: state,
|
|
374
|
-
newState: state,
|
|
375
|
-
hasMoreChanges: false,
|
|
376
|
-
created: [],
|
|
377
|
-
updated: [],
|
|
378
|
-
destroyed: [],
|
|
379
|
-
};
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
const addresses = (
|
|
383
|
-
list: { address: string; name?: string | null }[] | null | undefined
|
|
384
|
-
) =>
|
|
385
|
-
list?.length
|
|
386
|
-
? list.map((item) => ({ name: item.name || null, email: item.address }))
|
|
387
|
-
: null;
|
|
388
|
-
|
|
389
|
-
// ------------------------------------------------------------------ mailbox
|
|
390
|
-
|
|
391
|
-
function mailboxObject(row: JmapMailboxRow, canSend: boolean) {
|
|
392
|
-
return {
|
|
393
|
-
id: row.id,
|
|
394
|
-
name: row.name,
|
|
395
|
-
parentId: null,
|
|
396
|
-
role: row.role,
|
|
397
|
-
sortOrder: row.sortOrder,
|
|
398
|
-
totalEmails: row.totalEmails,
|
|
399
|
-
unreadEmails: row.unreadEmails,
|
|
400
|
-
totalThreads: row.totalThreads,
|
|
401
|
-
unreadThreads: row.unreadThreads,
|
|
402
|
-
myRights: {
|
|
403
|
-
mayReadItems: true,
|
|
404
|
-
mayAddItems: row.role !== "sent",
|
|
405
|
-
mayRemoveItems: true,
|
|
406
|
-
maySetSeen: true,
|
|
407
|
-
maySetKeywords: false,
|
|
408
|
-
mayCreateChild: false,
|
|
409
|
-
mayRename: false,
|
|
410
|
-
mayDelete: false,
|
|
411
|
-
maySubmit: canSend,
|
|
412
|
-
},
|
|
413
|
-
isSubscribed: true,
|
|
414
|
-
};
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
const mailboxGetArguments = z.object({
|
|
418
|
-
accountId,
|
|
419
|
-
ids: idList.nullish(),
|
|
420
|
-
properties,
|
|
421
|
-
});
|
|
422
|
-
|
|
423
|
-
async function mailboxGet(
|
|
424
|
-
state: RequestState,
|
|
425
|
-
args: z.output<typeof mailboxGetArguments>
|
|
426
|
-
) {
|
|
427
|
-
const owner = account(state, args.accountId);
|
|
428
|
-
|
|
429
|
-
const { state: mailboxState, mailboxes } = await mailboxStub(
|
|
430
|
-
state.context.env,
|
|
431
|
-
owner.id
|
|
432
|
-
).jmapMailboxes(state.context.user.id);
|
|
433
|
-
|
|
434
|
-
const ids = args.ids ?? mailboxes.map((row) => row.id);
|
|
435
|
-
const byId = new Map(mailboxes.map((row) => [row.id, row]));
|
|
436
|
-
|
|
437
|
-
return {
|
|
438
|
-
accountId: owner.id,
|
|
439
|
-
state: mailboxState,
|
|
440
|
-
list: ids.flatMap((id) => {
|
|
441
|
-
const row = byId.get(id);
|
|
442
|
-
|
|
443
|
-
return row
|
|
444
|
-
? [pick(mailboxObject(row, owner.canSend), args.properties)]
|
|
445
|
-
: [];
|
|
446
|
-
}),
|
|
447
|
-
notFound: ids.filter((id) => !byId.has(id)),
|
|
448
|
-
};
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
const mailboxQueryArguments = z.object({
|
|
452
|
-
accountId,
|
|
453
|
-
filter: z
|
|
454
|
-
.object({
|
|
455
|
-
/** null matches the mailboxes without a role. */
|
|
456
|
-
role: z.string().nullable().optional(),
|
|
457
|
-
name: z.string().optional(),
|
|
458
|
-
})
|
|
459
|
-
.nullish(),
|
|
460
|
-
});
|
|
461
|
-
|
|
462
|
-
async function mailboxQuery(
|
|
463
|
-
state: RequestState,
|
|
464
|
-
args: z.output<typeof mailboxQueryArguments>
|
|
465
|
-
) {
|
|
466
|
-
const owner = account(state, args.accountId);
|
|
467
|
-
|
|
468
|
-
const { state: mailboxState, mailboxes } = await mailboxStub(
|
|
469
|
-
state.context.env,
|
|
470
|
-
owner.id
|
|
471
|
-
).jmapMailboxes(state.context.user.id);
|
|
472
|
-
|
|
473
|
-
const role = args.filter?.role;
|
|
474
|
-
const name = args.filter?.name?.toLowerCase();
|
|
475
|
-
|
|
476
|
-
const ids = mailboxes.flatMap((row) =>
|
|
477
|
-
(role === undefined || row.role === role) &&
|
|
478
|
-
(name === undefined || row.name.toLowerCase().includes(name))
|
|
479
|
-
? [row.id]
|
|
480
|
-
: []
|
|
481
|
-
);
|
|
482
|
-
|
|
483
|
-
return {
|
|
484
|
-
accountId: owner.id,
|
|
485
|
-
queryState: mailboxState,
|
|
486
|
-
canCalculateChanges: false,
|
|
487
|
-
position: 0,
|
|
488
|
-
ids,
|
|
489
|
-
total: ids.length,
|
|
490
|
-
};
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
// -------------------------------------------------------------------- email
|
|
494
|
-
|
|
495
|
-
/** The FilterCondition properties (RFC 8621 §4.4.1) Email/query supports. */
|
|
496
|
-
const emailCondition = {
|
|
497
|
-
inMailbox: z.string().optional(),
|
|
498
|
-
inMailboxOtherThan: z.array(z.string()).optional(),
|
|
499
|
-
before: utcDate.transform((date) => Date.parse(date)).optional(),
|
|
500
|
-
after: utcDate.transform((date) => Date.parse(date)).optional(),
|
|
501
|
-
text: z.string().optional(),
|
|
502
|
-
from: z.string().optional(),
|
|
503
|
-
to: z.string().optional(),
|
|
504
|
-
subject: z.string().optional(),
|
|
505
|
-
hasKeyword: z.string().optional(),
|
|
506
|
-
notKeyword: z.string().optional(),
|
|
507
|
-
hasAttachment: z.boolean().optional(),
|
|
508
|
-
};
|
|
509
|
-
|
|
510
|
-
const emailConditionKeys = Object.keys(emailCondition);
|
|
511
|
-
|
|
512
|
-
/**
|
|
513
|
-
* An Email/query filter, flattened into one condition. Other conditions,
|
|
514
|
-
* operators than AND, and keywords than $seen are valid JMAP the store
|
|
515
|
-
* cannot answer: unsupportedFilter.
|
|
516
|
-
*/
|
|
517
|
-
const emailFilter: z.ZodType<JmapEmailFilter> = z.lazy(() =>
|
|
518
|
-
z
|
|
519
|
-
.record(z.string(), z.unknown())
|
|
520
|
-
.superRefine((filter, context) => {
|
|
521
|
-
const allowed = Object.hasOwn(filter, "operator")
|
|
522
|
-
? ["operator", "conditions"]
|
|
523
|
-
: emailConditionKeys;
|
|
524
|
-
|
|
525
|
-
const unsupported = Object.keys(filter).filter(
|
|
526
|
-
(key) => !allowed.includes(key)
|
|
527
|
-
);
|
|
528
|
-
|
|
529
|
-
if (unsupported.length) {
|
|
530
|
-
methodIssue(
|
|
531
|
-
context,
|
|
532
|
-
"unsupportedFilter",
|
|
533
|
-
`Unsupported filter: ${unsupported.join(", ")}`
|
|
534
|
-
);
|
|
535
|
-
}
|
|
536
|
-
})
|
|
537
|
-
.pipe(
|
|
538
|
-
z.object({
|
|
539
|
-
operator: z.enum(["AND", "OR", "NOT"]).optional(),
|
|
540
|
-
conditions: z.array(emailFilter).optional(),
|
|
541
|
-
...emailCondition,
|
|
542
|
-
})
|
|
543
|
-
)
|
|
544
|
-
.superRefine((filter, context) => {
|
|
545
|
-
if (filter.operator && filter.operator !== "AND") {
|
|
546
|
-
methodIssue(
|
|
547
|
-
context,
|
|
548
|
-
"unsupportedFilter",
|
|
549
|
-
"Only AND filters are supported"
|
|
550
|
-
);
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
if (filter.operator && !filter.conditions) {
|
|
554
|
-
context.addIssue({
|
|
555
|
-
code: "custom",
|
|
556
|
-
path: ["conditions"],
|
|
557
|
-
message: "A filter operator needs conditions",
|
|
558
|
-
});
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
for (const keyword of [filter.hasKeyword, filter.notKeyword]) {
|
|
562
|
-
if (keyword !== undefined && keyword !== "$seen") {
|
|
563
|
-
methodIssue(
|
|
564
|
-
context,
|
|
565
|
-
"unsupportedFilter",
|
|
566
|
-
"Only the $seen keyword is supported"
|
|
567
|
-
);
|
|
568
|
-
}
|
|
569
|
-
}
|
|
570
|
-
})
|
|
571
|
-
.transform(({ operator, conditions, ...condition }) => {
|
|
572
|
-
if (!operator) return condition;
|
|
573
|
-
// AND: every condition holds.
|
|
574
|
-
const merged: JmapEmailFilter = {};
|
|
575
|
-
|
|
576
|
-
for (const part of conditions ?? []) Object.assign(merged, part);
|
|
577
|
-
|
|
578
|
-
return merged;
|
|
579
|
-
})
|
|
580
|
-
);
|
|
581
|
-
|
|
582
|
-
const emailComparator = z
|
|
583
|
-
.object({
|
|
584
|
-
property: z.string(),
|
|
585
|
-
isAscending: z.boolean().optional(),
|
|
586
|
-
collation: z.string().optional(),
|
|
587
|
-
})
|
|
588
|
-
.superRefine((comparator, context) => {
|
|
589
|
-
if (!["receivedAt", "sentAt"].includes(comparator.property)) {
|
|
590
|
-
methodIssue(
|
|
591
|
-
context,
|
|
592
|
-
"unsupportedSort",
|
|
593
|
-
"Emails sort by receivedAt or sentAt"
|
|
594
|
-
);
|
|
595
|
-
}
|
|
596
|
-
});
|
|
597
|
-
|
|
598
|
-
const emailQueryArguments = z.object({
|
|
599
|
-
accountId,
|
|
600
|
-
filter: emailFilter.nullish(),
|
|
601
|
-
sort: z.array(emailComparator).nullish(),
|
|
602
|
-
position: z.number().int().nullish(),
|
|
603
|
-
limit: z.number().int().min(0).nullish(),
|
|
604
|
-
collapseThreads: z.boolean().nullish(),
|
|
605
|
-
});
|
|
606
|
-
|
|
607
|
-
async function emailQuery(
|
|
608
|
-
state: RequestState,
|
|
609
|
-
args: z.output<typeof emailQueryArguments>
|
|
610
|
-
) {
|
|
611
|
-
const owner = account(state, args.accountId);
|
|
612
|
-
const ascending = args.sort?.[0]?.isAscending === true;
|
|
613
|
-
// Negative positions (from the end) are not supported; they start at the top.
|
|
614
|
-
const position = Math.max(0, args.position ?? 0);
|
|
615
|
-
const limit = Math.min(MAX_OBJECTS, args.limit ?? 100);
|
|
616
|
-
|
|
617
|
-
const result = await mailboxStub(state.context.env, owner.id).jmapQueryEmails(
|
|
618
|
-
{
|
|
619
|
-
userId: state.context.user.id,
|
|
620
|
-
filter: args.filter ?? {},
|
|
621
|
-
ascending,
|
|
622
|
-
position,
|
|
623
|
-
limit,
|
|
624
|
-
collapseThreads: args.collapseThreads === true,
|
|
625
|
-
}
|
|
626
|
-
);
|
|
627
|
-
|
|
628
|
-
return {
|
|
629
|
-
accountId: owner.id,
|
|
630
|
-
queryState: result.state,
|
|
631
|
-
canCalculateChanges: false,
|
|
632
|
-
position,
|
|
633
|
-
ids: result.ids,
|
|
634
|
-
total: result.total,
|
|
635
|
-
limit,
|
|
636
|
-
};
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
const defaultEmailProperties = [
|
|
640
|
-
"id",
|
|
641
|
-
"blobId",
|
|
642
|
-
"threadId",
|
|
643
|
-
"mailboxIds",
|
|
644
|
-
"keywords",
|
|
645
|
-
"size",
|
|
646
|
-
"receivedAt",
|
|
647
|
-
"messageId",
|
|
648
|
-
"inReplyTo",
|
|
649
|
-
"references",
|
|
650
|
-
"sender",
|
|
651
|
-
"from",
|
|
652
|
-
"to",
|
|
653
|
-
"cc",
|
|
654
|
-
"bcc",
|
|
655
|
-
"replyTo",
|
|
656
|
-
"subject",
|
|
657
|
-
"sentAt",
|
|
658
|
-
"hasAttachment",
|
|
659
|
-
"preview",
|
|
660
|
-
"bodyValues",
|
|
661
|
-
"textBody",
|
|
662
|
-
"htmlBody",
|
|
663
|
-
"attachments",
|
|
664
|
-
];
|
|
665
|
-
|
|
666
|
-
const emailGetArguments = z.object({
|
|
667
|
-
accountId,
|
|
668
|
-
ids: idList.nullish(),
|
|
669
|
-
properties,
|
|
670
|
-
fetchTextBodyValues: z.boolean().nullish(),
|
|
671
|
-
fetchHTMLBodyValues: z.boolean().nullish(),
|
|
672
|
-
fetchAllBodyValues: z.boolean().nullish(),
|
|
673
|
-
maxBodyValueBytes: z.number().int().min(0).nullish(),
|
|
674
|
-
});
|
|
675
|
-
|
|
676
|
-
type EmailGetArguments = z.output<typeof emailGetArguments>;
|
|
677
|
-
|
|
678
|
-
async function emailObject(
|
|
679
|
-
env: Env,
|
|
680
|
-
row: { email: Email; mailboxId: string; seen: boolean },
|
|
681
|
-
args: EmailGetArguments
|
|
682
|
-
) {
|
|
683
|
-
const { email } = row;
|
|
684
|
-
const raw = `raw~${email.id}`;
|
|
685
|
-
|
|
686
|
-
const textBody = [
|
|
687
|
-
{
|
|
688
|
-
partId: "text",
|
|
689
|
-
blobId: raw,
|
|
690
|
-
size: email.bodyText?.length ?? 0,
|
|
691
|
-
name: null,
|
|
692
|
-
type: "text/plain",
|
|
693
|
-
charset: "utf-8",
|
|
694
|
-
disposition: null,
|
|
695
|
-
cid: null,
|
|
696
|
-
},
|
|
697
|
-
];
|
|
698
|
-
|
|
699
|
-
const htmlBody = email.bodyHtmlR2Key
|
|
700
|
-
? [
|
|
701
|
-
{
|
|
702
|
-
partId: "html",
|
|
703
|
-
blobId: raw,
|
|
704
|
-
size: 0,
|
|
705
|
-
name: null,
|
|
706
|
-
type: "text/html",
|
|
707
|
-
charset: "utf-8",
|
|
708
|
-
disposition: null,
|
|
709
|
-
cid: null,
|
|
710
|
-
},
|
|
711
|
-
]
|
|
712
|
-
: textBody;
|
|
713
|
-
|
|
714
|
-
const attachments = email.attachmentsJson.map((attachment) => ({
|
|
715
|
-
partId: `att-${attachment.id}`,
|
|
716
|
-
blobId: `att~${email.id}~${attachment.id}`,
|
|
717
|
-
size: attachment.size,
|
|
718
|
-
name: attachment.filename,
|
|
719
|
-
type: attachment.contentType,
|
|
720
|
-
charset: null,
|
|
721
|
-
disposition: attachment.disposition,
|
|
722
|
-
cid: attachment.contentId,
|
|
723
|
-
}));
|
|
724
|
-
|
|
725
|
-
const wanted = args.properties ?? defaultEmailProperties;
|
|
726
|
-
const maxBytes = args.maxBodyValueBytes ?? 0;
|
|
727
|
-
|
|
728
|
-
const bodyValue = (value: string) => ({
|
|
729
|
-
value:
|
|
730
|
-
maxBytes && value.length > maxBytes ? value.slice(0, maxBytes) : value,
|
|
731
|
-
isEncodingProblem: false,
|
|
732
|
-
isTruncated: Boolean(maxBytes && value.length > maxBytes),
|
|
733
|
-
});
|
|
734
|
-
|
|
735
|
-
const bodyValues: Record<string, ReturnType<typeof bodyValue>> = {};
|
|
736
|
-
|
|
737
|
-
if (wanted.includes("bodyValues")) {
|
|
738
|
-
const wantText =
|
|
739
|
-
args.fetchTextBodyValues === true || args.fetchAllBodyValues === true;
|
|
740
|
-
|
|
741
|
-
const wantHtml =
|
|
742
|
-
args.fetchHTMLBodyValues === true || args.fetchAllBodyValues === true;
|
|
743
|
-
|
|
744
|
-
if (wantText || (wantHtml && !email.bodyHtmlR2Key)) {
|
|
745
|
-
bodyValues.text = bodyValue(email.bodyText ?? "");
|
|
746
|
-
}
|
|
747
|
-
|
|
748
|
-
if (wantHtml && email.bodyHtmlR2Key) {
|
|
749
|
-
const object = await env.MAIL_STORAGE.get(email.bodyHtmlR2Key);
|
|
750
|
-
bodyValues.html = bodyValue(object ? await object.text() : "");
|
|
751
|
-
}
|
|
752
|
-
}
|
|
753
|
-
|
|
754
|
-
const timestamp = email.timelineAt.toISOString();
|
|
755
|
-
const keywords: Record<string, true> = row.seen ? { $seen: true } : {};
|
|
756
|
-
|
|
757
|
-
const object = {
|
|
758
|
-
id: email.id,
|
|
759
|
-
blobId: raw,
|
|
760
|
-
threadId: email.conversationId,
|
|
761
|
-
mailboxIds: { [row.mailboxId]: true },
|
|
762
|
-
keywords,
|
|
763
|
-
size:
|
|
764
|
-
(email.bodyText?.length ?? 0) +
|
|
765
|
-
email.attachmentsJson.reduce(
|
|
766
|
-
(total, attachment) => total + attachment.size,
|
|
767
|
-
0
|
|
768
|
-
),
|
|
769
|
-
receivedAt: timestamp,
|
|
770
|
-
messageId: email.messageIdHeader
|
|
771
|
-
? [email.messageIdHeader.replaceAll(/^<|>$/gu, "")]
|
|
772
|
-
: null,
|
|
773
|
-
inReplyTo: email.inReplyToJson?.length ? email.inReplyToJson : null,
|
|
774
|
-
references: email.referencesJson?.length ? email.referencesJson : null,
|
|
775
|
-
sender: null,
|
|
776
|
-
from: addresses(email.fromJson),
|
|
777
|
-
to: addresses(email.toJson),
|
|
778
|
-
cc: addresses(email.ccJson),
|
|
779
|
-
bcc: addresses(email.bccJson),
|
|
780
|
-
replyTo: addresses(email.replyToJson),
|
|
781
|
-
subject: email.subject,
|
|
782
|
-
sentAt: timestamp,
|
|
783
|
-
hasAttachment: attachments.some(
|
|
784
|
-
(attachment) => attachment.disposition === "attachment"
|
|
785
|
-
),
|
|
786
|
-
preview: email.preview,
|
|
787
|
-
bodyValues,
|
|
788
|
-
textBody,
|
|
789
|
-
htmlBody,
|
|
790
|
-
attachments,
|
|
791
|
-
bodyStructure: {
|
|
792
|
-
partId: null,
|
|
793
|
-
type: "multipart/mixed",
|
|
794
|
-
subParts: [...htmlBody, ...attachments],
|
|
795
|
-
},
|
|
796
|
-
};
|
|
797
|
-
|
|
798
|
-
return pick(object, wanted);
|
|
799
|
-
}
|
|
800
|
-
|
|
801
|
-
async function emailGet(state: RequestState, args: EmailGetArguments) {
|
|
802
|
-
const owner = account(state, args.accountId);
|
|
803
|
-
|
|
804
|
-
if (!args.ids) {
|
|
805
|
-
throw new MethodError("requestTooLarge", "Ask for emails by id");
|
|
806
|
-
}
|
|
807
|
-
|
|
808
|
-
const { ids } = args;
|
|
809
|
-
|
|
810
|
-
const result = await mailboxStub(state.context.env, owner.id).jmapEmails(
|
|
811
|
-
state.context.user.id,
|
|
812
|
-
ids
|
|
813
|
-
);
|
|
814
|
-
|
|
815
|
-
const found = new Set(result.emails.map((row) => row.email.id));
|
|
816
|
-
|
|
817
|
-
return {
|
|
818
|
-
accountId: owner.id,
|
|
819
|
-
state: result.state,
|
|
820
|
-
list: await Promise.all(
|
|
821
|
-
result.emails.map((row) => emailObject(state.context.env, row, args))
|
|
822
|
-
),
|
|
823
|
-
notFound: ids.filter((id) => !found.has(id)),
|
|
824
|
-
};
|
|
825
|
-
}
|
|
826
|
-
|
|
827
|
-
/** A patch key is a JSON Pointer into the email (RFC 8620 §5.3). */
|
|
828
|
-
function patchPath(key: string) {
|
|
829
|
-
return key
|
|
830
|
-
.split("/")
|
|
831
|
-
.map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
|
|
832
|
-
}
|
|
833
|
-
|
|
834
|
-
/** Keywords and mailboxIds map their names to true (RFC 8621 §4.1.1). */
|
|
835
|
-
const trueSet = z.record(z.string(), z.literal(true));
|
|
836
|
-
|
|
837
|
-
/** One entry of a set: true adds it, null removes it. */
|
|
838
|
-
const setMember = z.literal(true).nullable();
|
|
839
|
-
|
|
840
|
-
/**
|
|
841
|
-
* An Email/set update patch: the $seen keyword and the one mailbox an email
|
|
842
|
-
* is in are all that change.
|
|
843
|
-
*/
|
|
844
|
-
const emailPatch = z
|
|
845
|
-
.record(z.string(), z.json())
|
|
846
|
-
.transform((patch, context) => {
|
|
847
|
-
let seen: boolean | undefined;
|
|
848
|
-
let target: string | undefined;
|
|
849
|
-
|
|
850
|
-
for (const [key, value] of Object.entries(patch)) {
|
|
851
|
-
const path = patchPath(key);
|
|
852
|
-
|
|
853
|
-
const fail = (message: string) =>
|
|
854
|
-
context.addIssue({ code: "custom", path, message, input: value });
|
|
855
|
-
|
|
856
|
-
if (key === "keywords") {
|
|
857
|
-
const keywords = trueSet.safeParse(value);
|
|
858
|
-
|
|
859
|
-
if (!keywords.success) fail("keywords map keywords to true");
|
|
860
|
-
else if (Object.keys(keywords.data).some((name) => name !== "$seen")) {
|
|
861
|
-
fail("Only the $seen keyword is stored");
|
|
862
|
-
} else seen = Object.hasOwn(keywords.data, "$seen");
|
|
863
|
-
} else if (key === "keywords/$seen") {
|
|
864
|
-
const member = setMember.safeParse(value);
|
|
865
|
-
|
|
866
|
-
if (member.success) seen = member.data === true;
|
|
867
|
-
else fail("A keyword is set to true or null");
|
|
868
|
-
} else if (key.startsWith("keywords/")) {
|
|
869
|
-
fail("Only the $seen keyword is stored");
|
|
870
|
-
} else if (key === "mailboxIds") {
|
|
871
|
-
const mailboxIds = trueSet.safeParse(value);
|
|
872
|
-
const ids = mailboxIds.success ? Object.keys(mailboxIds.data) : [];
|
|
873
|
-
|
|
874
|
-
if (ids.length === 1) [target] = ids;
|
|
875
|
-
else fail("An email is in exactly one mailbox");
|
|
876
|
-
} else if (key.startsWith("mailboxIds/")) {
|
|
877
|
-
const member = setMember.safeParse(value);
|
|
878
|
-
|
|
879
|
-
if (!member.success) fail("A mailbox is set to true or null");
|
|
880
|
-
else if (member.data) target = key.slice("mailboxIds/".length);
|
|
881
|
-
} else {
|
|
882
|
-
fail(`${key} cannot be changed`);
|
|
883
|
-
}
|
|
884
|
-
}
|
|
885
|
-
|
|
886
|
-
return { seen, target };
|
|
887
|
-
});
|
|
888
|
-
|
|
889
|
-
const draftAddress = z.object({
|
|
890
|
-
name: z.string().nullish(),
|
|
891
|
-
email: z.string(),
|
|
892
|
-
});
|
|
893
|
-
|
|
894
|
-
const draftAddresses = z
|
|
895
|
-
.array(draftAddress)
|
|
896
|
-
.nullish()
|
|
897
|
-
.transform((list) => list?.map((item) => item.email) ?? []);
|
|
898
|
-
|
|
899
|
-
/** A body part of a draft names its value in bodyValues. */
|
|
900
|
-
const draftBodyPart = z.array(z.object({ partId: z.string() })).nullish();
|
|
901
|
-
|
|
902
|
-
const draftAttachment = z
|
|
903
|
-
.object({
|
|
904
|
-
blobId: z
|
|
905
|
-
.string()
|
|
906
|
-
.regex(UPLOAD_BLOB, "Attachments must be blobs uploaded to this account")
|
|
907
|
-
.transform((blobId) => blobId.replace(UPLOAD_BLOB, "$1")),
|
|
908
|
-
name: z.string().nullish(),
|
|
909
|
-
type: z.string().nullish(),
|
|
910
|
-
disposition: z.string().nullish(),
|
|
911
|
-
cid: z
|
|
912
|
-
.string()
|
|
913
|
-
.nullish()
|
|
914
|
-
.transform((cid) => cid?.replaceAll(/^<|>$/gu, "") || undefined),
|
|
915
|
-
})
|
|
916
|
-
.superRefine((part, context) => {
|
|
917
|
-
if (part.disposition === "inline" && !part.cid) {
|
|
918
|
-
context.addIssue({
|
|
919
|
-
code: "custom",
|
|
920
|
-
path: ["cid"],
|
|
921
|
-
message: "Inline attachments need a cid",
|
|
922
|
-
});
|
|
923
|
-
}
|
|
924
|
-
})
|
|
925
|
-
.transform((part): DraftAttachment => ({
|
|
926
|
-
uploadId: part.blobId,
|
|
927
|
-
name: part.name ?? "attachment",
|
|
928
|
-
type: part.type ?? "application/octet-stream",
|
|
929
|
-
disposition: part.disposition === "inline" ? "inline" : "attachment",
|
|
930
|
-
contentId: part.disposition === "inline" ? part.cid : undefined,
|
|
931
|
-
}));
|
|
932
|
-
|
|
933
|
-
/** An Email/set create object (RFC 8621 §4.6): a message to send in this request. */
|
|
934
|
-
const draftSchema = z
|
|
935
|
-
.object({
|
|
936
|
-
to: draftAddresses,
|
|
937
|
-
cc: draftAddresses,
|
|
938
|
-
bcc: draftAddresses,
|
|
939
|
-
subject: z.string().nullish(),
|
|
940
|
-
bodyValues: z.record(z.string(), z.object({ value: z.string() })).nullish(),
|
|
941
|
-
textBody: draftBodyPart,
|
|
942
|
-
htmlBody: draftBodyPart,
|
|
943
|
-
attachments: z
|
|
944
|
-
.array(draftAttachment)
|
|
945
|
-
.max(
|
|
946
|
-
MAX_COMPOSER_ATTACHMENT_COUNT,
|
|
947
|
-
`At most ${MAX_COMPOSER_ATTACHMENT_COUNT} attachments per message`
|
|
948
|
-
)
|
|
949
|
-
.nullish()
|
|
950
|
-
.transform((list) => list ?? [])
|
|
951
|
-
.refine(
|
|
952
|
-
(list) =>
|
|
953
|
-
new Set(list.map((item) => item.uploadId)).size === list.length,
|
|
954
|
-
"Each blob can be attached once"
|
|
955
|
-
),
|
|
956
|
-
})
|
|
957
|
-
.transform((input, context) => {
|
|
958
|
-
const values = new Map(Object.entries(input.bodyValues ?? {}));
|
|
959
|
-
|
|
960
|
-
const partText = (parts: { partId: string }[] | null | undefined) => {
|
|
961
|
-
const [first] = parts ?? [];
|
|
962
|
-
|
|
963
|
-
return first ? values.get(first.partId)?.value : undefined;
|
|
964
|
-
};
|
|
965
|
-
|
|
966
|
-
const bodyText = partText(input.textBody);
|
|
967
|
-
const bodyHtml = partText(input.htmlBody);
|
|
968
|
-
|
|
969
|
-
if (bodyText === undefined && bodyHtml === undefined) {
|
|
970
|
-
context.addIssue({
|
|
971
|
-
code: "custom",
|
|
972
|
-
path: ["textBody"],
|
|
973
|
-
message: "Give the message a textBody or htmlBody with bodyValues",
|
|
974
|
-
});
|
|
975
|
-
}
|
|
976
|
-
|
|
977
|
-
return {
|
|
978
|
-
to: input.to,
|
|
979
|
-
cc: input.cc,
|
|
980
|
-
bcc: input.bcc,
|
|
981
|
-
subject: input.subject ?? "",
|
|
982
|
-
bodyText: bodyText ?? "",
|
|
983
|
-
bodyHtml,
|
|
984
|
-
attachments: input.attachments,
|
|
985
|
-
};
|
|
986
|
-
});
|
|
987
|
-
|
|
988
|
-
const emailSetArguments = z.object({
|
|
989
|
-
accountId,
|
|
990
|
-
ifInState: z.string().nullish(),
|
|
991
|
-
create: setObjects,
|
|
992
|
-
update: setObjects,
|
|
993
|
-
destroy: idList.nullish(),
|
|
994
|
-
});
|
|
995
|
-
|
|
996
|
-
type EmailSetArguments = z.output<typeof emailSetArguments>;
|
|
997
|
-
|
|
998
|
-
/** Email/set creates drafts only to send them; changing or destroying mail is organizing. */
|
|
999
|
-
function emailSetScopes(args: EmailSetArguments) {
|
|
1000
|
-
const scopes: string[] = [];
|
|
1001
|
-
|
|
1002
|
-
if (args.create && Object.keys(args.create).length) {
|
|
1003
|
-
scopes.push(MAIL_SEND_SCOPE);
|
|
1004
|
-
}
|
|
1005
|
-
|
|
1006
|
-
if (
|
|
1007
|
-
(args.update && Object.keys(args.update).length) ||
|
|
1008
|
-
args.destroy?.length
|
|
1009
|
-
) {
|
|
1010
|
-
scopes.push(MAIL_ORGANIZE_SCOPE);
|
|
1011
|
-
}
|
|
1012
|
-
|
|
1013
|
-
return scopes;
|
|
1014
|
-
}
|
|
1015
|
-
|
|
1016
|
-
async function emailSet(state: RequestState, args: EmailSetArguments) {
|
|
1017
|
-
const owner = account(state, args.accountId);
|
|
1018
|
-
const stub = mailboxStub(state.context.env, owner.id);
|
|
1019
|
-
const oldState = await stub.jmapState();
|
|
1020
|
-
|
|
1021
|
-
if (args.ifInState != null && args.ifInState !== oldState) {
|
|
1022
|
-
throw new MethodError("stateMismatch");
|
|
1023
|
-
}
|
|
1024
|
-
|
|
1025
|
-
const created = new Map<string, JsonObject>();
|
|
1026
|
-
const notCreated = new Map<string, JsonObject>();
|
|
1027
|
-
|
|
1028
|
-
const drafts = Object.entries(args.create ?? {}).flatMap(
|
|
1029
|
-
([creationId, input]) => {
|
|
1030
|
-
const parsed = draftSchema.safeParse(input);
|
|
1031
|
-
|
|
1032
|
-
if (!parsed.success) {
|
|
1033
|
-
notCreated.set(
|
|
1034
|
-
creationId,
|
|
1035
|
-
invalidProperties(parsed.error.issues, { topLevel: true })
|
|
1036
|
-
);
|
|
1037
|
-
|
|
1038
|
-
return [];
|
|
1039
|
-
}
|
|
1040
|
-
|
|
1041
|
-
const { attachments, ...message } = parsed.data;
|
|
1042
|
-
|
|
1043
|
-
// The rules the mail app's composer follows: valid, normalized and
|
|
1044
|
-
// deduplicated recipients within the limits, a body, content ids.
|
|
1045
|
-
const compose = composeSchema.safeParse({
|
|
1046
|
-
...message,
|
|
1047
|
-
requestId: crypto.randomUUID(),
|
|
1048
|
-
mailboxId: owner.id,
|
|
1049
|
-
attachments: attachments.map((attachment) => ({
|
|
1050
|
-
uploadId: attachment.uploadId,
|
|
1051
|
-
disposition: attachment.disposition,
|
|
1052
|
-
contentId: attachment.contentId,
|
|
1053
|
-
})),
|
|
1054
|
-
});
|
|
1055
|
-
|
|
1056
|
-
if (!compose.success) {
|
|
1057
|
-
notCreated.set(
|
|
1058
|
-
creationId,
|
|
1059
|
-
invalidProperties(compose.error.issues.map(draftIssue), {
|
|
1060
|
-
topLevel: true,
|
|
1061
|
-
})
|
|
1062
|
-
);
|
|
1063
|
-
|
|
1064
|
-
return [];
|
|
1065
|
-
}
|
|
1066
|
-
|
|
1067
|
-
return [
|
|
1068
|
-
{
|
|
1069
|
-
creationId,
|
|
1070
|
-
draft: { accountId: owner.id, compose: compose.data, attachments },
|
|
1071
|
-
},
|
|
1072
|
-
];
|
|
1073
|
-
}
|
|
1074
|
-
);
|
|
1075
|
-
|
|
1076
|
-
const missingBlobs = await Promise.all(
|
|
1077
|
-
drafts.map(async ({ draft }) => {
|
|
1078
|
-
try {
|
|
1079
|
-
// The name and type come with the email, after the bytes were uploaded.
|
|
1080
|
-
await Promise.all(
|
|
1081
|
-
draft.attachments.map((attachment) =>
|
|
1082
|
-
describeComposerUpload({
|
|
1083
|
-
env: state.context.env,
|
|
1084
|
-
mailboxId: owner.id,
|
|
1085
|
-
userId: state.context.user.id,
|
|
1086
|
-
uploadId: attachment.uploadId,
|
|
1087
|
-
filename: attachment.name,
|
|
1088
|
-
contentType: attachment.type,
|
|
1089
|
-
})
|
|
1090
|
-
)
|
|
1091
|
-
);
|
|
1092
|
-
|
|
1093
|
-
return null;
|
|
1094
|
-
} catch (error) {
|
|
1095
|
-
if (!(error instanceof UploadValidationError)) throw error;
|
|
1096
|
-
|
|
1097
|
-
return error.message;
|
|
1098
|
-
}
|
|
1099
|
-
})
|
|
1100
|
-
);
|
|
1101
|
-
|
|
1102
|
-
for (const [index, { creationId, draft }] of drafts.entries()) {
|
|
1103
|
-
const missing = missingBlobs[index];
|
|
1104
|
-
|
|
1105
|
-
if (missing) {
|
|
1106
|
-
notCreated.set(creationId, {
|
|
1107
|
-
type: "blobNotFound",
|
|
1108
|
-
description: missing,
|
|
1109
|
-
});
|
|
1110
|
-
continue;
|
|
1111
|
-
}
|
|
1112
|
-
|
|
1113
|
-
// Drafts are not stored: one is sent by EmailSubmission/set in the same request.
|
|
1114
|
-
const id = `draft-${crypto.randomUUID()}`;
|
|
1115
|
-
state.drafts.set(id, draft);
|
|
1116
|
-
state.createdIds.set(creationId, id);
|
|
1117
|
-
created.set(creationId, {
|
|
1118
|
-
id,
|
|
1119
|
-
blobId: `draft~${id}`,
|
|
1120
|
-
threadId: id,
|
|
1121
|
-
size: draft.compose.bodyText.length,
|
|
1122
|
-
});
|
|
1123
|
-
}
|
|
1124
|
-
|
|
1125
|
-
const updated = new Map<string, null>();
|
|
1126
|
-
const notUpdated = new Map<string, JsonObject>();
|
|
1127
|
-
const reads: [string, boolean][] = [];
|
|
1128
|
-
const moves = new Map<string, string[]>();
|
|
1129
|
-
|
|
1130
|
-
for (const [id, patch] of Object.entries(args.update ?? {})) {
|
|
1131
|
-
const change = emailPatch.safeParse(patch);
|
|
1132
|
-
|
|
1133
|
-
if (!change.success) {
|
|
1134
|
-
notUpdated.set(
|
|
1135
|
-
id,
|
|
1136
|
-
change.error.issues.some((issue) => issue.path.length === 0)
|
|
1137
|
-
? { type: "invalidPatch", description: "A patch is an object" }
|
|
1138
|
-
: invalidProperties(change.error.issues)
|
|
1139
|
-
);
|
|
1140
|
-
continue;
|
|
1141
|
-
}
|
|
1142
|
-
|
|
1143
|
-
const { seen, target } = change.data;
|
|
1144
|
-
|
|
1145
|
-
if (seen !== undefined) reads.push([id, seen]);
|
|
1146
|
-
|
|
1147
|
-
if (target) moves.set(target, [...(moves.get(target) ?? []), id]);
|
|
1148
|
-
updated.set(id, null);
|
|
1149
|
-
}
|
|
1150
|
-
|
|
1151
|
-
const readResults = await Promise.all(
|
|
1152
|
-
reads.map(([id, seen]) =>
|
|
1153
|
-
stub.setMessageRead(state.context.user.id, id, seen)
|
|
1154
|
-
)
|
|
1155
|
-
);
|
|
1156
|
-
|
|
1157
|
-
for (const [index, [id]] of reads.entries()) {
|
|
1158
|
-
if (!readResults[index]) {
|
|
1159
|
-
updated.delete(id);
|
|
1160
|
-
notUpdated.set(id, { type: "notFound" });
|
|
1161
|
-
}
|
|
1162
|
-
}
|
|
1163
|
-
|
|
1164
|
-
const moveTargets = [...moves];
|
|
1165
|
-
|
|
1166
|
-
const moved = await Promise.all(
|
|
1167
|
-
moveTargets.map(([target, ids]) => stub.jmapMoveEmails(ids, target))
|
|
1168
|
-
);
|
|
1169
|
-
|
|
1170
|
-
for (const [index, [target, ids]] of moveTargets.entries()) {
|
|
1171
|
-
if (moved[index]) continue;
|
|
1172
|
-
|
|
1173
|
-
for (const id of ids) {
|
|
1174
|
-
updated.delete(id);
|
|
1175
|
-
notUpdated.set(id, {
|
|
1176
|
-
type: "invalidProperties",
|
|
1177
|
-
properties: ["mailboxIds"],
|
|
1178
|
-
description: `Emails cannot be moved to ${target}`,
|
|
1179
|
-
});
|
|
1180
|
-
}
|
|
1181
|
-
}
|
|
1182
|
-
|
|
1183
|
-
const destroyed: string[] = [];
|
|
1184
|
-
const notDestroyed = new Map<string, JsonObject>();
|
|
1185
|
-
const destroyIds = args.destroy ?? [];
|
|
1186
|
-
|
|
1187
|
-
if (destroyIds.length) {
|
|
1188
|
-
const { emails } = await stub.jmapEmails(state.context.user.id, destroyIds);
|
|
1189
|
-
const inTrash = emails.filter((row) => row.mailboxId === "trash");
|
|
1190
|
-
const elsewhere = emails.filter((row) => row.mailboxId !== "trash");
|
|
1191
|
-
|
|
1192
|
-
// Mail goes to Trash first; destroying it there deletes its conversation.
|
|
1193
|
-
if (elsewhere.length) {
|
|
1194
|
-
await stub.jmapMoveEmails(
|
|
1195
|
-
elsewhere.map((row) => row.email.id),
|
|
1196
|
-
"trash"
|
|
1197
|
-
);
|
|
1198
|
-
}
|
|
1199
|
-
|
|
1200
|
-
if (inTrash.length) {
|
|
1201
|
-
await stub.permanentlyDeleteConversations([
|
|
1202
|
-
...new Set(inTrash.map((row) => row.email.conversationId)),
|
|
1203
|
-
]);
|
|
1204
|
-
}
|
|
1205
|
-
|
|
1206
|
-
const found = new Set(emails.map((row) => row.email.id));
|
|
1207
|
-
|
|
1208
|
-
for (const id of destroyIds) {
|
|
1209
|
-
if (found.has(id)) destroyed.push(id);
|
|
1210
|
-
else notDestroyed.set(id, { type: "notFound" });
|
|
1211
|
-
}
|
|
1212
|
-
}
|
|
1213
|
-
|
|
1214
|
-
return {
|
|
1215
|
-
accountId: owner.id,
|
|
1216
|
-
oldState,
|
|
1217
|
-
newState: await stub.jmapState(),
|
|
1218
|
-
created: setResult(created),
|
|
1219
|
-
updated: setResult(updated),
|
|
1220
|
-
destroyed: destroyed.length ? destroyed : null,
|
|
1221
|
-
notCreated: setResult(notCreated),
|
|
1222
|
-
notUpdated: setResult(notUpdated),
|
|
1223
|
-
notDestroyed: setResult(notDestroyed),
|
|
1224
|
-
};
|
|
1225
|
-
}
|
|
1226
|
-
|
|
1227
|
-
// --------------------------------------------------- threads and identities
|
|
1228
|
-
|
|
1229
|
-
const threadGetArguments = z.object({ accountId, ids: idList });
|
|
1230
|
-
|
|
1231
|
-
async function threadGet(
|
|
1232
|
-
state: RequestState,
|
|
1233
|
-
args: z.output<typeof threadGetArguments>
|
|
1234
|
-
) {
|
|
1235
|
-
const owner = account(state, args.accountId);
|
|
1236
|
-
|
|
1237
|
-
const result = await mailboxStub(state.context.env, owner.id).jmapThreads(
|
|
1238
|
-
args.ids
|
|
1239
|
-
);
|
|
1240
|
-
|
|
1241
|
-
const threads = new Map(
|
|
1242
|
-
result.threads.map((thread) => [thread.id, thread.emailIds])
|
|
1243
|
-
);
|
|
1244
|
-
|
|
1245
|
-
return {
|
|
1246
|
-
accountId: owner.id,
|
|
1247
|
-
state: result.state,
|
|
1248
|
-
list: args.ids.flatMap((id) => {
|
|
1249
|
-
const emailIds = threads.get(id);
|
|
1250
|
-
|
|
1251
|
-
return emailIds ? [{ id, emailIds }] : [];
|
|
1252
|
-
}),
|
|
1253
|
-
notFound: args.ids.filter((id) => !threads.has(id)),
|
|
1254
|
-
};
|
|
1255
|
-
}
|
|
1256
|
-
|
|
1257
|
-
const identityGetArguments = z.object({
|
|
1258
|
-
accountId,
|
|
1259
|
-
ids: idList.nullish(),
|
|
1260
|
-
properties,
|
|
1261
|
-
});
|
|
1262
|
-
|
|
1263
|
-
function identityGet(
|
|
1264
|
-
state: RequestState,
|
|
1265
|
-
args: z.output<typeof identityGetArguments>
|
|
1266
|
-
) {
|
|
1267
|
-
const owner = account(state, args.accountId);
|
|
1268
|
-
|
|
1269
|
-
const list = owner.canSend
|
|
1270
|
-
? [
|
|
1271
|
-
{
|
|
1272
|
-
id: owner.id,
|
|
1273
|
-
name: owner.displayName,
|
|
1274
|
-
email: owner.address,
|
|
1275
|
-
replyTo: null,
|
|
1276
|
-
bcc: null,
|
|
1277
|
-
textSignature: "",
|
|
1278
|
-
htmlSignature: "",
|
|
1279
|
-
mayDelete: false,
|
|
1280
|
-
},
|
|
1281
|
-
]
|
|
1282
|
-
: [];
|
|
1283
|
-
|
|
1284
|
-
const ids = args.ids ?? list.map((identity) => identity.id);
|
|
1285
|
-
|
|
1286
|
-
return {
|
|
1287
|
-
accountId: owner.id,
|
|
1288
|
-
state: "1",
|
|
1289
|
-
list: list.flatMap((identity) =>
|
|
1290
|
-
ids.includes(identity.id) ? [pick(identity, args.properties)] : []
|
|
1291
|
-
),
|
|
1292
|
-
notFound: ids.filter((id) => id !== owner.id || !owner.canSend),
|
|
1293
|
-
};
|
|
1294
|
-
}
|
|
1295
|
-
|
|
1296
|
-
const submissionCreate = z.object({
|
|
1297
|
-
emailId: z.string(),
|
|
1298
|
-
identityId: z.string().optional(),
|
|
1299
|
-
});
|
|
1300
|
-
|
|
1301
|
-
const submissionSetArguments = z.object({
|
|
11
|
+
emailGet,
|
|
12
|
+
emailGetArguments,
|
|
13
|
+
emailQuery,
|
|
14
|
+
emailQueryArguments,
|
|
15
|
+
emailQueryChanges,
|
|
16
|
+
emailQueryChangesArguments,
|
|
17
|
+
emailSet,
|
|
18
|
+
emailSetArguments,
|
|
19
|
+
emailSetScopes,
|
|
20
|
+
} from "./email-methods";
|
|
21
|
+
import { emailImport, emailImportArguments } from "./import-methods";
|
|
22
|
+
import {
|
|
23
|
+
mailboxGet,
|
|
24
|
+
mailboxGetArguments,
|
|
25
|
+
mailboxQuery,
|
|
26
|
+
mailboxQueryArguments,
|
|
27
|
+
} from "./mailbox-methods";
|
|
28
|
+
import type {
|
|
29
|
+
Invocation,
|
|
30
|
+
JmapContext,
|
|
31
|
+
JmapRequest,
|
|
32
|
+
JsonObject,
|
|
33
|
+
RequestState,
|
|
34
|
+
} from "./method-core";
|
|
35
|
+
import {
|
|
36
|
+
CORE,
|
|
37
|
+
JmapError,
|
|
38
|
+
MAX_CALLS,
|
|
39
|
+
MethodError,
|
|
40
|
+
account,
|
|
1302
41
|
accountId,
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
requestUrl: state.context.requestUrl,
|
|
1324
|
-
compose: { ...draft.compose, userId: state.context.user.id },
|
|
1325
|
-
conversationId: `conv_${crypto.randomUUID().replaceAll("-", "")}`,
|
|
1326
|
-
related: null,
|
|
1327
|
-
forwarded: null,
|
|
1328
|
-
includeRelatedContext: false,
|
|
1329
|
-
fromAddress: owner.address,
|
|
1330
|
-
fromName: owner.displayName,
|
|
1331
|
-
defer: state.context.defer,
|
|
1332
|
-
});
|
|
1333
|
-
} catch (error) {
|
|
1334
|
-
return {
|
|
1335
|
-
error:
|
|
1336
|
-
error instanceof Error
|
|
1337
|
-
? error.message
|
|
1338
|
-
: "The message could not be sent",
|
|
1339
|
-
};
|
|
1340
|
-
}
|
|
1341
|
-
}
|
|
1342
|
-
|
|
1343
|
-
async function submissionSet(
|
|
1344
|
-
state: RequestState,
|
|
1345
|
-
args: z.output<typeof submissionSetArguments>,
|
|
1346
|
-
callId: string
|
|
1347
|
-
) {
|
|
1348
|
-
const owner = account(state, args.accountId);
|
|
1349
|
-
|
|
1350
|
-
if (!owner.canSend) {
|
|
1351
|
-
throw new MethodError("forbidden", "This account cannot send");
|
|
1352
|
-
}
|
|
1353
|
-
|
|
1354
|
-
const created = new Map<string, JsonObject>();
|
|
1355
|
-
const notCreated = new Map<string, JsonObject>();
|
|
1356
|
-
const sentDrafts = new Map<string, string>();
|
|
1357
|
-
|
|
1358
|
-
for (const [creationId, input] of Object.entries(args.create ?? {})) {
|
|
1359
|
-
const parsed = submissionCreate.safeParse(input);
|
|
1360
|
-
|
|
1361
|
-
if (!parsed.success) {
|
|
1362
|
-
notCreated.set(creationId, invalidProperties(parsed.error.issues));
|
|
1363
|
-
continue;
|
|
1364
|
-
}
|
|
1365
|
-
|
|
1366
|
-
const submission = parsed.data;
|
|
1367
|
-
|
|
1368
|
-
const emailId = submission.emailId.startsWith("#")
|
|
1369
|
-
? createdId(state, submission.emailId.slice(1))
|
|
1370
|
-
: submission.emailId;
|
|
1371
|
-
|
|
1372
|
-
const draft = emailId === undefined ? undefined : state.drafts.get(emailId);
|
|
1373
|
-
|
|
1374
|
-
if (emailId === undefined || !draft || draft.accountId !== owner.id) {
|
|
1375
|
-
notCreated.set(creationId, notADraft);
|
|
1376
|
-
continue;
|
|
1377
|
-
}
|
|
1378
|
-
|
|
1379
|
-
if (
|
|
1380
|
-
submission.identityId !== undefined &&
|
|
1381
|
-
submission.identityId !== owner.id
|
|
1382
|
-
) {
|
|
1383
|
-
notCreated.set(creationId, {
|
|
1384
|
-
type: "invalidProperties",
|
|
1385
|
-
properties: ["identityId"],
|
|
1386
|
-
description: "Unknown identity",
|
|
1387
|
-
});
|
|
1388
|
-
continue;
|
|
1389
|
-
}
|
|
1390
|
-
|
|
1391
|
-
// oxlint-disable-next-line eslint/no-await-in-loop -- submissions send mail in the order the client gave them
|
|
1392
|
-
const sent = await sendDraft(state, owner, draft);
|
|
1393
|
-
|
|
1394
|
-
if ("error" in sent) {
|
|
1395
|
-
notCreated.set(creationId, {
|
|
1396
|
-
type: "forbiddenToSend",
|
|
1397
|
-
description: sent.error,
|
|
1398
|
-
});
|
|
1399
|
-
continue;
|
|
1400
|
-
}
|
|
1401
|
-
|
|
1402
|
-
const id = `sub-${sent.email.id}`;
|
|
1403
|
-
state.createdIds.set(creationId, id);
|
|
1404
|
-
sentDrafts.set(id, emailId);
|
|
1405
|
-
created.set(creationId, {
|
|
1406
|
-
id,
|
|
1407
|
-
threadId: sent.email.conversationId,
|
|
1408
|
-
emailId: sent.email.id,
|
|
1409
|
-
sendAt: new Date().toISOString(),
|
|
1410
|
-
undoStatus: "final",
|
|
1411
|
-
});
|
|
1412
|
-
}
|
|
1413
|
-
|
|
1414
|
-
// The sent copy is already in Sent; drafts were never stored, so the
|
|
1415
|
-
// follow-up Email/set only reports them gone.
|
|
1416
|
-
const followUp = [
|
|
1417
|
-
...(args.onSuccessDestroyEmail ?? []),
|
|
1418
|
-
...Object.keys(args.onSuccessUpdateEmail ?? {}),
|
|
1419
|
-
].flatMap((reference) => {
|
|
1420
|
-
const id = reference.startsWith("#")
|
|
1421
|
-
? createdId(state, reference.slice(1))
|
|
1422
|
-
: reference;
|
|
1423
|
-
|
|
1424
|
-
const draftId = id === undefined ? undefined : sentDrafts.get(id);
|
|
1425
|
-
|
|
1426
|
-
return draftId === undefined ? [] : [draftId];
|
|
1427
|
-
});
|
|
1428
|
-
|
|
1429
|
-
if (followUp.length) {
|
|
1430
|
-
const stub = mailboxStub(state.context.env, owner.id);
|
|
1431
|
-
const current = await stub.jmapState();
|
|
1432
|
-
state.after.push([
|
|
1433
|
-
"Email/set",
|
|
1434
|
-
{
|
|
1435
|
-
accountId: owner.id,
|
|
1436
|
-
oldState: current,
|
|
1437
|
-
newState: current,
|
|
1438
|
-
created: null,
|
|
1439
|
-
updated: null,
|
|
1440
|
-
destroyed: followUp,
|
|
1441
|
-
notCreated: null,
|
|
1442
|
-
notUpdated: null,
|
|
1443
|
-
notDestroyed: null,
|
|
1444
|
-
},
|
|
1445
|
-
callId,
|
|
1446
|
-
]);
|
|
1447
|
-
}
|
|
1448
|
-
|
|
1449
|
-
return {
|
|
1450
|
-
accountId: owner.id,
|
|
1451
|
-
oldState: "1",
|
|
1452
|
-
newState: "1",
|
|
1453
|
-
created: setResult(created),
|
|
1454
|
-
notCreated: setResult(notCreated),
|
|
1455
|
-
updated: null,
|
|
1456
|
-
destroyed: null,
|
|
1457
|
-
notUpdated: null,
|
|
1458
|
-
notDestroyed: null,
|
|
1459
|
-
};
|
|
1460
|
-
}
|
|
1461
|
-
|
|
1462
|
-
// --------------------------------------------------------- push (RFC 8620 §7.2)
|
|
1463
|
-
|
|
1464
|
-
const MAX_PUSH_SUBSCRIPTIONS = 20;
|
|
1465
|
-
|
|
1466
|
-
type PushSubscriptionRow = typeof jmapPushSubscriptions.$inferSelect;
|
|
1467
|
-
|
|
1468
|
-
/** url and keys are never returned (§7.2.1). */
|
|
1469
|
-
function pushSubscriptionObject(row: PushSubscriptionRow) {
|
|
1470
|
-
return {
|
|
1471
|
-
id: row.id,
|
|
1472
|
-
deviceClientId: row.deviceClientId,
|
|
1473
|
-
verificationCode: row.verifiedAt ? row.verificationCode : null,
|
|
1474
|
-
expires: row.expiresAt.toISOString(),
|
|
1475
|
-
types: row.typesJson,
|
|
1476
|
-
};
|
|
1477
|
-
}
|
|
1478
|
-
|
|
1479
|
-
/** The data types to push; null is all of them. */
|
|
1480
|
-
const pushTypes = z.array(z.string()).nullish();
|
|
1481
|
-
|
|
1482
|
-
/** A PushSubscription create object (RFC 8620 §7.2). */
|
|
1483
|
-
const pushSubscriptionCreate = z.object({
|
|
1484
|
-
deviceClientId: z.string().min(1),
|
|
1485
|
-
url: z
|
|
1486
|
-
.url({ protocol: /^https$/u, error: "url must be an https URL" })
|
|
1487
|
-
.transform((url) => new URL(url).toString()),
|
|
1488
|
-
keys: z.object({ p256dh: z.string(), auth: z.string() }).nullish(),
|
|
1489
|
-
verificationCode: z
|
|
1490
|
-
.never({ error: "verificationCode is set by update" })
|
|
1491
|
-
.optional(),
|
|
1492
|
-
expires: utcDate.nullish(),
|
|
1493
|
-
types: pushTypes,
|
|
1494
|
-
});
|
|
1495
|
-
|
|
1496
|
-
/** Only these change after a subscription is created. */
|
|
1497
|
-
const pushSubscriptionPatch = z.strictObject({
|
|
1498
|
-
verificationCode: z.string().optional(),
|
|
1499
|
-
expires: utcDate.nullish(),
|
|
1500
|
-
types: pushTypes,
|
|
1501
|
-
});
|
|
1502
|
-
|
|
1503
|
-
function ownSubscriptions(state: RequestState) {
|
|
1504
|
-
return and(
|
|
1505
|
-
eq(jmapPushSubscriptions.userId, state.context.user.id),
|
|
1506
|
-
eq(jmapPushSubscriptions.clientId, state.context.clientId)
|
|
1507
|
-
);
|
|
1508
|
-
}
|
|
1509
|
-
|
|
1510
|
-
const pushSubscriptionGetArguments = z.object({
|
|
1511
|
-
ids: idList.nullish(),
|
|
1512
|
-
properties,
|
|
1513
|
-
});
|
|
1514
|
-
|
|
1515
|
-
async function pushSubscriptionGet(
|
|
1516
|
-
state: RequestState,
|
|
1517
|
-
args: z.output<typeof pushSubscriptionGetArguments>
|
|
1518
|
-
) {
|
|
1519
|
-
const db = createDb(state.context.env.DB);
|
|
1520
|
-
const ids = args.ids ?? null;
|
|
1521
|
-
|
|
1522
|
-
const rows = await db
|
|
1523
|
-
.select()
|
|
1524
|
-
.from(jmapPushSubscriptions)
|
|
1525
|
-
.where(
|
|
1526
|
-
ids
|
|
1527
|
-
? and(
|
|
1528
|
-
ownSubscriptions(state),
|
|
1529
|
-
inArray(jmapPushSubscriptions.id, ids.length ? ids : [""])
|
|
1530
|
-
)
|
|
1531
|
-
: ownSubscriptions(state)
|
|
1532
|
-
);
|
|
1533
|
-
|
|
1534
|
-
const found = new Set(rows.map((row) => row.id));
|
|
1535
|
-
|
|
1536
|
-
return {
|
|
1537
|
-
list: rows.map((row) => pick(pushSubscriptionObject(row), args.properties)),
|
|
1538
|
-
notFound: ids ? ids.filter((id) => !found.has(id)) : [],
|
|
1539
|
-
};
|
|
1540
|
-
}
|
|
1541
|
-
|
|
1542
|
-
const pushSubscriptionSetArguments = z.object({
|
|
1543
|
-
/** Push subscriptions have no state (§7.2): any given state mismatches. */
|
|
1544
|
-
ifInState: z.string().nullish(),
|
|
1545
|
-
create: setObjects,
|
|
1546
|
-
update: setObjects,
|
|
1547
|
-
destroy: idList.nullish(),
|
|
1548
|
-
});
|
|
1549
|
-
|
|
1550
|
-
async function createPushSubscriptions(
|
|
1551
|
-
state: RequestState,
|
|
1552
|
-
create: JsonObject
|
|
1553
|
-
) {
|
|
1554
|
-
const db = createDb(state.context.env.DB);
|
|
1555
|
-
const created = new Map<string, JsonObject>();
|
|
1556
|
-
const notCreated = new Map<string, JsonObject>();
|
|
1557
|
-
const entries = Object.entries(create);
|
|
1558
|
-
|
|
1559
|
-
if (!entries.length) return { created, notCreated };
|
|
1560
|
-
|
|
1561
|
-
// The devices with a subscription; a device has one, and a new one replaces it.
|
|
1562
|
-
const devices = new Set(
|
|
1563
|
-
(
|
|
1564
|
-
await db
|
|
1565
|
-
.select({ deviceClientId: jmapPushSubscriptions.deviceClientId })
|
|
1566
|
-
.from(jmapPushSubscriptions)
|
|
1567
|
-
.where(eq(jmapPushSubscriptions.userId, state.context.user.id))
|
|
1568
|
-
).map((row) => row.deviceClientId)
|
|
1569
|
-
);
|
|
1570
|
-
|
|
1571
|
-
const rows: PushSubscriptionRow[] = [];
|
|
1572
|
-
|
|
1573
|
-
for (const [creationId, input] of entries) {
|
|
1574
|
-
const parsed = pushSubscriptionCreate.safeParse(input);
|
|
1575
|
-
|
|
1576
|
-
if (!parsed.success) {
|
|
1577
|
-
notCreated.set(creationId, invalidProperties(parsed.error.issues));
|
|
1578
|
-
continue;
|
|
1579
|
-
}
|
|
1580
|
-
|
|
1581
|
-
const subscription = parsed.data;
|
|
1582
|
-
|
|
1583
|
-
if (subscription.keys && !state.context.vapid) {
|
|
1584
|
-
notCreated.set(creationId, {
|
|
1585
|
-
type: "invalidProperties",
|
|
1586
|
-
properties: ["keys"],
|
|
1587
|
-
description: "Web Push is not configured on this server",
|
|
1588
|
-
});
|
|
1589
|
-
continue;
|
|
1590
|
-
}
|
|
1591
|
-
|
|
1592
|
-
const others =
|
|
1593
|
-
devices.size - (devices.has(subscription.deviceClientId) ? 1 : 0);
|
|
1594
|
-
|
|
1595
|
-
if (others >= MAX_PUSH_SUBSCRIPTIONS) {
|
|
1596
|
-
notCreated.set(creationId, {
|
|
1597
|
-
type: "overQuota",
|
|
1598
|
-
description: `At most ${MAX_PUSH_SUBSCRIPTIONS} push subscriptions`,
|
|
1599
|
-
});
|
|
1600
|
-
continue;
|
|
1601
|
-
}
|
|
1602
|
-
|
|
1603
|
-
devices.add(subscription.deviceClientId);
|
|
1604
|
-
|
|
1605
|
-
const row: PushSubscriptionRow = {
|
|
1606
|
-
id: crypto.randomUUID(),
|
|
1607
|
-
userId: state.context.user.id,
|
|
1608
|
-
clientId: state.context.clientId,
|
|
1609
|
-
deviceClientId: subscription.deviceClientId,
|
|
1610
|
-
url: subscription.url,
|
|
1611
|
-
p256dh: subscription.keys?.p256dh ?? null,
|
|
1612
|
-
auth: subscription.keys?.auth ?? null,
|
|
1613
|
-
verificationCode: newVerificationCode(),
|
|
1614
|
-
verifiedAt: null,
|
|
1615
|
-
expiresAt: subscriptionExpiry(subscription.expires),
|
|
1616
|
-
typesJson: subscription.types ?? null,
|
|
1617
|
-
createdAt: new Date(),
|
|
1618
|
-
};
|
|
1619
|
-
|
|
1620
|
-
rows.push(row);
|
|
1621
|
-
state.createdIds.set(creationId, row.id);
|
|
1622
|
-
created.set(creationId, {
|
|
1623
|
-
id: row.id,
|
|
1624
|
-
expires: row.expiresAt.toISOString(),
|
|
1625
|
-
});
|
|
1626
|
-
}
|
|
1627
|
-
|
|
1628
|
-
// In order: a later subscription for the same device replaces an earlier one.
|
|
1629
|
-
const [first, ...rest] = rows.flatMap((row) => [
|
|
1630
|
-
db
|
|
1631
|
-
.delete(jmapPushSubscriptions)
|
|
1632
|
-
.where(
|
|
1633
|
-
and(
|
|
1634
|
-
eq(jmapPushSubscriptions.userId, row.userId),
|
|
1635
|
-
eq(jmapPushSubscriptions.deviceClientId, row.deviceClientId)
|
|
1636
|
-
)
|
|
1637
|
-
),
|
|
1638
|
-
db.insert(jmapPushSubscriptions).values(row),
|
|
1639
|
-
]);
|
|
1640
|
-
|
|
1641
|
-
if (first) await db.batch([first, ...rest]);
|
|
1642
|
-
|
|
1643
|
-
for (const row of rows) {
|
|
1644
|
-
state.context.defer(
|
|
1645
|
-
sendVerification(row, state.context.vapid).catch((error) => {
|
|
1646
|
-
console.error(
|
|
1647
|
-
"Could not send JMAP push verification",
|
|
1648
|
-
error instanceof Error ? error.message : String(error)
|
|
1649
|
-
);
|
|
1650
|
-
})
|
|
1651
|
-
);
|
|
1652
|
-
}
|
|
1653
|
-
|
|
1654
|
-
return { created, notCreated };
|
|
1655
|
-
}
|
|
1656
|
-
|
|
1657
|
-
async function updatePushSubscriptions(
|
|
1658
|
-
state: RequestState,
|
|
1659
|
-
update: JsonObject
|
|
1660
|
-
) {
|
|
1661
|
-
const db = createDb(state.context.env.DB);
|
|
1662
|
-
const updated = new Map<string, JsonObject | null>();
|
|
1663
|
-
const notUpdated = new Map<string, JsonObject>();
|
|
1664
|
-
const entries = Object.entries(update);
|
|
1665
|
-
|
|
1666
|
-
if (!entries.length) return { updated, notUpdated };
|
|
1667
|
-
|
|
1668
|
-
const rows = new Map(
|
|
1669
|
-
(
|
|
1670
|
-
await db
|
|
1671
|
-
.select()
|
|
1672
|
-
.from(jmapPushSubscriptions)
|
|
1673
|
-
.where(
|
|
1674
|
-
and(
|
|
1675
|
-
ownSubscriptions(state),
|
|
1676
|
-
inArray(
|
|
1677
|
-
jmapPushSubscriptions.id,
|
|
1678
|
-
entries.map(([id]) => id)
|
|
1679
|
-
)
|
|
1680
|
-
)
|
|
1681
|
-
)
|
|
1682
|
-
).map((row) => [row.id, row])
|
|
1683
|
-
);
|
|
1684
|
-
|
|
1685
|
-
const changed: Pick<
|
|
1686
|
-
PushSubscriptionRow,
|
|
1687
|
-
"id" | "verifiedAt" | "expiresAt" | "typesJson"
|
|
1688
|
-
>[] = [];
|
|
1689
|
-
|
|
1690
|
-
for (const [id, input] of entries) {
|
|
1691
|
-
const row = rows.get(id);
|
|
1692
|
-
|
|
1693
|
-
if (!row) {
|
|
1694
|
-
notUpdated.set(id, { type: "notFound" });
|
|
1695
|
-
continue;
|
|
1696
|
-
}
|
|
1697
|
-
|
|
1698
|
-
const parsed = pushSubscriptionPatch.safeParse(input);
|
|
1699
|
-
|
|
1700
|
-
if (!parsed.success) {
|
|
1701
|
-
notUpdated.set(id, invalidProperties(parsed.error.issues));
|
|
1702
|
-
continue;
|
|
1703
|
-
}
|
|
1704
|
-
|
|
1705
|
-
const patch = parsed.data;
|
|
1706
|
-
|
|
1707
|
-
if (
|
|
1708
|
-
patch.verificationCode !== undefined &&
|
|
1709
|
-
patch.verificationCode !== row.verificationCode
|
|
1710
|
-
) {
|
|
1711
|
-
notUpdated.set(id, {
|
|
1712
|
-
type: "invalidProperties",
|
|
1713
|
-
properties: ["verificationCode"],
|
|
1714
|
-
description: "The verification code does not match",
|
|
1715
|
-
});
|
|
1716
|
-
continue;
|
|
1717
|
-
}
|
|
1718
|
-
|
|
1719
|
-
const expiresAt =
|
|
1720
|
-
patch.expires === undefined
|
|
1721
|
-
? row.expiresAt
|
|
1722
|
-
: subscriptionExpiry(patch.expires);
|
|
1723
|
-
|
|
1724
|
-
changed.push({
|
|
1725
|
-
id,
|
|
1726
|
-
verifiedAt:
|
|
1727
|
-
patch.verificationCode === undefined
|
|
1728
|
-
? row.verifiedAt
|
|
1729
|
-
: (row.verifiedAt ?? new Date()),
|
|
1730
|
-
expiresAt,
|
|
1731
|
-
typesJson: patch.types === undefined ? row.typesJson : patch.types,
|
|
1732
|
-
});
|
|
1733
|
-
|
|
1734
|
-
// The server may shorten the asked expiry; then it says what it chose.
|
|
1735
|
-
const askedExpiry = patch.expires ? Date.parse(patch.expires) : null;
|
|
1736
|
-
|
|
1737
|
-
updated.set(
|
|
1738
|
-
id,
|
|
1739
|
-
askedExpiry !== null && askedExpiry !== expiresAt.getTime()
|
|
1740
|
-
? { expires: expiresAt.toISOString() }
|
|
1741
|
-
: null
|
|
1742
|
-
);
|
|
1743
|
-
}
|
|
1744
|
-
|
|
1745
|
-
const [first, ...rest] = changed.map(({ id, ...values }) =>
|
|
1746
|
-
db
|
|
1747
|
-
.update(jmapPushSubscriptions)
|
|
1748
|
-
.set(values)
|
|
1749
|
-
.where(eq(jmapPushSubscriptions.id, id))
|
|
1750
|
-
);
|
|
1751
|
-
|
|
1752
|
-
if (first) await db.batch([first, ...rest]);
|
|
1753
|
-
|
|
1754
|
-
return { updated, notUpdated };
|
|
1755
|
-
}
|
|
1756
|
-
|
|
1757
|
-
async function pushSubscriptionSet(
|
|
1758
|
-
state: RequestState,
|
|
1759
|
-
args: z.output<typeof pushSubscriptionSetArguments>
|
|
1760
|
-
) {
|
|
1761
|
-
const db = createDb(state.context.env.DB);
|
|
1762
|
-
|
|
1763
|
-
if (args.ifInState != null) throw new MethodError("stateMismatch");
|
|
1764
|
-
|
|
1765
|
-
const { created, notCreated } = await createPushSubscriptions(
|
|
1766
|
-
state,
|
|
1767
|
-
args.create ?? {}
|
|
1768
|
-
);
|
|
1769
|
-
|
|
1770
|
-
const { updated, notUpdated } = await updatePushSubscriptions(
|
|
1771
|
-
state,
|
|
1772
|
-
args.update ?? {}
|
|
1773
|
-
);
|
|
1774
|
-
|
|
1775
|
-
const destroyIds = args.destroy ?? [];
|
|
1776
|
-
|
|
1777
|
-
const removed = destroyIds.length
|
|
1778
|
-
? await db
|
|
1779
|
-
.delete(jmapPushSubscriptions)
|
|
1780
|
-
.where(
|
|
1781
|
-
and(
|
|
1782
|
-
ownSubscriptions(state),
|
|
1783
|
-
inArray(jmapPushSubscriptions.id, destroyIds)
|
|
1784
|
-
)
|
|
1785
|
-
)
|
|
1786
|
-
.returning({ id: jmapPushSubscriptions.id })
|
|
1787
|
-
: [];
|
|
1788
|
-
|
|
1789
|
-
const destroyed = new Set(removed.map((row) => row.id));
|
|
1790
|
-
const notDestroyed = new Map<string, JsonObject>();
|
|
1791
|
-
|
|
1792
|
-
for (const id of destroyIds) {
|
|
1793
|
-
if (!destroyed.has(id)) notDestroyed.set(id, { type: "notFound" });
|
|
1794
|
-
}
|
|
1795
|
-
|
|
1796
|
-
return {
|
|
1797
|
-
created: setResult(created),
|
|
1798
|
-
updated: setResult(updated),
|
|
1799
|
-
destroyed: destroyed.size ? [...destroyed] : null,
|
|
1800
|
-
notCreated: setResult(notCreated),
|
|
1801
|
-
notUpdated: setResult(notUpdated),
|
|
1802
|
-
notDestroyed: setResult(notDestroyed),
|
|
1803
|
-
};
|
|
1804
|
-
}
|
|
42
|
+
changesArguments,
|
|
43
|
+
idList,
|
|
44
|
+
parseArguments,
|
|
45
|
+
resolveReferences,
|
|
46
|
+
sessionState,
|
|
47
|
+
} from "./method-core";
|
|
48
|
+
import {
|
|
49
|
+
pushSubscriptionGet,
|
|
50
|
+
pushSubscriptionGetArguments,
|
|
51
|
+
pushSubscriptionSet,
|
|
52
|
+
pushSubscriptionSetArguments,
|
|
53
|
+
} from "./push-subscription-methods";
|
|
54
|
+
import {
|
|
55
|
+
identityGet,
|
|
56
|
+
identityGetArguments,
|
|
57
|
+
submissionSet,
|
|
58
|
+
submissionSetArguments,
|
|
59
|
+
threadGet,
|
|
60
|
+
threadGetArguments,
|
|
61
|
+
} from "./submission-methods";
|
|
1805
62
|
|
|
1806
63
|
// ----------------------------------------------------------------- dispatch
|
|
1807
64
|
|
|
@@ -1823,8 +80,8 @@ function method<Schema extends z.ZodType>(definition: {
|
|
|
1823
80
|
args: z.output<Schema>,
|
|
1824
81
|
callId: string
|
|
1825
82
|
) => JsonObject | Promise<JsonObject>;
|
|
1826
|
-
})
|
|
1827
|
-
return (state, raw, callId) => {
|
|
83
|
+
}) {
|
|
84
|
+
return ((state, raw, callId) => {
|
|
1828
85
|
const args = parseArguments(definition.arguments, raw);
|
|
1829
86
|
|
|
1830
87
|
const missing = definition
|
|
@@ -1839,25 +96,41 @@ function method<Schema extends z.ZodType>(definition: {
|
|
|
1839
96
|
}
|
|
1840
97
|
|
|
1841
98
|
return definition.run(state, args, callId);
|
|
1842
|
-
};
|
|
99
|
+
}) satisfies MethodHandler;
|
|
1843
100
|
}
|
|
1844
101
|
|
|
1845
102
|
const reading = () => [MAIL_READ_SCOPE];
|
|
1846
103
|
|
|
1847
|
-
/**
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
104
|
+
/**
|
|
105
|
+
* Foo/changes from the mailbox's change log, for the types that share its
|
|
106
|
+
* one state; a state it can't answer from makes the client resync.
|
|
107
|
+
*/
|
|
108
|
+
const changesMethod = (type: "Email" | "Thread" | "Mailbox") =>
|
|
109
|
+
method({
|
|
110
|
+
arguments: changesArguments,
|
|
111
|
+
scopes: reading,
|
|
112
|
+
run: async (state, args) => {
|
|
113
|
+
const owner = account(state, args.accountId);
|
|
114
|
+
|
|
115
|
+
const changes = await mailboxStub(
|
|
116
|
+
state.context.env,
|
|
117
|
+
owner.id
|
|
118
|
+
).jmapChanges({
|
|
119
|
+
type,
|
|
120
|
+
sinceState: args.sinceState,
|
|
121
|
+
userId: state.context.user.id,
|
|
122
|
+
maxChanges: args.maxChanges ?? null,
|
|
123
|
+
});
|
|
1853
124
|
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
}
|
|
125
|
+
if (!changes) throw new MethodError("cannotCalculateChanges");
|
|
126
|
+
const { emailsChanged: _counts, ...answer } = changes;
|
|
127
|
+
|
|
128
|
+
// Mailbox/changes also says which properties changed: any of them.
|
|
129
|
+
return type === "Mailbox"
|
|
130
|
+
? { accountId: owner.id, ...answer, updatedProperties: null }
|
|
131
|
+
: { accountId: owner.id, ...answer };
|
|
132
|
+
},
|
|
133
|
+
});
|
|
1861
134
|
|
|
1862
135
|
const methods = new Map<string, MethodHandler>([
|
|
1863
136
|
[
|
|
@@ -1884,7 +157,7 @@ const methods = new Map<string, MethodHandler>([
|
|
|
1884
157
|
run: mailboxQuery,
|
|
1885
158
|
}),
|
|
1886
159
|
],
|
|
1887
|
-
["Mailbox/changes",
|
|
160
|
+
["Mailbox/changes", changesMethod("Mailbox")],
|
|
1888
161
|
[
|
|
1889
162
|
"Email/query",
|
|
1890
163
|
method({
|
|
@@ -1902,15 +175,31 @@ const methods = new Map<string, MethodHandler>([
|
|
|
1902
175
|
method({
|
|
1903
176
|
arguments: emailSetArguments,
|
|
1904
177
|
scopes: emailSetScopes,
|
|
1905
|
-
run: emailSet,
|
|
178
|
+
run: (state, args) => emailSet(state, args),
|
|
179
|
+
}),
|
|
180
|
+
],
|
|
181
|
+
[
|
|
182
|
+
"Email/import",
|
|
183
|
+
method({
|
|
184
|
+
arguments: emailImportArguments,
|
|
185
|
+
scopes: () => [MAIL_ORGANIZE_SCOPE],
|
|
186
|
+
run: emailImport,
|
|
187
|
+
}),
|
|
188
|
+
],
|
|
189
|
+
["Email/changes", changesMethod("Email")],
|
|
190
|
+
[
|
|
191
|
+
"Email/queryChanges",
|
|
192
|
+
method({
|
|
193
|
+
arguments: emailQueryChangesArguments,
|
|
194
|
+
scopes: reading,
|
|
195
|
+
run: emailQueryChanges,
|
|
1906
196
|
}),
|
|
1907
197
|
],
|
|
1908
|
-
["Email/changes", mailboxChanges],
|
|
1909
198
|
[
|
|
1910
199
|
"Thread/get",
|
|
1911
200
|
method({ arguments: threadGetArguments, scopes: reading, run: threadGet }),
|
|
1912
201
|
],
|
|
1913
|
-
["Thread/changes",
|
|
202
|
+
["Thread/changes", changesMethod("Thread")],
|
|
1914
203
|
[
|
|
1915
204
|
"SearchSnippet/get",
|
|
1916
205
|
method({
|
|
@@ -2021,7 +310,11 @@ export async function runJmapRequest(
|
|
|
2021
310
|
|
|
2022
311
|
const response: JmapResponse = {
|
|
2023
312
|
methodResponses: state.responses,
|
|
2024
|
-
sessionState:
|
|
313
|
+
sessionState: await sessionState(
|
|
314
|
+
context.accounts,
|
|
315
|
+
context.scopes,
|
|
316
|
+
context.vapid?.publicKey ?? null
|
|
317
|
+
),
|
|
2025
318
|
};
|
|
2026
319
|
|
|
2027
320
|
// Only a request that sent createdIds gets them back (§3.4).
|