@open-workspace/email 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/README.md +23 -20
  2. package/alchemy/index.ts +273 -0
  3. package/drizzle/mailbox/0000_puzzling_dracula.sql +149 -0
  4. package/drizzle/mailbox/0001_mute_jack_flag.sql +12 -0
  5. package/drizzle/mailbox/meta/0000_snapshot.json +1002 -0
  6. package/drizzle/mailbox/meta/0001_snapshot.json +1002 -0
  7. package/drizzle/mailbox/meta/_journal.json +20 -0
  8. package/drizzle/mailbox/migrations.js +12 -0
  9. package/index.ts +3 -1
  10. package/migrations/0000_dry_moon_knight.sql +77 -0
  11. package/migrations/meta/0000_snapshot.json +248 -106
  12. package/migrations/meta/_journal.json +2 -2
  13. package/package.json +74 -68
  14. package/shared/attachment-preview.ts +37 -27
  15. package/shared/folder-order.ts +106 -0
  16. package/shared/mail-authentication.ts +8 -3
  17. package/shared/mail-feedback.ts +18 -25
  18. package/shared/mail-headers.ts +114 -39
  19. package/shared/mail-import.ts +38 -0
  20. package/shared/mail-path.ts +42 -0
  21. package/shared/mail-received.ts +174 -31
  22. package/shared/mail-remote.ts +59 -2
  23. package/shared/mail-sender-intel.ts +22 -4
  24. package/shared/mail.ts +78 -26
  25. package/shared/module.ts +33 -0
  26. package/shared/office-preview.ts +14 -2
  27. package/shared/pdfjs-assets.ts +35 -0
  28. package/shared/permissions.ts +73 -0
  29. package/shared/webhooks.ts +41 -0
  30. package/src/admin/blocked-senders.tsx +189 -0
  31. package/src/client.tsx +97 -0
  32. package/src/lib/mail-api.ts +9 -0
  33. package/src/mail/attachment-preview-dialog.tsx +161 -0
  34. package/src/mail/blocked-senders.tsx +138 -0
  35. package/src/mail/compose-window-chrome.tsx +194 -0
  36. package/src/mail/compose-window.tsx +486 -0
  37. package/src/mail/composer-asset-bookmarks.ts +409 -0
  38. package/src/mail/composer-asset.tsx +229 -0
  39. package/src/mail/composer-attachment-list.tsx +138 -0
  40. package/src/mail/composer-editor-document.ts +65 -0
  41. package/src/mail/composer-editor.tsx +284 -0
  42. package/src/mail/composer-linked-attachment-text.ts +12 -0
  43. package/src/mail/composer-recipient-fields.tsx +165 -0
  44. package/src/mail/composer-recipients.ts +208 -0
  45. package/src/mail/composer-session.ts +562 -0
  46. package/src/mail/composer-toolbar.tsx +303 -0
  47. package/src/mail/composer-upload-client.ts +105 -0
  48. package/src/mail/composer-upload-progress.ts +53 -0
  49. package/src/mail/conversation-list.tsx +550 -0
  50. package/src/mail/conversation-loading-skeleton.tsx +119 -0
  51. package/src/mail/conversation-message.tsx +346 -0
  52. package/src/mail/conversation-reply.tsx +470 -0
  53. package/src/mail/conversation-selection-toolbar.tsx +322 -0
  54. package/src/mail/conversation-view.tsx +437 -0
  55. package/src/mail/delivery-indicator.tsx +272 -0
  56. package/src/mail/email-html-body.tsx +203 -0
  57. package/src/mail/folder-glyph.tsx +46 -0
  58. package/src/mail/folder-manager.tsx +532 -0
  59. package/src/mail/format-bytes.ts +7 -0
  60. package/src/mail/mail-app-bar.tsx +253 -0
  61. package/src/mail/mail-background.tsx +12 -0
  62. package/src/mail/mail-dock.tsx +137 -0
  63. package/src/mail/mail-folders.ts +44 -0
  64. package/src/mail/mail-layout.css +236 -0
  65. package/src/mail/mail-location.ts +73 -0
  66. package/src/mail/mail-mailbox-sheet.tsx +275 -0
  67. package/src/mail/mail-nav-rail.tsx +129 -0
  68. package/src/mail/mail-nav.tsx +324 -0
  69. package/src/mail/mail-prefetch.ts +59 -0
  70. package/src/mail/mail-primitives.tsx +66 -0
  71. package/src/mail/mail-queries.ts +209 -0
  72. package/src/mail/mail-query-cache.ts +486 -0
  73. package/src/mail/mail-seed.ts +47 -0
  74. package/src/mail/mail-shell.tsx +126 -0
  75. package/src/mail/mailbox-ai-settings.tsx +185 -0
  76. package/src/mail/mailbox-realtime.tsx +251 -0
  77. package/src/mail/mailbox-route.tsx +15 -0
  78. package/src/mail/message-actions.tsx +353 -0
  79. package/src/mail/message-attachments.tsx +200 -0
  80. package/src/mail/message-format.ts +75 -0
  81. package/src/mail/message-header.tsx +260 -0
  82. package/src/mail/message-translation.tsx +225 -0
  83. package/src/mail/original-message-sheet.tsx +619 -0
  84. package/src/mail/original-message.ts +191 -0
  85. package/src/mail/outbound-notification.ts +53 -0
  86. package/src/mail/pane-splitter.tsx +117 -0
  87. package/src/mail/pdf-preview-toolbar.tsx +152 -0
  88. package/src/mail/pdf-preview.css +44 -0
  89. package/src/mail/pdf-preview.tsx +156 -0
  90. package/src/mail/pdf-translation-layout.ts +95 -0
  91. package/src/mail/print-message.ts +92 -0
  92. package/src/mail/reader-pane.tsx +535 -0
  93. package/src/mail/recipient-combobox.tsx +335 -0
  94. package/src/mail/recipient-field-row.tsx +34 -0
  95. package/src/mail/reply-to-warning.tsx +50 -0
  96. package/src/mail/sanitize-email-html.ts +430 -0
  97. package/src/mail/sender-actions.tsx +149 -0
  98. package/src/mail/sender-authentication.tsx +485 -0
  99. package/src/mail/sender-dialogs.tsx +384 -0
  100. package/src/mail/sender-security.tsx +545 -0
  101. package/src/mail/toolbar-tooltip.tsx +29 -0
  102. package/src/mail/translation-html.ts +49 -0
  103. package/src/mail/translation-language.ts +21 -0
  104. package/src/mail/types.ts +53 -0
  105. package/src/mail/unread-document-indicator.tsx +60 -0
  106. package/src/mail/use-compose-submission.ts +208 -0
  107. package/src/mail/use-composer-attachment-preflight.ts +184 -0
  108. package/src/mail/use-composer-submission.ts +117 -0
  109. package/src/mail/use-conversation-selection.ts +186 -0
  110. package/src/mail/use-mail-controller.ts +427 -0
  111. package/src/mail/use-mail-data.ts +279 -0
  112. package/src/mail/use-mail-safety.ts +155 -0
  113. package/src/mail/use-mail-send.ts +142 -0
  114. package/src/mail/use-pdf-translation-overlay.ts +156 -0
  115. package/src/mail/use-pdf-translation.ts +100 -0
  116. package/src/mail/use-pdf-viewer.ts +215 -0
  117. package/src/mail/use-reply-submission.ts +114 -0
  118. package/src/mail/use-sanitized-email-html.ts +20 -0
  119. package/src/mail/use-visible-message-read.ts +138 -0
  120. package/src/pwa/push-subscription.ts +151 -0
  121. package/src/settings/mail-apps-page.tsx +235 -0
  122. package/src/settings/notifications-page.tsx +291 -0
  123. package/worker/admin/blocked-sender-routes.ts +166 -0
  124. package/worker/admin/schemas.ts +11 -0
  125. package/worker/bindings.d.ts +14 -10
  126. package/worker/db/schema.ts +90 -34
  127. package/worker/jmap/eventsource.ts +169 -0
  128. package/worker/jmap/methods.ts +1716 -361
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +207 -0
  131. package/worker/jmap/routes.ts +448 -86
  132. package/worker/mail/access.ts +258 -21
  133. package/worker/mail/ai-classification.ts +36 -20
  134. package/worker/mail/ai-translation.ts +13 -6
  135. package/worker/mail/auth-headers.ts +395 -137
  136. package/worker/mail/bimi.ts +200 -73
  137. package/worker/mail/bootstrap.ts +79 -0
  138. package/worker/mail/capped-body.ts +36 -0
  139. package/worker/mail/classification-signals.ts +35 -25
  140. package/worker/mail/conversation-cursor.ts +30 -19
  141. package/worker/mail/delivery-events.ts +88 -62
  142. package/worker/mail/delivery-facts.ts +46 -10
  143. package/worker/mail/demo-routes.ts +34 -10
  144. package/worker/mail/doh.ts +62 -23
  145. package/worker/mail/downloads.ts +75 -40
  146. package/worker/mail/edge-cache.ts +155 -0
  147. package/worker/mail/header-metadata.ts +84 -52
  148. package/worker/mail/impersonation.ts +160 -38
  149. package/worker/mail/import-routes.ts +313 -0
  150. package/worker/mail/inbound-delivery.ts +19 -9
  151. package/worker/mail/inbound-threading.ts +18 -8
  152. package/worker/mail/inbound.ts +82 -40
  153. package/worker/mail/ip-intel.ts +110 -27
  154. package/worker/mail/isolate-cache.ts +35 -0
  155. package/worker/mail/link-domains.ts +29 -7
  156. package/worker/mail/mailbox-deletion.ts +10 -4
  157. package/worker/mail/mailbox-directory.ts +16 -6
  158. package/worker/mail/mailing-list.ts +94 -39
  159. package/worker/mail/message-security.ts +90 -15
  160. package/worker/mail/message-view.ts +18 -6
  161. package/worker/mail/office-conversion.ts +31 -9
  162. package/worker/mail/office-preview-container.ts +40 -13
  163. package/worker/mail/office-preview-queue.ts +76 -32
  164. package/worker/mail/org-domain.ts +8 -1
  165. package/worker/mail/outbound-content.ts +71 -26
  166. package/worker/mail/outbound-delivery.ts +31 -17
  167. package/worker/mail/outbound-service.ts +48 -30
  168. package/worker/mail/outbound-threading.ts +30 -17
  169. package/worker/mail/outbound.ts +97 -70
  170. package/worker/mail/outgoing-context.ts +25 -15
  171. package/worker/mail/participants.ts +44 -29
  172. package/worker/mail/push-notifications.ts +283 -171
  173. package/worker/mail/quote-parser.ts +21 -10
  174. package/worker/mail/r2-presigned-urls.ts +31 -25
  175. package/worker/mail/receive.ts +23 -11
  176. package/worker/mail/recipients.ts +6 -1
  177. package/worker/mail/remote-proxy.ts +187 -31
  178. package/worker/mail/remote-routes.ts +87 -0
  179. package/worker/mail/remote-token.ts +104 -0
  180. package/worker/mail/repeat.ts +19 -0
  181. package/worker/mail/reply-plan.ts +62 -33
  182. package/worker/mail/rfc.ts +32 -7
  183. package/worker/mail/routes.ts +871 -542
  184. package/worker/mail/safety-routes.ts +329 -202
  185. package/worker/mail/schemas.ts +84 -105
  186. package/worker/mail/search.ts +1 -0
  187. package/worker/mail/security-settings.ts +41 -9
  188. package/worker/mail/sender-intel.ts +206 -51
  189. package/worker/mail/spamhaus.ts +92 -45
  190. package/worker/mail/unsubscribe.ts +76 -18
  191. package/worker/mail/uploads.ts +153 -91
  192. package/worker/mail/webhook-source.ts +35 -12
  193. package/worker/mail/workspace-safety.ts +97 -38
  194. package/worker/mailbox/demo-html.ts +7 -7
  195. package/worker/mailbox/demo-seed.ts +10 -44
  196. package/worker/mailbox/demo.ts +597 -227
  197. package/worker/mailbox/email-index.ts +53 -0
  198. package/worker/mailbox/folder-model.ts +53 -17
  199. package/worker/mailbox/import-placement.ts +88 -0
  200. package/worker/mailbox/inbox-counts.ts +106 -0
  201. package/worker/mailbox/index.ts +1761 -737
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +7 -14
  204. package/worker/mailbox/office-preview-jobs.ts +56 -25
  205. package/worker/mailbox/schema.ts +87 -66
  206. package/worker/mailbox/senders.ts +176 -70
  207. package/worker/mcp/mail-action-tools.ts +128 -87
  208. package/worker/mcp/mail-compose-tools.ts +133 -82
  209. package/worker/mcp/mail-query-tools.ts +120 -71
  210. package/worker/mcp/mail-safety-tools.ts +321 -248
  211. package/worker/mcp/schemas.ts +43 -0
  212. package/worker/mcp/tools.ts +13 -10
  213. package/worker/module.ts +43 -18
  214. package/worker/sql.d.ts +8 -0
  215. package/alchemy.ts +0 -126
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/migrations/0000_email.sql +0 -53
  218. package/shared/mail-rules.ts +0 -156
  219. package/worker/admin/report-routes.ts +0 -164
  220. package/worker/mail/reported-messages.ts +0 -68
  221. package/worker/mailbox/legacy-migrations.ts +0 -41
  222. package/worker/mailbox/migrations.ts +0 -10
  223. package/worker/mailbox/rules.ts +0 -110
@@ -0,0 +1,43 @@
1
+ import { entityIdSchema } from "@open-workspace/core/module";
2
+ import { z } from "zod";
3
+
4
+ import {
5
+ MAX_BULK_CONVERSATION_COUNT,
6
+ mailboxStates,
7
+ replyActionModes,
8
+ } from "../../shared/mail";
9
+ import {
10
+ outboundMessageContentFields,
11
+ outboundRecipientFields,
12
+ } from "../mail/schemas";
13
+
14
+ export { entityIdSchema };
15
+
16
+ export const mailboxIdSchema = z.string().trim().min(1).max(255);
17
+
18
+ export const mailboxInputSchema = z.object({ mailboxId: mailboxIdSchema });
19
+
20
+ export const conversationIdsSchema = z
21
+ .array(entityIdSchema)
22
+ .min(1)
23
+ .max(MAX_BULK_CONVERSATION_COUNT)
24
+ .transform((ids) => [...new Set(ids)]);
25
+
26
+ export const messageContentFields = {
27
+ ...outboundMessageContentFields,
28
+ requestId: z
29
+ .uuid()
30
+ .optional()
31
+ .describe(
32
+ "Stable idempotency key. Reuse it when retrying the same send operation."
33
+ ),
34
+ };
35
+
36
+ export const recipientFields = outboundRecipientFields;
37
+
38
+ export const mailboxStateSchema = z.enum(mailboxStates);
39
+ export const replyModeSchema = z.enum(replyActionModes);
40
+
41
+ export function requestId(value: string | undefined) {
42
+ return value ?? crypto.randomUUID();
43
+ }
@@ -1,15 +1,18 @@
1
- import type { WorkspaceModule } from "@open-workspace/core/worker/modules.ts";
1
+ import type { McpToolRegistrar } from "@open-workspace/core/module";
2
+
2
3
  import { registerMailActionTools } from "./mail-action-tools";
3
4
  import { registerMailComposeTools } from "./mail-compose-tools";
4
5
  import { registerMailQueryTools } from "./mail-query-tools";
5
- import { registerAdminSafetyTools, registerMailSafetyTools } from "./mail-safety-tools";
6
+ import {
7
+ registerAdminSafetyTools,
8
+ registerMailSafetyTools,
9
+ } from "./mail-safety-tools";
6
10
 
7
- export const registerMailTools: NonNullable<WorkspaceModule["mcpTools"]> = (server, input) => {
8
- registerMailQueryTools(server, input.api);
9
- registerMailActionTools(server, input.api);
10
- registerMailComposeTools(server, input.api);
11
- registerMailSafetyTools(server, input.api);
12
- if (input.permissions.includes("review_reports")) {
13
- registerAdminSafetyTools(server, input.api);
14
- }
11
+ /** Mail tools; each declares the scope it needs, so a token sees only what it was granted. */
12
+ export const registerMailTools: McpToolRegistrar = (tool, input) => {
13
+ registerMailQueryTools(tool, input.api);
14
+ registerMailActionTools(tool, input.api);
15
+ registerMailComposeTools(tool, input.api);
16
+ registerMailSafetyTools(tool, input.api);
17
+ registerAdminSafetyTools(tool, input.api);
15
18
  };
package/worker/module.ts CHANGED
@@ -1,30 +1,45 @@
1
+ import type {
2
+ AppEnv,
3
+ QueueConsumer,
4
+ WorkspaceModule,
5
+ } from "@open-workspace/core/module";
1
6
  import { Hono } from "hono";
2
- import type { AppEnv } from "@open-workspace/core/worker/env.ts";
3
- import type { WorkspaceModule } from "@open-workspace/core/worker/modules.ts";
4
- import { reportAdminRoutes } from "./admin/report-routes";
7
+
8
+ import { EMAIL_MODULE, emailQueueRoles } from "../shared/module";
9
+ import type { EmailQueueRole } from "../shared/module";
10
+ import { emailPermissions, mailOauthScopes } from "../shared/permissions";
11
+ import { EMAIL_WEBHOOK_SOURCE, emailWebhookEvents } from "../shared/webhooks";
12
+ import { blockedSenderAdminRoutes } from "./admin/blocked-sender-routes";
13
+ import { jmapRoutes } from "./jmap/routes";
14
+ import { mailBootstrap } from "./mail/bootstrap";
5
15
  import { consumeDeliveryEvents } from "./mail/delivery-events";
6
16
  import { demoRoutes } from "./mail/demo-routes";
7
17
  import { mailDownloadRoutes } from "./mail/downloads";
8
- import { receiveEmail } from "./mail/receive";
18
+ import { mailImportRoutes } from "./mail/import-routes";
9
19
  import { deleteMailboxStorage } from "./mail/mailbox-deletion";
10
20
  import { consumeOfficePreviews } from "./mail/office-preview-queue";
11
21
  import {
12
22
  consumePushNotifications,
23
+ deleteUserPushSubscriptions,
13
24
  pushNotificationRoutes,
14
25
  } from "./mail/push-notifications";
26
+ import { receiveEmail } from "./mail/receive";
27
+ import { mailRemoteRoutes } from "./mail/remote-routes";
15
28
  import { mailRoutes } from "./mail/routes";
16
29
  import { emailWebhookData } from "./mail/webhook-source";
17
30
  import { seedEmailDemo } from "./mailbox/demo-seed";
18
- import { registerMailTools } from "./mcp/tools";
19
- import { jmapRoutes } from "./jmap/routes";
20
31
 
21
32
  /** Routes the browser and MCP use under /api. */
22
33
  export const mailAccountApi = new Hono<AppEnv>()
34
+ // Ahead of mailRoutes, whose session check it does without (it answers
35
+ // first, so that middleware never runs for it).
36
+ .route("/mail/remote", mailRemoteRoutes)
37
+ .route("/mail/import", mailImportRoutes)
23
38
  .route("/mail", mailRoutes)
24
- .route("/admin", reportAdminRoutes);
39
+ .route("/admin", blockedSenderAdminRoutes);
25
40
 
26
41
  const mailPublicRoutes = new Hono<AppEnv>()
27
- .route("/", jmapRoutes as unknown as Hono<AppEnv>)
42
+ .route("/", jmapRoutes)
28
43
  .route("/api/downloads", mailDownloadRoutes)
29
44
  .route("/api/demo", demoRoutes)
30
45
  .route("/api/notifications", pushNotificationRoutes);
@@ -33,29 +48,39 @@ const mailPublicRoutes = new Hono<AppEnv>()
33
48
  export const mailBrowserApi = new Hono<AppEnv>()
34
49
  .route("/api", mailAccountApi)
35
50
  .route("/", mailPublicRoutes);
51
+
36
52
  export type MailAppType = typeof mailBrowserApi;
37
53
 
38
54
  /**
39
55
  * Team mail: personal and shared inboxes, mailing lists, previews, safety,
40
- * and push. Pass `email()` to `createWorkspace({ modules })`, and export
41
- * `MailboxDO` and `OfficePreviewContainer` from the Worker entry.
56
+ * and push. `Email()` in alchemy.run.ts puts it in the generated Worker
57
+ * entry, which also exports `MailboxDO` and `OfficePreviewContainer`.
42
58
  */
43
59
  export function email(): WorkspaceModule {
44
60
  return {
45
- name: "email",
61
+ name: EMAIL_MODULE,
46
62
  accountApi: mailAccountApi,
63
+ bootstrap: mailBootstrap,
64
+ permissions: emailPermissions,
65
+ oauthScopes: mailOauthScopes,
47
66
  routes: mailPublicRoutes,
48
67
  email: (message, env) => receiveEmail(message, env),
49
68
  queues: {
50
- "office-previews": (batch, env) => consumeOfficePreviews(batch, env),
51
- "push-notifications": (batch, env) => consumePushNotifications(batch, env),
52
- "delivery-events": (batch, env) => consumeDeliveryEvents(batch, env),
53
- },
54
- mcpTools: registerMailTools,
55
- webhookSources: { email: emailWebhookData },
69
+ [emailQueueRoles.officePreviews]: (batch, env) =>
70
+ consumeOfficePreviews(batch, env),
71
+ [emailQueueRoles.pushNotifications]: (batch, env) =>
72
+ consumePushNotifications(batch, env),
73
+ [emailQueueRoles.deliveryEvents]: (batch, env) =>
74
+ consumeDeliveryEvents(batch, env),
75
+ } satisfies Record<EmailQueueRole, QueueConsumer>,
76
+ mcpTools: () =>
77
+ import("./mcp/tools").then((tools) => tools.registerMailTools),
78
+ webhookEvents: emailWebhookEvents,
79
+ webhookSources: { [EMAIL_WEBHOOK_SOURCE]: emailWebhookData },
56
80
  hooks: {
57
81
  mailboxDeleted: deleteMailboxStorage,
58
- seedDemo: (env, input) => seedEmailDemo(env, input),
82
+ sessionsRevoked: deleteUserPushSubscriptions,
83
+ seedDemo: (env) => seedEmailDemo(env),
59
84
  },
60
85
  };
61
86
  }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * SQL files imported as text: drizzle-kit's drizzle/mailbox/migrations.js
3
+ * imports each mailbox migration, and Alchemy's bundler loads `.sql` as text.
4
+ */
5
+ declare module "*.sql" {
6
+ const sql: string;
7
+ export default sql;
8
+ }
package/alchemy.ts DELETED
@@ -1,126 +0,0 @@
1
- import { dirname, join } from "node:path";
2
- import { fileURLToPath } from "node:url";
3
- import * as Cloudflare from "@alchemy.run/cloudflare";
4
- import * as Effect from "effect/Effect";
5
- import type { WorkspaceModuleInfra } from "@open-workspace/core/alchemy";
6
-
7
- const packageDir = dirname(fileURLToPath(import.meta.url));
8
-
9
- /** Email Sending events that update delivery status in the app. */
10
- const deliveryEvents = [
11
- "message.delivered",
12
- "message.bounced",
13
- "message.deferred",
14
- "message.complained",
15
- "message.failed",
16
- "message.rejected",
17
- ];
18
-
19
- export type EmailInfraProps = {
20
- /**
21
- * Mail domains to wire up: Email Routing on, catch-all to this Worker,
22
- * the domain onboarded to Email Sending, and its delivery events queued.
23
- * Each must be a zone in the account. Leave out to configure them in the
24
- * dashboard instead.
25
- */
26
- domains?: string[];
27
- /** R2 bucket for raw messages and attachments; defaults to `<name>-mail`. */
28
- bucketName?: string;
29
- /** Queue names default to `<name>-<role>`; set to keep existing queues. */
30
- queuePrefix?: string;
31
- /** Name of an existing Office preview container application to adopt. */
32
- containerName?: string;
33
- };
34
-
35
- /**
36
- * The mail module's Cloudflare resources: the mail bucket, a SQLite Durable
37
- * Object per mailbox, the Office preview container, its queues, and the
38
- * outbound mail binding.
39
- */
40
- export function Email(props: EmailInfraProps = {}): (name: string) => WorkspaceModuleInfra {
41
- return (name) => {
42
- const prefix = props.queuePrefix ?? name;
43
- const queue = (id: string, role: string) =>
44
- Cloudflare.Queues.Queue(id, { name: `${prefix}-${role}` });
45
- const officePreviews = queue("OfficePreviews", "office-previews");
46
- const pushNotifications = queue("PushNotifications", "push-notifications");
47
- const deliveryEventsQueue = queue("DeliveryEvents", "delivery-events");
48
-
49
- return {
50
- name: "email",
51
- migrations: join(packageDir, "migrations"),
52
- secrets: [
53
- "VAPID_PUBLIC_KEY",
54
- "VAPID_PRIVATE_KEY",
55
- "VAPID_SUBJECT",
56
- "R2_ACCESS_KEY_ID",
57
- "R2_SECRET_ACCESS_KEY",
58
- "R2_ACCOUNT_ID",
59
- "R2_BUCKET_NAME",
60
- "SPAMHAUS_DQS_KEY",
61
- ],
62
- env: {
63
- MAIL_STORAGE: Cloudflare.R2.Bucket("MailStorage", { name: props.bucketName ?? `${name}-mail` }),
64
- EMAIL: Cloudflare.Email.SendEmail("EMAIL"),
65
- MAILBOX: Cloudflare.DurableObject("MAILBOX", { className: "MailboxDO" }),
66
- OFFICE_PREVIEW_CONTAINER: Cloudflare.Container("OfficePreview", {
67
- className: "OfficePreviewContainer",
68
- ...(props.containerName ? { name: props.containerName } : {}),
69
- context: join(packageDir, "containers", "office-preview"),
70
- maxInstances: 2,
71
- }),
72
- OFFICE_PREVIEWS: officePreviews,
73
- PUSH_NOTIFICATIONS: pushNotifications,
74
- },
75
- afterWorker: ({ workerName }) =>
76
- Effect.gen(function* () {
77
- const consume = (
78
- id: string,
79
- source: typeof officePreviews,
80
- settings: { batchSize: number; maxConcurrency?: number; maxWaitTimeMs: number },
81
- ) =>
82
- Effect.gen(function* () {
83
- const { queueId } = yield* source;
84
- yield* Cloudflare.Queues.Consumer(id, {
85
- queueId,
86
- scriptName: workerName,
87
- settings: { maxRetries: 5, ...settings },
88
- });
89
- return queueId;
90
- });
91
- // Each preview converts in a container; two at a time.
92
- yield* consume("OfficePreviewsConsumer", officePreviews, {
93
- batchSize: 1,
94
- maxConcurrency: 2,
95
- maxWaitTimeMs: 1_000,
96
- });
97
- yield* consume("PushNotificationsConsumer", pushNotifications, {
98
- batchSize: 10,
99
- maxWaitTimeMs: 2_000,
100
- });
101
- const deliveryQueueId = yield* consume("DeliveryEventsConsumer", deliveryEventsQueue, {
102
- batchSize: 10,
103
- maxWaitTimeMs: 5_000,
104
- });
105
-
106
- for (const domain of props.domains ?? []) {
107
- const id = domain.replaceAll(".", "-");
108
- const routing = yield* Cloudflare.Email.Routing(`Routing-${id}`, { zone: domain });
109
- yield* Cloudflare.Email.CatchAll(`CatchAll-${id}`, {
110
- zone: routing.zoneId,
111
- actions: [{ type: "worker", value: [workerName] }],
112
- });
113
- yield* Cloudflare.Email.SendingSubdomain(`Sending-${id}`, {
114
- zoneId: routing.zoneId,
115
- name: domain,
116
- });
117
- yield* Cloudflare.Queues.Subscription(`DeliveryEvents-${id}`, {
118
- source: { type: "email.sending", zoneId: routing.zoneId, domain },
119
- events: deliveryEvents,
120
- queueId: deliveryQueueId,
121
- });
122
- }
123
- }),
124
- };
125
- };
126
- }
@@ -1,10 +0,0 @@
1
- FROM gotenberg/gotenberg:8.37.0
2
-
3
- # Only local Office uploads are accepted; document links cannot access the network.
4
- ENV CHROMIUM_DISABLE_ROUTES=true \
5
- API_DISABLE_DOWNLOAD_FROM=true \
6
- WEBHOOK_DISABLE=true \
7
- LIBREOFFICE_DENY_LIST=.* \
8
- API_TIMEOUT=90s
9
-
10
- EXPOSE 3000
@@ -1,53 +0,0 @@
1
- CREATE TABLE `blocked_senders` (
2
- `pattern` text PRIMARY KEY NOT NULL,
3
- `report_id` text,
4
- `created_by_user_id` text,
5
- `created_at` integer NOT NULL,
6
- FOREIGN KEY (`report_id`) REFERENCES `reported_messages`(`id`) ON UPDATE no action ON DELETE set null,
7
- FOREIGN KEY (`created_by_user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
8
- );
9
- --> statement-breakpoint
10
- CREATE TABLE `mailbox_notification_preferences` (
11
- `mailbox_id` text NOT NULL,
12
- `user_id` text NOT NULL,
13
- `enabled` integer DEFAULT true NOT NULL,
14
- `updated_at` integer DEFAULT (unixepoch() * 1000) NOT NULL,
15
- PRIMARY KEY(`mailbox_id`, `user_id`),
16
- FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON UPDATE no action ON DELETE cascade,
17
- FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
18
- );
19
- --> statement-breakpoint
20
- CREATE INDEX `mailbox_notification_preferences_user_idx` ON `mailbox_notification_preferences` (`user_id`);--> statement-breakpoint
21
- CREATE TABLE `reported_messages` (
22
- `id` text PRIMARY KEY NOT NULL,
23
- `mailbox_id` text NOT NULL,
24
- `email_id` text NOT NULL,
25
- `reporter_user_id` text,
26
- `sender_address` text NOT NULL,
27
- `sender_domain` text NOT NULL,
28
- `subject` text NOT NULL,
29
- `received_at` integer NOT NULL,
30
- `snapshot_json` text NOT NULL,
31
- `status` text DEFAULT 'open' NOT NULL,
32
- `resolved_by_user_id` text,
33
- `resolved_at` integer,
34
- `created_at` integer NOT NULL,
35
- FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON UPDATE no action ON DELETE cascade,
36
- FOREIGN KEY (`reporter_user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null,
37
- FOREIGN KEY (`resolved_by_user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
38
- );
39
- --> statement-breakpoint
40
- CREATE UNIQUE INDEX `reported_messages_email_unique` ON `reported_messages` (`mailbox_id`,`email_id`);--> statement-breakpoint
41
- CREATE INDEX `reported_messages_status_idx` ON `reported_messages` (`status`,`created_at`);--> statement-breakpoint
42
- CREATE TABLE `sender_reports` (
43
- `mailbox_id` text NOT NULL,
44
- `email_id` text NOT NULL,
45
- `address` text NOT NULL,
46
- `domain` text NOT NULL,
47
- `label` text NOT NULL,
48
- `created_at` integer NOT NULL,
49
- PRIMARY KEY(`mailbox_id`, `email_id`),
50
- FOREIGN KEY (`mailbox_id`) REFERENCES `mailboxes`(`id`) ON UPDATE no action ON DELETE cascade
51
- );
52
- --> statement-breakpoint
53
- CREATE INDEX `sender_reports_domain_idx` ON `sender_reports` (`domain`,`address`);
@@ -1,156 +0,0 @@
1
- /**
2
- * Deterministic per-mailbox filter rules ("Filter messages like this").
3
- * Pure so the worker (ingestion, "apply to existing") and the browser (rule
4
- * preview) share one definition of a match.
5
- */
6
-
7
- export const MAX_MAIL_RULES = 100;
8
-
9
- export type MailRuleConditions = {
10
- /** An address (exact) or a domain / `@domain` (domain and its subdomains). */
11
- from?: string;
12
- /** Matches any To or Cc recipient, with the same address/domain semantics. */
13
- to?: string;
14
- /** Case-insensitive substring of the subject. */
15
- subjectContains?: string;
16
- /** RFC 2919 list identifier, compared without angle brackets. */
17
- listId?: string;
18
- hasAttachment?: boolean;
19
- };
20
-
21
- export type MailRuleActions = {
22
- /** Custom folder to file matching conversations in. */
23
- folderId?: string;
24
- archive?: boolean;
25
- spam?: boolean;
26
- markRead?: boolean;
27
- /** Overrides the AI spam verdict (blocked senders still go to Spam). */
28
- neverSpam?: boolean;
29
- };
30
-
31
- export type MailRule = {
32
- id: string;
33
- name: string;
34
- enabled: boolean;
35
- conditions: MailRuleConditions;
36
- actions: MailRuleActions;
37
- };
38
-
39
- /** The facts a rule can look at, normalized by `ruleSubject`. */
40
- export type RuleSubject = {
41
- from: string;
42
- recipients: string[];
43
- subject: string;
44
- listId: string | null;
45
- hasAttachment: boolean;
46
- };
47
-
48
- export type RuleDestination =
49
- | { kind: "folder"; folderId: string }
50
- | { kind: "archive" }
51
- | { kind: "spam" };
52
-
53
- export type RuleOutcome = {
54
- ruleIds: string[];
55
- /** Set by the first matching rule that names one. */
56
- destination: RuleDestination | null;
57
- markRead: boolean;
58
- neverSpam: boolean;
59
- };
60
-
61
- function lower(value: string | null | undefined) {
62
- return (value ?? "").trim().toLocaleLowerCase();
63
- }
64
-
65
- export function normalizeListId(value: string | null | undefined) {
66
- return lower(value).replace(/^.*<([^>]*)>.*$/u, "$1").trim() || null;
67
- }
68
-
69
- export function ruleSubject(input: {
70
- from: string | null | undefined;
71
- recipients: Array<string | null | undefined>;
72
- subject: string | null | undefined;
73
- listId: string | null | undefined;
74
- hasAttachment: boolean;
75
- }): RuleSubject {
76
- return {
77
- from: lower(input.from),
78
- recipients: input.recipients.map(lower).filter(Boolean),
79
- subject: lower(input.subject),
80
- listId: normalizeListId(input.listId),
81
- hasAttachment: input.hasAttachment,
82
- };
83
- }
84
-
85
- /** `alex@x.com` matches exactly; `x.com` or `@x.com` matches x.com and *.x.com. */
86
- export function addressMatches(pattern: string, address: string) {
87
- const value = lower(pattern);
88
- if (!value || !address) return false;
89
- if (value.includes("@") && !value.startsWith("@")) return address === value;
90
- const domain = value.replace(/^@/u, "");
91
- const at = address.lastIndexOf("@");
92
- const host = at >= 0 ? address.slice(at + 1) : address;
93
- return host === domain || host.endsWith(`.${domain}`);
94
- }
95
-
96
- export function hasConditions(conditions: MailRuleConditions) {
97
- return Boolean(
98
- lower(conditions.from)
99
- || lower(conditions.to)
100
- || lower(conditions.subjectContains)
101
- || lower(conditions.listId)
102
- || conditions.hasAttachment,
103
- );
104
- }
105
-
106
- export function hasActions(actions: MailRuleActions) {
107
- return Boolean(actions.folderId || actions.archive || actions.spam || actions.markRead || actions.neverSpam);
108
- }
109
-
110
- /** Every present condition must hold; a rule without conditions never matches. */
111
- export function ruleMatches(conditions: MailRuleConditions, subject: RuleSubject) {
112
- if (!hasConditions(conditions)) return false;
113
- if (lower(conditions.from) && !addressMatches(conditions.from!, subject.from)) return false;
114
- if (lower(conditions.to) && !subject.recipients.some((address) => addressMatches(conditions.to!, address))) {
115
- return false;
116
- }
117
- const needle = lower(conditions.subjectContains);
118
- if (needle && !subject.subject.includes(needle)) return false;
119
- const listId = normalizeListId(conditions.listId);
120
- if (listId && subject.listId !== listId) return false;
121
- if (conditions.hasAttachment && !subject.hasAttachment) return false;
122
- return true;
123
- }
124
-
125
- export function ruleDestination(actions: MailRuleActions): RuleDestination | null {
126
- if (actions.spam) return { kind: "spam" };
127
- if (actions.archive) return { kind: "archive" };
128
- if (actions.folderId) return { kind: "folder", folderId: actions.folderId };
129
- return null;
130
- }
131
-
132
- /** Rules run in order; all matches contribute flags, the first destination wins. */
133
- export function evaluateRules(rules: readonly MailRule[], subject: RuleSubject): RuleOutcome {
134
- const outcome: RuleOutcome = { ruleIds: [], destination: null, markRead: false, neverSpam: false };
135
- for (const rule of rules) {
136
- if (!rule.enabled || !ruleMatches(rule.conditions, subject)) continue;
137
- outcome.ruleIds.push(rule.id);
138
- outcome.destination ??= ruleDestination(rule.actions);
139
- outcome.markRead ||= Boolean(rule.actions.markRead);
140
- outcome.neverSpam ||= Boolean(rule.actions.neverSpam);
141
- }
142
- // "Never spam" from any matching rule overrides a later rule's Spam action.
143
- if (outcome.neverSpam && outcome.destination?.kind === "spam") outcome.destination = null;
144
- return outcome;
145
- }
146
-
147
- /** Short human description, e.g. "From @hireline.example · Subject contains "alert"". */
148
- export function describeConditions(conditions: MailRuleConditions) {
149
- const parts: string[] = [];
150
- if (lower(conditions.from)) parts.push(`From ${conditions.from!.trim()}`);
151
- if (lower(conditions.to)) parts.push(`To ${conditions.to!.trim()}`);
152
- if (lower(conditions.subjectContains)) parts.push(`Subject contains “${conditions.subjectContains!.trim()}”`);
153
- if (lower(conditions.listId)) parts.push(`List ${normalizeListId(conditions.listId)}`);
154
- if (conditions.hasAttachment) parts.push("Has attachment");
155
- return parts.join(" · ");
156
- }