@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
|
@@ -1,164 +0,0 @@
|
|
|
1
|
-
import { zValidator } from "@hono/zod-validator";
|
|
2
|
-
import { desc, eq, inArray } from "drizzle-orm";
|
|
3
|
-
import { alias } from "drizzle-orm/sqlite-core";
|
|
4
|
-
import { Hono } from "hono";
|
|
5
|
-
import { normalizeBlockPattern } from "../../shared/mail-feedback";
|
|
6
|
-
import { createDb } from "@open-workspace/core/worker/db/client.ts";
|
|
7
|
-
import { mailboxAddressSql } from "@open-workspace/core/worker/db/mailboxes.ts";
|
|
8
|
-
import { domains, mailboxes, users } from "@open-workspace/core/worker/db/schema.ts";
|
|
9
|
-
import { blockedSenders, reportedMessages } from "../db/schema";
|
|
10
|
-
import type { AppEnv } from "@open-workspace/core/worker/env.ts";
|
|
11
|
-
import { apiError } from "@open-workspace/core/worker/lib/http.ts";
|
|
12
|
-
import { requireAuth } from "@open-workspace/core/worker/auth/middleware.ts";
|
|
13
|
-
import { adminAccessGuard } from "@open-workspace/core/worker/admin/access-guard.ts";
|
|
14
|
-
import { mailboxStub } from "../mailbox";
|
|
15
|
-
import {
|
|
16
|
-
reportStatusSchema,
|
|
17
|
-
workspaceBlockQuerySchema,
|
|
18
|
-
workspaceBlockSchema,
|
|
19
|
-
} from "@open-workspace/core/worker/admin/schemas.ts";
|
|
20
|
-
|
|
21
|
-
const MAX_LISTED_REPORTS = 200;
|
|
22
|
-
const MAILBOX_FANOUT = 20;
|
|
23
|
-
|
|
24
|
-
/** Moves existing mail from a newly blocked pattern to Spam in every mailbox. */
|
|
25
|
-
async function moveBlockedMailToSpam(env: Env, pattern: string) {
|
|
26
|
-
const rows = await createDb(env.DB).select({ id: mailboxes.id }).from(mailboxes);
|
|
27
|
-
let conversations = 0;
|
|
28
|
-
let affectedMailboxes = 0;
|
|
29
|
-
let failedMailboxes = 0;
|
|
30
|
-
for (let index = 0; index < rows.length; index += MAILBOX_FANOUT) {
|
|
31
|
-
const results = await Promise.allSettled(
|
|
32
|
-
rows.slice(index, index + MAILBOX_FANOUT).map((row) => mailboxStub(env, row.id).moveSenderToSpam(pattern)),
|
|
33
|
-
);
|
|
34
|
-
for (const result of results) {
|
|
35
|
-
if (result.status === "rejected") {
|
|
36
|
-
failedMailboxes += 1;
|
|
37
|
-
console.error(`Could not move mail from ${pattern} to Spam`, result.reason);
|
|
38
|
-
} else if (result.value > 0) {
|
|
39
|
-
conversations += result.value;
|
|
40
|
-
affectedMailboxes += 1;
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
return { conversations, mailboxes: affectedMailboxes, failedMailboxes };
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* Administrators review phishing reports here. They can read a reported
|
|
49
|
-
* message only through its report, never browse the mailbox it came from.
|
|
50
|
-
*/
|
|
51
|
-
export const reportAdminRoutes = new Hono<AppEnv>()
|
|
52
|
-
.use("*", requireAuth, adminAccessGuard)
|
|
53
|
-
.get("/reported-messages", async (c) => {
|
|
54
|
-
const db = createDb(c.env.DB);
|
|
55
|
-
const reporter = alias(users, "reporter");
|
|
56
|
-
const [rows, blocks] = await Promise.all([
|
|
57
|
-
db
|
|
58
|
-
.select({
|
|
59
|
-
id: reportedMessages.id,
|
|
60
|
-
mailboxId: reportedMessages.mailboxId,
|
|
61
|
-
mailboxAddress: mailboxAddressSql,
|
|
62
|
-
emailId: reportedMessages.emailId,
|
|
63
|
-
reporterName: reporter.name,
|
|
64
|
-
senderAddress: reportedMessages.senderAddress,
|
|
65
|
-
senderDomain: reportedMessages.senderDomain,
|
|
66
|
-
subject: reportedMessages.subject,
|
|
67
|
-
receivedAt: reportedMessages.receivedAt,
|
|
68
|
-
snapshot: reportedMessages.snapshotJson,
|
|
69
|
-
status: reportedMessages.status,
|
|
70
|
-
resolvedAt: reportedMessages.resolvedAt,
|
|
71
|
-
createdAt: reportedMessages.createdAt,
|
|
72
|
-
})
|
|
73
|
-
.from(reportedMessages)
|
|
74
|
-
.innerJoin(mailboxes, eq(mailboxes.id, reportedMessages.mailboxId))
|
|
75
|
-
.innerJoin(domains, eq(domains.id, mailboxes.domainId))
|
|
76
|
-
.leftJoin(reporter, eq(reporter.id, reportedMessages.reporterUserId))
|
|
77
|
-
.orderBy(desc(reportedMessages.createdAt))
|
|
78
|
-
.limit(MAX_LISTED_REPORTS),
|
|
79
|
-
db.select().from(blockedSenders).orderBy(desc(blockedSenders.createdAt)),
|
|
80
|
-
]);
|
|
81
|
-
const blocked = new Set(blocks.map((block) => block.pattern));
|
|
82
|
-
return c.json({
|
|
83
|
-
ok: true as const,
|
|
84
|
-
reports: rows.map((row) => ({
|
|
85
|
-
...row,
|
|
86
|
-
senderBlocked: blocked.has(row.senderAddress),
|
|
87
|
-
domainBlocked: blocked.has(`@${row.senderDomain}`),
|
|
88
|
-
})),
|
|
89
|
-
blockedSenders: blocks.map((block) => ({
|
|
90
|
-
pattern: block.pattern,
|
|
91
|
-
reportId: block.reportId,
|
|
92
|
-
createdAt: block.createdAt,
|
|
93
|
-
})),
|
|
94
|
-
});
|
|
95
|
-
})
|
|
96
|
-
.get("/reported-messages/:id/original", async (c) => {
|
|
97
|
-
const [report] = await createDb(c.env.DB)
|
|
98
|
-
.select({ mailboxId: reportedMessages.mailboxId, emailId: reportedMessages.emailId })
|
|
99
|
-
.from(reportedMessages)
|
|
100
|
-
.where(eq(reportedMessages.id, c.req.param("id")))
|
|
101
|
-
.limit(1);
|
|
102
|
-
if (!report) return apiError(c, 404, "NOT_FOUND", "Report not found");
|
|
103
|
-
const email = await mailboxStub(c.env, report.mailboxId).getEmail(report.emailId);
|
|
104
|
-
const object = email?.rawMimeR2Key ? await c.env.MAIL_STORAGE.get(email.rawMimeR2Key) : null;
|
|
105
|
-
if (!object) return apiError(c, 404, "NOT_FOUND", "The original message is no longer stored");
|
|
106
|
-
// Plain text in a sandbox: the original is evidence, never rendered.
|
|
107
|
-
return new Response(object.body, {
|
|
108
|
-
headers: {
|
|
109
|
-
"content-type": "text/plain; charset=utf-8",
|
|
110
|
-
"content-disposition": "inline",
|
|
111
|
-
"content-security-policy": "sandbox; default-src 'none'",
|
|
112
|
-
"x-content-type-options": "nosniff",
|
|
113
|
-
"cache-control": "private, no-store",
|
|
114
|
-
},
|
|
115
|
-
});
|
|
116
|
-
})
|
|
117
|
-
.patch("/reported-messages/:id", zValidator("json", reportStatusSchema), async (c) => {
|
|
118
|
-
const { status } = c.req.valid("json");
|
|
119
|
-
const resolved = status !== "open";
|
|
120
|
-
const updated = await createDb(c.env.DB)
|
|
121
|
-
.update(reportedMessages)
|
|
122
|
-
.set({
|
|
123
|
-
status,
|
|
124
|
-
resolvedAt: resolved ? new Date() : null,
|
|
125
|
-
resolvedByUserId: resolved ? c.get("user").id : null,
|
|
126
|
-
})
|
|
127
|
-
.where(eq(reportedMessages.id, c.req.param("id")))
|
|
128
|
-
.returning({ id: reportedMessages.id });
|
|
129
|
-
if (!updated.length) return apiError(c, 404, "NOT_FOUND", "Report not found");
|
|
130
|
-
return c.json({ ok: true as const });
|
|
131
|
-
})
|
|
132
|
-
.post("/blocked-senders", zValidator("json", workspaceBlockSchema), async (c) => {
|
|
133
|
-
const input = c.req.valid("json");
|
|
134
|
-
const pattern = normalizeBlockPattern(input.pattern);
|
|
135
|
-
if (!pattern) return apiError(c, 400, "BAD_REQUEST", "Enter an email address or a domain");
|
|
136
|
-
const db = createDb(c.env.DB);
|
|
137
|
-
const own = await db.select({ name: domains.name }).from(domains);
|
|
138
|
-
const domain = pattern.slice(pattern.lastIndexOf("@") + 1);
|
|
139
|
-
if (own.some((row) => domain === row.name || domain.endsWith(`.${row.name}`) || row.name.endsWith(`.${domain}`))) {
|
|
140
|
-
return apiError(c, 400, "BAD_REQUEST", "Workspace domains cannot be blocked");
|
|
141
|
-
}
|
|
142
|
-
await db.insert(blockedSenders).values({
|
|
143
|
-
pattern,
|
|
144
|
-
reportId: input.reportId ?? null,
|
|
145
|
-
createdByUserId: c.get("user").id,
|
|
146
|
-
createdAt: new Date(),
|
|
147
|
-
}).onConflictDoNothing();
|
|
148
|
-
if (input.reportId) {
|
|
149
|
-
await db
|
|
150
|
-
.update(reportedMessages)
|
|
151
|
-
.set({ status: "resolved", resolvedAt: new Date(), resolvedByUserId: c.get("user").id })
|
|
152
|
-
.where(inArray(reportedMessages.id, [input.reportId]));
|
|
153
|
-
}
|
|
154
|
-
const moved = input.moveExisting ? await moveBlockedMailToSpam(c.env, pattern) : null;
|
|
155
|
-
return c.json({ ok: true as const, pattern, moved });
|
|
156
|
-
})
|
|
157
|
-
.delete("/blocked-senders", zValidator("query", workspaceBlockQuerySchema), async (c) => {
|
|
158
|
-
const pattern = normalizeBlockPattern(c.req.valid("query").pattern);
|
|
159
|
-
const deleted = pattern
|
|
160
|
-
? await createDb(c.env.DB).delete(blockedSenders).where(eq(blockedSenders.pattern, pattern)).returning()
|
|
161
|
-
: [];
|
|
162
|
-
if (!deleted.length) return apiError(c, 404, "NOT_FOUND", "Blocked sender not found");
|
|
163
|
-
return c.json({ ok: true as const });
|
|
164
|
-
});
|
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
import { and, eq } from "drizzle-orm";
|
|
2
|
-
import type { MessageSecurity } from "../../shared/mail-authentication";
|
|
3
|
-
import type { ReportSnapshot } from "../../shared/mail-feedback";
|
|
4
|
-
import type { SenderIntel } from "../../shared/mail-sender-intel";
|
|
5
|
-
import { createDb } from "@open-workspace/core/worker/db/client.ts";
|
|
6
|
-
import { reportedMessages } from "../db/schema";
|
|
7
|
-
import { createId } from "@open-workspace/core/worker/lib/ids.ts";
|
|
8
|
-
import type { Email } from "../mailbox/schema";
|
|
9
|
-
import { linkDomains } from "./link-domains";
|
|
10
|
-
|
|
11
|
-
export function reportSnapshot(input: {
|
|
12
|
-
email: Email;
|
|
13
|
-
security: MessageSecurity | null;
|
|
14
|
-
intel: SenderIntel | null;
|
|
15
|
-
bodyHtml: string | null;
|
|
16
|
-
}): ReportSnapshot {
|
|
17
|
-
const { email, security, intel } = input;
|
|
18
|
-
const ai = email.aiClassificationJson;
|
|
19
|
-
return {
|
|
20
|
-
fromName: email.fromJson[0]?.name ?? null,
|
|
21
|
-
replyTo: email.replyToJson.map((item) => item.address),
|
|
22
|
-
to: [...email.toJson, ...email.ccJson].map((item) => item.address).slice(0, 20),
|
|
23
|
-
verdict: security?.verdict ?? "unavailable",
|
|
24
|
-
verdictReason: security?.verdictReason ?? "missing_results",
|
|
25
|
-
warnings: security?.warnings.map((warning) => warning.kind) ?? [],
|
|
26
|
-
spamScore: email.authenticationResultsJson?.source === "headers"
|
|
27
|
-
? email.authenticationResultsJson.spamScore
|
|
28
|
-
: null,
|
|
29
|
-
ip: intel?.ip ?? null,
|
|
30
|
-
network: intel?.network.asn ? `AS${intel.network.asn} ${intel.network.asName ?? ""}`.trim() : null,
|
|
31
|
-
country: intel?.network.country ?? null,
|
|
32
|
-
ai: ai ? { spam: ai.spam, spamConfidence: ai.spamConfidence, reason: ai.reason } : null,
|
|
33
|
-
linkDomains: linkDomains({ html: input.bodyHtml, text: [email.bodyText] }),
|
|
34
|
-
preview: email.preview.slice(0, 280),
|
|
35
|
-
};
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/** One admin report per message and mailbox; reporting again keeps the first one. */
|
|
39
|
-
export async function recordReportedMessage(binding: D1Database, input: {
|
|
40
|
-
mailboxId: string;
|
|
41
|
-
email: Email;
|
|
42
|
-
reporterUserId: string;
|
|
43
|
-
snapshot: ReportSnapshot;
|
|
44
|
-
}) {
|
|
45
|
-
const from = input.email.fromJson[0]?.address.toLocaleLowerCase() ?? "unknown@invalid";
|
|
46
|
-
const db = createDb(binding);
|
|
47
|
-
const id = createId("rpt");
|
|
48
|
-
await db.insert(reportedMessages).values({
|
|
49
|
-
id,
|
|
50
|
-
mailboxId: input.mailboxId,
|
|
51
|
-
emailId: input.email.id,
|
|
52
|
-
reporterUserId: input.reporterUserId,
|
|
53
|
-
senderAddress: from,
|
|
54
|
-
senderDomain: from.slice(from.lastIndexOf("@") + 1),
|
|
55
|
-
subject: input.email.subject,
|
|
56
|
-
receivedAt: input.email.timelineAt,
|
|
57
|
-
snapshotJson: input.snapshot,
|
|
58
|
-
status: "open",
|
|
59
|
-
createdAt: new Date(),
|
|
60
|
-
}).onConflictDoNothing();
|
|
61
|
-
const [row] = await db
|
|
62
|
-
.select({ id: reportedMessages.id })
|
|
63
|
-
.from(reportedMessages)
|
|
64
|
-
.where(and(eq(reportedMessages.mailboxId, input.mailboxId), eq(reportedMessages.emailId, input.email.id)))
|
|
65
|
-
.limit(1);
|
|
66
|
-
return row?.id ?? id;
|
|
67
|
-
}
|
|
68
|
-
|
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Mailbox migrations from before the 0.1.0 baseline, for Durable Objects
|
|
3
|
-
* created by earlier deployments. Applied only to a mailbox whose drizzle
|
|
4
|
-
* journal predates the baseline; new mailboxes never run them.
|
|
5
|
-
*/
|
|
6
|
-
export const legacyMailboxMigrations: ReadonlyArray<{ when: number; sql: string }> = [
|
|
7
|
-
{ when: 1784825133044, sql: "CREATE TABLE `conversations` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`latest_email_id` text NOT NULL,\n\t`timeline_at` integer NOT NULL,\n\t`mailbox_state` text DEFAULT 'active' NOT NULL,\n\t`folder_id` text,\n\t`has_incoming` integer DEFAULT false NOT NULL,\n\t`has_outgoing` integer DEFAULT false NOT NULL,\n\tFOREIGN KEY (`latest_email_id`) REFERENCES `emails`(`id`) ON UPDATE no action ON DELETE no action,\n\tFOREIGN KEY (`folder_id`) REFERENCES `folders`(`id`) ON UPDATE no action ON DELETE set null\n);\n--> statement-breakpoint\nCREATE INDEX `conversations_timeline_idx` ON `conversations` (`timeline_at`,`latest_email_id`);--> statement-breakpoint\nCREATE INDEX `conversations_inbox_timeline_idx` ON `conversations` (`mailbox_state`,`has_incoming`,`timeline_at`,`latest_email_id`);--> statement-breakpoint\nCREATE INDEX `conversations_sent_timeline_idx` ON `conversations` (`mailbox_state`,`has_outgoing`,`timeline_at`,`latest_email_id`);--> statement-breakpoint\nCREATE INDEX `conversations_folder_timeline_idx` ON `conversations` (`folder_id`,`timeline_at`,`latest_email_id`);--> statement-breakpoint\nCREATE TABLE `emails` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`request_fingerprint` text,\n\t`conversation_id` text NOT NULL,\n\t`direction` text NOT NULL,\n\t`message_id_header` text,\n\t`in_reply_to_json` text DEFAULT '[]' NOT NULL,\n\t`references_json` text DEFAULT '[]' NOT NULL,\n\t`from_json` text NOT NULL,\n\t`reply_to_json` text DEFAULT '[]' NOT NULL,\n\t`to_json` text DEFAULT '[]' NOT NULL,\n\t`cc_json` text DEFAULT '[]' NOT NULL,\n\t`bcc_json` text DEFAULT '[]' NOT NULL,\n\t`subject` text DEFAULT '(no subject)' NOT NULL,\n\t`preview` text DEFAULT '' NOT NULL,\n\t`body_text` text,\n\t`quoted_text` text,\n\t`body_html_r2_key` text,\n\t`raw_mime_r2_key` text,\n\t`attachments_json` text DEFAULT '[]' NOT NULL,\n\t`list_id` text,\n\t`list_post_address` text,\n\t`timeline_at` integer NOT NULL,\n\t`transport_state` text NOT NULL,\n\t`transport_error` text,\n\t`delivery_status_json` text DEFAULT '[]' NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `emails_conversation_timeline_idx` ON `emails` (`conversation_id`,`timeline_at`,`id`);--> statement-breakpoint\nCREATE INDEX `emails_message_id_header_idx` ON `emails` (`message_id_header`);--> statement-breakpoint\nCREATE TABLE `folders` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`name` text NOT NULL,\n\t`sort_order` integer DEFAULT 100 NOT NULL\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `folders_name_unique` ON `folders` (`name`);--> statement-breakpoint\nCREATE INDEX `folders_order_idx` ON `folders` (`sort_order`,`name`);--> statement-breakpoint\nCREATE TABLE `pending_inbound` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`raw_object_key` text NOT NULL,\n\t`envelope_from` text NOT NULL,\n\t`envelope_to` text NOT NULL,\n\t`received_at` integer NOT NULL,\n\t`attempts` integer DEFAULT 0 NOT NULL,\n\t`next_attempt_at` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `pending_inbound_next_attempt_idx` ON `pending_inbound` (`next_attempt_at`,`received_at`);--> statement-breakpoint\n-- Runtime-only search/projection objects: Drizzle snapshots do not model them.\nCREATE VIRTUAL TABLE `email_search` USING fts5(\n\t`email_id` UNINDEXED,\n\t`conversation_id` UNINDEXED,\n\t`subject`,\n\t`addresses`,\n\t`body`,\n\ttokenize = 'unicode61 remove_diacritics 2'\n);--> statement-breakpoint\nCREATE TRIGGER `emails_after_insert`\nAFTER INSERT ON `emails`\nBEGIN\n\tINSERT INTO `conversations` (\n\t\t`id`,\n\t\t`latest_email_id`,\n\t\t`timeline_at`,\n\t\t`mailbox_state`,\n\t\t`folder_id`,\n\t\t`has_incoming`,\n\t\t`has_outgoing`\n\t)\n\tVALUES (\n\t\tNEW.`conversation_id`,\n\t\tNEW.`id`,\n\t\tNEW.`timeline_at`,\n\t\t'active',\n\t\tNULL,\n\t\tNEW.`direction` = 'incoming',\n\t\tNEW.`direction` = 'outgoing'\n\t)\n\tON CONFLICT(`id`) DO UPDATE SET\n\t\t`latest_email_id` = CASE\n\t\t\tWHEN NEW.`timeline_at` > `conversations`.`timeline_at`\n\t\t\t\tOR (\n\t\t\t\t\tNEW.`timeline_at` = `conversations`.`timeline_at`\n\t\t\t\t\tAND NEW.`id` > `conversations`.`latest_email_id`\n\t\t\t\t)\n\t\t\tTHEN NEW.`id`\n\t\t\tELSE `conversations`.`latest_email_id`\n\t\tEND,\n\t\t`timeline_at` = MAX(`conversations`.`timeline_at`, NEW.`timeline_at`),\n\t\t`mailbox_state` = CASE\n\t\t\tWHEN `conversations`.`mailbox_state` IN ('archive', 'trash')\n\t\t\t\tOR (\n\t\t\t\t\t`conversations`.`mailbox_state` = 'spam'\n\t\t\t\t\tAND NEW.`direction` = 'outgoing'\n\t\t\t\t)\n\t\t\tTHEN 'active'\n\t\t\tELSE `conversations`.`mailbox_state`\n\t\tEND,\n\t\t`has_incoming` = `conversations`.`has_incoming`\n\t\t\tOR NEW.`direction` = 'incoming',\n\t\t`has_outgoing` = `conversations`.`has_outgoing`\n\t\t\tOR NEW.`direction` = 'outgoing';\n\n\tINSERT INTO `email_search` (\n\t\t`email_id`,\n\t\t`conversation_id`,\n\t\t`subject`,\n\t\t`addresses`,\n\t\t`body`\n\t)\n\tVALUES (\n\t\tNEW.`id`,\n\t\tNEW.`conversation_id`,\n\t\tNEW.`subject`,\n\t\tCOALESCE(NEW.`from_json`, '') || ' '\n\t\t\t|| COALESCE(NEW.`reply_to_json`, '') || ' '\n\t\t\t|| COALESCE(NEW.`to_json`, '') || ' '\n\t\t\t|| COALESCE(NEW.`cc_json`, '') || ' '\n\t\t\t|| COALESCE(NEW.`bcc_json`, ''),\n\t\tCOALESCE(NEW.`body_text`, '') || ' ' || COALESCE(NEW.`preview`, '')\n\t);\nEND;\n" },
|
|
8
|
-
{ when: 1787348208125, sql: "CREATE TABLE `email_read_states` (\n\t`user_id` text NOT NULL,\n\t`email_id` text NOT NULL,\n\t`read_at` integer NOT NULL,\n\tPRIMARY KEY(`user_id`, `email_id`),\n\tFOREIGN KEY (`email_id`) REFERENCES `emails`(`id`) ON UPDATE no action ON DELETE cascade\n);\n--> statement-breakpoint\nCREATE INDEX `email_read_states_email_idx` ON `email_read_states` (`email_id`);" },
|
|
9
|
-
{ when: 1787422760085, sql: "CREATE TABLE `pending_object_deletions` (\n\t`object_key` text PRIMARY KEY NOT NULL,\n\t`attempts` integer DEFAULT 0 NOT NULL,\n\t`next_attempt_at` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `pending_object_deletions_next_attempt_idx` ON `pending_object_deletions` (`next_attempt_at`);" },
|
|
10
|
-
{ when: 1787514819958, sql: "ALTER TABLE `emails` ADD `authentication_results_json` text;" },
|
|
11
|
-
{ when: 1787522950002, sql: "CREATE TABLE `mailbox_ai_configuration` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`instructions` text DEFAULT '' NOT NULL,\n\t`confidence_threshold` integer DEFAULT 75 NOT NULL,\n\t`updated_at` integer NOT NULL\n);\n--> statement-breakpoint\nALTER TABLE `emails` ADD `ai_classification_json` text;--> statement-breakpoint\nALTER TABLE `pending_inbound` ADD `ai_attempts` integer DEFAULT 0 NOT NULL;\n" },
|
|
12
|
-
{ when: 1791081433051, sql: "CREATE TABLE `pending_office_previews` (\n\t`source_key` text PRIMARY KEY NOT NULL,\n\t`email_id` text NOT NULL,\n\t`attachment_id` text NOT NULL,\n\t`attempts` integer DEFAULT 0 NOT NULL,\n\t`next_attempt_at` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `pending_office_previews_next_attempt_idx` ON `pending_office_previews` (`next_attempt_at`);" },
|
|
13
|
-
{ when: 1793417083777, sql: "ALTER TABLE `emails` ADD `envelope_from` text;--> statement-breakpoint\nALTER TABLE `emails` ADD `envelope_to` text;--> statement-breakpoint\nALTER TABLE `emails` ADD `list_unsubscribe_json` text;" },
|
|
14
|
-
{ when: 1793418627171, sql: "CREATE TABLE `senders` (\n\t`address` text PRIMARY KEY NOT NULL,\n\t`domain` text NOT NULL,\n\t`first_seen_at` integer,\n\t`last_seen_at` integer,\n\t`message_count` integer DEFAULT 0 NOT NULL,\n\t`outbound_count` integer DEFAULT 0 NOT NULL,\n\t`last_outbound_at` integer,\n\t`blocked_at` integer,\n\t`trusted_at` integer,\n\t`reported_at` integer\n);\n--> statement-breakpoint\nCREATE INDEX `senders_domain_idx` ON `senders` (`domain`);--> statement-breakpoint\nALTER TABLE `emails` ADD `sender_intel_json` text;--> statement-breakpoint\nINSERT INTO `senders` (`address`, `domain`, `first_seen_at`, `last_seen_at`, `message_count`)\nSELECT `address`, substr(`address`, instr(`address`, '@') + 1), min(`timeline_at`), max(`timeline_at`), count(*)\nFROM (\n\tSELECT lower(json_extract(`from_json`, '$[0].address')) AS `address`, `timeline_at`\n\tFROM `emails`\n\tWHERE `direction` = 'incoming'\n)\nWHERE `address` LIKE '%_@_%'\nGROUP BY `address`;--> statement-breakpoint\nINSERT INTO `senders` (`address`, `domain`, `outbound_count`, `last_outbound_at`)\nSELECT `address`, substr(`address`, instr(`address`, '@') + 1), count(*), max(`timeline_at`)\nFROM (\n\tSELECT lower(json_extract(`recipient`.`value`, '$.address')) AS `address`, `message`.`timeline_at`\n\tFROM `emails` AS `message`, json_each(`message`.`to_json`) AS `recipient`\n\tWHERE `message`.`direction` = 'outgoing'\n\tUNION ALL\n\tSELECT lower(json_extract(`recipient`.`value`, '$.address')), `message`.`timeline_at`\n\tFROM `emails` AS `message`, json_each(`message`.`cc_json`) AS `recipient`\n\tWHERE `message`.`direction` = 'outgoing'\n\tUNION ALL\n\tSELECT lower(json_extract(`recipient`.`value`, '$.address')), `message`.`timeline_at`\n\tFROM `emails` AS `message`, json_each(`message`.`bcc_json`) AS `recipient`\n\tWHERE `message`.`direction` = 'outgoing'\n)\nWHERE `address` LIKE '%_@_%'\nGROUP BY `address`\nON CONFLICT (`address`) DO UPDATE SET\n\t`outbound_count` = excluded.`outbound_count`,\n\t`last_outbound_at` = excluded.`last_outbound_at`;\n" },
|
|
15
|
-
{ when: 1793439647535, sql: "CREATE TABLE `mail_rules` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`name` text NOT NULL,\n\t`sort_order` integer DEFAULT 100 NOT NULL,\n\t`enabled` integer DEFAULT true NOT NULL,\n\t`conditions_json` text NOT NULL,\n\t`actions_json` text NOT NULL,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `mail_rules_order_idx` ON `mail_rules` (`sort_order`,`created_at`);--> statement-breakpoint\nCREATE TABLE `sender_feedback` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`address` text NOT NULL,\n\t`domain` text NOT NULL,\n\t`email_id` text,\n\t`label` text NOT NULL,\n\t`user_id` text,\n\t`created_at` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `sender_feedback_address_idx` ON `sender_feedback` (`address`,`created_at`);--> statement-breakpoint\nCREATE INDEX `sender_feedback_domain_idx` ON `sender_feedback` (`domain`);--> statement-breakpoint\nCREATE TABLE `unsubscriptions` (\n\t`list_key` text PRIMARY KEY NOT NULL,\n\t`email_id` text,\n\t`method` text NOT NULL,\n\t`status` text NOT NULL,\n\t`target` text,\n\t`detail` text,\n\t`user_id` text,\n\t`created_at` integer NOT NULL\n);\n--> statement-breakpoint\nALTER TABLE `emails` ADD `delivery_json` text;--> statement-breakpoint\nALTER TABLE `emails` ADD `screening_json` text;--> statement-breakpoint\nALTER TABLE `emails` ADD `report_label` text;" },
|
|
16
|
-
{ when: 1793467839387, sql: "ALTER TABLE `pending_inbound` ADD `list_address` text;" },
|
|
17
|
-
];
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Brings a mailbox created before the baseline up to it: applies the legacy
|
|
21
|
-
* migrations it has not run, then records the baseline as applied so drizzle
|
|
22
|
-
* does not create its tables a second time. A no-op for new mailboxes.
|
|
23
|
-
*/
|
|
24
|
-
export function upgradeLegacyMailbox(sql: SqlStorage, baselineWhen: number) {
|
|
25
|
-
const hasJournal = sql
|
|
26
|
-
.exec("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '__drizzle_migrations'")
|
|
27
|
-
.toArray().length > 0;
|
|
28
|
-
if (!hasJournal) return;
|
|
29
|
-
const [{ last }] = sql
|
|
30
|
-
.exec<{ last: number | null }>("SELECT max(created_at) AS last FROM __drizzle_migrations")
|
|
31
|
-
.toArray();
|
|
32
|
-
if (last === null || Number(last) >= baselineWhen) return;
|
|
33
|
-
for (const migration of legacyMailboxMigrations) {
|
|
34
|
-
if (migration.when <= Number(last)) continue;
|
|
35
|
-
for (const statement of migration.sql.split("--> statement-breakpoint")) {
|
|
36
|
-
if (statement.trim()) sql.exec(statement);
|
|
37
|
-
}
|
|
38
|
-
sql.exec("INSERT INTO __drizzle_migrations (hash, created_at) VALUES ('', ?)", migration.when);
|
|
39
|
-
}
|
|
40
|
-
sql.exec("INSERT INTO __drizzle_migrations (hash, created_at) VALUES ('', ?)", baselineWhen);
|
|
41
|
-
}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
// Generated by scripts/embed-mailbox-migrations.ts from drizzle/mailbox. Do not edit.
|
|
2
|
-
export default {
|
|
3
|
-
journal: {"version":"7","dialect":"sqlite","entries":[{"idx":0,"version":"6","when":1793490547954,"tag":"0000_mailbox","breakpoints":true}]},
|
|
4
|
-
migrations: {
|
|
5
|
-
m0000: "CREATE TABLE `conversations` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`latest_email_id` text NOT NULL,\n\t`timeline_at` integer NOT NULL,\n\t`mailbox_state` text DEFAULT 'active' NOT NULL,\n\t`folder_id` text,\n\t`has_incoming` integer DEFAULT false NOT NULL,\n\t`has_outgoing` integer DEFAULT false NOT NULL,\n\tFOREIGN KEY (`latest_email_id`) REFERENCES `emails`(`id`) ON UPDATE no action ON DELETE no action,\n\tFOREIGN KEY (`folder_id`) REFERENCES `folders`(`id`) ON UPDATE no action ON DELETE set null\n);\n--> statement-breakpoint\nCREATE INDEX `conversations_timeline_idx` ON `conversations` (`timeline_at`,`latest_email_id`);--> statement-breakpoint\nCREATE INDEX `conversations_inbox_timeline_idx` ON `conversations` (`mailbox_state`,`has_incoming`,`timeline_at`,`latest_email_id`);--> statement-breakpoint\nCREATE INDEX `conversations_sent_timeline_idx` ON `conversations` (`mailbox_state`,`has_outgoing`,`timeline_at`,`latest_email_id`);--> statement-breakpoint\nCREATE INDEX `conversations_folder_timeline_idx` ON `conversations` (`folder_id`,`timeline_at`,`latest_email_id`);--> statement-breakpoint\nCREATE TABLE `email_read_states` (\n\t`user_id` text NOT NULL,\n\t`email_id` text NOT NULL,\n\t`read_at` integer NOT NULL,\n\tPRIMARY KEY(`user_id`, `email_id`),\n\tFOREIGN KEY (`email_id`) REFERENCES `emails`(`id`) ON UPDATE no action ON DELETE cascade\n);\n--> statement-breakpoint\nCREATE INDEX `email_read_states_email_idx` ON `email_read_states` (`email_id`);--> statement-breakpoint\nCREATE TABLE `emails` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`request_fingerprint` text,\n\t`conversation_id` text NOT NULL,\n\t`direction` text NOT NULL,\n\t`message_id_header` text,\n\t`in_reply_to_json` text DEFAULT '[]' NOT NULL,\n\t`references_json` text DEFAULT '[]' NOT NULL,\n\t`from_json` text NOT NULL,\n\t`reply_to_json` text DEFAULT '[]' NOT NULL,\n\t`to_json` text DEFAULT '[]' NOT NULL,\n\t`cc_json` text DEFAULT '[]' NOT NULL,\n\t`bcc_json` text DEFAULT '[]' NOT NULL,\n\t`subject` text DEFAULT '(no subject)' NOT NULL,\n\t`preview` text DEFAULT '' NOT NULL,\n\t`body_text` text,\n\t`quoted_text` text,\n\t`body_html_r2_key` text,\n\t`raw_mime_r2_key` text,\n\t`authentication_results_json` text,\n\t`envelope_from` text,\n\t`envelope_to` text,\n\t`list_unsubscribe_json` text,\n\t`sender_intel_json` text,\n\t`ai_classification_json` text,\n\t`delivery_json` text,\n\t`screening_json` text,\n\t`report_label` text,\n\t`attachments_json` text DEFAULT '[]' NOT NULL,\n\t`list_id` text,\n\t`list_post_address` text,\n\t`timeline_at` integer NOT NULL,\n\t`transport_state` text NOT NULL,\n\t`transport_error` text,\n\t`delivery_status_json` text DEFAULT '[]' NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `emails_conversation_timeline_idx` ON `emails` (`conversation_id`,`timeline_at`,`id`);--> statement-breakpoint\nCREATE INDEX `emails_message_id_header_idx` ON `emails` (`message_id_header`);--> statement-breakpoint\nCREATE TABLE `folders` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`name` text NOT NULL,\n\t`sort_order` integer DEFAULT 100 NOT NULL\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `folders_name_unique` ON `folders` (`name`);--> statement-breakpoint\nCREATE INDEX `folders_order_idx` ON `folders` (`sort_order`,`name`);--> statement-breakpoint\nCREATE TABLE `mail_rules` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`name` text NOT NULL,\n\t`sort_order` integer DEFAULT 100 NOT NULL,\n\t`enabled` integer DEFAULT true NOT NULL,\n\t`conditions_json` text NOT NULL,\n\t`actions_json` text NOT NULL,\n\t`created_at` integer NOT NULL,\n\t`updated_at` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `mail_rules_order_idx` ON `mail_rules` (`sort_order`,`created_at`);--> statement-breakpoint\nCREATE TABLE `mailbox_ai_configuration` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`instructions` text DEFAULT '' NOT NULL,\n\t`confidence_threshold` integer DEFAULT 75 NOT NULL,\n\t`updated_at` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE TABLE `pending_inbound` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`raw_object_key` text NOT NULL,\n\t`envelope_from` text NOT NULL,\n\t`envelope_to` text NOT NULL,\n\t`list_address` text,\n\t`received_at` integer NOT NULL,\n\t`attempts` integer DEFAULT 0 NOT NULL,\n\t`ai_attempts` integer DEFAULT 0 NOT NULL,\n\t`next_attempt_at` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `pending_inbound_next_attempt_idx` ON `pending_inbound` (`next_attempt_at`,`received_at`);--> statement-breakpoint\nCREATE TABLE `pending_object_deletions` (\n\t`object_key` text PRIMARY KEY NOT NULL,\n\t`attempts` integer DEFAULT 0 NOT NULL,\n\t`next_attempt_at` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `pending_object_deletions_next_attempt_idx` ON `pending_object_deletions` (`next_attempt_at`);--> statement-breakpoint\nCREATE TABLE `pending_office_previews` (\n\t`source_key` text PRIMARY KEY NOT NULL,\n\t`email_id` text NOT NULL,\n\t`attachment_id` text NOT NULL,\n\t`attempts` integer DEFAULT 0 NOT NULL,\n\t`next_attempt_at` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `pending_office_previews_next_attempt_idx` ON `pending_office_previews` (`next_attempt_at`);--> statement-breakpoint\nCREATE TABLE `sender_feedback` (\n\t`id` text PRIMARY KEY NOT NULL,\n\t`address` text NOT NULL,\n\t`domain` text NOT NULL,\n\t`email_id` text,\n\t`label` text NOT NULL,\n\t`user_id` text,\n\t`created_at` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `sender_feedback_address_idx` ON `sender_feedback` (`address`,`created_at`);--> statement-breakpoint\nCREATE INDEX `sender_feedback_domain_idx` ON `sender_feedback` (`domain`);--> statement-breakpoint\nCREATE TABLE `senders` (\n\t`address` text PRIMARY KEY NOT NULL,\n\t`domain` text NOT NULL,\n\t`first_seen_at` integer,\n\t`last_seen_at` integer,\n\t`message_count` integer DEFAULT 0 NOT NULL,\n\t`outbound_count` integer DEFAULT 0 NOT NULL,\n\t`last_outbound_at` integer,\n\t`blocked_at` integer,\n\t`trusted_at` integer,\n\t`reported_at` integer\n);\n--> statement-breakpoint\nCREATE INDEX `senders_domain_idx` ON `senders` (`domain`);--> statement-breakpoint\nCREATE TABLE `unsubscriptions` (\n\t`list_key` text PRIMARY KEY NOT NULL,\n\t`email_id` text,\n\t`method` text NOT NULL,\n\t`status` text NOT NULL,\n\t`target` text,\n\t`detail` text,\n\t`user_id` text,\n\t`created_at` integer NOT NULL\n);--> statement-breakpoint\n-- Search index and conversation projection triggers; drizzle does not model them.\nCREATE VIRTUAL TABLE `email_search` USING fts5(\n\t`email_id` UNINDEXED,\n\t`conversation_id` UNINDEXED,\n\t`subject`,\n\t`addresses`,\n\t`body`,\n\ttokenize = 'unicode61 remove_diacritics 2'\n);--> statement-breakpoint\nCREATE TRIGGER `emails_after_insert`\nAFTER INSERT ON `emails`\nBEGIN\n\tINSERT INTO `conversations` (\n\t\t`id`,\n\t\t`latest_email_id`,\n\t\t`timeline_at`,\n\t\t`mailbox_state`,\n\t\t`folder_id`,\n\t\t`has_incoming`,\n\t\t`has_outgoing`\n\t)\n\tVALUES (\n\t\tNEW.`conversation_id`,\n\t\tNEW.`id`,\n\t\tNEW.`timeline_at`,\n\t\t'active',\n\t\tNULL,\n\t\tNEW.`direction` = 'incoming',\n\t\tNEW.`direction` = 'outgoing'\n\t)\n\tON CONFLICT(`id`) DO UPDATE SET\n\t\t`latest_email_id` = CASE\n\t\t\tWHEN NEW.`timeline_at` > `conversations`.`timeline_at`\n\t\t\t\tOR (\n\t\t\t\t\tNEW.`timeline_at` = `conversations`.`timeline_at`\n\t\t\t\t\tAND NEW.`id` > `conversations`.`latest_email_id`\n\t\t\t\t)\n\t\t\tTHEN NEW.`id`\n\t\t\tELSE `conversations`.`latest_email_id`\n\t\tEND,\n\t\t`timeline_at` = MAX(`conversations`.`timeline_at`, NEW.`timeline_at`),\n\t\t`mailbox_state` = CASE\n\t\t\tWHEN `conversations`.`mailbox_state` IN ('archive', 'trash')\n\t\t\t\tOR (\n\t\t\t\t\t`conversations`.`mailbox_state` = 'spam'\n\t\t\t\t\tAND NEW.`direction` = 'outgoing'\n\t\t\t\t)\n\t\t\tTHEN 'active'\n\t\t\tELSE `conversations`.`mailbox_state`\n\t\tEND,\n\t\t`has_incoming` = `conversations`.`has_incoming`\n\t\t\tOR NEW.`direction` = 'incoming',\n\t\t`has_outgoing` = `conversations`.`has_outgoing`\n\t\t\tOR NEW.`direction` = 'outgoing';\n\n\tINSERT INTO `email_search` (\n\t\t`email_id`,\n\t\t`conversation_id`,\n\t\t`subject`,\n\t\t`addresses`,\n\t\t`body`\n\t)\n\tVALUES (\n\t\tNEW.`id`,\n\t\tNEW.`conversation_id`,\n\t\tNEW.`subject`,\n\t\tCOALESCE(NEW.`from_json`, '') || ' '\n\t\t\t|| COALESCE(NEW.`reply_to_json`, '') || ' '\n\t\t\t|| COALESCE(NEW.`to_json`, '') || ' '\n\t\t\t|| COALESCE(NEW.`cc_json`, '') || ' '\n\t\t\t|| COALESCE(NEW.`bcc_json`, ''),\n\t\tCOALESCE(NEW.`body_text`, '') || ' ' || COALESCE(NEW.`preview`, '')\n\t);\nEND;\n",
|
|
6
|
-
},
|
|
7
|
-
};
|
|
8
|
-
|
|
9
|
-
/** When the newest migration was generated; the drizzle journal's high-water mark. */
|
|
10
|
-
export const LATEST_MAILBOX_MIGRATION = 1793490547954;
|
package/worker/mailbox/rules.ts
DELETED
|
@@ -1,110 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
MAX_MAIL_RULES,
|
|
3
|
-
ruleSubject,
|
|
4
|
-
type MailRule,
|
|
5
|
-
type MailRuleActions,
|
|
6
|
-
type MailRuleConditions,
|
|
7
|
-
type RuleSubject,
|
|
8
|
-
} from "../../shared/mail-rules";
|
|
9
|
-
import type { Email, NewEmail } from "./schema";
|
|
10
|
-
|
|
11
|
-
type RuleRow = {
|
|
12
|
-
id: string;
|
|
13
|
-
name: string;
|
|
14
|
-
sort_order: number;
|
|
15
|
-
enabled: number;
|
|
16
|
-
conditions_json: string;
|
|
17
|
-
actions_json: string;
|
|
18
|
-
};
|
|
19
|
-
|
|
20
|
-
export type MailRuleInput = {
|
|
21
|
-
name: string;
|
|
22
|
-
enabled: boolean;
|
|
23
|
-
conditions: MailRuleConditions;
|
|
24
|
-
actions: MailRuleActions;
|
|
25
|
-
};
|
|
26
|
-
|
|
27
|
-
export const MAIL_RULE_LIMIT_MESSAGE = `A mailbox can have at most ${MAX_MAIL_RULES} rules`;
|
|
28
|
-
|
|
29
|
-
function toRule(row: RuleRow): MailRule {
|
|
30
|
-
return {
|
|
31
|
-
id: row.id,
|
|
32
|
-
name: row.name,
|
|
33
|
-
enabled: Boolean(row.enabled),
|
|
34
|
-
conditions: JSON.parse(row.conditions_json) as MailRuleConditions,
|
|
35
|
-
actions: JSON.parse(row.actions_json) as MailRuleActions,
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export function listMailRules(sql: SqlStorage): MailRule[] {
|
|
40
|
-
return sql.exec<RuleRow>(
|
|
41
|
-
"select id, name, sort_order, enabled, conditions_json, actions_json from mail_rules order by sort_order, created_at, id",
|
|
42
|
-
).toArray().map(toRule);
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/** Drops a folder action whose folder no longer exists, so a rule never files into nothing. */
|
|
46
|
-
export function withExistingFolder(sql: SqlStorage, actions: MailRuleActions): MailRuleActions {
|
|
47
|
-
if (!actions.folderId) return actions;
|
|
48
|
-
const exists = sql.exec("select 1 from folders where id = ?", actions.folderId).toArray().length > 0;
|
|
49
|
-
if (exists) return actions;
|
|
50
|
-
const { folderId: _folderId, ...rest } = actions;
|
|
51
|
-
return rest;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export function insertMailRule(sql: SqlStorage, id: string, input: MailRuleInput, now: number) {
|
|
55
|
-
const count = Number(sql.exec<{ count: number }>("select count(*) as count from mail_rules").one().count);
|
|
56
|
-
if (count >= MAX_MAIL_RULES) throw new Error(MAIL_RULE_LIMIT_MESSAGE);
|
|
57
|
-
const last = sql.exec<{ value: number | null }>("select max(sort_order) as value from mail_rules").one().value;
|
|
58
|
-
sql.exec(
|
|
59
|
-
`insert into mail_rules (id, name, sort_order, enabled, conditions_json, actions_json, created_at, updated_at)
|
|
60
|
-
values (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
61
|
-
id,
|
|
62
|
-
input.name,
|
|
63
|
-
(last ?? 90) + 10,
|
|
64
|
-
input.enabled ? 1 : 0,
|
|
65
|
-
JSON.stringify(input.conditions),
|
|
66
|
-
JSON.stringify(withExistingFolder(sql, input.actions)),
|
|
67
|
-
now,
|
|
68
|
-
now,
|
|
69
|
-
);
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
export function updateMailRule(sql: SqlStorage, id: string, input: MailRuleInput, now: number) {
|
|
73
|
-
return sql.exec(
|
|
74
|
-
`update mail_rules set name = ?, enabled = ?, conditions_json = ?, actions_json = ?, updated_at = ?
|
|
75
|
-
where id = ? returning id`,
|
|
76
|
-
input.name,
|
|
77
|
-
input.enabled ? 1 : 0,
|
|
78
|
-
JSON.stringify(input.conditions),
|
|
79
|
-
JSON.stringify(withExistingFolder(sql, input.actions)),
|
|
80
|
-
now,
|
|
81
|
-
id,
|
|
82
|
-
).toArray().length > 0;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
export function deleteMailRule(sql: SqlStorage, id: string) {
|
|
86
|
-
return sql.exec("delete from mail_rules where id = ? returning id", id).toArray().length > 0;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/** Requires the complete current id list so a stale client cannot drop rules from the order. */
|
|
90
|
-
export function reorderMailRules(sql: SqlStorage, ids: string[]) {
|
|
91
|
-
const current = sql.exec<{ id: string }>("select id from mail_rules").toArray().map((row) => row.id);
|
|
92
|
-
if (current.length !== ids.length || new Set(ids).size !== ids.length || !ids.every((id) => current.includes(id))) {
|
|
93
|
-
return false;
|
|
94
|
-
}
|
|
95
|
-
ids.forEach((id, index) => {
|
|
96
|
-
sql.exec("update mail_rules set sort_order = ? where id = ?", (index + 1) * 10, id);
|
|
97
|
-
});
|
|
98
|
-
return true;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/** Rule facts for a stored or about-to-be-stored message. */
|
|
102
|
-
export function emailRuleSubject(email: Pick<NewEmail | Email, "fromJson" | "toJson" | "ccJson" | "subject" | "listId" | "attachmentsJson">): RuleSubject {
|
|
103
|
-
return ruleSubject({
|
|
104
|
-
from: email.fromJson[0]?.address,
|
|
105
|
-
recipients: [...(email.toJson ?? []), ...(email.ccJson ?? [])].map((recipient) => recipient.address),
|
|
106
|
-
subject: email.subject,
|
|
107
|
-
listId: email.listId,
|
|
108
|
-
hasAttachment: (email.attachmentsJson ?? []).some((attachment) => attachment.disposition === "attachment"),
|
|
109
|
-
});
|
|
110
|
-
}
|