From 922696e8b6366bc4acc0f4819cec1507c78de773 Mon Sep 17 00:00:00 2001 From: leemour Date: Thu, 26 Nov 2026 17:35:41 +0100 Subject: [PATCH 1/2] feat(sync): count Gmail's "send as" addresses as the owner's A Gmail profile signed in with Google now reads users.settings.sendAs.list at each sync and passes every address Gmail accepted (verificationStatus accepted, not the primary) to cli-core as the owner's, beside the configured aliases. The https://mail.google.com/ scope the sign-in already requests allows the call, so no scope is added. gmail.googleapis.com joins the hosts. A failed read (the Gmail API off in the Google project, a network error) keeps the list read last, under the sync-state key mail_send_as, so the owner's alias mail does not turn incoming because Gmail did not answer once. sync reports it as send_as.unread. App-password profiles read no list. Part of cli-core #3321. Co-Authored-By: Claude Opus 5.5 --- changes/feat-gmail-sendas-mail-signals.md | 7 +++ contracts/wirecat.json | 1 + docs/commands.md | 2 +- docs/configuration.md | 7 +++ docs/oauth-google.md | 4 +- src/aliases.test.ts | 4 +- src/commands/sync.ts | 32 ++++++++-- src/identity.ts | 1 + src/mail/send-as.ts | 75 +++++++++++++++++++++++ src/oauth.test.ts | 38 ++++++++++++ 10 files changed, 164 insertions(+), 7 deletions(-) create mode 100644 changes/feat-gmail-sendas-mail-signals.md create mode 100644 src/mail/send-as.ts diff --git a/changes/feat-gmail-sendas-mail-signals.md b/changes/feat-gmail-sendas-mail-signals.md new file mode 100644 index 0000000..d3c27e8 --- /dev/null +++ b/changes/feat-gmail-sendas-mail-signals.md @@ -0,0 +1,7 @@ +### Added + +- **Gmail's "send as" addresses count as yours.** A Gmail profile signed in with Google reads its "send as" list at + each `sync` (`users.settings.sendAs.list`, under the `https://mail.google.com/` scope the sign-in already asks for) + and counts every address Gmail accepted as yours, beside `aliases`. When Gmail does not answer, the list read last + is used, and `sync` says why under `send_as.unread`. A profile with an app password reads no list: set `aliases` + there ([configuration](../docs/configuration.md)). diff --git a/contracts/wirecat.json b/contracts/wirecat.json index 6cc4c0b..b8aeb9a 100644 --- a/contracts/wirecat.json +++ b/contracts/wirecat.json @@ -1160,6 +1160,7 @@ "accounts.google.com", "oauth2.googleapis.com", "openidconnect.googleapis.com", + "gmail.googleapis.com", "autoconfig.thunderbird.net", "data.iana.org", "imap.yandex.com", diff --git a/docs/commands.md b/docs/commands.md index b9474ac..4b46fbf 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -279,7 +279,7 @@ mail sync [options] | `--max-attachment-mb ` | the largest attachment to read this run, in MB (default: the profile's max_attachment_mb, else 10). | | `--rescan` | list the whole window again; also moves stored replies into their thread where the server has no thread ids. | -**Returns:** mail sync — address, since, timezone, folders, state, requests, listed, saved, and 14 more; every field: mail commands info sync +**Returns:** mail sync — address, since, timezone, folders, state, requests, listed, saved, and 15 more; every field: mail commands info sync **Example:** `mail personal sync`, `mail personal sync --since-time 2026-10-01 --max-messages 200`, `mail personal sync --folder INBOX` diff --git a/docs/configuration.md b/docs/configuration.md index 45bc488..f593e10 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -24,6 +24,13 @@ it came from, and its senders join your addresses in the store on their own; set mail in Sent yet. Mail stored before is marked at the next `sync`. The store keeps an address once it is yours: `config unset aliases` does not take it back. +A Gmail profile signed in with Google also reads Gmail's "send as" list at each `sync` +([Gmail API](https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.settings.sendAs/list)), and +every address Gmail accepted there is yours, as an alias is. The sign-in's `https://mail.google.com/` scope allows it; +your own Google app needs the Gmail API turned on (see [Gmail with OAuth](oauth-google.md)). When Gmail does not +answer, `sync` uses the list it read last and says why under `send_as.unread`. A profile with an app password cannot +read the list: name those addresses in `aliases`. + `read_attachments` (default `true`) and `max_attachment_mb` (default 10) decide whether `sync` reads the text of attachments into the search index and the largest file it reads. No file is kept. `sync --no-attachments`, `--attachments` and `--max-attachment-mb` override them for one run; `messages show` reads one email's attachments diff --git a/docs/oauth-google.md b/docs/oauth-google.md index 4807bff..6cf03bd 100644 --- a/docs/oauth-google.md +++ b/docs/oauth-google.md @@ -54,7 +54,9 @@ scope Gmail gives IMAP and SMTP ([XOAUTH2](https://developers.google.com/workspa Google's page does not say whether the Gmail API must be enabled for IMAP alone. If the sign-in works and `session status --check` then fails, enable the -[Gmail API](https://console.cloud.google.com/apis/library/gmail.googleapis.com) in this project and try again. +[Gmail API](https://console.cloud.google.com/apis/library/gmail.googleapis.com) in this project and try again. `sync` +also reads your "send as" addresses through the Gmail API. With the API off, `sync` reports `send_as.unread`, and +only `aliases` and the senders of your Sent mail count as yours. ## 4. Publish the app (Production), without verification diff --git a/src/aliases.test.ts b/src/aliases.test.ts index 4d72c14..f367e60 100644 --- a/src/aliases.test.ts +++ b/src/aliases.test.ts @@ -41,7 +41,9 @@ describe("the owner's aliases", () => { const set = await mail(["ya", "config", "set", "aliases", ALIAS, "--json"]) expect(set.code, set.err).toBe(0) - expect((await mail(["ya", "sync", "--since-time", "2026-01-01", "--json"])).code).toBe(0) + const synced = await mail(["ya", "sync", "--since-time", "2026-01-01", "--json"]) + expect(synced.code).toBe(0) + expect(JSON.parse(synced.out).item.send_as).toBeUndefined() expect(await facts()).toMatchObject({ outgoing: { Ping: false, Note: true, Hello: true }, diff --git a/src/commands/sync.ts b/src/commands/sync.ts index ca240ad..0ea41f5 100644 --- a/src/commands/sync.ts +++ b/src/commands/sync.ts @@ -21,15 +21,17 @@ import { storedMailRuleSet, syncMail, } from "@wirecat/cli-core/mail" +import type { MessageStore } from "@wirecat/cli-core/store" import { Command } from "commander" import * as v from "valibot" import { configuration, DEFAULT_SYNC_SINCE, SYNC_WINDOW } from "../config.js" import { IDENTITY } from "../identity.js" import { knownAges, lookUpAges, rdapDeps } from "../mail/domain-age.js" import { rethreadStored } from "../mail/rethread.js" +import { gmailAliases, readSendAs } from "../mail/send-as.js" import { DEFAULT_SYNC, providerFor, type SyncFolders } from "../providers.js" import { openMailStore } from "../store.js" -import { closing, contextOf, openMail, refuseOffline, repeatable } from "./context.js" +import { closing, contextOf, credentialOf, oauthKindOf, openMail, refuseOffline, repeatable } from "./context.js" const DAY_MS = 86_400_000 const WINDOW_DAYS: Record = { d: 1, w: 7, y: 365 } @@ -100,6 +102,18 @@ const issuesOf = (report: MailSyncResult) => [ : []), ] +/** Gmail's "send as" aliases, for a profile signed in to Google; an app password cannot call the Gmail API. */ +const sendAsOf = async (context: ReturnType, store: MessageStore, address: string) => { + const { mailbox } = context.settings + if (mailbox.auth !== "oauth" || oauthKindOf(mailbox) !== "google") return undefined + const { credential } = await credentialOf(context) + return gmailAliases(store, mailAccountKey(address), async () => { + const login = await credential.login() + if (!("accessToken" in login)) return [] + return readSendAs(login.accessToken, context.environment.fetch, context.environment.signal) + }) +} + /** The provider's folders by role (INBOX and Sent, All Mail on Gmail), unless the profile or `--folder` names some. */ export const foldersFor = async ( explicit: string[] | undefined, @@ -147,6 +161,11 @@ const mailSync = v.strictObject({ senders: v.optional( v.strictObject({ scored: v.number(), demoted: v.number(), domains_looked_up: v.number(), failed: v.number() }), ), + /** + * A Gmail OAuth profile: the "send as" aliases counted as the owner's beside `aliases`, and why Gmail's list could not + * be read this run, when it could not; the list read last is used then. + */ + send_as: v.optional(v.strictObject({ aliases: v.number(), unread: v.optional(v.string()) })), hint: v.optional(v.string()), }) @@ -209,7 +228,7 @@ export const syncCommand = (): Command => const budget = runBudgetOf(this, args.maxPages) // A retry is a request of the budget; openMail keeps it from ending after the deadline. const { backend } = await openMail(context, { canRetry: () => budget.take() === null }) - const { report, rethreaded, unreadable, senders } = await closing(backend, () => + const { report, rethreaded, unreadable, senders, sendAs } = await closing(backend, () => baseContext(this, configuration.resolveSettings).run(async () => { const { mailbox } = context.settings const defaults = providerFor(address, mailbox.host)?.sync ?? DEFAULT_SYNC @@ -219,8 +238,10 @@ export const syncCommand = (): Command => try { // The stored rules, as memo passes them: the saved position holds their fingerprint, so both must agree. const { rules, unreadable } = await storedMailRuleSet(store, { address }) + const sendAs = await sendAsOf(context, store, address) + const addresses = [...new Set([...(mailbox.aliases ?? []), ...(sendAs?.aliases ?? [])])] const report = await syncMail(backend, store, { - account: { address, mode: defaults.mode ?? "imap", folders, rules, addresses: mailbox.aliases ?? [] }, + account: { address, mode: defaults.mode ?? "imap", folders, rules, addresses }, since, ages: knownAges(context.env), budget, @@ -255,7 +276,7 @@ export const syncCommand = (): Command => Date.now(), rules, ) - return { report, rethreaded, unreadable, senders } + return { report, rethreaded, unreadable, senders, sendAs } } finally { await store.close() } @@ -344,6 +365,9 @@ export const syncCommand = (): Command => ...(report.deletionsSkipped ? { deletions_skipped: report.deletionsSkipped } : {}), ...(refused.length ? { refused_folders: refused } : {}), ...(report.partial ? { partial_emails: report.partial } : {}), + ...(sendAs + ? { send_as: { aliases: sendAs.aliases.length, ...(sendAs.unread ? { unread: sendAs.unread } : {}) } } + : {}), ...(senders ? { senders: { diff --git a/src/identity.ts b/src/identity.ts index 7981fa2..2d14ef3 100644 --- a/src/identity.ts +++ b/src/identity.ts @@ -30,6 +30,7 @@ export const DESKTOP: ManifestIdentity = { "accounts.google.com", "oauth2.googleapis.com", "openidconnect.googleapis.com", + "gmail.googleapis.com", "autoconfig.thunderbird.net", "data.iana.org", "imap.yandex.com", diff --git a/src/mail/send-as.ts b/src/mail/send-as.ts new file mode 100644 index 0000000..7bf7382 --- /dev/null +++ b/src/mail/send-as.ts @@ -0,0 +1,75 @@ +import type { AccountKey, MessageStore } from "@wirecat/cli-core/store" +import * as v from "valibot" +import { signInFetch } from "../oauth.js" + +/** Sync state under the mail account: the Gmail "send as" aliases last read, lower case, as a JSON array. */ +export const SEND_AS_KEY = "mail_send_as" + +const SEND_AS_URL = "https://gmail.googleapis.com/gmail/v1/users/me/settings/sendAs" + +const SendAsList = v.object({ + sendAs: v.optional( + v.array( + v.object({ + sendAsEmail: v.string(), + isPrimary: v.optional(v.boolean()), + verificationStatus: v.optional(v.string()), + }), + ), + ), +}) + +/** + * The account's custom "from" addresses Gmail accepted, without the account's own: + * https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.settings.sendAs/list. The + * https://mail.google.com/ scope the sign-in already asks for allows it. The token goes in a header, so no failure + * prints it. + */ +export const readSendAs = async (accessToken: string, fetcher?: typeof fetch, signal?: AbortSignal) => { + const response = await signInFetch(fetcher)(SEND_AS_URL, { + headers: { authorization: `Bearer ${accessToken}`, accept: "application/json" }, + ...(signal ? { signal } : {}), + redirect: "error", + }) + if (!response.ok) throw new Error(`Gmail answered HTTP ${response.status}`) + const list = v.safeParse(SendAsList, await response.json().catch(() => undefined)) + if (!list.success) throw new Error("Gmail's answer is not a sendAs list") + return [ + ...new Set( + (list.output.sendAs ?? []) + .filter(({ isPrimary, verificationStatus }) => !isPrimary && verificationStatus === "accepted") + .map(({ sendAsEmail }) => sendAsEmail.trim().toLowerCase()), + ), + ].sort() +} + +const savedOf = (value: string | undefined): string[] => { + if (value === undefined) return [] + try { + const parsed: unknown = JSON.parse(value) + return Array.isArray(parsed) ? parsed.filter((item): item is string => typeof item === "string") : [] + } catch { + return [] + } +} + +/** + * The Gmail aliases to count as the owner's this run. A read that fails keeps the last list read: the owner's mail + * from an alias must not turn incoming because Gmail did not answer once. + */ +export const gmailAliases = async ( + store: MessageStore, + key: AccountKey, + read: () => Promise, +): Promise<{ aliases: string[]; unread?: string }> => { + const saved = savedOf((await store.sync.syncState(key, SEND_AS_KEY))?.value) + let aliases: string[] + try { + aliases = await read() + } catch (error) { + return { aliases: saved, unread: error instanceof Error ? error.message : String(error) } + } + if (JSON.stringify(aliases) !== JSON.stringify(saved)) + await store.sync.setSyncState(key, SEND_AS_KEY, JSON.stringify(aliases)) + return { aliases } +} diff --git a/src/oauth.test.ts b/src/oauth.test.ts index e1b95d7..42954aa 100644 --- a/src/oauth.test.ts +++ b/src/oauth.test.ts @@ -4,6 +4,7 @@ import { join } from "node:path" import { PassThrough, Readable } from "node:stream" import { memoryKeyring } from "@wirecat/cli-base" import { constants } from "@wirecat/cli-core/constants" +import { openStore } from "@wirecat/cli-core/store" import { afterEach, describe, expect, it } from "vitest" import type { MailEnvironment } from "./commands/context.js" import type { MailCredential, MailEndpoint, RunBounds } from "./mail/backend.js" @@ -67,6 +68,8 @@ const harness = async ( account: address, revoked: 0, lookup: "ok" as "ok" | "refused" | "down" | "unverified", + sendAs: [] as { sendAsEmail: string; isPrimary?: boolean; verificationStatus?: string }[] | "refused", + sendAsTokens: [] as string[], } const tokenCalls: URLSearchParams[] = [] const fetch = (async (url: string | URL | Request, init?: RequestInit) => { @@ -75,6 +78,11 @@ const harness = async ( if (server.lookup === "refused") return new Response("", { status: 401 }) return Response.json({ email: server.account, email_verified: server.lookup !== "unverified" }) } + if (String(url).includes("/settings/sendAs")) { + server.sendAsTokens.push(new Headers(init?.headers).get("authorization") ?? "") + if (server.sendAs === "refused") return new Response("", { status: 403 }) + return Response.json({ sendAs: server.sendAs }) + } if (String(url).includes("/revoke")) { server.revoked += 1 return new Response("", { status: 200 }) @@ -351,6 +359,36 @@ describe("Gmail with your own Google app", { timeout: 20_000 }, () => { } const start = ["work", "session", "start", "--address", "me@gmail.com", "--json"] + it("counts the aliases Gmail accepted as the owner's, and keeps the last list when Gmail refuses", async () => { + const { mail, env, server, leaked } = await gmail() + server.sendAs = [ + { sendAsEmail: "me@gmail.com", isPrimary: true }, + { sendAsEmail: "Me.Alias@Example.com", verificationStatus: "accepted" }, + { sendAsEmail: "pending@example.com", verificationStatus: "pending" }, + ] + expect((await mail([...start, "--client-file", clientFile()])).code).toBe(0) + const sync = async () => { + const synced = await mail(["work", "sync", "--since-time", "2026-01-01", "--folder", "INBOX", "--json"]) + expect(synced.code, synced.err).toBe(0) + const store = await openStore({ env }) + try { + const own = await store.sync.syncState({ provider: "email", account: "me@gmail.com" }, "mail_own_addresses") + return { sendAs: item(synced.out).send_as, own: JSON.parse(own?.value ?? "[]") } + } finally { + await store.close() + } + } + + expect(await sync()).toEqual({ sendAs: { aliases: 1 }, own: ["me.alias@example.com"] }) + expect(server.sendAsTokens.at(-1)).toMatch(/^Bearer synthetic-access-/) + server.sendAs = "refused" + expect(await sync()).toEqual({ + sendAs: { aliases: 1, unread: "Gmail answered HTTP 403" }, + own: ["me.alias@example.com"], + }) + expect(leaked()).toBeNull() + }) + it("signs in with the client file, keeps its secret to refresh, and checks the account", async () => { const { mail, entry, accepted, tokenCalls, config, leaked } = await gmail() const started = await mail([...start, "--client-file", clientFile()]) From da7d149e5603422ac918dc26316cf59aa0cd42a5 Mon Sep 17 00:00:00 2001 From: leemour Date: Thu, 26 Nov 2026 17:40:31 +0100 Subject: [PATCH 2/2] fix(send): the sent copy's sync counts the saved send-as aliases too The sync after a send passes the whole list of the owner's addresses, so it must carry the send-as aliases the last sync read: cli-core treats a given list as complete. Co-Authored-By: Claude Opus 5.5 --- src/mail/send-as.ts | 6 +++++- src/mail/send.ts | 4 +++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/mail/send-as.ts b/src/mail/send-as.ts index 7bf7382..11514c0 100644 --- a/src/mail/send-as.ts +++ b/src/mail/send-as.ts @@ -53,6 +53,10 @@ const savedOf = (value: string | undefined): string[] => { } } +/** The send-as list the last sync read, so a run that does not ask Gmail counts the same addresses. */ +export const savedSendAs = async (store: MessageStore, key: AccountKey): Promise => + savedOf((await store.sync.syncState(key, SEND_AS_KEY))?.value) + /** * The Gmail aliases to count as the owner's this run. A read that fails keeps the last list read: the owner's mail * from an alias must not turn incoming because Gmail did not answer once. @@ -62,7 +66,7 @@ export const gmailAliases = async ( key: AccountKey, read: () => Promise, ): Promise<{ aliases: string[]; unread?: string }> => { - const saved = savedOf((await store.sync.syncState(key, SEND_AS_KEY))?.value) + const saved = await savedSendAs(store, key) let aliases: string[] try { aliases = await read() diff --git a/src/mail/send.ts b/src/mail/send.ts index 10443a7..52ac8ed 100644 --- a/src/mail/send.ts +++ b/src/mail/send.ts @@ -16,6 +16,7 @@ import type { MailBackend, Submitted } from "./backend.js" import { build, type Draft, type Person } from "./compose.js" import { locate, selectIds } from "./locate.js" import type { Mailbox } from "./organise.js" +import { savedSendAs } from "./send-as.js" type Attempt = Parameters[1] @@ -135,8 +136,9 @@ const storeSent = async (sending: Sending, messageId: string): Promise const { folders, mode } = await sending.syncFolders() const address = sending.mailbox.key.account const rules = await storedMailRules(sending.mailbox.store, { address }) + const sendAs = await savedSendAs(sending.mailbox.store, sending.mailbox.key) await syncMail(sending.backend, sending.mailbox.store, { - account: { address, mode, folders, rules, addresses: sending.aliases }, + account: { address, mode, folders, rules, addresses: [...new Set([...sending.aliases, ...sendAs])] }, since: new Date(Date.now() - SYNC_WINDOW_MS), saveCoverage: false, completePartial: false,