@open-workspace/email 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -20
- package/alchemy/index.ts +273 -0
- package/drizzle/mailbox/0000_puzzling_dracula.sql +149 -0
- package/drizzle/mailbox/0001_mute_jack_flag.sql +12 -0
- package/drizzle/mailbox/meta/0000_snapshot.json +1002 -0
- package/drizzle/mailbox/meta/0001_snapshot.json +1002 -0
- package/drizzle/mailbox/meta/_journal.json +20 -0
- package/drizzle/mailbox/migrations.js +12 -0
- package/index.ts +3 -1
- package/migrations/0000_dry_moon_knight.sql +77 -0
- package/migrations/meta/0000_snapshot.json +248 -106
- package/migrations/meta/_journal.json +2 -2
- package/package.json +74 -68
- package/shared/attachment-preview.ts +37 -27
- package/shared/folder-order.ts +106 -0
- package/shared/mail-authentication.ts +8 -3
- package/shared/mail-feedback.ts +18 -25
- package/shared/mail-headers.ts +114 -39
- package/shared/mail-import.ts +38 -0
- package/shared/mail-path.ts +42 -0
- package/shared/mail-received.ts +174 -31
- package/shared/mail-remote.ts +59 -2
- package/shared/mail-sender-intel.ts +22 -4
- package/shared/mail.ts +78 -26
- package/shared/module.ts +33 -0
- package/shared/office-preview.ts +14 -2
- package/shared/pdfjs-assets.ts +35 -0
- package/shared/permissions.ts +73 -0
- package/shared/webhooks.ts +41 -0
- package/src/admin/blocked-senders.tsx +189 -0
- package/src/client.tsx +97 -0
- package/src/lib/mail-api.ts +9 -0
- package/src/mail/attachment-preview-dialog.tsx +161 -0
- package/src/mail/blocked-senders.tsx +138 -0
- package/src/mail/compose-window-chrome.tsx +194 -0
- package/src/mail/compose-window.tsx +486 -0
- package/src/mail/composer-asset-bookmarks.ts +409 -0
- package/src/mail/composer-asset.tsx +229 -0
- package/src/mail/composer-attachment-list.tsx +138 -0
- package/src/mail/composer-editor-document.ts +65 -0
- package/src/mail/composer-editor.tsx +284 -0
- package/src/mail/composer-linked-attachment-text.ts +12 -0
- package/src/mail/composer-recipient-fields.tsx +165 -0
- package/src/mail/composer-recipients.ts +208 -0
- package/src/mail/composer-session.ts +562 -0
- package/src/mail/composer-toolbar.tsx +303 -0
- package/src/mail/composer-upload-client.ts +105 -0
- package/src/mail/composer-upload-progress.ts +53 -0
- package/src/mail/conversation-list.tsx +550 -0
- package/src/mail/conversation-loading-skeleton.tsx +119 -0
- package/src/mail/conversation-message.tsx +346 -0
- package/src/mail/conversation-reply.tsx +470 -0
- package/src/mail/conversation-selection-toolbar.tsx +322 -0
- package/src/mail/conversation-view.tsx +437 -0
- package/src/mail/delivery-indicator.tsx +272 -0
- package/src/mail/email-html-body.tsx +203 -0
- package/src/mail/folder-glyph.tsx +46 -0
- package/src/mail/folder-manager.tsx +532 -0
- package/src/mail/format-bytes.ts +7 -0
- package/src/mail/mail-app-bar.tsx +253 -0
- package/src/mail/mail-background.tsx +12 -0
- package/src/mail/mail-dock.tsx +137 -0
- package/src/mail/mail-folders.ts +44 -0
- package/src/mail/mail-layout.css +236 -0
- package/src/mail/mail-location.ts +73 -0
- package/src/mail/mail-mailbox-sheet.tsx +275 -0
- package/src/mail/mail-nav-rail.tsx +129 -0
- package/src/mail/mail-nav.tsx +324 -0
- package/src/mail/mail-prefetch.ts +59 -0
- package/src/mail/mail-primitives.tsx +66 -0
- package/src/mail/mail-queries.ts +209 -0
- package/src/mail/mail-query-cache.ts +486 -0
- package/src/mail/mail-seed.ts +47 -0
- package/src/mail/mail-shell.tsx +126 -0
- package/src/mail/mailbox-ai-settings.tsx +185 -0
- package/src/mail/mailbox-realtime.tsx +251 -0
- package/src/mail/mailbox-route.tsx +15 -0
- package/src/mail/message-actions.tsx +353 -0
- package/src/mail/message-attachments.tsx +200 -0
- package/src/mail/message-format.ts +75 -0
- package/src/mail/message-header.tsx +260 -0
- package/src/mail/message-translation.tsx +225 -0
- package/src/mail/original-message-sheet.tsx +619 -0
- package/src/mail/original-message.ts +191 -0
- package/src/mail/outbound-notification.ts +53 -0
- package/src/mail/pane-splitter.tsx +117 -0
- package/src/mail/pdf-preview-toolbar.tsx +152 -0
- package/src/mail/pdf-preview.css +44 -0
- package/src/mail/pdf-preview.tsx +156 -0
- package/src/mail/pdf-translation-layout.ts +95 -0
- package/src/mail/print-message.ts +92 -0
- package/src/mail/reader-pane.tsx +535 -0
- package/src/mail/recipient-combobox.tsx +335 -0
- package/src/mail/recipient-field-row.tsx +34 -0
- package/src/mail/reply-to-warning.tsx +50 -0
- package/src/mail/sanitize-email-html.ts +430 -0
- package/src/mail/sender-actions.tsx +149 -0
- package/src/mail/sender-authentication.tsx +485 -0
- package/src/mail/sender-dialogs.tsx +384 -0
- package/src/mail/sender-security.tsx +545 -0
- package/src/mail/toolbar-tooltip.tsx +29 -0
- package/src/mail/translation-html.ts +49 -0
- package/src/mail/translation-language.ts +21 -0
- package/src/mail/types.ts +53 -0
- package/src/mail/unread-document-indicator.tsx +60 -0
- package/src/mail/use-compose-submission.ts +208 -0
- package/src/mail/use-composer-attachment-preflight.ts +184 -0
- package/src/mail/use-composer-submission.ts +117 -0
- package/src/mail/use-conversation-selection.ts +186 -0
- package/src/mail/use-mail-controller.ts +427 -0
- package/src/mail/use-mail-data.ts +279 -0
- package/src/mail/use-mail-safety.ts +155 -0
- package/src/mail/use-mail-send.ts +142 -0
- package/src/mail/use-pdf-translation-overlay.ts +156 -0
- package/src/mail/use-pdf-translation.ts +100 -0
- package/src/mail/use-pdf-viewer.ts +215 -0
- package/src/mail/use-reply-submission.ts +114 -0
- package/src/mail/use-sanitized-email-html.ts +20 -0
- package/src/mail/use-visible-message-read.ts +138 -0
- package/src/pwa/push-subscription.ts +151 -0
- package/src/settings/mail-apps-page.tsx +235 -0
- package/src/settings/notifications-page.tsx +291 -0
- package/worker/admin/blocked-sender-routes.ts +166 -0
- package/worker/admin/schemas.ts +11 -0
- package/worker/bindings.d.ts +14 -10
- package/worker/db/schema.ts +90 -34
- package/worker/jmap/eventsource.ts +169 -0
- package/worker/jmap/methods.ts +1716 -361
- package/worker/jmap/push-types.ts +27 -0
- package/worker/jmap/push.ts +207 -0
- package/worker/jmap/routes.ts +448 -86
- package/worker/mail/access.ts +258 -21
- package/worker/mail/ai-classification.ts +36 -20
- package/worker/mail/ai-translation.ts +13 -6
- package/worker/mail/auth-headers.ts +395 -137
- package/worker/mail/bimi.ts +200 -73
- package/worker/mail/bootstrap.ts +79 -0
- package/worker/mail/capped-body.ts +36 -0
- package/worker/mail/classification-signals.ts +35 -25
- package/worker/mail/conversation-cursor.ts +30 -19
- package/worker/mail/delivery-events.ts +88 -62
- package/worker/mail/delivery-facts.ts +46 -10
- package/worker/mail/demo-routes.ts +34 -10
- package/worker/mail/doh.ts +62 -23
- package/worker/mail/downloads.ts +75 -40
- package/worker/mail/edge-cache.ts +155 -0
- package/worker/mail/header-metadata.ts +84 -52
- package/worker/mail/impersonation.ts +160 -38
- package/worker/mail/import-routes.ts +313 -0
- package/worker/mail/inbound-delivery.ts +19 -9
- package/worker/mail/inbound-threading.ts +18 -8
- package/worker/mail/inbound.ts +82 -40
- package/worker/mail/ip-intel.ts +110 -27
- package/worker/mail/isolate-cache.ts +35 -0
- package/worker/mail/link-domains.ts +29 -7
- package/worker/mail/mailbox-deletion.ts +10 -4
- package/worker/mail/mailbox-directory.ts +16 -6
- package/worker/mail/mailing-list.ts +94 -39
- package/worker/mail/message-security.ts +90 -15
- package/worker/mail/message-view.ts +18 -6
- package/worker/mail/office-conversion.ts +31 -9
- package/worker/mail/office-preview-container.ts +40 -13
- package/worker/mail/office-preview-queue.ts +76 -32
- package/worker/mail/org-domain.ts +8 -1
- package/worker/mail/outbound-content.ts +71 -26
- package/worker/mail/outbound-delivery.ts +31 -17
- package/worker/mail/outbound-service.ts +48 -30
- package/worker/mail/outbound-threading.ts +30 -17
- package/worker/mail/outbound.ts +97 -70
- package/worker/mail/outgoing-context.ts +25 -15
- package/worker/mail/participants.ts +44 -29
- package/worker/mail/push-notifications.ts +283 -171
- package/worker/mail/quote-parser.ts +21 -10
- package/worker/mail/r2-presigned-urls.ts +31 -25
- package/worker/mail/receive.ts +23 -11
- package/worker/mail/recipients.ts +6 -1
- package/worker/mail/remote-proxy.ts +187 -31
- package/worker/mail/remote-routes.ts +87 -0
- package/worker/mail/remote-token.ts +104 -0
- package/worker/mail/repeat.ts +19 -0
- package/worker/mail/reply-plan.ts +62 -33
- package/worker/mail/rfc.ts +32 -7
- package/worker/mail/routes.ts +871 -542
- package/worker/mail/safety-routes.ts +329 -202
- package/worker/mail/schemas.ts +84 -105
- package/worker/mail/search.ts +1 -0
- package/worker/mail/security-settings.ts +41 -9
- package/worker/mail/sender-intel.ts +206 -51
- package/worker/mail/spamhaus.ts +92 -45
- package/worker/mail/unsubscribe.ts +76 -18
- package/worker/mail/uploads.ts +153 -91
- package/worker/mail/webhook-source.ts +35 -12
- package/worker/mail/workspace-safety.ts +97 -38
- package/worker/mailbox/demo-html.ts +7 -7
- package/worker/mailbox/demo-seed.ts +10 -44
- package/worker/mailbox/demo.ts +597 -227
- package/worker/mailbox/email-index.ts +53 -0
- package/worker/mailbox/folder-model.ts +53 -17
- package/worker/mailbox/import-placement.ts +88 -0
- package/worker/mailbox/inbox-counts.ts +106 -0
- package/worker/mailbox/index.ts +1761 -737
- package/worker/mailbox/jmap-store.ts +139 -35
- package/worker/mailbox/model.ts +7 -14
- package/worker/mailbox/office-preview-jobs.ts +56 -25
- package/worker/mailbox/schema.ts +87 -66
- package/worker/mailbox/senders.ts +176 -70
- package/worker/mcp/mail-action-tools.ts +128 -87
- package/worker/mcp/mail-compose-tools.ts +133 -82
- package/worker/mcp/mail-query-tools.ts +120 -71
- package/worker/mcp/mail-safety-tools.ts +321 -248
- package/worker/mcp/schemas.ts +43 -0
- package/worker/mcp/tools.ts +13 -10
- package/worker/module.ts +43 -18
- package/worker/sql.d.ts +8 -0
- package/alchemy.ts +0 -126
- package/containers/office-preview/Dockerfile +0 -10
- package/migrations/0000_email.sql +0 -53
- package/shared/mail-rules.ts +0 -156
- package/worker/admin/report-routes.ts +0 -164
- package/worker/mail/reported-messages.ts +0 -68
- package/worker/mailbox/legacy-migrations.ts +0 -41
- package/worker/mailbox/migrations.ts +0 -10
- package/worker/mailbox/rules.ts +0 -110
package/worker/jmap/methods.ts
CHANGED
|
@@ -1,10 +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";
|
|
7
|
+
import { and, eq, inArray } from "drizzle-orm";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
|
|
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";
|
|
16
|
+
import { jmapPushSubscriptions } from "../db/schema";
|
|
17
|
+
import { submitOutgoing } from "../mail/outbound-service";
|
|
18
|
+
import { composeSchema } from "../mail/schemas";
|
|
19
|
+
import { describeComposerUpload, UploadValidationError } from "../mail/uploads";
|
|
1
20
|
import { mailboxStub } from "../mailbox";
|
|
2
|
-
import type { Email } from "../mailbox/schema";
|
|
3
21
|
import type { JmapEmailFilter, JmapMailboxRow } from "../mailbox/jmap-store";
|
|
4
|
-
import {
|
|
22
|
+
import type { Email } from "../mailbox/schema";
|
|
23
|
+
import {
|
|
24
|
+
newVerificationCode,
|
|
25
|
+
sendVerification,
|
|
26
|
+
subscriptionExpiry,
|
|
27
|
+
} from "./push";
|
|
28
|
+
import type { PushVapid } from "./push";
|
|
5
29
|
|
|
6
30
|
const CORE = "urn:ietf:params:jmap:core";
|
|
7
31
|
const MAX_OBJECTS = 500;
|
|
32
|
+
const MAX_CALLS = 32;
|
|
8
33
|
|
|
9
34
|
export type JmapAccount = {
|
|
10
35
|
id: string;
|
|
@@ -19,118 +44,347 @@ export type JmapAccount = {
|
|
|
19
44
|
export type JmapContext = {
|
|
20
45
|
env: Env;
|
|
21
46
|
user: { id: string; name: string };
|
|
47
|
+
/** The OAuth client the token was issued to; push subscriptions belong to it. */
|
|
48
|
+
clientId: string;
|
|
49
|
+
/** The token's mail scopes; each method needs its own (`scopes` of its definition). */
|
|
50
|
+
scopes: readonly string[];
|
|
51
|
+
/** Signs pushes to Web Push services; null when push is not configured. */
|
|
52
|
+
vapid: PushVapid | null;
|
|
22
53
|
accounts: JmapAccount[];
|
|
23
54
|
requestUrl: string;
|
|
24
55
|
defer: (task: Promise<unknown>) => void;
|
|
25
56
|
};
|
|
26
57
|
|
|
27
|
-
type
|
|
28
|
-
|
|
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];
|
|
29
74
|
|
|
30
75
|
/** A request-level error (RFC 8620 §3.6.1), answered as a problem document. */
|
|
31
76
|
export class JmapError extends Error {
|
|
32
|
-
constructor(
|
|
77
|
+
constructor(
|
|
78
|
+
readonly type: string,
|
|
79
|
+
message: string
|
|
80
|
+
) {
|
|
33
81
|
super(message);
|
|
34
82
|
}
|
|
35
83
|
}
|
|
36
84
|
|
|
37
|
-
/**
|
|
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. */
|
|
38
102
|
class MethodError extends Error {
|
|
39
|
-
constructor(
|
|
103
|
+
constructor(
|
|
104
|
+
readonly type: MethodErrorType,
|
|
105
|
+
message?: string
|
|
106
|
+
) {
|
|
40
107
|
super(message ?? type);
|
|
41
108
|
}
|
|
42
109
|
}
|
|
43
110
|
|
|
44
|
-
/**
|
|
111
|
+
/** Uploaded blobs are named after their upload: `upl~<upload id>`. */
|
|
112
|
+
export const UPLOAD_BLOB = /^upl~(upl_[a-f0-9]{32})$/u;
|
|
113
|
+
|
|
114
|
+
/** An attachment of a draft: bytes from /jmap/upload. */
|
|
115
|
+
type DraftAttachment = {
|
|
116
|
+
uploadId: string;
|
|
117
|
+
name: string;
|
|
118
|
+
type: string;
|
|
119
|
+
disposition: "attachment" | "inline";
|
|
120
|
+
contentId: string | undefined;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* A draft from Email/set create; it lives only for the request that sends
|
|
125
|
+
* it. It holds the message as the mail app's composer would send it.
|
|
126
|
+
*/
|
|
45
127
|
type Draft = {
|
|
46
128
|
accountId: string;
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
bcc: string[];
|
|
50
|
-
subject: string;
|
|
51
|
-
bodyText: string;
|
|
52
|
-
bodyHtml?: string;
|
|
129
|
+
compose: z.output<typeof composeSchema>;
|
|
130
|
+
attachments: DraftAttachment[];
|
|
53
131
|
};
|
|
54
132
|
|
|
133
|
+
/** The Email property a composer field comes from. */
|
|
134
|
+
function draftProperty(field: string) {
|
|
135
|
+
if (field === "bodyText") return "textBody";
|
|
136
|
+
|
|
137
|
+
if (field === "bodyHtml") return "htmlBody";
|
|
138
|
+
|
|
139
|
+
return field;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* A composer issue, at the Email property it is about. Issues about the
|
|
144
|
+
* message as a whole are about its recipients.
|
|
145
|
+
*/
|
|
146
|
+
function draftIssue(issue: Issue): Issue {
|
|
147
|
+
const [field = "to", ...rest] = issue.path;
|
|
148
|
+
|
|
149
|
+
return { ...issue, path: [draftProperty(String(field)), ...rest] };
|
|
150
|
+
}
|
|
151
|
+
|
|
55
152
|
type RequestState = {
|
|
56
153
|
context: JmapContext;
|
|
57
154
|
responses: Invocation[];
|
|
58
|
-
createdIds:
|
|
155
|
+
createdIds: Map<string, string>;
|
|
59
156
|
drafts: Map<string, Draft>;
|
|
60
157
|
/** Responses a method adds after its own, e.g. an implicit Email/set. */
|
|
61
158
|
after: Invocation[];
|
|
62
159
|
};
|
|
63
160
|
|
|
64
|
-
|
|
65
|
-
|
|
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);
|
|
66
164
|
}
|
|
67
165
|
|
|
68
166
|
// ---------------------------------------------------------------- references
|
|
69
167
|
|
|
70
168
|
/** RFC 8620 §3.7: a JSON Pointer where `*` maps over an array. */
|
|
71
|
-
function evaluatePointer(value:
|
|
169
|
+
function evaluatePointer(value: Json, path: string): Json {
|
|
72
170
|
if (path === "") return value;
|
|
73
|
-
|
|
171
|
+
|
|
172
|
+
const [head = "", ...rest] = path
|
|
173
|
+
.slice(1)
|
|
174
|
+
.split("/")
|
|
175
|
+
.map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
|
|
176
|
+
|
|
74
177
|
const tail = rest.length ? `/${rest.join("/")}` : "";
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
return
|
|
79
|
-
|
|
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);
|
|
80
195
|
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
196
|
+
|
|
197
|
+
throw new MethodError(
|
|
198
|
+
"invalidResultReference",
|
|
199
|
+
`Path ${path} does not resolve`
|
|
200
|
+
);
|
|
84
201
|
}
|
|
85
202
|
|
|
86
|
-
|
|
87
|
-
|
|
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
|
+
|
|
88
212
|
for (const [key, value] of Object.entries(args)) {
|
|
89
213
|
if (!key.startsWith("#")) {
|
|
90
214
|
resolved[key] = value;
|
|
91
215
|
continue;
|
|
92
216
|
}
|
|
217
|
+
|
|
93
218
|
const name = key.slice(1);
|
|
94
|
-
|
|
95
|
-
if (
|
|
96
|
-
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
|
+
);
|
|
97
234
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
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);
|
|
101
250
|
}
|
|
251
|
+
|
|
102
252
|
return resolved;
|
|
103
253
|
}
|
|
104
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
|
+
|
|
105
339
|
// ------------------------------------------------------------------ helpers
|
|
106
340
|
|
|
107
|
-
|
|
108
|
-
|
|
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
|
+
|
|
109
349
|
if (!found) throw new MethodError("accountNotFound");
|
|
350
|
+
|
|
110
351
|
return found;
|
|
111
352
|
}
|
|
112
353
|
|
|
113
|
-
function
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
if (
|
|
118
|
-
return value as string[];
|
|
119
|
-
}
|
|
354
|
+
function pick<Value extends Json>(
|
|
355
|
+
object: Record<string, Value>,
|
|
356
|
+
wanted: readonly string[] | null | undefined
|
|
357
|
+
) {
|
|
358
|
+
if (!wanted) return object;
|
|
120
359
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
360
|
+
return Object.fromEntries(
|
|
361
|
+
Object.entries(object).filter(
|
|
362
|
+
([key]) => key === "id" || wanted.includes(key)
|
|
363
|
+
)
|
|
364
|
+
);
|
|
124
365
|
}
|
|
125
366
|
|
|
126
367
|
/** We cannot list changes, only say whether anything changed. */
|
|
127
|
-
function changes(
|
|
368
|
+
function changes(owner: JmapAccount, sinceState: string, state: string) {
|
|
128
369
|
if (sinceState !== state) throw new MethodError("cannotCalculateChanges");
|
|
129
|
-
|
|
370
|
+
|
|
371
|
+
return {
|
|
372
|
+
accountId: owner.id,
|
|
373
|
+
oldState: state,
|
|
374
|
+
newState: state,
|
|
375
|
+
hasMoreChanges: false,
|
|
376
|
+
created: [],
|
|
377
|
+
updated: [],
|
|
378
|
+
destroyed: [],
|
|
379
|
+
};
|
|
130
380
|
}
|
|
131
381
|
|
|
132
|
-
const addresses = (
|
|
133
|
-
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;
|
|
134
388
|
|
|
135
389
|
// ------------------------------------------------------------------ mailbox
|
|
136
390
|
|
|
@@ -160,86 +414,217 @@ function mailboxObject(row: JmapMailboxRow, canSend: boolean) {
|
|
|
160
414
|
};
|
|
161
415
|
}
|
|
162
416
|
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
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);
|
|
167
435
|
const byId = new Map(mailboxes.map((row) => [row.id, row]));
|
|
436
|
+
|
|
168
437
|
return {
|
|
169
438
|
accountId: owner.id,
|
|
170
439
|
state: mailboxState,
|
|
171
440
|
list: ids.flatMap((id) => {
|
|
172
441
|
const row = byId.get(id);
|
|
173
|
-
|
|
442
|
+
|
|
443
|
+
return row
|
|
444
|
+
? [pick(mailboxObject(row, owner.canSend), args.properties)]
|
|
445
|
+
: [];
|
|
174
446
|
}),
|
|
175
447
|
notFound: ids.filter((id) => !byId.has(id)),
|
|
176
448
|
};
|
|
177
449
|
}
|
|
178
450
|
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
}
|
|
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
|
+
});
|
|
189
461
|
|
|
190
|
-
|
|
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
|
+
);
|
|
191
482
|
|
|
192
|
-
function emailFilter(value: unknown): JmapEmailFilter {
|
|
193
|
-
if (value == null) return {};
|
|
194
|
-
if (!isRecord(value)) throw new MethodError("unsupportedFilter");
|
|
195
|
-
if ("operator" in value) {
|
|
196
|
-
if (value.operator !== "AND" || !Array.isArray(value.conditions)) {
|
|
197
|
-
throw new MethodError("unsupportedFilter", "Only AND filters are supported");
|
|
198
|
-
}
|
|
199
|
-
return Object.assign({}, ...value.conditions.map(emailFilter));
|
|
200
|
-
}
|
|
201
|
-
const supported = ["inMailbox", "inMailboxOtherThan", "before", "after", "text", "from", "to", "subject", "hasKeyword", "notKeyword", "hasAttachment"];
|
|
202
|
-
const unknown = Object.keys(value).filter((key) => !supported.includes(key));
|
|
203
|
-
if (unknown.length) throw new MethodError("unsupportedFilter", `Unsupported filter: ${unknown.join(", ")}`);
|
|
204
|
-
for (const keyword of [value.hasKeyword, value.notKeyword]) {
|
|
205
|
-
if (keyword !== undefined && keyword !== "$seen") {
|
|
206
|
-
throw new MethodError("unsupportedFilter", "Only the $seen keyword is supported");
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
483
|
return {
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
...(typeof value.to === "string" ? { to: value.to } : {}),
|
|
217
|
-
...(typeof value.subject === "string" ? { subject: value.subject } : {}),
|
|
218
|
-
...(typeof value.hasKeyword === "string" ? { hasKeyword: value.hasKeyword } : {}),
|
|
219
|
-
...(typeof value.notKeyword === "string" ? { notKeyword: value.notKeyword } : {}),
|
|
220
|
-
...(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,
|
|
221
490
|
};
|
|
222
491
|
}
|
|
223
492
|
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
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
|
+
);
|
|
230
595
|
}
|
|
231
|
-
}
|
|
232
|
-
const ascending = isRecord(sort[0]) && sort[0].isAscending === true;
|
|
233
|
-
const position = Math.max(0, Number(args.position ?? 0) || 0);
|
|
234
|
-
const limit = Math.min(MAX_OBJECTS, Math.max(0, Number(args.limit ?? 100) || 100));
|
|
235
|
-
const result = await mailboxStub(state.context.env, owner.id).jmapQueryEmails({
|
|
236
|
-
userId: state.context.user.id,
|
|
237
|
-
filter: emailFilter(args.filter),
|
|
238
|
-
ascending,
|
|
239
|
-
position,
|
|
240
|
-
limit,
|
|
241
|
-
collapseThreads: args.collapseThreads === true,
|
|
242
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
|
+
|
|
243
628
|
return {
|
|
244
629
|
accountId: owner.id,
|
|
245
630
|
queryState: result.state,
|
|
@@ -252,25 +637,80 @@ async function emailQuery(state: RequestState, args: Args) {
|
|
|
252
637
|
}
|
|
253
638
|
|
|
254
639
|
const defaultEmailProperties = [
|
|
255
|
-
"id",
|
|
256
|
-
"
|
|
257
|
-
"
|
|
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",
|
|
258
664
|
];
|
|
259
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
|
+
|
|
260
678
|
async function emailObject(
|
|
261
679
|
env: Env,
|
|
262
680
|
row: { email: Email; mailboxId: string; seen: boolean },
|
|
263
|
-
args:
|
|
681
|
+
args: EmailGetArguments
|
|
264
682
|
) {
|
|
265
683
|
const { email } = row;
|
|
266
684
|
const raw = `raw~${email.id}`;
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
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
|
+
|
|
271
699
|
const htmlBody = email.bodyHtmlR2Key
|
|
272
|
-
? [
|
|
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
|
+
]
|
|
273
712
|
: textBody;
|
|
713
|
+
|
|
274
714
|
const attachments = email.attachmentsJson.map((attachment) => ({
|
|
275
715
|
partId: `att-${attachment.id}`,
|
|
276
716
|
blobId: `att~${email.id}~${attachment.id}`,
|
|
@@ -281,33 +721,55 @@ async function emailObject(
|
|
|
281
721
|
disposition: attachment.disposition,
|
|
282
722
|
cid: attachment.contentId,
|
|
283
723
|
}));
|
|
284
|
-
|
|
285
|
-
const
|
|
724
|
+
|
|
725
|
+
const wanted = args.properties ?? defaultEmailProperties;
|
|
726
|
+
const maxBytes = args.maxBodyValueBytes ?? 0;
|
|
727
|
+
|
|
286
728
|
const bodyValue = (value: string) => ({
|
|
287
|
-
value:
|
|
729
|
+
value:
|
|
730
|
+
maxBytes && value.length > maxBytes ? value.slice(0, maxBytes) : value,
|
|
288
731
|
isEncodingProblem: false,
|
|
289
732
|
isTruncated: Boolean(maxBytes && value.length > maxBytes),
|
|
290
733
|
});
|
|
734
|
+
|
|
291
735
|
const bodyValues: Record<string, ReturnType<typeof bodyValue>> = {};
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
const
|
|
295
|
-
|
|
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
|
+
|
|
296
748
|
if (wantHtml && email.bodyHtmlR2Key) {
|
|
297
749
|
const object = await env.MAIL_STORAGE.get(email.bodyHtmlR2Key);
|
|
298
750
|
bodyValues.html = bodyValue(object ? await object.text() : "");
|
|
299
751
|
}
|
|
300
752
|
}
|
|
753
|
+
|
|
301
754
|
const timestamp = email.timelineAt.toISOString();
|
|
755
|
+
const keywords: Record<string, true> = row.seen ? { $seen: true } : {};
|
|
756
|
+
|
|
302
757
|
const object = {
|
|
303
758
|
id: email.id,
|
|
304
759
|
blobId: raw,
|
|
305
760
|
threadId: email.conversationId,
|
|
306
761
|
mailboxIds: { [row.mailboxId]: true },
|
|
307
|
-
keywords
|
|
308
|
-
size:
|
|
762
|
+
keywords,
|
|
763
|
+
size:
|
|
764
|
+
(email.bodyText?.length ?? 0) +
|
|
765
|
+
email.attachmentsJson.reduce(
|
|
766
|
+
(total, attachment) => total + attachment.size,
|
|
767
|
+
0
|
|
768
|
+
),
|
|
309
769
|
receivedAt: timestamp,
|
|
310
|
-
messageId: email.messageIdHeader
|
|
770
|
+
messageId: email.messageIdHeader
|
|
771
|
+
? [email.messageIdHeader.replaceAll(/^<|>$/gu, "")]
|
|
772
|
+
: null,
|
|
311
773
|
inReplyTo: email.inReplyToJson?.length ? email.inReplyToJson : null,
|
|
312
774
|
references: email.referencesJson?.length ? email.referencesJson : null,
|
|
313
775
|
sender: null,
|
|
@@ -318,287 +780,678 @@ async function emailObject(
|
|
|
318
780
|
replyTo: addresses(email.replyToJson),
|
|
319
781
|
subject: email.subject,
|
|
320
782
|
sentAt: timestamp,
|
|
321
|
-
hasAttachment: attachments.some(
|
|
783
|
+
hasAttachment: attachments.some(
|
|
784
|
+
(attachment) => attachment.disposition === "attachment"
|
|
785
|
+
),
|
|
322
786
|
preview: email.preview,
|
|
323
787
|
bodyValues,
|
|
324
788
|
textBody,
|
|
325
789
|
htmlBody,
|
|
326
790
|
attachments,
|
|
327
|
-
bodyStructure: {
|
|
791
|
+
bodyStructure: {
|
|
792
|
+
partId: null,
|
|
793
|
+
type: "multipart/mixed",
|
|
794
|
+
subParts: [...htmlBody, ...attachments],
|
|
795
|
+
},
|
|
328
796
|
};
|
|
329
|
-
|
|
797
|
+
|
|
798
|
+
return pick(object, wanted);
|
|
330
799
|
}
|
|
331
800
|
|
|
332
|
-
async function emailGet(state: RequestState, args:
|
|
333
|
-
const owner = account(state, args);
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
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
|
+
|
|
337
815
|
const found = new Set(result.emails.map((row) => row.email.id));
|
|
816
|
+
|
|
338
817
|
return {
|
|
339
818
|
accountId: owner.id,
|
|
340
819
|
state: result.state,
|
|
341
|
-
list: await Promise.all(
|
|
820
|
+
list: await Promise.all(
|
|
821
|
+
result.emails.map((row) => emailObject(state.context.env, row, args))
|
|
822
|
+
),
|
|
342
823
|
notFound: ids.filter((id) => !found.has(id)),
|
|
343
824
|
};
|
|
344
825
|
}
|
|
345
826
|
|
|
346
|
-
/**
|
|
347
|
-
function
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
827
|
+
/** A patch key is a JSON Pointer into the email (RFC 8620 §5.3). */
|
|
828
|
+
function patchPath(key: string) {
|
|
829
|
+
return key
|
|
830
|
+
.split("/")
|
|
831
|
+
.map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/** Keywords and mailboxIds map their names to true (RFC 8621 §4.1.1). */
|
|
835
|
+
const trueSet = z.record(z.string(), z.literal(true));
|
|
836
|
+
|
|
837
|
+
/** One entry of a set: true adds it, null removes it. */
|
|
838
|
+
const setMember = z.literal(true).nullable();
|
|
839
|
+
|
|
840
|
+
/**
|
|
841
|
+
* An Email/set update patch: the $seen keyword and the one mailbox an email
|
|
842
|
+
* is in are all that change.
|
|
843
|
+
*/
|
|
844
|
+
const emailPatch = z
|
|
845
|
+
.record(z.string(), z.json())
|
|
846
|
+
.transform((patch, context) => {
|
|
847
|
+
let seen: boolean | undefined;
|
|
848
|
+
let target: string | undefined;
|
|
849
|
+
|
|
850
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
851
|
+
const path = patchPath(key);
|
|
852
|
+
|
|
853
|
+
const fail = (message: string) =>
|
|
854
|
+
context.addIssue({ code: "custom", path, message, input: value });
|
|
855
|
+
|
|
856
|
+
if (key === "keywords") {
|
|
857
|
+
const keywords = trueSet.safeParse(value);
|
|
858
|
+
|
|
859
|
+
if (!keywords.success) fail("keywords map keywords to true");
|
|
860
|
+
else if (Object.keys(keywords.data).some((name) => name !== "$seen")) {
|
|
861
|
+
fail("Only the $seen keyword is stored");
|
|
862
|
+
} else seen = Object.hasOwn(keywords.data, "$seen");
|
|
863
|
+
} else if (key === "keywords/$seen") {
|
|
864
|
+
const member = setMember.safeParse(value);
|
|
865
|
+
|
|
866
|
+
if (member.success) seen = member.data === true;
|
|
867
|
+
else fail("A keyword is set to true or null");
|
|
868
|
+
} else if (key.startsWith("keywords/")) {
|
|
869
|
+
fail("Only the $seen keyword is stored");
|
|
870
|
+
} else if (key === "mailboxIds") {
|
|
871
|
+
const mailboxIds = trueSet.safeParse(value);
|
|
872
|
+
const ids = mailboxIds.success ? Object.keys(mailboxIds.data) : [];
|
|
873
|
+
|
|
874
|
+
if (ids.length === 1) [target] = ids;
|
|
875
|
+
else fail("An email is in exactly one mailbox");
|
|
876
|
+
} else if (key.startsWith("mailboxIds/")) {
|
|
877
|
+
const member = setMember.safeParse(value);
|
|
878
|
+
|
|
879
|
+
if (!member.success) fail("A mailbox is set to true or null");
|
|
880
|
+
else if (member.data) target = key.slice("mailboxIds/".length);
|
|
881
|
+
} else {
|
|
882
|
+
fail(`${key} cannot be changed`);
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
return { seen, target };
|
|
887
|
+
});
|
|
888
|
+
|
|
889
|
+
const draftAddress = z.object({
|
|
890
|
+
name: z.string().nullish(),
|
|
891
|
+
email: z.string(),
|
|
892
|
+
});
|
|
893
|
+
|
|
894
|
+
const draftAddresses = z
|
|
895
|
+
.array(draftAddress)
|
|
896
|
+
.nullish()
|
|
897
|
+
.transform((list) => list?.map((item) => item.email) ?? []);
|
|
898
|
+
|
|
899
|
+
/** A body part of a draft names its value in bodyValues. */
|
|
900
|
+
const draftBodyPart = z.array(z.object({ partId: z.string() })).nullish();
|
|
901
|
+
|
|
902
|
+
const draftAttachment = z
|
|
903
|
+
.object({
|
|
904
|
+
blobId: z
|
|
905
|
+
.string()
|
|
906
|
+
.regex(UPLOAD_BLOB, "Attachments must be blobs uploaded to this account")
|
|
907
|
+
.transform((blobId) => blobId.replace(UPLOAD_BLOB, "$1")),
|
|
908
|
+
name: z.string().nullish(),
|
|
909
|
+
type: z.string().nullish(),
|
|
910
|
+
disposition: z.string().nullish(),
|
|
911
|
+
cid: z
|
|
912
|
+
.string()
|
|
913
|
+
.nullish()
|
|
914
|
+
.transform((cid) => cid?.replaceAll(/^<|>$/gu, "") || undefined),
|
|
915
|
+
})
|
|
916
|
+
.superRefine((part, context) => {
|
|
917
|
+
if (part.disposition === "inline" && !part.cid) {
|
|
918
|
+
context.addIssue({
|
|
919
|
+
code: "custom",
|
|
920
|
+
path: ["cid"],
|
|
921
|
+
message: "Inline attachments need a cid",
|
|
922
|
+
});
|
|
367
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);
|
|
368
1004
|
}
|
|
369
|
-
return { seen, target };
|
|
370
|
-
}
|
|
371
1005
|
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
};
|
|
381
|
-
const bodyText = partText(input.textBody);
|
|
382
|
-
const bodyHtml = partText(input.htmlBody);
|
|
383
|
-
if (bodyText === undefined && bodyHtml === undefined) return "Give the message a textBody or htmlBody with bodyValues";
|
|
384
|
-
return {
|
|
385
|
-
accountId: owner.id,
|
|
386
|
-
to: list(input.to),
|
|
387
|
-
cc: list(input.cc),
|
|
388
|
-
bcc: list(input.bcc),
|
|
389
|
-
subject: typeof input.subject === "string" ? input.subject : "",
|
|
390
|
-
bodyText: bodyText ?? "",
|
|
391
|
-
...(bodyHtml !== undefined ? { bodyHtml } : {}),
|
|
392
|
-
};
|
|
1006
|
+
if (
|
|
1007
|
+
(args.update && Object.keys(args.update).length) ||
|
|
1008
|
+
args.destroy?.length
|
|
1009
|
+
) {
|
|
1010
|
+
scopes.push(MAIL_ORGANIZE_SCOPE);
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
return scopes;
|
|
393
1014
|
}
|
|
394
1015
|
|
|
395
|
-
async function emailSet(state: RequestState, args:
|
|
396
|
-
const owner = account(state, args);
|
|
1016
|
+
async function emailSet(state: RequestState, args: EmailSetArguments) {
|
|
1017
|
+
const owner = account(state, args.accountId);
|
|
397
1018
|
const stub = mailboxStub(state.context.env, owner.id);
|
|
398
1019
|
const oldState = await stub.jmapState();
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
1020
|
+
|
|
1021
|
+
if (args.ifInState != null && args.ifInState !== oldState) {
|
|
1022
|
+
throw new MethodError("stateMismatch");
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
const created = new Map<string, JsonObject>();
|
|
1026
|
+
const notCreated = new Map<string, JsonObject>();
|
|
1027
|
+
|
|
1028
|
+
const drafts = Object.entries(args.create ?? {}).flatMap(
|
|
1029
|
+
([creationId, input]) => {
|
|
1030
|
+
const parsed = draftSchema.safeParse(input);
|
|
1031
|
+
|
|
1032
|
+
if (!parsed.success) {
|
|
1033
|
+
notCreated.set(
|
|
1034
|
+
creationId,
|
|
1035
|
+
invalidProperties(parsed.error.issues, { topLevel: true })
|
|
1036
|
+
);
|
|
1037
|
+
|
|
1038
|
+
return [];
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
const { attachments, ...message } = parsed.data;
|
|
1042
|
+
|
|
1043
|
+
// The rules the mail app's composer follows: valid, normalized and
|
|
1044
|
+
// deduplicated recipients within the limits, a body, content ids.
|
|
1045
|
+
const compose = composeSchema.safeParse({
|
|
1046
|
+
...message,
|
|
1047
|
+
requestId: crypto.randomUUID(),
|
|
1048
|
+
mailboxId: owner.id,
|
|
1049
|
+
attachments: attachments.map((attachment) => ({
|
|
1050
|
+
uploadId: attachment.uploadId,
|
|
1051
|
+
disposition: attachment.disposition,
|
|
1052
|
+
contentId: attachment.contentId,
|
|
1053
|
+
})),
|
|
1054
|
+
});
|
|
1055
|
+
|
|
1056
|
+
if (!compose.success) {
|
|
1057
|
+
notCreated.set(
|
|
1058
|
+
creationId,
|
|
1059
|
+
invalidProperties(compose.error.issues.map(draftIssue), {
|
|
1060
|
+
topLevel: true,
|
|
1061
|
+
})
|
|
1062
|
+
);
|
|
1063
|
+
|
|
1064
|
+
return [];
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
return [
|
|
1068
|
+
{
|
|
1069
|
+
creationId,
|
|
1070
|
+
draft: { accountId: owner.id, compose: compose.data, attachments },
|
|
1071
|
+
},
|
|
1072
|
+
];
|
|
1073
|
+
}
|
|
1074
|
+
);
|
|
1075
|
+
|
|
1076
|
+
const missingBlobs = await Promise.all(
|
|
1077
|
+
drafts.map(async ({ draft }) => {
|
|
1078
|
+
try {
|
|
1079
|
+
// The name and type come with the email, after the bytes were uploaded.
|
|
1080
|
+
await Promise.all(
|
|
1081
|
+
draft.attachments.map((attachment) =>
|
|
1082
|
+
describeComposerUpload({
|
|
1083
|
+
env: state.context.env,
|
|
1084
|
+
mailboxId: owner.id,
|
|
1085
|
+
userId: state.context.user.id,
|
|
1086
|
+
uploadId: attachment.uploadId,
|
|
1087
|
+
filename: attachment.name,
|
|
1088
|
+
contentType: attachment.type,
|
|
1089
|
+
})
|
|
1090
|
+
)
|
|
1091
|
+
);
|
|
1092
|
+
|
|
1093
|
+
return null;
|
|
1094
|
+
} catch (error) {
|
|
1095
|
+
if (!(error instanceof UploadValidationError)) throw error;
|
|
1096
|
+
|
|
1097
|
+
return error.message;
|
|
1098
|
+
}
|
|
1099
|
+
})
|
|
1100
|
+
);
|
|
1101
|
+
|
|
1102
|
+
for (const [index, { creationId, draft }] of drafts.entries()) {
|
|
1103
|
+
const missing = missingBlobs[index];
|
|
1104
|
+
|
|
1105
|
+
if (missing) {
|
|
1106
|
+
notCreated.set(creationId, {
|
|
1107
|
+
type: "blobNotFound",
|
|
1108
|
+
description: missing,
|
|
1109
|
+
});
|
|
406
1110
|
continue;
|
|
407
1111
|
}
|
|
1112
|
+
|
|
408
1113
|
// Drafts are not stored: one is sent by EmailSubmission/set in the same request.
|
|
409
1114
|
const id = `draft-${crypto.randomUUID()}`;
|
|
410
1115
|
state.drafts.set(id, draft);
|
|
411
|
-
state.createdIds
|
|
412
|
-
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
|
+
});
|
|
413
1123
|
}
|
|
414
1124
|
|
|
415
|
-
const updated
|
|
416
|
-
const notUpdated
|
|
417
|
-
const reads:
|
|
1125
|
+
const updated = new Map<string, null>();
|
|
1126
|
+
const notUpdated = new Map<string, JsonObject>();
|
|
1127
|
+
const reads: [string, boolean][] = [];
|
|
418
1128
|
const moves = new Map<string, string[]>();
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
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
|
+
);
|
|
423
1140
|
continue;
|
|
424
1141
|
}
|
|
425
|
-
|
|
1142
|
+
|
|
1143
|
+
const { seen, target } = change.data;
|
|
1144
|
+
|
|
426
1145
|
if (seen !== undefined) reads.push([id, seen]);
|
|
1146
|
+
|
|
427
1147
|
if (target) moves.set(target, [...(moves.get(target) ?? []), id]);
|
|
428
|
-
updated
|
|
1148
|
+
updated.set(id, null);
|
|
429
1149
|
}
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
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" });
|
|
434
1161
|
}
|
|
435
1162
|
}
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
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
|
+
});
|
|
442
1180
|
}
|
|
443
1181
|
}
|
|
444
1182
|
|
|
445
1183
|
const destroyed: string[] = [];
|
|
446
|
-
const notDestroyed
|
|
447
|
-
const destroyIds = args.destroy
|
|
1184
|
+
const notDestroyed = new Map<string, JsonObject>();
|
|
1185
|
+
const destroyIds = args.destroy ?? [];
|
|
1186
|
+
|
|
448
1187
|
if (destroyIds.length) {
|
|
449
1188
|
const { emails } = await stub.jmapEmails(state.context.user.id, destroyIds);
|
|
450
1189
|
const inTrash = emails.filter((row) => row.mailboxId === "trash");
|
|
451
1190
|
const elsewhere = emails.filter((row) => row.mailboxId !== "trash");
|
|
1191
|
+
|
|
452
1192
|
// Mail goes to Trash first; destroying it there deletes its conversation.
|
|
453
|
-
if (elsewhere.length)
|
|
1193
|
+
if (elsewhere.length) {
|
|
1194
|
+
await stub.jmapMoveEmails(
|
|
1195
|
+
elsewhere.map((row) => row.email.id),
|
|
1196
|
+
"trash"
|
|
1197
|
+
);
|
|
1198
|
+
}
|
|
1199
|
+
|
|
454
1200
|
if (inTrash.length) {
|
|
455
|
-
await stub.permanentlyDeleteConversations([
|
|
1201
|
+
await stub.permanentlyDeleteConversations([
|
|
1202
|
+
...new Set(inTrash.map((row) => row.email.conversationId)),
|
|
1203
|
+
]);
|
|
456
1204
|
}
|
|
1205
|
+
|
|
457
1206
|
const found = new Set(emails.map((row) => row.email.id));
|
|
1207
|
+
|
|
458
1208
|
for (const id of destroyIds) {
|
|
459
1209
|
if (found.has(id)) destroyed.push(id);
|
|
460
|
-
else notDestroyed
|
|
1210
|
+
else notDestroyed.set(id, { type: "notFound" });
|
|
461
1211
|
}
|
|
462
1212
|
}
|
|
1213
|
+
|
|
463
1214
|
return {
|
|
464
1215
|
accountId: owner.id,
|
|
465
1216
|
oldState,
|
|
466
1217
|
newState: await stub.jmapState(),
|
|
467
|
-
created:
|
|
468
|
-
updated:
|
|
1218
|
+
created: setResult(created),
|
|
1219
|
+
updated: setResult(updated),
|
|
469
1220
|
destroyed: destroyed.length ? destroyed : null,
|
|
470
|
-
notCreated:
|
|
471
|
-
notUpdated:
|
|
472
|
-
notDestroyed:
|
|
1221
|
+
notCreated: setResult(notCreated),
|
|
1222
|
+
notUpdated: setResult(notUpdated),
|
|
1223
|
+
notDestroyed: setResult(notDestroyed),
|
|
473
1224
|
};
|
|
474
1225
|
}
|
|
475
1226
|
|
|
476
1227
|
// --------------------------------------------------- threads and identities
|
|
477
1228
|
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
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
|
+
|
|
483
1245
|
return {
|
|
484
1246
|
accountId: owner.id,
|
|
485
1247
|
state: result.state,
|
|
486
|
-
list: ids.flatMap((id) =>
|
|
487
|
-
|
|
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)),
|
|
488
1254
|
};
|
|
489
1255
|
}
|
|
490
1256
|
|
|
491
|
-
|
|
492
|
-
|
|
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
|
+
|
|
493
1269
|
const list = owner.canSend
|
|
494
|
-
? [
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
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
|
+
]
|
|
504
1282
|
: [];
|
|
505
|
-
|
|
1283
|
+
|
|
1284
|
+
const ids = args.ids ?? list.map((identity) => identity.id);
|
|
1285
|
+
|
|
506
1286
|
return {
|
|
507
1287
|
accountId: owner.id,
|
|
508
1288
|
state: "1",
|
|
509
|
-
list: list.
|
|
1289
|
+
list: list.flatMap((identity) =>
|
|
1290
|
+
ids.includes(identity.id) ? [pick(identity, args.properties)] : []
|
|
1291
|
+
),
|
|
510
1292
|
notFound: ids.filter((id) => id !== owner.id || !owner.canSend),
|
|
511
1293
|
};
|
|
512
1294
|
}
|
|
513
1295
|
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
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>();
|
|
519
1356
|
const sentDrafts = new Map<string, string>();
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
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));
|
|
523
1363
|
continue;
|
|
524
1364
|
}
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
const
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
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);
|
|
534
1376
|
continue;
|
|
535
1377
|
}
|
|
536
|
-
|
|
537
|
-
|
|
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
|
+
});
|
|
538
1388
|
continue;
|
|
539
1389
|
}
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
mailboxId: owner.id,
|
|
547
|
-
to: draft.to,
|
|
548
|
-
cc: draft.cc,
|
|
549
|
-
bcc: draft.bcc,
|
|
550
|
-
subject: draft.subject,
|
|
551
|
-
bodyText: draft.bodyText,
|
|
552
|
-
...(draft.bodyHtml !== undefined ? { bodyHtml: draft.bodyHtml } : {}),
|
|
553
|
-
attachments: [],
|
|
554
|
-
userId: state.context.user.id,
|
|
555
|
-
},
|
|
556
|
-
conversationId: `conv_${crypto.randomUUID().replaceAll("-", "")}`,
|
|
557
|
-
related: null,
|
|
558
|
-
forwarded: null,
|
|
559
|
-
includeRelatedContext: false,
|
|
560
|
-
fromAddress: owner.address,
|
|
561
|
-
fromName: owner.displayName,
|
|
562
|
-
defer: state.context.defer,
|
|
563
|
-
});
|
|
564
|
-
const id = `sub-${submission.email.id}`;
|
|
565
|
-
state.createdIds[creationId] = id;
|
|
566
|
-
sentDrafts.set(id, emailId!);
|
|
567
|
-
created[creationId] = {
|
|
568
|
-
id,
|
|
569
|
-
threadId: submission.email.conversationId,
|
|
570
|
-
emailId: submission.email.id,
|
|
571
|
-
sendAt: new Date().toISOString(),
|
|
572
|
-
undoStatus: "final",
|
|
573
|
-
};
|
|
574
|
-
} catch (error) {
|
|
575
|
-
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, {
|
|
576
1396
|
type: "forbiddenToSend",
|
|
577
|
-
description: error
|
|
578
|
-
};
|
|
1397
|
+
description: sent.error,
|
|
1398
|
+
});
|
|
1399
|
+
continue;
|
|
579
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
|
+
});
|
|
580
1412
|
}
|
|
1413
|
+
|
|
581
1414
|
// The sent copy is already in Sent; drafts were never stored, so the
|
|
582
1415
|
// follow-up Email/set only reports them gone.
|
|
583
|
-
const followUp = [
|
|
584
|
-
|
|
585
|
-
.
|
|
586
|
-
|
|
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
|
+
|
|
587
1429
|
if (followUp.length) {
|
|
588
1430
|
const stub = mailboxStub(state.context.env, owner.id);
|
|
589
1431
|
const current = await stub.jmapState();
|
|
590
|
-
state.after.push([
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
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
|
+
]);
|
|
595
1447
|
}
|
|
1448
|
+
|
|
596
1449
|
return {
|
|
597
1450
|
accountId: owner.id,
|
|
598
1451
|
oldState: "1",
|
|
599
1452
|
newState: "1",
|
|
600
|
-
created:
|
|
601
|
-
notCreated:
|
|
1453
|
+
created: setResult(created),
|
|
1454
|
+
notCreated: setResult(notCreated),
|
|
602
1455
|
updated: null,
|
|
603
1456
|
destroyed: null,
|
|
604
1457
|
notUpdated: null,
|
|
@@ -606,73 +1459,575 @@ async function submissionSet(state: RequestState, args: Args, callId: string) {
|
|
|
606
1459
|
};
|
|
607
1460
|
}
|
|
608
1461
|
|
|
1462
|
+
// --------------------------------------------------------- push (RFC 8620 §7.2)
|
|
1463
|
+
|
|
1464
|
+
const MAX_PUSH_SUBSCRIPTIONS = 20;
|
|
1465
|
+
|
|
1466
|
+
type PushSubscriptionRow = typeof jmapPushSubscriptions.$inferSelect;
|
|
1467
|
+
|
|
1468
|
+
/** url and keys are never returned (§7.2.1). */
|
|
1469
|
+
function pushSubscriptionObject(row: PushSubscriptionRow) {
|
|
1470
|
+
return {
|
|
1471
|
+
id: row.id,
|
|
1472
|
+
deviceClientId: row.deviceClientId,
|
|
1473
|
+
verificationCode: row.verifiedAt ? row.verificationCode : null,
|
|
1474
|
+
expires: row.expiresAt.toISOString(),
|
|
1475
|
+
types: row.typesJson,
|
|
1476
|
+
};
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
/** The data types to push; null is all of them. */
|
|
1480
|
+
const pushTypes = z.array(z.string()).nullish();
|
|
1481
|
+
|
|
1482
|
+
/** A PushSubscription create object (RFC 8620 §7.2). */
|
|
1483
|
+
const pushSubscriptionCreate = z.object({
|
|
1484
|
+
deviceClientId: z.string().min(1),
|
|
1485
|
+
url: z
|
|
1486
|
+
.url({ protocol: /^https$/u, error: "url must be an https URL" })
|
|
1487
|
+
.transform((url) => new URL(url).toString()),
|
|
1488
|
+
keys: z.object({ p256dh: z.string(), auth: z.string() }).nullish(),
|
|
1489
|
+
verificationCode: z
|
|
1490
|
+
.never({ error: "verificationCode is set by update" })
|
|
1491
|
+
.optional(),
|
|
1492
|
+
expires: utcDate.nullish(),
|
|
1493
|
+
types: pushTypes,
|
|
1494
|
+
});
|
|
1495
|
+
|
|
1496
|
+
/** Only these change after a subscription is created. */
|
|
1497
|
+
const pushSubscriptionPatch = z.strictObject({
|
|
1498
|
+
verificationCode: z.string().optional(),
|
|
1499
|
+
expires: utcDate.nullish(),
|
|
1500
|
+
types: pushTypes,
|
|
1501
|
+
});
|
|
1502
|
+
|
|
1503
|
+
function ownSubscriptions(state: RequestState) {
|
|
1504
|
+
return and(
|
|
1505
|
+
eq(jmapPushSubscriptions.userId, state.context.user.id),
|
|
1506
|
+
eq(jmapPushSubscriptions.clientId, state.context.clientId)
|
|
1507
|
+
);
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
const pushSubscriptionGetArguments = z.object({
|
|
1511
|
+
ids: idList.nullish(),
|
|
1512
|
+
properties,
|
|
1513
|
+
});
|
|
1514
|
+
|
|
1515
|
+
async function pushSubscriptionGet(
|
|
1516
|
+
state: RequestState,
|
|
1517
|
+
args: z.output<typeof pushSubscriptionGetArguments>
|
|
1518
|
+
) {
|
|
1519
|
+
const db = createDb(state.context.env.DB);
|
|
1520
|
+
const ids = args.ids ?? null;
|
|
1521
|
+
|
|
1522
|
+
const rows = await db
|
|
1523
|
+
.select()
|
|
1524
|
+
.from(jmapPushSubscriptions)
|
|
1525
|
+
.where(
|
|
1526
|
+
ids
|
|
1527
|
+
? and(
|
|
1528
|
+
ownSubscriptions(state),
|
|
1529
|
+
inArray(jmapPushSubscriptions.id, ids.length ? ids : [""])
|
|
1530
|
+
)
|
|
1531
|
+
: ownSubscriptions(state)
|
|
1532
|
+
);
|
|
1533
|
+
|
|
1534
|
+
const found = new Set(rows.map((row) => row.id));
|
|
1535
|
+
|
|
1536
|
+
return {
|
|
1537
|
+
list: rows.map((row) => pick(pushSubscriptionObject(row), args.properties)),
|
|
1538
|
+
notFound: ids ? ids.filter((id) => !found.has(id)) : [],
|
|
1539
|
+
};
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
const pushSubscriptionSetArguments = z.object({
|
|
1543
|
+
/** Push subscriptions have no state (§7.2): any given state mismatches. */
|
|
1544
|
+
ifInState: z.string().nullish(),
|
|
1545
|
+
create: setObjects,
|
|
1546
|
+
update: setObjects,
|
|
1547
|
+
destroy: idList.nullish(),
|
|
1548
|
+
});
|
|
1549
|
+
|
|
1550
|
+
async function createPushSubscriptions(
|
|
1551
|
+
state: RequestState,
|
|
1552
|
+
create: JsonObject
|
|
1553
|
+
) {
|
|
1554
|
+
const db = createDb(state.context.env.DB);
|
|
1555
|
+
const created = new Map<string, JsonObject>();
|
|
1556
|
+
const notCreated = new Map<string, JsonObject>();
|
|
1557
|
+
const entries = Object.entries(create);
|
|
1558
|
+
|
|
1559
|
+
if (!entries.length) return { created, notCreated };
|
|
1560
|
+
|
|
1561
|
+
// The devices with a subscription; a device has one, and a new one replaces it.
|
|
1562
|
+
const devices = new Set(
|
|
1563
|
+
(
|
|
1564
|
+
await db
|
|
1565
|
+
.select({ deviceClientId: jmapPushSubscriptions.deviceClientId })
|
|
1566
|
+
.from(jmapPushSubscriptions)
|
|
1567
|
+
.where(eq(jmapPushSubscriptions.userId, state.context.user.id))
|
|
1568
|
+
).map((row) => row.deviceClientId)
|
|
1569
|
+
);
|
|
1570
|
+
|
|
1571
|
+
const rows: PushSubscriptionRow[] = [];
|
|
1572
|
+
|
|
1573
|
+
for (const [creationId, input] of entries) {
|
|
1574
|
+
const parsed = pushSubscriptionCreate.safeParse(input);
|
|
1575
|
+
|
|
1576
|
+
if (!parsed.success) {
|
|
1577
|
+
notCreated.set(creationId, invalidProperties(parsed.error.issues));
|
|
1578
|
+
continue;
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
const subscription = parsed.data;
|
|
1582
|
+
|
|
1583
|
+
if (subscription.keys && !state.context.vapid) {
|
|
1584
|
+
notCreated.set(creationId, {
|
|
1585
|
+
type: "invalidProperties",
|
|
1586
|
+
properties: ["keys"],
|
|
1587
|
+
description: "Web Push is not configured on this server",
|
|
1588
|
+
});
|
|
1589
|
+
continue;
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
const others =
|
|
1593
|
+
devices.size - (devices.has(subscription.deviceClientId) ? 1 : 0);
|
|
1594
|
+
|
|
1595
|
+
if (others >= MAX_PUSH_SUBSCRIPTIONS) {
|
|
1596
|
+
notCreated.set(creationId, {
|
|
1597
|
+
type: "overQuota",
|
|
1598
|
+
description: `At most ${MAX_PUSH_SUBSCRIPTIONS} push subscriptions`,
|
|
1599
|
+
});
|
|
1600
|
+
continue;
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
devices.add(subscription.deviceClientId);
|
|
1604
|
+
|
|
1605
|
+
const row: PushSubscriptionRow = {
|
|
1606
|
+
id: crypto.randomUUID(),
|
|
1607
|
+
userId: state.context.user.id,
|
|
1608
|
+
clientId: state.context.clientId,
|
|
1609
|
+
deviceClientId: subscription.deviceClientId,
|
|
1610
|
+
url: subscription.url,
|
|
1611
|
+
p256dh: subscription.keys?.p256dh ?? null,
|
|
1612
|
+
auth: subscription.keys?.auth ?? null,
|
|
1613
|
+
verificationCode: newVerificationCode(),
|
|
1614
|
+
verifiedAt: null,
|
|
1615
|
+
expiresAt: subscriptionExpiry(subscription.expires),
|
|
1616
|
+
typesJson: subscription.types ?? null,
|
|
1617
|
+
createdAt: new Date(),
|
|
1618
|
+
};
|
|
1619
|
+
|
|
1620
|
+
rows.push(row);
|
|
1621
|
+
state.createdIds.set(creationId, row.id);
|
|
1622
|
+
created.set(creationId, {
|
|
1623
|
+
id: row.id,
|
|
1624
|
+
expires: row.expiresAt.toISOString(),
|
|
1625
|
+
});
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
// In order: a later subscription for the same device replaces an earlier one.
|
|
1629
|
+
const [first, ...rest] = rows.flatMap((row) => [
|
|
1630
|
+
db
|
|
1631
|
+
.delete(jmapPushSubscriptions)
|
|
1632
|
+
.where(
|
|
1633
|
+
and(
|
|
1634
|
+
eq(jmapPushSubscriptions.userId, row.userId),
|
|
1635
|
+
eq(jmapPushSubscriptions.deviceClientId, row.deviceClientId)
|
|
1636
|
+
)
|
|
1637
|
+
),
|
|
1638
|
+
db.insert(jmapPushSubscriptions).values(row),
|
|
1639
|
+
]);
|
|
1640
|
+
|
|
1641
|
+
if (first) await db.batch([first, ...rest]);
|
|
1642
|
+
|
|
1643
|
+
for (const row of rows) {
|
|
1644
|
+
state.context.defer(
|
|
1645
|
+
sendVerification(row, state.context.vapid).catch((error) => {
|
|
1646
|
+
console.error(
|
|
1647
|
+
"Could not send JMAP push verification",
|
|
1648
|
+
error instanceof Error ? error.message : String(error)
|
|
1649
|
+
);
|
|
1650
|
+
})
|
|
1651
|
+
);
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
return { created, notCreated };
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
async function updatePushSubscriptions(
|
|
1658
|
+
state: RequestState,
|
|
1659
|
+
update: JsonObject
|
|
1660
|
+
) {
|
|
1661
|
+
const db = createDb(state.context.env.DB);
|
|
1662
|
+
const updated = new Map<string, JsonObject | null>();
|
|
1663
|
+
const notUpdated = new Map<string, JsonObject>();
|
|
1664
|
+
const entries = Object.entries(update);
|
|
1665
|
+
|
|
1666
|
+
if (!entries.length) return { updated, notUpdated };
|
|
1667
|
+
|
|
1668
|
+
const rows = new Map(
|
|
1669
|
+
(
|
|
1670
|
+
await db
|
|
1671
|
+
.select()
|
|
1672
|
+
.from(jmapPushSubscriptions)
|
|
1673
|
+
.where(
|
|
1674
|
+
and(
|
|
1675
|
+
ownSubscriptions(state),
|
|
1676
|
+
inArray(
|
|
1677
|
+
jmapPushSubscriptions.id,
|
|
1678
|
+
entries.map(([id]) => id)
|
|
1679
|
+
)
|
|
1680
|
+
)
|
|
1681
|
+
)
|
|
1682
|
+
).map((row) => [row.id, row])
|
|
1683
|
+
);
|
|
1684
|
+
|
|
1685
|
+
const changed: Pick<
|
|
1686
|
+
PushSubscriptionRow,
|
|
1687
|
+
"id" | "verifiedAt" | "expiresAt" | "typesJson"
|
|
1688
|
+
>[] = [];
|
|
1689
|
+
|
|
1690
|
+
for (const [id, input] of entries) {
|
|
1691
|
+
const row = rows.get(id);
|
|
1692
|
+
|
|
1693
|
+
if (!row) {
|
|
1694
|
+
notUpdated.set(id, { type: "notFound" });
|
|
1695
|
+
continue;
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
const parsed = pushSubscriptionPatch.safeParse(input);
|
|
1699
|
+
|
|
1700
|
+
if (!parsed.success) {
|
|
1701
|
+
notUpdated.set(id, invalidProperties(parsed.error.issues));
|
|
1702
|
+
continue;
|
|
1703
|
+
}
|
|
1704
|
+
|
|
1705
|
+
const patch = parsed.data;
|
|
1706
|
+
|
|
1707
|
+
if (
|
|
1708
|
+
patch.verificationCode !== undefined &&
|
|
1709
|
+
patch.verificationCode !== row.verificationCode
|
|
1710
|
+
) {
|
|
1711
|
+
notUpdated.set(id, {
|
|
1712
|
+
type: "invalidProperties",
|
|
1713
|
+
properties: ["verificationCode"],
|
|
1714
|
+
description: "The verification code does not match",
|
|
1715
|
+
});
|
|
1716
|
+
continue;
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
const expiresAt =
|
|
1720
|
+
patch.expires === undefined
|
|
1721
|
+
? row.expiresAt
|
|
1722
|
+
: subscriptionExpiry(patch.expires);
|
|
1723
|
+
|
|
1724
|
+
changed.push({
|
|
1725
|
+
id,
|
|
1726
|
+
verifiedAt:
|
|
1727
|
+
patch.verificationCode === undefined
|
|
1728
|
+
? row.verifiedAt
|
|
1729
|
+
: (row.verifiedAt ?? new Date()),
|
|
1730
|
+
expiresAt,
|
|
1731
|
+
typesJson: patch.types === undefined ? row.typesJson : patch.types,
|
|
1732
|
+
});
|
|
1733
|
+
|
|
1734
|
+
// The server may shorten the asked expiry; then it says what it chose.
|
|
1735
|
+
const askedExpiry = patch.expires ? Date.parse(patch.expires) : null;
|
|
1736
|
+
|
|
1737
|
+
updated.set(
|
|
1738
|
+
id,
|
|
1739
|
+
askedExpiry !== null && askedExpiry !== expiresAt.getTime()
|
|
1740
|
+
? { expires: expiresAt.toISOString() }
|
|
1741
|
+
: null
|
|
1742
|
+
);
|
|
1743
|
+
}
|
|
1744
|
+
|
|
1745
|
+
const [first, ...rest] = changed.map(({ id, ...values }) =>
|
|
1746
|
+
db
|
|
1747
|
+
.update(jmapPushSubscriptions)
|
|
1748
|
+
.set(values)
|
|
1749
|
+
.where(eq(jmapPushSubscriptions.id, id))
|
|
1750
|
+
);
|
|
1751
|
+
|
|
1752
|
+
if (first) await db.batch([first, ...rest]);
|
|
1753
|
+
|
|
1754
|
+
return { updated, notUpdated };
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
async function pushSubscriptionSet(
|
|
1758
|
+
state: RequestState,
|
|
1759
|
+
args: z.output<typeof pushSubscriptionSetArguments>
|
|
1760
|
+
) {
|
|
1761
|
+
const db = createDb(state.context.env.DB);
|
|
1762
|
+
|
|
1763
|
+
if (args.ifInState != null) throw new MethodError("stateMismatch");
|
|
1764
|
+
|
|
1765
|
+
const { created, notCreated } = await createPushSubscriptions(
|
|
1766
|
+
state,
|
|
1767
|
+
args.create ?? {}
|
|
1768
|
+
);
|
|
1769
|
+
|
|
1770
|
+
const { updated, notUpdated } = await updatePushSubscriptions(
|
|
1771
|
+
state,
|
|
1772
|
+
args.update ?? {}
|
|
1773
|
+
);
|
|
1774
|
+
|
|
1775
|
+
const destroyIds = args.destroy ?? [];
|
|
1776
|
+
|
|
1777
|
+
const removed = destroyIds.length
|
|
1778
|
+
? await db
|
|
1779
|
+
.delete(jmapPushSubscriptions)
|
|
1780
|
+
.where(
|
|
1781
|
+
and(
|
|
1782
|
+
ownSubscriptions(state),
|
|
1783
|
+
inArray(jmapPushSubscriptions.id, destroyIds)
|
|
1784
|
+
)
|
|
1785
|
+
)
|
|
1786
|
+
.returning({ id: jmapPushSubscriptions.id })
|
|
1787
|
+
: [];
|
|
1788
|
+
|
|
1789
|
+
const destroyed = new Set(removed.map((row) => row.id));
|
|
1790
|
+
const notDestroyed = new Map<string, JsonObject>();
|
|
1791
|
+
|
|
1792
|
+
for (const id of destroyIds) {
|
|
1793
|
+
if (!destroyed.has(id)) notDestroyed.set(id, { type: "notFound" });
|
|
1794
|
+
}
|
|
1795
|
+
|
|
1796
|
+
return {
|
|
1797
|
+
created: setResult(created),
|
|
1798
|
+
updated: setResult(updated),
|
|
1799
|
+
destroyed: destroyed.size ? [...destroyed] : null,
|
|
1800
|
+
notCreated: setResult(notCreated),
|
|
1801
|
+
notUpdated: setResult(notUpdated),
|
|
1802
|
+
notDestroyed: setResult(notDestroyed),
|
|
1803
|
+
};
|
|
1804
|
+
}
|
|
1805
|
+
|
|
609
1806
|
// ----------------------------------------------------------------- dispatch
|
|
610
1807
|
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
const
|
|
634
|
-
|
|
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
|
+
);
|
|
635
1859
|
},
|
|
636
|
-
|
|
637
|
-
|
|
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;
|
|
638
1969
|
};
|
|
639
1970
|
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
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
|
+
);
|
|
646
1981
|
}
|
|
647
|
-
|
|
648
|
-
|
|
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
|
+
);
|
|
649
1988
|
}
|
|
1989
|
+
|
|
650
1990
|
const state: RequestState = {
|
|
651
1991
|
context,
|
|
652
1992
|
responses: [],
|
|
653
|
-
createdIds:
|
|
1993
|
+
createdIds: new Map(Object.entries(request.createdIds ?? {})),
|
|
654
1994
|
drafts: new Map(),
|
|
655
1995
|
after: [],
|
|
656
1996
|
};
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
const [name, rawArgs, callId] = call as Invocation;
|
|
662
|
-
const method = methods[name];
|
|
1997
|
+
|
|
1998
|
+
for (const [name, rawArgs, callId] of request.methodCalls) {
|
|
1999
|
+
const handler = methods.get(name);
|
|
2000
|
+
|
|
663
2001
|
try {
|
|
664
|
-
if (!
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
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));
|
|
668
2012
|
} catch (error) {
|
|
669
2013
|
if (!(error instanceof MethodError)) throw error;
|
|
670
|
-
state.responses.push([
|
|
2014
|
+
state.responses.push([
|
|
2015
|
+
"error",
|
|
2016
|
+
{ type: error.type, description: error.message },
|
|
2017
|
+
callId,
|
|
2018
|
+
]);
|
|
671
2019
|
}
|
|
672
2020
|
}
|
|
673
|
-
|
|
2021
|
+
|
|
2022
|
+
const response: JmapResponse = {
|
|
674
2023
|
methodResponses: state.responses,
|
|
675
|
-
...(isRecord(body.createdIds) ? { createdIds: state.createdIds } : {}),
|
|
676
2024
|
sessionState: String(context.accounts.length),
|
|
677
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;
|
|
678
2033
|
}
|