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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changes/feat-gmail-sendas-mail-signals.md
Original file line number Diff line number Diff line change
@@ -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)).
1 change: 1 addition & 0 deletions contracts/wirecat.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ mail sync [options]
| `--max-attachment-mb <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`

Expand Down
7 changes: 7 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion docs/oauth-google.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 3 additions & 1 deletion src/aliases.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down
32 changes: 28 additions & 4 deletions src/commands/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, number> = { d: 1, w: 7, y: 365 }
Expand Down Expand Up @@ -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<typeof contextOf>, 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,
Expand Down Expand Up @@ -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()),
})

Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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()
}
Expand Down Expand Up @@ -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: {
Expand Down
1 change: 1 addition & 0 deletions src/identity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
79 changes: 79 additions & 0 deletions src/mail/send-as.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
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 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<string[]> =>
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.
*/
export const gmailAliases = async (
store: MessageStore,
key: AccountKey,
read: () => Promise<string[]>,
): Promise<{ aliases: string[]; unread?: string }> => {
const saved = await savedSendAs(store, key)
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 }
}
4 changes: 3 additions & 1 deletion src/mail/send.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof guardedWrite>[1]

Expand Down Expand Up @@ -135,8 +136,9 @@ const storeSent = async (sending: Sending, messageId: string): Promise<boolean>
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,
Expand Down
38 changes: 38 additions & 0 deletions src/oauth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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) => {
Expand All @@ -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 })
Expand Down Expand Up @@ -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()])
Expand Down
Loading