@blackbelt-technology/pi-dashboard-gmail-plugin 0.10.0 → 0.11.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/package.json +9 -4
- package/src/bridge/gmail-api.ts +23 -0
- package/src/bridge/tools.ts +217 -9
- package/src/client/AutoSetup.tsx +787 -0
- package/src/client/GmailSettings.tsx +467 -66
- package/src/client/auto-setup.ts +124 -0
- package/src/client/ui.ts +24 -0
- package/src/client/wizard.ts +80 -20
- package/src/configSchema.json +14 -1
- package/src/i18n.ts +420 -6
- package/src/server/accounts.ts +24 -0
- package/src/server/google-oauth.ts +6 -1
- package/src/server/index.ts +7 -0
- package/src/server/lease.ts +5 -1
- package/src/server/routes.ts +132 -25
- package/src/server/setup/browser-service.ts +55 -0
- package/src/server/setup/capture.ts +96 -0
- package/src/server/setup/cdp-page.ts +308 -0
- package/src/server/setup/errors.ts +36 -0
- package/src/server/setup/local.ts +27 -0
- package/src/server/setup/mask.ts +11 -0
- package/src/server/setup/run.ts +723 -0
- package/src/server/setup/setup-routes.ts +123 -0
- package/src/server/setup/steps.ts +458 -0
- package/src/server/store-client.ts +30 -0
- package/src/shared/auto-setup.ts +132 -0
- package/src/shared/client-json.ts +3 -1
- package/src/shared/protocol.ts +2 -0
- package/src/shared/scopes.ts +20 -4
- package/src/shared/setup.ts +43 -0
|
@@ -23,50 +23,59 @@ import {
|
|
|
23
23
|
copyText,
|
|
24
24
|
FieldShell,
|
|
25
25
|
oauthFlowClient,
|
|
26
|
+
SafeLink,
|
|
26
27
|
SelectField,
|
|
27
28
|
SettingsGroup,
|
|
28
29
|
SettingsNotice,
|
|
29
30
|
TextField,
|
|
31
|
+
ToggleField,
|
|
30
32
|
useT,
|
|
31
33
|
useUiPrimitive,
|
|
32
34
|
} from "@blackbelt-technology/dashboard-plugin-runtime";
|
|
33
35
|
import type React from "react";
|
|
34
36
|
import { useCallback, useEffect, useId, useRef, useState } from "react";
|
|
37
|
+
import type { Audience, AutoSetupState, SetupRunView } from "../shared/auto-setup.js";
|
|
35
38
|
import { validateClientJson } from "../shared/client-json.js";
|
|
36
39
|
import type { AccountInfo } from "../shared/protocol.js";
|
|
37
40
|
import { TIERS, type Tier } from "../shared/scopes.js";
|
|
38
|
-
import {
|
|
39
|
-
|
|
40
|
-
|
|
41
|
+
import { classifyProjectId, isEmail, normalizeEmail, normalizeProjectId } from "../shared/setup.js";
|
|
42
|
+
import { AutoSetupSection } from "./AutoSetup.js";
|
|
43
|
+
import { showUnverifiedNotice } from "./auto-setup.js";
|
|
44
|
+
import { api, btn, errorText, muted } from "./ui.js";
|
|
45
|
+
import {
|
|
46
|
+
AUDIENCE_HELP_EN,
|
|
47
|
+
CONSENT_HINT_EN,
|
|
48
|
+
consoleLinks,
|
|
49
|
+
ERROR_EN,
|
|
50
|
+
errorKey,
|
|
51
|
+
errorStep,
|
|
52
|
+
gcloudCommands,
|
|
53
|
+
UNVERIFIED_HINT_EN,
|
|
54
|
+
type WizardStep,
|
|
55
|
+
} from "./wizard.js";
|
|
41
56
|
|
|
42
57
|
interface GmailState {
|
|
43
58
|
client: { configured: boolean; clientId?: string; projectId?: string };
|
|
44
59
|
accounts: AccountInfo[];
|
|
60
|
+
/** Saved setup fields (`plugins.gmail`); absent from older servers. */
|
|
61
|
+
setup?: { projectId?: string; ownerAccount?: string };
|
|
62
|
+
/** Automatic-setup availability; absent from older servers. See change: add-gmail-auto-setup. */
|
|
63
|
+
autoSetup?: AutoSetupState;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface SavedSetup {
|
|
67
|
+
projectId: string;
|
|
68
|
+
ownerAccount: string;
|
|
45
69
|
}
|
|
46
70
|
|
|
47
71
|
type FlowState = React.ComponentProps<ReturnType<typeof useUiPrimitive<"ui:oauth-flow">>>["flow"];
|
|
48
72
|
type FlowStatus = NonNullable<FlowState["status"]>;
|
|
49
73
|
|
|
50
|
-
async function api<T>(path: string, init?: RequestInit): Promise<T> {
|
|
51
|
-
const res = await fetch(`${API}${path}`, {
|
|
52
|
-
...init,
|
|
53
|
-
headers: init?.body ? { "content-type": "application/json" } : undefined,
|
|
54
|
-
});
|
|
55
|
-
const body = (await res.json().catch(() => ({}))) as T & { error?: string };
|
|
56
|
-
if (!res.ok) throw Object.assign(new Error(body.error ?? `HTTP ${res.status}`), { code: body.error });
|
|
57
|
-
return body;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// Secondary button recipe (`ui-contract.md`); `tap-target` = 44 px touch, 32 px from sm.
|
|
61
|
-
const btn =
|
|
62
|
-
"focus-ring tap-target rounded-md border border-[var(--border-secondary)] bg-[var(--bg-tertiary)] px-2.5 text-xs font-semibold text-[var(--text-primary)] hover:bg-[var(--bg-hover)] disabled:opacity-50";
|
|
63
74
|
// The section's one primary action (white on the theme-invariant `--accent-solid`).
|
|
64
75
|
const primaryBtn =
|
|
65
76
|
"focus-ring tap-target rounded-md bg-[var(--accent-solid)] px-3 text-xs font-semibold text-white disabled:bg-[var(--bg-tertiary)] disabled:text-[var(--text-secondary)]";
|
|
66
77
|
const field =
|
|
67
78
|
"focus-ring rounded border border-[var(--border-secondary)] bg-[var(--bg-tertiary)] px-2 py-1 text-xs text-[var(--text-primary)]";
|
|
68
|
-
const muted = "text-xs text-[var(--text-secondary)]";
|
|
69
|
-
const errorText = "text-xs text-[var(--severity-error-fg)]";
|
|
70
79
|
// Static strings: Tailwind cannot see interpolated class names.
|
|
71
80
|
const pillBase = "inline-flex items-center rounded-full border px-1.5 py-px text-[11px] font-semibold";
|
|
72
81
|
const badgeOk = `${pillBase} border-[var(--severity-success-border)] bg-[var(--severity-success-bg)] text-[var(--severity-success-fg)]`;
|
|
@@ -125,11 +134,22 @@ function Copyable({ value }: { value: string }) {
|
|
|
125
134
|
);
|
|
126
135
|
}
|
|
127
136
|
|
|
137
|
+
/** A project-scoped link, or the "valid project id needed" statement while the id is empty or invalid. */
|
|
138
|
+
function ProjectLink({ href, label, step }: { href: string | null; label: string; step: WizardStep }) {
|
|
139
|
+
const t = useT();
|
|
140
|
+
if (href) return <StepLink href={href} label={label} />;
|
|
141
|
+
return (
|
|
142
|
+
<div className={muted} data-testid={`gmail-need-project-id-step-${step}`}>
|
|
143
|
+
{t("needValidProjectId", undefined, "A valid project id is needed before the project links and commands appear.")}
|
|
144
|
+
</div>
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
|
|
128
148
|
function StepLink({ href, label }: { href: string; label: string }) {
|
|
129
149
|
return (
|
|
130
|
-
<
|
|
150
|
+
<SafeLink href={href} target="_blank" rel="noopener noreferrer" className="focus-ring text-xs text-[var(--accent-text)] underline">
|
|
131
151
|
{label}
|
|
132
|
-
</
|
|
152
|
+
</SafeLink>
|
|
133
153
|
);
|
|
134
154
|
}
|
|
135
155
|
|
|
@@ -176,6 +196,150 @@ function WizardStepItem({
|
|
|
176
196
|
);
|
|
177
197
|
}
|
|
178
198
|
|
|
199
|
+
type Translate = ReturnType<typeof useT>;
|
|
200
|
+
|
|
201
|
+
function currentWizardStep(state: GmailState, focus: WizardStep | null): WizardStep | null {
|
|
202
|
+
return focus ?? (!state.client.configured ? 1 : state.accounts.length === 0 ? 6 : null);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function isStepDone(state: GmailState, current: WizardStep | null, n: WizardStep): boolean {
|
|
206
|
+
return n !== current && (state.client.configured ? n <= 5 || state.accounts.length > 0 : current !== null && n < current);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Flush a valid, unsaved typed project id; resolves false when the save failed. */
|
|
210
|
+
async function flushTypedProjectId(
|
|
211
|
+
projectId: string,
|
|
212
|
+
savedId: string,
|
|
213
|
+
saveSetup: (partial: Partial<SavedSetup>) => Promise<void>,
|
|
214
|
+
): Promise<boolean> {
|
|
215
|
+
if (classifyProjectId(projectId) !== "ok" || normalizeProjectId(projectId) === savedId) return true;
|
|
216
|
+
try {
|
|
217
|
+
await saveSetup({ projectId: normalizeProjectId(projectId) });
|
|
218
|
+
return true;
|
|
219
|
+
} catch {
|
|
220
|
+
return false;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function uploadMessages(t: Translate): Record<string, string> {
|
|
225
|
+
return {
|
|
226
|
+
not_json: t("errNotJson", undefined, "That file is not valid JSON. Upload the client_secret_*.json you downloaded (step 5)."),
|
|
227
|
+
web_client: t("errWebClient", undefined, "This is a Web application client. Create a Desktop app client instead (step 4)."),
|
|
228
|
+
not_installed: t("errNotInstalled", undefined, "No Desktop (`installed`) client in this file. Create a Desktop app client (step 4)."),
|
|
229
|
+
bad_client_id: t("errBadClientId", undefined, "The client id does not end in .apps.googleusercontent.com (step 4)."),
|
|
230
|
+
client_in_use: t(
|
|
231
|
+
"errClientInUse",
|
|
232
|
+
undefined,
|
|
233
|
+
"Accounts are connected with the current client. Revoke them first, then upload a different client.",
|
|
234
|
+
),
|
|
235
|
+
missing_secret: t("errMissingSecret", undefined, "The file has no client secret. Download it again from the client page (step 5)."),
|
|
236
|
+
setup_save_failed: t("errSetupSave", undefined, "The project id could not be saved, so the upload was not sent. Try again (step 1)."),
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function projectErrorText(t: Translate, projectErr: "looks_like_name" | "invalid" | null): string | null {
|
|
241
|
+
return (
|
|
242
|
+
projectErr === "looks_like_name"
|
|
243
|
+
? t(
|
|
244
|
+
"errProjectLooksLikeName",
|
|
245
|
+
undefined,
|
|
246
|
+
"That looks like the project name. The wizard needs the project id (lower-case, for example pidashboard-510015): open the project list and copy the ID column.",
|
|
247
|
+
)
|
|
248
|
+
: projectErr === "invalid"
|
|
249
|
+
? t(
|
|
250
|
+
"errProjectInvalid",
|
|
251
|
+
undefined,
|
|
252
|
+
"A project id is 6–30 characters: lower-case letters, digits and hyphens, starting with a letter and not ending with a hyphen.",
|
|
253
|
+
)
|
|
254
|
+
: null
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function ProjectModeLinks({
|
|
259
|
+
mode,
|
|
260
|
+
links,
|
|
261
|
+
cmds,
|
|
262
|
+
}: {
|
|
263
|
+
mode: "new" | "existing";
|
|
264
|
+
links: ReturnType<typeof consoleLinks>;
|
|
265
|
+
cmds: ReturnType<typeof gcloudCommands>;
|
|
266
|
+
}) {
|
|
267
|
+
const t = useT();
|
|
268
|
+
return mode === "new" ? (
|
|
269
|
+
<>
|
|
270
|
+
<div className={muted}>{t("withoutGcloud", undefined, "Without gcloud:")}</div>
|
|
271
|
+
<div className="flex gap-3">
|
|
272
|
+
<StepLink href={links.projectCreate} label={t("createProject", undefined, "Create project")} />
|
|
273
|
+
</div>
|
|
274
|
+
{cmds.create && (
|
|
275
|
+
<>
|
|
276
|
+
<div className={muted}>{t("withGcloud", undefined, "With gcloud (run it yourself):")}</div>
|
|
277
|
+
<Copyable value={cmds.create} />
|
|
278
|
+
</>
|
|
279
|
+
)}
|
|
280
|
+
</>
|
|
281
|
+
) : (
|
|
282
|
+
<>
|
|
283
|
+
<div className={muted}>{t("findProject", undefined, "Find your project's id:")}</div>
|
|
284
|
+
<div className="flex gap-3">
|
|
285
|
+
<StepLink href={links.projectList} label={t("openProjectList", undefined, "Open the project list")} />
|
|
286
|
+
</div>
|
|
287
|
+
<Copyable value={cmds.projectsList} />
|
|
288
|
+
</>
|
|
289
|
+
);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function MismatchNotice({ mismatch, onUse }: { mismatch: { saved: string; json: string }; onUse: () => void }) {
|
|
293
|
+
const t = useT();
|
|
294
|
+
return (
|
|
295
|
+
<SettingsNotice tone="error" testId="gmail-project-mismatch">
|
|
296
|
+
<div className="flex flex-col gap-1">
|
|
297
|
+
<span>
|
|
298
|
+
{t(
|
|
299
|
+
"projectMismatch",
|
|
300
|
+
{ saved: mismatch.saved, json: mismatch.json },
|
|
301
|
+
`The uploaded client belongs to project ${mismatch.json}, but the saved project id is ${mismatch.saved}.`,
|
|
302
|
+
)}
|
|
303
|
+
</span>
|
|
304
|
+
<span>
|
|
305
|
+
<button type="button" className={btn} data-testid="gmail-project-mismatch-use" onClick={onUse}>
|
|
306
|
+
{t("projectMismatchUse", { id: mismatch.json }, `Use ${mismatch.json}`)}
|
|
307
|
+
</button>
|
|
308
|
+
</span>
|
|
309
|
+
</div>
|
|
310
|
+
</SettingsNotice>
|
|
311
|
+
);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function AuthLoginNote({ cmds }: { cmds: ReturnType<typeof gcloudCommands> }) {
|
|
315
|
+
const t = useT();
|
|
316
|
+
if (!cmds.authLogin) return null;
|
|
317
|
+
return (
|
|
318
|
+
<>
|
|
319
|
+
<div className={muted} data-testid="gmail-auth-login-note">
|
|
320
|
+
{t("authLoginNote", undefined, "Run this once first, so gcloud can act as the owner account:")}
|
|
321
|
+
</div>
|
|
322
|
+
<Copyable value={cmds.authLogin} />
|
|
323
|
+
</>
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function EnableGmailApi({ links, cmds }: { links: ReturnType<typeof consoleLinks>; cmds: ReturnType<typeof gcloudCommands> }) {
|
|
328
|
+
const t = useT();
|
|
329
|
+
return links.gmailApi && cmds.enable ? (
|
|
330
|
+
<>
|
|
331
|
+
<div className="flex gap-3">
|
|
332
|
+
<StepLink href={links.gmailApi} label={t("enableGmail", undefined, "Enable the Gmail API")} />
|
|
333
|
+
</div>
|
|
334
|
+
<Copyable value={cmds.enable} />
|
|
335
|
+
</>
|
|
336
|
+
) : (
|
|
337
|
+
<div className={muted} data-testid="gmail-need-project-id">
|
|
338
|
+
{t("needValidProjectId", undefined, "A valid project id is needed before the project links and commands appear.")}
|
|
339
|
+
</div>
|
|
340
|
+
);
|
|
341
|
+
}
|
|
342
|
+
|
|
179
343
|
export function SetupWizard({
|
|
180
344
|
state,
|
|
181
345
|
highlight,
|
|
@@ -186,24 +350,107 @@ export function SetupWizard({
|
|
|
186
350
|
onUploaded: () => void;
|
|
187
351
|
}) {
|
|
188
352
|
const t = useT();
|
|
189
|
-
const
|
|
353
|
+
const savedSetup = useRef<SavedSetup>({
|
|
354
|
+
projectId: state.setup?.projectId ?? "",
|
|
355
|
+
ownerAccount: state.setup?.ownerAccount ?? "",
|
|
356
|
+
});
|
|
357
|
+
const [projectId, setProjectId] = useState(state.setup?.projectId ?? state.client.projectId ?? "");
|
|
358
|
+
const [owner, setOwner] = useState(state.setup?.ownerAccount ?? "");
|
|
359
|
+
// Presentational only (design D2): `existing` by default once a project id is known.
|
|
360
|
+
const [mode, setMode] = useState<"new" | "existing">(state.setup?.projectId || state.client.projectId ? "existing" : "new");
|
|
361
|
+
// Validation errors appear on blur only and clear the moment the value turns valid.
|
|
362
|
+
const [projectErr, setProjectErr] = useState<"looks_like_name" | "invalid" | null>(null);
|
|
363
|
+
const [ownerErr, setOwnerErr] = useState(false);
|
|
364
|
+
const [saveError, setSaveError] = useState<string | null>(null);
|
|
365
|
+
const [mismatch, setMismatch] = useState<{ saved: string; json: string } | null>(null);
|
|
190
366
|
const [uploadError, setUploadError] = useState<{ code: string; step: WizardStep } | null>(null);
|
|
191
|
-
const links = consoleLinks(projectId
|
|
192
|
-
const
|
|
367
|
+
const links = consoleLinks(projectId, owner);
|
|
368
|
+
const cmds = gcloudCommands(projectId, owner);
|
|
193
369
|
const [focus, setFocus] = useState<WizardStep | null>(highlight);
|
|
194
370
|
useEffect(() => setFocus(highlight ?? uploadError?.step ?? null), [highlight, uploadError]);
|
|
195
371
|
|
|
372
|
+
/** Persist setup fields; rejects on failure. The reply (normalized values) is what counts as saved. */
|
|
373
|
+
const saveSetup = async (partial: Partial<SavedSetup>): Promise<void> => {
|
|
374
|
+
const r = await api<{ setup?: { projectId?: string; ownerAccount?: string } }>("/setup", {
|
|
375
|
+
method: "PUT",
|
|
376
|
+
body: JSON.stringify(partial),
|
|
377
|
+
});
|
|
378
|
+
savedSetup.current = r.setup
|
|
379
|
+
? { projectId: r.setup.projectId ?? "", ownerAccount: r.setup.ownerAccount ?? "" }
|
|
380
|
+
: { ...savedSetup.current, ...partial };
|
|
381
|
+
};
|
|
382
|
+
const saveOnBlur = (partial: Partial<SavedSetup>) => {
|
|
383
|
+
setSaveError(null);
|
|
384
|
+
saveSetup(partial).catch((err: unknown) => setSaveError((err as { code?: string }).code ?? (err as Error).message));
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
const onProjectChange = (v: string) => {
|
|
388
|
+
setProjectId(v);
|
|
389
|
+
if (!v.trim() || classifyProjectId(v) === "ok") setProjectErr(null);
|
|
390
|
+
};
|
|
391
|
+
const onProjectBlur = () => {
|
|
392
|
+
const cls = classifyProjectId(projectId);
|
|
393
|
+
if (cls === "looks_like_name" || cls === "invalid") {
|
|
394
|
+
setProjectErr(cls);
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
setProjectErr(null);
|
|
398
|
+
const next = cls === "ok" ? normalizeProjectId(projectId) : "";
|
|
399
|
+
if (next !== savedSetup.current.projectId) saveOnBlur({ projectId: next });
|
|
400
|
+
};
|
|
401
|
+
const onOwnerChange = (v: string) => {
|
|
402
|
+
setOwner(v);
|
|
403
|
+
if (!v.trim() || isEmail(normalizeEmail(v))) setOwnerErr(false);
|
|
404
|
+
};
|
|
405
|
+
const onOwnerBlur = () => {
|
|
406
|
+
const email = normalizeEmail(owner);
|
|
407
|
+
if (email && !isEmail(email)) {
|
|
408
|
+
setOwnerErr(true);
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
setOwnerErr(false);
|
|
412
|
+
if (email !== savedSetup.current.ownerAccount) saveOnBlur({ ownerAccount: email });
|
|
413
|
+
};
|
|
414
|
+
const useJsonProject = () => {
|
|
415
|
+
if (!mismatch) return;
|
|
416
|
+
const id = mismatch.json;
|
|
417
|
+
setMismatch(null);
|
|
418
|
+
setProjectId(id);
|
|
419
|
+
setProjectErr(null);
|
|
420
|
+
saveOnBlur({ projectId: id });
|
|
421
|
+
};
|
|
422
|
+
|
|
423
|
+
const reconcileJsonProject = (jsonId: string | undefined) => {
|
|
424
|
+
if (!jsonId) return;
|
|
425
|
+
const savedId = savedSetup.current.projectId;
|
|
426
|
+
if (!savedId) {
|
|
427
|
+
// Nothing saved yet: adopt the client's project id.
|
|
428
|
+
setProjectId(jsonId);
|
|
429
|
+
setProjectErr(null);
|
|
430
|
+
saveOnBlur({ projectId: jsonId });
|
|
431
|
+
} else if (savedId !== jsonId) {
|
|
432
|
+
setMismatch({ saved: savedId, json: jsonId });
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
|
|
196
436
|
const upload = async (file: File) => {
|
|
197
437
|
setUploadError(null);
|
|
438
|
+
setMismatch(null);
|
|
198
439
|
const textContent = await file.text();
|
|
199
440
|
const local = validateClientJson(textContent);
|
|
200
441
|
if (!local.ok) {
|
|
201
442
|
setUploadError({ code: local.error.code, step: local.error.step });
|
|
202
443
|
return;
|
|
203
444
|
}
|
|
445
|
+
// Flush a valid, unsaved typed id first (removes the blur/upload race); a failed
|
|
446
|
+
// save aborts the upload so the comparison never runs against a stale id.
|
|
447
|
+
if (!(await flushTypedProjectId(projectId, savedSetup.current.projectId, saveSetup))) {
|
|
448
|
+
setUploadError({ code: "setup_save_failed", step: 1 });
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
204
451
|
try {
|
|
205
|
-
await api("/client", { method: "PUT", body: JSON.stringify({ json: JSON.parse(textContent) }) });
|
|
206
|
-
|
|
452
|
+
const reply = await api<{ projectId?: string }>("/client", { method: "PUT", body: JSON.stringify({ json: JSON.parse(textContent) }) });
|
|
453
|
+
reconcileJsonProject(reply.projectId);
|
|
207
454
|
onUploaded();
|
|
208
455
|
} catch (err) {
|
|
209
456
|
const code = (err as { code?: string }).code ?? "upload_failed";
|
|
@@ -212,55 +459,93 @@ export function SetupWizard({
|
|
|
212
459
|
};
|
|
213
460
|
|
|
214
461
|
// Current step: the highlighted one, else the next thing the user has to do.
|
|
215
|
-
const current
|
|
216
|
-
|
|
217
|
-
const
|
|
218
|
-
|
|
219
|
-
const uploadMsg: Record<string, string> = {
|
|
220
|
-
not_json: t("errNotJson", undefined, "That file is not valid JSON. Upload the client_secret_*.json you downloaded (step 5)."),
|
|
221
|
-
web_client: t("errWebClient", undefined, "This is a Web application client. Create a Desktop app client instead (step 4)."),
|
|
222
|
-
not_installed: t("errNotInstalled", undefined, "No Desktop (`installed`) client in this file. Create a Desktop app client (step 4)."),
|
|
223
|
-
bad_client_id: t("errBadClientId", undefined, "The client id does not end in .apps.googleusercontent.com (step 4)."),
|
|
224
|
-
client_in_use: t(
|
|
225
|
-
"errClientInUse",
|
|
226
|
-
undefined,
|
|
227
|
-
"Accounts are connected with the current client. Revoke them first, then upload a different client.",
|
|
228
|
-
),
|
|
229
|
-
missing_secret: t("errMissingSecret", undefined, "The file has no client secret. Download it again from the client page (step 5)."),
|
|
230
|
-
};
|
|
462
|
+
const current = currentWizardStep(state, focus);
|
|
463
|
+
const isDone = (n: WizardStep) => isStepDone(state, current, n);
|
|
464
|
+
const uploadMsg = uploadMessages(t);
|
|
465
|
+
const projectErrText = projectErrorText(t, projectErr);
|
|
231
466
|
|
|
232
467
|
return (
|
|
233
468
|
<ol className="m-0 flex list-none flex-col p-0" data-testid="gmail-wizard">
|
|
234
469
|
<WizardStepItem n={1} title={t("step1", undefined, "1. Google Cloud project + Gmail API")} current={current === 1} done={isDone(1)}>
|
|
235
|
-
<
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
470
|
+
<fieldset className="m-0 flex flex-wrap items-center gap-3 border-0 p-0" data-testid="gmail-project-mode">
|
|
471
|
+
<legend className="sr-only">{t("projectModeLegend", undefined, "Project")}</legend>
|
|
472
|
+
{(["new", "existing"] as const).map((m) => (
|
|
473
|
+
<label key={m} className={`${muted} flex items-center gap-1`}>
|
|
474
|
+
<input
|
|
475
|
+
type="radio"
|
|
476
|
+
name="gmail-project-mode"
|
|
477
|
+
value={m}
|
|
478
|
+
checked={mode === m}
|
|
479
|
+
onChange={() => setMode(m)}
|
|
480
|
+
className="focus-ring"
|
|
481
|
+
data-testid={`gmail-project-mode-${m}`}
|
|
482
|
+
/>
|
|
483
|
+
{m === "new" ? t("projectModeNew", undefined, "Create a new project") : t("projectModeExisting", undefined, "Use an existing project")}
|
|
484
|
+
</label>
|
|
485
|
+
))}
|
|
486
|
+
</fieldset>
|
|
487
|
+
<div onBlur={onProjectBlur}>
|
|
488
|
+
<TextField
|
|
489
|
+
label={t("projectId", undefined, "Project id")}
|
|
490
|
+
hint={
|
|
491
|
+
<>
|
|
492
|
+
{t(
|
|
493
|
+
"projectIdHint",
|
|
494
|
+
undefined,
|
|
495
|
+
"The id of your Google Cloud project, not its display name: lower-case letters, digits and hyphens, for example my-gmail-agent. The console's project list shows both; the id is in the ID column.",
|
|
496
|
+
)}
|
|
497
|
+
{projectErr === "looks_like_name" && (
|
|
498
|
+
<>
|
|
499
|
+
{" "}
|
|
500
|
+
<StepLink href={links.projectList} label={t("openProjectList", undefined, "Open the project list")} />
|
|
501
|
+
</>
|
|
502
|
+
)}
|
|
503
|
+
</>
|
|
504
|
+
}
|
|
505
|
+
error={projectErrText}
|
|
506
|
+
mono
|
|
507
|
+
value={projectId}
|
|
508
|
+
onChange={onProjectChange}
|
|
509
|
+
placeholder="my-gmail-agent"
|
|
510
|
+
testIds={{ control: "gmail-project-id", error: "gmail-project-error" }}
|
|
511
|
+
/>
|
|
512
|
+
</div>
|
|
513
|
+
<div onBlur={onOwnerBlur}>
|
|
514
|
+
<TextField
|
|
515
|
+
label={t("ownerAccount", undefined, "Owner account (optional)")}
|
|
516
|
+
hint={t(
|
|
517
|
+
"ownerHint",
|
|
518
|
+
undefined,
|
|
519
|
+
"The Google account that owns the project. Console links and gcloud commands then act as this account instead of your browser's default one.",
|
|
520
|
+
)}
|
|
521
|
+
error={ownerErr ? t("errOwnerInvalid", undefined, "Enter a full email address, for example you@gmail.com.") : null}
|
|
522
|
+
value={owner}
|
|
523
|
+
onChange={onOwnerChange}
|
|
524
|
+
placeholder="you@gmail.com"
|
|
525
|
+
testIds={{ control: "gmail-owner-account", error: "gmail-owner-error" }}
|
|
526
|
+
/>
|
|
248
527
|
</div>
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
528
|
+
{saveError && (
|
|
529
|
+
<div role="alert" className={errorText} data-testid="gmail-setup-save-error">
|
|
530
|
+
{t("errSetupSave", undefined, "The project id could not be saved, so the upload was not sent. Try again (step 1).")} ({saveError})
|
|
531
|
+
</div>
|
|
532
|
+
)}
|
|
533
|
+
{mismatch && <MismatchNotice mismatch={mismatch} onUse={useJsonProject} />}
|
|
534
|
+
<AuthLoginNote cmds={cmds} />
|
|
535
|
+
<ProjectModeLinks mode={mode} links={links} cmds={cmds} />
|
|
536
|
+
<EnableGmailApi links={links} cmds={cmds} />
|
|
252
537
|
</WizardStepItem>
|
|
253
538
|
<WizardStepItem n={2} title={t("step2", undefined, "2. Branding")} current={current === 2} done={isDone(2)}>
|
|
254
|
-
<
|
|
539
|
+
<ProjectLink href={links.branding} label={t("openBranding", undefined, "Open Branding")} step={2} />
|
|
255
540
|
<div className={muted}>{t("fallback2", undefined, "If the link moved: APIs & Services → OAuth consent screen.")}</div>
|
|
256
541
|
</WizardStepItem>
|
|
257
542
|
<WizardStepItem n={3} title={t("step3", undefined, "3. Audience + test users")} current={current === 3} done={isDone(3)}>
|
|
258
|
-
<
|
|
543
|
+
<ProjectLink href={links.audience} label={t("openAudience", undefined, "Open Audience")} step={3} />
|
|
259
544
|
<div className={muted}>
|
|
260
545
|
{t(
|
|
261
546
|
"audienceHelp",
|
|
262
547
|
undefined,
|
|
263
|
-
|
|
548
|
+
AUDIENCE_HELP_EN,
|
|
264
549
|
)}
|
|
265
550
|
</div>
|
|
266
551
|
<div className={muted}>
|
|
@@ -272,7 +557,7 @@ export function SetupWizard({
|
|
|
272
557
|
</div>
|
|
273
558
|
</WizardStepItem>
|
|
274
559
|
<WizardStepItem n={4} title={t("step4", undefined, "4. Desktop OAuth client")} current={current === 4} done={isDone(4)}>
|
|
275
|
-
<
|
|
560
|
+
<ProjectLink href={links.clientCreate} label={t("openClients", undefined, "Create client")} step={4} />
|
|
276
561
|
<div className={muted}>
|
|
277
562
|
{t("clientHelp", undefined, "Application type: Desktop app. Download the JSON. If the link moved: APIs & Services → Credentials.")}
|
|
278
563
|
</div>
|
|
@@ -348,6 +633,8 @@ function AccountRow({
|
|
|
348
633
|
const [msg, setMsg] = useState<string | null>(null);
|
|
349
634
|
const [aliasMsg, setAliasMsg] = useState<{ ok: boolean; text: string } | null>(null);
|
|
350
635
|
const [confirming, setConfirming] = useState(false);
|
|
636
|
+
const [filtersOn, setFiltersOn] = useState(acct.filters === true);
|
|
637
|
+
useEffect(() => setFiltersOn(acct.filters === true), [acct.filters]);
|
|
351
638
|
const run = async (fn: () => Promise<void>) => {
|
|
352
639
|
setMsg(null);
|
|
353
640
|
try {
|
|
@@ -365,6 +652,18 @@ function AccountRow({
|
|
|
365
652
|
if (r.flowId) onFlow(r.flowId);
|
|
366
653
|
else onChanged();
|
|
367
654
|
});
|
|
655
|
+
const toggleFilters = (enabled: boolean) =>
|
|
656
|
+
run(async () => {
|
|
657
|
+
const r = await api<{ applied?: boolean; flowId?: string }>(`/accounts/${encodeURIComponent(acct.sub)}/filters`, {
|
|
658
|
+
method: "POST",
|
|
659
|
+
body: JSON.stringify({ enabled }),
|
|
660
|
+
});
|
|
661
|
+
if (r.flowId) onFlow(r.flowId);
|
|
662
|
+
else {
|
|
663
|
+
setFiltersOn(enabled);
|
|
664
|
+
onChanged();
|
|
665
|
+
}
|
|
666
|
+
});
|
|
368
667
|
const saveAlias = async () => {
|
|
369
668
|
try {
|
|
370
669
|
await api(`/accounts/${encodeURIComponent(acct.sub)}`, { method: "PATCH", body: JSON.stringify({ alias: alias || null }) });
|
|
@@ -450,6 +749,13 @@ function AccountRow({
|
|
|
450
749
|
))}
|
|
451
750
|
</select>
|
|
452
751
|
</label>
|
|
752
|
+
<ToggleField
|
|
753
|
+
label={t("filtersFor", { email: acct.email }, `Filters for ${acct.email}`)}
|
|
754
|
+
hint={null}
|
|
755
|
+
testIds={{ control: "gmail-account-filters" }}
|
|
756
|
+
value={filtersOn}
|
|
757
|
+
onChange={(enabled) => void toggleFilters(enabled)}
|
|
758
|
+
/>
|
|
453
759
|
<button
|
|
454
760
|
type="button"
|
|
455
761
|
className={btn}
|
|
@@ -480,6 +786,13 @@ function AccountRow({
|
|
|
480
786
|
</span>
|
|
481
787
|
)}
|
|
482
788
|
</div>
|
|
789
|
+
<p className={`${muted} m-0`} data-testid="gmail-account-filters-help">
|
|
790
|
+
{t(
|
|
791
|
+
"filtersHelp",
|
|
792
|
+
undefined,
|
|
793
|
+
"Filters let agents list, create and delete Gmail filters. Turning them on asks Google for one extra permission (gmail.settings.basic); creating and deleting also need level send.",
|
|
794
|
+
)}
|
|
795
|
+
</p>
|
|
483
796
|
{confirming && (
|
|
484
797
|
<ConfirmDialog
|
|
485
798
|
message={t(
|
|
@@ -503,11 +816,17 @@ function AddAccount({
|
|
|
503
816
|
configured,
|
|
504
817
|
newTier,
|
|
505
818
|
onTier,
|
|
819
|
+
email,
|
|
820
|
+
onEmail,
|
|
821
|
+
emailError,
|
|
506
822
|
onAdd,
|
|
507
823
|
}: {
|
|
508
824
|
configured: boolean;
|
|
509
825
|
newTier: Tier;
|
|
510
826
|
onTier: (t: Tier) => void;
|
|
827
|
+
email: string;
|
|
828
|
+
onEmail: (v: string) => void;
|
|
829
|
+
emailError: boolean;
|
|
511
830
|
onAdd: () => void;
|
|
512
831
|
}) {
|
|
513
832
|
const t = useT();
|
|
@@ -523,6 +842,17 @@ function AddAccount({
|
|
|
523
842
|
onChange={(v) => onTier(v as Tier)}
|
|
524
843
|
testIds={{ control: "gmail-new-level" }}
|
|
525
844
|
/>
|
|
845
|
+
<TextField
|
|
846
|
+
label={t("addEmail", undefined, "Account email (optional)")}
|
|
847
|
+
hint={t("addEmailHint", undefined, "Google then skips its account chooser and signs in as this address.")}
|
|
848
|
+
error={emailError ? t("errOwnerInvalid", undefined, "Enter a full email address, for example you@gmail.com.") : null}
|
|
849
|
+
type="email"
|
|
850
|
+
autoComplete="email"
|
|
851
|
+
value={email}
|
|
852
|
+
onChange={onEmail}
|
|
853
|
+
placeholder="you@gmail.com"
|
|
854
|
+
testIds={{ control: "gmail-add-email", error: "gmail-add-email-error" }}
|
|
855
|
+
/>
|
|
526
856
|
<div className="flex flex-wrap items-center gap-2">
|
|
527
857
|
<button
|
|
528
858
|
type="button"
|
|
@@ -566,6 +896,39 @@ function FlowErrorNotice({ code, step, errKey, clientId }: { code: string; step:
|
|
|
566
896
|
);
|
|
567
897
|
}
|
|
568
898
|
|
|
899
|
+
/** `POST /accounts` body (the optional email becomes `login_hint`); `null` when the email is typed but not an address. */
|
|
900
|
+
function accountRequest(tier: Tier, rawEmail: string): { tier: Tier; email?: string } | null {
|
|
901
|
+
const email = normalizeEmail(rawEmail);
|
|
902
|
+
if (!email) return { tier };
|
|
903
|
+
return isEmail(email) ? { tier, email } : null;
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
/** The wizard's props: a hand-off run overlays its project id / owner account and picks the step (task 4.3). */
|
|
907
|
+
function wizardProps(state: GmailState, handoff: SetupRunView | null, errorStep: WizardStep | null): { state: GmailState; highlight: WizardStep | null } {
|
|
908
|
+
if (!handoff) return { state, highlight: errorStep };
|
|
909
|
+
return {
|
|
910
|
+
state: {
|
|
911
|
+
...state,
|
|
912
|
+
setup: {
|
|
913
|
+
projectId: handoff.projectId ?? handoff.created.projectId ?? state.setup?.projectId,
|
|
914
|
+
ownerAccount: handoff.ownerEmail ?? state.setup?.ownerAccount,
|
|
915
|
+
},
|
|
916
|
+
},
|
|
917
|
+
highlight: handoff.handoff?.wizardStep ?? errorStep,
|
|
918
|
+
};
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
/** Sign-in notice for an External or unknown audience (design D11). */
|
|
922
|
+
function UnverifiedHint({ audience }: { audience: Audience | null }) {
|
|
923
|
+
const t = useT();
|
|
924
|
+
if (!showUnverifiedNotice(audience)) return null;
|
|
925
|
+
return (
|
|
926
|
+
<p className={`${muted} m-0`} data-testid="gmail-unverified-hint">
|
|
927
|
+
{t("unverifiedHint", undefined, UNVERIFIED_HINT_EN)}
|
|
928
|
+
</p>
|
|
929
|
+
);
|
|
930
|
+
}
|
|
931
|
+
|
|
569
932
|
export function GmailSettings() {
|
|
570
933
|
const t = useT();
|
|
571
934
|
const OAuthFlow = useUiPrimitive("ui:oauth-flow");
|
|
@@ -575,6 +938,12 @@ export function GmailSettings() {
|
|
|
575
938
|
const [flowError, setFlowError] = useState<string | null>(null);
|
|
576
939
|
const [lastRevoke, setLastRevoke] = useState<string | null>(null);
|
|
577
940
|
const [newTier, setNewTier] = useState<Tier>("readonly");
|
|
941
|
+
const [addEmail, setAddEmail] = useState("");
|
|
942
|
+
const [addEmailError, setAddEmailError] = useState(false);
|
|
943
|
+
// Automatic setup (change: add-gmail-auto-setup): hand-off view for the wizard, audience
|
|
944
|
+
// for the unverified-app notice (null = unknown → the notice shows).
|
|
945
|
+
const [handoff, setHandoff] = useState<SetupRunView | null>(null);
|
|
946
|
+
const [audience, setAudience] = useState<Audience | null>(null);
|
|
578
947
|
// Latch (design D1): once the user reports a Google-page code, no late poll
|
|
579
948
|
// result may overwrite it or re-mount the flow view. Reset on a new flow.
|
|
580
949
|
const reportedRef = useRef<string | null>(null);
|
|
@@ -625,11 +994,17 @@ export function GmailSettings() {
|
|
|
625
994
|
};
|
|
626
995
|
|
|
627
996
|
const addAccount = async () => {
|
|
997
|
+
const request = accountRequest(newTier, addEmail);
|
|
998
|
+
setAddEmailError(!request);
|
|
999
|
+
if (!request) return;
|
|
628
1000
|
reportedRef.current = null;
|
|
629
1001
|
setFlowError(null);
|
|
630
1002
|
setFlow({ phase: "starting" });
|
|
631
1003
|
try {
|
|
632
|
-
const r = await api<{ flowId: string }>("/accounts", {
|
|
1004
|
+
const r = await api<{ flowId: string }>("/accounts", {
|
|
1005
|
+
method: "POST",
|
|
1006
|
+
body: JSON.stringify(request),
|
|
1007
|
+
});
|
|
633
1008
|
await startFlow(r.flowId);
|
|
634
1009
|
} catch (err) {
|
|
635
1010
|
setFlow(null);
|
|
@@ -654,6 +1029,7 @@ export function GmailSettings() {
|
|
|
654
1029
|
const step = errorStep(flowError);
|
|
655
1030
|
const errKey = errorKey(flowError);
|
|
656
1031
|
const { client } = state;
|
|
1032
|
+
const wizard = wizardProps(state, handoff, step);
|
|
657
1033
|
const summary = !client.configured
|
|
658
1034
|
? t("summaryNotConfigured", undefined, "not configured")
|
|
659
1035
|
: client.projectId
|
|
@@ -668,9 +1044,22 @@ export function GmailSettings() {
|
|
|
668
1044
|
title={t("setup", undefined, "Google Cloud setup")}
|
|
669
1045
|
meta={summary}
|
|
670
1046
|
summaryTestId="gmail-setup-summary"
|
|
671
|
-
defaultOpen={!client.configured || state.accounts.length === 0 || step !== null}
|
|
1047
|
+
defaultOpen={!client.configured || state.accounts.length === 0 || step !== null || handoff !== null}
|
|
672
1048
|
>
|
|
673
|
-
<
|
|
1049
|
+
<AutoSetupSection
|
|
1050
|
+
autoSetup={state.autoSetup}
|
|
1051
|
+
setup={state.setup}
|
|
1052
|
+
onAudience={setAudience}
|
|
1053
|
+
onOwnerEmail={setAddEmail}
|
|
1054
|
+
onHandoff={setHandoff}
|
|
1055
|
+
onRefresh={() => void refresh()}
|
|
1056
|
+
/>
|
|
1057
|
+
<SetupWizard
|
|
1058
|
+
key={handoff ? `handoff-${handoff.runId}` : "manual"}
|
|
1059
|
+
state={wizard.state}
|
|
1060
|
+
highlight={wizard.highlight}
|
|
1061
|
+
onUploaded={() => void refresh()}
|
|
1062
|
+
/>
|
|
674
1063
|
</SettingsGroup>
|
|
675
1064
|
|
|
676
1065
|
<div className="flex flex-col gap-2" data-testid="gmail-accounts">
|
|
@@ -710,9 +1099,10 @@ export function GmailSettings() {
|
|
|
710
1099
|
{t(
|
|
711
1100
|
"consentHint",
|
|
712
1101
|
undefined,
|
|
713
|
-
|
|
1102
|
+
CONSENT_HINT_EN,
|
|
714
1103
|
)}
|
|
715
1104
|
</p>
|
|
1105
|
+
<UnverifiedHint audience={audience} />
|
|
716
1106
|
<OAuthFlow
|
|
717
1107
|
flow={flow}
|
|
718
1108
|
onSendInput={(id, value) => oauthFlowClient.input(id, value)}
|
|
@@ -743,7 +1133,18 @@ export function GmailSettings() {
|
|
|
743
1133
|
)}
|
|
744
1134
|
</div>
|
|
745
1135
|
) : (
|
|
746
|
-
<AddAccount
|
|
1136
|
+
<AddAccount
|
|
1137
|
+
configured={client.configured}
|
|
1138
|
+
newTier={newTier}
|
|
1139
|
+
onTier={setNewTier}
|
|
1140
|
+
email={addEmail}
|
|
1141
|
+
onEmail={(v) => {
|
|
1142
|
+
setAddEmail(v);
|
|
1143
|
+
setAddEmailError(false);
|
|
1144
|
+
}}
|
|
1145
|
+
emailError={addEmailError}
|
|
1146
|
+
onAdd={() => void addAccount()}
|
|
1147
|
+
/>
|
|
747
1148
|
)}
|
|
748
1149
|
{flowError && <FlowErrorNotice code={flowError} step={step} errKey={errKey} clientId={client.clientId ?? ""} />}
|
|
749
1150
|
{lastRevoke && (
|