@open-workspace/email 0.1.1 → 0.3.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 +6 -3
- package/alchemy.ts +27 -11
- package/migrations/0000_email.sql +18 -0
- package/migrations/meta/0000_snapshot.json +127 -1
- package/migrations/meta/_journal.json +1 -1
- package/package.json +3 -3
- package/shared/mail.ts +11 -8
- package/worker/db/schema.ts +34 -1
- package/worker/jmap/eventsource.ts +101 -0
- package/worker/jmap/methods.ts +927 -0
- package/worker/jmap/push.ts +123 -0
- package/worker/jmap/routes.ts +277 -0
- package/worker/mail/header-metadata.ts +4 -38
- package/worker/mail/push-notifications.ts +17 -3
- package/worker/mail/r2-presigned-urls.ts +2 -2
- package/worker/mail/routes.ts +3 -3
- package/worker/mail/safety-routes.ts +2 -3
- package/worker/mail/uploads.ts +29 -0
- package/worker/mailbox/demo.ts +2 -2
- package/worker/mailbox/index.ts +79 -23
- package/worker/mailbox/jmap-store.ts +238 -0
- package/worker/mailbox/model.ts +2 -11
- package/worker/module.ts +2 -0
- package/worker/mailbox/legacy-migrations.ts +0 -41
|
@@ -0,0 +1,927 @@
|
|
|
1
|
+
import { and, eq, inArray } from "drizzle-orm";
|
|
2
|
+
import { createDb } from "@open-workspace/core/worker/db/client.ts";
|
|
3
|
+
import { MAX_COMPOSER_ATTACHMENT_COUNT } from "../../shared/mail";
|
|
4
|
+
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
|
+
import { submitOutgoing } from "../mail/outbound-service";
|
|
9
|
+
import { describeComposerUpload, UploadValidationError } from "../mail/uploads";
|
|
10
|
+
import { newVerificationCode, sendVerification, subscriptionExpiry, type PushVapid } from "./push";
|
|
11
|
+
|
|
12
|
+
const CORE = "urn:ietf:params:jmap:core";
|
|
13
|
+
const MAX_OBJECTS = 500;
|
|
14
|
+
|
|
15
|
+
export type JmapAccount = {
|
|
16
|
+
id: string;
|
|
17
|
+
address: string;
|
|
18
|
+
displayName: string;
|
|
19
|
+
ownerUserId: string | null;
|
|
20
|
+
isPrimary: boolean;
|
|
21
|
+
canSend: boolean;
|
|
22
|
+
isPersonal: boolean;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export type JmapContext = {
|
|
26
|
+
env: Env;
|
|
27
|
+
user: { id: string; name: string };
|
|
28
|
+
/** The OAuth client the token was issued to; push subscriptions belong to it. */
|
|
29
|
+
clientId: string;
|
|
30
|
+
/** Signs pushes to Web Push services; null when push is not configured. */
|
|
31
|
+
vapid: PushVapid | null;
|
|
32
|
+
accounts: JmapAccount[];
|
|
33
|
+
requestUrl: string;
|
|
34
|
+
defer: (task: Promise<unknown>) => void;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
type Args = Record<string, unknown>;
|
|
38
|
+
type Invocation = [string, Args, string];
|
|
39
|
+
|
|
40
|
+
/** A request-level error (RFC 8620 §3.6.1), answered as a problem document. */
|
|
41
|
+
export class JmapError extends Error {
|
|
42
|
+
constructor(readonly type: string, message: string) {
|
|
43
|
+
super(message);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A method-level error (RFC 8620 §3.6.2), answered in place of the method's response. */
|
|
48
|
+
class MethodError extends Error {
|
|
49
|
+
constructor(readonly type: string, message?: string) {
|
|
50
|
+
super(message ?? type);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** An attachment of a draft: bytes from /jmap/upload. */
|
|
55
|
+
type DraftAttachment = {
|
|
56
|
+
uploadId: string;
|
|
57
|
+
name: string;
|
|
58
|
+
type: string;
|
|
59
|
+
disposition: "attachment" | "inline";
|
|
60
|
+
contentId?: string;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/** A draft from Email/set create; it lives only for the request that sends it. */
|
|
64
|
+
type Draft = {
|
|
65
|
+
accountId: string;
|
|
66
|
+
to: string[];
|
|
67
|
+
cc: string[];
|
|
68
|
+
bcc: string[];
|
|
69
|
+
subject: string;
|
|
70
|
+
bodyText: string;
|
|
71
|
+
bodyHtml?: string;
|
|
72
|
+
attachments: DraftAttachment[];
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/** Uploaded blobs are named after their upload: `upl~<upload id>`. */
|
|
76
|
+
export const UPLOAD_BLOB = /^upl~(upl_[a-f0-9]{32})$/u;
|
|
77
|
+
|
|
78
|
+
type RequestState = {
|
|
79
|
+
context: JmapContext;
|
|
80
|
+
responses: Invocation[];
|
|
81
|
+
createdIds: Record<string, string>;
|
|
82
|
+
drafts: Map<string, Draft>;
|
|
83
|
+
/** Responses a method adds after its own, e.g. an implicit Email/set. */
|
|
84
|
+
after: Invocation[];
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
88
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ---------------------------------------------------------------- references
|
|
92
|
+
|
|
93
|
+
/** RFC 8620 §3.7: a JSON Pointer where `*` maps over an array. */
|
|
94
|
+
function evaluatePointer(value: unknown, path: string): unknown {
|
|
95
|
+
if (path === "") return value;
|
|
96
|
+
const [head, ...rest] = path.slice(1).split("/").map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
|
|
97
|
+
const tail = rest.length ? `/${rest.join("/")}` : "";
|
|
98
|
+
if (head === "*" && Array.isArray(value)) {
|
|
99
|
+
return value.flatMap((item) => {
|
|
100
|
+
const result = evaluatePointer(item, tail);
|
|
101
|
+
return Array.isArray(result) ? result : [result];
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
if (Array.isArray(value) && /^\d+$/u.test(head!)) return evaluatePointer(value[Number(head)], tail);
|
|
105
|
+
if (isRecord(value) && head! in value) return evaluatePointer(value[head!], tail);
|
|
106
|
+
throw new MethodError("invalidResultReference", `Path ${path} does not resolve`);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function resolveReferences(state: RequestState, args: Args): Args {
|
|
110
|
+
const resolved: Args = {};
|
|
111
|
+
for (const [key, value] of Object.entries(args)) {
|
|
112
|
+
if (!key.startsWith("#")) {
|
|
113
|
+
resolved[key] = value;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
const name = key.slice(1);
|
|
117
|
+
if (name in args) throw new MethodError("invalidArguments", `Both ${name} and #${name} given`);
|
|
118
|
+
if (!isRecord(value) || typeof value.resultOf !== "string" || typeof value.name !== "string" || typeof value.path !== "string") {
|
|
119
|
+
throw new MethodError("invalidResultReference");
|
|
120
|
+
}
|
|
121
|
+
const source = state.responses.find(([method, , callId]) => callId === value.resultOf && method === value.name);
|
|
122
|
+
if (!source) throw new MethodError("invalidResultReference", `No ${value.name} result for ${value.resultOf}`);
|
|
123
|
+
resolved[name] = evaluatePointer(source[1], value.path);
|
|
124
|
+
}
|
|
125
|
+
return resolved;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// ------------------------------------------------------------------ helpers
|
|
129
|
+
|
|
130
|
+
function account(state: RequestState, args: Args) {
|
|
131
|
+
const found = state.context.accounts.find((item) => item.id === args.accountId);
|
|
132
|
+
if (!found) throw new MethodError("accountNotFound");
|
|
133
|
+
return found;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function stringIds(value: unknown, name = "ids") {
|
|
137
|
+
if (!Array.isArray(value) || value.some((id) => typeof id !== "string")) {
|
|
138
|
+
throw new MethodError("invalidArguments", `${name} must be a list of ids`);
|
|
139
|
+
}
|
|
140
|
+
if (value.length > MAX_OBJECTS) throw new MethodError("requestTooLarge");
|
|
141
|
+
return value as string[];
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function pick<T extends Record<string, unknown>>(object: T, properties: unknown) {
|
|
145
|
+
if (!Array.isArray(properties)) return object;
|
|
146
|
+
return Object.fromEntries(Object.entries(object).filter(([key]) => key === "id" || properties.includes(key)));
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** We cannot list changes, only say whether anything changed. */
|
|
150
|
+
function changes(accountId: string, sinceState: unknown, state: string) {
|
|
151
|
+
if (sinceState !== state) throw new MethodError("cannotCalculateChanges");
|
|
152
|
+
return { accountId, oldState: state, newState: state, hasMoreChanges: false, created: [], updated: [], destroyed: [] };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const addresses = (list: Array<{ address: string; name?: string | null }> | null | undefined) =>
|
|
156
|
+
list?.length ? list.map((item) => ({ name: item.name || null, email: item.address })) : null;
|
|
157
|
+
|
|
158
|
+
// ------------------------------------------------------------------ mailbox
|
|
159
|
+
|
|
160
|
+
function mailboxObject(row: JmapMailboxRow, canSend: boolean) {
|
|
161
|
+
return {
|
|
162
|
+
id: row.id,
|
|
163
|
+
name: row.name,
|
|
164
|
+
parentId: null,
|
|
165
|
+
role: row.role,
|
|
166
|
+
sortOrder: row.sortOrder,
|
|
167
|
+
totalEmails: row.totalEmails,
|
|
168
|
+
unreadEmails: row.unreadEmails,
|
|
169
|
+
totalThreads: row.totalThreads,
|
|
170
|
+
unreadThreads: row.unreadThreads,
|
|
171
|
+
myRights: {
|
|
172
|
+
mayReadItems: true,
|
|
173
|
+
mayAddItems: row.role !== "sent",
|
|
174
|
+
mayRemoveItems: true,
|
|
175
|
+
maySetSeen: true,
|
|
176
|
+
maySetKeywords: false,
|
|
177
|
+
mayCreateChild: false,
|
|
178
|
+
mayRename: false,
|
|
179
|
+
mayDelete: false,
|
|
180
|
+
maySubmit: canSend,
|
|
181
|
+
},
|
|
182
|
+
isSubscribed: true,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function mailboxGet(state: RequestState, args: Args) {
|
|
187
|
+
const owner = account(state, args);
|
|
188
|
+
const { state: mailboxState, mailboxes } = await mailboxStub(state.context.env, owner.id).jmapMailboxes(state.context.user.id);
|
|
189
|
+
const ids = args.ids == null ? mailboxes.map((row) => row.id) : stringIds(args.ids);
|
|
190
|
+
const byId = new Map(mailboxes.map((row) => [row.id, row]));
|
|
191
|
+
return {
|
|
192
|
+
accountId: owner.id,
|
|
193
|
+
state: mailboxState,
|
|
194
|
+
list: ids.flatMap((id) => {
|
|
195
|
+
const row = byId.get(id);
|
|
196
|
+
return row ? [pick(mailboxObject(row, owner.canSend), args.properties)] : [];
|
|
197
|
+
}),
|
|
198
|
+
notFound: ids.filter((id) => !byId.has(id)),
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function mailboxQuery(state: RequestState, args: Args) {
|
|
203
|
+
const owner = account(state, args);
|
|
204
|
+
const { state: mailboxState, mailboxes } = await mailboxStub(state.context.env, owner.id).jmapMailboxes(state.context.user.id);
|
|
205
|
+
const filter = isRecord(args.filter) ? args.filter : {};
|
|
206
|
+
const ids = mailboxes
|
|
207
|
+
.filter((row) => !("role" in filter) || row.role === filter.role)
|
|
208
|
+
.filter((row) => typeof filter.name !== "string" || row.name.toLowerCase().includes(filter.name.toLowerCase()))
|
|
209
|
+
.map((row) => row.id);
|
|
210
|
+
return { accountId: owner.id, queryState: mailboxState, canCalculateChanges: false, position: 0, ids, total: ids.length };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// -------------------------------------------------------------------- email
|
|
214
|
+
|
|
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
|
+
return {
|
|
233
|
+
...(typeof value.inMailbox === "string" ? { inMailbox: value.inMailbox } : {}),
|
|
234
|
+
...(Array.isArray(value.inMailboxOtherThan) ? { inMailboxOtherThan: value.inMailboxOtherThan.map(String) } : {}),
|
|
235
|
+
...(typeof value.before === "string" ? { before: Date.parse(value.before) } : {}),
|
|
236
|
+
...(typeof value.after === "string" ? { after: Date.parse(value.after) } : {}),
|
|
237
|
+
...(typeof value.text === "string" ? { text: value.text } : {}),
|
|
238
|
+
...(typeof value.from === "string" ? { from: value.from } : {}),
|
|
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 } : {}),
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async function emailQuery(state: RequestState, args: Args) {
|
|
248
|
+
const owner = account(state, args);
|
|
249
|
+
const sort = Array.isArray(args.sort) ? args.sort : [];
|
|
250
|
+
for (const comparator of sort) {
|
|
251
|
+
if (!isRecord(comparator) || !["receivedAt", "sentAt"].includes(String(comparator.property))) {
|
|
252
|
+
throw new MethodError("unsupportedSort", "Emails sort by receivedAt or sentAt");
|
|
253
|
+
}
|
|
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
|
+
});
|
|
266
|
+
return {
|
|
267
|
+
accountId: owner.id,
|
|
268
|
+
queryState: result.state,
|
|
269
|
+
canCalculateChanges: false,
|
|
270
|
+
position,
|
|
271
|
+
ids: result.ids,
|
|
272
|
+
total: result.total,
|
|
273
|
+
limit,
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const defaultEmailProperties = [
|
|
278
|
+
"id", "blobId", "threadId", "mailboxIds", "keywords", "size", "receivedAt", "messageId",
|
|
279
|
+
"inReplyTo", "references", "sender", "from", "to", "cc", "bcc", "replyTo", "subject",
|
|
280
|
+
"sentAt", "hasAttachment", "preview", "bodyValues", "textBody", "htmlBody", "attachments",
|
|
281
|
+
];
|
|
282
|
+
|
|
283
|
+
async function emailObject(
|
|
284
|
+
env: Env,
|
|
285
|
+
row: { email: Email; mailboxId: string; seen: boolean },
|
|
286
|
+
args: Args,
|
|
287
|
+
) {
|
|
288
|
+
const { email } = row;
|
|
289
|
+
const raw = `raw~${email.id}`;
|
|
290
|
+
const textBody = [{
|
|
291
|
+
partId: "text", blobId: raw, size: email.bodyText?.length ?? 0, name: null,
|
|
292
|
+
type: "text/plain", charset: "utf-8", disposition: null, cid: null,
|
|
293
|
+
}];
|
|
294
|
+
const htmlBody = email.bodyHtmlR2Key
|
|
295
|
+
? [{ partId: "html", blobId: raw, size: 0, name: null, type: "text/html", charset: "utf-8", disposition: null, cid: null }]
|
|
296
|
+
: textBody;
|
|
297
|
+
const attachments = email.attachmentsJson.map((attachment) => ({
|
|
298
|
+
partId: `att-${attachment.id}`,
|
|
299
|
+
blobId: `att~${email.id}~${attachment.id}`,
|
|
300
|
+
size: attachment.size,
|
|
301
|
+
name: attachment.filename,
|
|
302
|
+
type: attachment.contentType,
|
|
303
|
+
charset: null,
|
|
304
|
+
disposition: attachment.disposition,
|
|
305
|
+
cid: attachment.contentId,
|
|
306
|
+
}));
|
|
307
|
+
const properties = Array.isArray(args.properties) ? args.properties as string[] : defaultEmailProperties;
|
|
308
|
+
const maxBytes = Number(args.maxBodyValueBytes ?? 0) || 0;
|
|
309
|
+
const bodyValue = (value: string) => ({
|
|
310
|
+
value: maxBytes && value.length > maxBytes ? value.slice(0, maxBytes) : value,
|
|
311
|
+
isEncodingProblem: false,
|
|
312
|
+
isTruncated: Boolean(maxBytes && value.length > maxBytes),
|
|
313
|
+
});
|
|
314
|
+
const bodyValues: Record<string, ReturnType<typeof bodyValue>> = {};
|
|
315
|
+
if (properties.includes("bodyValues")) {
|
|
316
|
+
const wantText = args.fetchTextBodyValues === true || args.fetchAllBodyValues === true;
|
|
317
|
+
const wantHtml = args.fetchHTMLBodyValues === true || args.fetchAllBodyValues === true;
|
|
318
|
+
if (wantText || (wantHtml && !email.bodyHtmlR2Key)) bodyValues.text = bodyValue(email.bodyText ?? "");
|
|
319
|
+
if (wantHtml && email.bodyHtmlR2Key) {
|
|
320
|
+
const object = await env.MAIL_STORAGE.get(email.bodyHtmlR2Key);
|
|
321
|
+
bodyValues.html = bodyValue(object ? await object.text() : "");
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
const timestamp = email.timelineAt.toISOString();
|
|
325
|
+
const object = {
|
|
326
|
+
id: email.id,
|
|
327
|
+
blobId: raw,
|
|
328
|
+
threadId: email.conversationId,
|
|
329
|
+
mailboxIds: { [row.mailboxId]: true },
|
|
330
|
+
keywords: row.seen ? { $seen: true } : {},
|
|
331
|
+
size: (email.bodyText?.length ?? 0) + email.attachmentsJson.reduce((total, attachment) => total + attachment.size, 0),
|
|
332
|
+
receivedAt: timestamp,
|
|
333
|
+
messageId: email.messageIdHeader ? [email.messageIdHeader.replace(/^<|>$/gu, "")] : null,
|
|
334
|
+
inReplyTo: email.inReplyToJson?.length ? email.inReplyToJson : null,
|
|
335
|
+
references: email.referencesJson?.length ? email.referencesJson : null,
|
|
336
|
+
sender: null,
|
|
337
|
+
from: addresses(email.fromJson),
|
|
338
|
+
to: addresses(email.toJson),
|
|
339
|
+
cc: addresses(email.ccJson),
|
|
340
|
+
bcc: addresses(email.bccJson),
|
|
341
|
+
replyTo: addresses(email.replyToJson),
|
|
342
|
+
subject: email.subject,
|
|
343
|
+
sentAt: timestamp,
|
|
344
|
+
hasAttachment: attachments.some((attachment) => attachment.disposition === "attachment"),
|
|
345
|
+
preview: email.preview,
|
|
346
|
+
bodyValues,
|
|
347
|
+
textBody,
|
|
348
|
+
htmlBody,
|
|
349
|
+
attachments,
|
|
350
|
+
bodyStructure: { partId: null, type: "multipart/mixed", subParts: [...htmlBody, ...attachments] },
|
|
351
|
+
};
|
|
352
|
+
return Object.fromEntries(Object.entries(object).filter(([key]) => key === "id" || properties.includes(key)));
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
async function emailGet(state: RequestState, args: Args) {
|
|
356
|
+
const owner = account(state, args);
|
|
357
|
+
if (args.ids == null) throw new MethodError("requestTooLarge", "Ask for emails by id");
|
|
358
|
+
const ids = stringIds(args.ids);
|
|
359
|
+
const result = await mailboxStub(state.context.env, owner.id).jmapEmails(state.context.user.id, ids);
|
|
360
|
+
const found = new Set(result.emails.map((row) => row.email.id));
|
|
361
|
+
return {
|
|
362
|
+
accountId: owner.id,
|
|
363
|
+
state: result.state,
|
|
364
|
+
list: await Promise.all(result.emails.map((row) => emailObject(state.context.env, row as never, args))),
|
|
365
|
+
notFound: ids.filter((id) => !found.has(id)),
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** The keyword and mailbox changes in an Email/set update patch. */
|
|
370
|
+
function emailPatch(patch: Args) {
|
|
371
|
+
let seen: boolean | undefined;
|
|
372
|
+
let target: string | undefined;
|
|
373
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
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 };
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function draftFrom(owner: JmapAccount, input: Args): Draft | string {
|
|
396
|
+
const list = (value: unknown) =>
|
|
397
|
+
Array.isArray(value) ? value.flatMap((item) => isRecord(item) && typeof item.email === "string" ? [item.email] : []) : [];
|
|
398
|
+
const bodyValues = isRecord(input.bodyValues) ? input.bodyValues : {};
|
|
399
|
+
const partText = (parts: unknown) => {
|
|
400
|
+
if (!Array.isArray(parts) || !isRecord(parts[0])) return undefined;
|
|
401
|
+
const value = bodyValues[String(parts[0].partId)];
|
|
402
|
+
return isRecord(value) && typeof value.value === "string" ? value.value : undefined;
|
|
403
|
+
};
|
|
404
|
+
const bodyText = partText(input.textBody);
|
|
405
|
+
const bodyHtml = partText(input.htmlBody);
|
|
406
|
+
if (bodyText === undefined && bodyHtml === undefined) return "Give the message a textBody or htmlBody with bodyValues";
|
|
407
|
+
const attachments: DraftAttachment[] = [];
|
|
408
|
+
for (const part of Array.isArray(input.attachments) ? input.attachments : []) {
|
|
409
|
+
const upload = isRecord(part) && typeof part.blobId === "string" ? UPLOAD_BLOB.exec(part.blobId) : null;
|
|
410
|
+
if (!upload) return "Attachments must be blobs uploaded to this account";
|
|
411
|
+
const inline = part.disposition === "inline";
|
|
412
|
+
const contentId = typeof part.cid === "string" ? part.cid.replace(/^<|>$/gu, "") : undefined;
|
|
413
|
+
if (inline && !contentId) return "Inline attachments need a cid";
|
|
414
|
+
attachments.push({
|
|
415
|
+
uploadId: upload[1]!,
|
|
416
|
+
name: typeof part.name === "string" ? part.name : "attachment",
|
|
417
|
+
type: typeof part.type === "string" ? part.type : "application/octet-stream",
|
|
418
|
+
disposition: inline ? "inline" : "attachment",
|
|
419
|
+
...(inline ? { contentId } : {}),
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
if (attachments.length > MAX_COMPOSER_ATTACHMENT_COUNT) {
|
|
423
|
+
return `At most ${MAX_COMPOSER_ATTACHMENT_COUNT} attachments per message`;
|
|
424
|
+
}
|
|
425
|
+
if (new Set(attachments.map((item) => item.uploadId)).size !== attachments.length) {
|
|
426
|
+
return "Each blob can be attached once";
|
|
427
|
+
}
|
|
428
|
+
return {
|
|
429
|
+
accountId: owner.id,
|
|
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
|
+
};
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
async function emailSet(state: RequestState, args: Args) {
|
|
441
|
+
const owner = account(state, args);
|
|
442
|
+
const stub = mailboxStub(state.context.env, owner.id);
|
|
443
|
+
const oldState = await stub.jmapState();
|
|
444
|
+
if (args.ifInState !== undefined && args.ifInState !== oldState) throw new MethodError("stateMismatch");
|
|
445
|
+
const created: Args = {};
|
|
446
|
+
const notCreated: Args = {};
|
|
447
|
+
for (const [creationId, input] of Object.entries(isRecord(args.create) ? args.create : {})) {
|
|
448
|
+
const draft = isRecord(input) ? draftFrom(owner, input) : "Invalid email";
|
|
449
|
+
if (typeof draft === "string") {
|
|
450
|
+
notCreated[creationId] = { type: "invalidProperties", description: draft };
|
|
451
|
+
continue;
|
|
452
|
+
}
|
|
453
|
+
try {
|
|
454
|
+
// The name and type come with the email, after the bytes were uploaded.
|
|
455
|
+
await Promise.all(draft.attachments.map((attachment) => describeComposerUpload({
|
|
456
|
+
env: state.context.env,
|
|
457
|
+
mailboxId: owner.id,
|
|
458
|
+
userId: state.context.user.id,
|
|
459
|
+
uploadId: attachment.uploadId,
|
|
460
|
+
filename: attachment.name,
|
|
461
|
+
contentType: attachment.type,
|
|
462
|
+
})));
|
|
463
|
+
} catch (error) {
|
|
464
|
+
if (!(error instanceof UploadValidationError)) throw error;
|
|
465
|
+
notCreated[creationId] = { type: "blobNotFound", description: error.message };
|
|
466
|
+
continue;
|
|
467
|
+
}
|
|
468
|
+
// Drafts are not stored: one is sent by EmailSubmission/set in the same request.
|
|
469
|
+
const id = `draft-${crypto.randomUUID()}`;
|
|
470
|
+
state.drafts.set(id, draft);
|
|
471
|
+
state.createdIds[creationId] = id;
|
|
472
|
+
created[creationId] = { id, blobId: `draft~${id}`, threadId: id, size: draft.bodyText.length };
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
const updated: Args = {};
|
|
476
|
+
const notUpdated: Args = {};
|
|
477
|
+
const reads: Array<[string, boolean]> = [];
|
|
478
|
+
const moves = new Map<string, string[]>();
|
|
479
|
+
for (const [id, patch] of Object.entries(isRecord(args.update) ? args.update : {})) {
|
|
480
|
+
const change = isRecord(patch) ? emailPatch(patch) : { error: "Invalid patch" };
|
|
481
|
+
if ("error" in change && change.error) {
|
|
482
|
+
notUpdated[id] = { type: "invalidProperties", description: change.error };
|
|
483
|
+
continue;
|
|
484
|
+
}
|
|
485
|
+
const { seen, target } = change as { seen?: boolean; target?: string };
|
|
486
|
+
if (seen !== undefined) reads.push([id, seen]);
|
|
487
|
+
if (target) moves.set(target, [...(moves.get(target) ?? []), id]);
|
|
488
|
+
updated[id] = null;
|
|
489
|
+
}
|
|
490
|
+
for (const [id, seen] of reads) {
|
|
491
|
+
if (!(await stub.setMessageRead(state.context.user.id, id, seen))) {
|
|
492
|
+
delete updated[id];
|
|
493
|
+
notUpdated[id] = { type: "notFound" };
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
for (const [target, ids] of moves) {
|
|
497
|
+
if (!(await stub.jmapMoveEmails(ids, target))) {
|
|
498
|
+
for (const id of ids) {
|
|
499
|
+
delete updated[id];
|
|
500
|
+
notUpdated[id] = { type: "invalidProperties", description: `Emails cannot be moved to ${target}` };
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
const destroyed: string[] = [];
|
|
506
|
+
const notDestroyed: Args = {};
|
|
507
|
+
const destroyIds = args.destroy == null ? [] : stringIds(args.destroy, "destroy");
|
|
508
|
+
if (destroyIds.length) {
|
|
509
|
+
const { emails } = await stub.jmapEmails(state.context.user.id, destroyIds);
|
|
510
|
+
const inTrash = emails.filter((row) => row.mailboxId === "trash");
|
|
511
|
+
const elsewhere = emails.filter((row) => row.mailboxId !== "trash");
|
|
512
|
+
// Mail goes to Trash first; destroying it there deletes its conversation.
|
|
513
|
+
if (elsewhere.length) await stub.jmapMoveEmails(elsewhere.map((row) => row.email.id), "trash");
|
|
514
|
+
if (inTrash.length) {
|
|
515
|
+
await stub.permanentlyDeleteConversations([...new Set(inTrash.map((row) => row.email.conversationId))]);
|
|
516
|
+
}
|
|
517
|
+
const found = new Set(emails.map((row) => row.email.id));
|
|
518
|
+
for (const id of destroyIds) {
|
|
519
|
+
if (found.has(id)) destroyed.push(id);
|
|
520
|
+
else notDestroyed[id] = { type: "notFound" };
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
return {
|
|
524
|
+
accountId: owner.id,
|
|
525
|
+
oldState,
|
|
526
|
+
newState: await stub.jmapState(),
|
|
527
|
+
created: Object.keys(created).length ? created : null,
|
|
528
|
+
updated: Object.keys(updated).length ? updated : null,
|
|
529
|
+
destroyed: destroyed.length ? destroyed : null,
|
|
530
|
+
notCreated: Object.keys(notCreated).length ? notCreated : null,
|
|
531
|
+
notUpdated: Object.keys(notUpdated).length ? notUpdated : null,
|
|
532
|
+
notDestroyed: Object.keys(notDestroyed).length ? notDestroyed : null,
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// --------------------------------------------------- threads and identities
|
|
537
|
+
|
|
538
|
+
async function threadGet(state: RequestState, args: Args) {
|
|
539
|
+
const owner = account(state, args);
|
|
540
|
+
const ids = stringIds(args.ids);
|
|
541
|
+
const result = await mailboxStub(state.context.env, owner.id).jmapThreads(ids);
|
|
542
|
+
const threads = new Map(result.threads as Array<[string, string[]]>);
|
|
543
|
+
return {
|
|
544
|
+
accountId: owner.id,
|
|
545
|
+
state: result.state,
|
|
546
|
+
list: ids.flatMap((id) => threads.has(id) ? [{ id, emailIds: threads.get(id)! }] : []),
|
|
547
|
+
notFound: ids.filter((id) => !threads.has(id)),
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
function identityGet(state: RequestState, args: Args) {
|
|
552
|
+
const owner = account(state, args);
|
|
553
|
+
const list = owner.canSend
|
|
554
|
+
? [{
|
|
555
|
+
id: owner.id,
|
|
556
|
+
name: owner.displayName,
|
|
557
|
+
email: owner.address,
|
|
558
|
+
replyTo: null,
|
|
559
|
+
bcc: null,
|
|
560
|
+
textSignature: "",
|
|
561
|
+
htmlSignature: "",
|
|
562
|
+
mayDelete: false,
|
|
563
|
+
}]
|
|
564
|
+
: [];
|
|
565
|
+
const ids = args.ids == null ? list.map((identity) => identity.id) : stringIds(args.ids);
|
|
566
|
+
return {
|
|
567
|
+
accountId: owner.id,
|
|
568
|
+
state: "1",
|
|
569
|
+
list: list.filter((identity) => ids.includes(identity.id)),
|
|
570
|
+
notFound: ids.filter((id) => id !== owner.id || !owner.canSend),
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
async function submissionSet(state: RequestState, args: Args, callId: string) {
|
|
575
|
+
const owner = account(state, args);
|
|
576
|
+
if (!owner.canSend) throw new MethodError("forbidden", "This account cannot send");
|
|
577
|
+
const created: Args = {};
|
|
578
|
+
const notCreated: Args = {};
|
|
579
|
+
const sentDrafts = new Map<string, string>();
|
|
580
|
+
for (const [creationId, input] of Object.entries(isRecord(args.create) ? args.create : {})) {
|
|
581
|
+
if (!isRecord(input) || typeof input.emailId !== "string") {
|
|
582
|
+
notCreated[creationId] = { type: "invalidProperties", description: "emailId is required" };
|
|
583
|
+
continue;
|
|
584
|
+
}
|
|
585
|
+
const emailId = input.emailId.startsWith("#")
|
|
586
|
+
? state.createdIds[input.emailId.slice(1)]
|
|
587
|
+
: input.emailId;
|
|
588
|
+
const draft = emailId ? state.drafts.get(emailId) : undefined;
|
|
589
|
+
if (!draft || draft.accountId !== owner.id) {
|
|
590
|
+
notCreated[creationId] = {
|
|
591
|
+
type: "invalidProperties",
|
|
592
|
+
description: "Send an email created by Email/set earlier in the same request",
|
|
593
|
+
};
|
|
594
|
+
continue;
|
|
595
|
+
}
|
|
596
|
+
if (input.identityId !== undefined && input.identityId !== owner.id) {
|
|
597
|
+
notCreated[creationId] = { type: "invalidProperties", description: "Unknown identity" };
|
|
598
|
+
continue;
|
|
599
|
+
}
|
|
600
|
+
try {
|
|
601
|
+
const submission = await submitOutgoing({
|
|
602
|
+
env: state.context.env,
|
|
603
|
+
requestUrl: state.context.requestUrl,
|
|
604
|
+
compose: {
|
|
605
|
+
requestId: crypto.randomUUID(),
|
|
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] = {
|
|
640
|
+
type: "forbiddenToSend",
|
|
641
|
+
description: error instanceof Error ? error.message : "The message could not be sent",
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
// The sent copy is already in Sent; drafts were never stored, so the
|
|
646
|
+
// follow-up Email/set only reports them gone.
|
|
647
|
+
const followUp = [args.onSuccessDestroyEmail, args.onSuccessUpdateEmail ? Object.keys(args.onSuccessUpdateEmail as Args) : null]
|
|
648
|
+
.flatMap((value) => Array.isArray(value) ? value as string[] : [])
|
|
649
|
+
.map((reference) => reference.startsWith("#") ? state.createdIds[reference.slice(1)] : reference)
|
|
650
|
+
.flatMap((id) => id && sentDrafts.has(id) ? [sentDrafts.get(id)!] : []);
|
|
651
|
+
if (followUp.length) {
|
|
652
|
+
const stub = mailboxStub(state.context.env, owner.id);
|
|
653
|
+
const current = await stub.jmapState();
|
|
654
|
+
state.after.push(["Email/set", {
|
|
655
|
+
accountId: owner.id, oldState: current, newState: current,
|
|
656
|
+
created: null, updated: null, destroyed: followUp,
|
|
657
|
+
notCreated: null, notUpdated: null, notDestroyed: null,
|
|
658
|
+
}, callId]);
|
|
659
|
+
}
|
|
660
|
+
return {
|
|
661
|
+
accountId: owner.id,
|
|
662
|
+
oldState: "1",
|
|
663
|
+
newState: "1",
|
|
664
|
+
created: Object.keys(created).length ? created : null,
|
|
665
|
+
notCreated: Object.keys(notCreated).length ? notCreated : null,
|
|
666
|
+
updated: null,
|
|
667
|
+
destroyed: null,
|
|
668
|
+
notUpdated: null,
|
|
669
|
+
notDestroyed: null,
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// --------------------------------------------------------- push (RFC 8620 §7.2)
|
|
674
|
+
|
|
675
|
+
const MAX_PUSH_SUBSCRIPTIONS = 20;
|
|
676
|
+
|
|
677
|
+
type PushSubscriptionRow = typeof jmapPushSubscriptions.$inferSelect;
|
|
678
|
+
|
|
679
|
+
/** url and keys are never returned (§7.2.1). */
|
|
680
|
+
function pushSubscriptionObject(row: PushSubscriptionRow) {
|
|
681
|
+
return {
|
|
682
|
+
id: row.id,
|
|
683
|
+
deviceClientId: row.deviceClientId,
|
|
684
|
+
verificationCode: row.verifiedAt ? row.verificationCode : null,
|
|
685
|
+
expires: row.expiresAt.toISOString(),
|
|
686
|
+
types: row.typesJson,
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
function pushTypes(value: unknown) {
|
|
691
|
+
if (value === null || value === undefined) return null;
|
|
692
|
+
if (!Array.isArray(value) || value.some((type) => typeof type !== "string")) {
|
|
693
|
+
throw new MethodError("invalidArguments", "types must be a list of type names or null");
|
|
694
|
+
}
|
|
695
|
+
return value as string[];
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
function ownSubscriptions(state: RequestState) {
|
|
699
|
+
return and(
|
|
700
|
+
eq(jmapPushSubscriptions.userId, state.context.user.id),
|
|
701
|
+
eq(jmapPushSubscriptions.clientId, state.context.clientId),
|
|
702
|
+
);
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
async function pushSubscriptionGet(state: RequestState, args: Args) {
|
|
706
|
+
const db = createDb(state.context.env.DB);
|
|
707
|
+
const ids = args.ids == null ? null : stringIds(args.ids);
|
|
708
|
+
const rows = await db.select().from(jmapPushSubscriptions).where(ids
|
|
709
|
+
? and(ownSubscriptions(state), inArray(jmapPushSubscriptions.id, ids.length ? ids : [""]))
|
|
710
|
+
: ownSubscriptions(state));
|
|
711
|
+
const found = new Set(rows.map((row) => row.id));
|
|
712
|
+
return {
|
|
713
|
+
list: rows.map((row) => pick(pushSubscriptionObject(row), args.properties)),
|
|
714
|
+
notFound: ids ? ids.filter((id) => !found.has(id)) : [],
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
function pushKeys(value: unknown) {
|
|
719
|
+
if (value === null || value === undefined) return { p256dh: null, auth: null };
|
|
720
|
+
if (!isRecord(value) || typeof value.p256dh !== "string" || typeof value.auth !== "string") {
|
|
721
|
+
return "keys has p256dh and auth";
|
|
722
|
+
}
|
|
723
|
+
return { p256dh: value.p256dh, auth: value.auth };
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
function pushUrl(value: unknown) {
|
|
727
|
+
if (typeof value !== "string") return null;
|
|
728
|
+
try {
|
|
729
|
+
const url = new URL(value);
|
|
730
|
+
return url.protocol === "https:" ? url.toString() : null;
|
|
731
|
+
} catch {
|
|
732
|
+
return null;
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
async function pushSubscriptionSet(state: RequestState, args: Args) {
|
|
737
|
+
const db = createDb(state.context.env.DB);
|
|
738
|
+
if (args.ifInState !== undefined && args.ifInState !== null) throw new MethodError("stateMismatch");
|
|
739
|
+
const created: Args = {};
|
|
740
|
+
const notCreated: Args = {};
|
|
741
|
+
for (const [creationId, input] of Object.entries(isRecord(args.create) ? args.create : {})) {
|
|
742
|
+
const url = isRecord(input) ? pushUrl(input.url) : null;
|
|
743
|
+
const keys = isRecord(input) ? pushKeys(input.keys) : "Invalid subscription";
|
|
744
|
+
if (!isRecord(input) || typeof input.deviceClientId !== "string" || !input.deviceClientId || !url) {
|
|
745
|
+
notCreated[creationId] = { type: "invalidProperties", description: "deviceClientId and an https url are required" };
|
|
746
|
+
continue;
|
|
747
|
+
}
|
|
748
|
+
if (typeof keys === "string" || input.verificationCode !== undefined) {
|
|
749
|
+
notCreated[creationId] = {
|
|
750
|
+
type: "invalidProperties",
|
|
751
|
+
description: typeof keys === "string" ? keys : "verificationCode is set by update",
|
|
752
|
+
};
|
|
753
|
+
continue;
|
|
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` };
|
|
764
|
+
continue;
|
|
765
|
+
}
|
|
766
|
+
let types: string[] | null;
|
|
767
|
+
try {
|
|
768
|
+
types = pushTypes(input.types);
|
|
769
|
+
} catch (error) {
|
|
770
|
+
notCreated[creationId] = { type: "invalidProperties", description: (error as Error).message };
|
|
771
|
+
continue;
|
|
772
|
+
}
|
|
773
|
+
const row: PushSubscriptionRow = {
|
|
774
|
+
id: crypto.randomUUID(),
|
|
775
|
+
userId: state.context.user.id,
|
|
776
|
+
clientId: state.context.clientId,
|
|
777
|
+
deviceClientId: input.deviceClientId,
|
|
778
|
+
url,
|
|
779
|
+
...keys,
|
|
780
|
+
verificationCode: newVerificationCode(),
|
|
781
|
+
verifiedAt: null,
|
|
782
|
+
expiresAt: subscriptionExpiry(input.expires),
|
|
783
|
+
typesJson: types,
|
|
784
|
+
createdAt: new Date(),
|
|
785
|
+
};
|
|
786
|
+
// A device has one subscription; a new one replaces it.
|
|
787
|
+
await db.batch([
|
|
788
|
+
db.delete(jmapPushSubscriptions).where(and(
|
|
789
|
+
eq(jmapPushSubscriptions.userId, row.userId),
|
|
790
|
+
eq(jmapPushSubscriptions.deviceClientId, row.deviceClientId),
|
|
791
|
+
)),
|
|
792
|
+
db.insert(jmapPushSubscriptions).values(row),
|
|
793
|
+
]);
|
|
794
|
+
state.createdIds[creationId] = row.id;
|
|
795
|
+
created[creationId] = { id: row.id, expires: row.expiresAt.toISOString() };
|
|
796
|
+
state.context.defer(sendVerification(row, state.context.vapid).catch((error) => {
|
|
797
|
+
console.error("Could not send JMAP push verification", error instanceof Error ? error.message : String(error));
|
|
798
|
+
}));
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
const updated: Args = {};
|
|
802
|
+
const notUpdated: Args = {};
|
|
803
|
+
for (const [id, patch] of Object.entries(isRecord(args.update) ? args.update : {})) {
|
|
804
|
+
const [row] = await db.select().from(jmapPushSubscriptions).where(and(ownSubscriptions(state), eq(jmapPushSubscriptions.id, id)));
|
|
805
|
+
if (!row) {
|
|
806
|
+
notUpdated[id] = { type: "notFound" };
|
|
807
|
+
continue;
|
|
808
|
+
}
|
|
809
|
+
if (!isRecord(patch) || Object.keys(patch).some((key) => !["verificationCode", "expires", "types"].includes(key))) {
|
|
810
|
+
notUpdated[id] = { type: "invalidProperties", description: "Only verificationCode, expires, and types change" };
|
|
811
|
+
continue;
|
|
812
|
+
}
|
|
813
|
+
if (patch.verificationCode !== undefined && patch.verificationCode !== row.verificationCode) {
|
|
814
|
+
notUpdated[id] = { type: "invalidProperties", description: "The verification code does not match" };
|
|
815
|
+
continue;
|
|
816
|
+
}
|
|
817
|
+
let types = row.typesJson;
|
|
818
|
+
try {
|
|
819
|
+
if ("types" in patch) types = pushTypes(patch.types);
|
|
820
|
+
} catch (error) {
|
|
821
|
+
notUpdated[id] = { type: "invalidProperties", description: (error as Error).message };
|
|
822
|
+
continue;
|
|
823
|
+
}
|
|
824
|
+
const expiresAt = "expires" in patch ? subscriptionExpiry(patch.expires) : row.expiresAt;
|
|
825
|
+
await db.update(jmapPushSubscriptions).set({
|
|
826
|
+
verifiedAt: patch.verificationCode !== undefined ? row.verifiedAt ?? new Date() : row.verifiedAt,
|
|
827
|
+
expiresAt,
|
|
828
|
+
typesJson: types,
|
|
829
|
+
}).where(eq(jmapPushSubscriptions.id, id));
|
|
830
|
+
const askedExpiry = typeof patch.expires === "string" ? Date.parse(patch.expires) : null;
|
|
831
|
+
updated[id] = askedExpiry !== null && askedExpiry !== expiresAt.getTime()
|
|
832
|
+
? { expires: expiresAt.toISOString() }
|
|
833
|
+
: null;
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
const destroyIds = args.destroy == null ? [] : stringIds(args.destroy, "destroy");
|
|
837
|
+
const removed = destroyIds.length
|
|
838
|
+
? await db.delete(jmapPushSubscriptions)
|
|
839
|
+
.where(and(ownSubscriptions(state), inArray(jmapPushSubscriptions.id, destroyIds)))
|
|
840
|
+
.returning({ id: jmapPushSubscriptions.id })
|
|
841
|
+
: [];
|
|
842
|
+
const destroyed = removed.map((row) => row.id);
|
|
843
|
+
const notDestroyed = Object.fromEntries(destroyIds
|
|
844
|
+
.filter((id) => !destroyed.includes(id))
|
|
845
|
+
.map((id) => [id, { type: "notFound" }]));
|
|
846
|
+
return {
|
|
847
|
+
created: Object.keys(created).length ? created : null,
|
|
848
|
+
updated: Object.keys(updated).length ? updated : null,
|
|
849
|
+
destroyed: destroyed.length ? destroyed : null,
|
|
850
|
+
notCreated: Object.keys(notCreated).length ? notCreated : null,
|
|
851
|
+
notUpdated: Object.keys(notUpdated).length ? notUpdated : null,
|
|
852
|
+
notDestroyed: Object.keys(notDestroyed).length ? notDestroyed : null,
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
// ----------------------------------------------------------------- dispatch
|
|
857
|
+
|
|
858
|
+
const methods: Record<string, (state: RequestState, args: Args, callId: string) => unknown> = {
|
|
859
|
+
"Core/echo": (_state, args) => args,
|
|
860
|
+
"Mailbox/get": mailboxGet,
|
|
861
|
+
"Mailbox/query": mailboxQuery,
|
|
862
|
+
"Mailbox/changes": async (state, args) => {
|
|
863
|
+
const owner = account(state, args);
|
|
864
|
+
return changes(owner.id, args.sinceState, await mailboxStub(state.context.env, owner.id).jmapState());
|
|
865
|
+
},
|
|
866
|
+
"Email/query": emailQuery,
|
|
867
|
+
"Email/get": emailGet,
|
|
868
|
+
"Email/set": emailSet,
|
|
869
|
+
"Email/changes": async (state, args) => {
|
|
870
|
+
const owner = account(state, args);
|
|
871
|
+
return changes(owner.id, args.sinceState, await mailboxStub(state.context.env, owner.id).jmapState());
|
|
872
|
+
},
|
|
873
|
+
"Thread/get": threadGet,
|
|
874
|
+
"Thread/changes": async (state, args) => {
|
|
875
|
+
const owner = account(state, args);
|
|
876
|
+
return changes(owner.id, args.sinceState, await mailboxStub(state.context.env, owner.id).jmapState());
|
|
877
|
+
},
|
|
878
|
+
"SearchSnippet/get": (state, args) => {
|
|
879
|
+
const owner = account(state, args);
|
|
880
|
+
const ids = stringIds(args.emailIds, "emailIds");
|
|
881
|
+
return { accountId: owner.id, list: ids.map((emailId) => ({ emailId, subject: null, preview: null })), notFound: [] };
|
|
882
|
+
},
|
|
883
|
+
"Identity/get": identityGet,
|
|
884
|
+
"EmailSubmission/set": submissionSet,
|
|
885
|
+
"PushSubscription/get": pushSubscriptionGet,
|
|
886
|
+
"PushSubscription/set": pushSubscriptionSet,
|
|
887
|
+
};
|
|
888
|
+
|
|
889
|
+
export async function runJmapRequest(context: JmapContext, body: unknown) {
|
|
890
|
+
if (!isRecord(body) || !Array.isArray(body.using) || !Array.isArray(body.methodCalls)) {
|
|
891
|
+
throw new JmapError("urn:ietf:params:jmap:error:notRequest", "A JMAP request has using and methodCalls");
|
|
892
|
+
}
|
|
893
|
+
if (!body.using.includes(CORE)) {
|
|
894
|
+
throw new JmapError("urn:ietf:params:jmap:error:unknownCapability", `${CORE} is required`);
|
|
895
|
+
}
|
|
896
|
+
if (body.methodCalls.length > 32) {
|
|
897
|
+
throw new JmapError("urn:ietf:params:jmap:error:limit", "At most 32 method calls per request");
|
|
898
|
+
}
|
|
899
|
+
const state: RequestState = {
|
|
900
|
+
context,
|
|
901
|
+
responses: [],
|
|
902
|
+
createdIds: isRecord(body.createdIds) ? { ...body.createdIds as Record<string, string> } : {},
|
|
903
|
+
drafts: new Map(),
|
|
904
|
+
after: [],
|
|
905
|
+
};
|
|
906
|
+
for (const call of body.methodCalls) {
|
|
907
|
+
if (!Array.isArray(call) || typeof call[0] !== "string" || !isRecord(call[1]) || typeof call[2] !== "string") {
|
|
908
|
+
throw new JmapError("urn:ietf:params:jmap:error:notRequest", "Each method call is [name, arguments, id]");
|
|
909
|
+
}
|
|
910
|
+
const [name, rawArgs, callId] = call as Invocation;
|
|
911
|
+
const method = methods[name];
|
|
912
|
+
try {
|
|
913
|
+
if (!method) throw new MethodError("unknownMethod");
|
|
914
|
+
const args = resolveReferences(state, rawArgs);
|
|
915
|
+
state.responses.push([name, await method(state, args, callId) as Args, callId]);
|
|
916
|
+
state.responses.push(...state.after.splice(0));
|
|
917
|
+
} catch (error) {
|
|
918
|
+
if (!(error instanceof MethodError)) throw error;
|
|
919
|
+
state.responses.push(["error", { type: error.type, description: error.message }, callId]);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
return {
|
|
923
|
+
methodResponses: state.responses,
|
|
924
|
+
...(isRecord(body.createdIds) ? { createdIds: state.createdIds } : {}),
|
|
925
|
+
sessionState: String(context.accounts.length),
|
|
926
|
+
};
|
|
927
|
+
}
|