@open-workspace/email 0.1.1 → 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.
@@ -0,0 +1,123 @@
1
+ import { rawPayload, sendPushNotification, topicFromString } from "@mmmike/web-push/send";
2
+ import { and, eq, gt, inArray, isNotNull, lte } from "drizzle-orm";
3
+ import { createDb } from "@open-workspace/core/worker/db/client.ts";
4
+ import { mailboxAccess, mailboxes } from "@open-workspace/core/worker/db/schema.ts";
5
+ import { createId } from "@open-workspace/core/worker/lib/ids.ts";
6
+ import { jmapPushSubscriptions } from "../db/schema";
7
+
8
+ /** Data types whose state a mailbox account reports; one state covers them all. */
9
+ export const JMAP_PUSH_TYPES = ["Email", "Mailbox", "Thread", "EmailDelivery"] as const;
10
+
11
+ /** Subscriptions live a week unless the client asks for less, then renew. */
12
+ const MAX_SUBSCRIPTION_MS = 7 * 24 * 60 * 60 * 1_000;
13
+ /** State changes are worth little once a client resyncs anyway. */
14
+ const STATE_CHANGE_TTL_SECONDS = 24 * 60 * 60;
15
+
16
+ export type PushVapid = { publicKey: string; privateKey: string; subject: string };
17
+
18
+ type Subscription = typeof jmapPushSubscriptions.$inferSelect;
19
+
20
+ export function stateChange(changed: Record<string, string>) {
21
+ return {
22
+ "@type": "StateChange",
23
+ changed: Object.fromEntries(Object.entries(changed).map(([accountId, state]) => [
24
+ accountId,
25
+ Object.fromEntries(JMAP_PUSH_TYPES.map((type) => [type, state])),
26
+ ])),
27
+ };
28
+ }
29
+
30
+ export function subscriptionExpiry(requested: unknown, now = Date.now()) {
31
+ const latest = now + MAX_SUBSCRIPTION_MS;
32
+ const asked = typeof requested === "string" ? Date.parse(requested) : Number.NaN;
33
+ return new Date(Number.isFinite(asked) ? Math.max(now, Math.min(asked, latest)) : latest);
34
+ }
35
+
36
+ /**
37
+ * POSTs a JMAP push object to a subscription: Web Push encrypted (RFC 8291)
38
+ * and VAPID-signed when the client gave keys, plain JSON otherwise.
39
+ * Returns false when the push service says the subscription is gone.
40
+ */
41
+ export async function postToSubscription(
42
+ subscription: Pick<Subscription, "url" | "p256dh" | "auth">,
43
+ body: unknown,
44
+ vapid: PushVapid | null,
45
+ options: { ttl: number; topic?: string },
46
+ ) {
47
+ if (subscription.p256dh && subscription.auth) {
48
+ if (!vapid) throw new Error("Web Push is not configured");
49
+ return sendPushNotification(
50
+ { endpoint: subscription.url, keys: { p256dh: subscription.p256dh, auth: subscription.auth } },
51
+ rawPayload(JSON.stringify(body)),
52
+ vapid,
53
+ { ttl: options.ttl, urgency: "normal", ...(options.topic ? { topic: options.topic } : {}) },
54
+ );
55
+ }
56
+ const response = await fetch(subscription.url, {
57
+ method: "POST",
58
+ headers: {
59
+ "content-type": "application/json; charset=utf-8",
60
+ ttl: String(options.ttl),
61
+ ...(options.topic ? { topic: options.topic } : {}),
62
+ },
63
+ body: JSON.stringify(body),
64
+ signal: AbortSignal.timeout(30_000),
65
+ });
66
+ if (response.status === 404 || response.status === 410) return false;
67
+ if (!response.ok) throw new Error(`Push endpoint answered ${response.status}`);
68
+ return true;
69
+ }
70
+
71
+ export function newVerificationCode() {
72
+ return createId("pvc");
73
+ }
74
+
75
+ /** Sends the PushVerification object a new subscription is confirmed with. */
76
+ export async function sendVerification(subscription: Subscription, vapid: PushVapid | null) {
77
+ await postToSubscription(subscription, {
78
+ "@type": "PushVerification",
79
+ pushSubscriptionId: subscription.id,
80
+ verificationCode: subscription.verificationCode,
81
+ }, vapid, { ttl: 60 * 60 });
82
+ }
83
+
84
+ /**
85
+ * Tells every verified subscription of someone who can open the mailbox that
86
+ * its state moved. Expired subscriptions are dropped on the way.
87
+ */
88
+ export async function deliverJmapStateChange(
89
+ env: Env,
90
+ input: { mailboxId: string; state: string },
91
+ vapid: PushVapid,
92
+ ) {
93
+ const db = createDb(env.DB);
94
+ const now = new Date();
95
+ await db.delete(jmapPushSubscriptions).where(lte(jmapPushSubscriptions.expiresAt, now));
96
+ const targets = await db
97
+ .select({ subscription: jmapPushSubscriptions })
98
+ .from(jmapPushSubscriptions)
99
+ .innerJoin(mailboxAccess, eq(mailboxAccess.userId, jmapPushSubscriptions.userId))
100
+ .innerJoin(mailboxes, eq(mailboxes.id, mailboxAccess.mailboxId))
101
+ .where(and(
102
+ eq(mailboxAccess.mailboxId, input.mailboxId),
103
+ eq(mailboxes.delivery, "inbox"),
104
+ isNotNull(jmapPushSubscriptions.verifiedAt),
105
+ gt(jmapPushSubscriptions.expiresAt, now),
106
+ ));
107
+ const gone: string[] = [];
108
+ await Promise.all(targets.map(async ({ subscription }) => {
109
+ const types = subscription.typesJson;
110
+ if (types && !types.some((type) => (JMAP_PUSH_TYPES as readonly string[]).includes(type))) return;
111
+ try {
112
+ const delivered = await postToSubscription(subscription, stateChange({ [input.mailboxId]: input.state }), vapid, {
113
+ ttl: STATE_CHANGE_TTL_SECONDS,
114
+ // A newer state replaces an undelivered older one.
115
+ topic: await topicFromString(`jmap:${subscription.id}:${input.mailboxId}`),
116
+ });
117
+ if (!delivered) gone.push(subscription.id);
118
+ } catch (error) {
119
+ console.error("JMAP push delivery failed", error instanceof Error ? error.message : String(error));
120
+ }
121
+ }));
122
+ if (gone.length) await db.delete(jmapPushSubscriptions).where(inArray(jmapPushSubscriptions.id, gone));
123
+ }
@@ -0,0 +1,277 @@
1
+ import { and, eq } from "drizzle-orm";
2
+ import { Hono, type Context } from "hono";
3
+ import { JMAP_SCOPE } from "@open-workspace/core/shared/oidc.ts";
4
+ import { bearerToken } from "@open-workspace/core/worker/auth/middleware.ts";
5
+ import { createDb } from "@open-workspace/core/worker/db/client.ts";
6
+ import { mailboxAddressSql } from "@open-workspace/core/worker/db/mailboxes.ts";
7
+ import { domains, mailboxAccess, mailboxes } from "@open-workspace/core/worker/db/schema.ts";
8
+ import type { AppEnv } from "@open-workspace/core/worker/env.ts";
9
+ import { checkRateLimit } from "@open-workspace/core/worker/lib/rate-limit.ts";
10
+ import {
11
+ authenticateAccessToken,
12
+ jmapProtectedResourceMetadataUrl,
13
+ } from "@open-workspace/core/worker/oidc/mcp-clients.ts";
14
+ import { MAX_COMPOSER_ATTACHMENT_BYTES } from "../../shared/mail";
15
+ import { mailboxStub } from "../mailbox";
16
+ import { vapidConfiguration } from "../mail/push-notifications";
17
+ import {
18
+ createComposerUploadIntent,
19
+ finalizeComposerUpload,
20
+ loadComposerUpload,
21
+ storeComposerUploadContent,
22
+ UploadValidationError,
23
+ } from "../mail/uploads";
24
+ import { jmapEventStream } from "./eventsource";
25
+ import { JmapError, runJmapRequest, UPLOAD_BLOB, type JmapAccount, type JmapContext } from "./methods";
26
+
27
+ const CAPABILITIES = {
28
+ "urn:ietf:params:jmap:core": {
29
+ maxSizeUpload: MAX_COMPOSER_ATTACHMENT_BYTES,
30
+ maxConcurrentUpload: 1,
31
+ maxSizeRequest: 10_000_000,
32
+ maxConcurrentRequests: 4,
33
+ maxCallsInRequest: 32,
34
+ maxObjectsInGet: 500,
35
+ maxObjectsInSet: 500,
36
+ collationAlgorithms: ["i;unicode-casemap"],
37
+ },
38
+ "urn:ietf:params:jmap:mail": {},
39
+ "urn:ietf:params:jmap:submission": {},
40
+ };
41
+
42
+ type JmapUser = { id: string; name: string; clientId: string; token: string };
43
+ type JmapEnv = AppEnv & { Variables: AppEnv["Variables"] & { jmapUser: JmapUser } };
44
+
45
+ function problem(c: Context, status: 400 | 401 | 403 | 404 | 413 | 429, type: string, detail: string) {
46
+ return c.json({ type, status, detail }, status, { "content-type": "application/problem+json" });
47
+ }
48
+
49
+ /** The mailboxes this person can open; each is a JMAP account. */
50
+ export async function jmapAccounts(env: Env, userId: string): Promise<JmapAccount[]> {
51
+ const rows = await createDb(env.DB)
52
+ .select({
53
+ id: mailboxes.id,
54
+ address: mailboxAddressSql,
55
+ displayName: mailboxes.displayName,
56
+ ownerUserId: mailboxes.ownerUserId,
57
+ isPrimary: mailboxes.isPrimary,
58
+ canSend: mailboxAccess.canSend,
59
+ })
60
+ .from(mailboxAccess)
61
+ .innerJoin(mailboxes, eq(mailboxAccess.mailboxId, mailboxes.id))
62
+ .innerJoin(domains, eq(mailboxes.domainId, domains.id))
63
+ .where(and(eq(mailboxAccess.userId, userId), eq(mailboxes.delivery, "inbox")));
64
+ return rows.map((row) => ({
65
+ ...row,
66
+ isPersonal: row.ownerUserId === userId,
67
+ }));
68
+ }
69
+
70
+ function sessionObject(
71
+ origin: string,
72
+ user: { id: string; name: string },
73
+ accounts: JmapAccount[],
74
+ vapidPublicKey: string | null,
75
+ ) {
76
+ const primary = accounts.find((account) => account.isPersonal && account.isPrimary)
77
+ ?? accounts.find((account) => account.isPersonal)
78
+ ?? accounts[0];
79
+ return {
80
+ capabilities: {
81
+ ...CAPABILITIES,
82
+ // RFC 9749: push services that require VAPID accept our pushes.
83
+ ...(vapidPublicKey ? { "urn:ietf:params:jmap:webpush-vapid": { applicationServerKey: vapidPublicKey } } : {}),
84
+ },
85
+ accounts: Object.fromEntries(accounts.map((account) => [account.id, {
86
+ name: account.address,
87
+ isPersonal: account.isPersonal,
88
+ isReadOnly: false,
89
+ accountCapabilities: {
90
+ "urn:ietf:params:jmap:mail": {
91
+ maxMailboxesPerEmail: 1,
92
+ maxMailboxDepth: 1,
93
+ maxSizeMailboxName: 80,
94
+ maxSizeAttachmentsPerEmail: MAX_COMPOSER_ATTACHMENT_BYTES,
95
+ emailQuerySortOptions: ["receivedAt", "sentAt"],
96
+ mayCreateTopLevelMailbox: false,
97
+ },
98
+ ...(account.canSend
99
+ ? { "urn:ietf:params:jmap:submission": { maxDelayedSend: 0, submissionExtensions: {} } }
100
+ : {}),
101
+ },
102
+ }])),
103
+ primaryAccounts: primary
104
+ ? {
105
+ "urn:ietf:params:jmap:mail": primary.id,
106
+ "urn:ietf:params:jmap:submission": primary.id,
107
+ }
108
+ : {},
109
+ username: primary?.address ?? user.name,
110
+ apiUrl: `${origin}/jmap/api`,
111
+ downloadUrl: `${origin}/jmap/download/{accountId}/{blobId}/{name}?type={type}`,
112
+ uploadUrl: `${origin}/jmap/upload/{accountId}`,
113
+ eventSourceUrl: `${origin}/jmap/eventsource?types={types}&closeafter={closeafter}&ping={ping}`,
114
+ state: String(accounts.length),
115
+ };
116
+ }
117
+
118
+ const requireJmapAuth = async (c: Context<JmapEnv>, next: () => Promise<void>) => {
119
+ const token = bearerToken(c.req.raw);
120
+ const identity = token
121
+ ? await authenticateAccessToken(createDb(c.env.DB), token, JMAP_SCOPE)
122
+ : null;
123
+ if (!identity) {
124
+ c.header("www-authenticate", [
125
+ `Bearer resource_metadata="${jmapProtectedResourceMetadataUrl(new URL(c.req.url).origin)}"`,
126
+ `scope="${JMAP_SCOPE}"`,
127
+ ...(token ? ['error="invalid_token"'] : []),
128
+ ].join(", "));
129
+ return problem(c, 401, "about:blank", token ? "The access token is invalid or expired" : "Sign in with OAuth");
130
+ }
131
+ c.set("jmapUser", { id: identity.user.id, name: identity.user.name, clientId: identity.clientId, token: token! });
132
+ await next();
133
+ };
134
+
135
+ /**
136
+ * JMAP (RFC 8620) for mail (RFC 8621) with OAuth bearer tokens carrying the
137
+ * jmap scope. Each mailbox the person can open is a JMAP account.
138
+ */
139
+ export const jmapRoutes = new Hono<JmapEnv>()
140
+ .get("/.well-known/jmap", (c) => c.redirect("/jmap/session", 302))
141
+ .use("/jmap/*", requireJmapAuth)
142
+ .get("/jmap/session", async (c) => {
143
+ const user = c.get("jmapUser");
144
+ const vapid = await vapidConfiguration(c.env);
145
+ return c.json(sessionObject(new URL(c.req.url).origin, user, await jmapAccounts(c.env, user.id), vapid?.publicKey ?? null));
146
+ })
147
+ .post("/jmap/api", async (c) => {
148
+ if (!c.req.header("content-type")?.toLowerCase().startsWith("application/json")) {
149
+ return problem(c, 400, "urn:ietf:params:jmap:error:notJSON", "The request must be JSON");
150
+ }
151
+ let body: unknown;
152
+ try {
153
+ body = await c.req.json();
154
+ } catch {
155
+ return problem(c, 400, "urn:ietf:params:jmap:error:notJSON", "The request is not valid JSON");
156
+ }
157
+ const user = c.get("jmapUser");
158
+ const context: JmapContext = {
159
+ env: c.env,
160
+ user: { id: user.id, name: user.name },
161
+ clientId: user.clientId,
162
+ vapid: await vapidConfiguration(c.env),
163
+ accounts: await jmapAccounts(c.env, user.id),
164
+ requestUrl: c.req.url,
165
+ defer: (task) => c.executionCtx.waitUntil(task),
166
+ };
167
+ try {
168
+ return c.json(await runJmapRequest(context, body));
169
+ } catch (error) {
170
+ if (error instanceof JmapError) return problem(c, 400, error.type, error.message);
171
+ throw error;
172
+ }
173
+ })
174
+ .get("/jmap/download/:accountId/:blobId/:name", async (c) => {
175
+ const user = c.get("jmapUser");
176
+ const account = (await jmapAccounts(c.env, user.id)).find((item) => item.id === c.req.param("accountId"));
177
+ if (!account) return problem(c, 404, "about:blank", "Account not found");
178
+ const blobId = c.req.param("blobId");
179
+ const upload = UPLOAD_BLOB.exec(blobId);
180
+ const blob = /^(raw|att)~([^~]+)(?:~(.+))?$/u.exec(blobId);
181
+ let key: string | null | undefined;
182
+ if (upload) {
183
+ key = await loadComposerUpload({ env: c.env, mailboxId: account.id, userId: user.id, uploadId: upload[1]! })
184
+ .then((found) => found.r2Key, () => null);
185
+ } else if (blob) {
186
+ const [, kind, emailId, attachmentId] = blob;
187
+ const email = await mailboxStub(c.env, account.id).getEmail(emailId!);
188
+ key = kind === "raw"
189
+ ? email?.rawMimeR2Key
190
+ : email?.attachmentsJson.find((attachment) => attachment.id === attachmentId)?.r2Key;
191
+ }
192
+ const object = key ? await c.env.MAIL_STORAGE.get(key) : null;
193
+ if (!object) return problem(c, 404, "about:blank", "Blob not found");
194
+ const type = c.req.query("type")
195
+ || object.httpMetadata?.contentType
196
+ || (blob?.[1] === "raw" ? "message/rfc822" : "application/octet-stream");
197
+ return new Response(object.body, {
198
+ headers: {
199
+ "content-type": type,
200
+ "content-disposition": `attachment; filename*=UTF-8''${encodeURIComponent(c.req.param("name"))}`,
201
+ "cache-control": "private, immutable, max-age=31536000",
202
+ },
203
+ });
204
+ })
205
+ .post("/jmap/upload/:accountId", async (c) => {
206
+ const user = c.get("jmapUser");
207
+ const account = (await jmapAccounts(c.env, user.id)).find((item) => item.id === c.req.param("accountId"));
208
+ if (!account) return problem(c, 404, "about:blank", "Account not found");
209
+ // Uploads become attachments of sent mail, so they need send access.
210
+ if (!account.canSend) return problem(c, 403, "about:blank", "This account cannot send");
211
+ const rate = await checkRateLimit(c.env.DB, {
212
+ action: "mail-upload",
213
+ identifier: user.id,
214
+ limit: 30,
215
+ windowMs: 60_000,
216
+ });
217
+ if (!rate.allowed) {
218
+ c.header("retry-after", String(rate.retryAfterSeconds));
219
+ return problem(c, 429, "about:blank", "Too many uploads");
220
+ }
221
+ const contentType = c.req.header("content-type")?.trim() || "application/octet-stream";
222
+ const declared = Number(c.req.header("content-length"));
223
+ // Without a length, buffer the body to learn it; uploads are bounded anyway.
224
+ let body: ReadableStream<Uint8Array> | ArrayBuffer | null = c.req.raw.body;
225
+ let size = declared;
226
+ if (!Number.isSafeInteger(declared) || declared < 0) {
227
+ body = await c.req.arrayBuffer();
228
+ size = body.byteLength;
229
+ }
230
+ if (size > MAX_COMPOSER_ATTACHMENT_BYTES) {
231
+ return problem(c, 413, "urn:ietf:params:jmap:error:limit", "The upload is too large");
232
+ }
233
+ try {
234
+ const intent = await createComposerUploadIntent({
235
+ env: c.env,
236
+ requestOrigin: new URL(c.req.url).origin,
237
+ mailboxId: account.id,
238
+ userId: user.id,
239
+ filename: "upload",
240
+ contentType,
241
+ size,
242
+ });
243
+ await storeComposerUploadContent({
244
+ env: c.env,
245
+ mailboxId: account.id,
246
+ userId: user.id,
247
+ uploadId: intent.id,
248
+ body,
249
+ contentType,
250
+ contentLength: size,
251
+ });
252
+ const upload = await finalizeComposerUpload({
253
+ env: c.env,
254
+ mailboxId: account.id,
255
+ userId: user.id,
256
+ uploadId: intent.id,
257
+ defer: (task) => c.executionCtx.waitUntil(task),
258
+ });
259
+ return c.json({ accountId: account.id, blobId: `upl~${upload.id}`, type: upload.contentType, size: upload.size }, 201);
260
+ } catch (error) {
261
+ if (error instanceof UploadValidationError) return problem(c, 400, "about:blank", error.message);
262
+ throw error;
263
+ }
264
+ })
265
+ .get("/jmap/eventsource", async (c) => {
266
+ const user = c.get("jmapUser");
267
+ return jmapEventStream({
268
+ env: c.env,
269
+ accounts: await jmapAccounts(c.env, user.id),
270
+ types: c.req.query("types") ?? "*",
271
+ closeAfterState: c.req.query("closeafter") === "state",
272
+ pingSeconds: Number(c.req.query("ping") ?? 0),
273
+ // The stream outlives the request check; the token is checked again on each ping.
274
+ stillAuthorized: async () => Boolean(await authenticateAccessToken(createDb(c.env.DB), user.token, JMAP_SCOPE)),
275
+ defer: (task) => c.executionCtx.waitUntil(task),
276
+ });
277
+ });
@@ -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?.source === "headers" && stored.version === 1 ? stored : null;
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
- * Messages stored before sender intelligence existed get it on first view,
48
- * using the same lookups as ingestion. A result where every lookup failed is
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
- const subject = env.VAPID_SUBJECT;
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 === "dispatch") await dispatchPushJob(env, job);
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() || "openworkspace";
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
 
@@ -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, withHeaderMetadata, withSenderIntel } from "./header-metadata";
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
- await withHeaderMetadata(c.env, mailbox, stored),
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 = await withHeaderMetadata(c.env, mailbox, stored);
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 = await withHeaderMetadata(input.env, mailbox, result.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 = await withHeaderMetadata(c.env, mailbox, stored);
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)) {
@@ -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;
@@ -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: "workers-ai",
357
- model: "@cf/meta/llama-3.1-8b-instruct",
356
+ source: "ai",
357
+ model: "openai/gpt-6-luna",
358
358
  processedAt: timelineAt.getTime() + 2_000,
359
359
  ...input.checks.ai,
360
360
  }