@open-workspace/email 0.3.0 → 0.4.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 (221) hide show
  1. package/README.md +22 -22
  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_email.sql → 0000_dry_moon_knight.sql} +26 -20
  11. package/migrations/meta/0000_snapshot.json +125 -109
  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 +77 -28
  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 +63 -40
  127. package/worker/jmap/eventsource.ts +84 -16
  128. package/worker/jmap/methods.ts +1630 -524
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +140 -56
  131. package/worker/jmap/routes.ts +366 -105
  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 +88 -22
  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 +271 -173
  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 +870 -541
  184. package/worker/mail/safety-routes.ts +328 -200
  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 +126 -93
  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 +595 -225
  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 +1734 -721
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +8 -6
  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 -142
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/shared/mail-rules.ts +0 -156
  218. package/worker/admin/report-routes.ts +0 -164
  219. package/worker/mail/reported-messages.ts +0 -68
  220. package/worker/mailbox/migrations.ts +0 -10
  221. package/worker/mailbox/rules.ts +0 -110
@@ -1,30 +1,267 @@
1
- import { and, eq } from "drizzle-orm";
2
- import type { Database } from "@open-workspace/core/worker/db/client.ts";
3
- import { domains, mailboxAccess, mailboxes } from "@open-workspace/core/worker/db/schema.ts";
4
- import { mailboxAddressSql, mailboxKind } from "@open-workspace/core/worker/db/mailboxes.ts";
1
+ import {
2
+ createDb,
3
+ mailboxAccess,
4
+ mailboxes,
5
+ sessions,
6
+ mailboxAddressSql,
7
+ mailboxKind,
8
+ mailboxKindOrderSql,
9
+ timed,
10
+ } from "@open-workspace/core/module";
11
+ import type {
12
+ SessionCompanion,
13
+ AppEnv,
14
+ Database,
15
+ } from "@open-workspace/core/module";
16
+ import { and, desc, eq, gt, sql } from "drizzle-orm";
17
+ import type { Context } from "hono";
18
+ import { z } from "zod";
5
19
 
6
- export async function getMailboxAccess(
7
- db: Database,
8
- userId: string,
9
- mailboxId: string,
10
- ) {
11
- const [access] = await db
12
- .select({
13
- id: mailboxes.id,
14
- address: mailboxAddressSql,
15
- displayName: mailboxes.displayName,
16
- ownerUserId: mailboxes.ownerUserId,
17
- canSend: mailboxAccess.canSend,
18
- })
20
+ import { mailboxCounts, mailboxReadCounts } from "../db/schema";
21
+
22
+ const accessColumns = {
23
+ id: mailboxes.id,
24
+ address: mailboxAddressSql,
25
+ displayName: mailboxes.displayName,
26
+ ownerUserId: mailboxes.ownerUserId,
27
+ canSend: mailboxAccess.canSend,
28
+ };
29
+
30
+ /**
31
+ * With the inbox counts each mailbox's Durable Object keeps in D1 (joined by
32
+ * `withInboxCounts`); a mailbox without a row has had no mail yet.
33
+ */
34
+ const listColumns = {
35
+ ...accessColumns,
36
+ isPrimary: mailboxes.isPrimary,
37
+ unreadCount:
38
+ sql<number>`max(0, coalesce(${mailboxCounts.incomingCount}, 0) - coalesce(${mailboxReadCounts.readCount}, 0))`.as(
39
+ "unread_count"
40
+ ),
41
+ version: sql<number>`coalesce(${mailboxCounts.version}, 0)`.as(
42
+ "counts_version"
43
+ ),
44
+ };
45
+
46
+ const inboxCountsJoin = eq(mailboxCounts.mailboxId, mailboxAccess.mailboxId);
47
+
48
+ const readCountsJoin = and(
49
+ eq(mailboxReadCounts.mailboxId, mailboxAccess.mailboxId),
50
+ eq(mailboxReadCounts.userId, mailboxAccess.userId)
51
+ );
52
+
53
+ const listOrder = [
54
+ mailboxKindOrderSql,
55
+ desc(mailboxes.isPrimary),
56
+ mailboxes.displayName,
57
+ ] as const;
58
+
59
+ const accessRowSchema = z.object({
60
+ id: z.string(),
61
+ address: z.string(),
62
+ displayName: z.string(),
63
+ ownerUserId: z.string().nullable(),
64
+ canSend: z.boolean(),
65
+ });
66
+
67
+ type AccessRow = z.infer<typeof accessRowSchema>;
68
+
69
+ export const mailboxListRowSchema = accessRowSchema.extend({
70
+ isPrimary: z.boolean(),
71
+ unreadCount: z.number(),
72
+ version: z.number(),
73
+ });
74
+
75
+ export type MailboxListRow = z.infer<typeof mailboxListRowSchema>;
76
+
77
+ function withKind(access: AccessRow | undefined) {
78
+ return access ? { ...access, kind: mailboxKind(access.ownerUserId) } : null;
79
+ }
80
+
81
+ function accessQuery(db: Database, userId: string, mailboxId: string) {
82
+ return db
83
+ .select(accessColumns)
19
84
  .from(mailboxAccess)
20
85
  .innerJoin(mailboxes, eq(mailboxAccess.mailboxId, mailboxes.id))
21
- .innerJoin(domains, eq(mailboxes.domainId, domains.id))
22
86
  .where(
23
87
  and(
24
88
  eq(mailboxAccess.userId, userId),
25
- eq(mailboxAccess.mailboxId, mailboxId),
26
- ),
89
+ eq(mailboxAccess.mailboxId, mailboxId)
90
+ )
27
91
  )
28
92
  .limit(1);
29
- return access ? { ...access, kind: mailboxKind(access.ownerUserId) } : null;
93
+ }
94
+
95
+ function listQuery(db: Database, userId: string) {
96
+ return db
97
+ .select(listColumns)
98
+ .from(mailboxAccess)
99
+ .innerJoin(mailboxes, eq(mailboxAccess.mailboxId, mailboxes.id))
100
+ .leftJoin(mailboxCounts, inboxCountsJoin)
101
+ .leftJoin(mailboxReadCounts, readCountsJoin)
102
+ .where(eq(mailboxAccess.userId, userId))
103
+ .orderBy(...listOrder);
104
+ }
105
+
106
+ function sessionScope(tokenHash: string, now: Date) {
107
+ return and(
108
+ eq(sessions.userId, mailboxAccess.userId),
109
+ eq(sessions.tokenHash, tokenHash),
110
+ gt(sessions.expiresAt, now)
111
+ );
112
+ }
113
+
114
+ /**
115
+ * The mailbox list (with inbox counts) of the session with `tokenHash`, for
116
+ * a session lookup's batch; rows are meaningful only if core accepts it.
117
+ */
118
+ export function sessionMailboxListQuery(
119
+ db: Database,
120
+ tokenHash: string,
121
+ now: Date
122
+ ) {
123
+ return db
124
+ .select(listColumns)
125
+ .from(mailboxAccess)
126
+ .innerJoin(sessions, sessionScope(tokenHash, now))
127
+ .innerJoin(mailboxes, eq(mailboxAccess.mailboxId, mailboxes.id))
128
+ .leftJoin(mailboxCounts, inboxCountsJoin)
129
+ .leftJoin(mailboxReadCounts, readCountsJoin)
130
+ .orderBy(...listOrder);
131
+ }
132
+
133
+ export async function getMailboxAccess(
134
+ db: Database,
135
+ userId: string,
136
+ mailboxId: string
137
+ ) {
138
+ const [access] = await accessQuery(db, userId, mailboxId);
139
+
140
+ return withKind(access);
141
+ }
142
+
143
+ /** Mailboxes a person can open, personal first, then primary, then by name. */
144
+ export function listAccessibleMailboxes(
145
+ db: Database,
146
+ userId: string
147
+ ): Promise<MailboxListRow[]> {
148
+ return listQuery(db, userId).all();
149
+ }
150
+
151
+ type MailboxTarget = { kind: "list" } | { kind: "mailbox"; mailboxId: string };
152
+
153
+ /**
154
+ * The mailbox a mail API request is about, read from the URL the way the
155
+ * routes read it: `/mail/mailboxes` (the list), `/mail/mailboxes/:id/...`, or
156
+ * a `mailboxId` query parameter.
157
+ */
158
+ function mailboxTarget(c: Context<AppEnv>): MailboxTarget | null {
159
+ const match = /^(?:\/api)?\/mail\/mailboxes(?:\/([^/]+))?\/?/u.exec(
160
+ c.req.path
161
+ );
162
+
163
+ if (match && !match[1]) {
164
+ return c.req.method === "GET" && /\/mailboxes\/?$/u.test(c.req.path)
165
+ ? { kind: "list" }
166
+ : null;
167
+ }
168
+
169
+ const raw = match?.[1] ?? c.req.query("mailboxId");
170
+
171
+ if (!raw) return null;
172
+
173
+ try {
174
+ return {
175
+ kind: "mailbox",
176
+ mailboxId: match?.[1] ? decodeURIComponent(raw) : raw,
177
+ };
178
+ } catch {
179
+ return null;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Runs the request's mailbox authorization in the session lookup's D1 batch.
185
+ * The statements are scoped to the session's own token (and expiry), and
186
+ * their rows are used only after core accepted that same session, so the
187
+ * outcome matches a separate query made after authentication.
188
+ */
189
+ export const mailAccessCompanion: SessionCompanion = ({
190
+ c,
191
+ db,
192
+ tokenHash,
193
+ now,
194
+ }) => {
195
+ const target = mailboxTarget(c);
196
+
197
+ if (!target) return null;
198
+
199
+ if (target.kind === "list") {
200
+ return sessionMailboxListQuery(db, tokenHash, now);
201
+ }
202
+
203
+ return db
204
+ .select(accessColumns)
205
+ .from(mailboxAccess)
206
+ .innerJoin(sessions, sessionScope(tokenHash, now))
207
+ .innerJoin(mailboxes, eq(mailboxAccess.mailboxId, mailboxes.id))
208
+ .where(eq(mailboxAccess.mailboxId, target.mailboxId))
209
+ .limit(1);
210
+ };
211
+
212
+ /**
213
+ * The rows the session batch ran for this request (mailAccessCompanion),
214
+ * parsed with `schema`: core hands them over untyped.
215
+ */
216
+ function preloadedRows<Row>(
217
+ c: Context<AppEnv>,
218
+ matches: (target: MailboxTarget) => boolean,
219
+ schema: z.ZodType<Row>
220
+ ) {
221
+ if (c.get("authKind") !== "session") return undefined;
222
+ const target = mailboxTarget(c);
223
+
224
+ if (!target || !matches(target)) return undefined;
225
+ const rows = z.array(schema).safeParse(c.get("authCompanion"));
226
+
227
+ return rows.success ? rows.data : undefined;
228
+ }
229
+
230
+ /** The signed-in person's access to a mailbox, or null; "send" also needs send rights. */
231
+ export async function accessibleMailbox(
232
+ c: Context<AppEnv>,
233
+ mailboxId: string,
234
+ permission: "read" | "send"
235
+ ) {
236
+ const preloaded = preloadedRows(
237
+ c,
238
+ (target) => target.kind === "mailbox" && target.mailboxId === mailboxId,
239
+ accessRowSchema
240
+ );
241
+
242
+ const access = preloaded
243
+ ? withKind(preloaded[0])
244
+ : await timed(c, "d1", "access", () =>
245
+ getMailboxAccess(createDb(c.env.DB), c.get("user").id, mailboxId)
246
+ );
247
+
248
+ if (!access || (permission === "send" && !access.canSend)) return null;
249
+
250
+ return access;
251
+ }
252
+
253
+ /** The signed-in person's mailboxes, from the session batch when it carried them. */
254
+ export async function accessibleMailboxes(c: Context<AppEnv>) {
255
+ const preloaded = preloadedRows(
256
+ c,
257
+ (target) => target.kind === "list",
258
+ mailboxListRowSchema
259
+ );
260
+
261
+ return (
262
+ preloaded ??
263
+ (await timed(c, "d1", "mailboxes", () =>
264
+ listAccessibleMailboxes(createDb(c.env.DB), c.get("user").id)
265
+ ))
266
+ );
30
267
  }
@@ -1,23 +1,30 @@
1
+ import type { AiObjectRunner } from "@open-workspace/core/module";
1
2
  import { z } from "zod";
2
- import type { EmailAiClassification, MailboxAiConfiguration } from "../mailbox/model";
3
- import type { AiObjectRunner } from "@open-workspace/core/worker/ai/generate.ts";
3
+
4
+ import type {
5
+ EmailAiClassification,
6
+ MailboxAiConfiguration,
7
+ } from "../mailbox/model";
4
8
  import type { ClassificationSignals } from "./classification-signals";
5
9
 
6
10
  export const MAILBOX_AI_MAX_ATTEMPTS = 2;
7
11
  export const MAILBOX_AI_TARGET_EML_TOKENS = 180_000;
8
12
  export const MAILBOX_AI_ESTIMATED_BYTES_PER_TOKEN = 3;
13
+
9
14
  export const MAILBOX_AI_MAX_EML_BYTES =
10
15
  MAILBOX_AI_TARGET_EML_TOKENS * MAILBOX_AI_ESTIMATED_BYTES_PER_TOKEN;
11
16
 
12
17
  const MAX_INFERENCE_MS = 60_000;
13
18
 
14
- const classificationSchema = z.object({
15
- spam: z.boolean(),
16
- spamConfidence: z.number().min(0).max(1),
17
- folderId: z.string().min(1).max(200).nullable(),
18
- folderConfidence: z.number().min(0).max(1),
19
- reason: z.string().trim().min(1).max(500),
20
- }).strict();
19
+ const classificationSchema = z
20
+ .object({
21
+ spam: z.boolean(),
22
+ spamConfidence: z.number().min(0).max(1),
23
+ folderId: z.string().min(1).max(200).nullable(),
24
+ folderConfidence: z.number().min(0).max(1),
25
+ reason: z.string().trim().min(1).max(500),
26
+ })
27
+ .strict();
21
28
 
22
29
  export class EmailAiClassificationError extends Error {
23
30
  constructor(message: string, options?: ErrorOptions) {
@@ -41,7 +48,7 @@ export function limitRawMimeForAi(rawMime: ArrayBuffer) {
41
48
 
42
49
  export async function classifyInboundEmail(input: {
43
50
  rawMime: ArrayBuffer;
44
- folders: Array<{ id: string; name: string }>;
51
+ folders: { id: string; name: string }[];
45
52
  configuration: MailboxAiConfiguration;
46
53
  /** Receiver-side facts the model cannot derive from the .eml itself. */
47
54
  signals?: ClassificationSignals | null;
@@ -52,6 +59,7 @@ export async function classifyInboundEmail(input: {
52
59
  }): Promise<EmailAiClassification> {
53
60
  const trustedFolderIds = new Set(input.folders.map((folder) => folder.id));
54
61
  const threshold = input.configuration.confidenceThreshold / 100;
62
+
55
63
  const system = [
56
64
  "Classify an inbound email for a mailbox application.",
57
65
  "The first input is the original raw RFC 822 message in .eml format, except that the tail may be omitted to keep its estimated input below the 200,000-token processing limit. Images are not extracted or sent as separate image inputs.",
@@ -65,7 +73,7 @@ export async function classifyInboundEmail(input: {
65
73
  "A domain mismatch is a risk signal, not proof by itself: legitimate services may use separate sending or tracking domains. Use the combined identity, link, attachment metadata, and message context, but set spam true whenever the evidence is clearly deceptive or malicious.",
66
74
  "Treat mail clearly resulting from an action initiated by the recipient, such as an application, registration, purchase, support request, password reset, or account activity, as solicited transactional mail unless it is deceptive or malicious.",
67
75
  input.signals
68
- ? "receiverSignals were measured by this mail server, not taken from the message, and can be trusted: Cloudflare's SPF/DKIM/DMARC verdict and spam score, the sending IP's reverse DNS (ptr, forwardConfirmed, genericPtr), its network owner (asn, asOrganization, country), Spamhaus blocklist hits when configured, whether this is the first message from the sender, lookalike or display-name impersonation checks against this workspace, delivery: the address this mailbox received the message at (deliveredTo), whether the To or Cc headers name it (addressedToThisMailbox), the address the message was written for instead (addressedTo), whether mail to that address regularly reaches this mailbox (knownAddressee, typically the person's own forwarding), and the organization that forwarded it (forwardedVia); userFeedback: how often people in this mailbox reported this sender (or its domain) as spam or phishing, or marked it not spam, and workspaceFeedback: the same counts from other mailboxes in this organization, with how many mailboxes reported this exact address. Weigh them with the content: an account or security notice about an account other than deliveredTo that was forwarded here, unless knownAddressee is true, is strong phishing evidence even with passing DKIM and DMARC, unless knownAddressee is true or forwardedVia is the addressed account's own email provider (the person forwarding their own account); a blocklist hit, a lookalike domain, or a display name copied from a colleague on an external address are strong phishing evidence; previous spam or phishing reports about the same sender, here or elsewhere in the organization, are strong spam evidence, and not-spam feedback is evidence against, with this mailbox's own feedback outweighing the organization's; reports about other addresses at a large shared domain are weak evidence; a first-time sender or missing reverse DNS alone is not."
76
+ ? "receiverSignals were measured by this mail server, not taken from the message, and can be trusted: Cloudflare's SPF/DKIM/DMARC verdict and spam score, the sending IP's reverse DNS (ptr, forwardConfirmed, genericPtr), its network owner (asn, asOrganization, country), Spamhaus blocklist hits when configured, whether this is the first message from the sender, lookalike or display-name impersonation checks against this workspace, delivery: the address this mailbox received the message at (deliveredTo), whether the To or Cc headers name it (addressedToThisMailbox), the address the message was written for instead (addressedTo), whether mail to that address regularly reaches this mailbox (knownAddressee, typically the person's own forwarding), and the organization that forwarded it (forwardedVia); userFeedback: how often people in this mailbox reported this sender (or its domain) as spam, or marked it not spam, and workspaceFeedback: the same counts from other mailboxes in this organization, with how many mailboxes reported this exact address. Weigh them with the content: an account or security notice about an account other than deliveredTo that was forwarded here, unless knownAddressee is true, is strong phishing evidence even with passing DKIM and DMARC, unless knownAddressee is true or forwardedVia is the addressed account's own email provider (the person forwarding their own account); a blocklist hit, a lookalike domain, or a display name copied from a colleague on an external address are strong phishing evidence; previous spam reports about the same sender, here or elsewhere in the organization, are strong spam evidence, and not-spam feedback is evidence against, with this mailbox's own feedback outweighing the organization's; reports about other addresses at a large shared domain are weak evidence; a first-time sender or missing reverse DNS alone is not."
69
77
  : "",
70
78
  "Choose folderId only from the supplied customFolders. Use null when none is a good semantic match.",
71
79
  "Do not invent folders and do not choose a weak match merely to avoid null.",
@@ -74,7 +82,10 @@ export async function classifyInboundEmail(input: {
74
82
  input.configuration.instructions
75
83
  ? `Trusted mailbox classification rules:\n${input.configuration.instructions}`
76
84
  : "",
77
- ].filter(Boolean).join("\n");
85
+ ]
86
+ .filter(Boolean)
87
+ .join("\n");
88
+
78
89
  const limited = limitRawMimeForAi(input.rawMime);
79
90
  const eml = new TextDecoder().decode(limited.rawMime);
80
91
 
@@ -87,19 +98,24 @@ export async function classifyInboundEmail(input: {
87
98
  JSON.stringify({
88
99
  customFolders: input.folders,
89
100
  rawMessageTruncated: limited.truncated,
90
- ...(input.signals ? { receiverSignals: input.signals } : {}),
101
+ // JSON leaves the key out when there are no signals.
102
+ receiverSignals: input.signals ?? undefined,
91
103
  }),
92
104
  ],
93
105
  schema: classificationSchema,
94
106
  signal: AbortSignal.timeout(MAX_INFERENCE_MS),
95
107
  });
108
+
96
109
  const spam = parsed.spam && parsed.spamConfidence >= threshold;
97
- const folderId = !spam
98
- && parsed.folderId
99
- && parsed.folderConfidence >= threshold
100
- && trustedFolderIds.has(parsed.folderId)
101
- ? parsed.folderId
102
- : null;
110
+
111
+ const folderId =
112
+ !spam &&
113
+ parsed.folderId &&
114
+ parsed.folderConfidence >= threshold &&
115
+ trustedFolderIds.has(parsed.folderId)
116
+ ? parsed.folderId
117
+ : null;
118
+
103
119
  return {
104
120
  source: "ai",
105
121
  model: input.model,
@@ -113,7 +129,7 @@ export async function classifyInboundEmail(input: {
113
129
  } catch (error) {
114
130
  throw new EmailAiClassificationError(
115
131
  "The AI model could not classify the incoming message",
116
- { cause: error },
132
+ { cause: error }
117
133
  );
118
134
  }
119
135
  }
@@ -1,9 +1,11 @@
1
+ import type { AiObjectRunner } from "@open-workspace/core/module";
1
2
  import { z } from "zod";
2
- import type { AiObjectRunner } from "@open-workspace/core/worker/ai/generate.ts";
3
3
 
4
- const translationSchema = z.object({
5
- translations: z.array(z.string()),
6
- }).strict();
4
+ const translationSchema = z
5
+ .object({
6
+ translations: z.array(z.string()),
7
+ })
8
+ .strict();
7
9
 
8
10
  export async function translateEmailSegments(input: {
9
11
  segments: string[];
@@ -22,10 +24,15 @@ export async function translateEmailSegments(input: {
22
24
  schema: translationSchema,
23
25
  signal: AbortSignal.timeout(60_000),
24
26
  });
27
+
25
28
  const translations = result.translations.map((value) => value.trim());
26
- if (translations.length !== input.segments.length
27
- || translations.some((value) => !value)) {
29
+
30
+ if (
31
+ translations.length !== input.segments.length ||
32
+ translations.some((value) => !value)
33
+ ) {
28
34
  throw new Error("Translation segments are incomplete");
29
35
  }
36
+
30
37
  return translations;
31
38
  }