@open-workspace/email 0.5.0 → 0.5.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-workspace/email",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Team mail for OpenWorkspace: personal and shared inboxes, mailing lists, previews, safety, and AI.",
5
5
  "keywords": [
6
6
  "alchemy",
@@ -53,63 +53,63 @@
53
53
  },
54
54
  "dependencies": {
55
55
  "@hono/zod-validator": "0.9.1",
56
- "@hookform/resolvers": "7.0.6",
56
+ "@hookform/resolvers": "7.0.10",
57
57
  "@mmmike/web-push": "1.5.0",
58
58
  "@modelcontextprotocol/server": "2.4.0",
59
- "@tanstack/react-query": "5.107.1",
60
- "@tiptap/extension-placeholder": "3.33.1",
61
- "@tiptap/extension-table": "3.33.1",
62
- "@tiptap/pm": "3.33.1",
63
- "@tiptap/react": "3.33.1",
64
- "@tiptap/starter-kit": "3.33.1",
59
+ "@tanstack/react-query": "5.108.4",
60
+ "@tiptap/extension-placeholder": "3.35.1",
61
+ "@tiptap/extension-table": "3.35.1",
62
+ "@tiptap/pm": "3.35.1",
63
+ "@tiptap/react": "3.35.1",
64
+ "@tiptap/starter-kit": "3.35.1",
65
65
  "aws4fetch": "1.0.20",
66
66
  "date-fns": "4.4.0",
67
- "dompurify": "3.4.17",
67
+ "dompurify": "3.5.0",
68
68
  "drizzle-orm": "0.45.4",
69
- "hono": "4.13.17",
69
+ "hono": "4.13.23",
70
70
  "html-to-text": "10.0.1",
71
71
  "linkifyjs": "4.4.0",
72
- "lucide-react": "1.71.0",
72
+ "lucide-react": "1.84.0",
73
73
  "nuqs": "2.10.3",
74
74
  "pdfjs-dist": "6.5.438",
75
75
  "postal-mime": "4.2.1",
76
76
  "react": "19.3.1",
77
77
  "react-hook-form": "7.92.0",
78
- "react-router": "8.5.1",
78
+ "react-router": "8.5.3",
79
79
  "sanitize-html": "2.18.2",
80
80
  "sonner": "2.0.8",
81
- "tldts": "7.4.21",
81
+ "tldts": "7.6.4",
82
82
  "zod": "4.6.7"
83
83
  },
84
84
  "devDependencies": {
85
- "@alchemy.run/cloudflare": "2.0.0-beta.85",
86
- "@alchemy.run/test": "2.0.0-beta.85",
87
- "@effect/platform-bun": "4.1.3",
88
- "@effect/platform-node": "4.1.3",
89
- "@open-workspace/core": "0.5.0",
90
- "@open-workspace/create": "0.5.0",
91
- "@types/bun": "1.4.4",
85
+ "@alchemy.run/cloudflare": "2.0.0-beta.87",
86
+ "@alchemy.run/test": "2.0.0-beta.87",
87
+ "@effect/platform-bun": "4.1.7",
88
+ "@effect/platform-node": "4.1.7",
89
+ "@open-workspace/core": "0.5.2",
90
+ "@open-workspace/create": "0.5.2",
91
+ "@types/bun": "1.4.5",
92
92
  "@types/html-to-text": "9.0.4",
93
93
  "@types/jsdom": "30.0.0",
94
- "@types/node": "26.6.6",
95
- "@types/react": "19.3.0",
94
+ "@types/node": "26.6.11",
95
+ "@types/react": "19.3.3",
96
96
  "@types/react-dom": "19.3.0",
97
97
  "@types/sanitize-html": "2.16.2",
98
- "ai": "7.0.166",
99
- "alchemy": "2.0.0-beta.85",
98
+ "ai": "7.0.185",
99
+ "alchemy": "2.0.0-beta.87",
100
100
  "drizzle-kit": "0.31.11",
101
- "effect": "4.1.3",
102
- "jsdom": "30.1.3",
103
- "openid-client": "6.8.9",
104
- "playwright": "1.65.0",
105
- "standardwebhooks": "1.1.1",
101
+ "effect": "4.1.7",
102
+ "jsdom": "31.0.1",
103
+ "openid-client": "6.9.1",
104
+ "playwright": "1.65.1",
105
+ "standardwebhooks": "1.3.0",
106
106
  "typescript": "7.0.2",
107
- "vite": "8.3.7"
107
+ "vite": "8.4.0"
108
108
  },
109
109
  "peerDependencies": {
110
- "@alchemy.run/cloudflare": "2.0.0-beta.85",
111
- "@open-workspace/core": "0.5.0",
112
- "alchemy": "2.0.0-beta.85",
113
- "effect": "4.1.3"
110
+ "@alchemy.run/cloudflare": "2.0.0-beta.87",
111
+ "@open-workspace/core": "0.5.2",
112
+ "alchemy": "2.0.0-beta.87",
113
+ "effect": "4.1.7"
114
114
  }
115
115
  }
@@ -99,7 +99,11 @@ export type SecurityWarning =
99
99
  }
100
100
  | { kind: "display_name_impersonation"; severity: "danger"; name: string }
101
101
  | { kind: "embedded_address"; severity: "caution"; claimed: string }
102
- | { kind: "unverified_sender"; severity: "caution"; domain: string | null }
102
+ | {
103
+ kind: "unverified_sender";
104
+ severity: "caution" | "danger";
105
+ domain: string | null;
106
+ }
103
107
  /** Replies go to another organization than the one in From. */
104
108
  | {
105
109
  kind: "reply_to_mismatch";
@@ -39,11 +39,14 @@ function AddressAutoReplySection({
39
39
  return (
40
40
  <div className="space-y-2">
41
41
  <h3 className="text-sm leading-none font-medium">Auto-reply</h3>
42
- <MailboxAutoReply
43
- mailbox={{ id: address.mailboxId, address: address.address }}
44
- uploadMailboxId={uploadMailbox?.id}
45
- section
46
- />
42
+ {/* Its editor keeps the upload mailbox it first had. */}
43
+ {mailboxes.isPending ? null : (
44
+ <MailboxAutoReply
45
+ mailbox={{ id: address.mailboxId, address: address.address }}
46
+ uploadMailboxId={uploadMailbox?.id}
47
+ section
48
+ />
49
+ )}
47
50
  </div>
48
51
  );
49
52
  }
package/src/client.tsx CHANGED
@@ -188,7 +188,9 @@ const mail: ClientModule = {
188
188
  background: mailBackground.Component,
189
189
  preload: async () => {
190
190
  // Message bodies need the sanitizer (DOMPurify); the screen need not wait for it.
191
- loadSanitizer().catch(() => undefined);
191
+ loadSanitizer().catch((error) =>
192
+ console.warn("Could not preload the sanitizer", error)
193
+ );
192
194
 
193
195
  await Promise.all([mailboxRoute.preload(), mailBackground.preload()]);
194
196
  },
@@ -341,7 +341,7 @@ export function ComposeWindow({
341
341
  }
342
342
 
343
343
  async function discardDraft() {
344
- if (busy) return;
344
+ if (busy || closing) return;
345
345
 
346
346
  if (
347
347
  !(await confirm({
@@ -354,9 +354,13 @@ export function ComposeWindow({
354
354
  return;
355
355
  }
356
356
 
357
+ // Closing meanwhile would close it twice.
358
+ setClosing(true);
359
+
357
360
  try {
358
361
  await autosave.discard();
359
362
  } catch (error) {
363
+ setClosing(false);
360
364
  toast.error(
361
365
  error instanceof Error ? error.message : "Could not discard the draft"
362
366
  );
@@ -80,9 +80,9 @@ class AssetBookmarkStep extends Step {
80
80
  try {
81
81
  Step.jsonID("openworkspaceAssetBookmark", AssetBookmarkStep);
82
82
  } catch (error) {
83
- if (
84
- !(error instanceof RangeError && error.message.includes("Duplicate use"))
85
- ) {
83
+ if (!(
84
+ error instanceof RangeError && error.message.includes("Duplicate use")
85
+ )) {
86
86
  throw error;
87
87
  }
88
88
  }
@@ -119,8 +119,8 @@ function MailboxSheet({
119
119
  if (!open) return;
120
120
 
121
121
  for (const id of otherIds.split(" ").filter(Boolean)) {
122
- void prefetchMailboxSwitch(queryClient, id, folder).catch(
123
- () => undefined
122
+ void prefetchMailboxSwitch(queryClient, id, folder).catch((error) =>
123
+ console.warn("Mailbox prefetch failed", error)
124
124
  );
125
125
  }
126
126
  }, [open, otherIds, folder, queryClient]);
@@ -75,6 +75,6 @@ export function prefetchMail({
75
75
  });
76
76
  }
77
77
  },
78
- () => undefined
78
+ (error) => console.warn("Mail prefetch failed", error)
79
79
  );
80
80
  }
@@ -289,7 +289,9 @@ function warningHeadline(warning: SecurityWarning, message: MessageDetail) {
289
289
  }
290
290
 
291
291
  case "unverified_sender": {
292
- return `We couldn't verify that this message came from ${warning.domain ?? message.fromAddress}.`;
292
+ return warning.severity === "danger"
293
+ ? `This message claims to be from ${message.fromAddress} in your workspace, but we couldn't verify it. Someone outside may be impersonating them.`
294
+ : `We couldn't verify that this message came from ${warning.domain ?? message.fromAddress}.`;
293
295
  }
294
296
 
295
297
  case "reply_to_mismatch": {
@@ -18,9 +18,10 @@ function updateAppBadge(count: number) {
18
18
  const operation =
19
19
  count > 0 ? navigator.setAppBadge?.(count) : navigator.clearAppBadge?.();
20
20
 
21
- void operation?.catch(() => {
22
- // Badging is optional and can be denied independently of notifications.
23
- });
21
+ // Badging is optional and can be denied independently of notifications.
22
+ void operation?.catch((error) =>
23
+ console.debug("Could not update the app badge", error)
24
+ );
24
25
  }
25
26
 
26
27
  export function UnreadDocumentIndicator() {
@@ -124,8 +124,9 @@ export function useComposerAttachmentPreflight(
124
124
  const resolvePlan = useEffectEvent((signal: AbortSignal) => {
125
125
  if (!hasAttachments || assets.some((asset) => !asset.uploadId)) return;
126
126
  void resolveComposerAttachmentPlan(session, context, assets, signal).catch(
127
- () => {
127
+ (error) => {
128
128
  // Background preflight is advisory. Final submission reports failures.
129
+ if (!signal.aborted) console.warn("Attachment preflight failed", error);
129
130
  }
130
131
  );
131
132
  });
@@ -253,12 +253,10 @@ export function useComposerCore(input: {
253
253
  event.dataTransfer.dropEffect = busy ? "none" : "copy";
254
254
  },
255
255
  onDragLeave: (event: DragEvent<HTMLFormElement>) => {
256
- if (
257
- !(
258
- event.relatedTarget instanceof Node &&
259
- event.currentTarget.contains(event.relatedTarget)
260
- )
261
- ) {
256
+ if (!(
257
+ event.relatedTarget instanceof Node &&
258
+ event.currentTarget.contains(event.relatedTarget)
259
+ )) {
262
260
  setDragging(false);
263
261
  }
264
262
  },
@@ -644,6 +644,9 @@ export function useMailController(route: MailRoute) {
644
644
  * stays open.
645
645
  */
646
646
  function followOwnChange(places: readonly ConversationPlace[]) {
647
+ // Answered after switching mailboxes: that screen is gone.
648
+ if (!live.current.mounted) return;
649
+
647
650
  const open = live.current.route.conversationId;
648
651
  const place = places.find((item) => item.from === open && item.left);
649
652
 
@@ -666,6 +669,7 @@ export function useMailController(route: MailRoute) {
666
669
  const now = live.current.route;
667
670
 
668
671
  return (
672
+ live.current.mounted &&
669
673
  !now.conversationId &&
670
674
  now.mailboxId === list.mailboxId &&
671
675
  // A list's path names Inbox by leaving the folder out.
@@ -80,7 +80,10 @@ export async function jmapEventStream(input: {
80
80
  }
81
81
  }
82
82
 
83
- writer.close().catch(() => {});
83
+ // Closing fails when the client has already gone.
84
+ writer
85
+ .close()
86
+ .catch((error) => console.debug("Event stream already closed", error));
84
87
  finished();
85
88
  };
86
89
 
@@ -299,7 +299,17 @@ export async function runJmapRequest(
299
299
 
300
300
  state.responses.push([name, result, callId], ...state.after.splice(0));
301
301
  } catch (error) {
302
- if (!(error instanceof MethodError)) throw error;
302
+ // A call that failed unexpectedly answers serverFail (RFC 8620
303
+ // §3.6.2), so the answers to earlier calls, a sent message's among
304
+ // them, still reach the client and it doesn't send it again.
305
+ state.after.splice(0);
306
+
307
+ if (!(error instanceof MethodError)) {
308
+ console.error(`JMAP ${name} failed`, error);
309
+ state.responses.push(["error", { type: "serverFail" }, callId]);
310
+ continue;
311
+ }
312
+
303
313
  state.responses.push([
304
314
  "error",
305
315
  { type: error.type, description: error.message },
@@ -400,7 +400,25 @@ export async function sendArchived(
400
400
  : null;
401
401
 
402
402
  const recorded = entry ? await recordEntry(env, entry) : false;
403
- const result = await env.EMAIL.send(message);
403
+ let result: Awaited<ReturnType<Env["EMAIL"]["send"]>>;
404
+
405
+ try {
406
+ result = await env.EMAIL.send(message);
407
+ } catch (error) {
408
+ // No copy of this attempt will ever exist: the row would wait a week and
409
+ // then show as a lost copy. A resend is an attempt of its own.
410
+ if (recorded) {
411
+ await createDb(env.DB)
412
+ .delete(mailArchiveEntries)
413
+ .where(eq(mailArchiveEntries.id, sent.id))
414
+ .catch((cause: unknown) => {
415
+ console.error(`Could not drop ${sent.id} from the archive`, cause);
416
+ });
417
+ }
418
+
419
+ throw error;
420
+ }
421
+
404
422
  onSent?.(result);
405
423
 
406
424
  if (!entry && !sent.rawKey) {
@@ -319,7 +319,8 @@ function matchSignature(
319
319
  type Verdict = Pick<InboundAuthentication, "verdict" | "verdictReason">;
320
320
 
321
321
  function verdictFor(
322
- input: Pick<InboundAuthentication, "spf" | "dkim" | "dmarc" | "arc">
322
+ input: Pick<InboundAuthentication, "spf" | "dkim" | "dmarc" | "arc">,
323
+ fromDomain: string | null
323
324
  ) {
324
325
  const alignedDkimPass = input.dkim.some(
325
326
  (dkim) => dkim.result === "pass" && dkim.aligned
@@ -327,7 +328,12 @@ function verdictFor(
327
328
 
328
329
  const alignedSpfPass = input.spf?.result === "pass" && input.spf.aligned;
329
330
 
330
- if (input.dmarc?.result === "pass") {
331
+ // DMARC passed for the From the app shows, not another one Cloudflare
332
+ // read (two From headers, or several addresses in one).
333
+ if (
334
+ input.dmarc?.result === "pass" &&
335
+ input.dmarc.headerFrom?.toLowerCase() === fromDomain?.toLowerCase()
336
+ ) {
331
337
  return {
332
338
  verdict: "verified",
333
339
  verdictReason: "dmarc_pass",
@@ -692,7 +698,7 @@ export function parseInboundAuthentication(input: {
692
698
  }
693
699
  : null,
694
700
  spamScore: score,
695
- ...verdictFor(parts),
701
+ ...verdictFor(parts, fromDomain),
696
702
  upstream,
697
703
  ignoredCloudflareClaims,
698
704
  trustedHeader: authenticationResults.field.value.slice(
@@ -12,7 +12,11 @@ import { Hono } from "hono";
12
12
  import type { Context } from "hono";
13
13
  import { z } from "zod";
14
14
 
15
- import { MAIL_ORGANIZE_SCOPE, MAIL_READ_SCOPE } from "../../shared/permissions";
15
+ import {
16
+ MAIL_ORGANIZE_SCOPE,
17
+ MAIL_READ_SCOPE,
18
+ MAIL_SEND_SCOPE,
19
+ } from "../../shared/permissions";
16
20
  import { mailboxStub } from "../mailbox";
17
21
  import type { AutoReplyMessage, AutoReplySettings } from "../mailbox/schema";
18
22
  import {
@@ -118,9 +122,10 @@ export const autoReplyRoutes = new Hono<AppEnv>()
118
122
  )
119
123
  );
120
124
  })
125
+ // Its text goes out as the mailbox, so an app sets it only if it may send.
121
126
  .put(
122
127
  "/mailboxes/:id/auto-reply",
123
- oauthScope(MAIL_ORGANIZE_SCOPE),
128
+ oauthScope(MAIL_ORGANIZE_SCOPE, MAIL_SEND_SCOPE),
124
129
  zValidator("json", autoReplySchema),
125
130
  async (c) => {
126
131
  const mailboxId = c.req.param("id");
@@ -6,7 +6,7 @@ import { normalizedParticipantSet } from "./participants";
6
6
 
7
7
  type ThreadParent = Pick<
8
8
  Email,
9
- "listId" | "fromJson" | "toJson" | "ccJson" | "bccJson"
9
+ "listId" | "listPostAddress" | "fromJson" | "toJson" | "ccJson" | "bccJson"
10
10
  >;
11
11
 
12
12
  /**
@@ -25,7 +25,20 @@ export function shouldDetachInboundReply(input: {
25
25
  const normalizedListId = input.listId?.trim().toLocaleLowerCase() ?? null;
26
26
  const parentListId = parent.listId?.trim().toLocaleLowerCase() ?? null;
27
27
 
28
- if (parent.listId && parentListId !== normalizedListId) return true;
28
+ // A reply-all's direct copy has no List-Id but names the list: it stays
29
+ // in the list's thread, as the list's own copy (then a duplicate) would.
30
+ const listPost = parent.listPostAddress?.toLocaleLowerCase() ?? null;
31
+
32
+ const namesList =
33
+ normalizedListId === null &&
34
+ listPost !== null &&
35
+ [...input.to, ...input.cc].some(
36
+ (recipient) => recipient.address.toLocaleLowerCase() === listPost
37
+ );
38
+
39
+ if (parent.listId && parentListId !== normalizedListId && !namesList) {
40
+ return true;
41
+ }
29
42
 
30
43
  const parentParticipants = normalizedParticipantSet(
31
44
  [...parent.fromJson, ...parent.toJson, ...parent.ccJson].map(
@@ -150,10 +150,17 @@ export function securityWarnings(input: {
150
150
  }
151
151
  }
152
152
 
153
- if (input.authentication?.verdict === "suspicious") {
153
+ const verdict = input.authentication?.verdict;
154
+
155
+ // From the workspace's own domain, mail that isn't proven to be is how a
156
+ // colleague is impersonated: a danger, which trusting them doesn't hide.
157
+ if (
158
+ verdict === "suspicious" ||
159
+ (!input.external && verdict === "unverified")
160
+ ) {
154
161
  warnings.push({
155
162
  kind: "unverified_sender",
156
- severity: "caution",
163
+ severity: input.external ? "caution" : "danger",
157
164
  domain: input.fromDomain,
158
165
  });
159
166
  }
@@ -201,6 +208,10 @@ export function messageSecurity(input: {
201
208
  }) {
202
209
  const auth = input.authentication;
203
210
 
211
+ // Trusting an address quiets warnings only for mail proven to be from it:
212
+ // spoofed, it is warned about as from anyone.
213
+ const trusted = Boolean(input.trusted) && auth?.verdict === "verified";
214
+
204
215
  const fromDomain =
205
216
  addressDomain(input.fromAddress) ?? auth?.fromDomain ?? null;
206
217
 
@@ -246,10 +257,10 @@ export function messageSecurity(input: {
246
257
  replyTo: input.replyTo,
247
258
  listId: input.listId,
248
259
  delivery: input.delivery,
249
- trusted: input.trusted,
260
+ trusted,
250
261
  }),
251
262
  firstTimeSender: Boolean(
252
- !input.trusted &&
263
+ !trusted &&
253
264
  external &&
254
265
  history &&
255
266
  history.inboundCount <= 1 &&
@@ -260,6 +271,6 @@ export function messageSecurity(input: {
260
271
  replyTo: input.replyTo ?? [],
261
272
  listId: input.listId ?? null,
262
273
  }),
263
- trusted: Boolean(input.trusted),
274
+ trusted,
264
275
  } satisfies MessageSecurity;
265
276
  }
@@ -614,6 +614,8 @@ export const mailRoutes = new Hono<AppEnv>()
614
614
  }
615
615
 
616
616
  const headers = new Headers(c.req.raw.headers);
617
+ // Only the Worker's JMAP stream may ask for a socket nothing re-checks.
618
+ headers.delete("x-openworkspace-jmap");
617
619
  headers.set("x-openworkspace-user-id", user.id);
618
620
  headers.set("x-openworkspace-session-id", c.get("sessionId"));
619
621
  headers.set(
@@ -1292,7 +1294,10 @@ export const mailRoutes = new Hono<AppEnv>()
1292
1294
  ])
1293
1295
  );
1294
1296
 
1295
- workspace.catch(() => undefined);
1297
+ // Awaited below, unless the mailbox call fails or finds nothing first.
1298
+ workspace.catch((error) =>
1299
+ console.warn("Workspace inputs failed to load", error)
1300
+ );
1296
1301
 
1297
1302
  const view = await timed(c, "do", "conversation", () =>
1298
1303
  mailbox.getConversationView(
@@ -1536,7 +1541,10 @@ export const mailRoutes = new Hono<AppEnv>()
1536
1541
  ])
1537
1542
  );
1538
1543
 
1539
- workspace.catch(() => undefined);
1544
+ // Awaited below, unless the mailbox call fails or finds nothing first.
1545
+ workspace.catch((error) =>
1546
+ console.warn("Workspace inputs failed to load", error)
1547
+ );
1540
1548
 
1541
1549
  const view = await timed(c, "do", "message", () =>
1542
1550
  mailbox.getMessageSenderView(c.req.param("id"))
@@ -13,7 +13,11 @@ import { Hono } from "hono";
13
13
  import type { Context } from "hono";
14
14
  import type { z } from "zod";
15
15
 
16
- import { MAIL_ORGANIZE_SCOPE, MAIL_READ_SCOPE } from "../../shared/permissions";
16
+ import {
17
+ MAIL_ORGANIZE_SCOPE,
18
+ MAIL_READ_SCOPE,
19
+ MAIL_SEND_SCOPE,
20
+ } from "../../shared/permissions";
17
21
  import { signatures } from "../db/schema";
18
22
  import { accessibleMailbox } from "./access";
19
23
  import {
@@ -135,9 +139,10 @@ export const signatureRoutes = new Hono<AppEnv>()
135
139
 
136
140
  return c.json(signatureView(owner, await loadSignature(c.env, owner)));
137
141
  })
142
+ // It rides on every message sent, so an app sets it only if it may send.
138
143
  .put(
139
144
  "/signature",
140
- oauthScope(MAIL_ORGANIZE_SCOPE),
145
+ oauthScope(MAIL_ORGANIZE_SCOPE, MAIL_SEND_SCOPE),
141
146
  zValidator("json", signatureSchema),
142
147
  (c) => saveResponse(c, { userId: c.get("user").id }, c.req.valid("json"))
143
148
  )
@@ -189,6 +189,21 @@ export async function maybeAutoReply(
189
189
  ? writer
190
190
  : null;
191
191
 
192
+ // Anyone can write the envelope sender: the reply goes there only when SPF
193
+ // passed for it or a verified From shares its domain. Otherwise a
194
+ // stranger could aim the workspace's reply at anyone (backscatter), or at
195
+ // one of its own lists, which would take it as a member's.
196
+ const auth = email.authenticationResultsJson;
197
+
198
+ const envelopeProven =
199
+ !auth ||
200
+ auth.verdict === "unavailable" ||
201
+ (auth.spf?.result === "pass" &&
202
+ relaxedAligned(auth.spf.domain, recipient)) ||
203
+ (author !== null && relaxedAligned(author, recipient));
204
+
205
+ if (!envelopeProven) return;
206
+
192
207
  // The workspace's own message also needs the reply to go to From's
193
208
  // domain: a colleague's signed message resent with another envelope
194
209
  // sender (a replay) would otherwise hand it to whoever resent it.
@@ -224,11 +224,16 @@ export async function importMessage(
224
224
  envelopeTo: input.original?.envelopeTo ?? null,
225
225
  };
226
226
 
227
- // Mail imported from another system has no local authentication verdict.
228
- // Its quote is kept as a sent message's, without the `>` it went out with.
227
+ // Mail imported from another system has no local authentication verdict:
228
+ // headers in the uploaded file claiming Cloudflare checked it are the
229
+ // uploader's to write. Only this workspace's own snapshot keeps its own.
230
+ if (direction === "outgoing" || !input.original) {
231
+ imported.authenticationResultsJson = null;
232
+ }
233
+
234
+ // A sent message's quote is kept without the `>` it went out with.
229
235
  if (direction === "outgoing") {
230
236
  imported.quotedText = parsed.quotedText && sentQuote(parsed.quotedText);
231
- imported.authenticationResultsJson = null;
232
237
  imported.listUnsubscribeJson = null;
233
238
  }
234
239
 
@@ -190,25 +190,35 @@ export async function undoSpam(m: MailboxContext, userId: string, id: string) {
190
190
  const { receipt } = stored;
191
191
 
192
192
  // A teammate's newer filing, report or trust change takes precedence.
193
- if (
194
- !canRestoreFiling(m, receipt) ||
195
- !isDeepStrictEqual(
193
+ const restorable = () =>
194
+ canRestoreFiling(m, receipt) &&
195
+ isDeepStrictEqual(
196
196
  senders(
197
197
  m,
198
198
  receipt.sendersAfter.map((row) => row.address)
199
199
  ),
200
200
  receipt.sendersAfter
201
- )
202
- ) {
203
- return false;
204
- }
201
+ );
202
+
203
+ if (!restorable()) return false;
205
204
 
206
205
  await undoWorkspaceFeedback(
207
206
  m.env.DB,
208
207
  required(m.state.id.name, "named mailbox"),
209
208
  receipt.workspace
210
209
  );
211
- m.db.transaction(() => {
210
+
211
+ // Checked again after the wait: another undo of it, or a teammate's
212
+ // change, may have come first.
213
+ const undone = m.db.transaction(() => {
214
+ const claimed = m.db
215
+ .delete(spamUndoReceipts)
216
+ .where(eq(spamUndoReceipts.id, id))
217
+ .returning({ id: spamUndoReceipts.id })
218
+ .all();
219
+
220
+ if (!claimed.length || !restorable()) return false;
221
+
212
222
  restoreFiling(m, receipt);
213
223
 
214
224
  for (const sender of receipt.sendersAfter) {
@@ -231,8 +241,11 @@ export async function undoSpam(m: MailboxContext, userId: string, id: string) {
231
241
  .run();
232
242
  }
233
243
 
234
- m.db.delete(spamUndoReceipts).where(eq(spamUndoReceipts.id, id)).run();
244
+ return true;
235
245
  });
246
+
247
+ if (!undone) return false;
248
+
236
249
  m.forgetParticipants();
237
250
  void m.announce();
238
251
 
@@ -6,7 +6,11 @@ import { apiPath, runTool } from "@open-workspace/core/module";
6
6
  import { z } from "zod";
7
7
 
8
8
  import { autoReplyAudiences } from "../../shared/mail";
9
- import { MAIL_ORGANIZE_SCOPE, MAIL_READ_SCOPE } from "../../shared/permissions";
9
+ import {
10
+ MAIL_ORGANIZE_SCOPE,
11
+ MAIL_READ_SCOPE,
12
+ MAIL_SEND_SCOPE,
13
+ } from "../../shared/permissions";
10
14
  import { ruleInputSchema, ruleTestSchema } from "../mail/rules";
11
15
  import { retentionFolderSchema } from "../mail/schemas";
12
16
  import {
@@ -183,7 +187,7 @@ export function registerMailActionTools(
183
187
  text: z.string().max(10_000).describe("The same reply as plain text."),
184
188
  });
185
189
 
186
- tool(MAIL_ORGANIZE_SCOPE)(
190
+ tool([MAIL_ORGANIZE_SCOPE, MAIL_SEND_SCOPE])(
187
191
  "set_auto_reply",
188
192
  {
189
193
  title: "Set auto-reply",