Skip to content
Merged
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
23 changes: 23 additions & 0 deletions changes/feat-contact-signals.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
### Added

- **`people.list` rows say how a sender's mail reached the owner.** Each row has `reach` (`direct`, `group`,
`broadcast` or `null`) and `signals` (`auto-submitted`, `null-return-path`, `no-reply`, `one-click-unsubscribe`,
`feedback-id`, `bulk-mail`, `discussion-list`, `many-recipients`, `undisclosed-recipients`), worked out for the page
and not stored ([ARCHITECTURE.md](../docs/dev/ARCHITECTURE.md)). A List-Id three addresses write to is a discussion
(`group`), one sender under many `+tag` addresses a newsletter. The types `Reach`, `SenderSignal` and `REACHES` are
exported from `./store`.
- **Mail sync keeps `Auto-Submitted`, one-click `List-Unsubscribe-Post` and `Feedback-ID`** in `emails.headers`,
each only when a DKIM signature of the From's own domain that Gmail passed covers it, and an empty Return-Path
([MAIL.md](../docs/dev/MAIL.md#syncmailsource-store-options)). Mail of an IMAP server without Gmail's stamp keeps
none of the three. No store version.

### Fixed

- **A sender whose mail a program sends is `automated`, not a stranger.** Most of their mail with a signed
`Auto-Submitted` (not an auto-reply) or an empty Return-Path makes them `automated` (signals `auto-submitted`,
`null-return-path`), unless the owner wrote to them. Every stored kind is worked out again on the next list.

### Changed — may break callers

- **`KindSignal` has two more values, `auto-submitted` and `null-return-path`, and `ListedPerson` two more fields,
`reach` and `signals`.** Code that maps every `KindSignal` or builds a `ListedPerson` by hand adds them.
11 changes: 10 additions & 1 deletion docs/dev/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -660,7 +660,9 @@ proposes them instead. A no-reply address (`isNoReplyAddress`) is no one's: it n
one kind and lists one kind at a time. The owner, people added by hand and task assignees are a `person`; then
`automated` (a bot, a no-reply address, whose local part has a no-reply word as one of its parts or, `bounce`
aside, starts or ends with one; a notification address, with `notify`, `notification(s)` or `alert(s)` as one part;
mostly bulk mail, memo's `bulk_never_replied`, a notification name); then
mostly bulk mail, memo's `bulk_never_replied`, a notification name; most of their mail with an `Auto-Submitted`
their own domain signed or an empty Return-Path ([MAIL.md](MAIL.md#syncmailsource-store-options)), unless the owner
wrote to them); then
`organization` (`organization_identities`, a role address, a legal form or company word in the name); then a named
`person` with a tie; a named one with no tie is a `stranger`;
one with nothing to show as a name is `unsorted`. Before any of these, `test` holds what a test run left
Expand All @@ -682,6 +684,13 @@ proposes them instead. A no-reply address (`isNoReplyAddress`) is no one's: it n
(`PRAGMA data_version`), else the list answers from memory. `KIND_RULES` in `people-list.ts`
is bumped when the rules change in code, which works out everyone again; a read-only open with anything to work out
answers from memory (cli-testing `performance/memo/people-list`).
Each row of a page also carries `reach` and `signals` (`sender-signals.ts`), worked out for that page only and
never stored: `broadcast` for mail with a one-click unsubscribe or a `Feedback-ID` its domain signed, in the bulk
box, or with no To or Cc; `group` for a List-Id that `DISCUSSION_SENDERS` (3) addresses send to, `+tag` aside, or
more than `SMALL_GROUP_MEMBERS` recipients; else `direct`. The owner missing from a To or Cc that names others says
nothing, since an alias the store does not know looks the same. The reach most of their mail had wins, the wider on a
tie; mail the owner wrote them or a private chat both wrote in makes it `direct`, and with no mail a one-to-one chat
or a small group does. `null` when nothing says. The page reads every stored email's List-Id once for this.
`people.similar` serves a form that adds a person: names starting like the typed words, the same `variantKey` first;
a `name:` search looks for the typed text in both scripts (`spellings`). Each row's `usernameSource` names the
messenger its `@username` belongs to.
Expand Down
10 changes: 10 additions & 0 deletions docs/dev/MAIL.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,16 @@ 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.
- **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
`auto-replied`, [RFC 3834](https://www.rfc-editor.org/rfc/rfc3834)), `list-unsubscribe-post` (one-click,
[RFC 8058](https://www.rfc-editor.org/rfc/rfc8058)) and `feedback-id`. The sender writes every header itself, so
they are kept only when a DKIM signature Gmail passed covers them and the signature's domain has the From's
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.
- **Quick folders.** A folder whose `search` says `quick` is not listed with headers: the sync lists the UID, flags,
date and size of every message in the window, and reads the raw bytes of the newest `max` not done and not located
(a budgeted run: `fetchBatch` a round). It takes the id from the Message-ID, so stored mail keeps its id and the same
Expand Down
2 changes: 1 addition & 1 deletion docs/storage/schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -732,7 +732,7 @@ One email.
| `flagged` | integer | | | 1 when it is flagged or starred |
| `draft` | integer | | | 1 for a draft not yet sent |
| `size` | integer | | | the raw email's size, in bytes |
| `headers` | text | | | JSON: every header, as received |
| `headers` | text | | | JSON: the header fields `mailHeadersOf` keeps (docs/dev/MAIL.md) |
| `metadata` | text | | | JSON: what the source sends that has no column, and is not searched |
| `created_at` | integer | not null | | when this row was saved here |
| `updated_at` | integer | not null | | when this row last changed here |
Expand Down
2 changes: 1 addition & 1 deletion scripts/schema/spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -658,7 +658,7 @@ const NEW = {
c("flagged", "integer"),
c("draft", "integer"),
c("size", "integer"),
c("headers", "text", { note: "JSON: every header, as received" }),
c("headers", "text", { note: "JSON: the header fields `mailHeadersOf` keeps (docs/dev/MAIL.md)" }),
meta(),
...ts(),
del(),
Expand Down
2 changes: 2 additions & 0 deletions src/domain/person-kinds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export type KindSignal =
| "bot"
| "no-reply"
| "notification-address"
| "auto-submitted"
| "null-return-path"
| "bulk-mail"
| "bulk-never-replied"
| "automated-name"
Expand Down
59 changes: 59 additions & 0 deletions src/mail/headers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { describe, expect, it } from "vitest"
import { mailHeadersOf, signedFieldsOf, unfold } from "./headers.js"

const head = (lines: string[]) => unfold(`${lines.join("\r\n")}\r\n`)
const raw = (lines: string[]) => new TextEncoder().encode(`${lines.join("\r\n")}\r\n\r\nBody`)

const SIGNATURE = "DKIM-Signature: v=1; d=news.shop.example; s=s1;\r\n h=From:Subject:Auto-Submitted:Feedback-ID; b=x"

describe("signedFieldsOf", () => {
it("names the fields a passing signature of the From's own domain covers", () => {
const stamp = "Authentication-Results: mx.google.com; dkim=pass header.i=@news.shop.example header.s=s1"
expect([...signedFieldsOf(head([SIGNATURE, stamp]), "deals@shop.example")]).toEqual([
"from",
"subject",
"auto-submitted",
"feedback-id",
])
})

it("reads a signer named with a local part", () => {
const stamp = "Authentication-Results: mx.google.com; dkim=pass header.i=bot@news.shop.example"
expect(signedFieldsOf(head([SIGNATURE, stamp]), "deals@shop.example").has("auto-submitted")).toBe(true)
})

it("trusts nothing from another domain's signature, a failed one or a stamp not Gmail's", () => {
const pass = "Authentication-Results: mx.google.com; dkim=pass header.i=@news.shop.example"
expect(signedFieldsOf(head([SIGNATURE, pass]), "deals@other.example").size).toBe(0)
const failed = "Authentication-Results: mx.google.com; dkim=fail header.i=@news.shop.example"
expect(signedFieldsOf(head([SIGNATURE, failed]), "deals@shop.example").size).toBe(0)
const foreign = "Authentication-Results: relay.shop.example; dkim=pass header.i=@news.shop.example"
expect(signedFieldsOf(head([SIGNATURE, foreign]), "deals@shop.example").size).toBe(0)
})
})

describe("mailHeadersOf", () => {
it("keeps Auto-Submitted, one-click unsubscribe and Feedback-ID only when signed, and an empty Return-Path", () => {
const fields = [
"From: Deals <deals@shop.example>",
"Return-Path: <>",
"Auto-Submitted: auto-generated",
"Feedback-ID: 1:2:shop",
"List-Unsubscribe-Post: List-Unsubscribe=One-Click",
SIGNATURE,
"Authentication-Results: mx.google.com; dkim=pass header.i=@news.shop.example",
]
expect(mailHeadersOf(raw(fields))).toEqual({
dkim: "pass",
"auto-submitted": "auto-generated",
"feedback-id": true,
"null-return-path": true,
})
})

it("takes an auto-reply's empty Return-Path for no program", () => {
expect(mailHeadersOf(raw(["From: pia@office.example", "Return-Path: <>", "Auto-Submitted: auto-replied"]))).toEqual(
{},
)
})
})
73 changes: 68 additions & 5 deletions src/mail/headers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { decodeWords } from "postal-mime"
import { registrableOf } from "./score.js"

/**
* The header fields memo reads at list time: enough to group mail by sender, apply the owner's rules and keep
Expand Down Expand Up @@ -41,11 +42,15 @@ const fieldsOf = (unfolded: string, name: string): string[] =>
[...unfolded.matchAll(new RegExp(`^${name}:[ \\t]*(.*?)\\r?$`, "gim"))].map(([, value]) => value as string)

/**
* The verdicts in Gmail's own Authentication-Results. Only the copy Gmail stamps as mx.google.com counts: a sender
* can add one under any other name, and Gmail removes forged copies under its own (RFC 8601 §5).
* Gmail's own Authentication-Results. Only the copy Gmail stamps as mx.google.com counts: a sender can add one under
* any other name, and Gmail removes forged copies under its own (RFC 8601 §5).
*/
const gmailStampOf = (unfolded: string): string | undefined =>
fieldsOf(unfolded, "Authentication-Results").find((value) => /^mx\.google\.com\s*;/i.test(value))

/** The verdicts in Gmail's own Authentication-Results. */
export const authOf = (unfolded: string): AuthVerdicts | undefined => {
const stamped = fieldsOf(unfolded, "Authentication-Results").find((value) => /^mx\.google\.com\s*;/i.test(value))
const stamped = gmailStampOf(unfolded)
if (stamped === undefined) return undefined
const results = [...stamped.matchAll(/\b(spf|dkim|dmarc)=([a-z]+)/gi)].map(([, method, result]) => [
(method as string).toLowerCase(),
Expand All @@ -60,6 +65,61 @@ export const authOf = (unfolded: string): AuthVerdicts | undefined => {
return Object.keys(verdicts).length ? verdicts : undefined
}

const tagsOf = (value: string): Map<string, string> =>
new Map(
value.split(";").flatMap((tag) => {
const at = tag.indexOf("=")
return at === -1 ? [] : [[tag.slice(0, at).trim().toLowerCase(), tag.slice(at + 1).replace(/\s+/g, "")]]
}),
)

/**
* The header fields a DKIM signature Gmail passed covers, when that signature's domain is the From's own (its
* registrable domain). A sender writes every header itself; only a signature of its own domain vouches for one.
* Without Gmail's stamp nothing is trusted: other servers' Authentication-Results may be the sender's own.
*/
export const signedFieldsOf = (unfolded: string, from: string | undefined): Set<string> => {
const stamped = gmailStampOf(unfolded)
if (stamped === undefined || from === undefined) return new Set()
const passed = [...stamped.matchAll(/\bdkim=pass\b[^;]*?\bheader\.[id]=([^\s;]+)/gi)].map(([, identity]) =>
(identity as string).slice((identity as string).lastIndexOf("@") + 1).toLowerCase(),
)
const own = registrableOf(from)
const signed = new Set<string>()
for (const signature of fieldsOf(unfolded, "DKIM-Signature")) {
const tags = tagsOf(signature)
const domain = tags.get("d")?.toLowerCase()
if (domain === undefined || registrableOf(domain) !== own) continue
if (!passed.some((one) => one === domain || one.endsWith(`.${domain}`))) continue
for (const name of (tags.get("h") ?? "").split(":")) if (name !== "") signed.add(name.toLowerCase())
}
return signed
}

/**
* 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`.
* 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.
*/
const programSignalsOf = (unfolded: string, from: string | undefined): Record<string, string | boolean> => {
const signed = signedFieldsOf(unfolded, from)
const submitted = field(unfolded, "Auto-Submitted")
?.trim()
.toLowerCase()
.split(/[\s;(]/)[0]
const generated = submitted !== undefined && submitted !== "" && submitted !== "no" && submitted !== "auto-replied"
const oneClick = /list-unsubscribe\s*=\s*one-click/i.test(field(unfolded, "List-Unsubscribe-Post") ?? "")
return {
...(generated && signed.has("auto-submitted") ? { "auto-submitted": submitted } : {}),
...(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"
? { "null-return-path": true }
: {}),
}
}

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 @@ -115,19 +175,22 @@ const headTextOf = (raw: Uint8Array): string => {
export const headersOfRaw = (raw: Uint8Array): MailHeaders => headersOf(headTextOf(raw))

/**
* List-Id, the bulk-mail fields, Reply-To and Gmail's SPF, DKIM and DMARC verdicts of a whole email, kept on mail
* stored in full so a rule or a sender score can be worked out from the store later. Names are lower case.
* List-Id, the bulk-mail fields, Reply-To, Gmail's SPF, DKIM and DMARC verdicts 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.
*/
export const mailHeadersOf = (raw: Uint8Array): Record<string, string | boolean> => {
const unfolded = unfold(headTextOf(raw))
const listId = listIdOf(field(unfolded, "List-Id"))
const precedence = field(unfolded, "Precedence")?.trim().toLowerCase()
const [replyTo] = addressesOf(field(unfolded, "Reply-To"))
const [from] = addressesOf(field(unfolded, "From"))
return {
...(listId ? { "list-id": listId } : {}),
...(replyTo === undefined ? {} : { "reply-to": replyTo }),
...authOf(unfolded),
...(field(unfolded, "List-Unsubscribe") === undefined ? {} : { "list-unsubscribe": true }),
...(precedence ? { precedence } : {}),
...programSignalsOf(unfolded, from),
}
}
Loading
Loading