@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 CHANGED
@@ -25,6 +25,9 @@ turns on Email Routing, sends every address to the Worker, onboards the domain
25
25
  to Email Sending, and subscribes delivery events. Leave `domains` out to set
26
26
  those up in the dashboard.
27
27
 
28
- Optional secrets: `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY`, `VAPID_SUBJECT` for
29
- web push; `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_ACCOUNT_ID`,
30
- `R2_BUCKET_NAME` for direct attachment transfers; `SPAMHAUS_DQS_KEY`.
28
+ Web push keys are minted by Alchemy on the first deploy (`VapidKeys`); push
29
+ services see the app's URL as the contact unless `pushContact` is set.
30
+
31
+ Optional secrets: `R2_ACCESS_KEY_ID` and `R2_SECRET_ACCESS_KEY` (an R2 API token
32
+ for the mail bucket) for direct attachment transfers; `SPAMHAUS_DQS_KEY`.
33
+ Uploads that are never sent expire from the bucket after seven days.
package/alchemy.ts CHANGED
@@ -2,7 +2,7 @@ import { dirname, join } from "node:path";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import * as Cloudflare from "@alchemy.run/cloudflare";
4
4
  import * as Effect from "effect/Effect";
5
- import type { WorkspaceModuleInfra } from "@open-workspace/core/alchemy";
5
+ import { VapidKeys, type WorkspaceModuleInfra } from "@open-workspace/core/alchemy";
6
6
 
7
7
  const packageDir = dirname(fileURLToPath(import.meta.url));
8
8
 
@@ -26,10 +26,12 @@ export type EmailInfraProps = {
26
26
  domains?: string[];
27
27
  /** R2 bucket for raw messages and attachments; defaults to `<name>-mail`. */
28
28
  bucketName?: string;
29
- /** Queue names default to `<name>-<role>`; set to keep existing queues. */
29
+ /** Prefix of the module's queue names; defaults to `<name>`. */
30
30
  queuePrefix?: string;
31
- /** Name of an existing Office preview container application to adopt. */
31
+ /** Office preview container application name; Alchemy names it by default. */
32
32
  containerName?: string;
33
+ /** Contact for push services (mailto: or https:); defaults to the app's URL. */
34
+ pushContact?: string;
33
35
  };
34
36
 
35
37
  /**
@@ -44,23 +46,36 @@ export function Email(props: EmailInfraProps = {}): (name: string) => WorkspaceM
44
46
  Cloudflare.Queues.Queue(id, { name: `${prefix}-${role}` });
45
47
  const officePreviews = queue("OfficePreviews", "office-previews");
46
48
  const pushNotifications = queue("PushNotifications", "push-notifications");
49
+ const mailStorage = Cloudflare.R2.Bucket("MailStorage", {
50
+ name: props.bucketName ?? `${name}-mail`,
51
+ // Uploads that were never sent.
52
+ lifecycleRules: [{
53
+ id: "expire-composer-uploads",
54
+ prefix: "composer-uploads/",
55
+ deleteObjectsTransition: { condition: { type: "Age", maxAge: 7 * 24 * 60 * 60 } },
56
+ }],
57
+ });
47
58
  const deliveryEventsQueue = queue("DeliveryEvents", "delivery-events");
48
59
 
49
60
  return {
50
61
  name: "email",
51
62
  migrations: join(packageDir, "migrations"),
52
63
  secrets: [
53
- "VAPID_PUBLIC_KEY",
54
- "VAPID_PRIVATE_KEY",
55
- "VAPID_SUBJECT",
56
64
  "R2_ACCESS_KEY_ID",
57
65
  "R2_SECRET_ACCESS_KEY",
58
- "R2_ACCOUNT_ID",
59
- "R2_BUCKET_NAME",
60
66
  "SPAMHAUS_DQS_KEY",
61
67
  ],
62
- env: {
63
- MAIL_STORAGE: Cloudflare.R2.Bucket("MailStorage", { name: props.bucketName ?? `${name}-mail` }),
68
+ env: Effect.gen(function* () {
69
+ const vapid = yield* VapidKeys("VapidKeys", {});
70
+ const bucket = yield* mailStorage;
71
+ return {
72
+ // For presigned direct transfers, with the R2 API token in the secrets.
73
+ R2_ACCOUNT_ID: bucket.accountId,
74
+ R2_BUCKET_NAME: bucket.bucketName,
75
+ VAPID_PUBLIC_KEY: vapid.publicKey,
76
+ VAPID_PRIVATE_KEY: vapid.privateKey,
77
+ ...(props.pushContact ? { VAPID_SUBJECT: props.pushContact } : {}),
78
+ MAIL_STORAGE: mailStorage,
64
79
  EMAIL: Cloudflare.Email.SendEmail("EMAIL"),
65
80
  MAILBOX: Cloudflare.DurableObject("MAILBOX", { className: "MailboxDO" }),
66
81
  OFFICE_PREVIEW_CONTAINER: Cloudflare.Container("OfficePreview", {
@@ -71,7 +86,8 @@ export function Email(props: EmailInfraProps = {}): (name: string) => WorkspaceM
71
86
  }),
72
87
  OFFICE_PREVIEWS: officePreviews,
73
88
  PUSH_NOTIFICATIONS: pushNotifications,
74
- },
89
+ };
90
+ }),
75
91
  afterWorker: ({ workerName }) =>
76
92
  Effect.gen(function* () {
77
93
  const consume = (
@@ -7,6 +7,24 @@ CREATE TABLE `blocked_senders` (
7
7
  FOREIGN KEY (`created_by_user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
8
8
  );
9
9
  --> statement-breakpoint
10
+ CREATE TABLE `jmap_push_subscriptions` (
11
+ `id` text PRIMARY KEY NOT NULL,
12
+ `user_id` text NOT NULL,
13
+ `client_id` text NOT NULL,
14
+ `device_client_id` text NOT NULL,
15
+ `url` text NOT NULL,
16
+ `p256dh` text,
17
+ `auth` text,
18
+ `verification_code` text NOT NULL,
19
+ `verified_at` integer,
20
+ `expires_at` integer NOT NULL,
21
+ `types_json` text,
22
+ `created_at` integer NOT NULL,
23
+ FOREIGN KEY (`client_id`,`user_id`) REFERENCES `oidc_grants`(`client_id`,`user_id`) ON UPDATE no action ON DELETE cascade
24
+ );
25
+ --> statement-breakpoint
26
+ CREATE UNIQUE INDEX `jmap_push_subscriptions_device_unique` ON `jmap_push_subscriptions` (`user_id`,`device_client_id`);--> statement-breakpoint
27
+ CREATE INDEX `jmap_push_subscriptions_expires_idx` ON `jmap_push_subscriptions` (`expires_at`);--> statement-breakpoint
10
28
  CREATE TABLE `mailbox_notification_preferences` (
11
29
  `mailbox_id` text NOT NULL,
12
30
  `user_id` text NOT NULL,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": "6",
3
3
  "dialect": "sqlite",
4
- "id": "cf90d43b-4927-4d8c-aad6-9d1182a8e66a",
4
+ "id": "e1a507fb-c877-4e1a-8bd6-acc6a143255f",
5
5
  "prevId": "00000000-0000-0000-0000-000000000000",
6
6
  "tables": {
7
7
  "blocked_senders": {
@@ -69,6 +69,132 @@
69
69
  "uniqueConstraints": {},
70
70
  "checkConstraints": {}
71
71
  },
72
+ "jmap_push_subscriptions": {
73
+ "name": "jmap_push_subscriptions",
74
+ "columns": {
75
+ "id": {
76
+ "name": "id",
77
+ "type": "text",
78
+ "primaryKey": true,
79
+ "notNull": true,
80
+ "autoincrement": false
81
+ },
82
+ "user_id": {
83
+ "name": "user_id",
84
+ "type": "text",
85
+ "primaryKey": false,
86
+ "notNull": true,
87
+ "autoincrement": false
88
+ },
89
+ "client_id": {
90
+ "name": "client_id",
91
+ "type": "text",
92
+ "primaryKey": false,
93
+ "notNull": true,
94
+ "autoincrement": false
95
+ },
96
+ "device_client_id": {
97
+ "name": "device_client_id",
98
+ "type": "text",
99
+ "primaryKey": false,
100
+ "notNull": true,
101
+ "autoincrement": false
102
+ },
103
+ "url": {
104
+ "name": "url",
105
+ "type": "text",
106
+ "primaryKey": false,
107
+ "notNull": true,
108
+ "autoincrement": false
109
+ },
110
+ "p256dh": {
111
+ "name": "p256dh",
112
+ "type": "text",
113
+ "primaryKey": false,
114
+ "notNull": false,
115
+ "autoincrement": false
116
+ },
117
+ "auth": {
118
+ "name": "auth",
119
+ "type": "text",
120
+ "primaryKey": false,
121
+ "notNull": false,
122
+ "autoincrement": false
123
+ },
124
+ "verification_code": {
125
+ "name": "verification_code",
126
+ "type": "text",
127
+ "primaryKey": false,
128
+ "notNull": true,
129
+ "autoincrement": false
130
+ },
131
+ "verified_at": {
132
+ "name": "verified_at",
133
+ "type": "integer",
134
+ "primaryKey": false,
135
+ "notNull": false,
136
+ "autoincrement": false
137
+ },
138
+ "expires_at": {
139
+ "name": "expires_at",
140
+ "type": "integer",
141
+ "primaryKey": false,
142
+ "notNull": true,
143
+ "autoincrement": false
144
+ },
145
+ "types_json": {
146
+ "name": "types_json",
147
+ "type": "text",
148
+ "primaryKey": false,
149
+ "notNull": false,
150
+ "autoincrement": false
151
+ },
152
+ "created_at": {
153
+ "name": "created_at",
154
+ "type": "integer",
155
+ "primaryKey": false,
156
+ "notNull": true,
157
+ "autoincrement": false
158
+ }
159
+ },
160
+ "indexes": {
161
+ "jmap_push_subscriptions_device_unique": {
162
+ "name": "jmap_push_subscriptions_device_unique",
163
+ "columns": [
164
+ "user_id",
165
+ "device_client_id"
166
+ ],
167
+ "isUnique": true
168
+ },
169
+ "jmap_push_subscriptions_expires_idx": {
170
+ "name": "jmap_push_subscriptions_expires_idx",
171
+ "columns": [
172
+ "expires_at"
173
+ ],
174
+ "isUnique": false
175
+ }
176
+ },
177
+ "foreignKeys": {
178
+ "jmap_push_subscriptions_client_id_user_id_oidc_grants_client_id_user_id_fk": {
179
+ "name": "jmap_push_subscriptions_client_id_user_id_oidc_grants_client_id_user_id_fk",
180
+ "tableFrom": "jmap_push_subscriptions",
181
+ "tableTo": "oidc_grants",
182
+ "columnsFrom": [
183
+ "client_id",
184
+ "user_id"
185
+ ],
186
+ "columnsTo": [
187
+ "client_id",
188
+ "user_id"
189
+ ],
190
+ "onDelete": "cascade",
191
+ "onUpdate": "no action"
192
+ }
193
+ },
194
+ "compositePrimaryKeys": {},
195
+ "uniqueConstraints": {},
196
+ "checkConstraints": {}
197
+ },
72
198
  "mailbox_notification_preferences": {
73
199
  "name": "mailbox_notification_preferences",
74
200
  "columns": {
@@ -5,7 +5,7 @@
5
5
  {
6
6
  "idx": 0,
7
7
  "version": "6",
8
- "when": 1793490619333,
8
+ "when": 1793521253047,
9
9
  "tag": "0000_email",
10
10
  "breakpoints": true
11
11
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-workspace/email",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "Team mail for OpenWorkspace: personal and shared inboxes, mailing lists, previews, safety, and AI.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -20,7 +20,7 @@
20
20
  "db:generate": "drizzle-kit generate && drizzle-kit generate --config=drizzle.mailbox.config.ts && bun scripts/embed-mailbox-migrations.ts"
21
21
  },
22
22
  "peerDependencies": {
23
- "@open-workspace/core": "0.1.1",
23
+ "@open-workspace/core": "0.3.0",
24
24
  "alchemy": "2.0.0-beta.84",
25
25
  "@alchemy.run/cloudflare": "2.0.0-beta.84",
26
26
  "effect": "4.0.7"
@@ -42,7 +42,7 @@
42
42
  "@base-ui/react": "1.7.0",
43
43
  "@effect/platform-bun": "4.0.7",
44
44
  "@effect/platform-node": "4.0.7",
45
- "@open-workspace/core": "0.1.1",
45
+ "@open-workspace/core": "0.3.0",
46
46
  "@simplewebauthn/browser": "13.3.0",
47
47
  "@tanstack/react-query": "5.102.8",
48
48
  "@tiptap/extension-image": "3.30.5",
package/shared/mail.ts CHANGED
@@ -68,14 +68,17 @@ type MailboxPushJobBase = {
68
68
  subject: string;
69
69
  };
70
70
 
71
- export type MailboxPushJob = MailboxPushJobBase & (
72
- | { type: "dispatch" }
73
- | {
74
- type: "deliver";
75
- targetSubscriptionId: string;
76
- mailboxDisplayName: string;
77
- }
78
- );
71
+ export type MailboxPushJob =
72
+ | (MailboxPushJobBase & (
73
+ | { type: "dispatch" }
74
+ | {
75
+ type: "deliver";
76
+ targetSubscriptionId: string;
77
+ mailboxDisplayName: string;
78
+ }
79
+ ))
80
+ /** The mailbox's JMAP state moved; tell JMAP push subscribers. */
81
+ | { type: "jmap-state"; mailboxId: string; state: string; occurredAt: number };
79
82
 
80
83
  export const MAX_COMPOSER_ATTACHMENT_BYTES = 500_000_000;
81
84
  export const MAX_COMPOSER_ATTACHMENT_COUNT = 10;
@@ -1,5 +1,6 @@
1
1
  import { sql } from "drizzle-orm";
2
2
  import {
3
+ foreignKey,
3
4
  index,
4
5
  integer,
5
6
  primaryKey,
@@ -7,7 +8,7 @@ import {
7
8
  text,
8
9
  uniqueIndex,
9
10
  } from "drizzle-orm/sqlite-core";
10
- import { mailboxes, users } from "@open-workspace/core/worker/db/schema.ts";
11
+ import { mailboxes, oidcGrants, users } from "@open-workspace/core/worker/db/schema.ts";
11
12
  import type { ReportSnapshot } from "../../shared/mail-feedback";
12
13
 
13
14
  /** D1 tables of the mail module; core's tables are in @open-workspace/core. */
@@ -95,3 +96,35 @@ export const blockedSenders = sqliteTable(
95
96
  createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull(),
96
97
  },
97
98
  );
99
+
100
+ /**
101
+ * JMAP push subscriptions (RFC 8620 §7.2). Each belongs to the OAuth grant
102
+ * that created it, so revoking the app's access removes it.
103
+ */
104
+ export const jmapPushSubscriptions = sqliteTable(
105
+ "jmap_push_subscriptions",
106
+ {
107
+ id: text("id").primaryKey(),
108
+ userId: text("user_id").notNull(),
109
+ clientId: text("client_id").notNull(),
110
+ deviceClientId: text("device_client_id").notNull(),
111
+ url: text("url").notNull(),
112
+ /** Web Push encryption keys (RFC 8291), base64url; both or neither. */
113
+ p256dh: text("p256dh"),
114
+ auth: text("auth"),
115
+ verificationCode: text("verification_code").notNull(),
116
+ verifiedAt: integer("verified_at", { mode: "timestamp_ms" }),
117
+ expiresAt: integer("expires_at", { mode: "timestamp_ms" }).notNull(),
118
+ /** Data types to push, or null for all. */
119
+ typesJson: text("types_json", { mode: "json" }).$type<string[] | null>(),
120
+ createdAt: integer("created_at", { mode: "timestamp_ms" }).notNull(),
121
+ },
122
+ (table) => [
123
+ foreignKey({
124
+ columns: [table.clientId, table.userId],
125
+ foreignColumns: [oidcGrants.clientId, oidcGrants.userId],
126
+ }).onDelete("cascade"),
127
+ uniqueIndex("jmap_push_subscriptions_device_unique").on(table.userId, table.deviceClientId),
128
+ index("jmap_push_subscriptions_expires_idx").on(table.expiresAt),
129
+ ],
130
+ );
@@ -0,0 +1,101 @@
1
+ import { mailboxStub } from "../mailbox";
2
+ import type { JmapAccount } from "./methods";
3
+ import { JMAP_PUSH_TYPES, stateChange } from "./push";
4
+
5
+ /** How often a stream re-checks its token when the client asked for no pings. */
6
+ const AUTHORIZATION_CHECK_SECONDS = 300;
7
+ const MIN_PING_SECONDS = 30;
8
+
9
+ /**
10
+ * An RFC 8620 §7.3 event stream: a `state` event whenever one of the
11
+ * accounts' mailboxes changes, and `ping` events at the asked interval.
12
+ * Each mailbox Durable Object sends its new state over a WebSocket the
13
+ * stream holds open.
14
+ */
15
+ export async function jmapEventStream(input: {
16
+ env: Env;
17
+ accounts: JmapAccount[];
18
+ /** `*` or a comma-separated list of data types. */
19
+ types: string;
20
+ closeAfterState: boolean;
21
+ pingSeconds: number;
22
+ stillAuthorized: () => Promise<boolean>;
23
+ defer: (task: Promise<unknown>) => void;
24
+ }) {
25
+ const wanted = input.types === "*" ? null : input.types.split(",").map((type) => type.trim());
26
+ const interested = !wanted || wanted.some((type) => (JMAP_PUSH_TYPES as readonly string[]).includes(type));
27
+ const pingSeconds = Number.isFinite(input.pingSeconds) && input.pingSeconds > 0
28
+ ? Math.max(MIN_PING_SECONDS, Math.floor(input.pingSeconds))
29
+ : 0;
30
+
31
+ const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>();
32
+ const writer = writable.getWriter();
33
+ const encoder = new TextEncoder();
34
+ const sockets: WebSocket[] = [];
35
+ let timer: ReturnType<typeof setInterval> | undefined;
36
+ let closed = false;
37
+ let finished!: () => void;
38
+ input.defer(new Promise<void>((resolve) => { finished = resolve; }));
39
+
40
+ const close = () => {
41
+ if (closed) return;
42
+ closed = true;
43
+ clearInterval(timer);
44
+ for (const socket of sockets) {
45
+ try {
46
+ socket.close(1000, "Event stream closed");
47
+ } catch {
48
+ // Already closed by the mailbox.
49
+ }
50
+ }
51
+ writer.close().catch(() => {});
52
+ finished();
53
+ };
54
+ const write = (text: string) => {
55
+ if (closed) return;
56
+ // A write fails once the client has gone; that ends the stream.
57
+ writer.write(encoder.encode(text)).catch(close);
58
+ };
59
+ const event = (name: string, data: unknown) => write(`event: ${name}\ndata: ${JSON.stringify(data)}\n\n`);
60
+
61
+ if (interested) {
62
+ for (const account of input.accounts) {
63
+ const response = await mailboxStub(input.env, account.id).fetch(new Request("https://mailbox.internal/jmap", {
64
+ headers: { upgrade: "websocket", "x-openworkspace-jmap": "1" },
65
+ }));
66
+ const socket = response.webSocket;
67
+ if (!socket) continue;
68
+ socket.accept();
69
+ sockets.push(socket);
70
+ socket.addEventListener("message", (message) => {
71
+ if (typeof message.data !== "string") return;
72
+ event("state", stateChange({ [account.id]: message.data }));
73
+ if (input.closeAfterState) close();
74
+ });
75
+ // A mailbox that goes away (deleted, or the object restarted) ends the
76
+ // stream; the client reconnects and gets a fresh set of accounts.
77
+ socket.addEventListener("close", close);
78
+ socket.addEventListener("error", close);
79
+ }
80
+ }
81
+
82
+ const tick = async () => {
83
+ if (!(await input.stillAuthorized().catch(() => false))) {
84
+ close();
85
+ return;
86
+ }
87
+ if (pingSeconds) event("ping", { "@type": "Ping", interval: pingSeconds });
88
+ else write(": keep-alive\n\n");
89
+ };
90
+ timer = setInterval(() => void tick(), (pingSeconds || AUTHORIZATION_CHECK_SECONDS) * 1_000);
91
+ // Flush the headers to the client straight away.
92
+ write(": connected\n\n");
93
+
94
+ return new Response(readable, {
95
+ headers: {
96
+ "content-type": "text/event-stream; charset=utf-8",
97
+ "cache-control": "no-cache, no-transform",
98
+ "x-accel-buffering": "no",
99
+ },
100
+ });
101
+ }