Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions changes/fix-mail-own-addresses-signals.md
Original file line number Diff line number Diff line change
@@ -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.
20 changes: 19 additions & 1 deletion docs/dev/MAIL.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ account `{ provider: "email", account: <address, lower case> }`.
(`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
Expand All @@ -53,7 +60,17 @@ account `{ provider: "email", account: <address, lower case> }`.
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
Expand Down Expand Up @@ -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:<holder>` | a holder's processing mark: `throughId`, `throughAt`, `held`, `read`, `skipped` by reason |
Expand Down
71 changes: 71 additions & 0 deletions src/mail/body-signals.ts
Original file line number Diff line number Diff line change
@@ -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<string, string | string[] | Record<string, string>>

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<string, string> => {
const blocks = jsonLdOf(html)
const fields: Record<string, string> = {}
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 }),
}
}
11 changes: 10 additions & 1 deletion src/mail/email-input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string | boolean>,
mail: Pick<ParsedMail, "signals">,
): Pick<EmailInput, "headers"> => {
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,
Expand All @@ -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),
})
22 changes: 22 additions & 0 deletions src/mail/headers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <pia@shop.example>",
"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: <dev.lists.example>", `List-Post: ${post}`]
expect(mailHeadersOf(raw(list("<mailto:dev@lists.example>")))).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 <news@shop.example>",
Expand Down
11 changes: 9 additions & 2 deletions src/mail/headers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand All @@ -112,6 +113,8 @@ const programSignalsOf = (unfolded: string, from: string | undefined): Record<st
const oneClick = /list-unsubscribe\s*=\s*one-click/i.test(field(unfolded, "List-Unsubscribe-Post") ?? "")
return {
...(generated && signed.has("auto-submitted") ? { "auto-submitted": submitted } : {}),
// Its own key: `auto-submitted` marks a program, and a person's out-of-office makes no bot.
...(submitted === "auto-replied" && signed.has("auto-submitted") ? { "auto-replied": true } : {}),
...(oneClick && signed.has("list-unsubscribe-post") ? { "list-unsubscribe-post": true } : {}),
...(field(unfolded, "Feedback-ID") !== undefined && signed.has("feedback-id") ? { "feedback-id": true } : {}),
...(/^\s*<\s*>/.test(field(unfolded, "Return-Path") ?? "") && submitted !== "auto-replied"
Expand All @@ -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" <real@z.com>), so quoted names and comments go first.
Expand Down Expand Up @@ -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.
Expand All @@ -208,6 +214,7 @@ export const mailHeadersOf = (raw: Uint8Array): Record<string, string | boolean>
...(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),
Expand Down
6 changes: 6 additions & 0 deletions src/mail/mail-types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down
33 changes: 24 additions & 9 deletions src/mail/mail-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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")
Expand All @@ -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)
Expand All @@ -218,21 +225,29 @@ export const mailTypeOf = (input: MailTypeInput): MailTypeOf => {
return typed("other", null)
}

const JSON_LD_OPEN = /<script[^>]*type\s*=\s*["']?application\/ld\+json[^>]*>/gi
// `[^<>]` and not `[^>]`: a run of `<script` with no `>` would be read to the end from each of them.
const JSON_LD_OPEN = /<script[^<>]*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<string>()
/** 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("</script>", 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<string>()
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]
}
Loading
Loading