From 0e1b7128ad7f34defdbe012b5a7846623f0f2dd9 Mon Sep 17 00:00:00 2001 From: leemour Date: Thu, 26 Nov 2026 01:32:42 +0100 Subject: [PATCH] feat(mail): subscriptions read, List-Unsubscribe targets, bots by what they send Closes the gaps of #3371 for WireCat Desktop's Subscriptions view and Bots filters (owner's rulings, 2026-11-25). - store.mail.subscriptions: broadcast mail grouped by List-Id, else by the sender, newest group first, grouped, counted and paged in SQL. Each group gives its key, List-Id, name, sender ref and address, mail count, newest email and unsubscribe target (https, mailto, oneClick). The target is looked up for the page's groups only, through emails_by_list_id or the sender's identities. - mailHeadersOf keeps list-unsubscribe-https and list-unsubscribe-mailto, only under the From domain's passing DKIM signature that covers List-Unsubscribe. list-unsubscribe and list-unsubscribe-post are unchanged. - people.listBots takes sends: alerts, receipts, newsletters, marketing, messenger, mapped to mail types in BOT_SENDS, filtered in SQL. No store version: the targets live in emails.headers, and the read stays fast on the existing indexes (cli-testing performance/mail/subscriptions). Nothing unsubscribes. Co-Authored-By: Claude Opus 5.5 --- biome.json | 2 +- changes/feat-mail-subscriptions.md | 17 ++ docs/dev/GLOSSARY.md | 1 + docs/dev/MAIL.md | 7 + docs/reasons.md | 1 + src/errors/reasons.ts | 1 + src/mail/headers.test.ts | 19 +++ src/mail/headers.ts | 24 ++- src/store/areas.ts | 7 + src/store/index.ts | 7 + src/store/mail-subscriptions.test.ts | 164 ++++++++++++++++++ src/store/people.ts | 3 +- src/store/sqlite/bot-sends.ts | 49 ++++++ src/store/sqlite/emails.ts | 4 +- src/store/sqlite/mail-subscriptions.ts | 222 +++++++++++++++++++++++++ src/store/sqlite/sender-bots.ts | 14 +- 16 files changed, 535 insertions(+), 7 deletions(-) create mode 100644 changes/feat-mail-subscriptions.md create mode 100644 src/store/mail-subscriptions.test.ts create mode 100644 src/store/sqlite/bot-sends.ts create mode 100644 src/store/sqlite/mail-subscriptions.ts diff --git a/biome.json b/biome.json index 9a2bda3e3..77bf3f6ff 100644 --- a/biome.json +++ b/biome.json @@ -792,7 +792,7 @@ "noExcessiveLinesPerFile": { "level": "error", "options": { - "maxLines": 1038 + "maxLines": 1040 } } } diff --git a/changes/feat-mail-subscriptions.md b/changes/feat-mail-subscriptions.md new file mode 100644 index 000000000..40b3e1243 --- /dev/null +++ b/changes/feat-mail-subscriptions.md @@ -0,0 +1,17 @@ +### Added + +- **Subscriptions: `store.mail.subscriptions`** (experimental). Broadcast mail grouped by `List-Id`, else by its + sender (`sender-bot:`, `person:` or `address:
`), newest group first, grouped, counted and paged in + SQL (`limit`, default 100, and `offset`; `accountIds`, `since`, `until` and `types` narrow it). Each group gives its + `key`, `listId`, `name`, the `sender` ref and `address` of its newest email, its mail count, that `newest` email and + `unsubscribe`: the `https` and `mailto` targets and `oneClick` from its newest email that names one, or `null`. + Nothing is unsubscribed. A store opened read-only works types out in memory, as the type filters do. +- **List-Unsubscribe targets are kept.** Mail stored in full keeps `list-unsubscribe-https` and + `list-unsubscribe-mailto` in `emails.headers`, only when the From domain's DKIM signature that Gmail passed covers + `List-Unsubscribe`. `list-unsubscribe` stays `true` whenever the field is present, and `list-unsubscribe-post` is + kept as before. Mail stored earlier has no target until it is read again. No store version. +- **`people.listBots` filters by what a bot sends:** `sends` takes `alerts` (`security`, `system_alert`, + `account_notice`), `receipts` (`order`, `bill`, `shipping`), `newsletters`, `marketing` (`promotion`) and + `messenger` (a bot with an account in a messenger), any of them, in SQL. `BOT_SENDS` and `BotSends` are exported + from `@wirecat/cli-core/store` and `@wirecat/cli-core/store/areas` (experimental), so memo and Desktop read one map. + An unknown name is refused with `sender-bot.unknown-sends`. diff --git a/docs/dev/GLOSSARY.md b/docs/dev/GLOSSARY.md index d1e33258f..ca000c633 100644 --- a/docs/dev/GLOSSARY.md +++ b/docs/dev/GLOSSARY.md @@ -79,6 +79,7 @@ Verbs used but not in cli-base's vocabulary, by CLI (2026-10-12). Each needs a r | bot | a program that writes to the owner: a no-reply or alert address, a messenger's bot, a service's mail; an entity apart from people, with a name, identities and an optional organization, and no ties, tasks or merge review (`sender-bot:`, the `sender_bots` table). Not an agent: `bot:` and the `bots` table are agents that work here | automated person, sender (for a bot) | `people list kind:automated` still lists people a name or a bulk mailbox marks; memo's `{ bot }` author and `bot list` mean agents and a messenger's bot account | | mail type | what one email is, apart from who sent it: one of the words in [Mail types](#mail-types), worked out per email from what the store keeps of it (`emails.mail_type`; key `mailType` in the API, `mail_type` in CLI JSON; search field `type:`). A sender's view is a summary of its mail, so a shop that sends receipts and sales counts under `order` and under `promotion` | category, kind (a person's `kind` is another thing), label | none | | sorting rule | the owner's or the program's word on what mail is, by one of five scopes tried in this order: one mail, a List-Id or a subject pattern, an address, a registrable domain; then the header classifier. It sets a mail type, makes the sender a bot or a person for its whole history, or files the sender under an organization (`mail_sort_rules`, `store.mail.sorting`). An email it typed has `typeSignal` `rule:`. Not a mail rule: `mail_rules` decide how one account's sync stores mail | filter, mail rule, label rule | none | +| subscription (mail) | a list, or a sender of broadcast mail with no List-Id, as Subscriptions shows it: grouped by `List-Id`, else by the sender, with its mail count, newest email and unsubscribe target (`store.mail.subscriptions`). Not a `subscriptions` row, which is a charge that repeats | feed, newsletter, mailing list | none | | reach | how a message reached the owner: `direct` (to the owner or a few people), `group` (a large group or a discussion list), `broadcast` (one sender to many readers who cannot answer in place). Worked out per email (`emails.reach`, key `reach`, search field `reach:`) and per sender (`people list`) | audience, scope | none | | contact | one person as one source knows them: a mail correspondent, a Telegram user, a Drive owner, a calendar attendee; an `identities` row | user | none found beyond the above | | entity | the thing the owner means — a person, an event, a document; it carries no provider id ([WC-DATA-2](https://github.com/WireCatLabs/cli-base/blob/main/docs/standards/data-model.md)) | record, object | none | diff --git a/docs/dev/MAIL.md b/docs/dev/MAIL.md index 2b794bccb..7a246dbec 100644 --- a/docs/dev/MAIL.md +++ b/docs/dev/MAIL.md @@ -54,6 +54,13 @@ account `{ provider: "email", account: }`. 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. +- **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 + [RFC 2369](https://www.rfc-editor.org/rfc/rfc2369)'s list), only when the same signature covers `List-Unsubscribe`: + a target is where an unsubscribe goes, so a forged one is never offered. `store.mail.subscriptions` reads them; with + `list-unsubscribe-post` and an https target the unsubscribe is one-click (RFC 8058, which requires both fields + signed). Nothing in cli-core unsubscribes. Mail stored before cli-core kept the targets has none 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 diff --git a/docs/reasons.md b/docs/reasons.md index 86476b2fb..9f88800f8 100644 --- a/docs/reasons.md +++ b/docs/reasons.md @@ -537,6 +537,7 @@ headings. | `sender-bot.not-a-person` | `validation_error` | the identity named is a sender bot's, not a person's; name a person | | | `sender-bot.not-found` | `not_found` | no sender bot has that id; the bots list names them | | | `sender-bot.owner` | `validation_error` | the owner's own person is never a bot | | +| `sender-bot.unknown-sends` | `validation_error` | a bot list filters by alerts, receipts, newsletters, marketing or messenger | | | `serve.outdated` | `configuration_error` | the store or the installed version is newer than this serve; it stopped so its unit starts the installed one | | | `session.duplicate` | `conflict` | another profile here already signs in to this account as this user | | | `session.missing` | `authentication_error` | this profile is not signed in: no saved sign-in or API token | | diff --git a/src/errors/reasons.ts b/src/errors/reasons.ts index 556111b5c..26212bd5e 100644 --- a/src/errors/reasons.ts +++ b/src/errors/reasons.ts @@ -740,6 +740,7 @@ const OTHERS: Entry[] = [ validation("sender-bot.not-a-person", "the identity named is a sender bot's, not a person's; name a person"), validation("sender-bot.empty", "the person or bot named holds no identity to move"), validation("sender-bot.assignee", "a sender bot is no one's assignee; move it to a person first"), + validation("sender-bot.unknown-sends", "a bot list filters by alerts, receipts, newsletters, marketing or messenger"), validation("mail-sort.scope", "a sorting rule's scope is mail, list, subject, address or domain"), validation("mail-sort.apply-to", "a sorting rule says whether it sorts past mail too: applyTo all or new"), validation("mail-sort.value", "the value names no mail, list, subject, address or domain of that scope"), diff --git a/src/mail/headers.test.ts b/src/mail/headers.test.ts index bc4d1bcc9..89fa98fde 100644 --- a/src/mail/headers.test.ts +++ b/src/mail/headers.test.ts @@ -56,4 +56,23 @@ describe("mailHeadersOf", () => { {}, ) }) + + it("keeps the https and mailto unsubscribe targets only under the From domain's own signature", () => { + const fields = (signed: string) => [ + "From: News ", + "List-Unsubscribe: , ,", + " ", + "List-Unsubscribe-Post: List-Unsubscribe=One-Click", + `DKIM-Signature: v=1; d=shop.example; s=s1; h=From:${signed}; b=x`, + "Authentication-Results: mx.google.com; dkim=pass header.i=@shop.example", + ] + expect(mailHeadersOf(raw(fields("List-Unsubscribe:List-Unsubscribe-Post")))).toEqual({ + dkim: "pass", + "list-unsubscribe": true, + "list-unsubscribe-https": "https://shop.example/u/1", + "list-unsubscribe-mailto": "mailto:leave@shop.example?subject=leave", + "list-unsubscribe-post": true, + }) + expect(mailHeadersOf(raw(fields("Subject")))).toEqual({ dkim: "pass", "list-unsubscribe": true }) + }) }) diff --git a/src/mail/headers.ts b/src/mail/headers.ts index 554e3c54b..d2e8bf5a7 100644 --- a/src/mail/headers.ts +++ b/src/mail/headers.ts @@ -120,6 +120,22 @@ const programSignalsOf = (unfolded: string, from: string | undefined): Record => { + const value = field(unfolded, "List-Unsubscribe") + if (value === undefined || !signedFieldsOf(unfolded, from).has("list-unsubscribe")) return {} + const targets = [...value.matchAll(/<\s*([^<>\s]+)\s*>/g)].map(([, target]) => target as string) + const https = targets.find((target) => /^https:\/\/[^/\s]/i.test(target)) + const mailto = targets.find((target) => /^mailto:[^@\s]+@[^@\s]+/i.test(target)) + return { + ...(https === undefined ? {} : { "list-unsubscribe-https": https }), + ...(mailto === undefined ? {} : { "list-unsubscribe-mailto": mailto }), + } +} + 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. @@ -176,9 +192,10 @@ 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 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. + * List-Id, 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. */ export const mailHeadersOf = (raw: Uint8Array): Record => { const unfolded = unfold(headTextOf(raw)) @@ -192,6 +209,7 @@ export const mailHeadersOf = (raw: Uint8Array): Record ...authOf(unfolded), ...(field(unfolded, "List-Unsubscribe") === undefined ? {} : { "list-unsubscribe": true }), ...(precedence ? { precedence } : {}), + ...unsubscribeTargetsOf(unfolded, from), ...programSignalsOf(unfolded, from), } } diff --git a/src/store/areas.ts b/src/store/areas.ts index 2f9e6a128..7d6868978 100644 --- a/src/store/areas.ts +++ b/src/store/areas.ts @@ -10,6 +10,7 @@ export { type AddedSourceInput, addedSourceKeyOf, } from "./sqlite/added-sources.js" +export { BOT_SENDS, type BotSends } from "./sqlite/bot-sends.js" export type { ContractFilter } from "./sqlite/business-contracts.js" export type { CatalogEntry, CatalogInput, CatalogQuery } from "./sqlite/catalog.js" export type { CrmChange, CrmChangeKind } from "./sqlite/crm-changes.js" @@ -31,6 +32,12 @@ export { type Project, SCOPES, } from "./sqlite/knowledge.js" +export type { + MailSubscription, + MailSubscriptionFilter, + MailSubscriptionList, + UnsubscribeTarget, +} from "./sqlite/mail-subscriptions.js" export type { MeetingVectors } from "./sqlite/meeting-vectors.js" export type { Author, Memory } from "./sqlite/memories.js" export type { TransactionFilter } from "./sqlite/money-transactions.js" diff --git a/src/store/index.ts b/src/store/index.ts index c93cec242..5098b5468 100644 --- a/src/store/index.ts +++ b/src/store/index.ts @@ -228,6 +228,7 @@ export type { StageName, } from "./sqlite/base-stages.js" export { baseSettingKey } from "./sqlite/base-suggest.js" +export { BOT_SENDS, type BotSends } from "./sqlite/bot-sends.js" export type { BotUpdate, BotUpdateStore } from "./sqlite/bot-updates.js" export type { Contract, @@ -372,6 +373,12 @@ export type { } from "./sqlite/knowledge.js" export { ORGANIZATION_KINDS, PROJECT_TYPES, SCOPES } from "./sqlite/knowledge.js" export type { MailRule, MailRuleCount, MailRuleInput, MailRulesStore } from "./sqlite/mail-rules.js" +export type { + MailSubscription, + MailSubscriptionFilter, + MailSubscriptionList, + UnsubscribeTarget, +} from "./sqlite/mail-subscriptions.js" export { type ListedAccount, MEETING_ROW_KINDS, diff --git a/src/store/mail-subscriptions.test.ts b/src/store/mail-subscriptions.test.ts new file mode 100644 index 000000000..5ea8c8bd5 --- /dev/null +++ b/src/store/mail-subscriptions.test.ts @@ -0,0 +1,164 @@ +import { mkdtempSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { afterEach, describe, expect, it } from "vitest" +import { syncMail } from "../mail/sync.js" +import { type FakeMail, fakeMailSource } from "../mail/testing/index.js" +import { openCache } from "./open.js" +import { type AccountKey, openStore } from "./store.js" + +const ME = "owner@home.example.com" +const NOW = Date.parse("2026-10-04T12:00:00Z") +const SINCE = new Date("2026-09-01T00:00:00Z") + +let n = 0 +const mail = (from: [string, string], subject: string, day: number, overrides: Partial = {}): FakeMail => { + n += 1 + return { + uid: String(100 + n), + messageId: ``, + threadId: String(9000 + n), + receivedAt: `2026-09-${String(day).padStart(2, "0")}T08:00:00Z`, + subject, + from, + to: [[null, ME]], + text: `Synthetic body ${n}`, + ...overrides, + } +} + +const signed = (domain: string, fields: string[]) => [ + `DKIM-Signature: v=1; a=rsa-sha256; d=${domain}; s=s1; h=from:to:subject:${fields.join(":")}; b=abc`, + `Authentication-Results: mx.google.com; dkim=pass header.i=@${domain} header.s=s1 header.b=abc`, +] + +const oneClick = (domain: string, target: string) => [ + `List-Unsubscribe: <${target}>, `, + "List-Unsubscribe-Post: List-Unsubscribe=One-Click", + ...signed(domain, ["list-unsubscribe", "list-unsubscribe-post"]), +] + +const handles: { close(): unknown }[] = [] +afterEach(async () => { + for (const handle of handles.splice(0)) await handle.close() +}) + +const storePath = () => join(mkdtempSync(join(tmpdir(), "mail-subscriptions-")), "store.db") + +const synced = async (messages: FakeMail[], path = storePath()) => { + const store = await openStore({ path }) + handles.push(store) + await syncMail(fakeMailSource({ messages }), store, { account: { address: ME }, since: SINCE, now: () => NOW }) + return { store, path } +} + +const NEWS: [string, string] = ["Weekly News", "news@paper.example.com"] +const SHOP: [string, string] = ["Shop", "deals@store.example.com"] + +const inbox = () => [ + mail(NEWS, "Issue 1", 10, { listId: "weekly.paper.example.com" }), + mail(NEWS, "Issue 2", 17, { + extraHeaders: [ + "List-Id: Weekly ", + ...oneClick("paper.example.com", "https://paper.example.com/u/2"), + ], + }), + mail(NEWS, "Issue 3", 24, { listId: "weekly.paper.example.com" }), + mail(SHOP, "Winter sale: 30% off", 12, { + extraHeaders: [ + "List-Unsubscribe: ", + "List-Unsubscribe-Post: List-Unsubscribe=One-Click", + ...signed("store.example.com", ["list-unsubscribe-post"]), + ], + }), + mail(SHOP, "Thank you for your order #4411", 13), + mail(["Pia Lund", "pia@friends.example.com"], "Dinner on Friday?", 20), +] + +describe("subscriptions", () => { + it("groups broadcast mail by List-Id, else by sender, newest first, with the newest mail and the unsubscribe target", async () => { + const { store } = await synced(inbox()) + + const { items, total, hasMore } = await store.mail.subscriptions() + + expect(total).toBe(2) + expect(hasMore).toBe(false) + expect(items).toMatchObject([ + { + key: "list:weekly.paper.example.com", + listId: "weekly.paper.example.com", + name: "Weekly News", + address: "news@paper.example.com", + emails: 3, + newest: { subject: "Issue 3", at: Date.parse("2026-09-24T08:00:00Z") }, + unsubscribe: { + https: "https://paper.example.com/u/2", + mailto: "mailto:leave@paper.example.com", + oneClick: true, + }, + }, + { listId: null, name: "Shop", address: "deals@store.example.com", emails: 1, unsubscribe: null }, + ]) + expect(items[0]?.sender).toMatch(/^(person|sender-bot):\d+$/) + expect(items[1]?.key).toBe(items[1]?.sender ?? "address:deals@store.example.com") + }) + + it("pages groups in SQL and keeps the total", async () => { + const { store } = await synced(inbox()) + + const second = await store.mail.subscriptions({ limit: 1, offset: 1 }) + expect(second).toMatchObject({ total: 2, hasMore: false, items: [{ name: "Shop" }] }) + expect(await store.mail.subscriptions({ limit: 1 })).toMatchObject({ total: 2, hasMore: true }) + expect(await store.mail.subscriptions({ limit: 1, offset: 5 })).toEqual({ items: [], total: 2, hasMore: false }) + expect((await store.mail.subscriptions({ types: ["promotion"] })).items.map(({ name }) => name)).toEqual(["Shop"]) + const { id } = await store.accounts.storedAccount({ provider: "email", account: ME }) + expect((await store.mail.subscriptions({ accountIds: [id] })).total).toBe(2) + expect((await store.mail.subscriptions({ accountIds: [] })).total).toBe(0) + }) + + it("answers from a read-only open of a store whose types were never worked out, and writes nothing", async () => { + const path = storePath() + const { store } = await synced(inbox(), path) + await store.close() + handles.splice(handles.indexOf(store), 1) + const raw = await openCache(path) + handles.push(raw) + const untyped = () => Number(raw.prepare("SELECT count(*) AS n FROM emails WHERE mail_type IS NULL").get()?.n) + expect(untyped()).toBe(6) + const readOnly = await openStore({ path, readOnly: true }) + handles.push(readOnly) + + expect((await readOnly.mail.subscriptions()).items.map(({ name, emails }) => ({ name, emails }))).toEqual([ + { name: "Weekly News", emails: 3 }, + { name: "Shop", emails: 1 }, + ]) + expect(untyped()).toBe(6) + }) +}) + +describe("bots by what they send", () => { + const TG: AccountKey = { provider: "telegram", account: "1" } + + it("filters bots by the mail types they send and by a messenger account, in SQL", async () => { + const { store } = await synced([ + mail(["Bank", "noreply@bank.example.com"], "New sign-in to your account", 10), + mail(["Store", "noreply@store.example.com"], "Thank you for your order #4411", 11), + ]) + await store.people.savePeople(TG, [{ id: "50", name: "Helper", isBot: true }]) + await store.people.list({ limit: 0 }) + const names = async (sends: Parameters[0]["sends"]) => + (await store.people.listBots({ limit: 50, ...(sends ? { sends } : {}) })).items.map( + ({ displayName }) => displayName, + ) + + expect(await names(undefined)).toEqual(["Bank", "Helper", "Store"]) + expect(await names(["alerts"])).toEqual(["Bank"]) + expect(await names(["receipts"])).toEqual(["Store"]) + expect(await names(["messenger"])).toEqual(["Helper"]) + expect(await names(["alerts", "messenger"])).toEqual(["Bank", "Helper"]) + expect(await names(["marketing"])).toEqual([]) + await expect(store.people.listBots({ limit: 5, sends: ["spam" as "alerts"] })).rejects.toMatchObject({ + details: { reason: "sender-bot.unknown-sends" }, + }) + }) +}) diff --git a/src/store/people.ts b/src/store/people.ts index 93758a270..5cc21bc96 100644 --- a/src/store/people.ts +++ b/src/store/people.ts @@ -23,6 +23,7 @@ import type { import { keysOver } from "./keys.js" import { ownerPerson } from "./sqlite/actors.js" import { agentLink, agentMergeOf, agentMerges, linkEvidenceOver } from "./sqlite/agent-links.js" +import { sendsWhere } from "./sqlite/bot-sends.js" import type { ContactFilter } from "./sqlite/identities.js" import * as identities from "./sqlite/identities.js" import * as identityProposals from "./sqlite/identity-proposals.js" @@ -439,7 +440,7 @@ export const peopleStoreOver = (context: StoreContext, keyed: AccountPeople): Pe }, listBots: async (options) => { storeKinds(database) - return listBots(database, options) + return listBots(database, options, options.sends === undefined ? undefined : sendsWhere(database, options.sends)) }, showBot: async (bot) => showBot(database, bot), moveToBot: async (subject, by, options) => { diff --git a/src/store/sqlite/bot-sends.ts b/src/store/sqlite/bot-sends.ts new file mode 100644 index 000000000..73db96e74 --- /dev/null +++ b/src/store/sqlite/bot-sends.ts @@ -0,0 +1,49 @@ +import { CliError } from "@wirecat/cli-base" +import type { MailType } from "../../mail/mail-types.js" +import type { CacheDatabase, SqlValue } from "../driver.js" +import { typeWhere } from "./email-types.js" + +/** + * What a bot sends, as the Bots tab filters it: the mail types that put a bot under each name. `messenger` is a bot + * with an account in a messenger, whatever it sends. @experimental + */ +export const BOT_SENDS = { + alerts: ["security", "system_alert", "account_notice"], + receipts: ["order", "bill", "shipping"], + newsletters: ["newsletter"], + marketing: ["promotion"], + messenger: null, +} as const satisfies Record +/** @experimental */ +export type BotSends = keyof typeof BOT_SENDS + +/** Which bots send any of these, over `b`: by the type of their mail, or a messenger account. */ +export const sendsWhere = ( + database: CacheDatabase, + sends: readonly BotSends[], +): { sql: string; params: SqlValue[] } => { + const unknown = sends.filter((name) => !Object.hasOwn(BOT_SENDS, name)) + if (unknown.length > 0 || sends.length === 0) + throw new CliError( + "validation_error", + `a bot sends one of ${Object.keys(BOT_SENDS).join(", ")}, got "${unknown.join(", ")}"`, + { reason: "sender-bot.unknown-sends" }, + ) + const types = [...new Set(sends.flatMap((name) => BOT_SENDS[name] ?? []))] + const typed = types.length === 0 ? undefined : typeWhere(database, { types }) + const any = [ + ...(typed === undefined + ? [] + : [ + "EXISTS (SELECT 1 FROM sender_bot_identities s JOIN emails e ON e.from_identity_id = s.identity_id " + + `WHERE s.bot_id = b.id AND e.deleted_at IS NULL AND e.outgoing IS NOT 1 AND ${typed.sql.join(" AND ")})`, + ]), + ...(sends.includes("messenger") + ? [ + "EXISTS (SELECT 1 FROM sender_bot_identities s JOIN identities i ON i.id = s.identity_id " + + "WHERE s.bot_id = b.id AND i.provider <> 'email')", + ] + : []), + ] + return { sql: `(${any.join(" OR ")})`, params: typed?.params ?? [] } +} diff --git a/src/store/sqlite/emails.ts b/src/store/sqlite/emails.ts index 83223914d..523e38a7d 100644 --- a/src/store/sqlite/emails.ts +++ b/src/store/sqlite/emails.ts @@ -45,6 +45,7 @@ import { ensurePerson } from "./identities.js" import { nearestMailPieces } from "./mail-nearest.js" import { type MailRulesStore, mailRulesOver } from "./mail-rules.js" import { type MailSorting, mailSortingOver, settleThreads } from "./mail-sorting.js" +import { type MailSubscriptionStore, mailSubscriptionStore } from "./mail-subscriptions.js" import { type AttachmentInput, attachmentOf, saveAttachment, wordsQuery } from "./meetings.js" import type { Orm, StoreContext } from "./open.js" import type { Reach } from "./sender-signals.js" @@ -303,7 +304,7 @@ export interface SenderScore { } /** Mail in tables of its own: threads, emails, recipients and mailboxes, keyed by account and Message-ID. */ -export interface MailStore extends PartialMailStore, MailActivityStore, MailTypeStore { +export interface MailStore extends PartialMailStore, MailActivityStore, MailTypeStore, MailSubscriptionStore { saveThread(input: ThreadSave): Promise /** Several threads and sync state in one transaction: a slice of mail commits with its resume point, or not at all. */ saveThreads(inputs: ThreadSave[], states?: SyncStateSave[]): Promise @@ -916,6 +917,7 @@ export const mailStoreOver = ( ...partialMail(database), ...mailActivity(database), ...mailTypeStore(database), + ...mailSubscriptionStore(database), async emailFacts(filter = {}) { const [where, params] = emailWhere(database, filter) return database diff --git a/src/store/sqlite/mail-subscriptions.ts b/src/store/sqlite/mail-subscriptions.ts new file mode 100644 index 000000000..51e133168 --- /dev/null +++ b/src/store/sqlite/mail-subscriptions.ts @@ -0,0 +1,222 @@ +import { SENDER_BOT_PREFIX } from "../../domain/person-kinds.js" +import type { MailType } from "../../mail/mail-types.js" +import type { CacheDatabase, SqlValue } from "../driver.js" +import { typeWhere } from "./email-types.js" +import { LIST_ID } from "./sender-signals.js" +import { read } from "./transaction.js" + +/** Where an unsubscribe goes, as the newest mail of a subscription that names one gave it. @experimental */ +export interface UnsubscribeTarget { + /** The https target of List-Unsubscribe. */ + https: string | null + /** The mailto target of List-Unsubscribe. */ + mailto: string | null + /** + * RFC 8058 one-click: the mail also carries `List-Unsubscribe-Post: List-Unsubscribe=One-Click`, and its From + * domain signed both fields, so a POST to `https` unsubscribes without opening a page. + */ + oneClick: boolean + /** The mail the target was read from. */ + emailId: number +} + +/** One list, or one sender of broadcast mail with no List-Id: a row of Subscriptions. @experimental */ +export interface MailSubscription { + /** `list:`, else the sender: `sender-bot:`, `person:` or `address:
`. */ + key: string + listId: string | null + /** The display name on its newest email, else its address. */ + name: string | null + /** Who sent its newest email: `sender-bot:`, `person:`, or `null` when the address is linked to neither. */ + sender: string | null + /** The From address of its newest email, lower case. */ + address: string | null + /** Its broadcast emails the filter takes in. */ + emails: number + newest: { id: number; externalId: string; subject: string | null; at: number | null } + /** `null` when none of its emails names a target its sender's DKIM signature vouches for. */ + unsubscribe: UnsubscribeTarget | null +} + +/** @experimental */ +export interface MailSubscriptionFilter { + /** Only mail of these accounts; every account when left out. */ + accountIds?: readonly number[] + since?: number + /** Exclusive. */ + until?: number + /** Only emails of these types: the promotions of a shop, without its receipts. */ + types?: readonly MailType[] + limit?: number + offset?: number +} + +/** @experimental */ +export interface MailSubscriptionList { + items: MailSubscription[] + total: number + hasMore: boolean +} + +const LIMIT = 100 + +const HTTPS = "json_extract(e.headers, '$.\"list-unsubscribe-https\"')" +const MAILTO = "json_extract(e.headers, '$.\"list-unsubscribe-mailto\"')" + +const KEY = + `CASE WHEN ${LIST_ID} IS NOT NULL THEN 'list:' || ${LIST_ID} ` + + `WHEN b.bot_id IS NOT NULL THEN '${SENDER_BOT_PREFIX}' || b.bot_id ` + + "WHEN l.person_id IS NOT NULL THEN 'person:' || l.person_id " + + "ELSE 'address:' || lower(e.from_address) END" + +const SENDERS = + "FROM emails e LEFT JOIN sender_bot_identities b ON b.identity_id = e.from_identity_id " + + "LEFT JOIN identity_links l ON l.identity_id = e.from_identity_id AND b.bot_id IS NULL" + +/** The bare `id` is the row of `max(at)`, SQLite's rule for a bare column beside a single max(). */ +const groupsSql = (where: string) => + `SELECT key, count(*) AS emails, max(at) AS last, id AS newest, count(*) OVER () AS total FROM ` + + `(SELECT e.id, coalesce(e.received_at, e.sent_at) AS at, ${KEY} AS key ${SENDERS} WHERE ${where}) ` + + "GROUP BY key ORDER BY last DESC, key LIMIT ? OFFSET ?" + +const EMAILS = + `SELECT e.id, e.external_id, e.subject, lower(e.from_address) AS address, e.from_name, ${LIST_ID} AS list, ` + + `coalesce(e.received_at, e.sent_at) AS at, ${HTTPS} AS https, ${MAILTO} AS mailto, e.from_identity_id, ` + + "json_extract(e.headers, '$.\"list-unsubscribe-post\"') IS 1 AS post, b.bot_id, l.person_id " + + `${SENDERS} WHERE e.id IN (SELECT value FROM json_each(?))` + +/** + * Where a group's mail comes from, through an index: its List-Id, or its sender's identities and no List-Id. A target + * belongs to the list or the sender, so any of its mail in these accounts may name it, whatever its type or date. The + * `+` keeps SQLite off `emails_by_list_id` for "no List-Id", which holds most of the mail: 10 ms a group, not 0.05. + */ +const SOURCES = { + list: `${LIST_ID} = ?`, + bot: `e.from_identity_id IN (SELECT identity_id FROM sender_bot_identities WHERE bot_id = ?) AND +${LIST_ID} IS NULL`, + person: `e.from_identity_id IN (SELECT identity_id FROM identity_links WHERE person_id = ?) AND +${LIST_ID} IS NULL`, + address: `e.from_identity_id = ? AND +${LIST_ID} IS NULL`, +} as const + +const sourceOf = (newest: Record): [keyof typeof SOURCES, SqlValue] | undefined => + typeof newest.list === "string" + ? ["list", newest.list] + : newest.bot_id != null + ? ["bot", Number(newest.bot_id)] + : newest.person_id != null + ? ["person", Number(newest.person_id)] + : newest.from_identity_id != null + ? ["address", Number(newest.from_identity_id)] + : undefined + +const str = (value: unknown): string | null => (typeof value === "string" ? value : null) + +/** + * Broadcast mail grouped by List-Id, else by its sender, newest group first, grouped, counted and paged in SQL. Each + * group carries its newest email and the unsubscribe target of its newest email that names one. + */ +export const mailSubscriptions = (database: CacheDatabase, filter: MailSubscriptionFilter): MailSubscriptionList => { + const limit = filter.limit ?? LIMIT + const offset = filter.offset ?? 0 + const typed = typeWhere(database, { reaches: ["broadcast"], ...(filter.types ? { types: filter.types } : {}) }) + const where = ["e.deleted_at IS NULL", "e.outgoing IS NOT 1", "e.from_address IS NOT NULL", ...typed.sql] + const params: SqlValue[] = [...typed.params] + const add = (sql: string, value: number | undefined) => { + if (value === undefined) return + where.push(sql) + params.push(value) + } + if (filter.accountIds !== undefined) { + where.push("e.account_id IN (SELECT value FROM json_each(?))") + params.push(JSON.stringify(filter.accountIds)) + } + add("coalesce(e.received_at, e.sent_at) >= ?", filter.since) + add("coalesce(e.received_at, e.sent_at) < ?", filter.until) + return read(database, () => { + const groups = database.prepare(groupsSql(where.join(" AND "))).all(...params, limit, offset) + const total = + groups.length > 0 + ? Number(groups[0]?.total) + : offset === 0 + ? 0 + : Number( + database + .prepare(`SELECT count(DISTINCT ${KEY}) AS n ${SENDERS} WHERE ${where.join(" AND ")}`) + .get(...params)?.n, + ) + const emailsOf = (ids: number[]) => + new Map( + database + .prepare(EMAILS) + .all(JSON.stringify(ids)) + .map((row) => [Number(row.id), row]), + ) + const newestOf = emailsOf(groups.map((group) => Number(group.newest))) + const accounts = filter.accountIds === undefined ? "" : " AND e.account_id IN (SELECT value FROM json_each(?))" + const targetSql = (source: string) => + `SELECT e.id FROM emails e WHERE ${source} AND e.deleted_at IS NULL AND e.outgoing IS NOT 1${accounts} ` + + `AND (${HTTPS} IS NOT NULL OR ${MAILTO} IS NOT NULL) ORDER BY coalesce(e.received_at, e.sent_at) DESC, e.id DESC LIMIT 1` + const statements = new Map>() + const targetIdOf = (newest: Record | undefined): number | undefined => { + const source = newest === undefined ? undefined : sourceOf(newest) + if (source === undefined) return undefined + const [kind, value] = source + const statement = statements.get(kind) ?? database.prepare(targetSql(SOURCES[kind])) + statements.set(kind, statement) + const found = statement.get( + value, + ...(filter.accountIds === undefined ? [] : [JSON.stringify(filter.accountIds)]), + ) + return found === undefined ? undefined : Number(found.id) + } + const targets = groups.map((group) => targetIdOf(newestOf.get(Number(group.newest)))) + const targetOf = emailsOf(targets.filter((id) => id !== undefined)) + const items = groups.map((group, at): MailSubscription => { + const newest = newestOf.get(Number(group.newest)) ?? {} + const targetId = targets[at] + const target = targetId === undefined ? undefined : targetOf.get(targetId) + const https = str(target?.https) + return { + key: String(group.key), + listId: str(newest.list), + name: str(newest.from_name) ?? str(newest.address), + sender: + newest.bot_id != null + ? `${SENDER_BOT_PREFIX}${newest.bot_id}` + : newest.person_id != null + ? `person:${newest.person_id}` + : null, + address: str(newest.address), + emails: Number(group.emails), + newest: { + id: Number(group.newest), + externalId: String(newest.external_id), + subject: str(newest.subject), + at: newest.at == null ? null : Number(newest.at), + }, + unsubscribe: + target === undefined + ? null + : { + https, + mailto: str(target.mailto), + oneClick: https !== null && Number(target.post) === 1, + emailId: Number(target.id), + }, + } + }) + return { items, total, hasMore: total > offset + groups.length } + }) +} + +/** @experimental */ +export interface MailSubscriptionStore { + /** + * Subscriptions: broadcast mail grouped by List-Id, else by sender, newest first, each with its mail count, newest + * email and unsubscribe target. Nothing is unsubscribed. + */ + subscriptions(filter?: MailSubscriptionFilter): Promise +} + +export const mailSubscriptionStore = (database: CacheDatabase): MailSubscriptionStore => ({ + subscriptions: async (filter = {}) => mailSubscriptions(database, filter), +}) diff --git a/src/store/sqlite/sender-bots.ts b/src/store/sqlite/sender-bots.ts index 4d714b5c7..84210b35f 100644 --- a/src/store/sqlite/sender-bots.ts +++ b/src/store/sqlite/sender-bots.ts @@ -4,6 +4,7 @@ import { SENDER_BOT_PREFIX } from "../../domain/person-kinds.js" import type { CacheDatabase, SqlValue } from "../driver.js" import { fold } from "../normalize.js" import type { IdentityRef, PersonRecord } from "../types.js" +import type { BotSends } from "./bot-sends.js" import { groupByDomain, releaseDomainHolds } from "./domain-organizations.js" import { currentPerson } from "./merged-persons.js" import type { StoreContext } from "./open.js" @@ -66,6 +67,8 @@ export interface BotListOptions { query?: string /** `organization:`: the bots that send for it. */ organization?: string + /** Only bots that send any of these (`BOT_SENDS`). */ + sends?: readonly BotSends[] limit: number offset?: number } @@ -518,7 +521,12 @@ const detailsOf = (database: CacheDatabase, bot: number): SenderBotDetails => { } /** The sender bots, by name; a bot a build before version 75 sorted shows once a list has settled it. */ -export const listBots = (database: CacheDatabase, options: BotListOptions): BotList => { +/** `sent` is `sendsWhere` of `options.sends`, worked out before the read: it may keep mail types. */ +export const listBots = ( + database: CacheDatabase, + options: BotListOptions, + sent?: { sql: string; params: SqlValue[] }, +): BotList => { const { limit, offset = 0 } = options const where = [HOLDS] const params: SqlValue[] = [] @@ -547,6 +555,10 @@ export const listBots = (database: CacheDatabase, options: BotListOptions): BotL where.push("b.organization_id = ?") params.push(Number(id)) } + if (sent !== undefined) { + where.push(sent.sql) + for (const param of sent.params) params.push(param) + } return read(database, () => { const filter = where.join(" AND ") const total = Number(database.prepare(`SELECT count(*) AS n FROM sender_bots b WHERE ${filter}`).get(...params)?.n)