diff --git a/changes/fix-mail-own-addresses-signals.md b/changes/fix-mail-own-addresses-signals.md
new file mode 100644
index 000000000..e4cea763b
--- /dev/null
+++ b/changes/fix-mail-own-addresses-signals.md
@@ -0,0 +1,17 @@
+### Fixed
+
+- **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.
+
+### 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..231f83326 100644
--- a/docs/dev/MAIL.md
+++ b/docs/dev/MAIL.md
@@ -44,6 +44,13 @@ 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.** 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
+ 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 +60,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 +238,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 = /", 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..12477433c 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,72 @@ 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, { addresses: [] })
+
+ 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, { 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 = {
+ 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, { addresses: [] })
+
+ 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..ebd14de8f 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,50 @@ 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. 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,
- own: ReadonlySet,
mailboxes: readonly string[],
- { name, now }: { name: string; now: number },
+ { name, now, configured }: { name: string; now: number; configured?: readonly string[] | undefined },
): 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 = 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 },
+ now,
+ )
+ const others = found.filter((address) => address !== account)
+ const dropped = before.filter((address) => !others.includes(address))
+ 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()))
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..dc85a4d33 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: snapshot ? undefined : 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("