@open-workspace/email 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -3
- package/alchemy.ts +27 -11
- package/migrations/0000_email.sql +18 -0
- package/migrations/meta/0000_snapshot.json +127 -1
- package/migrations/meta/_journal.json +1 -1
- package/package.json +3 -3
- package/shared/mail.ts +11 -8
- package/worker/db/schema.ts +34 -1
- package/worker/jmap/eventsource.ts +101 -0
- package/worker/jmap/methods.ts +250 -1
- package/worker/jmap/push.ts +123 -0
- package/worker/jmap/routes.ts +125 -24
- package/worker/mail/header-metadata.ts +4 -38
- package/worker/mail/push-notifications.ts +17 -3
- package/worker/mail/r2-presigned-urls.ts +2 -2
- package/worker/mail/routes.ts +3 -3
- package/worker/mail/safety-routes.ts +2 -3
- package/worker/mail/uploads.ts +29 -0
- package/worker/mailbox/demo.ts +2 -2
- package/worker/mailbox/index.ts +34 -23
- package/worker/mailbox/model.ts +2 -11
- package/worker/mailbox/legacy-migrations.ts +0 -41
|
@@ -1,52 +1,18 @@
|
|
|
1
1
|
import type { InboundAuthentication } from "../../shared/mail-authentication";
|
|
2
2
|
import type { mailboxStub } from "../mailbox";
|
|
3
3
|
import type { Email } from "../mailbox/schema";
|
|
4
|
-
import { inboundHeaderMetadata } from "./auth-headers";
|
|
5
|
-
import { rawHeaderText } from "./inbound";
|
|
6
4
|
import { linkDomains } from "./link-domains";
|
|
7
5
|
import { collectSenderIntel, senderIntelWorthStoring } from "./sender-intel";
|
|
8
6
|
|
|
9
|
-
const HEADER_RANGE_BYTES = 256 * 1024;
|
|
10
|
-
|
|
11
7
|
export function headerAuthentication(email: Email): InboundAuthentication | null {
|
|
12
8
|
const stored = email.authenticationResultsJson;
|
|
13
|
-
return stored?.
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* Messages stored before header parsing (or with legacy Cloudflare analytics)
|
|
18
|
-
* are parsed from the original's header section on first view, then persisted.
|
|
19
|
-
*/
|
|
20
|
-
export async function withHeaderMetadata(
|
|
21
|
-
env: Env,
|
|
22
|
-
mailbox: ReturnType<typeof mailboxStub>,
|
|
23
|
-
email: Email,
|
|
24
|
-
): Promise<Email> {
|
|
25
|
-
if (email.direction !== "incoming" || !email.rawMimeR2Key || headerAuthentication(email)) {
|
|
26
|
-
return email;
|
|
27
|
-
}
|
|
28
|
-
try {
|
|
29
|
-
const object = await env.MAIL_STORAGE.get(email.rawMimeR2Key, {
|
|
30
|
-
range: { offset: 0, length: HEADER_RANGE_BYTES },
|
|
31
|
-
});
|
|
32
|
-
if (!object) return email;
|
|
33
|
-
const metadata = inboundHeaderMetadata({
|
|
34
|
-
rawHeaders: rawHeaderText(await object.arrayBuffer()),
|
|
35
|
-
fromAddress: email.fromJson[0]?.address ?? null,
|
|
36
|
-
envelopeFrom: email.envelopeFrom,
|
|
37
|
-
});
|
|
38
|
-
await mailbox.setEmailHeaderMetadata(email.id, metadata);
|
|
39
|
-
return { ...email, ...metadata };
|
|
40
|
-
} catch (error) {
|
|
41
|
-
console.error(`Could not parse authentication headers for ${email.id}`, error);
|
|
42
|
-
return email;
|
|
43
|
-
}
|
|
9
|
+
return stored?.version === 1 ? stored : null;
|
|
44
10
|
}
|
|
45
11
|
|
|
46
12
|
/**
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
* returned for display but not stored, so a later view retries.
|
|
13
|
+
* Ingestion skips storing sender intelligence when every lookup failed; such
|
|
14
|
+
* a message gets it on view, with the same lookups. A result that failed again
|
|
15
|
+
* is returned for display but not stored, so a later view retries.
|
|
50
16
|
*/
|
|
51
17
|
export async function withSenderIntel(
|
|
52
18
|
env: Env,
|
|
@@ -21,6 +21,7 @@ import type { AppEnv, PushBindings } from "@open-workspace/core/worker/env.ts";
|
|
|
21
21
|
import { apiError } from "@open-workspace/core/worker/lib/http.ts";
|
|
22
22
|
import { createId } from "@open-workspace/core/worker/lib/ids.ts";
|
|
23
23
|
import { mailboxStub } from "../mailbox";
|
|
24
|
+
import { deliverJmapStateChange } from "../jmap/push";
|
|
24
25
|
import { getMailboxAccess } from "./access";
|
|
25
26
|
|
|
26
27
|
export const PUSH_NOTIFICATION_QUEUE = "openworkspace-push-notifications";
|
|
@@ -65,6 +66,12 @@ const pushJobBaseSchema = z.object({
|
|
|
65
66
|
});
|
|
66
67
|
|
|
67
68
|
const pushJobSchema = z.discriminatedUnion("type", [
|
|
69
|
+
z.object({
|
|
70
|
+
type: z.literal("jmap-state"),
|
|
71
|
+
mailboxId: z.string().min(1),
|
|
72
|
+
state: z.string().min(1).max(100),
|
|
73
|
+
occurredAt: z.number().int().nonnegative(),
|
|
74
|
+
}),
|
|
68
75
|
pushJobBaseSchema.extend({ type: z.literal("dispatch") }),
|
|
69
76
|
pushJobBaseSchema.extend({
|
|
70
77
|
type: z.literal("deliver"),
|
|
@@ -139,10 +146,11 @@ function pushFailureDetails(error: unknown) {
|
|
|
139
146
|
: { message: String(error) };
|
|
140
147
|
}
|
|
141
148
|
|
|
142
|
-
function pushConfiguration(env: PushBindings) {
|
|
149
|
+
function pushConfiguration(env: PushBindings & { IDENTITY_PROVIDER_ORIGIN?: string }) {
|
|
143
150
|
const publicKey = env.VAPID_PUBLIC_KEY;
|
|
144
151
|
const privateKey = env.VAPID_PRIVATE_KEY;
|
|
145
|
-
|
|
152
|
+
// Push services want a contact; the app's own URL is one.
|
|
153
|
+
const subject = env.VAPID_SUBJECT ?? env.IDENTITY_PROVIDER_ORIGIN;
|
|
146
154
|
if (!publicKey || !privateKey || !subject) {
|
|
147
155
|
return Promise.resolve({
|
|
148
156
|
configuration: null,
|
|
@@ -444,12 +452,18 @@ async function deliverPushJob(
|
|
|
444
452
|
}
|
|
445
453
|
}
|
|
446
454
|
|
|
455
|
+
/** The server's VAPID identity, or null when push is not configured. */
|
|
456
|
+
export async function vapidConfiguration(env: Env & PushBindings) {
|
|
457
|
+
return (await pushConfiguration(env)).configuration;
|
|
458
|
+
}
|
|
459
|
+
|
|
447
460
|
async function processPushJob(env: Env & PushBindings, job: MailboxPushJob) {
|
|
448
461
|
const ageMs = Math.max(0, Date.now() - job.occurredAt);
|
|
449
462
|
if (ageMs >= MAX_PUSH_JOB_AGE_MS) return;
|
|
450
463
|
const configuration = (await pushConfiguration(env)).configuration;
|
|
451
464
|
if (!configuration) return;
|
|
452
|
-
if (job.type === "
|
|
465
|
+
if (job.type === "jmap-state") await deliverJmapStateChange(env, job, configuration);
|
|
466
|
+
else if (job.type === "dispatch") await dispatchPushJob(env, job);
|
|
453
467
|
else await deliverPushJob(env, job, configuration, ageMs);
|
|
454
468
|
}
|
|
455
469
|
|
|
@@ -9,8 +9,8 @@ function r2S3Credentials(env: Bindings) {
|
|
|
9
9
|
const accessKeyId = env.R2_ACCESS_KEY_ID?.trim();
|
|
10
10
|
const secretAccessKey = env.R2_SECRET_ACCESS_KEY?.trim();
|
|
11
11
|
const accountId = env.R2_ACCOUNT_ID?.trim();
|
|
12
|
-
const bucketName = env.R2_BUCKET_NAME?.trim()
|
|
13
|
-
if (!accessKeyId || !secretAccessKey || !accountId) return null;
|
|
12
|
+
const bucketName = env.R2_BUCKET_NAME?.trim();
|
|
13
|
+
if (!accessKeyId || !secretAccessKey || !accountId || !bucketName) return null;
|
|
14
14
|
return { accessKeyId, secretAccessKey, accountId, bucketName };
|
|
15
15
|
}
|
|
16
16
|
|
package/worker/mail/routes.ts
CHANGED
|
@@ -47,7 +47,7 @@ import {
|
|
|
47
47
|
} from "./outgoing-context";
|
|
48
48
|
import { participantLabels } from "./participants";
|
|
49
49
|
import { buildReplyPlan } from "./reply-plan";
|
|
50
|
-
import { headerAuthentication,
|
|
50
|
+
import { headerAuthentication, withSenderIntel } from "./header-metadata";
|
|
51
51
|
import { messageSecurity, type SenderHistory } from "./message-security";
|
|
52
52
|
import { BIMI_LOGO_HEADERS, bimiLogoPath, bimiObjectKey } from "./bimi";
|
|
53
53
|
import { storedSenderIntel } from "./sender-intel";
|
|
@@ -815,7 +815,7 @@ export const mailRoutes = new Hono<AppEnv>()
|
|
|
815
815
|
const email = await withSenderIntel(
|
|
816
816
|
c.env,
|
|
817
817
|
mailbox,
|
|
818
|
-
|
|
818
|
+
stored,
|
|
819
819
|
{ bodyHtml, workspaceDomains: identity.domains, dqsKey },
|
|
820
820
|
);
|
|
821
821
|
const readStates = readStatesByEmail.get(email.id) ?? [];
|
|
@@ -984,7 +984,7 @@ export const mailRoutes = new Hono<AppEnv>()
|
|
|
984
984
|
if (!stored?.rawMimeR2Key || stored.direction !== "incoming") {
|
|
985
985
|
return apiError(c, 404, "NOT_FOUND", "Original message not found");
|
|
986
986
|
}
|
|
987
|
-
const message =
|
|
987
|
+
const message = stored;
|
|
988
988
|
const from = message.fromJson[0]?.address ?? "";
|
|
989
989
|
const [identity, history] = await Promise.all([
|
|
990
990
|
workspaceIdentity(c.env.DB),
|
|
@@ -11,7 +11,6 @@ import { MAIL_RULE_LIMIT_MESSAGE } from "../mailbox/rules";
|
|
|
11
11
|
import type { Email } from "../mailbox/schema";
|
|
12
12
|
import { getMailboxAccess } from "./access";
|
|
13
13
|
import { oneClickFetcher } from "./demo-routes";
|
|
14
|
-
import { withHeaderMetadata } from "./header-metadata";
|
|
15
14
|
import { emailListKey, emailSecurity } from "./message-view";
|
|
16
15
|
import { submitOutgoing } from "./outbound-service";
|
|
17
16
|
import { recordReportedMessage, reportSnapshot } from "./reported-messages";
|
|
@@ -61,7 +60,7 @@ async function reportOne(input: {
|
|
|
61
60
|
}
|
|
62
61
|
let reportId: string | null = null;
|
|
63
62
|
if (input.kind === "phishing") {
|
|
64
|
-
const email =
|
|
63
|
+
const email = result.email;
|
|
65
64
|
const address = email.fromJson[0]?.address ?? "";
|
|
66
65
|
const [identity, history, bodyHtml] = await Promise.all([
|
|
67
66
|
workspaceIdentity(input.env.DB),
|
|
@@ -99,7 +98,7 @@ export const mailSafetyRoutes = new Hono<AppEnv>()
|
|
|
99
98
|
const stored = await mailbox.getEmail(c.req.param("id"));
|
|
100
99
|
if (!stored || stored.direction !== "incoming") return apiError(c, 404, "NOT_FOUND", "Message not found");
|
|
101
100
|
// Stored at ingestion from the original; never taken from the client.
|
|
102
|
-
const email =
|
|
101
|
+
const email = stored;
|
|
103
102
|
const methods = email.listUnsubscribeJson;
|
|
104
103
|
const listKey = emailListKey(email);
|
|
105
104
|
if (!methods || !listKey || (!methods.httpsUrl && !methods.mailto)) {
|
package/worker/mail/uploads.ts
CHANGED
|
@@ -487,6 +487,35 @@ export async function loadComposerUpload(input: {
|
|
|
487
487
|
};
|
|
488
488
|
}
|
|
489
489
|
|
|
490
|
+
/**
|
|
491
|
+
* Sets the name and type a finished upload is sent with, for clients that
|
|
492
|
+
* upload bytes first and describe them when composing (JMAP).
|
|
493
|
+
*/
|
|
494
|
+
export async function describeComposerUpload(input: {
|
|
495
|
+
env: Bindings;
|
|
496
|
+
mailboxId: string;
|
|
497
|
+
userId: string;
|
|
498
|
+
uploadId: string;
|
|
499
|
+
filename: string;
|
|
500
|
+
contentType: string;
|
|
501
|
+
}) {
|
|
502
|
+
const keys = composerUploadKeys(input.mailboxId, input.userId, input.uploadId);
|
|
503
|
+
const meta = assertUploadOwner(
|
|
504
|
+
await readUploadMeta(input.env, keys.metadata),
|
|
505
|
+
input.userId,
|
|
506
|
+
input.mailboxId,
|
|
507
|
+
);
|
|
508
|
+
await putUploadMeta({
|
|
509
|
+
env: input.env,
|
|
510
|
+
metadataKey: keys.metadata,
|
|
511
|
+
meta: {
|
|
512
|
+
...meta,
|
|
513
|
+
filename: input.filename.trim().slice(0, 255) || meta.filename,
|
|
514
|
+
contentType: input.contentType.trim().slice(0, 255) || meta.contentType,
|
|
515
|
+
},
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
|
|
490
519
|
export async function copyStoredAttachmentToMessage(input: {
|
|
491
520
|
env: Bindings;
|
|
492
521
|
sourceKey: string;
|
package/worker/mailbox/demo.ts
CHANGED
|
@@ -353,8 +353,8 @@ function email(input: DemoInput, now: number): NewEmail {
|
|
|
353
353
|
senderIntelJson: demoSenderIntel(input, timelineAt.getTime() + 1_500),
|
|
354
354
|
aiClassificationJson: input.checks
|
|
355
355
|
? {
|
|
356
|
-
source: "
|
|
357
|
-
model: "
|
|
356
|
+
source: "ai",
|
|
357
|
+
model: "openai/gpt-6-luna",
|
|
358
358
|
processedAt: timelineAt.getTime() + 2_000,
|
|
359
359
|
...input.checks.ai,
|
|
360
360
|
}
|
package/worker/mailbox/index.ts
CHANGED
|
@@ -3,7 +3,6 @@ import { and, asc, desc, eq, inArray, isNull, lt, lte, or, sql } from "drizzle-o
|
|
|
3
3
|
import { drizzle, type DrizzleSqliteDODatabase } from "drizzle-orm/durable-sqlite";
|
|
4
4
|
import { migrate } from "drizzle-orm/durable-sqlite/migrator";
|
|
5
5
|
import migrations from "./migrations";
|
|
6
|
-
import { upgradeLegacyMailbox } from "./legacy-migrations";
|
|
7
6
|
import {
|
|
8
7
|
bumpJmapState,
|
|
9
8
|
emailPlacement as jmapEmailPlacement,
|
|
@@ -151,6 +150,11 @@ const ALARM_WAKE_DELAY_MS = 1_000;
|
|
|
151
150
|
const PRESENCE_TTL_MS = 60_000;
|
|
152
151
|
const AI_CONFIGURATION_ID = "default";
|
|
153
152
|
|
|
153
|
+
/** Browser sessions, authorized against their session on every update. */
|
|
154
|
+
const SESSION_SOCKET_TAG = "session";
|
|
155
|
+
/** JMAP EventSource streams held by the Worker; they receive the new state. */
|
|
156
|
+
const JMAP_SOCKET_TAG = "jmap";
|
|
157
|
+
|
|
154
158
|
type MailboxSocketAttachment = {
|
|
155
159
|
userId: string;
|
|
156
160
|
sessionId: string;
|
|
@@ -344,8 +348,6 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
344
348
|
this.bindings = env;
|
|
345
349
|
this.db = drizzle(ctx.storage, { schema });
|
|
346
350
|
ctx.blockConcurrencyWhile(async () => {
|
|
347
|
-
ctx.storage.transactionSync(() =>
|
|
348
|
-
upgradeLegacyMailbox(ctx.storage.sql, migrations.journal.entries[0]!.when));
|
|
349
351
|
await migrate(this.db, migrations);
|
|
350
352
|
});
|
|
351
353
|
}
|
|
@@ -354,6 +356,12 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
354
356
|
if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") {
|
|
355
357
|
return new Response("WebSocket upgrade required", { status: 426 });
|
|
356
358
|
}
|
|
359
|
+
// JMAP EventSource streams; the Worker holding one checks its token.
|
|
360
|
+
if (request.headers.get("x-openworkspace-jmap") === "1") {
|
|
361
|
+
const pair = new WebSocketPair();
|
|
362
|
+
this.state.acceptWebSocket(pair[1], [JMAP_SOCKET_TAG]);
|
|
363
|
+
return new Response(null, { status: 101, webSocket: pair[0] });
|
|
364
|
+
}
|
|
357
365
|
const userId = request.headers.get("x-openworkspace-user-id");
|
|
358
366
|
const sessionId = request.headers.get("x-openworkspace-session-id");
|
|
359
367
|
const sessionTokenHash = request.headers.get("x-openworkspace-session-token-hash");
|
|
@@ -372,7 +380,7 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
372
380
|
visibility,
|
|
373
381
|
presenceUpdatedAt: Date.now(),
|
|
374
382
|
} satisfies MailboxSocketAttachment);
|
|
375
|
-
this.state.acceptWebSocket(server);
|
|
383
|
+
this.state.acceptWebSocket(server, [SESSION_SOCKET_TAG]);
|
|
376
384
|
return new Response(null, { status: 101, webSocket: client });
|
|
377
385
|
}
|
|
378
386
|
|
|
@@ -430,7 +438,7 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
430
438
|
userId: string;
|
|
431
439
|
visibleAfter: number;
|
|
432
440
|
}) {
|
|
433
|
-
const sockets = this.state.getWebSockets().flatMap((socket) => {
|
|
441
|
+
const sockets = this.state.getWebSockets(SESSION_SOCKET_TAG).flatMap((socket) => {
|
|
434
442
|
const attachment = socketAttachment(socket);
|
|
435
443
|
if (attachment) {
|
|
436
444
|
if (
|
|
@@ -490,7 +498,7 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
490
498
|
} catch (error) {
|
|
491
499
|
// Closing forces clients to reconnect and refresh instead of silently
|
|
492
500
|
// losing the only invalidation now that there is no polling fallback.
|
|
493
|
-
for (const socket of this.state.getWebSockets()) {
|
|
501
|
+
for (const socket of this.state.getWebSockets(SESSION_SOCKET_TAG)) {
|
|
494
502
|
socket.close(1011, "Realtime authorization is temporarily unavailable");
|
|
495
503
|
}
|
|
496
504
|
throw error;
|
|
@@ -510,6 +518,25 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
510
518
|
this.state.waitUntil(this.broadcastUpdate().catch((error) => {
|
|
511
519
|
console.error("Could not authorize realtime delivery", error);
|
|
512
520
|
}));
|
|
521
|
+
this.announceJmapState();
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** Tells JMAP EventSource streams and push subscribers the new state. */
|
|
525
|
+
private announceJmapState() {
|
|
526
|
+
const mailboxId = this.state.id.name;
|
|
527
|
+
if (!mailboxId) return;
|
|
528
|
+
const state = jmapState(this.state.storage);
|
|
529
|
+
for (const socket of this.state.getWebSockets(JMAP_SOCKET_TAG)) {
|
|
530
|
+
try {
|
|
531
|
+
socket.send(state);
|
|
532
|
+
} catch {
|
|
533
|
+
socket.close(1011, "Could not deliver realtime event");
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
const job: MailboxPushJob = { type: "jmap-state", mailboxId, state, occurredAt: Date.now() };
|
|
537
|
+
this.state.waitUntil(this.bindings.PUSH_NOTIFICATIONS.send(job).catch((error) => {
|
|
538
|
+
console.error("Could not queue JMAP push", error);
|
|
539
|
+
}));
|
|
513
540
|
}
|
|
514
541
|
|
|
515
542
|
private queueIncomingNotification(email: Email) {
|
|
@@ -1349,7 +1376,7 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
1349
1376
|
console.error("Could not read workspace identity for sender checks", error);
|
|
1350
1377
|
}
|
|
1351
1378
|
const stored = email.authenticationResultsJson;
|
|
1352
|
-
const authentication = stored
|
|
1379
|
+
const authentication = stored ?? null;
|
|
1353
1380
|
const from = email.fromJson[0] ?? { address: "", name: null };
|
|
1354
1381
|
const sql = this.state.storage.sql;
|
|
1355
1382
|
const status = from.address ? senderStatuses(sql, [from.address]).get(from.address.toLocaleLowerCase()) : undefined;
|
|
@@ -1579,22 +1606,6 @@ export class MailboxDO extends DurableObject<Env> {
|
|
|
1579
1606
|
return Object.fromEntries(senderHistory(this.state.storage.sql, addresses));
|
|
1580
1607
|
}
|
|
1581
1608
|
|
|
1582
|
-
/** Lazy backfill for messages stored before header parsing existed. */
|
|
1583
|
-
setEmailHeaderMetadata(
|
|
1584
|
-
emailId: string,
|
|
1585
|
-
metadata: {
|
|
1586
|
-
authenticationResultsJson: InboundAuthentication;
|
|
1587
|
-
listUnsubscribeJson: ListUnsubscribe | null;
|
|
1588
|
-
},
|
|
1589
|
-
) {
|
|
1590
|
-
return this.db
|
|
1591
|
-
.update(emails)
|
|
1592
|
-
.set(metadata)
|
|
1593
|
-
.where(and(eq(emails.id, emailId), eq(emails.direction, "incoming")))
|
|
1594
|
-
.returning({ id: emails.id })
|
|
1595
|
-
.all().length > 0;
|
|
1596
|
-
}
|
|
1597
|
-
|
|
1598
1609
|
/** Block, trust and report state for senders, and unsubscribe records for lists. */
|
|
1599
1610
|
getMessageSafetyContext(addresses: string[], listKeys: string[]) {
|
|
1600
1611
|
const keys = [...new Set(listKeys)].slice(0, 100);
|
package/worker/mailbox/model.ts
CHANGED
|
@@ -15,15 +15,7 @@ export type {
|
|
|
15
15
|
} from "../../shared/mail-authentication";
|
|
16
16
|
export type { DeliveryFacts, SenderIntel } from "../../shared/mail-sender-intel";
|
|
17
17
|
|
|
18
|
-
|
|
19
|
-
* Rows written before header parsing carried Cloudflare GraphQL analytics.
|
|
20
|
-
* They are re-derived from the stored original on first view.
|
|
21
|
-
*/
|
|
22
|
-
export type LegacyEmailAuthentication = { source: "cloudflare" };
|
|
23
|
-
|
|
24
|
-
export type StoredEmailAuthentication =
|
|
25
|
-
| import("../../shared/mail-authentication").InboundAuthentication
|
|
26
|
-
| LegacyEmailAuthentication;
|
|
18
|
+
export type StoredEmailAuthentication = import("../../shared/mail-authentication").InboundAuthentication;
|
|
27
19
|
|
|
28
20
|
export type MailboxAiConfiguration = {
|
|
29
21
|
instructions: string;
|
|
@@ -31,8 +23,7 @@ export type MailboxAiConfiguration = {
|
|
|
31
23
|
};
|
|
32
24
|
|
|
33
25
|
export type EmailAiClassification = {
|
|
34
|
-
|
|
35
|
-
source: "ai" | "workers-ai";
|
|
26
|
+
source: "ai";
|
|
36
27
|
model: string;
|
|
37
28
|
processedAt: number;
|
|
38
29
|
spam: boolean;
|
|
@@ -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
|
-
}
|