@blackbelt-technology/pi-dashboard-gmail-plugin 0.8.0 → 0.9.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.9.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.9.0",
65
+ "@blackbelt-technology/pi-dashboard-shared": "^0.9.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",
@@ -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";
@@ -68,6 +70,7 @@ export class GmailApi {
68
70
  }
69
71
  if (res.status === 401) throw new GmailToolError("unauthorized", "unauthorized: Gmail rejected the access token");
70
72
  if (res.status === 404) throw new GmailToolError("not_found", "not_found: no such message, thread or attachment");
73
+ if (res.status === 403) throw await classify403(res);
71
74
  throw new GmailToolError("gmail_error", `gmail_error: Gmail returned HTTP ${res.status}`);
72
75
  }
73
76
 
@@ -116,6 +119,61 @@ export class GmailApi {
116
119
  }
117
120
  }
118
121
 
122
+ const GMAIL_403 = () => new GmailToolError("gmail_error", "gmail_error: Gmail returned HTTP 403");
123
+ const isObj = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
124
+
125
+ const DISABLED = new Set(["SERVICE_DISABLED", "accessNotConfigured"]);
126
+ const SCOPE = new Set(["ACCESS_TOKEN_SCOPE_INSUFFICIENT", "insufficientPermissions"]);
127
+
128
+ /**
129
+ * Classify a Gmail 403 from Google's machine-readable `reason` ONLY (design
130
+ * D9). Google's body is untrusted: every field is type-guarded, any throw
131
+ * degrades to the generic `gmail_error`, and no body text (message,
132
+ * activationUrl, "consumer" other than `projects/<digits>`) reaches the message.
133
+ * See change: improve-gmail-settings-ux.
134
+ */
135
+ async function classify403(res: Response): Promise<GmailToolError> {
136
+ try {
137
+ const body: unknown = JSON.parse(await res.text());
138
+ const err = isObj(body) ? body.error : undefined;
139
+ if (!isObj(err)) return GMAIL_403();
140
+ // Modern shape: details[] ErrorInfo (reason + metadata); legacy: errors[].reason.
141
+ const infos = (Array.isArray(err.details) ? err.details : []).filter(
142
+ (d): d is Record<string, unknown> =>
143
+ isObj(d) && typeof d["@type"] === "string" && d["@type"].endsWith("google.rpc.ErrorInfo") && typeof d.reason === "string",
144
+ );
145
+ const legacy = (Array.isArray(err.errors) ? err.errors : [])
146
+ .map((e) => (isObj(e) && typeof e.reason === "string" ? e.reason : undefined))
147
+ .filter((r): r is string => r !== undefined);
148
+
149
+ const meta = (i: Record<string, unknown>) => (isObj(i.metadata) ? i.metadata : {});
150
+ const forGmail = (i: Record<string, unknown>) => {
151
+ const service = meta(i).service;
152
+ return typeof service !== "string" || service === "gmail.googleapis.com";
153
+ };
154
+ const disabled = infos.find((i) => DISABLED.has(i.reason as string) && forGmail(i));
155
+ if (disabled || legacy.some((r) => DISABLED.has(r))) {
156
+ const consumer = disabled ? meta(disabled).consumer : undefined;
157
+ const n = typeof consumer === "string" ? /^projects\/(\d{1,20})$/.exec(consumer)?.[1] : undefined;
158
+ return new GmailToolError(
159
+ "api_disabled",
160
+ n
161
+ ? `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.`
162
+ : "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.",
163
+ );
164
+ }
165
+ if (infos.some((i) => SCOPE.has(i.reason as string)) || legacy.some((r) => SCOPE.has(r))) {
166
+ return new GmailToolError(
167
+ "scope_insufficient",
168
+ "scope_insufficient: the account's grant lacks the Gmail permission; re-authenticate it in Settings \u2192 Plugins \u2192 Gmail with every permission ticked.",
169
+ );
170
+ }
171
+ return GMAIL_403();
172
+ } catch {
173
+ return GMAIL_403();
174
+ }
175
+ }
176
+
119
177
  /** Case-insensitive header lookup. */
120
178
  export function header(part: GmailPart | undefined, name: string): string | undefined {
121
179
  const n = name.toLowerCase();
@@ -5,14 +5,21 @@
5
5
  * (add / re-auth / level / alias / revoke, status badges, honest scope limit).
6
6
  * Sign-in flows render through the host `ui:oauth-flow` primitive.
7
7
  * See change: add-gmail-plugin.
8
+ *
9
+ * improve-gmail-settings-ux: declared theme tokens + `.focus-ring` on every
10
+ * control; consent hint + "Google showed an error?" disclosure while a sign-in
11
+ * waits (reported code latched via `reportedRef`, so neither poll callback can
12
+ * overwrite it or re-mount the flow); every flow error rendered as a sentence
13
+ * (`errorKey` / `ERROR_EN`); Revoke via `ui:confirm-dialog`; alias feedback;
14
+ * level descriptions; collapsed-summary project/client id.
8
15
  */
9
16
  import { oauthFlowClient, useT, useUiPrimitive } from "@blackbelt-technology/dashboard-plugin-runtime";
10
17
  import type React from "react";
11
- import { useCallback, useEffect, useRef, useState } from "react";
18
+ import { useCallback, useEffect, useId, useRef, useState } from "react";
12
19
  import { validateClientJson } from "../shared/client-json.js";
13
20
  import type { AccountInfo } from "../shared/protocol.js";
14
21
  import { TIERS, type Tier } from "../shared/scopes.js";
15
- import { consoleLinks, errorStep, gcloudCommands, type WizardStep } from "./wizard.js";
22
+ import { consoleLinks, ERROR_EN, errorKey, errorStep, gcloudCommands, type WizardStep } from "./wizard.js";
16
23
 
17
24
  const API = "/api/plugins/gmail";
18
25
 
@@ -35,8 +42,15 @@ async function api<T>(path: string, init?: RequestInit): Promise<T> {
35
42
  }
36
43
 
37
44
  const btn =
38
- "rounded border border-[var(--border)] px-2 py-0.5 text-[12px] hover:bg-[var(--bg-hover)] disabled:opacity-50";
45
+ "focus-ring rounded border border-[var(--border-primary)] px-2 py-0.5 text-[12px] hover:bg-[var(--bg-hover)] disabled:opacity-50";
46
+ const field = "focus-ring rounded border border-[var(--border-primary)] bg-transparent text-[12px]";
39
47
  const muted = "text-[12px] text-[var(--text-muted)]";
48
+ const errorText = "text-[12px] text-[var(--severity-error-fg)]";
49
+ // Static strings: Tailwind cannot see interpolated class names.
50
+ const badgeOk =
51
+ "rounded border border-[var(--severity-success-border)] bg-[var(--severity-success-bg)] px-1 text-[11px] text-[var(--severity-success-fg)]";
52
+ const badgeReauth =
53
+ "rounded border border-[var(--severity-warning-border)] bg-[var(--severity-warning-bg)] px-1 text-[11px] text-[var(--severity-warning-fg)]";
40
54
 
41
55
  /** Poll a flow every 500 ms until terminal. */
42
56
  function useFlowPoll(flowId: string | undefined, onPending: (s: FlowStatus) => void, onDone: (err: string | null) => void) {
@@ -70,7 +84,7 @@ function Copyable({ value }: { value: string }) {
70
84
  const t = useT();
71
85
  return (
72
86
  <div className="flex items-center gap-2">
73
- <code className="flex-1 overflow-x-auto rounded bg-[var(--bg-subtle)] px-2 py-1 text-[12px]">{value}</code>
87
+ <code className="flex-1 overflow-x-auto rounded bg-[var(--bg-tertiary)] px-2 py-1 text-[12px]">{value}</code>
74
88
  <button type="button" className={btn} onClick={() => void navigator.clipboard?.writeText(value)}>
75
89
  {t("copy", undefined, "Copy")}
76
90
  </button>
@@ -80,7 +94,7 @@ function Copyable({ value }: { value: string }) {
80
94
 
81
95
  function StepLink({ href, label }: { href: string; label: string }) {
82
96
  return (
83
- <a href={href} target="_blank" rel="noopener noreferrer" className="text-[12px] text-[var(--accent)] underline">
97
+ <a href={href} target="_blank" rel="noopener noreferrer" className="focus-ring text-[12px] text-[var(--accent-text)] underline">
84
98
  {label}
85
99
  </a>
86
100
  );
@@ -122,7 +136,7 @@ export function SetupWizard({
122
136
  };
123
137
 
124
138
  const stepClass = (n: WizardStep) =>
125
- `rounded border p-2 ${focus === n ? "border-[var(--warning)]" : "border-[var(--border)]"}`;
139
+ `rounded border p-2 ${focus === n ? "border-[var(--accent)]" : "border-[var(--border-primary)]"}`;
126
140
  const uploadMsg: Record<string, string> = {
127
141
  not_json: t("errNotJson", undefined, "That file is not valid JSON. Upload the client_secret_*.json you downloaded (step 5)."),
128
142
  web_client: t("errWebClient", undefined, "This is a Web application client. Create a Desktop app client instead (step 4)."),
@@ -144,7 +158,7 @@ export function SetupWizard({
144
158
  {t("projectId", undefined, "Project id")}
145
159
  <input
146
160
  data-testid="gmail-project-id"
147
- className="rounded border border-[var(--border)] bg-transparent px-1 text-[12px]"
161
+ className={`${field} px-1`}
148
162
  value={projectId}
149
163
  onChange={(e) => setProjectId(e.target.value)}
150
164
  placeholder="my-gmail-agent"
@@ -171,7 +185,14 @@ export function SetupWizard({
171
185
  {t(
172
186
  "audienceHelp",
173
187
  undefined,
174
- "Workspace org: choose Internal. Otherwise External, and add every Gmail address you will connect as a test user. In Testing, tokens expire after 7 days; “Publish app” gives longer-lived tokens with an unverified-app warning.",
188
+ "Internal admits only accounts of the project's own Workspace organization: choose it only when every account you will connect belongs to that organization. Otherwise choose External and add every address you will connect as a test user. In Testing, tokens expire after 7 days; “Publish app” gives longer-lived tokens with an unverified-app warning.",
189
+ )}
190
+ </div>
191
+ <div className={muted}>
192
+ {t(
193
+ "audienceErrors",
194
+ undefined,
195
+ "Google error pages: org_internal = the account is outside the organization, switch to External; access_denied = add the account as a test user; admin_policy_enforced = the account's Workspace admin must trust this OAuth client.",
175
196
  )}
176
197
  </div>
177
198
  </li>
@@ -186,6 +207,7 @@ export function SetupWizard({
186
207
  <div className="font-medium text-[13px]">{t("step5", undefined, "5. Upload client_secret_*.json")}</div>
187
208
  <input
188
209
  type="file"
210
+ className="focus-ring text-[12px]"
189
211
  accept="application/json,.json"
190
212
  data-testid="gmail-client-upload"
191
213
  aria-label={t("uploadLabel", undefined, "Upload the OAuth client JSON")}
@@ -200,7 +222,7 @@ export function SetupWizard({
200
222
  </div>
201
223
  )}
202
224
  {uploadError && (
203
- <div role="alert" className="text-[12px] text-[var(--error)]" data-testid="gmail-upload-error" data-step={uploadError.step}>
225
+ <div role="alert" className={errorText} data-testid="gmail-upload-error" data-step={uploadError.step}>
204
226
  {uploadMsg[uploadError.code] ?? uploadError.code}
205
227
  </div>
206
228
  )}
@@ -214,6 +236,28 @@ export function SetupWizard({
214
236
  }
215
237
 
216
238
  const TIER_LABEL: Record<Tier, string> = { readonly: "readonly", draft: "draft", send: "send" };
239
+ const TIER_DESC: Record<Tier, [key: string, en: string]> = {
240
+ readonly: ["tierReadonly", "read mail"],
241
+ draft: ["tierDraft", "read + create drafts"],
242
+ send: ["tierSend", "read, draft, send, reply, labels, archive, trash"],
243
+ };
244
+
245
+ /** `<option>`s carrying each level's own description. */
246
+ function TierOptions() {
247
+ const t = useT();
248
+ return (
249
+ <>
250
+ {TIERS.map((tier) => (
251
+ <option key={tier} value={tier}>
252
+ {`${TIER_LABEL[tier]} — ${t(TIER_DESC[tier][0], undefined, TIER_DESC[tier][1])}`}
253
+ </option>
254
+ ))}
255
+ </>
256
+ );
257
+ }
258
+
259
+ /** Codes the user can report from Google's own error page (closed list, design D1). */
260
+ const REPORT_CODES = ["org_internal", "access_denied", "admin_policy_enforced", "other"] as const;
217
261
 
218
262
  function AccountRow({
219
263
  acct,
@@ -227,8 +271,11 @@ function AccountRow({
227
271
  onRevoked: (email: string, remoteRevoked: boolean) => void;
228
272
  }) {
229
273
  const t = useT();
274
+ const ConfirmDialog = useUiPrimitive("ui:confirm-dialog");
230
275
  const [alias, setAlias] = useState(acct.alias ?? "");
231
276
  const [msg, setMsg] = useState<string | null>(null);
277
+ const [aliasMsg, setAliasMsg] = useState<{ ok: boolean; text: string } | null>(null);
278
+ const [confirming, setConfirming] = useState(false);
232
279
  const run = async (fn: () => Promise<void>) => {
233
280
  setMsg(null);
234
281
  try {
@@ -246,82 +293,123 @@ function AccountRow({
246
293
  if (r.flowId) onFlow(r.flowId);
247
294
  else onChanged();
248
295
  });
296
+ const saveAlias = async () => {
297
+ try {
298
+ await api(`/accounts/${encodeURIComponent(acct.sub)}`, { method: "PATCH", body: JSON.stringify({ alias: alias || null }) });
299
+ setAliasMsg({ ok: true, text: t("aliasSaved", undefined, "Saved") });
300
+ onChanged();
301
+ } catch (err) {
302
+ const code = (err as { code?: string }).code ?? (err as Error).message;
303
+ const text =
304
+ code === "alias_taken"
305
+ ? t("errAliasTaken", undefined, "That alias is already used by another account.")
306
+ : code === "invalid_alias"
307
+ ? t("errInvalidAlias", undefined, "Aliases are 1–40 letters, digits, '.', '_' or '-'.")
308
+ : code;
309
+ setAliasMsg({ ok: false, text });
310
+ }
311
+ };
312
+ const revoke = () =>
313
+ run(async () => {
314
+ const r = await api<{ remoteRevoked: boolean }>(`/accounts/${encodeURIComponent(acct.sub)}`, { method: "DELETE" });
315
+ onRevoked(acct.email, r.remoteRevoked);
316
+ onChanged();
317
+ });
249
318
  return (
250
- <li className="flex flex-wrap items-center gap-2 rounded border border-[var(--border)] p-2" data-testid="gmail-account-row" data-email={acct.email}>
251
- <span className="font-medium text-[13px]" data-testid="gmail-account-email">
252
- {acct.email}
253
- </span>
254
- {acct.status === "ok" ? (
255
- <span className="rounded bg-[var(--success-bg)] px-1 text-[11px]" data-testid="gmail-account-status" data-status="ok">
256
- {t("statusOk", undefined, "ok")}
257
- </span>
258
- ) : (
259
- <span className="rounded bg-[var(--warning-bg)] px-1 text-[11px]" data-testid="gmail-account-status" data-status="reauth_required">
260
- {t("statusReauth", undefined, "re-auth needed")}
319
+ <li
320
+ className="flex flex-col gap-1 rounded border border-[var(--border-primary)] p-2"
321
+ data-testid="gmail-account-row"
322
+ data-email={acct.email}
323
+ >
324
+ <div className="flex flex-wrap items-center gap-2">
325
+ <span className="font-medium text-[13px]" data-testid="gmail-account-email">
326
+ {acct.email}
261
327
  </span>
262
- )}
263
- {acct.testingHint && (
264
- <span className={muted} title={t("testingHint", undefined, "Testing-mode app: Google expires this grant after 7 days.")}>
265
- {t("testingBadge", undefined, "testing: 7-day")}
266
- </span>
267
- )}
268
- <label className={muted}>
269
- {t("level", undefined, "Level")}{" "}
270
- <select
271
- data-testid="gmail-account-level"
272
- value={acct.tier}
273
- onChange={(e) => void setLevel(e.target.value as Tier)}
274
- className="rounded border border-[var(--border)] bg-transparent text-[12px]"
328
+ {acct.status === "ok" ? (
329
+ <span className={badgeOk} data-testid="gmail-account-status" data-status="ok">
330
+ {t("statusOk", undefined, "ok")}
331
+ </span>
332
+ ) : (
333
+ <span className={badgeReauth} data-testid="gmail-account-status" data-status="reauth_required">
334
+ {t("statusReauth", undefined, "re-auth needed")}
335
+ </span>
336
+ )}
337
+ {acct.testingHint && (
338
+ <span className={muted} title={t("testingHint", undefined, "Testing-mode app: Google expires this grant after 7 days.")}>
339
+ {t("testingBadge", undefined, "testing: 7-day")}
340
+ </span>
341
+ )}
342
+ <input
343
+ aria-label={t("aliasLabel", undefined, "Alias")}
344
+ data-testid="gmail-account-alias"
345
+ className={`${field} w-24 px-1`}
346
+ value={alias}
347
+ placeholder={t("aliasPlaceholder", undefined, "alias")}
348
+ onChange={(e) => {
349
+ setAlias(e.target.value);
350
+ setAliasMsg(null);
351
+ }}
352
+ onBlur={() => alias !== (acct.alias ?? "") && void saveAlias()}
353
+ />
354
+ {aliasMsg && (
355
+ <span
356
+ role={aliasMsg.ok ? "status" : "alert"}
357
+ className={aliasMsg.ok ? muted : errorText}
358
+ data-testid="gmail-alias-feedback"
359
+ >
360
+ {aliasMsg.text}
361
+ </span>
362
+ )}
363
+ </div>
364
+ <div className="flex flex-wrap items-center gap-2">
365
+ <label className={muted}>
366
+ {t("level", undefined, "Level")}{" "}
367
+ <select
368
+ data-testid="gmail-account-level"
369
+ value={acct.tier}
370
+ onChange={(e) => void setLevel(e.target.value as Tier)}
371
+ className={field}
372
+ >
373
+ <TierOptions />
374
+ </select>
375
+ </label>
376
+ <button
377
+ type="button"
378
+ className={btn}
379
+ data-testid="gmail-account-reauth"
380
+ onClick={() =>
381
+ void run(async () => {
382
+ // Force a fresh consent at the current level (status reset on persist).
383
+ const r = await api<{ flowId?: string }>(`/accounts/${encodeURIComponent(acct.sub)}/reauth`, { method: "POST" });
384
+ if (r.flowId) onFlow(r.flowId);
385
+ })
386
+ }
275
387
  >
276
- {TIERS.map((tier) => (
277
- <option key={tier} value={tier}>
278
- {TIER_LABEL[tier]}
279
- </option>
280
- ))}
281
- </select>
282
- </label>
283
- <input
284
- aria-label={t("aliasLabel", undefined, "Alias")}
285
- data-testid="gmail-account-alias"
286
- className="w-24 rounded border border-[var(--border)] bg-transparent px-1 text-[12px]"
287
- value={alias}
288
- placeholder={t("aliasPlaceholder", undefined, "alias")}
289
- onChange={(e) => setAlias(e.target.value)}
290
- onBlur={() =>
291
- alias !== (acct.alias ?? "") &&
292
- void run(async () => {
293
- await api(`/accounts/${encodeURIComponent(acct.sub)}`, { method: "PATCH", body: JSON.stringify({ alias: alias || null }) });
294
- onChanged();
295
- })
296
- }
297
- />
298
- <button type="button" className={btn} data-testid="gmail-account-reauth" onClick={() =>
299
- void run(async () => {
300
- // Force a fresh consent at the current level (status reset on persist).
301
- const r = await api<{ flowId?: string }>(`/accounts/${encodeURIComponent(acct.sub)}/reauth`, { method: "POST" });
302
- if (r.flowId) onFlow(r.flowId);
303
- })
304
- }>
305
- {t("reauth", undefined, "Re-authenticate")}
306
- </button>
307
- <button
308
- type="button"
309
- className={btn}
310
- data-testid="gmail-account-revoke"
311
- onClick={() =>
312
- void run(async () => {
313
- const r = await api<{ remoteRevoked: boolean }>(`/accounts/${encodeURIComponent(acct.sub)}`, { method: "DELETE" });
314
- onRevoked(acct.email, r.remoteRevoked);
315
- onChanged();
316
- })
317
- }
318
- >
319
- {t("revoke", undefined, "Revoke")}
320
- </button>
321
- {msg && (
322
- <span role="alert" className="text-[12px] text-[var(--error)]">
323
- {msg}
324
- </span>
388
+ {t("reauth", undefined, "Re-authenticate")}
389
+ </button>
390
+ <button type="button" className={btn} data-testid="gmail-account-revoke" onClick={() => setConfirming(true)}>
391
+ {t("revoke", undefined, "Revoke")}
392
+ </button>
393
+ {msg && (
394
+ <span role="alert" className={errorText}>
395
+ {msg}
396
+ </span>
397
+ )}
398
+ </div>
399
+ {confirming && (
400
+ <ConfirmDialog
401
+ message={t(
402
+ "revokeConfirm",
403
+ { email: acct.email },
404
+ `Revoke ${acct.email}? The dashboard forgets the account and asks Google to revoke its access.`,
405
+ )}
406
+ confirmLabel={t("revoke", undefined, "Revoke")}
407
+ onConfirm={() => {
408
+ setConfirming(false);
409
+ void revoke();
410
+ }}
411
+ onCancel={() => setConfirming(false)}
412
+ />
325
413
  )}
326
414
  </li>
327
415
  );
@@ -330,12 +418,16 @@ function AccountRow({
330
418
  export function GmailSettings() {
331
419
  const t = useT();
332
420
  const OAuthFlow = useUiPrimitive("ui:oauth-flow");
421
+ const newLevelId = useId();
333
422
  const [state, setState] = useState<GmailState | null>(null);
334
423
  const [loadError, setLoadError] = useState<string | null>(null);
335
424
  const [flow, setFlow] = useState<FlowState | null>(null);
336
425
  const [flowError, setFlowError] = useState<string | null>(null);
337
426
  const [lastRevoke, setLastRevoke] = useState<string | null>(null);
338
427
  const [newTier, setNewTier] = useState<Tier>("readonly");
428
+ // Latch (design D1): once the user reports a Google-page code, no late poll
429
+ // result may overwrite it or re-mount the flow view. Reset on a new flow.
430
+ const reportedRef = useRef<string | null>(null);
339
431
 
340
432
  const refresh = useCallback(async () => {
341
433
  try {
@@ -350,6 +442,7 @@ export function GmailSettings() {
350
442
  }, [refresh]);
351
443
 
352
444
  const startFlow = async (flowId: string) => {
445
+ reportedRef.current = null;
353
446
  setFlowError(null);
354
447
  try {
355
448
  setFlow({ phase: "waiting", status: await oauthFlowClient.status(flowId) });
@@ -360,15 +453,29 @@ export function GmailSettings() {
360
453
  };
361
454
  useFlowPoll(
362
455
  flow?.status?.flowId,
363
- (status) => setFlow({ phase: "waiting", status }),
456
+ (status) => {
457
+ if (reportedRef.current) return;
458
+ setFlow({ phase: "waiting", status });
459
+ },
364
460
  (err) => {
461
+ if (reportedRef.current) return;
365
462
  setFlow(null);
366
463
  setFlowError(err);
367
464
  void refresh();
368
465
  },
369
466
  );
370
467
 
468
+ /** Order is load-bearing (design D1): latch, then clear, then cancel. */
469
+ const report = (code: string) => {
470
+ const flowId = flow?.status?.flowId;
471
+ reportedRef.current = code;
472
+ setFlow(null);
473
+ setFlowError(code);
474
+ if (flowId) void oauthFlowClient.cancel(flowId).catch(() => {});
475
+ };
476
+
371
477
  const addAccount = async () => {
478
+ reportedRef.current = null;
372
479
  setFlowError(null);
373
480
  setFlow({ phase: "starting" });
374
481
  try {
@@ -380,17 +487,26 @@ export function GmailSettings() {
380
487
  }
381
488
  };
382
489
 
383
- if (loadError) return <div role="alert" className="text-[12px] text-[var(--error)]">{loadError}</div>;
490
+ if (loadError) return <div role="alert" className={errorText}>{loadError}</div>;
384
491
  if (!state) return <div className={muted}>{t("loading", undefined, "Loading…")}</div>;
385
492
 
386
493
  const step = errorStep(flowError);
494
+ const errKey = errorKey(flowError);
495
+ const { client } = state;
496
+ const summary = !client.configured
497
+ ? t("summaryNotConfigured", undefined, "not configured")
498
+ : client.projectId
499
+ ? t("summaryProject", { projectId: client.projectId }, `✓ project ${client.projectId}`)
500
+ : t("summaryClient", { clientId: client.clientId ?? "" }, `✓ ${client.clientId ?? ""}`);
387
501
  return (
388
502
  <section className="flex flex-col gap-3" data-testid="gmail-settings" aria-labelledby="gmail-settings-title">
389
503
  <h3 id="gmail-settings-title" className="font-semibold text-[14px]">
390
504
  {t("title", undefined, "Gmail")}
391
505
  </h3>
392
- <details open={!state.client.configured || state.accounts.length === 0 || step !== null}>
393
- <summary className="cursor-pointer text-[13px]">{t("setup", undefined, "Google Cloud setup")}</summary>
506
+ <details open={!client.configured || state.accounts.length === 0 || step !== null}>
507
+ <summary className="focus-ring cursor-pointer text-[13px]" data-testid="gmail-setup-summary">
508
+ {t("setup", undefined, "Google Cloud setup")} <span className={muted}>{summary}</span>
509
+ </summary>
394
510
  <SetupWizard state={state} highlight={step} onUploaded={() => void refresh()} />
395
511
  </details>
396
512
 
@@ -400,7 +516,7 @@ export function GmailSettings() {
400
516
  {t(
401
517
  "levelHelp",
402
518
  undefined,
403
- "Levels: readonly = read; draft = + drafts; send = + send, reply, labels, archive, trash. Levels are enforced by this plugin, not by Google: a token carries every scope Google granted (draft-level compose access could technically send), so a level controls what the agent's tools may do. Any session on this dashboard can use every account within its level.",
519
+ "Levels are enforced by this plugin, not by Google: a token carries every scope Google granted (draft-level compose access could technically send), so a level limits what the agent's tools may do. Any session on this dashboard can use every account within its level.",
404
520
  )}
405
521
  </p>
406
522
  {state.accounts.length === 0 && <div className={muted}>{t("noAccounts", undefined, "No accounts connected.")}</div>}
@@ -426,38 +542,83 @@ export function GmailSettings() {
426
542
  ))}
427
543
  </ul>
428
544
  {flow ? (
429
- <OAuthFlow
430
- flow={flow}
431
- onSendInput={(id, value) => oauthFlowClient.input(id, value)}
432
- onCancel={(id) => {
433
- void oauthFlowClient.cancel(id);
434
- }}
435
- />
545
+ <div className="flex flex-col gap-2">
546
+ <p className={muted} data-testid="gmail-consent-hint">
547
+ {t(
548
+ "consentHint",
549
+ undefined,
550
+ "On Google's consent screen tick every permission (Select all). The Gmail permission may start unticked.",
551
+ )}
552
+ </p>
553
+ <OAuthFlow
554
+ flow={flow}
555
+ onSendInput={(id, value) => oauthFlowClient.input(id, value)}
556
+ onCancel={(id) => {
557
+ void oauthFlowClient.cancel(id);
558
+ }}
559
+ />
560
+ {flow.phase === "waiting" && (
561
+ <details data-testid="gmail-google-error">
562
+ <summary className="focus-ring cursor-pointer text-[12px]">
563
+ {t("googleErrorSummary", undefined, "Google showed an error instead of returning here?")}
564
+ </summary>
565
+ <div className={muted}>{t("googleErrorHelp", undefined, "Pick the error code Google displayed:")}</div>
566
+ <div className="flex flex-wrap gap-2">
567
+ {REPORT_CODES.map((code) => (
568
+ <button
569
+ key={code}
570
+ type="button"
571
+ className={btn}
572
+ data-testid={`gmail-report-${code}`}
573
+ onClick={() => report(code)}
574
+ >
575
+ {code === "other" ? t("reportOther", undefined, "Something else") : code}
576
+ </button>
577
+ ))}
578
+ </div>
579
+ </details>
580
+ )}
581
+ </div>
436
582
  ) : (
437
- <div className="flex items-center gap-2">
438
- <select
439
- aria-label={t("newLevel", undefined, "Level for the new account")}
440
- data-testid="gmail-new-level"
441
- value={newTier}
442
- onChange={(e) => setNewTier(e.target.value as Tier)}
443
- className="rounded border border-[var(--border)] bg-transparent text-[12px]"
444
- >
445
- {TIERS.map((tier) => (
446
- <option key={tier} value={tier}>
447
- {TIER_LABEL[tier]}
448
- </option>
449
- ))}
450
- </select>
451
- <button type="button" className={btn} data-testid="gmail-add-account" disabled={!state.client.configured} onClick={() => void addAccount()}>
452
- {t("addAccount", undefined, "Add account")}
453
- </button>
583
+ <div className="flex flex-col gap-1">
584
+ <div className="flex items-center gap-2">
585
+ <label htmlFor={newLevelId} className={muted}>
586
+ {t("newLevel", undefined, "Level for the new account")}
587
+ </label>
588
+ <select
589
+ id={newLevelId}
590
+ data-testid="gmail-new-level"
591
+ value={newTier}
592
+ onChange={(e) => setNewTier(e.target.value as Tier)}
593
+ className={field}
594
+ >
595
+ <TierOptions />
596
+ </select>
597
+ <button
598
+ type="button"
599
+ className={btn}
600
+ data-testid="gmail-add-account"
601
+ disabled={!client.configured}
602
+ onClick={() => void addAccount()}
603
+ >
604
+ {t("addAccount", undefined, "Add account")}
605
+ </button>
606
+ </div>
607
+ <p className={muted} data-testid="gmail-cross-org-hint">
608
+ {t(
609
+ "crossOrgHint",
610
+ undefined,
611
+ "Accounts outside the project's Workspace organization need an External audience, with each account added as a test user (step 3).",
612
+ )}
613
+ </p>
454
614
  </div>
455
615
  )}
456
616
  {flowError && (
457
- <div role="alert" className="text-[12px] text-[var(--error)]" data-testid="gmail-flow-error" data-step={step ?? ""}>
458
- {step
459
- ? t("flowErrorStep", { error: flowError, step }, `Sign-in failed (${flowError}). Fix wizard step ${step}.`)
460
- : t("flowError", { error: flowError }, `Sign-in failed: ${flowError}`)}
617
+ <div role="alert" className={errorText} data-testid="gmail-flow-error" data-step={step ?? ""}>
618
+ {t(errKey, { clientId: client.clientId ?? "" }, ERROR_EN[errKey])}{" "}
619
+ <span className={muted} data-testid="gmail-flow-error-code">
620
+ ({flowError})
621
+ </span>
461
622
  </div>
462
623
  )}
463
624
  {lastRevoke && (
@@ -2,7 +2,10 @@
2
2
  * Setup-wizard data (design D7): console deep links, copyable gcloud commands
3
3
  * and the sign-in-error → wizard-step map. Pure — the server never executes
4
4
  * the commands. See change: add-gmail-plugin.
5
+ * Plus the sign-in error table (`errorKey`, `ERROR_EN`).
6
+ * See change: improve-gmail-settings-ux.
5
7
  */
8
+ import { type FlowCode, knownFlowCode } from "../shared/flow-codes.js";
6
9
 
7
10
  export type WizardStep = 1 | 2 | 3 | 4 | 5 | 6;
8
11
 
@@ -40,7 +43,11 @@ export function gcloudCommands(projectId: string): string[] {
40
43
  return [`gcloud projects create ${id}`, `gcloud services enable gmail.googleapis.com --project ${id}`];
41
44
  }
42
45
 
43
- /** Map a sign-in / upload error code to the wizard step that fixes it. */
46
+ /**
47
+ * Map a sign-in / upload error code to the wizard step that fixes it.
48
+ * `admin_policy_enforced` → null: the fix is in the account's Workspace Admin
49
+ * console, not in a wizard step (improve-gmail-settings-ux D2).
50
+ */
44
51
  export function errorStep(code: string | undefined | null): WizardStep | null {
45
52
  switch (code) {
46
53
  case "access_denied":
@@ -61,3 +68,69 @@ export function errorStep(code: string | undefined | null): WizardStep | null {
61
68
  return null;
62
69
  }
63
70
  }
71
+
72
+ export { KNOWN_FLOW_CODES } from "../shared/flow-codes.js";
73
+
74
+ /** i18n key per flow code (design D2). `cancelled` also matches the host's "Cancelled". */
75
+ const CODE_KEY: Record<FlowCode, string> = {
76
+ org_internal: "errOrgInternal",
77
+ access_denied: "errAccessDenied",
78
+ admin_policy_enforced: "errAdminPolicy",
79
+ redirect_uri_mismatch: "errRedirectMismatch",
80
+ invalid_client: "errInvalidClient",
81
+ scope_missing: "errScopeMissing",
82
+ account_mismatch: "errAccountMismatch",
83
+ missing_refresh: "errMissingRefresh",
84
+ email_unverified: "errEmailUnverified",
85
+ invalid_redirect: "errInvalidRedirect",
86
+ state_mismatch: "errStateMismatch",
87
+ callback_failed: "errCallbackFailed",
88
+ token_exchange_failed: "errTokenExchange",
89
+ id_token_invalid: "errIdToken",
90
+ authorization_failed: "errAuthorization",
91
+ timeout: "errTimeout",
92
+ start_timeout: "errStartTimeout",
93
+ login_failed: "errLoginFailed",
94
+ cancelled: "errCancelled",
95
+ aborted: "errAborted",
96
+ };
97
+
98
+ /**
99
+ * English sentence per error key (the catalogs carry only zh-CN / hu; a dynamic
100
+ * key MUST pass this as its `t()` fallback). `{clientId}` is interpolated.
101
+ */
102
+ export const ERROR_EN: Record<string, string> = {
103
+ errOrgInternal:
104
+ "Google blocked this account: the OAuth app's audience is Internal, which admits only accounts of the project's own Workspace organization. Switch the audience to External and add this account as a test user (step 3).",
105
+ errAccessDenied:
106
+ "Google denied access: the account is not an allowed test user, or the consent was declined. Add the account as a test user (step 3) and try again.",
107
+ errAdminPolicy:
108
+ "This account's Google Workspace admin blocks the app. Ask that admin to trust OAuth client {clientId} (Admin console → Security → API controls → App access control).",
109
+ errRedirectMismatch: "Google rejected the redirect address. Create a Desktop app client, not a Web client (step 4).",
110
+ errInvalidClient: "Google does not recognise the OAuth client. Download its JSON again and upload it (step 5).",
111
+ errScopeMissing:
112
+ "Google did not grant the Gmail permission. Add the account again and tick every permission on Google's consent screen.",
113
+ errAccountMismatch: "You signed in with a different Google account. Re-authenticate with the account shown in the row.",
114
+ errMissingRefresh: "Google returned no long-lived token. Revoke the app at myaccount.google.com/permissions, then add the account again.",
115
+ errEmailUnverified: "Google reports this account's email as unverified. Verify it with Google, then try again.",
116
+ errInvalidRedirect: "The pasted address is not the redirect Google sent. Paste the full URL from the browser's address bar.",
117
+ errStateMismatch: "The pasted redirect belongs to another sign-in. Start again and paste the URL from this sign-in.",
118
+ errCallbackFailed: "The sign-in callback failed. Try again.",
119
+ errTokenExchange: "Google refused to exchange the sign-in code. Check the uploaded client (step 5) and try again.",
120
+ errIdToken: "Google's sign-in answer could not be verified. Try again.",
121
+ errAuthorization: "Google reported a sign-in error. Try again; if it repeats, check the setup steps above.",
122
+ errTimeout: "Sign-in timed out waiting for Google. If Google showed an error page, report it with the option below the sign-in link.",
123
+ errStartTimeout: "The sign-in did not start in time. Try again.",
124
+ errLoginFailed: "The sign-in could not start. Try again.",
125
+ errCancelled: "Sign-in was cancelled.",
126
+ errAborted: "Sign-in was aborted.",
127
+ errGeneric: "Sign-in failed. Try again; if it keeps failing, check the setup steps above.",
128
+ };
129
+
130
+ /** i18n key for a terminal flow error; unknown input → `errGeneric` (exact match only). */
131
+ export function errorKey(code: string | undefined | null): string {
132
+ if (typeof code !== "string") return "errGeneric";
133
+ if (code.toLowerCase() === "cancelled") return "errCancelled";
134
+ const known = knownFlowCode(code);
135
+ return known ? CODE_KEY[known] : "errGeneric";
136
+ }
package/src/i18n.ts CHANGED
@@ -10,24 +10,52 @@ export const catalog = {
10
10
  addAccount: "添加账户",
11
11
  aliasLabel: "别名",
12
12
  aliasPlaceholder: "别名",
13
+ aliasSaved: "已保存",
14
+ audienceErrors:
15
+ "Google 错误页面:org_internal = 账户不属于该组织,请改为“外部”;access_denied = 将账户添加为测试用户;admin_policy_enforced = 该账户的 Workspace 管理员必须信任此 OAuth 客户端。",
13
16
  audienceHelp:
14
- "Workspace 组织:选择“内部”。否则选择“外部”,并将要连接的每个 Gmail 地址添加为测试用户。测试模式下令牌 7 天后过期;“发布应用”可获得更长期的令牌,但会显示未验证应用警告。",
17
+ "“内部”仅允许项目所属 Workspace 组织的账户:只有当你要连接的每个账户都属于该组织时才选择它。否则选择“外部”,并将要连接的每个地址添加为测试用户。测试模式下令牌 7 天后过期;“发布应用”可获得更长期的令牌,但会显示未验证应用警告。",
15
18
  clientHelp: "应用类型:桌面应用。下载 JSON。若链接已变更:API 和服务 → 凭据。",
19
+ consentHint: "在 Google 同意屏幕上勾选每一项权限(全选)。Gmail 权限可能默认未勾选。",
16
20
  copy: "复制",
17
21
  createProject: "创建项目",
22
+ crossOrgHint: "项目 Workspace 组织之外的账户需要“外部”目标对象,并将每个账户添加为测试用户(第 3 步)。",
18
23
  enableGmail: "启用 Gmail API",
24
+ errAborted: "登录已中止。",
25
+ errAccessDenied: "Google 拒绝了访问:该账户不是允许的测试用户,或拒绝了同意。请将账户添加为测试用户(第 3 步)后重试。",
26
+ errAccountMismatch: "你登录了另一个 Google 账户。请使用该行显示的账户重新验证。",
27
+ errAdminPolicy: "此账户的 Google Workspace 管理员阻止了该应用。请让该管理员信任 OAuth 客户端 {clientId}(管理控制台 → 安全 → API 控制 → 应用访问控制)。",
28
+ errAliasTaken: "该别名已被其他账户使用。",
29
+ errAuthorization: "Google 报告了登录错误。请重试;若反复出现,请检查上面的设置步骤。",
19
30
  errBadClientId: "客户端 ID 不以 .apps.googleusercontent.com 结尾(第 4 步)。",
31
+ errCallbackFailed: "登录回调失败。请重试。",
32
+ errCancelled: "登录已取消。",
20
33
  errClientInUse: "当前客户端下已连接账户。请先撤销它们,再上传其他客户端。",
34
+ errEmailUnverified: "Google 报告此账户的电子邮件未验证。请在 Google 完成验证后重试。",
35
+ errGeneric: "登录失败。请重试;若一直失败,请检查上面的设置步骤。",
36
+ errIdToken: "无法验证 Google 的登录响应。请重试。",
37
+ errInvalidAlias: "别名为 1–40 个字母、数字、“.”、“_”或“-”。",
38
+ errInvalidClient: "Google 无法识别该 OAuth 客户端。请重新下载其 JSON 并上传(第 5 步)。",
39
+ errInvalidRedirect: "粘贴的地址不是 Google 发送的重定向。请粘贴浏览器地址栏中的完整 URL。",
40
+ errLoginFailed: "无法开始登录。请重试。",
41
+ errMissingRefresh: "Google 未返回长期令牌。请在 myaccount.google.com/permissions 撤销该应用,然后重新添加账户。",
21
42
  errMissingSecret: "文件中没有客户端密钥。请从客户端页面重新下载(第 5 步)。",
22
43
  errNotInstalled: "此文件中没有桌面(installed)客户端。请创建桌面应用客户端(第 4 步)。",
23
44
  errNotJson: "该文件不是有效的 JSON。请上传你下载的 client_secret_*.json(第 5 步)。",
45
+ errOrgInternal: "Google 阻止了此账户:OAuth 应用的目标对象为“内部”,仅允许项目所属 Workspace 组织的账户。请将目标对象改为“外部”,并将此账户添加为测试用户(第 3 步)。",
46
+ errRedirectMismatch: "Google 拒绝了重定向地址。请创建桌面应用客户端,而不是 Web 客户端(第 4 步)。",
47
+ errScopeMissing: "Google 未授予 Gmail 权限。请重新添加账户,并在 Google 同意屏幕上勾选每一项权限。",
48
+ errStartTimeout: "登录未能及时开始。请重试。",
49
+ errStateMismatch: "粘贴的重定向属于另一次登录。请重新开始,并粘贴本次登录的 URL。",
50
+ errTimeout: "等待 Google 超时。如果 Google 显示了错误页面,请通过登录链接下方的选项报告。",
51
+ errTokenExchange: "Google 拒绝交换登录代码。请检查上传的客户端(第 5 步)后重试。",
24
52
  errWebClient: "这是 Web 应用客户端。请改为创建桌面应用客户端(第 4 步)。",
25
53
  fallback2: "若链接已变更:API 和服务 → OAuth 同意屏幕。",
26
- flowError: "登录失败:{error}",
27
- flowErrorStep: "登录失败({error})。请修正向导第 {step} 步。",
54
+ googleErrorHelp: "选择 Google 显示的错误代码:",
55
+ googleErrorSummary: "Google 显示了错误而没有返回这里?",
28
56
  level: "级别",
29
57
  levelHelp:
30
- "级别:readonly = 读取;draft = + 草稿;send = + 发送、回复、标签、归档、删除。级别由本插件执行,而非 Google:令牌带有 Google 授予的全部范围(draft 级的撰写权限理论上也能发送),因此级别控制的是代理工具可以做什么。此仪表盘上的任何会话都可以在级别范围内使用每个账户。",
58
+ "级别由本插件执行,而非 Google:令牌带有 Google 授予的全部范围(draft 级的撰写权限理论上也能发送),因此级别限制的是代理工具可以做什么。此仪表盘上的任何会话都可以在级别范围内使用每个账户。",
31
59
  loading: "加载中…",
32
60
  newLevel: "新账户的级别",
33
61
  noAccounts: "尚未连接账户。",
@@ -36,7 +64,9 @@ export const catalog = {
36
64
  openClients: "创建客户端",
37
65
  projectId: "项目 ID",
38
66
  reauth: "重新验证",
67
+ reportOther: "其他错误",
39
68
  revoke: "撤销",
69
+ revokeConfirm: "撤销 {email}?仪表盘将忘记该账户,并请求 Google 撤销其访问权限。",
40
70
  revokedOk: "{email} 已移除,并已在 Google 撤销访问权限。",
41
71
  revokeManual: "{email} 已在本地移除,但无法连接 Google。请在 myaccount.google.com/permissions 撤销访问权限。",
42
72
  setup: "Google Cloud 设置",
@@ -49,8 +79,14 @@ export const catalog = {
49
79
  step5: "5. 上传 client_secret_*.json",
50
80
  step6: "6. 测试登录",
51
81
  step6Help: "在下方添加第一个账户 —— 这就是测试登录。",
82
+ summaryClient: "✓ {clientId}",
83
+ summaryNotConfigured: "未配置",
84
+ summaryProject: "✓ 项目 {projectId}",
52
85
  testingBadge: "测试:7 天",
53
86
  testingHint: "测试模式应用:Google 会在 7 天后使此授权过期。",
87
+ tierDraft: "读取 + 创建草稿",
88
+ tierReadonly: "读取邮件",
89
+ tierSend: "读取、草稿、发送、回复、标签、归档、删除",
54
90
  title: "Gmail",
55
91
  uploadLabel: "上传 OAuth 客户端 JSON",
56
92
  withGcloud: "使用 gcloud(请自行运行):",
@@ -61,24 +97,69 @@ export const catalog = {
61
97
  addAccount: "Fiók hozzáadása",
62
98
  aliasLabel: "Álnév",
63
99
  aliasPlaceholder: "álnév",
100
+ aliasSaved: "Mentve",
101
+ audienceErrors:
102
+ "Google hibaoldalak: org_internal = a fiók a szervezeten kívül van, válts Külsőre; access_denied = vedd fel a fiókot tesztfelhasználóként; admin_policy_enforced = a fiók Workspace-adminisztrátorának meg kell bíznia ebben az OAuth-ügyfélben.",
64
103
  audienceHelp:
65
- "Workspace-szervezet: válaszd a Belső lehetőséget. Egyébként Külső, és vedd fel tesztfelhasználóként minden csatlakoztatandó Gmail-címet. Tesztelés módban a tokenek 7 nap után lejárnak; az „Alkalmazás közzététele” hosszabb életű tokeneket ad, nem ellenőrzött alkalmazás figyelmeztetéssel.",
66
- clientHelp: "Alkalmazástípus: Asztali alkalmazás. Töltsd le a JSON-t. Ha a link elköltözött: API-k és szolgáltatások → Hitelesítő adatok.",
104
+ "A Belső csak a projekt saját Workspace-szervezetének fiókjait engedi be: csak akkor válaszd, ha minden csatlakoztatandó fiók ehhez a szervezethez tartozik. Egyébként válaszd a Külsőt, és vedd fel tesztfelhasználóként minden csatlakoztatandó címet. Tesztelés módban a tokenek 7 nap után lejárnak; az „Alkalmazás közzététele” hosszabb életű tokeneket ad, nem ellenőrzött alkalmazás figyelmeztetéssel.",
105
+ clientHelp:
106
+ "Alkalmazástípus: Asztali alkalmazás. Töltsd le a JSON-t. Ha a link elköltözött: API-k és szolgáltatások → Hitelesítő adatok.",
107
+ consentHint:
108
+ "A Google hozzájárulási képernyőjén pipálj be minden engedélyt (Összes kijelölése). A Gmail-engedély kezdetben kipipálatlan lehet.",
67
109
  copy: "Másolás",
68
110
  createProject: "Projekt létrehozása",
111
+ crossOrgHint:
112
+ "A projekt Workspace-szervezetén kívüli fiókokhoz Külső célközönség kell, minden fiókot tesztfelhasználóként felvéve (3. lépés).",
69
113
  enableGmail: "Gmail API engedélyezése",
114
+ errAborted: "A bejelentkezés megszakadt.",
115
+ errAccessDenied:
116
+ "A Google megtagadta a hozzáférést: a fiók nem engedélyezett tesztfelhasználó, vagy elutasították a hozzájárulást. Vedd fel a fiókot tesztfelhasználóként (3. lépés), és próbáld újra.",
117
+ errAccountMismatch: "Másik Google-fiókkal jelentkeztél be. Hitelesíts újra a sorban látható fiókkal.",
118
+ errAdminPolicy:
119
+ "A fiók Google Workspace-adminisztrátora letiltja az alkalmazást. Kérd meg, hogy bízzon meg a(z) {clientId} OAuth-ügyfélben (Felügyeleti konzol → Biztonság → API-vezérlők → Alkalmazás-hozzáférés).",
120
+ errAliasTaken: "Ezt az álnevet már egy másik fiók használja.",
121
+ errAuthorization:
122
+ "A Google bejelentkezési hibát jelzett. Próbáld újra; ha ismétlődik, ellenőrizd a fenti beállítási lépéseket.",
70
123
  errBadClientId: "Az ügyfél-azonosító nem .apps.googleusercontent.com végződésű (4. lépés).",
71
- errClientInUse: "A jelenlegi ügyféllel fiókok vannak csatlakoztatva. Előbb vond vissza őket, majd tölts fel másik ügyfelet.",
124
+ errCallbackFailed: "A bejelentkezési visszahívás sikertelen. Próbáld újra.",
125
+ errCancelled: "A bejelentkezés megszakítva.",
126
+ errClientInUse:
127
+ "A jelenlegi ügyféllel fiókok vannak csatlakoztatva. Előbb vond vissza őket, majd tölts fel másik ügyfelet.",
128
+ errEmailUnverified:
129
+ "A Google szerint a fiók e-mail-címe nincs ellenőrizve. Ellenőrizd a Google-nál, majd próbáld újra.",
130
+ errGeneric:
131
+ "A bejelentkezés sikertelen. Próbáld újra; ha továbbra is hibázik, ellenőrizd a fenti beállítási lépéseket.",
132
+ errIdToken: "A Google bejelentkezési válasza nem ellenőrizhető. Próbáld újra.",
133
+ errInvalidAlias: "Az álnév 1–40 betű, számjegy, '.', '_' vagy '-'.",
134
+ errInvalidClient: "A Google nem ismeri fel az OAuth-ügyfelet. Töltsd le újra a JSON-t, és töltsd fel (5. lépés).",
135
+ errInvalidRedirect:
136
+ "A beillesztett cím nem a Google által küldött átirányítás. Illeszd be a böngésző címsorából a teljes URL-t.",
137
+ errLoginFailed: "A bejelentkezés nem indult el. Próbáld újra.",
138
+ errMissingRefresh:
139
+ "A Google nem adott hosszú életű tokent. Vond vissza az alkalmazást a myaccount.google.com/permissions oldalon, majd add hozzá újra a fiókot.",
72
140
  errMissingSecret: "A fájlban nincs ügyféltitok. Töltsd le újra az ügyfél oldaláról (5. lépés).",
73
141
  errNotInstalled: "A fájlban nincs asztali (installed) ügyfél. Hozz létre asztali alkalmazás ügyfelet (4. lépés).",
74
142
  errNotJson: "A fájl nem érvényes JSON. Töltsd fel a letöltött client_secret_*.json fájlt (5. lépés).",
143
+ errOrgInternal:
144
+ "A Google letiltotta ezt a fiókot: az OAuth-alkalmazás célközönsége Belső, amely csak a projekt saját Workspace-szervezetének fiókjait engedi be. Állítsd a célközönséget Külsőre, és vedd fel ezt a fiókot tesztfelhasználóként (3. lépés).",
145
+ errRedirectMismatch:
146
+ "A Google elutasította az átirányítási címet. Asztali alkalmazás ügyfelet hozz létre, ne webes ügyfelet (4. lépés).",
147
+ errScopeMissing:
148
+ "A Google nem adta meg a Gmail-engedélyt. Add hozzá újra a fiókot, és a Google hozzájárulási képernyőjén pipálj be minden engedélyt.",
149
+ errStartTimeout: "A bejelentkezés nem indult el időben. Próbáld újra.",
150
+ errStateMismatch:
151
+ "A beillesztett átirányítás egy másik bejelentkezéshez tartozik. Kezdd újra, és ennek a bejelentkezésnek az URL-jét illeszd be.",
152
+ errTimeout:
153
+ "Lejárt a várakozás a Google-ra. Ha a Google hibaoldalt mutatott, jelentsd a bejelentkezési link alatti lehetőséggel.",
154
+ errTokenExchange:
155
+ "A Google nem váltotta be a bejelentkezési kódot. Ellenőrizd a feltöltött ügyfelet (5. lépés), és próbáld újra.",
75
156
  errWebClient: "Ez webalkalmazás-ügyfél. Hozz létre helyette asztali alkalmazás ügyfelet (4. lépés).",
76
157
  fallback2: "Ha a link elköltözött: API-k és szolgáltatások → OAuth-hozzájárulási képernyő.",
77
- flowError: "A bejelentkezés sikertelen: {error}",
78
- flowErrorStep: "A bejelentkezés sikertelen ({error}). Javítsd a varázsló {step}. lépését.",
158
+ googleErrorHelp: "Válaszd ki a Google által mutatott hibakódot:",
159
+ googleErrorSummary: "A Google hibát mutatott, ahelyett hogy visszairányított volna?",
79
160
  level: "Szint",
80
161
  levelHelp:
81
- "Szintek: readonly = olvasás; draft = + piszkozatok; send = + küldés, válasz, címkék, archiválás, kuka. A szinteket ez a bővítmény érvényesíti, nem a Google: a token a Google által megadott összes hatókört hordozza (a draft szintű írási jog technikailag küldhetne is), így a szint azt szabályozza, mit tehetnek az ügynök eszközei. A dashboard bármely munkamenete használhat minden fiókot a saját szintjén belül.",
162
+ "A szinteket ez a bővítmény érvényesíti, nem a Google: a token a Google által megadott összes hatókört hordozza (a draft szintű írási jog technikailag küldhetne is), így a szint azt korlátozza, mit tehetnek az ügynök eszközei. A dashboard bármely munkamenete használhat minden fiókot a saját szintjén belül.",
82
163
  loading: "Betöltés…",
83
164
  newLevel: "Az új fiók szintje",
84
165
  noAccounts: "Nincs csatlakoztatott fiók.",
@@ -87,7 +168,10 @@ export const catalog = {
87
168
  openClients: "Ügyfél létrehozása",
88
169
  projectId: "Projektazonosító",
89
170
  reauth: "Újrahitelesítés",
171
+ reportOther: "Valami más",
90
172
  revoke: "Visszavonás",
173
+ revokeConfirm:
174
+ "Visszavonod: {email}? A dashboard elfelejti a fiókot, és kéri a Google-t a hozzáférés visszavonására.",
91
175
  revokedOk: "{email} eltávolítva, a hozzáférés a Google-nál visszavonva.",
92
176
  revokeManual:
93
177
  "{email} helyben eltávolítva, de a Google nem volt elérhető. Vond vissza a hozzáférést a myaccount.google.com/permissions oldalon.",
@@ -101,8 +185,14 @@ export const catalog = {
101
185
  step5: "5. client_secret_*.json feltöltése",
102
186
  step6: "6. Próba-bejelentkezés",
103
187
  step6Help: "Add hozzá lent az első fiókot — ez a próba-bejelentkezés.",
188
+ summaryClient: "✓ {clientId}",
189
+ summaryNotConfigured: "nincs beállítva",
190
+ summaryProject: "✓ projekt: {projectId}",
104
191
  testingBadge: "teszt: 7 nap",
105
192
  testingHint: "Tesztelés módú alkalmazás: a Google 7 nap után lejártatja ezt a hozzáférést.",
193
+ tierDraft: "olvasás + piszkozatok",
194
+ tierReadonly: "levelek olvasása",
195
+ tierSend: "olvasás, piszkozat, küldés, válasz, címkék, archiválás, kuka",
106
196
  title: "Gmail",
107
197
  uploadLabel: "OAuth-ügyfél JSON feltöltése",
108
198
  withGcloud: "gcloud-dal (futtasd magad):",
@@ -4,6 +4,8 @@
4
4
  * with `@fastify/rate-limit` (loopback allow-listed). Tiers: `operate`
5
5
  * (`packages/shared/src/route-tiers.ts`). Responses NEVER carry tokens or the
6
6
  * client secret. See change: add-gmail-plugin.
7
+ * A failed sign-in logs ONE `[gmail] sign-in failed: <code>` warn, code from
8
+ * `KNOWN_FLOW_CODES` or `sign_in_failed`. See change: improve-gmail-settings-ux.
7
9
  */
8
10
 
9
11
  import type {
@@ -14,6 +16,7 @@ import rateLimit from "@fastify/rate-limit";
14
16
  import type { FastifyInstance, FastifyReply } from "fastify";
15
17
  import { validateClientJson } from "../shared/client-json.js";
16
18
  import type { GoogleEndpoints } from "../shared/endpoints.js";
19
+ import { knownFlowCode } from "../shared/flow-codes.js";
17
20
  import { isTier, scopesCoverTier, type Tier } from "../shared/scopes.js";
18
21
  import { AccountError, type AccountStore, summarize } from "./accounts.js";
19
22
  import { revokeToken } from "./gmail-rest.js";
@@ -65,7 +68,16 @@ export async function mountGmailRoutes(fastify: FastifyInstance, deps: GmailRout
65
68
  if (!deps.oauth) return reply.code(501).send({ error: "oauth_unavailable" });
66
69
  const client = await store.getClient();
67
70
  if (!client) return reply.code(409).send({ error: "no_client" });
68
- const loginFlow = createGoogleLoginFlow({
71
+ // One failure, one warn line: a login throwing before its first event also
72
+ // rejects startFlow (login_failed), so whichever site logs first wins.
73
+ // The line carries an allow-listed code only (improve-gmail-settings-ux D3).
74
+ let logged = false;
75
+ const logFailure = (err: unknown) => {
76
+ if (logged) return;
77
+ logged = true;
78
+ logger.warn(`[gmail] sign-in failed: ${knownFlowCode((err as { code?: unknown } | null)?.code) ?? "sign_in_failed"}`);
79
+ };
80
+ const googleFlow = createGoogleLoginFlow({
69
81
  client,
70
82
  endpoints,
71
83
  tier,
@@ -73,29 +85,46 @@ export async function mountGmailRoutes(fastify: FastifyInstance, deps: GmailRout
73
85
  fetchImpl: deps.fetchImpl,
74
86
  createCallback: deps.createCallback,
75
87
  });
88
+ const loginFlow = {
89
+ ...googleFlow,
90
+ login: async (ix: Parameters<typeof googleFlow.login>[0]) => {
91
+ try {
92
+ return await googleFlow.login(ix);
93
+ } catch (err) {
94
+ logFailure(err);
95
+ throw err;
96
+ }
97
+ },
98
+ };
76
99
  try {
77
100
  return await deps.oauth.startFlow({
78
101
  key: expect ? `reauth-${expect.sub}` : `add-${newId()}`,
79
102
  loginFlow,
80
103
  persist: async (credential) => {
81
- const c = credential as GoogleSignInResult;
82
- if (expect && c.sub !== expect.sub) throw new GmailFlowError("account_mismatch");
83
- // Consent-screen checkboxes can be cleared: never store a level the grant cannot serve.
84
- if (!scopesCoverTier(c.grantedScopes, c.tier)) throw new GmailFlowError("scope_missing");
85
- const acct = await store.upsertFromSignIn({
86
- sub: c.sub,
87
- email: c.email,
88
- tier: c.tier,
89
- scopes: c.grantedScopes,
90
- access: c.access,
91
- refresh: c.refresh || undefined,
92
- expires: c.expires,
93
- testingHint: c.testingHint,
94
- });
95
- logger.info(`[gmail] sign-in ${acct.email} tier=${acct.tier}: ok`);
104
+ try {
105
+ const c = credential as GoogleSignInResult;
106
+ if (expect && c.sub !== expect.sub) throw new GmailFlowError("account_mismatch");
107
+ // Consent-screen checkboxes can be cleared: never store a level the grant cannot serve.
108
+ if (!scopesCoverTier(c.grantedScopes, c.tier)) throw new GmailFlowError("scope_missing");
109
+ const acct = await store.upsertFromSignIn({
110
+ sub: c.sub,
111
+ email: c.email,
112
+ tier: c.tier,
113
+ scopes: c.grantedScopes,
114
+ access: c.access,
115
+ refresh: c.refresh || undefined,
116
+ expires: c.expires,
117
+ testingHint: c.testingHint,
118
+ });
119
+ logger.info(`[gmail] sign-in ${acct.email} tier=${acct.tier}: ok`);
120
+ } catch (err) {
121
+ logFailure(err);
122
+ throw err;
123
+ }
96
124
  },
97
125
  });
98
126
  } catch (err) {
127
+ logFailure(err);
99
128
  return sendError(reply, err);
100
129
  }
101
130
  }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Closed set of fixed, input-free codes a Gmail sign-in flow can terminate
3
+ * with (design D2/D3). Shared by the server failure log (allow-list) and the
4
+ * client error table. See change: improve-gmail-settings-ux.
5
+ */
6
+ export const KNOWN_FLOW_CODES = [
7
+ "org_internal",
8
+ "access_denied",
9
+ "admin_policy_enforced",
10
+ "redirect_uri_mismatch",
11
+ "invalid_client",
12
+ "scope_missing",
13
+ "account_mismatch",
14
+ "missing_refresh",
15
+ "email_unverified",
16
+ "invalid_redirect",
17
+ "state_mismatch",
18
+ "callback_failed",
19
+ "token_exchange_failed",
20
+ "id_token_invalid",
21
+ "authorization_failed",
22
+ "timeout",
23
+ "start_timeout",
24
+ "login_failed",
25
+ "cancelled",
26
+ "aborted",
27
+ ] as const;
28
+
29
+ export type FlowCode = (typeof KNOWN_FLOW_CODES)[number];
30
+
31
+ const KNOWN = new Set<string>(KNOWN_FLOW_CODES);
32
+
33
+ /** `code` when it is a string in {@link KNOWN_FLOW_CODES}, else `null` (exact match). */
34
+ export function knownFlowCode(code: unknown): FlowCode | null {
35
+ return typeof code === "string" && KNOWN.has(code) ? (code as FlowCode) : null;
36
+ }