@open-workspace/email 0.3.0 → 0.4.1
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 +22 -22
- 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_email.sql → 0000_dry_moon_knight.sql} +26 -20
- package/migrations/meta/0000_snapshot.json +125 -109
- 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 +77 -28
- 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 +63 -40
- package/worker/jmap/eventsource.ts +84 -16
- package/worker/jmap/methods.ts +1630 -524
- package/worker/jmap/push-types.ts +27 -0
- package/worker/jmap/push.ts +140 -56
- package/worker/jmap/routes.ts +366 -105
- 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 +88 -22
- 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 +271 -173
- 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 +870 -541
- package/worker/mail/safety-routes.ts +328 -200
- 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 +126 -93
- 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 +595 -225
- 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 +1734 -721
- package/worker/mailbox/jmap-store.ts +139 -35
- package/worker/mailbox/model.ts +8 -6
- 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 -142
- package/containers/office-preview/Dockerfile +0 -10
- 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/migrations.ts +0 -10
- package/worker/mailbox/rules.ts +0 -110
package/worker/jmap/methods.ts
CHANGED
|
@@ -1,16 +1,35 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createDb,
|
|
3
|
+
describeIssues,
|
|
4
|
+
issueProperties,
|
|
5
|
+
} from "@open-workspace/core/module";
|
|
6
|
+
import type { Issue } from "@open-workspace/core/module";
|
|
1
7
|
import { and, eq, inArray } from "drizzle-orm";
|
|
2
|
-
import {
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
|
|
3
10
|
import { MAX_COMPOSER_ATTACHMENT_COUNT } from "../../shared/mail";
|
|
11
|
+
import {
|
|
12
|
+
MAIL_ORGANIZE_SCOPE,
|
|
13
|
+
MAIL_READ_SCOPE,
|
|
14
|
+
MAIL_SEND_SCOPE,
|
|
15
|
+
} from "../../shared/permissions";
|
|
4
16
|
import { jmapPushSubscriptions } from "../db/schema";
|
|
5
|
-
import { mailboxStub } from "../mailbox";
|
|
6
|
-
import type { Email } from "../mailbox/schema";
|
|
7
|
-
import type { JmapEmailFilter, JmapMailboxRow } from "../mailbox/jmap-store";
|
|
8
17
|
import { submitOutgoing } from "../mail/outbound-service";
|
|
18
|
+
import { composeSchema } from "../mail/schemas";
|
|
9
19
|
import { describeComposerUpload, UploadValidationError } from "../mail/uploads";
|
|
10
|
-
import {
|
|
20
|
+
import { mailboxStub } from "../mailbox";
|
|
21
|
+
import type { JmapEmailFilter, JmapMailboxRow } from "../mailbox/jmap-store";
|
|
22
|
+
import type { Email } from "../mailbox/schema";
|
|
23
|
+
import {
|
|
24
|
+
newVerificationCode,
|
|
25
|
+
sendVerification,
|
|
26
|
+
subscriptionExpiry,
|
|
27
|
+
} from "./push";
|
|
28
|
+
import type { PushVapid } from "./push";
|
|
11
29
|
|
|
12
30
|
const CORE = "urn:ietf:params:jmap:core";
|
|
13
31
|
const MAX_OBJECTS = 500;
|
|
32
|
+
const MAX_CALLS = 32;
|
|
14
33
|
|
|
15
34
|
export type JmapAccount = {
|
|
16
35
|
id: string;
|
|
@@ -27,6 +46,8 @@ export type JmapContext = {
|
|
|
27
46
|
user: { id: string; name: string };
|
|
28
47
|
/** The OAuth client the token was issued to; push subscriptions belong to it. */
|
|
29
48
|
clientId: string;
|
|
49
|
+
/** The token's mail scopes; each method needs its own (`scopes` of its definition). */
|
|
50
|
+
scopes: readonly string[];
|
|
30
51
|
/** Signs pushes to Web Push services; null when push is not configured. */
|
|
31
52
|
vapid: PushVapid | null;
|
|
32
53
|
accounts: JmapAccount[];
|
|
@@ -34,126 +55,336 @@ export type JmapContext = {
|
|
|
34
55
|
defer: (task: Promise<unknown>) => void;
|
|
35
56
|
};
|
|
36
57
|
|
|
37
|
-
type
|
|
38
|
-
|
|
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];
|
|
39
74
|
|
|
40
75
|
/** A request-level error (RFC 8620 §3.6.1), answered as a problem document. */
|
|
41
76
|
export class JmapError extends Error {
|
|
42
|
-
constructor(
|
|
77
|
+
constructor(
|
|
78
|
+
readonly type: string,
|
|
79
|
+
message: string
|
|
80
|
+
) {
|
|
43
81
|
super(message);
|
|
44
82
|
}
|
|
45
83
|
}
|
|
46
84
|
|
|
47
|
-
/**
|
|
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. */
|
|
48
102
|
class MethodError extends Error {
|
|
49
|
-
constructor(
|
|
103
|
+
constructor(
|
|
104
|
+
readonly type: MethodErrorType,
|
|
105
|
+
message?: string
|
|
106
|
+
) {
|
|
50
107
|
super(message ?? type);
|
|
51
108
|
}
|
|
52
109
|
}
|
|
53
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
|
+
|
|
54
114
|
/** An attachment of a draft: bytes from /jmap/upload. */
|
|
55
115
|
type DraftAttachment = {
|
|
56
116
|
uploadId: string;
|
|
57
117
|
name: string;
|
|
58
118
|
type: string;
|
|
59
119
|
disposition: "attachment" | "inline";
|
|
60
|
-
contentId
|
|
120
|
+
contentId: string | undefined;
|
|
61
121
|
};
|
|
62
122
|
|
|
63
|
-
/**
|
|
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
|
+
*/
|
|
64
127
|
type Draft = {
|
|
65
128
|
accountId: string;
|
|
66
|
-
|
|
67
|
-
cc: string[];
|
|
68
|
-
bcc: string[];
|
|
69
|
-
subject: string;
|
|
70
|
-
bodyText: string;
|
|
71
|
-
bodyHtml?: string;
|
|
129
|
+
compose: z.output<typeof composeSchema>;
|
|
72
130
|
attachments: DraftAttachment[];
|
|
73
131
|
};
|
|
74
132
|
|
|
75
|
-
/**
|
|
76
|
-
|
|
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
|
+
}
|
|
77
151
|
|
|
78
152
|
type RequestState = {
|
|
79
153
|
context: JmapContext;
|
|
80
154
|
responses: Invocation[];
|
|
81
|
-
createdIds:
|
|
155
|
+
createdIds: Map<string, string>;
|
|
82
156
|
drafts: Map<string, Draft>;
|
|
83
157
|
/** Responses a method adds after its own, e.g. an implicit Email/set. */
|
|
84
158
|
after: Invocation[];
|
|
85
159
|
};
|
|
86
160
|
|
|
87
|
-
|
|
88
|
-
|
|
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);
|
|
89
164
|
}
|
|
90
165
|
|
|
91
166
|
// ---------------------------------------------------------------- references
|
|
92
167
|
|
|
93
168
|
/** RFC 8620 §3.7: a JSON Pointer where `*` maps over an array. */
|
|
94
|
-
function evaluatePointer(value:
|
|
169
|
+
function evaluatePointer(value: Json, path: string): Json {
|
|
95
170
|
if (path === "") return value;
|
|
96
|
-
|
|
171
|
+
|
|
172
|
+
const [head = "", ...rest] = path
|
|
173
|
+
.slice(1)
|
|
174
|
+
.split("/")
|
|
175
|
+
.map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
|
|
176
|
+
|
|
97
177
|
const tail = rest.length ? `/${rest.join("/")}` : "";
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
return
|
|
102
|
-
|
|
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);
|
|
103
195
|
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
196
|
+
|
|
197
|
+
throw new MethodError(
|
|
198
|
+
"invalidResultReference",
|
|
199
|
+
`Path ${path} does not resolve`
|
|
200
|
+
);
|
|
107
201
|
}
|
|
108
202
|
|
|
109
|
-
|
|
110
|
-
|
|
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
|
+
|
|
111
212
|
for (const [key, value] of Object.entries(args)) {
|
|
112
213
|
if (!key.startsWith("#")) {
|
|
113
214
|
resolved[key] = value;
|
|
114
215
|
continue;
|
|
115
216
|
}
|
|
217
|
+
|
|
116
218
|
const name = key.slice(1);
|
|
117
|
-
|
|
118
|
-
if (
|
|
119
|
-
throw new MethodError(
|
|
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
|
+
);
|
|
120
234
|
}
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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);
|
|
124
250
|
}
|
|
251
|
+
|
|
125
252
|
return resolved;
|
|
126
253
|
}
|
|
127
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
|
+
|
|
128
339
|
// ------------------------------------------------------------------ helpers
|
|
129
340
|
|
|
130
|
-
|
|
131
|
-
|
|
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
|
+
|
|
132
349
|
if (!found) throw new MethodError("accountNotFound");
|
|
350
|
+
|
|
133
351
|
return found;
|
|
134
352
|
}
|
|
135
353
|
|
|
136
|
-
function
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
if (
|
|
141
|
-
return value as string[];
|
|
142
|
-
}
|
|
354
|
+
function pick<Value extends Json>(
|
|
355
|
+
object: Record<string, Value>,
|
|
356
|
+
wanted: readonly string[] | null | undefined
|
|
357
|
+
) {
|
|
358
|
+
if (!wanted) return object;
|
|
143
359
|
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
360
|
+
return Object.fromEntries(
|
|
361
|
+
Object.entries(object).filter(
|
|
362
|
+
([key]) => key === "id" || wanted.includes(key)
|
|
363
|
+
)
|
|
364
|
+
);
|
|
147
365
|
}
|
|
148
366
|
|
|
149
367
|
/** We cannot list changes, only say whether anything changed. */
|
|
150
|
-
function changes(
|
|
368
|
+
function changes(owner: JmapAccount, sinceState: string, state: string) {
|
|
151
369
|
if (sinceState !== state) throw new MethodError("cannotCalculateChanges");
|
|
152
|
-
|
|
370
|
+
|
|
371
|
+
return {
|
|
372
|
+
accountId: owner.id,
|
|
373
|
+
oldState: state,
|
|
374
|
+
newState: state,
|
|
375
|
+
hasMoreChanges: false,
|
|
376
|
+
created: [],
|
|
377
|
+
updated: [],
|
|
378
|
+
destroyed: [],
|
|
379
|
+
};
|
|
153
380
|
}
|
|
154
381
|
|
|
155
|
-
const addresses = (
|
|
156
|
-
list
|
|
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;
|
|
157
388
|
|
|
158
389
|
// ------------------------------------------------------------------ mailbox
|
|
159
390
|
|
|
@@ -183,86 +414,217 @@ function mailboxObject(row: JmapMailboxRow, canSend: boolean) {
|
|
|
183
414
|
};
|
|
184
415
|
}
|
|
185
416
|
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
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);
|
|
190
435
|
const byId = new Map(mailboxes.map((row) => [row.id, row]));
|
|
436
|
+
|
|
191
437
|
return {
|
|
192
438
|
accountId: owner.id,
|
|
193
439
|
state: mailboxState,
|
|
194
440
|
list: ids.flatMap((id) => {
|
|
195
441
|
const row = byId.get(id);
|
|
196
|
-
|
|
442
|
+
|
|
443
|
+
return row
|
|
444
|
+
? [pick(mailboxObject(row, owner.canSend), args.properties)]
|
|
445
|
+
: [];
|
|
197
446
|
}),
|
|
198
447
|
notFound: ids.filter((id) => !byId.has(id)),
|
|
199
448
|
};
|
|
200
449
|
}
|
|
201
450
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
}
|
|
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
|
+
});
|
|
212
461
|
|
|
213
|
-
|
|
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
|
+
);
|
|
214
482
|
|
|
215
|
-
function emailFilter(value: unknown): JmapEmailFilter {
|
|
216
|
-
if (value == null) return {};
|
|
217
|
-
if (!isRecord(value)) throw new MethodError("unsupportedFilter");
|
|
218
|
-
if ("operator" in value) {
|
|
219
|
-
if (value.operator !== "AND" || !Array.isArray(value.conditions)) {
|
|
220
|
-
throw new MethodError("unsupportedFilter", "Only AND filters are supported");
|
|
221
|
-
}
|
|
222
|
-
return Object.assign({}, ...value.conditions.map(emailFilter));
|
|
223
|
-
}
|
|
224
|
-
const supported = ["inMailbox", "inMailboxOtherThan", "before", "after", "text", "from", "to", "subject", "hasKeyword", "notKeyword", "hasAttachment"];
|
|
225
|
-
const unknown = Object.keys(value).filter((key) => !supported.includes(key));
|
|
226
|
-
if (unknown.length) throw new MethodError("unsupportedFilter", `Unsupported filter: ${unknown.join(", ")}`);
|
|
227
|
-
for (const keyword of [value.hasKeyword, value.notKeyword]) {
|
|
228
|
-
if (keyword !== undefined && keyword !== "$seen") {
|
|
229
|
-
throw new MethodError("unsupportedFilter", "Only the $seen keyword is supported");
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
483
|
return {
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
...(typeof value.to === "string" ? { to: value.to } : {}),
|
|
240
|
-
...(typeof value.subject === "string" ? { subject: value.subject } : {}),
|
|
241
|
-
...(typeof value.hasKeyword === "string" ? { hasKeyword: value.hasKeyword } : {}),
|
|
242
|
-
...(typeof value.notKeyword === "string" ? { notKeyword: value.notKeyword } : {}),
|
|
243
|
-
...(typeof value.hasAttachment === "boolean" ? { hasAttachment: value.hasAttachment } : {}),
|
|
484
|
+
accountId: owner.id,
|
|
485
|
+
queryState: mailboxState,
|
|
486
|
+
canCalculateChanges: false,
|
|
487
|
+
position: 0,
|
|
488
|
+
ids,
|
|
489
|
+
total: ids.length,
|
|
244
490
|
};
|
|
245
491
|
}
|
|
246
492
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
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
|
+
);
|
|
253
595
|
}
|
|
254
|
-
}
|
|
255
|
-
const ascending = isRecord(sort[0]) && sort[0].isAscending === true;
|
|
256
|
-
const position = Math.max(0, Number(args.position ?? 0) || 0);
|
|
257
|
-
const limit = Math.min(MAX_OBJECTS, Math.max(0, Number(args.limit ?? 100) || 100));
|
|
258
|
-
const result = await mailboxStub(state.context.env, owner.id).jmapQueryEmails({
|
|
259
|
-
userId: state.context.user.id,
|
|
260
|
-
filter: emailFilter(args.filter),
|
|
261
|
-
ascending,
|
|
262
|
-
position,
|
|
263
|
-
limit,
|
|
264
|
-
collapseThreads: args.collapseThreads === true,
|
|
265
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
|
+
|
|
266
628
|
return {
|
|
267
629
|
accountId: owner.id,
|
|
268
630
|
queryState: result.state,
|
|
@@ -275,25 +637,80 @@ async function emailQuery(state: RequestState, args: Args) {
|
|
|
275
637
|
}
|
|
276
638
|
|
|
277
639
|
const defaultEmailProperties = [
|
|
278
|
-
"id",
|
|
279
|
-
"
|
|
280
|
-
"
|
|
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",
|
|
281
664
|
];
|
|
282
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
|
+
|
|
283
678
|
async function emailObject(
|
|
284
679
|
env: Env,
|
|
285
680
|
row: { email: Email; mailboxId: string; seen: boolean },
|
|
286
|
-
args:
|
|
681
|
+
args: EmailGetArguments
|
|
287
682
|
) {
|
|
288
683
|
const { email } = row;
|
|
289
684
|
const raw = `raw~${email.id}`;
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
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
|
+
|
|
294
699
|
const htmlBody = email.bodyHtmlR2Key
|
|
295
|
-
? [
|
|
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
|
+
]
|
|
296
712
|
: textBody;
|
|
713
|
+
|
|
297
714
|
const attachments = email.attachmentsJson.map((attachment) => ({
|
|
298
715
|
partId: `att-${attachment.id}`,
|
|
299
716
|
blobId: `att~${email.id}~${attachment.id}`,
|
|
@@ -304,33 +721,55 @@ async function emailObject(
|
|
|
304
721
|
disposition: attachment.disposition,
|
|
305
722
|
cid: attachment.contentId,
|
|
306
723
|
}));
|
|
307
|
-
|
|
308
|
-
const
|
|
724
|
+
|
|
725
|
+
const wanted = args.properties ?? defaultEmailProperties;
|
|
726
|
+
const maxBytes = args.maxBodyValueBytes ?? 0;
|
|
727
|
+
|
|
309
728
|
const bodyValue = (value: string) => ({
|
|
310
|
-
value:
|
|
729
|
+
value:
|
|
730
|
+
maxBytes && value.length > maxBytes ? value.slice(0, maxBytes) : value,
|
|
311
731
|
isEncodingProblem: false,
|
|
312
732
|
isTruncated: Boolean(maxBytes && value.length > maxBytes),
|
|
313
733
|
});
|
|
734
|
+
|
|
314
735
|
const bodyValues: Record<string, ReturnType<typeof bodyValue>> = {};
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
const
|
|
318
|
-
|
|
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
|
+
|
|
319
748
|
if (wantHtml && email.bodyHtmlR2Key) {
|
|
320
749
|
const object = await env.MAIL_STORAGE.get(email.bodyHtmlR2Key);
|
|
321
750
|
bodyValues.html = bodyValue(object ? await object.text() : "");
|
|
322
751
|
}
|
|
323
752
|
}
|
|
753
|
+
|
|
324
754
|
const timestamp = email.timelineAt.toISOString();
|
|
755
|
+
const keywords: Record<string, true> = row.seen ? { $seen: true } : {};
|
|
756
|
+
|
|
325
757
|
const object = {
|
|
326
758
|
id: email.id,
|
|
327
759
|
blobId: raw,
|
|
328
760
|
threadId: email.conversationId,
|
|
329
761
|
mailboxIds: { [row.mailboxId]: true },
|
|
330
|
-
keywords
|
|
331
|
-
size:
|
|
762
|
+
keywords,
|
|
763
|
+
size:
|
|
764
|
+
(email.bodyText?.length ?? 0) +
|
|
765
|
+
email.attachmentsJson.reduce(
|
|
766
|
+
(total, attachment) => total + attachment.size,
|
|
767
|
+
0
|
|
768
|
+
),
|
|
332
769
|
receivedAt: timestamp,
|
|
333
|
-
messageId: email.messageIdHeader
|
|
770
|
+
messageId: email.messageIdHeader
|
|
771
|
+
? [email.messageIdHeader.replaceAll(/^<|>$/gu, "")]
|
|
772
|
+
: null,
|
|
334
773
|
inReplyTo: email.inReplyToJson?.length ? email.inReplyToJson : null,
|
|
335
774
|
references: email.referencesJson?.length ? email.referencesJson : null,
|
|
336
775
|
sender: null,
|
|
@@ -341,328 +780,678 @@ async function emailObject(
|
|
|
341
780
|
replyTo: addresses(email.replyToJson),
|
|
342
781
|
subject: email.subject,
|
|
343
782
|
sentAt: timestamp,
|
|
344
|
-
hasAttachment: attachments.some(
|
|
783
|
+
hasAttachment: attachments.some(
|
|
784
|
+
(attachment) => attachment.disposition === "attachment"
|
|
785
|
+
),
|
|
345
786
|
preview: email.preview,
|
|
346
787
|
bodyValues,
|
|
347
788
|
textBody,
|
|
348
789
|
htmlBody,
|
|
349
790
|
attachments,
|
|
350
|
-
bodyStructure: {
|
|
791
|
+
bodyStructure: {
|
|
792
|
+
partId: null,
|
|
793
|
+
type: "multipart/mixed",
|
|
794
|
+
subParts: [...htmlBody, ...attachments],
|
|
795
|
+
},
|
|
351
796
|
};
|
|
352
|
-
|
|
797
|
+
|
|
798
|
+
return pick(object, wanted);
|
|
353
799
|
}
|
|
354
800
|
|
|
355
|
-
async function emailGet(state: RequestState, args:
|
|
356
|
-
const owner = account(state, args);
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
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
|
+
|
|
360
815
|
const found = new Set(result.emails.map((row) => row.email.id));
|
|
816
|
+
|
|
361
817
|
return {
|
|
362
818
|
accountId: owner.id,
|
|
363
819
|
state: result.state,
|
|
364
|
-
list: await Promise.all(
|
|
820
|
+
list: await Promise.all(
|
|
821
|
+
result.emails.map((row) => emailObject(state.context.env, row, args))
|
|
822
|
+
),
|
|
365
823
|
notFound: ids.filter((id) => !found.has(id)),
|
|
366
824
|
};
|
|
367
825
|
}
|
|
368
826
|
|
|
369
|
-
/**
|
|
370
|
-
function
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
if (key === "keywords" && isRecord(value)) {
|
|
375
|
-
const keywords = Object.keys(value);
|
|
376
|
-
if (keywords.some((keyword) => keyword !== "$seen")) return { error: "Only the $seen keyword is stored" };
|
|
377
|
-
seen = value.$seen === true;
|
|
378
|
-
} else if (key === "keywords/$seen") {
|
|
379
|
-
seen = value === true;
|
|
380
|
-
} else if (key.startsWith("keywords/")) {
|
|
381
|
-
return { error: "Only the $seen keyword is stored" };
|
|
382
|
-
} else if (key === "mailboxIds" && isRecord(value)) {
|
|
383
|
-
const ids = Object.keys(value).filter((id) => value[id] === true);
|
|
384
|
-
if (ids.length !== 1) return { error: "An email is in exactly one mailbox" };
|
|
385
|
-
target = ids[0];
|
|
386
|
-
} else if (key.startsWith("mailboxIds/")) {
|
|
387
|
-
if (value === true) target = key.slice("mailboxIds/".length);
|
|
388
|
-
} else {
|
|
389
|
-
return { error: `${key} cannot be changed` };
|
|
390
|
-
}
|
|
391
|
-
}
|
|
392
|
-
return { seen, target };
|
|
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", "~"));
|
|
393
832
|
}
|
|
394
833
|
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
const
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
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);
|
|
424
1004
|
}
|
|
425
|
-
|
|
426
|
-
|
|
1005
|
+
|
|
1006
|
+
if (
|
|
1007
|
+
(args.update && Object.keys(args.update).length) ||
|
|
1008
|
+
args.destroy?.length
|
|
1009
|
+
) {
|
|
1010
|
+
scopes.push(MAIL_ORGANIZE_SCOPE);
|
|
427
1011
|
}
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
to: list(input.to),
|
|
431
|
-
cc: list(input.cc),
|
|
432
|
-
bcc: list(input.bcc),
|
|
433
|
-
subject: typeof input.subject === "string" ? input.subject : "",
|
|
434
|
-
bodyText: bodyText ?? "",
|
|
435
|
-
...(bodyHtml !== undefined ? { bodyHtml } : {}),
|
|
436
|
-
attachments,
|
|
437
|
-
};
|
|
1012
|
+
|
|
1013
|
+
return scopes;
|
|
438
1014
|
}
|
|
439
1015
|
|
|
440
|
-
async function emailSet(state: RequestState, args:
|
|
441
|
-
const owner = account(state, args);
|
|
1016
|
+
async function emailSet(state: RequestState, args: EmailSetArguments) {
|
|
1017
|
+
const owner = account(state, args.accountId);
|
|
442
1018
|
const stub = mailboxStub(state.context.env, owner.id);
|
|
443
1019
|
const oldState = await stub.jmapState();
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
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(),
|
|
457
1048
|
mailboxId: owner.id,
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
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
|
+
});
|
|
466
1110
|
continue;
|
|
467
1111
|
}
|
|
1112
|
+
|
|
468
1113
|
// Drafts are not stored: one is sent by EmailSubmission/set in the same request.
|
|
469
1114
|
const id = `draft-${crypto.randomUUID()}`;
|
|
470
1115
|
state.drafts.set(id, draft);
|
|
471
|
-
state.createdIds
|
|
472
|
-
created
|
|
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
|
+
});
|
|
473
1123
|
}
|
|
474
1124
|
|
|
475
|
-
const updated
|
|
476
|
-
const notUpdated
|
|
477
|
-
const reads:
|
|
1125
|
+
const updated = new Map<string, null>();
|
|
1126
|
+
const notUpdated = new Map<string, JsonObject>();
|
|
1127
|
+
const reads: [string, boolean][] = [];
|
|
478
1128
|
const moves = new Map<string, string[]>();
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
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
|
+
);
|
|
483
1140
|
continue;
|
|
484
1141
|
}
|
|
485
|
-
|
|
1142
|
+
|
|
1143
|
+
const { seen, target } = change.data;
|
|
1144
|
+
|
|
486
1145
|
if (seen !== undefined) reads.push([id, seen]);
|
|
1146
|
+
|
|
487
1147
|
if (target) moves.set(target, [...(moves.get(target) ?? []), id]);
|
|
488
|
-
updated
|
|
1148
|
+
updated.set(id, null);
|
|
489
1149
|
}
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
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" });
|
|
494
1161
|
}
|
|
495
1162
|
}
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
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
|
+
});
|
|
502
1180
|
}
|
|
503
1181
|
}
|
|
504
1182
|
|
|
505
1183
|
const destroyed: string[] = [];
|
|
506
|
-
const notDestroyed
|
|
507
|
-
const destroyIds = args.destroy
|
|
1184
|
+
const notDestroyed = new Map<string, JsonObject>();
|
|
1185
|
+
const destroyIds = args.destroy ?? [];
|
|
1186
|
+
|
|
508
1187
|
if (destroyIds.length) {
|
|
509
1188
|
const { emails } = await stub.jmapEmails(state.context.user.id, destroyIds);
|
|
510
1189
|
const inTrash = emails.filter((row) => row.mailboxId === "trash");
|
|
511
1190
|
const elsewhere = emails.filter((row) => row.mailboxId !== "trash");
|
|
1191
|
+
|
|
512
1192
|
// Mail goes to Trash first; destroying it there deletes its conversation.
|
|
513
|
-
if (elsewhere.length)
|
|
1193
|
+
if (elsewhere.length) {
|
|
1194
|
+
await stub.jmapMoveEmails(
|
|
1195
|
+
elsewhere.map((row) => row.email.id),
|
|
1196
|
+
"trash"
|
|
1197
|
+
);
|
|
1198
|
+
}
|
|
1199
|
+
|
|
514
1200
|
if (inTrash.length) {
|
|
515
|
-
await stub.permanentlyDeleteConversations([
|
|
1201
|
+
await stub.permanentlyDeleteConversations([
|
|
1202
|
+
...new Set(inTrash.map((row) => row.email.conversationId)),
|
|
1203
|
+
]);
|
|
516
1204
|
}
|
|
1205
|
+
|
|
517
1206
|
const found = new Set(emails.map((row) => row.email.id));
|
|
1207
|
+
|
|
518
1208
|
for (const id of destroyIds) {
|
|
519
1209
|
if (found.has(id)) destroyed.push(id);
|
|
520
|
-
else notDestroyed
|
|
1210
|
+
else notDestroyed.set(id, { type: "notFound" });
|
|
521
1211
|
}
|
|
522
1212
|
}
|
|
1213
|
+
|
|
523
1214
|
return {
|
|
524
1215
|
accountId: owner.id,
|
|
525
1216
|
oldState,
|
|
526
1217
|
newState: await stub.jmapState(),
|
|
527
|
-
created:
|
|
528
|
-
updated:
|
|
1218
|
+
created: setResult(created),
|
|
1219
|
+
updated: setResult(updated),
|
|
529
1220
|
destroyed: destroyed.length ? destroyed : null,
|
|
530
|
-
notCreated:
|
|
531
|
-
notUpdated:
|
|
532
|
-
notDestroyed:
|
|
1221
|
+
notCreated: setResult(notCreated),
|
|
1222
|
+
notUpdated: setResult(notUpdated),
|
|
1223
|
+
notDestroyed: setResult(notDestroyed),
|
|
533
1224
|
};
|
|
534
1225
|
}
|
|
535
1226
|
|
|
536
1227
|
// --------------------------------------------------- threads and identities
|
|
537
1228
|
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
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
|
+
|
|
543
1245
|
return {
|
|
544
1246
|
accountId: owner.id,
|
|
545
1247
|
state: result.state,
|
|
546
|
-
list: ids.flatMap((id) =>
|
|
547
|
-
|
|
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)),
|
|
548
1254
|
};
|
|
549
1255
|
}
|
|
550
1256
|
|
|
551
|
-
|
|
552
|
-
|
|
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
|
+
|
|
553
1269
|
const list = owner.canSend
|
|
554
|
-
? [
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
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
|
+
]
|
|
564
1282
|
: [];
|
|
565
|
-
|
|
1283
|
+
|
|
1284
|
+
const ids = args.ids ?? list.map((identity) => identity.id);
|
|
1285
|
+
|
|
566
1286
|
return {
|
|
567
1287
|
accountId: owner.id,
|
|
568
1288
|
state: "1",
|
|
569
|
-
list: list.
|
|
1289
|
+
list: list.flatMap((identity) =>
|
|
1290
|
+
ids.includes(identity.id) ? [pick(identity, args.properties)] : []
|
|
1291
|
+
),
|
|
570
1292
|
notFound: ids.filter((id) => id !== owner.id || !owner.canSend),
|
|
571
1293
|
};
|
|
572
1294
|
}
|
|
573
1295
|
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
1296
|
+
const submissionCreate = z.object({
|
|
1297
|
+
emailId: z.string(),
|
|
1298
|
+
identityId: z.string().optional(),
|
|
1299
|
+
});
|
|
1300
|
+
|
|
1301
|
+
const submissionSetArguments = z.object({
|
|
1302
|
+
accountId,
|
|
1303
|
+
create: setObjects,
|
|
1304
|
+
onSuccessDestroyEmail: z.array(z.string()).nullish(),
|
|
1305
|
+
onSuccessUpdateEmail: z.record(z.string(), z.json()).nullish(),
|
|
1306
|
+
});
|
|
1307
|
+
|
|
1308
|
+
const notADraft = {
|
|
1309
|
+
type: "invalidProperties",
|
|
1310
|
+
properties: ["emailId"],
|
|
1311
|
+
description: "Send an email created by Email/set earlier in the same request",
|
|
1312
|
+
};
|
|
1313
|
+
|
|
1314
|
+
/** Sends a draft as the account; a failure is the reason it was not sent. */
|
|
1315
|
+
async function sendDraft(
|
|
1316
|
+
state: RequestState,
|
|
1317
|
+
owner: JmapAccount,
|
|
1318
|
+
draft: Draft
|
|
1319
|
+
) {
|
|
1320
|
+
try {
|
|
1321
|
+
return await submitOutgoing({
|
|
1322
|
+
env: state.context.env,
|
|
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>();
|
|
579
1356
|
const sentDrafts = new Map<string, string>();
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
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));
|
|
583
1363
|
continue;
|
|
584
1364
|
}
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
const
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
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);
|
|
594
1376
|
continue;
|
|
595
1377
|
}
|
|
596
|
-
|
|
597
|
-
|
|
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
|
+
});
|
|
598
1388
|
continue;
|
|
599
1389
|
}
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
mailboxId: owner.id,
|
|
607
|
-
to: draft.to,
|
|
608
|
-
cc: draft.cc,
|
|
609
|
-
bcc: draft.bcc,
|
|
610
|
-
subject: draft.subject,
|
|
611
|
-
bodyText: draft.bodyText,
|
|
612
|
-
...(draft.bodyHtml !== undefined ? { bodyHtml: draft.bodyHtml } : {}),
|
|
613
|
-
attachments: draft.attachments.map((attachment) => ({
|
|
614
|
-
uploadId: attachment.uploadId,
|
|
615
|
-
disposition: attachment.disposition,
|
|
616
|
-
...(attachment.contentId ? { contentId: attachment.contentId } : {}),
|
|
617
|
-
})),
|
|
618
|
-
userId: state.context.user.id,
|
|
619
|
-
},
|
|
620
|
-
conversationId: `conv_${crypto.randomUUID().replaceAll("-", "")}`,
|
|
621
|
-
related: null,
|
|
622
|
-
forwarded: null,
|
|
623
|
-
includeRelatedContext: false,
|
|
624
|
-
fromAddress: owner.address,
|
|
625
|
-
fromName: owner.displayName,
|
|
626
|
-
defer: state.context.defer,
|
|
627
|
-
});
|
|
628
|
-
const id = `sub-${submission.email.id}`;
|
|
629
|
-
state.createdIds[creationId] = id;
|
|
630
|
-
sentDrafts.set(id, emailId!);
|
|
631
|
-
created[creationId] = {
|
|
632
|
-
id,
|
|
633
|
-
threadId: submission.email.conversationId,
|
|
634
|
-
emailId: submission.email.id,
|
|
635
|
-
sendAt: new Date().toISOString(),
|
|
636
|
-
undoStatus: "final",
|
|
637
|
-
};
|
|
638
|
-
} catch (error) {
|
|
639
|
-
notCreated[creationId] = {
|
|
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, {
|
|
640
1396
|
type: "forbiddenToSend",
|
|
641
|
-
description: error
|
|
642
|
-
};
|
|
1397
|
+
description: sent.error,
|
|
1398
|
+
});
|
|
1399
|
+
continue;
|
|
643
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
|
+
});
|
|
644
1412
|
}
|
|
1413
|
+
|
|
645
1414
|
// The sent copy is already in Sent; drafts were never stored, so the
|
|
646
1415
|
// follow-up Email/set only reports them gone.
|
|
647
|
-
const followUp = [
|
|
648
|
-
|
|
649
|
-
.
|
|
650
|
-
|
|
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
|
+
|
|
651
1429
|
if (followUp.length) {
|
|
652
1430
|
const stub = mailboxStub(state.context.env, owner.id);
|
|
653
1431
|
const current = await stub.jmapState();
|
|
654
|
-
state.after.push([
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
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
|
+
]);
|
|
659
1447
|
}
|
|
1448
|
+
|
|
660
1449
|
return {
|
|
661
1450
|
accountId: owner.id,
|
|
662
1451
|
oldState: "1",
|
|
663
1452
|
newState: "1",
|
|
664
|
-
created:
|
|
665
|
-
notCreated:
|
|
1453
|
+
created: setResult(created),
|
|
1454
|
+
notCreated: setResult(notCreated),
|
|
666
1455
|
updated: null,
|
|
667
1456
|
destroyed: null,
|
|
668
1457
|
notUpdated: null,
|
|
@@ -687,241 +1476,558 @@ function pushSubscriptionObject(row: PushSubscriptionRow) {
|
|
|
687
1476
|
};
|
|
688
1477
|
}
|
|
689
1478
|
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
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
|
+
});
|
|
697
1502
|
|
|
698
1503
|
function ownSubscriptions(state: RequestState) {
|
|
699
1504
|
return and(
|
|
700
1505
|
eq(jmapPushSubscriptions.userId, state.context.user.id),
|
|
701
|
-
eq(jmapPushSubscriptions.clientId, state.context.clientId)
|
|
1506
|
+
eq(jmapPushSubscriptions.clientId, state.context.clientId)
|
|
702
1507
|
);
|
|
703
1508
|
}
|
|
704
1509
|
|
|
705
|
-
|
|
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
|
+
) {
|
|
706
1519
|
const db = createDb(state.context.env.DB);
|
|
707
|
-
const ids = args.ids
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
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
|
+
|
|
711
1534
|
const found = new Set(rows.map((row) => row.id));
|
|
1535
|
+
|
|
712
1536
|
return {
|
|
713
1537
|
list: rows.map((row) => pick(pushSubscriptionObject(row), args.properties)),
|
|
714
1538
|
notFound: ids ? ids.filter((id) => !found.has(id)) : [],
|
|
715
1539
|
};
|
|
716
1540
|
}
|
|
717
1541
|
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
}
|
|
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
|
+
});
|
|
725
1549
|
|
|
726
|
-
function
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
return url.protocol === "https:" ? url.toString() : null;
|
|
731
|
-
} catch {
|
|
732
|
-
return null;
|
|
733
|
-
}
|
|
734
|
-
}
|
|
735
|
-
|
|
736
|
-
async function pushSubscriptionSet(state: RequestState, args: Args) {
|
|
1550
|
+
async function createPushSubscriptions(
|
|
1551
|
+
state: RequestState,
|
|
1552
|
+
create: JsonObject
|
|
1553
|
+
) {
|
|
737
1554
|
const db = createDb(state.context.env.DB);
|
|
738
|
-
|
|
739
|
-
const
|
|
740
|
-
const
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
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));
|
|
746
1578
|
continue;
|
|
747
1579
|
}
|
|
748
|
-
|
|
749
|
-
|
|
1580
|
+
|
|
1581
|
+
const subscription = parsed.data;
|
|
1582
|
+
|
|
1583
|
+
if (subscription.keys && !state.context.vapid) {
|
|
1584
|
+
notCreated.set(creationId, {
|
|
750
1585
|
type: "invalidProperties",
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
}
|
|
755
|
-
if (keys.p256dh && !state.context.vapid) {
|
|
756
|
-
notCreated[creationId] = { type: "invalidProperties", description: "Web Push is not configured on this server" };
|
|
757
|
-
continue;
|
|
758
|
-
}
|
|
759
|
-
const existing = await db.select({ id: jmapPushSubscriptions.id, deviceClientId: jmapPushSubscriptions.deviceClientId })
|
|
760
|
-
.from(jmapPushSubscriptions)
|
|
761
|
-
.where(eq(jmapPushSubscriptions.userId, state.context.user.id));
|
|
762
|
-
if (existing.filter((row) => row.deviceClientId !== input.deviceClientId).length >= MAX_PUSH_SUBSCRIPTIONS) {
|
|
763
|
-
notCreated[creationId] = { type: "overQuota", description: `At most ${MAX_PUSH_SUBSCRIPTIONS} push subscriptions` };
|
|
1586
|
+
properties: ["keys"],
|
|
1587
|
+
description: "Web Push is not configured on this server",
|
|
1588
|
+
});
|
|
764
1589
|
continue;
|
|
765
1590
|
}
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
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
|
+
});
|
|
771
1600
|
continue;
|
|
772
1601
|
}
|
|
1602
|
+
|
|
1603
|
+
devices.add(subscription.deviceClientId);
|
|
1604
|
+
|
|
773
1605
|
const row: PushSubscriptionRow = {
|
|
774
1606
|
id: crypto.randomUUID(),
|
|
775
1607
|
userId: state.context.user.id,
|
|
776
1608
|
clientId: state.context.clientId,
|
|
777
|
-
deviceClientId:
|
|
778
|
-
url,
|
|
779
|
-
|
|
1609
|
+
deviceClientId: subscription.deviceClientId,
|
|
1610
|
+
url: subscription.url,
|
|
1611
|
+
p256dh: subscription.keys?.p256dh ?? null,
|
|
1612
|
+
auth: subscription.keys?.auth ?? null,
|
|
780
1613
|
verificationCode: newVerificationCode(),
|
|
781
1614
|
verifiedAt: null,
|
|
782
|
-
expiresAt: subscriptionExpiry(
|
|
783
|
-
typesJson: types,
|
|
1615
|
+
expiresAt: subscriptionExpiry(subscription.expires),
|
|
1616
|
+
typesJson: subscription.types ?? null,
|
|
784
1617
|
createdAt: new Date(),
|
|
785
1618
|
};
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
)
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
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
|
+
);
|
|
799
1652
|
}
|
|
800
1653
|
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
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
|
+
|
|
805
1693
|
if (!row) {
|
|
806
|
-
notUpdated
|
|
1694
|
+
notUpdated.set(id, { type: "notFound" });
|
|
807
1695
|
continue;
|
|
808
1696
|
}
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
notUpdated[id] = { type: "invalidProperties", description: "The verification code does not match" };
|
|
1697
|
+
|
|
1698
|
+
const parsed = pushSubscriptionPatch.safeParse(input);
|
|
1699
|
+
|
|
1700
|
+
if (!parsed.success) {
|
|
1701
|
+
notUpdated.set(id, invalidProperties(parsed.error.issues));
|
|
815
1702
|
continue;
|
|
816
1703
|
}
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
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
|
+
});
|
|
822
1716
|
continue;
|
|
823
1717
|
}
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
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()),
|
|
827
1730
|
expiresAt,
|
|
828
|
-
typesJson: types,
|
|
829
|
-
})
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
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
|
+
);
|
|
834
1743
|
}
|
|
835
1744
|
|
|
836
|
-
const
|
|
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
|
+
|
|
837
1777
|
const removed = destroyIds.length
|
|
838
|
-
? await db
|
|
839
|
-
|
|
840
|
-
|
|
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 })
|
|
841
1787
|
: [];
|
|
842
|
-
|
|
843
|
-
const
|
|
844
|
-
|
|
845
|
-
|
|
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
|
+
|
|
846
1796
|
return {
|
|
847
|
-
created:
|
|
848
|
-
updated:
|
|
849
|
-
destroyed: destroyed.
|
|
850
|
-
notCreated:
|
|
851
|
-
notUpdated:
|
|
852
|
-
notDestroyed:
|
|
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),
|
|
853
1803
|
};
|
|
854
1804
|
}
|
|
855
1805
|
|
|
856
1806
|
// ----------------------------------------------------------------- dispatch
|
|
857
1807
|
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
const
|
|
881
|
-
|
|
1808
|
+
type MethodHandler = (
|
|
1809
|
+
state: RequestState,
|
|
1810
|
+
args: JsonObject,
|
|
1811
|
+
callId: string
|
|
1812
|
+
) => JsonObject | Promise<JsonObject>;
|
|
1813
|
+
|
|
1814
|
+
/**
|
|
1815
|
+
* A method: its arguments' schema, the mail scopes a call needs (each
|
|
1816
|
+
* method needs its own), and what it does with the parsed arguments.
|
|
1817
|
+
*/
|
|
1818
|
+
function method<Schema extends z.ZodType>(definition: {
|
|
1819
|
+
arguments: Schema;
|
|
1820
|
+
scopes: (args: z.output<Schema>) => readonly string[];
|
|
1821
|
+
run: (
|
|
1822
|
+
state: RequestState,
|
|
1823
|
+
args: z.output<Schema>,
|
|
1824
|
+
callId: string
|
|
1825
|
+
) => JsonObject | Promise<JsonObject>;
|
|
1826
|
+
}): MethodHandler {
|
|
1827
|
+
return (state, raw, callId) => {
|
|
1828
|
+
const args = parseArguments(definition.arguments, raw);
|
|
1829
|
+
|
|
1830
|
+
const missing = definition
|
|
1831
|
+
.scopes(args)
|
|
1832
|
+
.filter((scope) => !state.context.scopes.includes(scope));
|
|
1833
|
+
|
|
1834
|
+
if (missing.length) {
|
|
1835
|
+
throw new MethodError(
|
|
1836
|
+
"forbidden",
|
|
1837
|
+
`This token was not given ${missing.join(", ")}`
|
|
1838
|
+
);
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
return definition.run(state, args, callId);
|
|
1842
|
+
};
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1845
|
+
const reading = () => [MAIL_READ_SCOPE];
|
|
1846
|
+
|
|
1847
|
+
/** Foo/changes for the types that share the mailbox's one state. */
|
|
1848
|
+
const mailboxChanges = method({
|
|
1849
|
+
arguments: changesArguments,
|
|
1850
|
+
scopes: reading,
|
|
1851
|
+
run: async (state, args) => {
|
|
1852
|
+
const owner = account(state, args.accountId);
|
|
1853
|
+
|
|
1854
|
+
return changes(
|
|
1855
|
+
owner,
|
|
1856
|
+
args.sinceState,
|
|
1857
|
+
await mailboxStub(state.context.env, owner.id).jmapState()
|
|
1858
|
+
);
|
|
882
1859
|
},
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
1860
|
+
});
|
|
1861
|
+
|
|
1862
|
+
const methods = new Map<string, MethodHandler>([
|
|
1863
|
+
[
|
|
1864
|
+
"Core/echo",
|
|
1865
|
+
method({
|
|
1866
|
+
arguments: z.record(z.string(), z.json()),
|
|
1867
|
+
scopes: () => [],
|
|
1868
|
+
run: (_state, args) => args,
|
|
1869
|
+
}),
|
|
1870
|
+
],
|
|
1871
|
+
[
|
|
1872
|
+
"Mailbox/get",
|
|
1873
|
+
method({
|
|
1874
|
+
arguments: mailboxGetArguments,
|
|
1875
|
+
scopes: reading,
|
|
1876
|
+
run: mailboxGet,
|
|
1877
|
+
}),
|
|
1878
|
+
],
|
|
1879
|
+
[
|
|
1880
|
+
"Mailbox/query",
|
|
1881
|
+
method({
|
|
1882
|
+
arguments: mailboxQueryArguments,
|
|
1883
|
+
scopes: reading,
|
|
1884
|
+
run: mailboxQuery,
|
|
1885
|
+
}),
|
|
1886
|
+
],
|
|
1887
|
+
["Mailbox/changes", mailboxChanges],
|
|
1888
|
+
[
|
|
1889
|
+
"Email/query",
|
|
1890
|
+
method({
|
|
1891
|
+
arguments: emailQueryArguments,
|
|
1892
|
+
scopes: reading,
|
|
1893
|
+
run: emailQuery,
|
|
1894
|
+
}),
|
|
1895
|
+
],
|
|
1896
|
+
[
|
|
1897
|
+
"Email/get",
|
|
1898
|
+
method({ arguments: emailGetArguments, scopes: reading, run: emailGet }),
|
|
1899
|
+
],
|
|
1900
|
+
[
|
|
1901
|
+
"Email/set",
|
|
1902
|
+
method({
|
|
1903
|
+
arguments: emailSetArguments,
|
|
1904
|
+
scopes: emailSetScopes,
|
|
1905
|
+
run: emailSet,
|
|
1906
|
+
}),
|
|
1907
|
+
],
|
|
1908
|
+
["Email/changes", mailboxChanges],
|
|
1909
|
+
[
|
|
1910
|
+
"Thread/get",
|
|
1911
|
+
method({ arguments: threadGetArguments, scopes: reading, run: threadGet }),
|
|
1912
|
+
],
|
|
1913
|
+
["Thread/changes", mailboxChanges],
|
|
1914
|
+
[
|
|
1915
|
+
"SearchSnippet/get",
|
|
1916
|
+
method({
|
|
1917
|
+
arguments: z.object({ accountId, emailIds: idList }),
|
|
1918
|
+
scopes: reading,
|
|
1919
|
+
run: (state, args) => ({
|
|
1920
|
+
accountId: account(state, args.accountId).id,
|
|
1921
|
+
list: args.emailIds.map((emailId) => ({
|
|
1922
|
+
emailId,
|
|
1923
|
+
subject: null,
|
|
1924
|
+
preview: null,
|
|
1925
|
+
})),
|
|
1926
|
+
notFound: [],
|
|
1927
|
+
}),
|
|
1928
|
+
}),
|
|
1929
|
+
],
|
|
1930
|
+
[
|
|
1931
|
+
"Identity/get",
|
|
1932
|
+
method({
|
|
1933
|
+
arguments: identityGetArguments,
|
|
1934
|
+
scopes: reading,
|
|
1935
|
+
run: identityGet,
|
|
1936
|
+
}),
|
|
1937
|
+
],
|
|
1938
|
+
[
|
|
1939
|
+
"EmailSubmission/set",
|
|
1940
|
+
method({
|
|
1941
|
+
arguments: submissionSetArguments,
|
|
1942
|
+
scopes: () => [MAIL_SEND_SCOPE],
|
|
1943
|
+
run: submissionSet,
|
|
1944
|
+
}),
|
|
1945
|
+
],
|
|
1946
|
+
[
|
|
1947
|
+
"PushSubscription/get",
|
|
1948
|
+
method({
|
|
1949
|
+
arguments: pushSubscriptionGetArguments,
|
|
1950
|
+
scopes: reading,
|
|
1951
|
+
run: pushSubscriptionGet,
|
|
1952
|
+
}),
|
|
1953
|
+
],
|
|
1954
|
+
[
|
|
1955
|
+
"PushSubscription/set",
|
|
1956
|
+
method({
|
|
1957
|
+
arguments: pushSubscriptionSetArguments,
|
|
1958
|
+
scopes: reading,
|
|
1959
|
+
run: pushSubscriptionSet,
|
|
1960
|
+
}),
|
|
1961
|
+
],
|
|
1962
|
+
]);
|
|
1963
|
+
|
|
1964
|
+
/** RFC 8620 §3.4. */
|
|
1965
|
+
type JmapResponse = {
|
|
1966
|
+
methodResponses: Invocation[];
|
|
1967
|
+
createdIds?: Record<string, string>;
|
|
1968
|
+
sessionState: string;
|
|
887
1969
|
};
|
|
888
1970
|
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
1971
|
+
/** Runs a parsed request's method calls (RFC 8620 §3.3). */
|
|
1972
|
+
export async function runJmapRequest(
|
|
1973
|
+
context: JmapContext,
|
|
1974
|
+
request: JmapRequest
|
|
1975
|
+
) {
|
|
1976
|
+
if (!request.using.includes(CORE)) {
|
|
1977
|
+
throw new JmapError(
|
|
1978
|
+
"urn:ietf:params:jmap:error:unknownCapability",
|
|
1979
|
+
`${CORE} is required`
|
|
1980
|
+
);
|
|
895
1981
|
}
|
|
896
|
-
|
|
897
|
-
|
|
1982
|
+
|
|
1983
|
+
if (request.methodCalls.length > MAX_CALLS) {
|
|
1984
|
+
throw new JmapError(
|
|
1985
|
+
"urn:ietf:params:jmap:error:limit",
|
|
1986
|
+
`At most ${MAX_CALLS} method calls per request`
|
|
1987
|
+
);
|
|
898
1988
|
}
|
|
1989
|
+
|
|
899
1990
|
const state: RequestState = {
|
|
900
1991
|
context,
|
|
901
1992
|
responses: [],
|
|
902
|
-
createdIds:
|
|
1993
|
+
createdIds: new Map(Object.entries(request.createdIds ?? {})),
|
|
903
1994
|
drafts: new Map(),
|
|
904
1995
|
after: [],
|
|
905
1996
|
};
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
const [name, rawArgs, callId] = call as Invocation;
|
|
911
|
-
const method = methods[name];
|
|
1997
|
+
|
|
1998
|
+
for (const [name, rawArgs, callId] of request.methodCalls) {
|
|
1999
|
+
const handler = methods.get(name);
|
|
2000
|
+
|
|
912
2001
|
try {
|
|
913
|
-
if (!
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
2002
|
+
if (!handler) throw new MethodError("unknownMethod");
|
|
2003
|
+
|
|
2004
|
+
// oxlint-disable-next-line eslint/no-await-in-loop -- a call may reference the results of earlier ones (RFC 8620 §3.7), so calls run in order
|
|
2005
|
+
const result = await handler(
|
|
2006
|
+
state,
|
|
2007
|
+
resolveReferences(state, rawArgs),
|
|
2008
|
+
callId
|
|
2009
|
+
);
|
|
2010
|
+
|
|
2011
|
+
state.responses.push([name, result, callId], ...state.after.splice(0));
|
|
917
2012
|
} catch (error) {
|
|
918
2013
|
if (!(error instanceof MethodError)) throw error;
|
|
919
|
-
state.responses.push([
|
|
2014
|
+
state.responses.push([
|
|
2015
|
+
"error",
|
|
2016
|
+
{ type: error.type, description: error.message },
|
|
2017
|
+
callId,
|
|
2018
|
+
]);
|
|
920
2019
|
}
|
|
921
2020
|
}
|
|
922
|
-
|
|
2021
|
+
|
|
2022
|
+
const response: JmapResponse = {
|
|
923
2023
|
methodResponses: state.responses,
|
|
924
|
-
...(isRecord(body.createdIds) ? { createdIds: state.createdIds } : {}),
|
|
925
2024
|
sessionState: String(context.accounts.length),
|
|
926
2025
|
};
|
|
2026
|
+
|
|
2027
|
+
// Only a request that sent createdIds gets them back (§3.4).
|
|
2028
|
+
if (request.createdIds) {
|
|
2029
|
+
response.createdIds = Object.fromEntries(state.createdIds);
|
|
2030
|
+
}
|
|
2031
|
+
|
|
2032
|
+
return response;
|
|
927
2033
|
}
|