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 CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ Entry point initialises `NSApplication` (`.prohibited` -- no dock icon) for macO

**Which fields govern a tool is read off `macmcpContextSchema`'s own `applies_to`** (`restrictFieldsGoverning`), never re-typed per handler. Every handler used to name the fields it checked as `accountKeys`/`mailboxKeys` arguments, and the ones with nothing to reconcile passed `[]` and checked nothing: `mail_list_mailboxes` — the discovery tool — listed **every mailbox on the machine** to a mediated call carrying no `mail_mailboxes`, and `mail_send`, `mail_create_draft` and `mail_list_accounts` never consulted that field at all. Belt and braces, `allowedList` maps a field with no value to the **empty** list rather than to `nil`: `nil` means "no restriction" to every generated script, so one forgotten call site could widen a confinement into its opposite. An operator field (`source: "operator"`) with no value refuses the whole tool; a `project_path` field governs the **parameter** instead — a distinction only macMCP can make, since relay's `checkScopePresence` reads `applies_to` as a tool-level denial and has no notion of an argument. `file_dirs` names a tool in `applies_to` only when the tool cannot function without it: `mail_save_attachment`'s `destination` is required, so it is named and relay denies it outright with no value, which is ADR-011 finding 1's intended outcome. `mail_get_source`'s `save_to`, and `mail_send`/`mail_create_draft`'s `attachments`, are all optional — each tool works with the field unset — so none of the three is named, and each is confined at its own parameter (`writeDestination`, `writeDestination`, `readableAttachment`) instead. macMCP enforcing a parameter relay does not advertise is the fail-CLOSED direction of a mismatch between the two declarations; ADR-011 decision 9 forbids only the opposite one, where relay advertises a confinement that is not real.

**The reconciliation rule is stated once and applied identically at every seam** (`MailScope.accountTargets` / `mailboxTargets` / `writeDestination` / `readableAttachment`): an absent *or default-valued* argument resolves **to the scope** (so a scoped `mail_get_emails` with no `mailbox` reads what the client may reach, not an `INBOX` that may not be one of them); a tool-level wildcard (`mailbox: "all"`) resolves to the scope and does **not** error; an **explicit** argument outside it is an error, never a silent narrowing, because silent narrowing lets an agent build a false model of what it can reach and burn calls discovering the truth. Under a scope, `all` excludes nothing — a profile that names Trash was given it deliberately, and subtracting it would overrule the enumeration an operator typed. Values are mailbox **paths**, matched case-insensitively as every caller-supplied name in this file is; a scope resolving names by a different rule from the one the tools resolve arguments by is how an operator allows a mailbox the client cannot reach.
**The reconciliation rule is stated once and applied identically at every seam** (`MailScope.accountTargets` / `mailboxTargets` / `writeDestination` / `readableAttachment`): an absent *or default-valued* argument resolves **to the scope** (so a scoped `mail_get_emails` with no `mailbox` reads what the client may reach, not an `INBOX` that may not be one of them); a tool-level wildcard (`mailbox: "all"`) resolves to the scope and does **not** error; an **explicit** argument outside it is an error, never a silent narrowing, because silent narrowing lets an agent build a false model of what it can reach and burn calls discovering the truth. Under a scope, `all` excludes nothing — a profile that names Trash was given it deliberately, and subtracting it would overrule the enumeration an operator typed. Values are mailbox **paths**, matched case-insensitively as every caller-supplied name in this file is; a scope resolving names by a different rule from the one the tools resolve arguments by is how an operator allows a mailbox the client cannot reach. A `mail_mailboxes` entry may also be written `Account/Mailbox` (e.g. `Work/INBOX`, `Work/[Gmail]/All Mail`) to match only that account's mailbox rather than forming a cross-product across every allowed account. Because mailbox paths themselves contain `/`, an entry is split at its first `/` only if the first segment equals (after the existing NFC + lowercase folding) one of the allowed account names in `mail_accounts` and the remainder is non-empty; otherwise the whole entry is a plain mailbox path matching any allowed account (`*` stays the only wildcard).

**Where the check has to happen is decided by how the thing is reached.** The scan intersects the allowed paths with the mailbox list *inside the generated script, before a single message column is fetched* — post-filtering rows still reads every subject of every mailbox the caller may not touch. `findMessageJXA` is necessarily **post-hoc**, because `byId` resolves globally, and both halves are compared: the mailbox **name** alone admits another account's `INBOX`, which is verbatim a bug that already shipped here. `mail_move` checks the source off the message and the **resolved** destination (account *and* full path) at the last moment before `found.mailbox = destMbox`, since a leaf name and a defaulted `target_account` sit between the string the caller wrote and the mailbox that would be written to. `senderJXA` asks a second question beside ownership — Mail owning `alice@` says the message *can* go out as it, not that this client may be Alice — and with neither `from` nor `account` it resolves the identity to the scope instead of letting Mail use its default account, which would have sent as someone else and reported `{"status": "sent"}`. The enumerators are scoped at both levels: `mail_list_mailboxes` is where every `mailbox` argument a caller ever passes comes from.

Expand Down
10 changes: 8 additions & 2 deletions Sources/macMCP/ContextSchema.swift
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,10 @@ private let mailScopeFields: [ScopeField] = [
noun: "mailbox",
description: "Mailbox paths within those accounts this client may reach — for reading and "
+ "for writing alike, so a client that may not read a mailbox may not move a message "
+ "into it either, and a client without Drafts here cannot create drafts",
+ "into it either, and a client without Drafts here cannot create drafts. Entries may "
+ "be plain mailbox paths (matching any allowed account) or Account/Mailbox (e.g. "
+ "“Work/INBOX”, “Work/[Gmail]/All Mail”), matching only that account's mailbox when "
+ "the first segment before ‘/’ matches an allowed account name.",
appliesTo: ["mail_*"],
dependsOn: ["mail_accounts"],
enumerate: { values in
Expand Down Expand Up @@ -234,7 +237,10 @@ private let mailScopeFields: [ScopeField] = [
//
// Each service is two fields -- the account and the thing inside it -- with
// the second `depends_on` the first, which is the `mail_accounts` /
// `mail_mailboxes` shape and combines the same way: a **cross-product**.
// `mail_mailboxes` shape and combines the same way: a **cross-product** (and
// `mail_mailboxes` additionally accepts `Account/Mailbox` entries to pin a
// mailbox to one account, split at the first `/` only when the first segment
// matches an allowed account name).
// Accounts `[iCloud, On My Mac]` with calendars `[iCloud/Work]` means the
// calendars in those accounts that are also in that list, which is one
// calendar. The account field is not redundant beside the leaf field: it is
Expand Down
110 changes: 106 additions & 4 deletions Sources/macMCP/Services/MailScope.swift
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,101 @@ extension ResourceScope {
}
}

// MARK: - Account-qualified mailbox entries

/// One entry in `mail_mailboxes`, split into an optional account qualifier
/// and a mailbox path.
///
/// **Slash ambiguity.** Mailbox paths themselves contain `/` (e.g.
/// `[Gmail]/All Mail`, `Projects/Archive`). An entry is split at its first
/// `/` if and only if the first segment equals (under `fold`) one of the
/// allowed account names in `mail_accounts` and the remainder is non-empty;
/// otherwise the whole entry is a plain mailbox path matching any allowed
/// account.
struct MailMailboxRule: Equatable {
/// `nil` for a plain entry (matches any allowed account); non-nil for
/// an `Account/Mailbox` entry (matches only that account).
let account: String?
let mailbox: String
}

/// Splits `entry` at its first ASCII `/` scalar (never on `Character`,
/// which would skip a `/` followed by a combining mark).
static func splitFirstSlash(_ entry: String) -> (head: String, tail: String)? {
guard let slash = entry.unicodeScalars.firstIndex(of: "/") else { return nil }
let head = String(entry.unicodeScalars[..<slash])
let tail = String(entry.unicodeScalars[entry.unicodeScalars.index(after: slash)...])
guard !head.isEmpty, !tail.isEmpty else { return nil }
return (head, tail)
}

/// Parses `mail_mailboxes` entries against `allowedAccounts`.
/// When `allowedAccounts` is `nil` (e.g. `mail_accounts: ["*"]`), no entry
/// is split here because there is no concrete list of allowed account names
/// in Swift; generated JXA resolves prefixes against live account names.
static func parseMailboxRules(
_ entries: [String],
allowedAccounts: [String]?
) -> [MailMailboxRule] {
let foldedAccounts = Set((allowedAccounts ?? []).map(fold))
return entries.map { entry in
if !foldedAccounts.isEmpty,
let (head, tail) = splitFirstSlash(entry),
foldedAccounts.contains(fold(head)) {
return MailMailboxRule(account: head, mailbox: tail)
}
return MailMailboxRule(account: nil, mailbox: entry)
}
}

/// The mailbox paths this scope allows for `account` (or across all allowed
/// accounts when `account == nil`). Returns `nil` for `.unscoped` /
/// `.unrestricted`, and `[]` for `.refuse` / `.confirmedEmpty`.
func allowedMailboxes(forAccount account: String? = nil) -> [String]? {
switch mailboxesAccess {
case .unscoped, .unrestricted:
return nil
case .refuse, .confirmedEmpty:
return []
case .allowed(let entries):
switch accountsAccess {
case .allowed(let accts):
let rules = ResourceScope.parseMailboxRules(entries, allowedAccounts: accts)
guard let account else {
return rules.map(\.mailbox)
}
let want = ResourceScope.fold(account)
return rules.compactMap { rule in
guard let ruleAccount = rule.account else { return rule.mailbox }
return ResourceScope.fold(ruleAccount) == want ? rule.mailbox : nil
}
case .unrestricted:
// Wildcard `mail_accounts` (`"*"`): Swift does not hold live
// account names, so JXA is authoritative. When a specific
// `account` is named, treat it as a known account name so
// `Account/Mailbox` entries for that account are recognised;
// when `account` is omitted, include both full entries and
// post-slash tails so valid paths reach JXA without false
// refusals.
if let account {
let rules = ResourceScope.parseMailboxRules(entries, allowedAccounts: [account])
return rules.map(\.mailbox)
}
var candidates: [String] = []
for entry in entries {
candidates.append(entry)
if let (_, tail) = ResourceScope.splitFirstSlash(entry) {
candidates.append(tail)
}
}
return candidates
case .unscoped, .refuse, .confirmedEmpty:
let rules = ResourceScope.parseMailboxRules(entries, allowedAccounts: nil)
return rules.map(\.mailbox)
}
}
}

/// The mailbox paths a scan may read, for a `mailbox` argument.
///
/// `requested` is the argument **as the caller wrote it** -- `nil` for
Expand All @@ -148,13 +243,19 @@ extension ResourceScope {
/// made. `wildcard` is the tool-level "everything" value, which also
/// resolves to the scope.
///
/// An explicit argument is matched against the allowed paths first, then
/// When `account` is non-nil, only entries applicable to that account (plain
/// entries and `Account/Mailbox` entries for that account) are considered.
/// An explicit argument is matched against those mailbox paths first, then
/// against their leaf names, which is the same two-step every mailbox
/// argument is resolved by (a bare name is a path with one component; a
/// leaf name is a fallback). The *result* is still the whole allowed list:
/// the intersection with what Mail actually holds happens inside the scan,
/// against paths read off Mail rather than against strings.
func mailboxTargets(requested: String?, wildcard: String = "all") -> Decision<[String]> {
func mailboxTargets(
requested: String?,
account: String? = nil,
wildcard: String = "all"
) -> Decision<[String]> {
switch mailboxesAccess {
case .unscoped:
return .unscoped
Expand Down Expand Up @@ -183,8 +284,9 @@ extension ResourceScope {
guard let requested, requested.lowercased() != wildcard.lowercased() else {
return .use(allowed)
}
let leaves = allowed.map { $0.split(separator: "/").last.map(String.init) ?? $0 }
guard MailScope.names(requested, oneOf: allowed)
let applicable = allowedMailboxes(forAccount: account) ?? []
let leaves = applicable.map { $0.split(separator: "/").last.map(String.init) ?? $0 }
guard MailScope.names(requested, oneOf: applicable)
|| MailScope.names(requested, oneOf: leaves) else {
return .refuse(
"mailbox \"\(requested)\" is outside the mailboxes this client may reach. "
Expand Down
Loading
Loading