From 3ec2531ecf5236090a8c8e731ca49b3f3fe5235d Mon Sep 17 00:00:00 2001 From: leemour Date: Thu, 26 Nov 2026 17:30:37 +0100 Subject: [PATCH 1/2] fix(mail): a removed alias stops being the owner's; sync keeps auto-replied, List-Post, schema.org and calendar method An alias the owner removes from config stopped counting nowhere: ownAddresses joined the stored mail_own_addresses with the configured list, and settleOwnMail wrote the union back. The sync now keeps the configured list under mail_own_configured. An address that left it and has no live mail in Sent leaves mail_own_addresses, its mail outside Sent is incoming again (markOwnMail `removed`), and its email identity leaves the owner when the rules joined it. The owner's own link stays. Part of #3321. Mail sync keeps in emails.headers what #3358 listed as not stored, with no store version: - auto-replied: a signed Auto-Submitted: auto-replied, apart from auto-submitted, so an out-of-office makes no bot; - list-post: List-Post naming where to post (not NO); - schema-types and schema-fields: the schema.org type names (at most 10) and orderNumber, orderStatus, trackingNumber, reservationNumber, reservationStatus, never the HTML; - calendar-method: the text/calendar part's method. The classifier reads them: auto-replied is auto_reply, List-Id mail with List-Post and no campaign marker is a discussion_list, and stored schema types count as body_html's do. The JSON-LD opener regex no longer rescans a run of ` --- changes/fix-mail-own-addresses-signals.md | 16 +++++ docs/dev/MAIL.md | 19 +++++- src/mail/body-signals.ts | 71 +++++++++++++++++++++++ src/mail/email-input.ts | 11 +++- src/mail/headers.test.ts | 22 +++++++ src/mail/headers.ts | 11 +++- src/mail/mail-types.test.ts | 6 ++ src/mail/mail-types.ts | 33 ++++++++--- src/mail/own.test.ts | 53 +++++++++++++++++ src/mail/own.ts | 48 ++++++++++++--- src/mail/parse.ts | 4 ++ src/mail/retry.ts | 4 +- src/mail/sync.ts | 3 +- src/store/mail-types.test.ts | 48 +++++++++++++++ src/store/sqlite/email-state.ts | 21 ++++++- src/store/sqlite/email-types.ts | 7 ++- src/store/sqlite/emails.ts | 4 +- 17 files changed, 351 insertions(+), 30 deletions(-) create mode 100644 changes/fix-mail-own-addresses-signals.md create mode 100644 src/mail/body-signals.ts diff --git a/changes/fix-mail-own-addresses-signals.md b/changes/fix-mail-own-addresses-signals.md new file mode 100644 index 000000000..31d484646 --- /dev/null +++ b/changes/fix-mail-own-addresses-signals.md @@ -0,0 +1,16 @@ +### Fixed + +- **An alias the owner removes stops being the owner's on the next mail sync.** The addresses a sync is given are kept + under `mail_own_configured`. One that is gone and has no mail in Sent leaves `mail_own_addresses`; the account's + mail from it outside Sent is incoming again, and its email identity leaves the owner when the rules joined it. A link + the owner made stays. `settleOwnMail` now takes the configured list as `configured` in its options, and + `store.mail.markOwnMail` takes `removed`. No store version. Part of #3321. + +### Added + +- **Mail sync keeps more of what decides a mail's type** in `emails.headers`, no store version: `auto-replied` (a + signed `Auto-Submitted: auto-replied`, apart from `auto-submitted`), `list-post` (List-Post naming where to post), + `schema-types` and `schema-fields` (the schema.org type names and a few values of the HTML, never the HTML), and + `calendar-method` (`request`, `cancel`, `reply`). The mail types read them: an auto-reply is `auto_reply`, List-Id + mail with List-Post and no campaign marker is a `discussion_list`, and stored schema types count as `body_html`'s + do. Mail stored earlier has none of them until mail sync reads it again. From the gaps #3358 listed. diff --git a/docs/dev/MAIL.md b/docs/dev/MAIL.md index 7a246dbec..68a8def3f 100644 --- a/docs/dev/MAIL.md +++ b/docs/dev/MAIL.md @@ -44,6 +44,12 @@ account `{ provider: "email", account: }`. (`store.mail.markOwnMail`), and the account is saved again, so `linkOwnIdentities` joins their identities to the owner. Partial completion, `readEmailWhole` and a server search read the same list. A mail tie needs mail the owner wrote, so this is what gives the people an alias writes to their tie. Nothing is taken from a name. +- **An alias the owner removes.** The list a sync is given is kept under `mail_own_configured`. An address that was in + it and is not now, and has no live mail in Sent, leaves `mail_own_addresses`: the account's mail from it outside + Sent is incoming again, and its email identity leaves the owner when the rules joined it (`account`, by `rules`). + A link the owner made stays. The join moved every identity of the alias's person, and only the email identity moves + back. A store from before `mail_own_configured` takes every stored address as possibly configured once: an address + only a Sent folder this run does not read vouched for drops then. - **Stored headers.** An email stored in full keeps some header fields as JSON in `emails.headers` (`mailHeadersOf`, `src/mail/headers.ts`): `list-id`, `list-unsubscribe`, `precedence`, `reply-to`, Gmail's `spf`, `dkim` and `dmarc`, and what marks a program or a list. Those last are `auto-submitted` (its value, unless `no` or @@ -53,7 +59,17 @@ account `{ provider: "email", account: }`. registrable domain (`signedFieldsOf`). **Gap:** only Gmail's own `mx.google.com` stamp is read, so mail of an IMAP server never keeps these three; another server's Authentication-Results may be the sender's own. An empty Return-Path, which the receiving server writes, is kept as `null-return-path` unless the mail is an auto-reply: a - person's out-of-office comes that way too. Mail stored before these keys keeps none of them until read again. + person's out-of-office comes that way too. A signed `Auto-Submitted: auto-replied` is kept as `auto-replied`, apart + from `auto-submitted`, which marks a program: the mail is an `auto_reply`, and its sender stays a person. + `list-post` is `true` when List-Post names where to post, not when it says `NO` (RFC 2369), and is kept unsigned, + like List-Id: with no campaign marker it makes List-Id mail a `discussion_list` before three senders are stored. + Mail stored before these keys keeps none of them until read again. +- **What the body says.** The store keeps no HTML of synced mail, so `parseMail` reads it once (`bodySignalsOf`, + `src/mail/body-signals.ts`) and the sync keeps beside the headers: `schema-types`, the schema.org types its JSON-LD + or microdata declares (at most 10), `schema-fields`, the first `orderNumber`, `orderStatus`, `trackingNumber`, + `reservationNumber` and `reservationStatus` (up to 100 characters each), and `calendar-method`, the method of its + `text/calendar` part (`request`, `cancel`, `reply`, from the Content-Type or the part's `METHOD`). The mail types + read `schema-types` as they read a kept `body_html`. - **Unsubscribe targets.** `list-unsubscribe` stays `true` whenever the field is present, signed or not: the mail types and the bot rules read it as a mark of bulk mail. The targets themselves are kept apart, as `list-unsubscribe-https` and `list-unsubscribe-mailto` (the first of each scheme in @@ -221,6 +237,7 @@ All under the account, in `store.sync` (`syncState`, `setSyncState`): | `mail_resume:mbox` | a `MboxPoint`: the file's size and modification time, and whether every message was read | | `mail_folder_scope` | the mode and folders of the last run; a change skips deletions once | | `mail_own_addresses` | the owner's other addresses on the account, lower case: the configured ones and the senders of mail in Sent | +| `mail_own_configured` | the addresses the last sync was given as the owner's, lower case, so a removed one stops counting | | `mail_coverage` | the folders, window and whether the last run was complete | | `mail_sender_scores` | when `scoreSenders` last ran, its version (`SCORE_VERSION`) and the senders it ranks lower | | `consumer:` | a holder's processing mark: `throughId`, `throughAt`, `held`, `read`, `skipped` by reason | diff --git a/src/mail/body-signals.ts b/src/mail/body-signals.ts new file mode 100644 index 000000000..05eb82f2e --- /dev/null +++ b/src/mail/body-signals.ts @@ -0,0 +1,71 @@ +import { jsonLdOf, schemaTypesOf } from "./mail-types.js" + +const MAX_TYPES = 10 +const MAX_VALUE_CHARS = 100 +const ICS_HEAD_BYTES = 64 * 1024 +/** The few schema.org values that name the order, parcel or booking an email is about. */ +const SCHEMA_FIELDS = ["orderNumber", "orderStatus", "trackingNumber", "reservationNumber", "reservationStatus"] +const CALENDAR_PARTS = new Set(["text/calendar", "application/ics"]) + +export interface CalendarPart { + mimeType: string + /** The Content-Type `method` parameter, as postal-mime gives it. */ + method?: string | undefined + content: ArrayBuffer | Uint8Array | string +} + +/** What `mailHeadersOf` cannot see in the header: kept beside it under `emails.headers`, never the HTML itself. */ +export type BodySignals = Record> + +const ldValue = (blocks: readonly string[], name: string): string | undefined => { + const pattern = new RegExp(`"${name}"\\s*:\\s*"([^"\\\\]{1,${MAX_VALUE_CHARS}})"`) + for (const block of blocks) { + const found = pattern.exec(block)?.[1] + if (found !== undefined) return found + } + return undefined +} + +const itemValue = (html: string, name: string): string | undefined => { + const tag = new RegExp(`<[^<>]*\\bitemprop\\s*=\\s*["']?${name}\\b[^<>]*>`, "i").exec(html)?.[0] + return tag === undefined + ? undefined + : new RegExp(`\\bcontent\\s*=\\s*["']([^"'<>]{1,${MAX_VALUE_CHARS}})["']`, "i").exec(tag)?.[1] +} + +const schemaFieldsOf = (html: string): Record => { + const blocks = jsonLdOf(html) + const fields: Record = {} + for (const name of SCHEMA_FIELDS) { + const value = (ldValue(blocks, name) ?? itemValue(html, name))?.trim() + if (value) fields[name] = value + } + return fields +} + +const icsHead = (content: CalendarPart["content"]): string => + typeof content === "string" + ? content.slice(0, ICS_HEAD_BYTES) + : Buffer.from(content instanceof Uint8Array ? content : new Uint8Array(content)) + .subarray(0, ICS_HEAD_BYTES) + .toString("utf8") + +/** REQUEST, CANCEL, REPLY (RFC 5546): an invitation, its cancellation or someone's answer. */ +const calendarMethodOf = (parts: readonly CalendarPart[]): string | undefined => { + const part = parts.find(({ mimeType }) => CALENDAR_PARTS.has(mimeType.toLowerCase())) + if (part === undefined) return undefined + const method = part.method ?? /^METHOD:[ \t]*([A-Za-z-]+)/m.exec(icsHead(part.content))?.[1] + return method?.trim().toLowerCase() || undefined +} + +/** schema.org type names and a few of their values, and a calendar part's method. */ +export const bodySignalsOf = (html: string | undefined, parts: readonly CalendarPart[]): BodySignals => { + const types = html ? schemaTypesOf(html).slice(0, MAX_TYPES) : [] + const fields = types.length > 0 && html ? schemaFieldsOf(html) : {} + const method = calendarMethodOf(parts) + return { + ...(types.length > 0 ? { "schema-types": types } : {}), + ...(Object.keys(fields).length > 0 ? { "schema-fields": fields } : {}), + ...(method === undefined ? {} : { "calendar-method": method }), + } +} diff --git a/src/mail/email-input.ts b/src/mail/email-input.ts index a90428f04..5ab5a5ebb 100644 --- a/src/mail/email-input.ts +++ b/src/mail/email-input.ts @@ -10,6 +10,15 @@ export const sentAtOf = (date: string | null, receivedAt: string): number => { return Number.isNaN(sent) ? Date.parse(receivedAt) : sent } +/** The header fields `mailHeadersOf` kept, with what the body says beside them. */ +export const storedHeaders = ( + header: Record, + mail: Pick, +): Pick => { + const headers = { ...header, ...mail.signals } + return Object.keys(headers).length ? { headers } : {} +} + /** What one read email stores of itself, whichever run read it; where it is filed is the caller's. */ export const parsedEmail = ( mail: ParsedMail, @@ -28,6 +37,6 @@ export const parsedEmail = ( receivedAt: Date.parse(item.receivedAt), bodyText: mail.text || null, size: item.size ?? null, - ...(Object.keys(header).length ? { headers: header } : {}), + ...storedHeaders(header, mail), outgoing: sentByOwner(mail.from?.email, own, inSent), }) diff --git a/src/mail/headers.test.ts b/src/mail/headers.test.ts index 89fa98fde..1185d8b7e 100644 --- a/src/mail/headers.test.ts +++ b/src/mail/headers.test.ts @@ -57,6 +57,28 @@ describe("mailHeadersOf", () => { ) }) + it("keeps a signed auto-reply apart from Auto-Submitted, so a person's out-of-office makes no program", () => { + const fields = [ + "From: Pia ", + "Return-Path: <>", + "Auto-Submitted: auto-replied", + SIGNATURE, + "Authentication-Results: mx.google.com; dkim=pass header.i=@news.shop.example", + ] + expect(mailHeadersOf(raw(fields))).toEqual({ dkim: "pass", "auto-replied": true }) + }) + + it("keeps a List-Post that names where to post, not one that says NO", () => { + const list = (post: string) => ["From: rin@lists.example", "List-Id: ", `List-Post: ${post}`] + expect(mailHeadersOf(raw(list("")))).toEqual({ + "list-id": "dev.lists.example", + "list-post": true, + }) + expect(mailHeadersOf(raw(list("NO (posting not allowed on this list)")))).toEqual({ + "list-id": "dev.lists.example", + }) + }) + it("keeps the https and mailto unsubscribe targets only under the From domain's own signature", () => { const fields = (signed: string) => [ "From: News ", diff --git a/src/mail/headers.ts b/src/mail/headers.ts index d2e8bf5a7..bc1c7846a 100644 --- a/src/mail/headers.ts +++ b/src/mail/headers.ts @@ -98,7 +98,8 @@ export const signedFieldsOf = (unfolded: string, from: string | undefined): Set< /** * What says a program or a list sent the mail, each only when DKIM vouches for it (`signedFieldsOf`): - * `Auto-Submitted` other than `no` (RFC 3834), the one-click unsubscribe of RFC 8058 and Google's `Feedback-ID`. + * `Auto-Submitted` other than `no` (RFC 3834), `auto-replied` apart, the one-click unsubscribe of RFC 8058 and Google's + * `Feedback-ID`. * An empty Return-Path is the receiving server's, not the sender's, and marks a program unless it is an auto-reply, * which RFC 3834 sends that way too: a person's out-of-office makes no bot. */ @@ -112,6 +113,8 @@ const programSignalsOf = (unfolded: string, from: string | undefined): Record/.test(field(unfolded, "Return-Path") ?? "") && submitted !== "auto-replied" @@ -136,6 +139,9 @@ const unsubscribeTargetsOf = (unfolded: string, from: string | undefined): Recor } } +/** A List-Post that names where to post (RFC 2369): a discussion list's mark. `NO` says members cannot post. */ +const listPostOf = (value: string | undefined): boolean => value !== undefined && /<\s*[a-z][a-z+.-]*:/i.test(value) + export const addressesOf = (value: string | undefined): string[] => { if (value === undefined) return [] // A display name may itself look like an address ("bob@y.com" ), so quoted names and comments go first. @@ -192,7 +198,7 @@ const headTextOf = (raw: Uint8Array): string => { export const headersOfRaw = (raw: Uint8Array): MailHeaders => headersOf(headTextOf(raw)) /** - * List-Id, the bulk-mail fields, Reply-To, Gmail's SPF, DKIM and DMARC verdicts, the unsubscribe targets + * List-Id, List-Post, the bulk-mail fields, Reply-To, Gmail's SPF, DKIM and DMARC verdicts, the unsubscribe targets * (`unsubscribeTargetsOf`) and what marks a program or a list (`programSignalsOf`) of a whole email, kept on mail * stored in full so a rule, a sender score or a person's kind can be worked out from the store later. Names are lower * case. @@ -208,6 +214,7 @@ export const mailHeadersOf = (raw: Uint8Array): Record ...(replyTo === undefined ? {} : { "reply-to": replyTo }), ...authOf(unfolded), ...(field(unfolded, "List-Unsubscribe") === undefined ? {} : { "list-unsubscribe": true }), + ...(listPostOf(field(unfolded, "List-Post")) ? { "list-post": true } : {}), ...(precedence ? { precedence } : {}), ...unsubscribeTargetsOf(unfolded, from), ...programSignalsOf(unfolded, from), diff --git a/src/mail/mail-types.test.ts b/src/mail/mail-types.test.ts index c1c062d7f..cf7d65b67 100644 --- a/src/mail/mail-types.test.ts +++ b/src/mail/mail-types.test.ts @@ -50,6 +50,12 @@ describe("the type of one email", () => { "discussion_list discussion-list", ], [{ headers: { precedence: "list" } }, "discussion_list precedence-list"], + [{ headers: { "list-id": "dev.example.org", "list-post": true }, listSenders: 1 }, "discussion_list list-post"], + [ + { headers: { "list-id": "news.example.org", "list-post": true, "feedback-id": true }, listSenders: 1 }, + "newsletter list-id", + ], + [{ subject: "Away until Monday", headers: { "auto-replied": true }, ownerWrote: true }, "auto_reply auto-replied"], [{ headers: { precedence: "list", "list-id": "news.example.org" }, listSenders: 1 }, "newsletter list-id"], [{ from: "info@shop.example.com", headers: { "feedback-id": true } }, "promotion marketing-address"], [{ from: "x@esp.example.com", headers: { "feedback-id": true }, bot: true }, "promotion feedback-id"], diff --git a/src/mail/mail-types.ts b/src/mail/mail-types.ts index b17393fcd..c7145d263 100644 --- a/src/mail/mail-types.ts +++ b/src/mail/mail-types.ts @@ -141,9 +141,11 @@ export const mailTypeOf = (input: MailTypeInput): MailTypeOf => { const precedence = typeof headers.precedence === "string" ? headers.precedence : "" const bulkPrecedence = precedence === "bulk" || precedence === "junk" const autoSubmitted = headers["auto-submitted"] !== undefined - // With a List-Id, its senders decide: one sender, even under `+tag` addresses, writes a newsletter. + // With a List-Id, its senders decide: one sender, even under `+tag` addresses, writes a newsletter. A List-Post + // with no campaign marker says members post there, before a third sender is stored. + const listPost = listId && headers["list-post"] === true && !feedbackId && !oneClick const discussion = listId - ? input.listSenders >= DISCUSSION_SENDERS + ? input.listSenders >= DISCUSSION_SENDERS || listPost : precedence === "list" && !feedbackId && !MARKETING_SENDER.test(from) const mass = listUnsubscribe || bulkPrecedence || listId || oneClick const transactional = !mass && !feedbackId @@ -167,6 +169,7 @@ export const mailTypeOf = (input: MailTypeInput): MailTypeOf => { const report = input.parts.find((part) => REPORT_PARTS.has(part)) if (report !== undefined) return typed("auto_reply", report) if (MAILER_DAEMON.test(from)) return typed("auto_reply", "mailer-daemon") + if (headers["auto-replied"] === true) return typed("auto_reply", "auto-replied") if (!mass && AUTO_REPLY_SUBJECT.test(subject)) return typed("auto_reply", "auto-reply-subject") if (weak && trusted && SECURITY_SENDER.test(from)) return typed("security", "security-address") if (weak && trusted && SECURITY_SUBJECT.test(subject)) return typed("security", "security-subject") @@ -192,7 +195,11 @@ export const mailTypeOf = (input: MailTypeInput): MailTypeOf => { if (weak && BILL_SUBJECT.test(subject)) return typed("bill", "bill-subject") if (!person && input.sector === "social") return typed("social_notification", "sector:social") - if (discussion) return typed("discussion_list", listId ? "discussion-list" : "precedence-list") + if (discussion) + return typed( + "discussion_list", + !listId ? "precedence-list" : input.listSenders >= DISCUSSION_SENDERS ? "discussion-list" : "list-post", + ) // Transactional mail sometimes carries List-Unsubscribe: an automated sender with no campaign marker sends notices. const automated = AUTOMATED_SENDER.test(from) && !MARKETING_SENDER.test(from) if (listUnsubscribe && !oneClick && !feedbackId && !bulkPrecedence && automated) @@ -218,21 +225,29 @@ export const mailTypeOf = (input: MailTypeInput): MailTypeOf => { return typed("other", null) } -const JSON_LD_OPEN = /]*type\s*=\s*["']?application\/ld\+json[^>]*>/gi +// `[^<>]` and not `[^>]`: a run of `` would be read to the end from each of them. +const JSON_LD_OPEN = /]*type\s*=\s*["']?application\/ld\+json[^<>]*>/gi const ITEM_TYPE = /\bitemtype\s*=\s*["']?https?:\/\/schema\.org\/([A-Za-z]+)/gi const LD_TYPE = /"@type"\s*:\s*"(?:https?:\/\/schema\.org\/)?([A-Za-z]+)"/g -/** The schema.org types an email's HTML declares, in JSON-LD or microdata, as Gmail's markup reads them. @experimental */ -export const schemaTypesOf = (html: string | null): string[] => { - if (html === null || html === "") return [] - const found = new Set() +/** The text of each JSON-LD block of an email's HTML. */ +export const jsonLdOf = (html: string): string[] => { + const blocks: string[] = [] for (const open of html.matchAll(JSON_LD_OPEN)) { const start = open.index + open[0].length const end = html.indexOf("", start) // An unclosed block ends the scan: every later opener would search to the end again. if (end === -1) break - for (const [, type] of html.slice(start, end).matchAll(LD_TYPE)) found.add(type as string) + blocks.push(html.slice(start, end)) } + return blocks +} + +/** The schema.org types an email's HTML declares, in JSON-LD or microdata, as Gmail's markup reads them. @experimental */ +export const schemaTypesOf = (html: string | null): string[] => { + if (html === null || html === "") return [] + const found = new Set() + for (const block of jsonLdOf(html)) for (const [, type] of block.matchAll(LD_TYPE)) found.add(type as string) for (const [, type] of html.matchAll(ITEM_TYPE)) found.add(type as string) return [...found] } diff --git a/src/mail/own.test.ts b/src/mail/own.test.ts index e8eb81f9c..ca7fa08e9 100644 --- a/src/mail/own.test.ts +++ b/src/mail/own.test.ts @@ -5,6 +5,7 @@ import { afterEach, describe, expect, it } from "vitest" import { type MessageStore, openStore } from "../store/index.js" import { mailFolders } from "./folders.js" import { mailTurn } from "./owed.js" +import { OWN_MAIL_CONFIGURED } from "./own.js" import type { MailAccount } from "./sync.js" import { syncMail } from "./sync.js" import { type FakeMail, type FakeMailbox, fakeMailSource } from "./testing/index.js" @@ -159,6 +160,58 @@ describe("the owner's mail", () => { expect(await ownerHolds(store, ALIAS)).toBe(true) }) + it("stops counting an alias the owner no longer configures: its mail is incoming, its identity leaves the owner", async () => { + const store = await sandbox() + const box: FakeMailbox = { + messages: [mail(1), mail(2, { from: ["Owner Example", ALIAS], to: [["Pat Example", "pat@example.test"]] })], + } + await sync(store, box, { addresses: [ALIAS] }) + expect(await outgoing(store)).toEqual({ "9001": false, "9002": true }) + expect(await ownerHolds(store, ALIAS)).toBe(true) + + await sync(store, box) + + expect(await outgoing(store)).toEqual({ "9001": false, "9002": false }) + expect(await tiesOf(store, "pat@example.test")).not.toContain("mail") + expect(await ownerHolds(store, ALIAS)).toBe(false) + expect(await ownerHolds(store, ME)).toBe(true) + }) + + it("keeps a removed alias the owner's while its mail is in Sent, and the owner's own link of it", async () => { + const store = await sandbox() + const other = "second@example.test" + const box: FakeMailbox = { + messages: [ + mail(1, { from: ["Owner Example", ALIAS], to: [["Pat Example", "pat@example.test"]], labels: ["Sent"] }), + mail(2, { from: ["Owner Example", other], to: [["Pat Example", "pat@example.test"]] }), + mail(3), + ], + } + await sync(store, box, { addresses: [ALIAS, other] }) + await store.people.unlinkIdentity({ provider: "email", id: other }, { method: "unlink", by: "owner" }) + await store.people.linkToOwner({ provider: "email", id: other }) + + await sync(store, box) + + expect(await outgoing(store)).toEqual({ "9001": true, "9002": false, "9003": false }) + expect(await ownerHolds(store, ALIAS)).toBe(true) + expect(await ownerHolds(store, other)).toBe(true) + }) + + it("lets go of an alias stored before the configured list was kept", async () => { + const store = await sandbox() + const box: FakeMailbox = { + messages: [mail(1), mail(2, { from: ["Owner Example", ALIAS], to: [["Pat Example", "pat@example.test"]] })], + } + await sync(store, box, { addresses: [ALIAS] }) + await store.sync.clearSyncState(KEY, OWN_MAIL_CONFIGURED) + + await sync(store, box) + + expect(await outgoing(store)).toEqual({ "9001": false, "9002": false }) + expect(await ownerHolds(store, ALIAS)).toBe(false) + }) + it("joins no alias to the owner while the account itself is not the owner's", async () => { const store = await sandbox() await store.people.savePeople({ provider: "telegram", account: "5" }, [{ id: "5", name: "Slava Owner" }]) diff --git a/src/mail/own.ts b/src/mail/own.ts index 5354119d5..6e87492e8 100644 --- a/src/mail/own.ts +++ b/src/mail/own.ts @@ -2,12 +2,14 @@ import type { AccountKey, MessageStore } from "../store/index.js" import { OWN_MAIL_ADDRESSES as OWN_ADDRESSES } from "../store/sqlite/own-identities.js" /** Gmail's label on mail the account sent, as `decodedLabelName` gives `\\Sent`. */ export const SENT_LABEL = "Sent" +/** Sync state under a mail account: the addresses its sync was last given as the owner's, lower case, as JSON. */ +export const OWN_MAIL_CONFIGURED = "mail_own_configured" const normal = (address: string): string => address.trim().toLowerCase() -const storedOwn = async (store: MessageStore, key: AccountKey): Promise => { - const value = (await store.sync.syncState(key, OWN_ADDRESSES))?.value - if (value === undefined) return [] +const storedList = async (store: MessageStore, key: AccountKey, name: string): Promise => { + const value = (await store.sync.syncState(key, name))?.value + if (value === undefined) return undefined try { const parsed: unknown = JSON.parse(value) return Array.isArray(parsed) ? parsed.filter((item): item is string => typeof item === "string") : [] @@ -16,6 +18,9 @@ const storedOwn = async (store: MessageStore, key: AccountKey): Promise => + (await storedList(store, key, OWN_ADDRESSES)) ?? [] + /** The mailbox address, the addresses the owner configured, and those the account's sent mail came from. */ export const ownAddresses = async ( store: MessageStore, @@ -30,24 +35,49 @@ export const sentByOwner = ( inSent = false, ): boolean | null => (inSent ? true : from == null ? null : own.has(normal(from))) +/** Only links the account rules made go: the owner's own link of an address stays. */ +const disownIdentities = async (store: MessageStore, addresses: readonly string[]): Promise => { + const owner = await store.people.owner() + for (const address of addresses) { + const held = owner?.identities.some( + ({ provider, id, method, linkedBy }) => + provider === "email" && id === address && method === "account" && linkedBy === "rules", + ) + if (held) await store.people.unlinkIdentity({ provider: "email", id: address }, { method: "unlink", by: "rules" }) + } +} + /** - * After a sync: the senders of the mail in Sent join the owner's addresses, the account's mail from any of them - * becomes outgoing, and their identities join the owner as the account's own does. + * After a sync: the senders of the mail in Sent join the owner's addresses beside `configured`, the account's mail from + * any of them becomes outgoing, and their identities join the owner as the account's own does. An address no longer + * configured, with no mail in Sent, stops being the owner's: its mail outside Sent is incoming again and its identity + * leaves the owner. Before the configured list was first kept, every stored address may have been configured. */ export const settleOwnMail = async ( store: MessageStore, key: AccountKey, accountId: number, - own: ReadonlySet, mailboxes: readonly string[], - { name, now }: { name: string; now: number }, + { name, now, configured }: { name: string; now: number; configured: readonly string[] }, ): Promise => { + const account = normal(key.account) const before = await storedOwn(store, key) - const found = await store.mail.markOwnMail(accountId, { addresses: [...own], mailboxes }, now) - const others = found.filter((address) => address !== normal(key.account)) + const wanted = [...new Set(configured.map(normal))].filter((address) => address !== account).sort() + const kept = await storedList(store, key, OWN_MAIL_CONFIGURED) + const removed = (kept ?? before).filter((address) => !wanted.includes(address)) + const found = await store.mail.markOwnMail( + accountId, + { addresses: [account, ...wanted, ...before.filter((address) => !removed.includes(address))], mailboxes, removed }, + now, + ) + const others = found.filter((address) => address !== account) + const dropped = before.filter((address) => !others.includes(address)) + if (JSON.stringify(wanted) !== JSON.stringify(kept ?? []) || (kept === undefined && before.length > 0)) + await store.sync.setSyncState(key, OWN_MAIL_CONFIGURED, JSON.stringify(wanted)) if (others.length === 0 && before.length === 0) return if (JSON.stringify(others) !== JSON.stringify([...before].sort())) await store.sync.setSyncState(key, OWN_ADDRESSES, JSON.stringify(others)) + await disownIdentities(store, dropped) // Saving the account again is what links its own identities, now with these addresses. await store.accounts.saveAccount(key, { name }) } diff --git a/src/mail/parse.ts b/src/mail/parse.ts index 1d18df94a..307239670 100644 --- a/src/mail/parse.ts +++ b/src/mail/parse.ts @@ -1,6 +1,7 @@ import { CliError } from "@wirecat/cli-base" import PostalMime, { type Address as PostalAddress } from "postal-mime" import { decodeEntities } from "../domain/html-entities.js" +import { type BodySignals, bodySignalsOf } from "./body-signals.js" export interface Address { email: string @@ -21,6 +22,8 @@ export interface ParsedMail { references: string[] attachments: { id: number; name: string; mime: string | null; bytes: Uint8Array | null }[] text: string + /** schema.org markup and a calendar method read from the body, which the store keeps beside the headers. */ + signals?: BodySignals } // The store cuts a body into pieces itself; this only guards against a pathological one, like a pasted log. @@ -123,5 +126,6 @@ export const parseMail = async ( bytes: bytesOf(part.content), })), text: text.replace(/\r\n?/g, "\n").slice(0, maxBodyChars), + signals: bodySignalsOf(email.html, email.attachments), } } diff --git a/src/mail/retry.ts b/src/mail/retry.ts index 5da735b91..0fda0e4fe 100644 --- a/src/mail/retry.ts +++ b/src/mail/retry.ts @@ -9,7 +9,7 @@ import { type MailAttachmentPolicy, readAttachments, } from "./attachments.js" -import { sentAtOf } from "./email-input.js" +import { sentAtOf, storedHeaders } from "./email-input.js" import { mailFolders } from "./folders.js" import { mailHeadersOf } from "./headers.js" import { type ParsedMail, parseMail } from "./parse.js" @@ -120,7 +120,7 @@ export const retryUnread = async ({ receivedAt: Date.parse(item.receivedAt), bodyText: mail.text || null, size: item.size ?? stored.size, - ...(Object.keys(header).length ? { headers: header } : {}), + ...storedHeaders(header, mail), outgoing: mail.from === null ? null : mail.from.email === key.account, mailboxes: stored.mailboxes.map(({ externalId, name, kind }) => ({ externalId, name, kind })), ...(stored.read === null ? {} : { read: stored.read }), diff --git a/src/mail/sync.ts b/src/mail/sync.ts index cac6bb5f8..ae82c2d55 100644 --- a/src/mail/sync.ts +++ b/src/mail/sync.ts @@ -955,9 +955,10 @@ const syncRound = async ( if (bulk.size) await store.mail.setMailboxes(accountId, [bulkBox], bulk, startedAt) if (!snapshot) await store.sync.setSyncState(key, "mail_folder_scope", scope) if (!snapshot) await store.mail.backfillSentAt(accountId, SENT_AT_BACKFILL_PER_RUN) - await settleOwnMail(store, key, accountId, own, [...(sent ? [sent] : []), `label:${SENT_LABEL}`], { + await settleOwnMail(store, key, accountId, [...(sent ? [sent] : []), `label:${SENT_LABEL}`], { name: account.address, now: startedAt, + configured: account.addresses ?? [], }) await stopIfAborted() const indexed = await index?.(store, key) diff --git a/src/store/mail-types.test.ts b/src/store/mail-types.test.ts index 73f39c387..349406ba5 100644 --- a/src/store/mail-types.test.ts +++ b/src/store/mail-types.test.ts @@ -214,6 +214,54 @@ describe("the type of each email", () => { }) }) +describe("what mail sync keeps for the type", () => { + it("keeps schema.org types and a few values, the calendar method, an auto-reply and List-Post, not the HTML", async () => { + const order = + '

Thanks

' + const parcel = + '
' + + '
' + const { store } = await synced([ + mail(["Shop", "hello@shop.example.com"], "Thanks", { html: order }), + mail(["Post", "hello@post.example.com"], "Parcel", { html: parcel }), + mail(["Kai Example", "kai@corp.example.com"], "Planning", { + attachment: { name: "invite.ics", mime: "text/calendar", content: "BEGIN:VCALENDAR\r\nMETHOD:CANCEL\r\n" }, + }), + mail(["Pia Example", "pia@corp.example.com"], "Away until Monday", { + extraHeaders: ["Auto-Submitted: auto-replied", ...signed("corp.example.com", ["auto-submitted"])], + }), + mail(["Rin Example", "rin@lists.example.com"], "Release notes", { + listId: "dev.lists.example.com", + extraHeaders: ["List-Post: "], + }), + ]) + + const kept = Object.fromEntries( + (await store.mail.emails({ limit: 50 })).map((email) => [email.subject, email.headers]), + ) + expect(kept.Thanks).toMatchObject({ + "schema-types": ["Order", "Organization"], + "schema-fields": { orderNumber: "A-1001" }, + }) + expect(kept.Parcel).toMatchObject({ + "schema-types": ["ParcelDelivery"], + "schema-fields": { trackingNumber: "TRK-77" }, + }) + expect(kept.Planning).toMatchObject({ "calendar-method": "cancel" }) + expect(kept["Away until Monday"]).toMatchObject({ "auto-replied": true }) + expect(kept["Release notes"]).toMatchObject({ "list-post": true }) + expect(JSON.stringify(kept)).not.toContain(" { it("lists a shop under its receipts and under its broadcasts, with all its mail counted", async () => { const { store } = await synced([ diff --git a/src/store/sqlite/email-state.ts b/src/store/sqlite/email-state.ts index 1263648ec..615fc22fd 100644 --- a/src/store/sqlite/email-state.ts +++ b/src/store/sqlite/email-state.ts @@ -98,12 +98,17 @@ export const markEmailsRestored = ( /** * Takes the senders of the live mail in `mailboxes` as the owner's, beside `addresses`, and marks every email of the - * account from any of them outgoing. Answers the addresses, lower case. + * account from any of them outgoing. Mail outside `mailboxes` from a `removed` address that is not among them is + * incoming again. Answers the addresses, lower case. */ export const markOwnMail = ( database: CacheDatabase, accountId: number, - { addresses, mailboxes }: { addresses: readonly string[]; mailboxes: readonly string[] }, + { + addresses, + mailboxes, + removed = [], + }: { addresses: readonly string[]; mailboxes: readonly string[]; removed?: readonly string[] }, now: number, ): string[] => { const own = new Set(addresses.map((address) => address.trim().toLowerCase())) @@ -125,5 +130,17 @@ export const markOwnMail = ( AND external_id IN (SELECT value FROM json_each(?)))`, ) .run(now, accountId, JSON.stringify([...own])) + const disowned = removed.map((address) => address.trim().toLowerCase()).filter((address) => !own.has(address)) + if (disowned.length > 0) + database + .prepare( + `UPDATE emails SET outgoing = 0, updated_at = ? WHERE account_id = ? AND outgoing = 1 + AND from_identity_id IN (SELECT id FROM identities WHERE provider = 'email' + AND external_id IN (SELECT value FROM json_each(?))) + AND NOT EXISTS (SELECT 1 FROM email_mailboxes m JOIN mailboxes b ON b.id = m.mailbox_id + WHERE m.email_id = emails.id AND b.account_id = emails.account_id + AND b.external_id IN (SELECT value FROM json_each(?)))`, + ) + .run(now, accountId, JSON.stringify(disowned), JSON.stringify(mailboxes)) return [...own].sort() } diff --git a/src/store/sqlite/email-types.ts b/src/store/sqlite/email-types.ts index 219878aca..44e98e95b 100644 --- a/src/store/sqlite/email-types.ts +++ b/src/store/sqlite/email-types.ts @@ -79,7 +79,12 @@ export const typesOf = ( headers: typeof row.list === "string" ? { ...headers, "list-id": row.list } : headers, recipients: row.recipients == null ? null : Number(row.recipients), parts: JSON.parse(String(row.parts ?? "[]")) as string[], - schemaTypes: schemaTypesOf(typeof row.body_html === "string" ? row.body_html : null), + schemaTypes: [ + ...new Set([ + ...schemaTypesOf(typeof row.body_html === "string" ? row.body_html : null), + ...(Array.isArray(headers["schema-types"]) ? headers["schema-types"].map(String) : []), + ]), + ], listSenders: typeof row.list === "string" ? (senders.get(row.list) ?? 0) : 0, ownerWrote: Number(row.owner_wrote) === 1, bot: Number(row.bot) === 1, diff --git a/src/store/sqlite/emails.ts b/src/store/sqlite/emails.ts index 523e38a7d..1ada73904 100644 --- a/src/store/sqlite/emails.ts +++ b/src/store/sqlite/emails.ts @@ -346,11 +346,11 @@ export interface MailStore extends PartialMailStore, MailActivityStore, MailType /** * Takes the senders of the live mail in `mailboxes` (the Sent folder, Gmail's `label:Sent`) as the owner's, beside * `addresses`, and marks the account's mail from any of them outgoing, so mail stored before it was known counts. - * Answers the addresses, lower case. + * Mail outside `mailboxes` from a `removed` address not among them is incoming again. Answers the addresses. */ markOwnMail( accountId: number, - own: { addresses: readonly string[]; mailboxes: readonly string[] }, + own: { addresses: readonly string[]; mailboxes: readonly string[]; removed?: readonly string[] }, now: number, ): Promise /** Gives up to `limit` emails stored without `sent_at` their internal date; answers how many. */ From 989a7c2f9f7f8bab89beb3043f189454a9aa12c3 Mon Sep 17 00:00:00 2001 From: leemour Date: Thu, 26 Nov 2026 17:39:02 +0100 Subject: [PATCH 2/2] fix(mail): only a defined addresses list removes an alias; archive imports drop nothing A sync that passes no MailAccount.addresses, and an mbox import, must not read as the owner removing every alias. Removal now runs only when the caller gives the whole list. Co-Authored-By: Claude Opus 5.5 --- changes/fix-mail-own-addresses-signals.md | 5 +++-- docs/dev/MAIL.md | 5 +++-- src/mail/own.test.ts | 20 +++++++++++++++++--- src/mail/own.ts | 17 +++++++++-------- src/mail/sync.ts | 2 +- 5 files changed, 33 insertions(+), 16 deletions(-) diff --git a/changes/fix-mail-own-addresses-signals.md b/changes/fix-mail-own-addresses-signals.md index 31d484646..e4cea763b 100644 --- a/changes/fix-mail-own-addresses-signals.md +++ b/changes/fix-mail-own-addresses-signals.md @@ -1,7 +1,8 @@ ### Fixed -- **An alias the owner removes stops being the owner's on the next mail sync.** The addresses a sync is given are kept - under `mail_own_configured`. One that is gone and has no mail in Sent leaves `mail_own_addresses`; the account's +- **An alias the owner removes stops being the owner's on the next mail sync.** A defined `MailAccount.addresses` is + now the whole list; a sync without it, and an archive import, drop nothing. The list is kept under + `mail_own_configured`. One that is gone and has no mail in Sent leaves `mail_own_addresses`; the account's mail from it outside Sent is incoming again, and its email identity leaves the owner when the rules joined it. A link the owner made stays. `settleOwnMail` now takes the configured list as `configured` in its options, and `store.mail.markOwnMail` takes `removed`. No store version. Part of #3321. diff --git a/docs/dev/MAIL.md b/docs/dev/MAIL.md index 68a8def3f..231f83326 100644 --- a/docs/dev/MAIL.md +++ b/docs/dev/MAIL.md @@ -44,8 +44,9 @@ account `{ provider: "email", account: }`. (`store.mail.markOwnMail`), and the account is saved again, so `linkOwnIdentities` joins their identities to the owner. Partial completion, `readEmailWhole` and a server search read the same list. A mail tie needs mail the owner wrote, so this is what gives the people an alias writes to their tie. Nothing is taken from a name. -- **An alias the owner removes.** The list a sync is given is kept under `mail_own_configured`. An address that was in - it and is not now, and has no live mail in Sent, leaves `mail_own_addresses`: the account's mail from it outside +- **An alias the owner removes.** A defined `addresses` is the whole list: a caller passes it only when it knows every + alias. The list is kept under `mail_own_configured`; a sync with no `addresses`, and an archive import, change + nothing stored. An address that was in it and is not now, and has no live mail in Sent, leaves `mail_own_addresses`: the account's mail from it outside Sent is incoming again, and its email identity leaves the owner when the rules joined it (`account`, by `rules`). A link the owner made stays. The join moved every identity of the alias's person, and only the email identity moves back. A store from before `mail_own_configured` takes every stored address as possibly configured once: an address diff --git a/src/mail/own.test.ts b/src/mail/own.test.ts index ca7fa08e9..12477433c 100644 --- a/src/mail/own.test.ts +++ b/src/mail/own.test.ts @@ -169,7 +169,7 @@ describe("the owner's mail", () => { expect(await outgoing(store)).toEqual({ "9001": false, "9002": true }) expect(await ownerHolds(store, ALIAS)).toBe(true) - await sync(store, box) + await sync(store, box, { addresses: [] }) expect(await outgoing(store)).toEqual({ "9001": false, "9002": false }) expect(await tiesOf(store, "pat@example.test")).not.toContain("mail") @@ -191,13 +191,27 @@ describe("the owner's mail", () => { await store.people.unlinkIdentity({ provider: "email", id: other }, { method: "unlink", by: "owner" }) await store.people.linkToOwner({ provider: "email", id: other }) - await sync(store, box) + await sync(store, box, { addresses: [] }) expect(await outgoing(store)).toEqual({ "9001": true, "9002": false, "9003": false }) expect(await ownerHolds(store, ALIAS)).toBe(true) expect(await ownerHolds(store, other)).toBe(true) }) + it("drops no alias for a sync given no list, nor for an archive import", async () => { + const store = await sandbox() + const box: FakeMailbox = { + messages: [mail(1), mail(2, { from: ["Owner Example", ALIAS], to: [["Pat Example", "pat@example.test"]] })], + } + await sync(store, box, { addresses: [ALIAS] }) + + await sync(store, box) + await sync(store, box, { mode: "mbox", addresses: [] }) + + expect(await outgoing(store)).toEqual({ "9001": false, "9002": true }) + expect(await ownerHolds(store, ALIAS)).toBe(true) + }) + it("lets go of an alias stored before the configured list was kept", async () => { const store = await sandbox() const box: FakeMailbox = { @@ -206,7 +220,7 @@ describe("the owner's mail", () => { await sync(store, box, { addresses: [ALIAS] }) await store.sync.clearSyncState(KEY, OWN_MAIL_CONFIGURED) - await sync(store, box) + await sync(store, box, { addresses: [] }) expect(await outgoing(store)).toEqual({ "9001": false, "9002": false }) expect(await ownerHolds(store, ALIAS)).toBe(false) diff --git a/src/mail/own.ts b/src/mail/own.ts index 6e87492e8..ebd14de8f 100644 --- a/src/mail/own.ts +++ b/src/mail/own.ts @@ -49,22 +49,23 @@ const disownIdentities = async (store: MessageStore, addresses: readonly string[ /** * After a sync: the senders of the mail in Sent join the owner's addresses beside `configured`, the account's mail from - * any of them becomes outgoing, and their identities join the owner as the account's own does. An address no longer - * configured, with no mail in Sent, stops being the owner's: its mail outside Sent is incoming again and its identity - * leaves the owner. Before the configured list was first kept, every stored address may have been configured. + * any of them becomes outgoing, and their identities join the owner as the account's own does. A `configured` list is + * the whole list: an address no longer in it, with no mail in Sent, stops being the owner's, its mail outside Sent is + * incoming again and its identity leaves the owner. Before the list was first kept, every stored address may have + * been configured. Without a list nothing stored is dropped: a caller that does not know the list removes nothing. */ export const settleOwnMail = async ( store: MessageStore, key: AccountKey, accountId: number, mailboxes: readonly string[], - { name, now, configured }: { name: string; now: number; configured: readonly string[] }, + { name, now, configured }: { name: string; now: number; configured?: readonly string[] | undefined }, ): Promise => { const account = normal(key.account) const before = await storedOwn(store, key) - const wanted = [...new Set(configured.map(normal))].filter((address) => address !== account).sort() - const kept = await storedList(store, key, OWN_MAIL_CONFIGURED) - const removed = (kept ?? before).filter((address) => !wanted.includes(address)) + const wanted = [...new Set((configured ?? []).map(normal))].filter((address) => address !== account).sort() + const kept = configured === undefined ? wanted : await storedList(store, key, OWN_MAIL_CONFIGURED) + const removed = configured === undefined ? [] : (kept ?? before).filter((address) => !wanted.includes(address)) const found = await store.mail.markOwnMail( accountId, { addresses: [account, ...wanted, ...before.filter((address) => !removed.includes(address))], mailboxes, removed }, @@ -72,7 +73,7 @@ export const settleOwnMail = async ( ) const others = found.filter((address) => address !== account) const dropped = before.filter((address) => !others.includes(address)) - if (JSON.stringify(wanted) !== JSON.stringify(kept ?? []) || (kept === undefined && before.length > 0)) + if (configured !== undefined && (JSON.stringify(wanted) !== JSON.stringify(kept ?? []) || kept === undefined)) await store.sync.setSyncState(key, OWN_MAIL_CONFIGURED, JSON.stringify(wanted)) if (others.length === 0 && before.length === 0) return if (JSON.stringify(others) !== JSON.stringify([...before].sort())) diff --git a/src/mail/sync.ts b/src/mail/sync.ts index ae82c2d55..dc85a4d33 100644 --- a/src/mail/sync.ts +++ b/src/mail/sync.ts @@ -958,7 +958,7 @@ const syncRound = async ( await settleOwnMail(store, key, accountId, [...(sent ? [sent] : []), `label:${SENT_LABEL}`], { name: account.address, now: startedAt, - configured: account.addresses ?? [], + configured: snapshot ? undefined : account.addresses, }) await stopIfAborted() const indexed = await index?.(store, key)