@open-workspace/email 0.2.0 → 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.
@@ -1,7 +1,13 @@
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";
1
5
  import { mailboxStub } from "../mailbox";
2
6
  import type { Email } from "../mailbox/schema";
3
7
  import type { JmapEmailFilter, JmapMailboxRow } from "../mailbox/jmap-store";
4
8
  import { submitOutgoing } from "../mail/outbound-service";
9
+ import { describeComposerUpload, UploadValidationError } from "../mail/uploads";
10
+ import { newVerificationCode, sendVerification, subscriptionExpiry, type PushVapid } from "./push";
5
11
 
6
12
  const CORE = "urn:ietf:params:jmap:core";
7
13
  const MAX_OBJECTS = 500;
@@ -19,6 +25,10 @@ export type JmapAccount = {
19
25
  export type JmapContext = {
20
26
  env: Env;
21
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;
22
32
  accounts: JmapAccount[];
23
33
  requestUrl: string;
24
34
  defer: (task: Promise<unknown>) => void;
@@ -41,6 +51,15 @@ class MethodError extends Error {
41
51
  }
42
52
  }
43
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
+
44
63
  /** A draft from Email/set create; it lives only for the request that sends it. */
45
64
  type Draft = {
46
65
  accountId: string;
@@ -50,8 +69,12 @@ type Draft = {
50
69
  subject: string;
51
70
  bodyText: string;
52
71
  bodyHtml?: string;
72
+ attachments: DraftAttachment[];
53
73
  };
54
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
+
55
78
  type RequestState = {
56
79
  context: JmapContext;
57
80
  responses: Invocation[];
@@ -381,6 +404,27 @@ function draftFrom(owner: JmapAccount, input: Args): Draft | string {
381
404
  const bodyText = partText(input.textBody);
382
405
  const bodyHtml = partText(input.htmlBody);
383
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
+ }
384
428
  return {
385
429
  accountId: owner.id,
386
430
  to: list(input.to),
@@ -389,6 +433,7 @@ function draftFrom(owner: JmapAccount, input: Args): Draft | string {
389
433
  subject: typeof input.subject === "string" ? input.subject : "",
390
434
  bodyText: bodyText ?? "",
391
435
  ...(bodyHtml !== undefined ? { bodyHtml } : {}),
436
+ attachments,
392
437
  };
393
438
  }
394
439
 
@@ -405,6 +450,21 @@ async function emailSet(state: RequestState, args: Args) {
405
450
  notCreated[creationId] = { type: "invalidProperties", description: draft };
406
451
  continue;
407
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
+ }
408
468
  // Drafts are not stored: one is sent by EmailSubmission/set in the same request.
409
469
  const id = `draft-${crypto.randomUUID()}`;
410
470
  state.drafts.set(id, draft);
@@ -550,7 +610,11 @@ async function submissionSet(state: RequestState, args: Args, callId: string) {
550
610
  subject: draft.subject,
551
611
  bodyText: draft.bodyText,
552
612
  ...(draft.bodyHtml !== undefined ? { bodyHtml: draft.bodyHtml } : {}),
553
- attachments: [],
613
+ attachments: draft.attachments.map((attachment) => ({
614
+ uploadId: attachment.uploadId,
615
+ disposition: attachment.disposition,
616
+ ...(attachment.contentId ? { contentId: attachment.contentId } : {}),
617
+ })),
554
618
  userId: state.context.user.id,
555
619
  },
556
620
  conversationId: `conv_${crypto.randomUUID().replaceAll("-", "")}`,
@@ -606,6 +670,189 @@ async function submissionSet(state: RequestState, args: Args, callId: string) {
606
670
  };
607
671
  }
608
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
+
609
856
  // ----------------------------------------------------------------- dispatch
610
857
 
611
858
  const methods: Record<string, (state: RequestState, args: Args, callId: string) => unknown> = {
@@ -635,6 +882,8 @@ const methods: Record<string, (state: RequestState, args: Args, callId: string)
635
882
  },
636
883
  "Identity/get": identityGet,
637
884
  "EmailSubmission/set": submissionSet,
885
+ "PushSubscription/get": pushSubscriptionGet,
886
+ "PushSubscription/set": pushSubscriptionSet,
638
887
  };
639
888
 
640
889
  export async function runJmapRequest(context: JmapContext, body: unknown) {
@@ -0,0 +1,123 @@
1
+ import { rawPayload, sendPushNotification, topicFromString } from "@mmmike/web-push/send";
2
+ import { and, eq, gt, inArray, isNotNull, lte } from "drizzle-orm";
3
+ import { createDb } from "@open-workspace/core/worker/db/client.ts";
4
+ import { mailboxAccess, mailboxes } from "@open-workspace/core/worker/db/schema.ts";
5
+ import { createId } from "@open-workspace/core/worker/lib/ids.ts";
6
+ import { jmapPushSubscriptions } from "../db/schema";
7
+
8
+ /** Data types whose state a mailbox account reports; one state covers them all. */
9
+ export const JMAP_PUSH_TYPES = ["Email", "Mailbox", "Thread", "EmailDelivery"] as const;
10
+
11
+ /** Subscriptions live a week unless the client asks for less, then renew. */
12
+ const MAX_SUBSCRIPTION_MS = 7 * 24 * 60 * 60 * 1_000;
13
+ /** State changes are worth little once a client resyncs anyway. */
14
+ const STATE_CHANGE_TTL_SECONDS = 24 * 60 * 60;
15
+
16
+ export type PushVapid = { publicKey: string; privateKey: string; subject: string };
17
+
18
+ type Subscription = typeof jmapPushSubscriptions.$inferSelect;
19
+
20
+ export function stateChange(changed: Record<string, string>) {
21
+ return {
22
+ "@type": "StateChange",
23
+ changed: Object.fromEntries(Object.entries(changed).map(([accountId, state]) => [
24
+ accountId,
25
+ Object.fromEntries(JMAP_PUSH_TYPES.map((type) => [type, state])),
26
+ ])),
27
+ };
28
+ }
29
+
30
+ export function subscriptionExpiry(requested: unknown, now = Date.now()) {
31
+ const latest = now + MAX_SUBSCRIPTION_MS;
32
+ const asked = typeof requested === "string" ? Date.parse(requested) : Number.NaN;
33
+ return new Date(Number.isFinite(asked) ? Math.max(now, Math.min(asked, latest)) : latest);
34
+ }
35
+
36
+ /**
37
+ * POSTs a JMAP push object to a subscription: Web Push encrypted (RFC 8291)
38
+ * and VAPID-signed when the client gave keys, plain JSON otherwise.
39
+ * Returns false when the push service says the subscription is gone.
40
+ */
41
+ export async function postToSubscription(
42
+ subscription: Pick<Subscription, "url" | "p256dh" | "auth">,
43
+ body: unknown,
44
+ vapid: PushVapid | null,
45
+ options: { ttl: number; topic?: string },
46
+ ) {
47
+ if (subscription.p256dh && subscription.auth) {
48
+ if (!vapid) throw new Error("Web Push is not configured");
49
+ return sendPushNotification(
50
+ { endpoint: subscription.url, keys: { p256dh: subscription.p256dh, auth: subscription.auth } },
51
+ rawPayload(JSON.stringify(body)),
52
+ vapid,
53
+ { ttl: options.ttl, urgency: "normal", ...(options.topic ? { topic: options.topic } : {}) },
54
+ );
55
+ }
56
+ const response = await fetch(subscription.url, {
57
+ method: "POST",
58
+ headers: {
59
+ "content-type": "application/json; charset=utf-8",
60
+ ttl: String(options.ttl),
61
+ ...(options.topic ? { topic: options.topic } : {}),
62
+ },
63
+ body: JSON.stringify(body),
64
+ signal: AbortSignal.timeout(30_000),
65
+ });
66
+ if (response.status === 404 || response.status === 410) return false;
67
+ if (!response.ok) throw new Error(`Push endpoint answered ${response.status}`);
68
+ return true;
69
+ }
70
+
71
+ export function newVerificationCode() {
72
+ return createId("pvc");
73
+ }
74
+
75
+ /** Sends the PushVerification object a new subscription is confirmed with. */
76
+ export async function sendVerification(subscription: Subscription, vapid: PushVapid | null) {
77
+ await postToSubscription(subscription, {
78
+ "@type": "PushVerification",
79
+ pushSubscriptionId: subscription.id,
80
+ verificationCode: subscription.verificationCode,
81
+ }, vapid, { ttl: 60 * 60 });
82
+ }
83
+
84
+ /**
85
+ * Tells every verified subscription of someone who can open the mailbox that
86
+ * its state moved. Expired subscriptions are dropped on the way.
87
+ */
88
+ export async function deliverJmapStateChange(
89
+ env: Env,
90
+ input: { mailboxId: string; state: string },
91
+ vapid: PushVapid,
92
+ ) {
93
+ const db = createDb(env.DB);
94
+ const now = new Date();
95
+ await db.delete(jmapPushSubscriptions).where(lte(jmapPushSubscriptions.expiresAt, now));
96
+ const targets = await db
97
+ .select({ subscription: jmapPushSubscriptions })
98
+ .from(jmapPushSubscriptions)
99
+ .innerJoin(mailboxAccess, eq(mailboxAccess.userId, jmapPushSubscriptions.userId))
100
+ .innerJoin(mailboxes, eq(mailboxes.id, mailboxAccess.mailboxId))
101
+ .where(and(
102
+ eq(mailboxAccess.mailboxId, input.mailboxId),
103
+ eq(mailboxes.delivery, "inbox"),
104
+ isNotNull(jmapPushSubscriptions.verifiedAt),
105
+ gt(jmapPushSubscriptions.expiresAt, now),
106
+ ));
107
+ const gone: string[] = [];
108
+ await Promise.all(targets.map(async ({ subscription }) => {
109
+ const types = subscription.typesJson;
110
+ if (types && !types.some((type) => (JMAP_PUSH_TYPES as readonly string[]).includes(type))) return;
111
+ try {
112
+ const delivered = await postToSubscription(subscription, stateChange({ [input.mailboxId]: input.state }), vapid, {
113
+ ttl: STATE_CHANGE_TTL_SECONDS,
114
+ // A newer state replaces an undelivered older one.
115
+ topic: await topicFromString(`jmap:${subscription.id}:${input.mailboxId}`),
116
+ });
117
+ if (!delivered) gone.push(subscription.id);
118
+ } catch (error) {
119
+ console.error("JMAP push delivery failed", error instanceof Error ? error.message : String(error));
120
+ }
121
+ }));
122
+ if (gone.length) await db.delete(jmapPushSubscriptions).where(inArray(jmapPushSubscriptions.id, gone));
123
+ }
@@ -6,16 +6,27 @@ import { createDb } from "@open-workspace/core/worker/db/client.ts";
6
6
  import { mailboxAddressSql } from "@open-workspace/core/worker/db/mailboxes.ts";
7
7
  import { domains, mailboxAccess, mailboxes } from "@open-workspace/core/worker/db/schema.ts";
8
8
  import type { AppEnv } from "@open-workspace/core/worker/env.ts";
9
+ import { checkRateLimit } from "@open-workspace/core/worker/lib/rate-limit.ts";
9
10
  import {
10
11
  authenticateAccessToken,
11
12
  jmapProtectedResourceMetadataUrl,
12
13
  } from "@open-workspace/core/worker/oidc/mcp-clients.ts";
14
+ import { MAX_COMPOSER_ATTACHMENT_BYTES } from "../../shared/mail";
13
15
  import { mailboxStub } from "../mailbox";
14
- import { JmapError, runJmapRequest, type JmapAccount, type JmapContext } from "./methods";
16
+ import { vapidConfiguration } from "../mail/push-notifications";
17
+ import {
18
+ createComposerUploadIntent,
19
+ finalizeComposerUpload,
20
+ loadComposerUpload,
21
+ storeComposerUploadContent,
22
+ UploadValidationError,
23
+ } from "../mail/uploads";
24
+ import { jmapEventStream } from "./eventsource";
25
+ import { JmapError, runJmapRequest, UPLOAD_BLOB, type JmapAccount, type JmapContext } from "./methods";
15
26
 
16
27
  const CAPABILITIES = {
17
28
  "urn:ietf:params:jmap:core": {
18
- maxSizeUpload: 0,
29
+ maxSizeUpload: MAX_COMPOSER_ATTACHMENT_BYTES,
19
30
  maxConcurrentUpload: 1,
20
31
  maxSizeRequest: 10_000_000,
21
32
  maxConcurrentRequests: 4,
@@ -28,14 +39,15 @@ const CAPABILITIES = {
28
39
  "urn:ietf:params:jmap:submission": {},
29
40
  };
30
41
 
31
- type JmapEnv = AppEnv & { Variables: AppEnv["Variables"] & { jmapUser: { id: string; name: string } } };
42
+ type JmapUser = { id: string; name: string; clientId: string; token: string };
43
+ type JmapEnv = AppEnv & { Variables: AppEnv["Variables"] & { jmapUser: JmapUser } };
32
44
 
33
- function problem(c: Context, status: 400 | 401 | 403 | 404 | 501, type: string, detail: string) {
45
+ function problem(c: Context, status: 400 | 401 | 403 | 404 | 413 | 429, type: string, detail: string) {
34
46
  return c.json({ type, status, detail }, status, { "content-type": "application/problem+json" });
35
47
  }
36
48
 
37
49
  /** The mailboxes this person can open; each is a JMAP account. */
38
- async function jmapAccounts(env: Env, userId: string): Promise<JmapAccount[]> {
50
+ export async function jmapAccounts(env: Env, userId: string): Promise<JmapAccount[]> {
39
51
  const rows = await createDb(env.DB)
40
52
  .select({
41
53
  id: mailboxes.id,
@@ -55,12 +67,21 @@ async function jmapAccounts(env: Env, userId: string): Promise<JmapAccount[]> {
55
67
  }));
56
68
  }
57
69
 
58
- function sessionObject(origin: string, user: { id: string; name: string }, accounts: JmapAccount[]) {
70
+ function sessionObject(
71
+ origin: string,
72
+ user: { id: string; name: string },
73
+ accounts: JmapAccount[],
74
+ vapidPublicKey: string | null,
75
+ ) {
59
76
  const primary = accounts.find((account) => account.isPersonal && account.isPrimary)
60
77
  ?? accounts.find((account) => account.isPersonal)
61
78
  ?? accounts[0];
62
79
  return {
63
- capabilities: CAPABILITIES,
80
+ capabilities: {
81
+ ...CAPABILITIES,
82
+ // RFC 9749: push services that require VAPID accept our pushes.
83
+ ...(vapidPublicKey ? { "urn:ietf:params:jmap:webpush-vapid": { applicationServerKey: vapidPublicKey } } : {}),
84
+ },
64
85
  accounts: Object.fromEntries(accounts.map((account) => [account.id, {
65
86
  name: account.address,
66
87
  isPersonal: account.isPersonal,
@@ -70,7 +91,7 @@ function sessionObject(origin: string, user: { id: string; name: string }, accou
70
91
  maxMailboxesPerEmail: 1,
71
92
  maxMailboxDepth: 1,
72
93
  maxSizeMailboxName: 80,
73
- maxSizeAttachmentsPerEmail: 0,
94
+ maxSizeAttachmentsPerEmail: MAX_COMPOSER_ATTACHMENT_BYTES,
74
95
  emailQuerySortOptions: ["receivedAt", "sentAt"],
75
96
  mayCreateTopLevelMailbox: false,
76
97
  },
@@ -107,7 +128,7 @@ const requireJmapAuth = async (c: Context<JmapEnv>, next: () => Promise<void>) =
107
128
  ].join(", "));
108
129
  return problem(c, 401, "about:blank", token ? "The access token is invalid or expired" : "Sign in with OAuth");
109
130
  }
110
- c.set("jmapUser", { id: identity.user.id, name: identity.user.name });
131
+ c.set("jmapUser", { id: identity.user.id, name: identity.user.name, clientId: identity.clientId, token: token! });
111
132
  await next();
112
133
  };
113
134
 
@@ -120,7 +141,8 @@ export const jmapRoutes = new Hono<JmapEnv>()
120
141
  .use("/jmap/*", requireJmapAuth)
121
142
  .get("/jmap/session", async (c) => {
122
143
  const user = c.get("jmapUser");
123
- return c.json(sessionObject(new URL(c.req.url).origin, user, await jmapAccounts(c.env, user.id)));
144
+ const vapid = await vapidConfiguration(c.env);
145
+ return c.json(sessionObject(new URL(c.req.url).origin, user, await jmapAccounts(c.env, user.id), vapid?.publicKey ?? null));
124
146
  })
125
147
  .post("/jmap/api", async (c) => {
126
148
  if (!c.req.header("content-type")?.toLowerCase().startsWith("application/json")) {
@@ -135,7 +157,9 @@ export const jmapRoutes = new Hono<JmapEnv>()
135
157
  const user = c.get("jmapUser");
136
158
  const context: JmapContext = {
137
159
  env: c.env,
138
- user,
160
+ user: { id: user.id, name: user.name },
161
+ clientId: user.clientId,
162
+ vapid: await vapidConfiguration(c.env),
139
163
  accounts: await jmapAccounts(c.env, user.id),
140
164
  requestUrl: c.req.url,
141
165
  defer: (task) => c.executionCtx.waitUntil(task),
@@ -151,17 +175,25 @@ export const jmapRoutes = new Hono<JmapEnv>()
151
175
  const user = c.get("jmapUser");
152
176
  const account = (await jmapAccounts(c.env, user.id)).find((item) => item.id === c.req.param("accountId"));
153
177
  if (!account) return problem(c, 404, "about:blank", "Account not found");
154
- const blob = /^(raw|att)~([^~]+)(?:~(.+))?$/u.exec(c.req.param("blobId"));
155
- if (!blob) return problem(c, 404, "about:blank", "Blob not found");
156
- const [, kind, emailId, attachmentId] = blob;
157
- const stub = mailboxStub(c.env, account.id);
158
- const email = await stub.getEmail(emailId!);
159
- const key = kind === "raw"
160
- ? email?.rawMimeR2Key
161
- : email?.attachmentsJson.find((attachment) => attachment.id === attachmentId)?.r2Key;
178
+ const blobId = c.req.param("blobId");
179
+ const upload = UPLOAD_BLOB.exec(blobId);
180
+ const blob = /^(raw|att)~([^~]+)(?:~(.+))?$/u.exec(blobId);
181
+ let key: string | null | undefined;
182
+ if (upload) {
183
+ key = await loadComposerUpload({ env: c.env, mailboxId: account.id, userId: user.id, uploadId: upload[1]! })
184
+ .then((found) => found.r2Key, () => null);
185
+ } else if (blob) {
186
+ const [, kind, emailId, attachmentId] = blob;
187
+ const email = await mailboxStub(c.env, account.id).getEmail(emailId!);
188
+ key = kind === "raw"
189
+ ? email?.rawMimeR2Key
190
+ : email?.attachmentsJson.find((attachment) => attachment.id === attachmentId)?.r2Key;
191
+ }
162
192
  const object = key ? await c.env.MAIL_STORAGE.get(key) : null;
163
193
  if (!object) return problem(c, 404, "about:blank", "Blob not found");
164
- const type = c.req.query("type") || (kind === "raw" ? "message/rfc822" : "application/octet-stream");
194
+ const type = c.req.query("type")
195
+ || object.httpMetadata?.contentType
196
+ || (blob?.[1] === "raw" ? "message/rfc822" : "application/octet-stream");
165
197
  return new Response(object.body, {
166
198
  headers: {
167
199
  "content-type": type,
@@ -170,7 +202,76 @@ export const jmapRoutes = new Hono<JmapEnv>()
170
202
  },
171
203
  });
172
204
  })
173
- .post("/jmap/upload/:accountId", (c) =>
174
- problem(c, 501, "about:blank", "Uploads are not supported yet; send attachments from the app"))
175
- .get("/jmap/eventsource", (c) =>
176
- problem(c, 501, "about:blank", "Push over EventSource is not supported yet"));
205
+ .post("/jmap/upload/:accountId", async (c) => {
206
+ const user = c.get("jmapUser");
207
+ const account = (await jmapAccounts(c.env, user.id)).find((item) => item.id === c.req.param("accountId"));
208
+ if (!account) return problem(c, 404, "about:blank", "Account not found");
209
+ // Uploads become attachments of sent mail, so they need send access.
210
+ if (!account.canSend) return problem(c, 403, "about:blank", "This account cannot send");
211
+ const rate = await checkRateLimit(c.env.DB, {
212
+ action: "mail-upload",
213
+ identifier: user.id,
214
+ limit: 30,
215
+ windowMs: 60_000,
216
+ });
217
+ if (!rate.allowed) {
218
+ c.header("retry-after", String(rate.retryAfterSeconds));
219
+ return problem(c, 429, "about:blank", "Too many uploads");
220
+ }
221
+ const contentType = c.req.header("content-type")?.trim() || "application/octet-stream";
222
+ const declared = Number(c.req.header("content-length"));
223
+ // Without a length, buffer the body to learn it; uploads are bounded anyway.
224
+ let body: ReadableStream<Uint8Array> | ArrayBuffer | null = c.req.raw.body;
225
+ let size = declared;
226
+ if (!Number.isSafeInteger(declared) || declared < 0) {
227
+ body = await c.req.arrayBuffer();
228
+ size = body.byteLength;
229
+ }
230
+ if (size > MAX_COMPOSER_ATTACHMENT_BYTES) {
231
+ return problem(c, 413, "urn:ietf:params:jmap:error:limit", "The upload is too large");
232
+ }
233
+ try {
234
+ const intent = await createComposerUploadIntent({
235
+ env: c.env,
236
+ requestOrigin: new URL(c.req.url).origin,
237
+ mailboxId: account.id,
238
+ userId: user.id,
239
+ filename: "upload",
240
+ contentType,
241
+ size,
242
+ });
243
+ await storeComposerUploadContent({
244
+ env: c.env,
245
+ mailboxId: account.id,
246
+ userId: user.id,
247
+ uploadId: intent.id,
248
+ body,
249
+ contentType,
250
+ contentLength: size,
251
+ });
252
+ const upload = await finalizeComposerUpload({
253
+ env: c.env,
254
+ mailboxId: account.id,
255
+ userId: user.id,
256
+ uploadId: intent.id,
257
+ defer: (task) => c.executionCtx.waitUntil(task),
258
+ });
259
+ return c.json({ accountId: account.id, blobId: `upl~${upload.id}`, type: upload.contentType, size: upload.size }, 201);
260
+ } catch (error) {
261
+ if (error instanceof UploadValidationError) return problem(c, 400, "about:blank", error.message);
262
+ throw error;
263
+ }
264
+ })
265
+ .get("/jmap/eventsource", async (c) => {
266
+ const user = c.get("jmapUser");
267
+ return jmapEventStream({
268
+ env: c.env,
269
+ accounts: await jmapAccounts(c.env, user.id),
270
+ types: c.req.query("types") ?? "*",
271
+ closeAfterState: c.req.query("closeafter") === "state",
272
+ pingSeconds: Number(c.req.query("ping") ?? 0),
273
+ // The stream outlives the request check; the token is checked again on each ping.
274
+ stillAuthorized: async () => Boolean(await authenticateAccessToken(createDb(c.env.DB), user.token, JMAP_SCOPE)),
275
+ defer: (task) => c.executionCtx.waitUntil(task),
276
+ });
277
+ });