@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.
- package/README.md +23 -20
- package/alchemy/index.ts +273 -0
- package/drizzle/mailbox/0000_puzzling_dracula.sql +149 -0
- package/drizzle/mailbox/0001_mute_jack_flag.sql +12 -0
- package/drizzle/mailbox/meta/0000_snapshot.json +1002 -0
- package/drizzle/mailbox/meta/0001_snapshot.json +1002 -0
- package/drizzle/mailbox/meta/_journal.json +20 -0
- package/drizzle/mailbox/migrations.js +12 -0
- package/index.ts +3 -1
- package/migrations/0000_dry_moon_knight.sql +77 -0
- package/migrations/meta/0000_snapshot.json +248 -106
- package/migrations/meta/_journal.json +2 -2
- package/package.json +74 -68
- package/shared/attachment-preview.ts +37 -27
- package/shared/folder-order.ts +106 -0
- package/shared/mail-authentication.ts +8 -3
- package/shared/mail-feedback.ts +18 -25
- package/shared/mail-headers.ts +114 -39
- package/shared/mail-import.ts +38 -0
- package/shared/mail-path.ts +42 -0
- package/shared/mail-received.ts +174 -31
- package/shared/mail-remote.ts +59 -2
- package/shared/mail-sender-intel.ts +22 -4
- package/shared/mail.ts +78 -26
- package/shared/module.ts +33 -0
- package/shared/office-preview.ts +14 -2
- package/shared/pdfjs-assets.ts +35 -0
- package/shared/permissions.ts +73 -0
- package/shared/webhooks.ts +41 -0
- package/src/admin/blocked-senders.tsx +189 -0
- package/src/client.tsx +97 -0
- package/src/lib/mail-api.ts +9 -0
- package/src/mail/attachment-preview-dialog.tsx +161 -0
- package/src/mail/blocked-senders.tsx +138 -0
- package/src/mail/compose-window-chrome.tsx +194 -0
- package/src/mail/compose-window.tsx +486 -0
- package/src/mail/composer-asset-bookmarks.ts +409 -0
- package/src/mail/composer-asset.tsx +229 -0
- package/src/mail/composer-attachment-list.tsx +138 -0
- package/src/mail/composer-editor-document.ts +65 -0
- package/src/mail/composer-editor.tsx +284 -0
- package/src/mail/composer-linked-attachment-text.ts +12 -0
- package/src/mail/composer-recipient-fields.tsx +165 -0
- package/src/mail/composer-recipients.ts +208 -0
- package/src/mail/composer-session.ts +562 -0
- package/src/mail/composer-toolbar.tsx +303 -0
- package/src/mail/composer-upload-client.ts +105 -0
- package/src/mail/composer-upload-progress.ts +53 -0
- package/src/mail/conversation-list.tsx +550 -0
- package/src/mail/conversation-loading-skeleton.tsx +119 -0
- package/src/mail/conversation-message.tsx +346 -0
- package/src/mail/conversation-reply.tsx +470 -0
- package/src/mail/conversation-selection-toolbar.tsx +322 -0
- package/src/mail/conversation-view.tsx +437 -0
- package/src/mail/delivery-indicator.tsx +272 -0
- package/src/mail/email-html-body.tsx +203 -0
- package/src/mail/folder-glyph.tsx +46 -0
- package/src/mail/folder-manager.tsx +532 -0
- package/src/mail/format-bytes.ts +7 -0
- package/src/mail/mail-app-bar.tsx +253 -0
- package/src/mail/mail-background.tsx +12 -0
- package/src/mail/mail-dock.tsx +137 -0
- package/src/mail/mail-folders.ts +44 -0
- package/src/mail/mail-layout.css +236 -0
- package/src/mail/mail-location.ts +73 -0
- package/src/mail/mail-mailbox-sheet.tsx +275 -0
- package/src/mail/mail-nav-rail.tsx +129 -0
- package/src/mail/mail-nav.tsx +324 -0
- package/src/mail/mail-prefetch.ts +59 -0
- package/src/mail/mail-primitives.tsx +66 -0
- package/src/mail/mail-queries.ts +209 -0
- package/src/mail/mail-query-cache.ts +486 -0
- package/src/mail/mail-seed.ts +47 -0
- package/src/mail/mail-shell.tsx +126 -0
- package/src/mail/mailbox-ai-settings.tsx +185 -0
- package/src/mail/mailbox-realtime.tsx +251 -0
- package/src/mail/mailbox-route.tsx +15 -0
- package/src/mail/message-actions.tsx +353 -0
- package/src/mail/message-attachments.tsx +200 -0
- package/src/mail/message-format.ts +75 -0
- package/src/mail/message-header.tsx +260 -0
- package/src/mail/message-translation.tsx +225 -0
- package/src/mail/original-message-sheet.tsx +619 -0
- package/src/mail/original-message.ts +191 -0
- package/src/mail/outbound-notification.ts +53 -0
- package/src/mail/pane-splitter.tsx +117 -0
- package/src/mail/pdf-preview-toolbar.tsx +152 -0
- package/src/mail/pdf-preview.css +44 -0
- package/src/mail/pdf-preview.tsx +156 -0
- package/src/mail/pdf-translation-layout.ts +95 -0
- package/src/mail/print-message.ts +92 -0
- package/src/mail/reader-pane.tsx +535 -0
- package/src/mail/recipient-combobox.tsx +335 -0
- package/src/mail/recipient-field-row.tsx +34 -0
- package/src/mail/reply-to-warning.tsx +50 -0
- package/src/mail/sanitize-email-html.ts +430 -0
- package/src/mail/sender-actions.tsx +149 -0
- package/src/mail/sender-authentication.tsx +485 -0
- package/src/mail/sender-dialogs.tsx +384 -0
- package/src/mail/sender-security.tsx +545 -0
- package/src/mail/toolbar-tooltip.tsx +29 -0
- package/src/mail/translation-html.ts +49 -0
- package/src/mail/translation-language.ts +21 -0
- package/src/mail/types.ts +53 -0
- package/src/mail/unread-document-indicator.tsx +60 -0
- package/src/mail/use-compose-submission.ts +208 -0
- package/src/mail/use-composer-attachment-preflight.ts +184 -0
- package/src/mail/use-composer-submission.ts +117 -0
- package/src/mail/use-conversation-selection.ts +186 -0
- package/src/mail/use-mail-controller.ts +427 -0
- package/src/mail/use-mail-data.ts +279 -0
- package/src/mail/use-mail-safety.ts +155 -0
- package/src/mail/use-mail-send.ts +142 -0
- package/src/mail/use-pdf-translation-overlay.ts +156 -0
- package/src/mail/use-pdf-translation.ts +100 -0
- package/src/mail/use-pdf-viewer.ts +215 -0
- package/src/mail/use-reply-submission.ts +114 -0
- package/src/mail/use-sanitized-email-html.ts +20 -0
- package/src/mail/use-visible-message-read.ts +138 -0
- package/src/pwa/push-subscription.ts +151 -0
- package/src/settings/mail-apps-page.tsx +235 -0
- package/src/settings/notifications-page.tsx +291 -0
- package/worker/admin/blocked-sender-routes.ts +166 -0
- package/worker/admin/schemas.ts +11 -0
- package/worker/bindings.d.ts +14 -10
- package/worker/db/schema.ts +90 -34
- package/worker/jmap/eventsource.ts +169 -0
- package/worker/jmap/methods.ts +1716 -361
- package/worker/jmap/push-types.ts +27 -0
- package/worker/jmap/push.ts +207 -0
- package/worker/jmap/routes.ts +448 -86
- package/worker/mail/access.ts +258 -21
- package/worker/mail/ai-classification.ts +36 -20
- package/worker/mail/ai-translation.ts +13 -6
- package/worker/mail/auth-headers.ts +395 -137
- package/worker/mail/bimi.ts +200 -73
- package/worker/mail/bootstrap.ts +79 -0
- package/worker/mail/capped-body.ts +36 -0
- package/worker/mail/classification-signals.ts +35 -25
- package/worker/mail/conversation-cursor.ts +30 -19
- package/worker/mail/delivery-events.ts +88 -62
- package/worker/mail/delivery-facts.ts +46 -10
- package/worker/mail/demo-routes.ts +34 -10
- package/worker/mail/doh.ts +62 -23
- package/worker/mail/downloads.ts +75 -40
- package/worker/mail/edge-cache.ts +155 -0
- package/worker/mail/header-metadata.ts +84 -52
- package/worker/mail/impersonation.ts +160 -38
- package/worker/mail/import-routes.ts +313 -0
- package/worker/mail/inbound-delivery.ts +19 -9
- package/worker/mail/inbound-threading.ts +18 -8
- package/worker/mail/inbound.ts +82 -40
- package/worker/mail/ip-intel.ts +110 -27
- package/worker/mail/isolate-cache.ts +35 -0
- package/worker/mail/link-domains.ts +29 -7
- package/worker/mail/mailbox-deletion.ts +10 -4
- package/worker/mail/mailbox-directory.ts +16 -6
- package/worker/mail/mailing-list.ts +94 -39
- package/worker/mail/message-security.ts +90 -15
- package/worker/mail/message-view.ts +18 -6
- package/worker/mail/office-conversion.ts +31 -9
- package/worker/mail/office-preview-container.ts +40 -13
- package/worker/mail/office-preview-queue.ts +76 -32
- package/worker/mail/org-domain.ts +8 -1
- package/worker/mail/outbound-content.ts +71 -26
- package/worker/mail/outbound-delivery.ts +31 -17
- package/worker/mail/outbound-service.ts +48 -30
- package/worker/mail/outbound-threading.ts +30 -17
- package/worker/mail/outbound.ts +97 -70
- package/worker/mail/outgoing-context.ts +25 -15
- package/worker/mail/participants.ts +44 -29
- package/worker/mail/push-notifications.ts +283 -171
- package/worker/mail/quote-parser.ts +21 -10
- package/worker/mail/r2-presigned-urls.ts +31 -25
- package/worker/mail/receive.ts +23 -11
- package/worker/mail/recipients.ts +6 -1
- package/worker/mail/remote-proxy.ts +187 -31
- package/worker/mail/remote-routes.ts +87 -0
- package/worker/mail/remote-token.ts +104 -0
- package/worker/mail/repeat.ts +19 -0
- package/worker/mail/reply-plan.ts +62 -33
- package/worker/mail/rfc.ts +32 -7
- package/worker/mail/routes.ts +871 -542
- package/worker/mail/safety-routes.ts +329 -202
- package/worker/mail/schemas.ts +84 -105
- package/worker/mail/search.ts +1 -0
- package/worker/mail/security-settings.ts +41 -9
- package/worker/mail/sender-intel.ts +206 -51
- package/worker/mail/spamhaus.ts +92 -45
- package/worker/mail/unsubscribe.ts +76 -18
- package/worker/mail/uploads.ts +153 -91
- package/worker/mail/webhook-source.ts +35 -12
- package/worker/mail/workspace-safety.ts +97 -38
- package/worker/mailbox/demo-html.ts +7 -7
- package/worker/mailbox/demo-seed.ts +10 -44
- package/worker/mailbox/demo.ts +597 -227
- package/worker/mailbox/email-index.ts +53 -0
- package/worker/mailbox/folder-model.ts +53 -17
- package/worker/mailbox/import-placement.ts +88 -0
- package/worker/mailbox/inbox-counts.ts +106 -0
- package/worker/mailbox/index.ts +1761 -737
- package/worker/mailbox/jmap-store.ts +139 -35
- package/worker/mailbox/model.ts +7 -14
- package/worker/mailbox/office-preview-jobs.ts +56 -25
- package/worker/mailbox/schema.ts +87 -66
- package/worker/mailbox/senders.ts +176 -70
- package/worker/mcp/mail-action-tools.ts +128 -87
- package/worker/mcp/mail-compose-tools.ts +133 -82
- package/worker/mcp/mail-query-tools.ts +120 -71
- package/worker/mcp/mail-safety-tools.ts +321 -248
- package/worker/mcp/schemas.ts +43 -0
- package/worker/mcp/tools.ts +13 -10
- package/worker/module.ts +43 -18
- package/worker/sql.d.ts +8 -0
- package/alchemy.ts +0 -126
- package/containers/office-preview/Dockerfile +0 -10
- package/migrations/0000_email.sql +0 -53
- package/shared/mail-rules.ts +0 -156
- package/worker/admin/report-routes.ts +0 -164
- package/worker/mail/reported-messages.ts +0 -68
- package/worker/mailbox/legacy-migrations.ts +0 -41
- package/worker/mailbox/migrations.ts +0 -10
- package/worker/mailbox/rules.ts +0 -110
package/worker/mail/access.ts
CHANGED
|
@@ -1,30 +1,267 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
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
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
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
|
-
|
|
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
|
-
|
|
3
|
-
import type {
|
|
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
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
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:
|
|
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
|
|
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
|
-
]
|
|
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
|
-
|
|
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
|
-
|
|
98
|
-
|
|
99
|
-
&&
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
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
|
|
5
|
-
|
|
6
|
-
|
|
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
|
-
|
|
27
|
-
|
|
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
|
}
|