@blackbelt-technology/pi-dashboard-gmail-plugin 0.11.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 CHANGED
@@ -2,47 +2,28 @@
2
2
 
3
3
  Multi-account Gmail for pi agents, managed from the pi-dashboard.
4
4
 
5
- - Guided Google Cloud setup (you bring your own OAuth client — Google offers no API to create one).
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 → General → Gmail)
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
- Google shows some errors (`org_internal`, `admin_policy_enforced`, …) on its own page and never returns to the dashboard. While a sign-in waits, open **"Google showed an error instead of returning here?"** under the sign-in link and pick the code Google displayed: the sign-in is cancelled and the fix is shown. Failed sign-ins are logged once on the server as `[gmail] sign-in failed: <code>` (a fixed code — never tokens, URLs or email).
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
- Revoking an account asks for confirmation first.
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 → Plugins → Gmail with every permission ticked. |
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 `gmail` (plaintext, mode 0600 — same posture as `auth.json`): the OAuth client and one record per account.
92
- - **Revoke** in the panel 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>.
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,6 +1,6 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-gmail-plugin",
3
- "version": "0.11.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
5
  "keywords": [
6
6
  "pi-dashboard-plugin"
@@ -64,8 +64,8 @@
64
64
  "react-dom": ">=18.0.0"
65
65
  },
66
66
  "dependencies": {
67
- "@blackbelt-technology/dashboard-plugin-runtime": "^0.11.0",
68
- "@blackbelt-technology/pi-dashboard-shared": "^0.11.0",
67
+ "@blackbelt-technology/dashboard-plugin-runtime": "^0.12.0",
68
+ "@blackbelt-technology/pi-dashboard-shared": "^0.12.0",
69
69
  "@fastify/rate-limit": "^11.2.0",
70
70
  "oauth4webapi": "^3.8.8",
71
71
  "ws": "^8.18.0"
@@ -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`. See change: add-gmail-plugin.
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 { ACCOUNTS_TYPE, type AccountInfo, LEASE_TYPE, type LeaseReply, PLUGIN_ID } from "../shared/protocol.js";
13
- import { isTier, type Op, tierAllows } from "../shared/scopes.js";
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
- const r = reply.result as Partial<LeaseReply> | null;
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
- async accounts(): Promise<AccountInfo[]> {
60
- const reply = await this.request(PLUGIN_ID, ACCOUNTS_TYPE, {});
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 AccountInfo[]) : [];
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
  }
@@ -195,7 +195,7 @@ interface FilterSpec {
195
195
  * check, confirm, lease or request: label actions only, no forwarding, no
196
196
  * blank / `*` / match-all criteria, no TRASH/SPAM additions.
197
197
  */
198
- export function parseFilterSpec(p: Record<string, unknown>): FilterSpec {
198
+ function parseFilterSpec(p: Record<string, unknown>): FilterSpec {
199
199
  const sections: Array<[string, unknown]> = [["request", p], ["criteria", p.criteria], ["filterAction", p.filterAction]];
200
200
  for (const [, obj] of sections) {
201
201
  if (isPlain(obj) && Object.keys(obj).some(isForwardKey)) {