@open-workspace/email 0.5.2 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +1 -2
  2. package/alchemy/index.ts +0 -16
  3. package/migrations/0003_after_0_5_2.sql +1 -0
  4. package/migrations/meta/0003_snapshot.json +703 -0
  5. package/migrations/meta/_journal.json +7 -0
  6. package/package.json +6 -5
  7. package/shared/mail.ts +3 -2
  8. package/shared/module.ts +1 -1
  9. package/src/client.tsx +20 -30
  10. package/src/extensions.ts +176 -0
  11. package/src/mail/compose-window-chrome.tsx +5 -10
  12. package/src/mail/compose-window.tsx +13 -2
  13. package/src/mail/composer-attach-button.tsx +106 -0
  14. package/src/mail/composer-editor.tsx +17 -0
  15. package/src/mail/composer-inserts.tsx +186 -0
  16. package/src/mail/composer-toolbar.tsx +3 -0
  17. package/src/mail/conversation-message.tsx +37 -1
  18. package/src/mail/conversation-reply.tsx +5 -10
  19. package/src/mail/message-actions.tsx +30 -0
  20. package/src/mail/message-attachments.tsx +62 -0
  21. package/src/mail/message-panels.tsx +206 -0
  22. package/src/mail/module-extensions.ts +87 -0
  23. package/src/mail/reader-pane.tsx +75 -47
  24. package/src/mail/recipient-combobox.tsx +32 -12
  25. package/src/mail/shared-compose.ts +45 -0
  26. package/src/settings/mail-notifications.tsx +119 -0
  27. package/src/settings/settings-queries.ts +0 -7
  28. package/worker/backups/file-parts.ts +9 -6
  29. package/worker/backups/mail-backup.ts +21 -4
  30. package/worker/backups/settings-backup.ts +56 -24
  31. package/worker/db/schema.ts +0 -36
  32. package/worker/jmap/method-core.ts +2 -3
  33. package/worker/jmap/push-subscription-methods.ts +5 -2
  34. package/worker/jmap/push.ts +10 -11
  35. package/worker/jmap/routes.ts +10 -49
  36. package/worker/mail/bimi.ts +2 -3
  37. package/worker/mail/person-erasure.ts +58 -0
  38. package/worker/mail/push-notifications.ts +59 -419
  39. package/worker/mail/remote-proxy.ts +3 -206
  40. package/worker/mail/remote-routes.ts +2 -2
  41. package/worker/mail/uploads.ts +14 -6
  42. package/worker/mail/webhook-source.ts +13 -1
  43. package/worker/mailbox/index.ts +27 -0
  44. package/worker/mailbox/mailbox-drafts.ts +5 -0
  45. package/worker/module-api.ts +239 -0
  46. package/worker/module.ts +11 -7
  47. package/src/pwa/push-key.ts +0 -18
  48. package/src/pwa/push-subscription.ts +0 -213
  49. package/src/settings/notifications-page.tsx +0 -306
  50. package/worker/mail/push-endpoint.ts +0 -17
@@ -1,15 +1,7 @@
1
- import { required } from "@open-workspace/core/shared";
1
+ import { assertPublicUrl } from "@open-workspace/core/module";
2
2
 
3
3
  import { repeatUntil } from "./repeat";
4
4
 
5
- const BLOCKED_HOST_SUFFIXES = [".localhost", ".local", ".internal"];
6
-
7
- const BLOCKED_HOSTS = new Set([
8
- "localhost",
9
- "metadata.google.internal",
10
- "metadata",
11
- ]);
12
-
13
5
  export const PROXYABLE_REMOTE_MEDIA_TYPES = new Set([
14
6
  "image/apng",
15
7
  "image/avif",
@@ -24,201 +16,6 @@ export const MAX_REMOTE_PROXY_BYTES = 5 * 1024 * 1024;
24
16
  export const REMOTE_PROXY_TIMEOUT_MS = 12_000;
25
17
  export const REMOTE_PROXY_MAX_REDIRECTS = 3;
26
18
 
27
- /** An IPv4 address as a 32-bit number, or null. The URL parser has already turned 0x7f.1 and 2130706433 into dotted form. */
28
- function ipv4Number(hostname: string) {
29
- const parts = hostname.split(".");
30
-
31
- if (
32
- parts.length !== 4 ||
33
- !parts.every((part) => /^\d{1,3}$/u.test(part) && Number(part) <= 255)
34
- ) {
35
- return null;
36
- }
37
-
38
- return parts.reduce((value, part) => value * 256 + Number(part), 0);
39
- }
40
-
41
- /** IPv4 networks a proxied fetch must never reach: private, loopback, link-local, shared, reserved, multicast. */
42
- const BLOCKED_IPV4: [network: string, bits: number][] = [
43
- ["0.0.0.0", 8],
44
- ["10.0.0.0", 8],
45
- ["100.64.0.0", 10],
46
- ["127.0.0.0", 8],
47
- ["169.254.0.0", 16],
48
- ["172.16.0.0", 12],
49
- ["192.0.0.0", 24],
50
- ["192.0.2.0", 24],
51
- ["192.88.99.0", 24],
52
- ["192.168.0.0", 16],
53
- ["198.18.0.0", 15],
54
- ["198.51.100.0", 24],
55
- ["203.0.113.0", 24],
56
- ["224.0.0.0", 4],
57
- ["240.0.0.0", 4],
58
- ];
59
-
60
- const BLOCKED_IPV4_RANGES = BLOCKED_IPV4.map(([network, bits]) => ({
61
- start: required(ipv4Number(network), `${network} is not an IPv4 address`),
62
- size: 2 ** (32 - bits),
63
- }));
64
-
65
- function isBlockedIpv4(address: number) {
66
- return BLOCKED_IPV4_RANGES.some(
67
- ({ start, size }) => address >= start && address < start + size
68
- );
69
- }
70
-
71
- type Ipv6Groups = [
72
- number,
73
- number,
74
- number,
75
- number,
76
- number,
77
- number,
78
- number,
79
- number,
80
- ];
81
-
82
- /** The eight 16-bit groups of an IPv6 address (brackets, a zone, an IPv4 tail allowed), or null. */
83
- function ipv6Groups(hostname: string) {
84
- let value = hostname
85
- .toLowerCase()
86
- .replaceAll(/^\[|\]$/gu, "")
87
- .split("%")[0];
88
-
89
- const tail = /:(\d+\.\d+\.\d+\.\d+)$/u.exec(value);
90
-
91
- if (tail) {
92
- const v4 = ipv4Number(tail[1]);
93
-
94
- if (v4 === null) return null;
95
- value = `${value.slice(0, tail.index)}:${(v4 >>> 16).toString(16)}:${(v4 & 0xff_ff).toString(16)}`;
96
- }
97
-
98
- const halves = value.split("::");
99
-
100
- if (halves.length > 2) return null;
101
- const head = halves[0] ? halves[0].split(":") : [];
102
- const rest = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
103
- const missing = 8 - head.length - rest.length;
104
-
105
- if (missing < 0 || (halves.length === 1 && missing !== 0)) return null;
106
-
107
- const groups = [
108
- ...head,
109
- ...Array.from({ length: missing }, () => "0"),
110
- ...rest,
111
- ];
112
-
113
- if (!groups.every((group) => /^[0-9a-f]{1,4}$/u.test(group))) return null;
114
-
115
- const [g0, g1, g2, g3, g4, g5, g6, g7] = groups.map((group) =>
116
- Number.parseInt(group, 16)
117
- );
118
-
119
- if (groups.length !== 8) return null;
120
-
121
- return [g0, g1, g2, g3, g4, g5, g6, g7] satisfies Ipv6Groups;
122
- }
123
-
124
- /**
125
- * Whether an IPv6 address is anything but a global unicast address on the
126
- * public internet: loopback, unspecified, IPv4-mapped or -compatible
127
- * (::ffff:7f00:1 is 127.0.0.1), NAT64 or 6to4 around a blocked IPv4
128
- * address, unique local, link- and site-local, documentation, discard,
129
- * Teredo, or multicast.
130
- */
131
- function isBlockedIpv6(groups: Ipv6Groups) {
132
- const [g0, g1, g2, g3, g4, g5, g6, g7] = groups;
133
-
134
- const embedded = (high: number, low: number) =>
135
- isBlockedIpv4(high * 65_536 + low);
136
-
137
- if (groups.slice(0, 6).every((group) => group === 0)) return true; // ::, ::1, ::a.b.c.d
138
-
139
- if (groups.slice(0, 5).every((group) => group === 0) && g5 === 0xff_ff) {
140
- return true;
141
- } // ::ffff:a.b.c.d
142
-
143
- if (
144
- g0 === 0 &&
145
- g1 === 0 &&
146
- g2 === 0 &&
147
- g3 === 0 &&
148
- g4 === 0xff_ff &&
149
- g5 === 0
150
- ) {
151
- return true;
152
- } // ::ffff:0:a.b.c.d
153
-
154
- if (g0 === 0x64 && g1 === 0xff_9b) return g2 === 1 || embedded(g6, g7); // NAT64
155
-
156
- if (g0 === 0x20_02) return embedded(g1, g2); // 6to4
157
-
158
- if (g0 === 0x20_01 && g1 === 0) return true; // Teredo
159
-
160
- if (g0 === 0x20_01 && g1 === 0xd_b8) return true; // documentation
161
-
162
- if (g0 === 0x1_00 && g1 === 0 && g2 === 0 && g3 === 0) return true; // discard
163
-
164
- if ((g0 & 0xfe_00) === 0xfc_00) return true; // unique local
165
-
166
- if ((g0 & 0xff_c0) === 0xfe_80 || (g0 & 0xff_c0) === 0xfe_c0) return true; // link- and site-local
167
-
168
- if ((g0 & 0xff_00) === 0xff_00) return true; // multicast
169
-
170
- return false;
171
- }
172
-
173
- /** Whether a URL's (already normalized) host is an IP address the proxy must not reach. */
174
- function isBlockedIp(hostname: string) {
175
- const v4 = ipv4Number(hostname);
176
-
177
- if (v4 !== null) return isBlockedIpv4(v4);
178
-
179
- if (!hostname.includes(":")) return false;
180
- const groups = ipv6Groups(hostname);
181
-
182
- // Anything that looks like IPv6 but does not parse is refused too.
183
- return !groups || isBlockedIpv6(groups);
184
- }
185
-
186
- export function assertProxyableRemoteUrl(value: string) {
187
- let url: URL;
188
-
189
- try {
190
- url = new URL(value);
191
- } catch {
192
- throw new Error("Remote URL is invalid");
193
- }
194
-
195
- if (url.protocol !== "http:" && url.protocol !== "https:") {
196
- throw new Error("Only http(s) remote URLs are allowed");
197
- }
198
-
199
- if (url.username || url.password) {
200
- throw new Error("Remote URLs must not include credentials");
201
- }
202
-
203
- // The URL parser has normalized the host: IPv4 in dotted decimal, IPv6
204
- // compressed in brackets. A trailing dot names the same host.
205
- const host = url.hostname.toLowerCase().replace(/\.$/u, "");
206
-
207
- if (!host || BLOCKED_HOSTS.has(host)) {
208
- throw new Error("Remote host is not allowed");
209
- }
210
-
211
- if (BLOCKED_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix))) {
212
- throw new Error("Remote host is not allowed");
213
- }
214
-
215
- if (isBlockedIp(host)) {
216
- throw new Error("Remote host is not allowed");
217
- }
218
-
219
- return url;
220
- }
221
-
222
19
  export function mediaType(contentType: string | null) {
223
20
  return contentType?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
224
21
  }
@@ -233,7 +30,7 @@ export function isProxyableRemoteMediaType(contentType: string | null) {
233
30
  }
234
31
 
235
32
  export async function fetchProxiedRemoteMedia(remoteUrl: string) {
236
- let current = assertProxyableRemoteUrl(remoteUrl);
33
+ let current = assertPublicUrl(remoteUrl);
237
34
 
238
35
  // The first request and each redirect hop, one after another.
239
36
  const media = await repeatUntil(REMOTE_PROXY_MAX_REDIRECTS + 1, async () => {
@@ -259,7 +56,7 @@ export async function fetchProxiedRemoteMedia(remoteUrl: string) {
259
56
  const location = response.headers.get("location");
260
57
 
261
58
  if (!location) throw new Error("Remote redirect is missing a location");
262
- current = assertProxyableRemoteUrl(new URL(location, current).toString());
59
+ current = assertPublicUrl(new URL(location, current).toString());
263
60
 
264
61
  return undefined;
265
62
  }
@@ -1,6 +1,7 @@
1
1
  import type { AppEnv } from "@open-workspace/core/module";
2
2
  import {
3
3
  apiError,
4
+ assertPublicUrl,
4
5
  rateLimitedResponse,
5
6
  withinRateLimit,
6
7
  timed,
@@ -9,7 +10,6 @@ import {
9
10
  import { Hono } from "hono";
10
11
 
11
12
  import { proxiedRemoteImage } from "./edge-cache";
12
- import { assertProxyableRemoteUrl } from "./remote-proxy";
13
13
  import { verifyRemoteToken } from "./remote-token";
14
14
  import { remoteProxyQuerySchema } from "./schemas";
15
15
 
@@ -40,7 +40,7 @@ export const mailRemoteRoutes = new Hono<AppEnv>().get(
40
40
  }
41
41
 
42
42
  try {
43
- assertProxyableRemoteUrl(url);
43
+ assertPublicUrl(url);
44
44
  } catch (error) {
45
45
  return apiError(
46
46
  c,
@@ -46,12 +46,17 @@ const uploadMetaSchema = z
46
46
  })
47
47
  .strict();
48
48
 
49
+ /** Where one person's composer uploads in a mailbox are. */
50
+ export function composerUploadsOf(mailboxId: string, userId: string) {
51
+ return `composer-uploads/${mailboxId}/${userId}/`;
52
+ }
53
+
49
54
  function composerUploadPrefix(
50
55
  mailboxId: string,
51
56
  userId: string,
52
57
  uploadId: string
53
58
  ) {
54
- return `composer-uploads/${mailboxId}/${userId}/${uploadId}`;
59
+ return `${composerUploadsOf(mailboxId, userId)}${uploadId}`;
55
60
  }
56
61
 
57
62
  export function composerUploadKey(
@@ -312,12 +317,15 @@ export async function storeComposerUploadContent(input: {
312
317
  throw new UploadValidationError("Attachment upload is already complete");
313
318
  }
314
319
 
315
- const contentType = (input.contentType || meta.contentType)
316
- .split(";", 1)[0]
317
- .trim()
318
- .toLowerCase();
320
+ // Compared without parameters: `text/calendar; method=REQUEST` is sent
321
+ // with its method, whichever of the two carries it.
322
+ const baseType = (type: string) =>
323
+ type.split(";", 1)[0]?.trim().toLowerCase();
319
324
 
320
- if (contentType !== meta.contentType.trim().toLowerCase()) {
325
+ if (
326
+ baseType(input.contentType || meta.contentType) !==
327
+ baseType(meta.contentType)
328
+ ) {
321
329
  throw new UploadValidationError("Attachment content type does not match");
322
330
  }
323
331
 
@@ -45,6 +45,18 @@ function publicEmail(email: Email, bodyHtml: string | null) {
45
45
  };
46
46
  }
47
47
 
48
+ /** The `data` of an `email.received` or `email.sent` event. */
49
+ export type MailEventData = {
50
+ mailbox: {
51
+ id: string;
52
+ address: string;
53
+ displayName: string;
54
+ ownerUserId: string | null;
55
+ kind: ReturnType<typeof mailboxKind>;
56
+ };
57
+ email: ReturnType<typeof publicEmail>;
58
+ };
59
+
48
60
  /** What outbound-service queues as an `EMAIL_WEBHOOK_SOURCE` source. */
49
61
  const EmailWebhookSource = z.object({
50
62
  mailboxId: z.string(),
@@ -91,5 +103,5 @@ export const emailWebhookData: WebhookSourceBuilder = async (env, queued) => {
91
103
  return {
92
104
  mailbox,
93
105
  email: publicEmail(email, htmlObject ? await htmlObject.text() : null),
94
- };
106
+ } satisfies MailEventData;
95
107
  };
@@ -72,6 +72,7 @@ import {
72
72
  systemFolderOrder,
73
73
  senderFeedback,
74
74
  senders,
75
+ spamUndoReceipts,
75
76
  unsubscriptions,
76
77
  } from "./schema";
77
78
  import type { NewEmail, NewFolder } from "./schema";
@@ -695,6 +696,32 @@ export class MailboxDO extends DurableObject<Env> {
695
696
  .get();
696
697
  }
697
698
 
699
+ /**
700
+ * Drops what this mailbox keeps for a person who is being erased: their
701
+ * drafts (files queued for deletion), read states and spam undo
702
+ * receipts. Their spam reports and unsubscribes stay, without their id.
703
+ * Repeating it finds nothing more.
704
+ */
705
+ async forgetPerson(userId: string) {
706
+ await mailboxDrafts.discardAllDrafts(this.context, userId);
707
+ this.db.transaction((tx) => {
708
+ tx.delete(emailReadStates)
709
+ .where(eq(emailReadStates.userId, userId))
710
+ .run();
711
+ tx.delete(spamUndoReceipts)
712
+ .where(eq(spamUndoReceipts.userId, userId))
713
+ .run();
714
+ tx.update(senderFeedback)
715
+ .set({ userId: null })
716
+ .where(eq(senderFeedback.userId, userId))
717
+ .run();
718
+ tx.update(unsubscriptions)
719
+ .set({ userId: null })
720
+ .where(eq(unsubscriptions.userId, userId))
721
+ .run();
722
+ });
723
+ }
724
+
698
725
  forgetDraftFiles(objectKeys: string[]) {
699
726
  return mailboxDrafts.forgetDraftFiles(this.context, objectKeys);
700
727
  }
@@ -376,6 +376,11 @@ export function discardDrafts(
376
376
  );
377
377
  }
378
378
 
379
+ /** Discards every draft of the person in this mailbox; their files are queued for deletion. */
380
+ export function discardAllDrafts(m: MailboxContext, userId: string) {
381
+ return discardMatchingDrafts(m, userId);
382
+ }
383
+
379
384
  async function discardMatchingDrafts(
380
385
  m: MailboxContext,
381
386
  userId: string,
@@ -0,0 +1,239 @@
1
+ /**
2
+ * What other modules may use of mail (`@open-workspace/email/module`):
3
+ * sending from a mailbox on someone's behalf, and reading what the
4
+ * `email.received` and `email.sent` events name. Anything else in this
5
+ * package can change in any release.
6
+ */
7
+ import { createDb, createId } from "@open-workspace/core/module";
8
+ import type { ModuleEvent } from "@open-workspace/core/module";
9
+ import { users } from "@open-workspace/core/schema";
10
+ import { eq } from "drizzle-orm";
11
+ import { z } from "zod";
12
+
13
+ import { MAX_COMPOSER_ATTACHMENT_COUNT } from "../shared/mail";
14
+ import { EMAIL_RECEIVED_EVENT, EMAIL_SENT_EVENT } from "../shared/webhooks";
15
+ import { getMailboxAccess } from "./mail/access";
16
+ import { messageIdForRequest } from "./mail/outbound";
17
+ import { submitOutgoing } from "./mail/outbound-service";
18
+ import { composeSchema } from "./mail/schemas";
19
+ import {
20
+ createComposerUploadIntent,
21
+ finalizeComposerUpload,
22
+ storeComposerUploadContent,
23
+ UploadValidationError,
24
+ } from "./mail/uploads";
25
+ import type { MailEventData } from "./mail/webhook-source";
26
+ import { mailboxStub } from "./mailbox";
27
+
28
+ export type { MailEventData } from "./mail/webhook-source";
29
+
30
+ /** Why `sendMail` refused: the sender can't send from the mailbox, or the message is invalid. */
31
+ export class MailSendError extends Error {
32
+ constructor(
33
+ readonly code: "FORBIDDEN" | "INVALID",
34
+ message: string
35
+ ) {
36
+ super(message);
37
+ this.name = "MailSendError";
38
+ }
39
+ }
40
+
41
+ export type ModuleMail = {
42
+ /** The mailbox it's sent from, and stored in (its Sent). */
43
+ mailboxId: string;
44
+ /**
45
+ * Who sends it: an active person with send rights on the mailbox, checked
46
+ * now. A module sending later on someone's behalf (a booking's
47
+ * confirmation) names that person.
48
+ */
49
+ userId: string;
50
+ /**
51
+ * The same key sends one message: a retried call (an event handled again)
52
+ * returns the message the first one sent. Use the event's id, say.
53
+ */
54
+ idempotencyKey: string;
55
+ to: string[];
56
+ cc?: string[];
57
+ bcc?: string[];
58
+ replyTo?: string;
59
+ subject: string;
60
+ text: string;
61
+ html?: string;
62
+ /** E.g. an invitation: `{ filename: "invite.ics", contentType: "text/calendar; method=REQUEST", content }`. */
63
+ attachments?: {
64
+ filename: string;
65
+ contentType: string;
66
+ content: Uint8Array<ArrayBuffer>;
67
+ }[];
68
+ };
69
+
70
+ /**
71
+ * Sends a message from a mailbox the way the app sends what a person
72
+ * writes: stored in its Sent, archived, and announced as `email.sent`.
73
+ * Throws `MailSendError` when `userId` can't send from the mailbox or the
74
+ * message is invalid.
75
+ */
76
+ export async function sendMail(env: Env, mail: ModuleMail) {
77
+ const db = createDb(env.DB);
78
+
79
+ const [sender, access] = await Promise.all([
80
+ db
81
+ .select({ name: users.name, status: users.status })
82
+ .from(users)
83
+ .where(eq(users.id, mail.userId))
84
+ .limit(1)
85
+ .then(([row]) => row),
86
+ getMailboxAccess(db, mail.userId, mail.mailboxId),
87
+ ]);
88
+
89
+ if (sender?.status !== "active" || !access?.canSend) {
90
+ throw new MailSendError(
91
+ "FORBIDDEN",
92
+ "This person can't send from this mailbox"
93
+ );
94
+ }
95
+
96
+ const requestId = await requestUuid(mail.mailboxId, mail.idempotencyKey);
97
+
98
+ // Sent already: its attachments would upload again under new ids, which
99
+ // the request's fingerprint would take for different content.
100
+ const existing = await mailboxStub(env, mail.mailboxId).getEmail(
101
+ await messageIdForRequest(mail.mailboxId, requestId)
102
+ );
103
+
104
+ if (existing?.direction === "outgoing") {
105
+ return {
106
+ messageId: existing.id,
107
+ conversationId: existing.conversationId,
108
+ };
109
+ }
110
+
111
+ const attachments = mail.attachments ?? [];
112
+
113
+ if (attachments.length > MAX_COMPOSER_ATTACHMENT_COUNT) {
114
+ throw new MailSendError(
115
+ "INVALID",
116
+ `A message can have at most ${MAX_COMPOSER_ATTACHMENT_COUNT} attachments`
117
+ );
118
+ }
119
+
120
+ const uploadIds = await Promise.all(
121
+ attachments.map((attachment) => uploadAttachment(env, mail, attachment))
122
+ ).catch((error: Error) => {
123
+ if (error instanceof UploadValidationError) {
124
+ throw new MailSendError("INVALID", error.message);
125
+ }
126
+
127
+ throw error;
128
+ });
129
+
130
+ const parsed = composeSchema.safeParse({
131
+ requestId,
132
+ mailboxId: mail.mailboxId,
133
+ to: mail.to,
134
+ cc: mail.cc ?? [],
135
+ bcc: mail.bcc ?? [],
136
+ replyTo: mail.replyTo,
137
+ subject: mail.subject,
138
+ bodyText: mail.text,
139
+ bodyHtml: mail.html,
140
+ attachments: uploadIds.map((uploadId) => ({ uploadId })),
141
+ });
142
+
143
+ if (!parsed.success) {
144
+ throw new MailSendError("INVALID", z.prettifyError(parsed.error));
145
+ }
146
+
147
+ const { storedImages: _, ...compose } = parsed.data;
148
+
149
+ const sent = await submitOutgoing({
150
+ env,
151
+ // Download links in the message point at the workspace.
152
+ requestUrl: env.IDENTITY_PROVIDER_ORIGIN,
153
+ compose: { ...compose, userId: mail.userId },
154
+ conversationId: createId("conv"),
155
+ related: null,
156
+ forwarded: null,
157
+ includeRelatedContext: false,
158
+ fromAddress: access.address,
159
+ fromName: access.displayName,
160
+ });
161
+
162
+ return {
163
+ messageId: sent.email.id,
164
+ conversationId: sent.email.conversationId,
165
+ };
166
+ }
167
+
168
+ /** A UUID (`composeSchema`'s request id) that the key always gives. */
169
+ async function requestUuid(mailboxId: string, key: string) {
170
+ const digest = await crypto.subtle.digest(
171
+ "SHA-256",
172
+ new TextEncoder().encode(`module-mail\0${mailboxId}\0${key}`)
173
+ );
174
+
175
+ const hex = Array.from(new Uint8Array(digest).subarray(0, 16), (byte) =>
176
+ byte.toString(16).padStart(2, "0")
177
+ ).join("");
178
+
179
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-8${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
180
+ }
181
+
182
+ async function uploadAttachment(
183
+ env: Env,
184
+ mail: ModuleMail,
185
+ attachment: NonNullable<ModuleMail["attachments"]>[number]
186
+ ) {
187
+ const owner = { env, mailboxId: mail.mailboxId, userId: mail.userId };
188
+
189
+ const intent = await createComposerUploadIntent({
190
+ ...owner,
191
+ filename: attachment.filename,
192
+ contentType: attachment.contentType,
193
+ size: attachment.content.byteLength,
194
+ });
195
+
196
+ await storeComposerUploadContent({
197
+ ...owner,
198
+ uploadId: intent.id,
199
+ // A view into a larger buffer sends only its own bytes.
200
+ body: attachment.content.slice().buffer,
201
+ contentType: intent.contentType,
202
+ contentLength: attachment.content.byteLength,
203
+ });
204
+
205
+ return (await finalizeComposerUpload({ ...owner, uploadId: intent.id })).id;
206
+ }
207
+
208
+ /**
209
+ * The payload of an `email.received` or `email.sent` event a module's
210
+ * `on` handler got: the mailbox and the message, as the webhook has it.
211
+ */
212
+ export function mailEventData(event: ModuleEvent) {
213
+ if (event.type !== EMAIL_RECEIVED_EVENT && event.type !== EMAIL_SENT_EVENT) {
214
+ throw new Error(`${event.type} is not a mail event`);
215
+ }
216
+
217
+ // SAFETY: core builds a mail event's data with `emailWebhookData`, whose
218
+ // result is `MailEventData`.
219
+ return event.data as MailEventData;
220
+ }
221
+
222
+ /**
223
+ * The message as it arrived (its MIME, with every part, such as a
224
+ * `text/calendar` invitation), for a received message; null for one this
225
+ * workspace sent, or once it's deleted.
226
+ */
227
+ export async function readReceivedMessage(
228
+ env: Env,
229
+ input: { mailboxId: string; messageId: string }
230
+ ) {
231
+ const email = await mailboxStub(env, input.mailboxId).getEmail(
232
+ input.messageId
233
+ );
234
+
235
+ if (email?.direction !== "incoming" || !email.rawMimeR2Key) return null;
236
+ const object = await env.MAIL_STORAGE.get(email.rawMimeR2Key);
237
+
238
+ return object ? new Uint8Array(await object.arrayBuffer()) : null;
239
+ }
package/worker/module.ts CHANGED
@@ -5,7 +5,7 @@ import type {
5
5
  } from "@open-workspace/core/module";
6
6
  import { Hono } from "hono";
7
7
 
8
- import { EMAIL_MODULE, emailQueueRoles } from "../shared/module";
8
+ import { EMAIL_MODULE, emailQueueRoles, JMAP_PATH } from "../shared/module";
9
9
  import type { EmailQueueRole } from "../shared/module";
10
10
  import { emailPermissions, mailOauthScopes } from "../shared/permissions";
11
11
  import { EMAIL_WEBHOOK_SOURCE, emailWebhookEvents } from "../shared/webhooks";
@@ -25,11 +25,11 @@ import {
25
25
  import { mailImportRoutes } from "./mail/import-routes";
26
26
  import { deleteMailboxStorage } from "./mail/mailbox-deletion";
27
27
  import { consumeOfficePreviews } from "./mail/office-preview-queue";
28
+ import { erasePersonMail } from "./mail/person-erasure";
28
29
  import {
29
30
  consumePushNotifications,
30
- deleteEndedSessionPushSubscriptions,
31
- deleteUserPushSubscriptions,
32
- pushNotificationRoutes,
31
+ deleteUserJmapPushSubscriptions,
32
+ notificationPreferenceRoutes,
33
33
  } from "./mail/push-notifications";
34
34
  import { receiveEmail } from "./mail/receive";
35
35
  import { mailRemoteRoutes } from "./mail/remote-routes";
@@ -52,7 +52,7 @@ const mailPublicRoutes = new Hono<AppEnv>()
52
52
  .route("/", jmapRoutes)
53
53
  .route("/api/downloads", mailDownloadRoutes)
54
54
  .route("/api/demo", demoRoutes)
55
- .route("/api/notifications", pushNotificationRoutes);
55
+ .route("/api/notifications", notificationPreferenceRoutes);
56
56
 
57
57
  /** The routes this module adds, for the browser's typed client. */
58
58
  export const mailBrowserApi = new Hono<AppEnv>()
@@ -74,6 +74,10 @@ export function email() {
74
74
  permissions: emailPermissions,
75
75
  oauthScopes: mailOauthScopes,
76
76
  routes: mailPublicRoutes,
77
+ // Mail apps get tokens for JMAP alone (jmap/routes.ts checks them).
78
+ protectedResources: [
79
+ { path: JMAP_PATH, name: "OpenWorkspace mail (JMAP)" },
80
+ ],
77
81
  email: (message, env) => receiveEmail(message, env),
78
82
  queues: {
79
83
  [emailQueueRoles.officePreviews]: (batch, env) =>
@@ -99,8 +103,8 @@ export function email() {
99
103
  ]);
100
104
  },
101
105
  mailboxDeleted: deleteMailboxStorage,
102
- sessionsEnded: deleteEndedSessionPushSubscriptions,
103
- sessionsRevoked: deleteUserPushSubscriptions,
106
+ personErased: erasePersonMail,
107
+ sessionsRevoked: deleteUserJmapPushSubscriptions,
104
108
  seedDemo: (env) => seedEmailDemo(env),
105
109
  },
106
110
  } satisfies WorkspaceModule;
@@ -1,18 +0,0 @@
1
- /**
2
- * Whether a browser push subscription was made with the server's current
3
- * VAPID public key. A subscription made with another key (the keys change
4
- * when a stage is recreated) still looks active, but the push service
5
- * rejects every message the server signs with its new key.
6
- */
7
- export function pushKeyMatches(
8
- subscriptionKey: ArrayBuffer | null,
9
- serverKey: Uint8Array
10
- ) {
11
- if (!subscriptionKey) return false;
12
- const bytes = new Uint8Array(subscriptionKey);
13
-
14
- return (
15
- bytes.length === serverKey.length &&
16
- bytes.every((byte, index) => byte === serverKey[index])
17
- );
18
- }