@blackbelt-technology/pi-dashboard-gmail-plugin 0.8.0 → 0.10.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
@@ -19,21 +19,28 @@ The wizard walks through these steps. Each console link carries `?project=<id>`.
19
19
  The dashboard never runs `gcloud`.
20
20
  2. **Branding.** Console → Google Auth Platform → Branding (older consoles: *APIs & Services → OAuth consent screen*). Fill in the app name and support email.
21
21
  3. **Audience.**
22
- - Workspace organisation: **Internal**.
23
- - Otherwise **External**, and add every Gmail address you will connect as a **test user**.
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.
24
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.
25
26
  4. **Client.** Clients → Create client → application type **Desktop app**. Download the JSON.
26
27
  5. **Upload** the `client_secret_*.json`. Only a Desktop (`installed`) client is accepted; a Web client is rejected.
27
28
  6. **Test sign-in** = add your first account.
28
29
 
29
- Sign-in errors point back to the step that fixes them:
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:
30
31
 
31
- | Error | Fix in step |
32
+ | Error | Fix |
32
33
  |---|---|
33
- | `access_denied` ("app not verified for this user") | 3 — add the address as a test user |
34
- | `org_internal` | 3 — audience |
35
- | `redirect_uri_mismatch`, Web client | 4 — create a **Desktop** client |
36
- | `invalid_client` | 5 — re-upload the client JSON |
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 |
40
+
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).
42
+
43
+ Revoking an account asks for confirmation first.
37
44
 
38
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.
39
46
 
@@ -67,6 +74,14 @@ Remote dashboards: the sign-in listens on a `127.0.0.1` loopback port of the **d
67
74
 
68
75
  Writes need a UI to confirm: a headless session is blocked, and a dismissed or timed-out prompt counts as "no".
69
76
 
77
+ Gmail API `403` errors are classified from Google's machine-readable reason only (its free text is never echoed):
78
+
79
+ | Tool error code | Meaning / fix |
80
+ |---|---|
81
+ | `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. |
83
+ | `gmail_error` | Any other 403. |
84
+
70
85
  ## Prompt injection
71
86
 
72
87
  Mail content is attacker-controlled. Mailbox-derived results are marked `details.untrusted = true` and declared to the optional `untrusted-content-guard` extension (reads untrusted, writes self-confirming). **Without the guard only the write confirmations protect you** — install it if agents read mail from strangers.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-gmail-plugin",
3
- "version": "0.8.0",
4
- "description": "Multi-account Gmail for pi agents \u2014 guided Google OAuth setup, per-account permission levels, server-side token leasing and account-scoped Gmail tools with confirmed writes.",
3
+ "version": "0.10.0",
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
  "license": "MIT",
6
6
  "publishConfig": {
7
7
  "access": "public"
@@ -61,10 +61,10 @@
61
61
  "react-dom": ">=18.0.0"
62
62
  },
63
63
  "dependencies": {
64
- "@blackbelt-technology/dashboard-plugin-runtime": "^0.8.0",
65
- "@blackbelt-technology/pi-dashboard-shared": "^0.8.0",
66
- "oauth4webapi": "^3.8.8",
67
- "@fastify/rate-limit": "^11.2.0"
64
+ "@blackbelt-technology/dashboard-plugin-runtime": "^0.10.0",
65
+ "@blackbelt-technology/pi-dashboard-shared": "^0.10.0",
66
+ "@fastify/rate-limit": "^11.2.0",
67
+ "oauth4webapi": "^3.8.8"
68
68
  },
69
69
  "devDependencies": {
70
70
  "@types/react": "^19.0.0",
@@ -17,7 +17,9 @@ import { isPathInside } from "@blackbelt-technology/pi-dashboard-shared/path-con
17
17
  export const MAX_ATTACH_BYTES = 20 * 1024 * 1024;
18
18
 
19
19
  class PathRefusedError extends Error {
20
- constructor(readonly code: "path_refused" | "exists" | "too_large") {
20
+ readonly code: "path_refused" | "exists" | "too_large";
21
+
22
+ constructor(code: "path_refused" | "exists" | "too_large") {
21
23
  super(
22
24
  code === "exists"
23
25
  ? "path_refused: target already exists (attachments never overwrite)"
@@ -25,6 +27,7 @@ class PathRefusedError extends Error {
25
27
  ? "path_refused: file exceeds the 20 MiB attachment limit"
26
28
  : "path_refused: path must stay inside the session working directory",
27
29
  );
30
+ this.code = code;
28
31
  this.name = "PathRefusedError";
29
32
  }
30
33
  }
@@ -2,7 +2,9 @@
2
2
  * Thin Gmail REST wrappers over `fetch` (design D6 — no `googleapis`).
3
3
  * One access token per instance (one lease per tool call). 429 / 5xx surface
4
4
  * as `rate_limited` / `gmail_unavailable` with Retry-After; NEVER retried here
5
- * (no retry storm). Error messages never include the token.
5
+ * (no retry storm). Error messages never include the token. 403 →
6
+ * `api_disabled` / `scope_insufficient` / `gmail_error` from Google's `reason`
7
+ * only (see change: improve-gmail-settings-ux).
6
8
  * See change: add-gmail-plugin.
7
9
  */
8
10
  import { GmailToolError } from "./lease-client.js";
@@ -32,11 +34,19 @@ export interface GmailMessage {
32
34
  }
33
35
 
34
36
  export class GmailApi {
37
+ private readonly base: string;
38
+ private readonly token: string;
39
+ private readonly fetchImpl: typeof fetch;
40
+
35
41
  constructor(
36
- private readonly base: string,
37
- private readonly token: string,
38
- private readonly fetchImpl: typeof fetch = fetch,
39
- ) {}
42
+ base: string,
43
+ token: string,
44
+ fetchImpl: typeof fetch = fetch,
45
+ ) {
46
+ this.base = base;
47
+ this.token = token;
48
+ this.fetchImpl = fetchImpl;
49
+ }
40
50
 
41
51
  private async call<T>(method: string, pathAndQuery: string, body?: unknown): Promise<T> {
42
52
  let res: Response;
@@ -68,6 +78,7 @@ export class GmailApi {
68
78
  }
69
79
  if (res.status === 401) throw new GmailToolError("unauthorized", "unauthorized: Gmail rejected the access token");
70
80
  if (res.status === 404) throw new GmailToolError("not_found", "not_found: no such message, thread or attachment");
81
+ if (res.status === 403) throw await classify403(res);
71
82
  throw new GmailToolError("gmail_error", `gmail_error: Gmail returned HTTP ${res.status}`);
72
83
  }
73
84
 
@@ -116,6 +127,61 @@ export class GmailApi {
116
127
  }
117
128
  }
118
129
 
130
+ const GMAIL_403 = () => new GmailToolError("gmail_error", "gmail_error: Gmail returned HTTP 403");
131
+ const isObj = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
132
+
133
+ const DISABLED = new Set(["SERVICE_DISABLED", "accessNotConfigured"]);
134
+ const SCOPE = new Set(["ACCESS_TOKEN_SCOPE_INSUFFICIENT", "insufficientPermissions"]);
135
+
136
+ /**
137
+ * Classify a Gmail 403 from Google's machine-readable `reason` ONLY (design
138
+ * D9). Google's body is untrusted: every field is type-guarded, any throw
139
+ * degrades to the generic `gmail_error`, and no body text (message,
140
+ * activationUrl, "consumer" other than `projects/<digits>`) reaches the message.
141
+ * See change: improve-gmail-settings-ux.
142
+ */
143
+ async function classify403(res: Response): Promise<GmailToolError> {
144
+ try {
145
+ const body: unknown = JSON.parse(await res.text());
146
+ const err = isObj(body) ? body.error : undefined;
147
+ if (!isObj(err)) return GMAIL_403();
148
+ // Modern shape: details[] ErrorInfo (reason + metadata); legacy: errors[].reason.
149
+ const infos = (Array.isArray(err.details) ? err.details : []).filter(
150
+ (d): d is Record<string, unknown> =>
151
+ isObj(d) && typeof d["@type"] === "string" && d["@type"].endsWith("google.rpc.ErrorInfo") && typeof d.reason === "string",
152
+ );
153
+ const legacy = (Array.isArray(err.errors) ? err.errors : [])
154
+ .map((e) => (isObj(e) && typeof e.reason === "string" ? e.reason : undefined))
155
+ .filter((r): r is string => r !== undefined);
156
+
157
+ const meta = (i: Record<string, unknown>) => (isObj(i.metadata) ? i.metadata : {});
158
+ const forGmail = (i: Record<string, unknown>) => {
159
+ const service = meta(i).service;
160
+ return typeof service !== "string" || service === "gmail.googleapis.com";
161
+ };
162
+ const disabled = infos.find((i) => DISABLED.has(i.reason as string) && forGmail(i));
163
+ if (disabled || legacy.some((r) => DISABLED.has(r))) {
164
+ const consumer = disabled ? meta(disabled).consumer : undefined;
165
+ const n = typeof consumer === "string" ? /^projects\/(\d{1,20})$/.exec(consumer)?.[1] : undefined;
166
+ return new GmailToolError(
167
+ "api_disabled",
168
+ n
169
+ ? `api_disabled: the Gmail API is disabled in Google Cloud project ${n}. Enable it: gcloud services enable gmail.googleapis.com --project=${n} (or APIs & Services \u2192 Library \u2192 Gmail API \u2192 Enable), then retry in a minute.`
170
+ : "api_disabled: the Gmail API is disabled in the dashboard's Google Cloud project. Enable it: gcloud services enable gmail.googleapis.com --project=<your-project> (or APIs & Services \u2192 Library \u2192 Gmail API \u2192 Enable), then retry in a minute.",
171
+ );
172
+ }
173
+ if (infos.some((i) => SCOPE.has(i.reason as string)) || legacy.some((r) => SCOPE.has(r))) {
174
+ return new GmailToolError(
175
+ "scope_insufficient",
176
+ "scope_insufficient: the account's grant lacks the Gmail permission; re-authenticate it in Settings \u2192 Plugins \u2192 Gmail with every permission ticked.",
177
+ );
178
+ }
179
+ return GMAIL_403();
180
+ } catch {
181
+ return GMAIL_403();
182
+ }
183
+ }
184
+
119
185
  /** Case-insensitive header lookup. */
120
186
  export function header(part: GmailPart | undefined, name: string): string | undefined {
121
187
  const n = name.toLowerCase();
@@ -15,11 +15,14 @@ import { isTier, type Op, tierAllows } from "../shared/scopes.js";
15
15
  export type LaneRequest = (pluginId: string, type: string, payload?: unknown) => Promise<PluginLaneReply>;
16
16
 
17
17
  export class GmailToolError extends Error {
18
+ readonly code: string;
19
+
18
20
  constructor(
19
- readonly code: string,
21
+ code: string,
20
22
  message: string,
21
23
  ) {
22
24
  super(message);
25
+ this.code = code;
23
26
  this.name = "GmailToolError";
24
27
  }
25
28
  }
@@ -34,7 +37,11 @@ function laneError(error: string): GmailToolError {
34
37
  }
35
38
 
36
39
  export class LeaseClient {
37
- constructor(private readonly request: LaneRequest = requestPluginServer) {}
40
+ private readonly request: LaneRequest;
41
+
42
+ constructor(request: LaneRequest = requestPluginServer) {
43
+ this.request = request;
44
+ }
38
45
 
39
46
  async lease(account: string, op: Op): Promise<LeaseReply> {
40
47
  const reply = await this.request(PLUGIN_ID, LEASE_TYPE, { account, op });