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
2 changes: 1 addition & 1 deletion biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -792,7 +792,7 @@
"noExcessiveLinesPerFile": {
"level": "error",
"options": {
"maxLines": 1038
"maxLines": 1040
}
}
}
Expand Down
17 changes: 17 additions & 0 deletions changes/feat-mail-subscriptions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
### Added

- **Subscriptions: `store.mail.subscriptions`** (experimental). Broadcast mail grouped by `List-Id`, else by its
sender (`sender-bot:<id>`, `person:<id>` or `address:<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`.
1 change: 1 addition & 0 deletions docs/dev/GLOSSARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<id>`, the `sender_bots` table). Not an agent: `bot:<id>` 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:<id>`. 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 |
Expand Down
7 changes: 7 additions & 0 deletions docs/dev/MAIL.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@ account `{ provider: "email", account: <address, lower case> }`.
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
Expand Down
1 change: 1 addition & 0 deletions docs/reasons.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 | |
Expand Down
1 change: 1 addition & 0 deletions src/errors/reasons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
19 changes: 19 additions & 0 deletions src/mail/headers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <news@shop.example>",
"List-Unsubscribe: <ftp://shop.example/x>, <mailto:leave@shop.example?subject=leave>,",
" <https://shop.example/u/1>",
"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 })
})
})
24 changes: 21 additions & 3 deletions src/mail/headers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,22 @@ const programSignalsOf = (unfolded: string, from: string | undefined): Record<st
}
}

/**
* The https and mailto targets of List-Unsubscribe (RFC 2369), each the first of its scheme, kept only when the From
* domain's DKIM signature covers the field: a target is where an unsubscribe goes, so a forged one must not be offered.
*/
const unsubscribeTargetsOf = (unfolded: string, from: string | undefined): Record<string, string> => {
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" <real@z.com>), so quoted names and comments go first.
Expand Down Expand Up @@ -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<string, string | boolean> => {
const unfolded = unfold(headTextOf(raw))
Expand All @@ -192,6 +209,7 @@ export const mailHeadersOf = (raw: Uint8Array): Record<string, string | boolean>
...authOf(unfolded),
...(field(unfolded, "List-Unsubscribe") === undefined ? {} : { "list-unsubscribe": true }),
...(precedence ? { precedence } : {}),
...unsubscribeTargetsOf(unfolded, from),
...programSignalsOf(unfolded, from),
}
}
7 changes: 7 additions & 0 deletions src/store/areas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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"
Expand Down
7 changes: 7 additions & 0 deletions src/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
164 changes: 164 additions & 0 deletions src/store/mail-subscriptions.test.ts
Original file line number Diff line number Diff line change
@@ -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> = {}): FakeMail => {
n += 1
return {
uid: String(100 + n),
messageId: `<m${n}@test.example.com>`,
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}>, <mailto:leave@${domain}>`,
"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 <weekly.paper.example.com>",
...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: <https://forged.example.net/u>",
"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<typeof store.people.listBots>[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" },
})
})
})
Loading
Loading