@blackbelt-technology/pi-dashboard-gmail-plugin 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -37
- package/package.json +9 -4
- package/src/bridge/gmail-api.ts +23 -0
- package/src/bridge/lease-client.ts +127 -7
- package/src/bridge/tools.ts +217 -9
- package/src/client/GmailSettings.tsx +51 -735
- package/src/configSchema.json +14 -1
- package/src/i18n.ts +9 -205
- package/src/server/accounts.ts +37 -0
- package/src/server/google-link.ts +81 -0
- package/src/server/google-oauth.ts +8 -3
- package/src/server/index.ts +31 -14
- package/src/server/lease.ts +8 -3
- package/src/server/routes.ts +36 -188
- package/src/shared/client-json.ts +5 -3
- package/src/shared/protocol.ts +20 -0
- package/src/shared/scopes.ts +22 -6
- package/src/shared/setup.ts +43 -0
- package/src/client/wizard.ts +0 -136
- package/src/server/gmail-rest.ts +0 -27
- package/src/shared/flow-codes.ts +0 -36
package/README.md
CHANGED
|
@@ -2,47 +2,28 @@
|
|
|
2
2
|
|
|
3
3
|
Multi-account Gmail for pi agents, managed from the pi-dashboard.
|
|
4
4
|
|
|
5
|
-
-
|
|
5
|
+
- Accounts and OAuth clients are managed in **Settings → Google accounts** (Google Connect), including the guided Google Cloud setup.
|
|
6
6
|
- Several Gmail accounts, each with its own **permission level**.
|
|
7
7
|
- Refresh tokens stay in the dashboard server; tools get a short-lived access token per call.
|
|
8
8
|
- Account-scoped tools; every write is confirmed by you.
|
|
9
9
|
|
|
10
|
-
## Setup (Settings →
|
|
11
|
-
|
|
12
|
-
The wizard walks through these steps. Each console link carries `?project=<id>`.
|
|
13
|
-
|
|
14
|
-
1. **Project + Gmail API.** Create a Google Cloud project and enable the Gmail API — via the console links, or run the copyable commands yourself:
|
|
15
|
-
```sh
|
|
16
|
-
gcloud projects create <project-id>
|
|
17
|
-
gcloud services enable gmail.googleapis.com --project <project-id>
|
|
18
|
-
```
|
|
19
|
-
The dashboard never runs `gcloud`.
|
|
20
|
-
2. **Branding.** Console → Google Auth Platform → Branding (older consoles: *APIs & Services → OAuth consent screen*). Fill in the app name and support email.
|
|
21
|
-
3. **Audience.**
|
|
22
|
-
- **Internal** admits only accounts of the project's own Workspace organisation. Choose it only when *every* account you will connect belongs to that organisation.
|
|
23
|
-
- Otherwise **External**, and add every address you will connect as a **test user** — this includes a second Workspace domain or a gmail.com account next to your Workspace account (with Internal, Google shows `Error 403: org_internal` for them).
|
|
24
|
-
- One OAuth client per dashboard: to mix organisations, use External.
|
|
25
|
-
- For an **External** app in *Testing* status, Google expires refresh tokens after **7 days** (the panel shows a `testing: 7-day` badge). *Publish app* gives longer-lived tokens, with an "unverified app" warning at sign-in.
|
|
26
|
-
4. **Client.** Clients → Create client → application type **Desktop app**. Download the JSON.
|
|
27
|
-
5. **Upload** the `client_secret_*.json`. Only a Desktop (`installed`) client is accepted; a Web client is rejected.
|
|
28
|
-
6. **Test sign-in** = add your first account.
|
|
29
|
-
|
|
30
|
-
Every sign-in error is shown as a sentence (the raw code next to it, for support) and, where the fix is in the wizard, highlights that step:
|
|
31
|
-
|
|
32
|
-
| Error | Fix |
|
|
33
|
-
|---|---|
|
|
34
|
-
| `access_denied` ("app not verified for this user") | step 3 — add the address as a test user |
|
|
35
|
-
| `org_internal` | step 3 — the account is outside the project's Workspace organisation: switch the audience to External and add it as a test user |
|
|
36
|
-
| `admin_policy_enforced` | the account's Workspace admin must trust the OAuth client id (Admin console → Security → API controls → App access control) |
|
|
37
|
-
| `scope_missing` | Google did not grant the Gmail permission — add the account again and tick every permission (*Select all*) on the consent screen |
|
|
38
|
-
| `redirect_uri_mismatch`, Web client | step 4 — create a **Desktop** client |
|
|
39
|
-
| `invalid_client` | step 5 — re-upload the client JSON |
|
|
10
|
+
## Setup (Settings → Google accounts)
|
|
40
11
|
|
|
41
|
-
|
|
12
|
+
Gmail accounts, OAuth clients and the guided Google Cloud setup are managed by the **Google accounts** plugin
|
|
13
|
+
(`@blackbelt-technology/pi-dashboard-google-plugin`): open **Settings → Google accounts**, connect an account and turn
|
|
14
|
+
on **Gmail** with a level. This plugin only provides the Gmail tools and the `gmail` product's permission levels; it
|
|
15
|
+
stores no accounts or clients of its own.
|
|
42
16
|
|
|
43
|
-
|
|
17
|
+
- Accounts and clients connected with the previous Gmail-only wizard are imported into Google accounts once, on the first
|
|
18
|
+
start after upgrading (client → "Gmail client (migrated)"; each account keeps its level, aliases and filters).
|
|
19
|
+
- When the Google accounts plugin is disabled, the Gmail tools stop working and Gmail's settings say "Turn on Google
|
|
20
|
+
accounts to manage Gmail accounts".
|
|
21
|
+
- Sign-in errors (`access_denied`, `org_internal`, `admin_policy_enforced`, `scope_missing`, `redirect_uri_mismatch`,
|
|
22
|
+
`invalid_client`) are explained, with the fix, in the Google accounts connect dialog. Remote dashboards, return paths
|
|
23
|
+
and the "Window didn't come back?" switch are described in the Google plugin README.
|
|
24
|
+
- REST: the former `/api/plugins/gmail/{client,setup,accounts,…}` management routes answer `410 { "error": "moved" }`
|
|
25
|
+
(`503 { "error": "google_connect_unavailable" }` while Google accounts is off). Use the Google plugin's routes.
|
|
44
26
|
|
|
45
|
-
Remote dashboards: the sign-in listens on a `127.0.0.1` loopback port of the **dashboard host**. When your browser runs elsewhere, the redirect page fails to load — copy its full URL from the address bar and paste it into the flow view.
|
|
46
27
|
|
|
47
28
|
## Permission levels
|
|
48
29
|
|
|
@@ -79,7 +60,7 @@ Gmail API `403` errors are classified from Google's machine-readable reason only
|
|
|
79
60
|
| Tool error code | Meaning / fix |
|
|
80
61
|
|---|---|
|
|
81
62
|
| `api_disabled` | The Gmail API is disabled in the OAuth client's Google Cloud project. The message names the project number and the command: `gcloud services enable gmail.googleapis.com --project=<n>` (or APIs & Services → Library → Gmail API → Enable), then retry in a minute. |
|
|
82
|
-
| `scope_insufficient` | The account's grant lacks the Gmail permission. Re-authenticate it in Settings →
|
|
63
|
+
| `scope_insufficient` | The account's grant lacks the Gmail permission. Re-authenticate it in Settings → Google accounts with every permission ticked. |
|
|
83
64
|
| `gmail_error` | Any other 403. |
|
|
84
65
|
|
|
85
66
|
## Prompt injection
|
|
@@ -88,10 +69,14 @@ Mail content is attacker-controlled. Mailbox-derived results are marked `details
|
|
|
88
69
|
|
|
89
70
|
## Storage and removal
|
|
90
71
|
|
|
91
|
-
- `~/.pi/agent/plugin-credentials.json`, namespace `
|
|
92
|
-
- **Revoke** in
|
|
72
|
+
- Accounts, clients and tokens live in the Google accounts plugin (`~/.pi/agent/plugin-credentials.json`, namespace `google`, plaintext, mode 0600 — same posture as `auth.json`). The legacy `gmail` namespace is only read once, to import it; it is never written back.
|
|
73
|
+
- **Revoke** in Settings → Google accounts calls Google's revoke endpoint (best effort) and deletes the local record. If Google cannot be reached, revoke manually at <https://myaccount.google.com/permissions>.
|
|
93
74
|
- Disabling or uninstalling the plugin does not revoke grants.
|
|
94
75
|
|
|
95
76
|
## Testing
|
|
96
77
|
|
|
97
78
|
`PI_E2E_GOOGLE_BASE_URL` points every Google endpoint at a fake server. It is honoured **only** for `http://127.0.0.1:*` / `http://localhost:*`; any other value is ignored with a warning.
|
|
79
|
+
|
|
80
|
+
## Rolling back
|
|
81
|
+
|
|
82
|
+
Rolling back to the pre-Google-Connect build keeps Gmail working only for accounts whose legacy token is still valid. It does not cover accounts first connected after the migration, accounts re-signed after `reauth_required`, accounts whose access was removed at Google, or Google invalidating older refresh tokens when it issues new ones. Levels, aliases and filters changed after migration are not written back.
|
package/package.json
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blackbelt-technology/pi-dashboard-gmail-plugin",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "Multi-account Gmail for pi agents — guided Google OAuth setup, per-account permission levels, server-side token leasing and account-scoped Gmail tools with confirmed writes.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"pi-dashboard-plugin"
|
|
7
|
+
],
|
|
5
8
|
"license": "MIT",
|
|
6
9
|
"publishConfig": {
|
|
7
10
|
"access": "public"
|
|
@@ -61,14 +64,16 @@
|
|
|
61
64
|
"react-dom": ">=18.0.0"
|
|
62
65
|
},
|
|
63
66
|
"dependencies": {
|
|
64
|
-
"@blackbelt-technology/dashboard-plugin-runtime": "^0.
|
|
65
|
-
"@blackbelt-technology/pi-dashboard-shared": "^0.
|
|
67
|
+
"@blackbelt-technology/dashboard-plugin-runtime": "^0.12.0",
|
|
68
|
+
"@blackbelt-technology/pi-dashboard-shared": "^0.12.0",
|
|
66
69
|
"@fastify/rate-limit": "^11.2.0",
|
|
67
|
-
"oauth4webapi": "^3.8.8"
|
|
70
|
+
"oauth4webapi": "^3.8.8",
|
|
71
|
+
"ws": "^8.18.0"
|
|
68
72
|
},
|
|
69
73
|
"devDependencies": {
|
|
70
74
|
"@types/react": "^19.0.0",
|
|
71
75
|
"@types/react-dom": "^19.0.0",
|
|
76
|
+
"@types/ws": "^8.18.1",
|
|
72
77
|
"react": "^19.0.0",
|
|
73
78
|
"react-dom": "^19.0.0"
|
|
74
79
|
}
|
package/src/bridge/gmail-api.ts
CHANGED
|
@@ -33,6 +33,13 @@ export interface GmailMessage {
|
|
|
33
33
|
payload?: GmailPart;
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
+
/** A Gmail filter (`users.settings.filters`): criteria + label actions only are ever sent. */
|
|
37
|
+
export interface GmailFilter {
|
|
38
|
+
id: string;
|
|
39
|
+
criteria?: Record<string, unknown>;
|
|
40
|
+
action?: { addLabelIds?: string[]; removeLabelIds?: string[]; forward?: string };
|
|
41
|
+
}
|
|
42
|
+
|
|
36
43
|
export class GmailApi {
|
|
37
44
|
private readonly base: string;
|
|
38
45
|
private readonly token: string;
|
|
@@ -125,6 +132,22 @@ export class GmailApi {
|
|
|
125
132
|
trash(id: string) {
|
|
126
133
|
return this.call<unknown>("POST", `messages/${encodeURIComponent(id)}/trash`);
|
|
127
134
|
}
|
|
135
|
+
|
|
136
|
+
listFilters() {
|
|
137
|
+
return this.call<{ filter?: GmailFilter[] }>("GET", "settings/filters");
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
getFilter(id: string) {
|
|
141
|
+
return this.call<GmailFilter>("GET", `settings/filters/${encodeURIComponent(id)}`);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
createFilter(criteria: Record<string, unknown>, action: Record<string, unknown>) {
|
|
145
|
+
return this.call<GmailFilter>("POST", "settings/filters", { criteria, action });
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
deleteFilter(id: string) {
|
|
149
|
+
return this.call<unknown>("DELETE", `settings/filters/${encodeURIComponent(id)}`);
|
|
150
|
+
}
|
|
128
151
|
}
|
|
129
152
|
|
|
130
153
|
const GMAIL_403 = () => new GmailToolError("gmail_error", "gmail_error: Gmail returned HTTP 403");
|
|
@@ -3,14 +3,27 @@
|
|
|
3
3
|
* private request lane — no bridge cache, so a lowered level refuses the very
|
|
4
4
|
* next call. The returned `tier` is re-checked against the op (defence in
|
|
5
5
|
* depth). Error codes from the server (`<code>: <detail>`) are parsed into
|
|
6
|
-
* `GmailToolError`.
|
|
6
|
+
* `GmailToolError`. When Google Connect owns the accounts the Gmail lanes answer
|
|
7
|
+
* `{delegate:"google"}` and this client follows it to `google/lease` /
|
|
8
|
+
* `google/accounts`, re-spelling refusals as the Gmail errors the tools already
|
|
9
|
+
* know (add-google-connect D1/D7). See change: add-gmail-plugin.
|
|
7
10
|
*/
|
|
8
11
|
import {
|
|
9
12
|
type PluginLaneReply,
|
|
10
13
|
requestPluginServer,
|
|
11
14
|
} from "@blackbelt-technology/dashboard-plugin-runtime/bridge";
|
|
12
|
-
import {
|
|
13
|
-
|
|
15
|
+
import {
|
|
16
|
+
ACCOUNTS_TYPE,
|
|
17
|
+
type AccountInfo,
|
|
18
|
+
GOOGLE_ACCOUNTS_TYPE,
|
|
19
|
+
GOOGLE_LEASE_TYPE,
|
|
20
|
+
GOOGLE_PLUGIN_ID,
|
|
21
|
+
isDelegateReply,
|
|
22
|
+
LEASE_TYPE,
|
|
23
|
+
type LeaseReply,
|
|
24
|
+
PLUGIN_ID,
|
|
25
|
+
} from "../shared/protocol.js";
|
|
26
|
+
import { isFilterOp, isTier, type Op, tierAllows } from "../shared/scopes.js";
|
|
14
27
|
|
|
15
28
|
export type LaneRequest = (pluginId: string, type: string, payload?: unknown) => Promise<PluginLaneReply>;
|
|
16
29
|
|
|
@@ -36,6 +49,37 @@ function laneError(error: string): GmailToolError {
|
|
|
36
49
|
return new GmailToolError(error.slice(0, 64) || "lane_error", `Gmail lease failed: ${error.slice(0, 200)}`);
|
|
37
50
|
}
|
|
38
51
|
|
|
52
|
+
/** The `google/accounts` row, as far as Gmail reads it. */
|
|
53
|
+
interface GoogleAccount {
|
|
54
|
+
sub: string;
|
|
55
|
+
email: string;
|
|
56
|
+
alias?: string;
|
|
57
|
+
status: "ok" | "reauth_required";
|
|
58
|
+
testingHint?: boolean;
|
|
59
|
+
addedAt: number;
|
|
60
|
+
products?: { gmail?: { level?: string; options?: { filters?: boolean } } };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const labelOf = (a: { email: string; alias?: string }): string => (a.alias ? `${a.alias} (${a.email})` : a.email);
|
|
64
|
+
|
|
65
|
+
/** The Google accounts that have Gmail on, as Gmail accounts (level → tier, filters option). */
|
|
66
|
+
function gmailAccounts(list: readonly GoogleAccount[]): AccountInfo[] {
|
|
67
|
+
const out: AccountInfo[] = [];
|
|
68
|
+
for (const a of list) {
|
|
69
|
+
const sel = a.products?.gmail;
|
|
70
|
+
if (!sel || !isTier(sel.level)) continue;
|
|
71
|
+
const info: AccountInfo = { sub: a.sub, email: a.email, tier: sel.level, status: a.status, addedAt: a.addedAt };
|
|
72
|
+
if (a.alias) info.alias = a.alias;
|
|
73
|
+
if (a.testingHint) info.testingHint = true;
|
|
74
|
+
if (sel.options?.filters) info.filters = true;
|
|
75
|
+
out.push(info);
|
|
76
|
+
}
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Refusal codes whose Gmail wording names the account's email (so `google/accounts` is consulted). */
|
|
81
|
+
const NEEDS_ACCOUNTS = new Set(["product_disabled", "level_insufficient", "reauth_required", "scope_missing", "not_found", "ambiguous"]);
|
|
82
|
+
|
|
39
83
|
export class LeaseClient {
|
|
40
84
|
private readonly request: LaneRequest;
|
|
41
85
|
|
|
@@ -46,7 +90,20 @@ export class LeaseClient {
|
|
|
46
90
|
async lease(account: string, op: Op): Promise<LeaseReply> {
|
|
47
91
|
const reply = await this.request(PLUGIN_ID, LEASE_TYPE, { account, op });
|
|
48
92
|
if (!reply.ok) throw laneError(reply.error);
|
|
49
|
-
|
|
93
|
+
if (isDelegateReply(reply.result)) return this.delegatedLease(account, op);
|
|
94
|
+
return this.checked(reply.result, op);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async accounts(): Promise<AccountInfo[]> {
|
|
98
|
+
const reply = await this.request(PLUGIN_ID, ACCOUNTS_TYPE, {});
|
|
99
|
+
if (!reply.ok) throw laneError(reply.error);
|
|
100
|
+
if (isDelegateReply(reply.result)) return gmailAccounts(await this.googleAccounts());
|
|
101
|
+
return Array.isArray(reply.result) ? (reply.result as AccountInfo[]) : [];
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Defence in depth: the tier the lane reports must allow the op, whichever lane answered. */
|
|
105
|
+
private checked(result: unknown, op: Op): LeaseReply {
|
|
106
|
+
const r = result as Partial<LeaseReply> | null;
|
|
50
107
|
if (!r || typeof r.accessToken !== "string" || !isTier(r.tier) || typeof r.email !== "string") {
|
|
51
108
|
throw new GmailToolError("bad_lease", "Gmail lease reply was malformed");
|
|
52
109
|
}
|
|
@@ -56,9 +113,72 @@ export class LeaseClient {
|
|
|
56
113
|
return r as LeaseReply;
|
|
57
114
|
}
|
|
58
115
|
|
|
59
|
-
|
|
60
|
-
|
|
116
|
+
/**
|
|
117
|
+
* Lease from `google/lease` with product `gmail`. No level is requested: the reply's level is checked here,
|
|
118
|
+
* so a refusal reads exactly like the pre-migration `tier_denied`. Transport failures keep the existing
|
|
119
|
+
* Gmail error; there is no fallback to legacy tokens (an imported, later disconnected account stays gone).
|
|
120
|
+
*/
|
|
121
|
+
private async delegatedLease(account: string, op: Op): Promise<LeaseReply> {
|
|
122
|
+
const reply = await this.request(GOOGLE_PLUGIN_ID, GOOGLE_LEASE_TYPE, { account, product: "gmail" });
|
|
123
|
+
if (!reply.ok) throw await this.googleRefusal(reply.error, account, op);
|
|
124
|
+
const r = reply.result as {
|
|
125
|
+
accessToken?: unknown;
|
|
126
|
+
expiresAt?: unknown;
|
|
127
|
+
email?: unknown;
|
|
128
|
+
level?: unknown;
|
|
129
|
+
options?: { filters?: boolean };
|
|
130
|
+
} | null;
|
|
131
|
+
if (!r || typeof r.accessToken !== "string" || typeof r.email !== "string" || typeof r.expiresAt !== "number" || !isTier(r.level)) {
|
|
132
|
+
throw new GmailToolError("bad_lease", "Gmail lease reply was malformed");
|
|
133
|
+
}
|
|
134
|
+
if (isFilterOp(op) && r.options?.filters !== true) {
|
|
135
|
+
throw new GmailToolError(
|
|
136
|
+
"filters_disabled",
|
|
137
|
+
`filters_disabled: filters are not enabled for ${r.email}; turn them on for this account in Settings → Google accounts`,
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
return this.checked({ accessToken: r.accessToken, expiresAt: r.expiresAt, email: r.email, tier: r.level }, op);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
private async googleAccounts(): Promise<GoogleAccount[]> {
|
|
144
|
+
const reply = await this.request(GOOGLE_PLUGIN_ID, GOOGLE_ACCOUNTS_TYPE, {});
|
|
61
145
|
if (!reply.ok) throw laneError(reply.error);
|
|
62
|
-
return Array.isArray(reply.result) ? (reply.result as
|
|
146
|
+
return Array.isArray(reply.result) ? (reply.result as GoogleAccount[]) : [];
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Map a `google/lease` refusal onto the existing Gmail codes and messages (D7). Anything else passes through. */
|
|
150
|
+
private async googleRefusal(error: string, account: string, op: Op): Promise<GmailToolError> {
|
|
151
|
+
const code = /^([a-z_]{1,64}): /.exec(error)?.[1];
|
|
152
|
+
if (!code || !NEEDS_ACCOUNTS.has(code)) {
|
|
153
|
+
return code === "default_client_unavailable" || code === "no_client"
|
|
154
|
+
? new GmailToolError("no_client", "no_client: the Gmail OAuth client is not configured")
|
|
155
|
+
: laneError(error);
|
|
156
|
+
}
|
|
157
|
+
const key = account.trim().toLowerCase();
|
|
158
|
+
const all = await this.googleAccounts().catch(() => [] as GoogleAccount[]);
|
|
159
|
+
const found = all.filter((a) => a.sub === account || a.email.toLowerCase() === key || a.alias?.toLowerCase() === key);
|
|
160
|
+
const email = found.length === 1 ? (found[0] as GoogleAccount).email : account;
|
|
161
|
+
switch (code) {
|
|
162
|
+
case "level_insufficient": {
|
|
163
|
+
const level = /"([a-z]+)"/.exec(error)?.[1];
|
|
164
|
+
return isTier(level)
|
|
165
|
+
? new GmailToolError("tier_denied", `tier_denied: ${email} is at level "${level}", which does not allow "${op}"`)
|
|
166
|
+
: laneError(error);
|
|
167
|
+
}
|
|
168
|
+
case "ambiguous":
|
|
169
|
+
return new GmailToolError("ambiguous", `ambiguous: Several connected accounts share ${account}; set an alias on each in the Gmail panel and use the alias.`);
|
|
170
|
+
case "product_disabled":
|
|
171
|
+
return new GmailToolError("not_found", `not_found: Gmail is off for ${email} in Settings → Google accounts`);
|
|
172
|
+
case "reauth_required":
|
|
173
|
+
return new GmailToolError("reauth_required", `reauth_required: ${email} needs re-authentication in the Gmail panel`);
|
|
174
|
+
case "scope_missing":
|
|
175
|
+
return new GmailToolError("scope_missing", `scope_missing: Google did not grant the scope "${op}" needs for ${email}; re-authenticate`);
|
|
176
|
+
case "not_found": {
|
|
177
|
+
const known = gmailAccounts(all).map(labelOf).join(", ") || "none connected";
|
|
178
|
+
return new GmailToolError("not_found", `not_found: No connected Gmail account matches "${account}". Known accounts: ${known}.`);
|
|
179
|
+
}
|
|
180
|
+
default:
|
|
181
|
+
return laneError(error);
|
|
182
|
+
}
|
|
63
183
|
}
|
|
64
184
|
}
|
package/src/bridge/tools.ts
CHANGED
|
@@ -13,15 +13,23 @@
|
|
|
13
13
|
* See change: add-gmail-plugin.
|
|
14
14
|
*/
|
|
15
15
|
import type { GoogleEndpoints } from "../shared/endpoints.js";
|
|
16
|
-
import type { LeaseReply } from "../shared/protocol.js";
|
|
17
|
-
import type
|
|
16
|
+
import type { AccountInfo, LeaseReply } from "../shared/protocol.js";
|
|
17
|
+
import { type Op, tierAllows } from "../shared/scopes.js";
|
|
18
18
|
import { MAX_ATTACH_BYTES, readInsideCwd, saveInsideCwd } from "./attachments.js";
|
|
19
|
-
import { extractBody, GmailApi, type GmailMessage, header, listAttachments } from "./gmail-api.js";
|
|
19
|
+
import { extractBody, GmailApi, type GmailFilter, type GmailMessage, header, listAttachments } from "./gmail-api.js";
|
|
20
20
|
import { GmailToolError, type LeaseClient } from "./lease-client.js";
|
|
21
21
|
import { buildMime, type MimeAttachment, toRaw } from "./mime.js";
|
|
22
22
|
|
|
23
|
-
export const READ_TOOLS = ["gmail_search", "gmail_get", "gmail_labels", "gmail_attachments"] as const;
|
|
24
|
-
export const WRITE_TOOLS = [
|
|
23
|
+
export const READ_TOOLS = ["gmail_search", "gmail_get", "gmail_labels", "gmail_attachments", "gmail_filters_list"] as const;
|
|
24
|
+
export const WRITE_TOOLS = [
|
|
25
|
+
"gmail_draft",
|
|
26
|
+
"gmail_send",
|
|
27
|
+
"gmail_reply",
|
|
28
|
+
"gmail_modify",
|
|
29
|
+
"gmail_trash",
|
|
30
|
+
"gmail_filter_create",
|
|
31
|
+
"gmail_filter_delete",
|
|
32
|
+
] as const;
|
|
25
33
|
|
|
26
34
|
const MAX_SEARCH_RESULTS = 50;
|
|
27
35
|
const PREVIEW_CHARS = 500;
|
|
@@ -149,19 +157,98 @@ function messageLines(m: { account: string; to: string[]; cc?: string[]; bcc?: s
|
|
|
149
157
|
];
|
|
150
158
|
}
|
|
151
159
|
|
|
152
|
-
|
|
160
|
+
/** A confirmed write needs an interactive UI; checked before anything reaches Google. */
|
|
161
|
+
function assertInteractive(ctx: ToolContext | undefined): void {
|
|
153
162
|
if (!ctx?.hasUI || !ctx.ui) {
|
|
154
163
|
throw new GmailToolError("blocked", "blocked: this Gmail write needs user confirmation, but no UI is available");
|
|
155
164
|
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function confirmWrite(ctx: ToolContext | undefined, title: string, lines: string[]): Promise<void> {
|
|
168
|
+
assertInteractive(ctx);
|
|
169
|
+
const ui = (ctx as ToolContext).ui as NonNullable<ToolContext["ui"]>;
|
|
156
170
|
let ok = false;
|
|
157
171
|
try {
|
|
158
|
-
ok = (await
|
|
172
|
+
ok = (await ui.confirm(title, lines.join("\n"))) === true;
|
|
159
173
|
} catch {
|
|
160
174
|
ok = false; // dismissed / timed out / transport error → deny
|
|
161
175
|
}
|
|
162
176
|
if (!ok) throw new GmailToolError("denied", "denied: the user did not approve this Gmail action");
|
|
163
177
|
}
|
|
164
178
|
|
|
179
|
+
const CRITERIA_STRING_KEYS = ["from", "to", "subject", "query", "negatedQuery"] as const;
|
|
180
|
+
const CRITERIA_KEYS: readonly string[] = [...CRITERIA_STRING_KEYS, "hasAttachment"];
|
|
181
|
+
const ACTION_KEYS: readonly string[] = ["addLabelIds", "removeLabelIds"];
|
|
182
|
+
const FORBIDDEN_ADD_LABELS = new Set(["TRASH", "SPAM"]);
|
|
183
|
+
|
|
184
|
+
const isPlain = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
185
|
+
const isForwardKey = (k: string) => k.toLowerCase().startsWith("forward");
|
|
186
|
+
const invalidFilter = (why: string) => new GmailToolError("invalid_filter", `invalid_filter: ${why}`);
|
|
187
|
+
|
|
188
|
+
interface FilterSpec {
|
|
189
|
+
criteria: Record<string, string | true>;
|
|
190
|
+
action: { addLabelIds?: string[]; removeLabelIds?: string[] };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Fail-closed allow-list for `gmail_filter_create`, run before any account
|
|
195
|
+
* check, confirm, lease or request: label actions only, no forwarding, no
|
|
196
|
+
* blank / `*` / match-all criteria, no TRASH/SPAM additions.
|
|
197
|
+
*/
|
|
198
|
+
function parseFilterSpec(p: Record<string, unknown>): FilterSpec {
|
|
199
|
+
const sections: Array<[string, unknown]> = [["request", p], ["criteria", p.criteria], ["filterAction", p.filterAction]];
|
|
200
|
+
for (const [, obj] of sections) {
|
|
201
|
+
if (isPlain(obj) && Object.keys(obj).some(isForwardKey)) {
|
|
202
|
+
throw new GmailToolError("forward_refused", "forward_refused: forwarding filters are not supported");
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
const extra = Object.keys(p).filter((k) => !["account", "criteria", "filterAction"].includes(k));
|
|
206
|
+
if (extra.length) throw invalidFilter(`unsupported field \`${extra[0]}\``);
|
|
207
|
+
if (!isPlain(p.criteria)) throw invalidFilter("`criteria` must be an object");
|
|
208
|
+
if (!isPlain(p.filterAction)) throw invalidFilter("`filterAction` must be an object");
|
|
209
|
+
|
|
210
|
+
const criteria: Record<string, string | true> = {};
|
|
211
|
+
for (const [k, v] of Object.entries(p.criteria)) {
|
|
212
|
+
if (!CRITERIA_KEYS.includes(k)) throw invalidFilter(`unsupported criteria field \`${k}\``);
|
|
213
|
+
if (k === "hasAttachment") {
|
|
214
|
+
if (typeof v !== "boolean") throw invalidFilter("`hasAttachment` must be a boolean");
|
|
215
|
+
if (v) criteria[k] = true;
|
|
216
|
+
} else {
|
|
217
|
+
if (typeof v !== "string") throw invalidFilter(`criteria \`${k}\` must be a string`);
|
|
218
|
+
const t = v.trim();
|
|
219
|
+
if (t && t !== "*") criteria[k] = t;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
if (!Object.keys(criteria).length) throw invalidFilter("at least one non-blank criterion (not `*`) is required");
|
|
223
|
+
|
|
224
|
+
const action: FilterSpec["action"] = {};
|
|
225
|
+
for (const [k, v] of Object.entries(p.filterAction)) {
|
|
226
|
+
if (!ACTION_KEYS.includes(k)) throw invalidFilter(`unsupported action field \`${k}\``);
|
|
227
|
+
if (!Array.isArray(v) || v.some((x) => typeof x !== "string")) throw invalidFilter(`\`${k}\` must be a list of label ids`);
|
|
228
|
+
const ids = (v as string[]).map((x) => x.trim()).filter(Boolean);
|
|
229
|
+
if (k === "addLabelIds" && ids.some((x) => FORBIDDEN_ADD_LABELS.has(x.toUpperCase()))) {
|
|
230
|
+
throw invalidFilter("a filter must not add the TRASH or SPAM label");
|
|
231
|
+
}
|
|
232
|
+
if (ids.length) action[k as "addLabelIds" | "removeLabelIds"] = ids;
|
|
233
|
+
}
|
|
234
|
+
if (!action.addLabelIds?.length && !action.removeLabelIds?.length) throw invalidFilter("at least one label id to add or remove is required");
|
|
235
|
+
return { criteria, action };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function describeCriteria(c: Record<string, unknown> | undefined): string {
|
|
239
|
+
const parts = Object.entries(c ?? {}).map(([k, v]) => `${k}=${typeof v === "string" ? v : String(v)}`);
|
|
240
|
+
return parts.length ? parts.join(", ") : "(none)";
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function describeAction(a: GmailFilter["action"]): string {
|
|
244
|
+
const parts = [
|
|
245
|
+
...(a?.addLabelIds?.length ? [`add labels ${a.addLabelIds.join(", ")}`] : []),
|
|
246
|
+
...(a?.removeLabelIds?.length ? [`remove labels ${a.removeLabelIds.join(", ")}`] : []),
|
|
247
|
+
...(a?.forward ? ["forward (not supported by this tool)"] : []),
|
|
248
|
+
];
|
|
249
|
+
return parts.length ? parts.join("; ") : "(none)";
|
|
250
|
+
}
|
|
251
|
+
|
|
165
252
|
export function createGmailTools(deps: GmailToolDeps): GmailToolDef[] {
|
|
166
253
|
const api = (l: LeaseReply) => new GmailApi(deps.endpoints.gmail, l.accessToken, deps.fetchImpl);
|
|
167
254
|
|
|
@@ -186,6 +273,33 @@ export function createGmailTools(deps: GmailToolDeps): GmailToolDef[] {
|
|
|
186
273
|
return run(await requireAccount(p), p, ctx);
|
|
187
274
|
};
|
|
188
275
|
|
|
276
|
+
/**
|
|
277
|
+
* Resolve `ref` (alias or email) against the secret-free account list and
|
|
278
|
+
* refuse a filter call the server would refuse anyway — BEFORE any confirm,
|
|
279
|
+
* lease or request. The lease stays authoritative.
|
|
280
|
+
*/
|
|
281
|
+
async function filterPrecheck(ref: string, op: "filters_read" | "filters_write"): Promise<AccountInfo> {
|
|
282
|
+
const list = await deps.leases.accounts();
|
|
283
|
+
const key = ref.trim().toLowerCase();
|
|
284
|
+
const hits = list.filter((a) => a.alias?.toLowerCase() === key || a.email.toLowerCase() === key);
|
|
285
|
+
if (hits.length === 0) {
|
|
286
|
+
const known = list.map((x) => (x.alias ? `${x.alias} (${x.email})` : x.email)).join(", ") || "none connected";
|
|
287
|
+
throw new GmailToolError("not_found", `not_found: no connected account matches "${ref}". Connected accounts: ${known}`);
|
|
288
|
+
}
|
|
289
|
+
if (hits.length > 1) throw new GmailToolError("ambiguous", `ambiguous: "${ref}" matches several accounts; use an alias`);
|
|
290
|
+
const acct = hits[0] as AccountInfo;
|
|
291
|
+
if (acct.filters !== true) {
|
|
292
|
+
throw new GmailToolError(
|
|
293
|
+
"filters_disabled",
|
|
294
|
+
`filters_disabled: filters are not enabled for ${acct.email}; turn them on for this account in the Gmail settings`,
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
if (!tierAllows(acct.tier, op)) {
|
|
298
|
+
throw new GmailToolError("tier_denied", `tier_denied: ${acct.email} is at level "${acct.tier}", which does not allow "${op}"`);
|
|
299
|
+
}
|
|
300
|
+
return acct;
|
|
301
|
+
}
|
|
302
|
+
|
|
189
303
|
async function loadAttachments(ctx: ToolContext | undefined, paths: string[]): Promise<MimeAttachment[]> {
|
|
190
304
|
if (!paths.length) return [];
|
|
191
305
|
if (!ctx?.cwd) throw new GmailToolError("path_refused", "path_refused: no session working directory");
|
|
@@ -264,10 +378,10 @@ export function createGmailTools(deps: GmailToolDeps): GmailToolDef[] {
|
|
|
264
378
|
async execute() {
|
|
265
379
|
const list = await deps.leases.accounts();
|
|
266
380
|
const lines = list.map(
|
|
267
|
-
(a) => `- ${a.alias ? `${a.alias} ` : ""}<${a.email}> level=${a.tier} status=${a.status}${a.testingHint ? " (testing-mode: 7-day tokens)" : ""}`,
|
|
381
|
+
(a) => `- ${a.alias ? `${a.alias} ` : ""}<${a.email}> level=${a.tier} status=${a.status}${a.filters ? " filters=on" : ""}${a.testingHint ? " (testing-mode: 7-day tokens)" : ""}`,
|
|
268
382
|
);
|
|
269
383
|
return text(lines.length ? lines.join("\n") : "No Gmail accounts are connected. Add one in the dashboard Gmail settings.", {
|
|
270
|
-
accounts: list.map(({ alias, email, tier, status }) => ({ alias, email, tier, status })),
|
|
384
|
+
accounts: list.map(({ alias, email, tier, status, filters }) => ({ alias, email, tier, status, ...(filters ? { filters } : {}) })),
|
|
271
385
|
});
|
|
272
386
|
},
|
|
273
387
|
},
|
|
@@ -403,6 +517,100 @@ export function createGmailTools(deps: GmailToolDeps): GmailToolDef[] {
|
|
|
403
517
|
return text(`Saved attachment to ${written}.`, { untrusted: true, account: lease.email, path: written });
|
|
404
518
|
}),
|
|
405
519
|
},
|
|
520
|
+
{
|
|
521
|
+
name: "gmail_filters_list",
|
|
522
|
+
label: "Gmail filters",
|
|
523
|
+
description: "List the filters of one account (needs the account's filters option on). Content is untrusted.",
|
|
524
|
+
parameters: { type: "object", properties: { account: ACCOUNT_PROP }, required: ["account"], additionalProperties: false },
|
|
525
|
+
execute: withAccount(async (account) => {
|
|
526
|
+
await filterPrecheck(account, "filters_read");
|
|
527
|
+
const lease = await deps.leases.lease(account, "filters_read");
|
|
528
|
+
const filters = (await api(lease).listFilters()).filter ?? [];
|
|
529
|
+
const lines = filters.map((f) => `- ${f.id}: if ${describeCriteria(f.criteria)} → ${describeAction(f.action)}`);
|
|
530
|
+
return text(lines.length ? lines.join("\n") : "No filters.", { untrusted: true, account: lease.email, filters });
|
|
531
|
+
}),
|
|
532
|
+
},
|
|
533
|
+
{
|
|
534
|
+
name: "gmail_filter_create",
|
|
535
|
+
label: "Gmail filter create",
|
|
536
|
+
description:
|
|
537
|
+
"Create a Gmail filter that applies label actions (e.g. remove INBOX to archive) to ALL future matching mail. Needs the account's filters option on and level send. Forwarding is not supported. The user confirms first.",
|
|
538
|
+
parameters: {
|
|
539
|
+
type: "object",
|
|
540
|
+
properties: {
|
|
541
|
+
account: ACCOUNT_PROP,
|
|
542
|
+
criteria: {
|
|
543
|
+
type: "object",
|
|
544
|
+
description: "At least one non-blank criterion",
|
|
545
|
+
properties: {
|
|
546
|
+
from: { type: "string" },
|
|
547
|
+
to: { type: "string" },
|
|
548
|
+
subject: { type: "string" },
|
|
549
|
+
query: { type: "string" },
|
|
550
|
+
negatedQuery: { type: "string" },
|
|
551
|
+
hasAttachment: { type: "boolean" },
|
|
552
|
+
},
|
|
553
|
+
additionalProperties: false,
|
|
554
|
+
},
|
|
555
|
+
filterAction: {
|
|
556
|
+
type: "object",
|
|
557
|
+
description: "Label ids to add or remove (never TRASH/SPAM additions)",
|
|
558
|
+
properties: {
|
|
559
|
+
addLabelIds: { type: "array", items: { type: "string", minLength: 1 } },
|
|
560
|
+
removeLabelIds: { type: "array", items: { type: "string", minLength: 1 } },
|
|
561
|
+
},
|
|
562
|
+
additionalProperties: false,
|
|
563
|
+
},
|
|
564
|
+
},
|
|
565
|
+
required: ["account", "criteria", "filterAction"],
|
|
566
|
+
additionalProperties: false,
|
|
567
|
+
},
|
|
568
|
+
// Order: validate → account-summary pre-check → no-UI check → confirm → write lease → REST.
|
|
569
|
+
execute: withAccount(async (account, p, ctx) => {
|
|
570
|
+
const spec = parseFilterSpec(p);
|
|
571
|
+
await filterPrecheck(account, "filters_write");
|
|
572
|
+
assertInteractive(ctx);
|
|
573
|
+
await confirmWrite(ctx, `Gmail: create filter in ${account}`, [
|
|
574
|
+
`Account: ${account}`,
|
|
575
|
+
`Criteria: ${describeCriteria(spec.criteria)}`,
|
|
576
|
+
`Actions: ${describeAction(spec.action)}`,
|
|
577
|
+
"",
|
|
578
|
+
"This filter applies to all future matching mail.",
|
|
579
|
+
]);
|
|
580
|
+
const lease = await deps.leases.lease(account, "filters_write");
|
|
581
|
+
const f = await api(lease).createFilter(spec.criteria, spec.action);
|
|
582
|
+
return text(`Filter ${f.id} created in ${lease.email}.`, { account: lease.email, filterId: f.id });
|
|
583
|
+
}),
|
|
584
|
+
},
|
|
585
|
+
{
|
|
586
|
+
name: "gmail_filter_delete",
|
|
587
|
+
label: "Gmail filter delete",
|
|
588
|
+
description:
|
|
589
|
+
"Delete a Gmail filter by id (needs the account's filters option on and level send). The user confirms first, seeing the filter's criteria and actions.",
|
|
590
|
+
parameters: {
|
|
591
|
+
type: "object",
|
|
592
|
+
properties: { account: ACCOUNT_PROP, id: { type: "string", minLength: 1, description: "Filter id (from gmail_filters_list)" } },
|
|
593
|
+
required: ["account", "id"],
|
|
594
|
+
additionalProperties: false,
|
|
595
|
+
},
|
|
596
|
+
// Order: validate → pre-check → no-UI check → read lease + GET → confirm → write lease → DELETE.
|
|
597
|
+
execute: withAccount(async (account, p, ctx) => {
|
|
598
|
+
const id = str(p.id, "id") as string;
|
|
599
|
+
await filterPrecheck(account, "filters_write");
|
|
600
|
+
assertInteractive(ctx);
|
|
601
|
+
const readLease = await deps.leases.lease(account, "filters_read");
|
|
602
|
+
const filter = await api(readLease).getFilter(id);
|
|
603
|
+
await confirmWrite(ctx, `Gmail: delete filter in ${account}`, [
|
|
604
|
+
`Account: ${account}`,
|
|
605
|
+
`Filter: ${filter.id ?? id}`,
|
|
606
|
+
`Criteria: ${describeCriteria(filter.criteria)}`,
|
|
607
|
+
`Actions: ${describeAction(filter.action)}`,
|
|
608
|
+
]);
|
|
609
|
+
const lease = await deps.leases.lease(account, "filters_write");
|
|
610
|
+
await api(lease).deleteFilter(id);
|
|
611
|
+
return text(`Filter ${id} deleted in ${lease.email}.`, { account: lease.email, filterId: id });
|
|
612
|
+
}),
|
|
613
|
+
},
|
|
406
614
|
compose("draft"),
|
|
407
615
|
compose("send"),
|
|
408
616
|
{
|