@blackbelt-technology/pi-dashboard-gmail-plugin 0.11.0 → 0.12.1

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.
@@ -1,124 +0,0 @@
1
- /**
2
- * Automatic-setup client data (pure, no React): hand-off reason → i18n key +
3
- * English sentence, checkpoint copy keys, start-error mapping, the publishing-links
4
- * check and the unverified-app notice rule. `AUTO_SETUP_ERROR_EN` is spread into
5
- * `ERROR_EN` (wizard.ts) so every dynamic key carries an English `t()` fallback.
6
- * See change: add-gmail-auto-setup.
7
- */
8
- import type { Audience, CheckpointKind, HandoffReason, PublishLinks, SetupRunState } from "../shared/auto-setup.js";
9
-
10
- /** i18n key per hand-off reason (design D3/D8/D9). */
11
- export const HANDOFF_KEY: Record<HandoffReason, string> = {
12
- unexpected_page: "handoffUnexpectedPage",
13
- locale: "handoffLocale",
14
- domain_blocked: "handoffDomainBlocked",
15
- publish_cancelled: "handoffPublishCancelled",
16
- timeout: "handoffTimeout",
17
- secret_capture_failed: "handoffSecretCaptureFailed",
18
- client_in_use: "handoffClientInUse",
19
- browser_closed: "handoffBrowserClosed",
20
- disabled: "handoffDisabled",
21
- unloaded: "handoffUnloaded",
22
- "no-chrome": "handoffNoChrome",
23
- "no-display": "handoffNoDisplay",
24
- "owned-by-other-server": "handoffOwnedByOtherServer",
25
- "profile-in-use": "handoffProfileInUse",
26
- "launch-failed": "handoffLaunchFailed",
27
- };
28
-
29
- /** Key for a hand-off reason; a reason a newer server adds falls back to the generic sentence. */
30
- export function handoffKey(reason: string): string {
31
- return (HANDOFF_KEY as Record<string, string>)[reason] ?? "handoffGeneric";
32
- }
33
-
34
- /** i18n key per human checkpoint (design D5). */
35
- export const CHECKPOINT_KEY: Record<CheckpointKind, string> = {
36
- sign_in: "autoCpSignIn",
37
- console_terms: "autoCpTerms",
38
- policy: "autoCpPolicy",
39
- publish: "autoCpPublish",
40
- };
41
-
42
- /** Run states in which the run is still going (polled every second). */
43
- const LIVE_STATES: readonly SetupRunState[] = ["starting", "running", "waiting_user", "waiting_decision", "busy"];
44
- export const isLive = (state: SetupRunState): boolean => LIVE_STATES.includes(state);
45
-
46
- /**
47
- * The unverified-app sentence applies unless the audience is known to be Internal
48
- * (design D11): External and "unknown" (no run observed on this page) both show it.
49
- */
50
- export function showUnverifiedNotice(audience: Audience | null | undefined): boolean {
51
- return audience !== "internal";
52
- }
53
-
54
- export type LinkError = "invalid_url" | "not_https" | "outside_domain" | "invalid_domain";
55
-
56
- /** Mirror of the server rule (design D7): `https:` and host under the authorized domain. */
57
- export function validateLinks(links: PublishLinks): Partial<Record<keyof PublishLinks, LinkError>> {
58
- const errors: Partial<Record<keyof PublishLinks, LinkError>> = {};
59
- const domain = links.authorizedDomain.trim().toLowerCase();
60
- if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/.test(domain)) errors.authorizedDomain = "invalid_domain";
61
- for (const key of ["homePage", "privacyPolicy"] as const) {
62
- let url: URL;
63
- try {
64
- url = new URL(links[key].trim());
65
- } catch {
66
- errors[key] = "invalid_url";
67
- continue;
68
- }
69
- if (url.protocol !== "https:") errors[key] = "not_https";
70
- else if (!errors.authorizedDomain && url.hostname !== domain && !url.hostname.endsWith(`.${domain}`)) errors[key] = "outside_domain";
71
- }
72
- return errors;
73
- }
74
-
75
- export const LINK_ERROR_KEY: Record<LinkError, string> = {
76
- invalid_url: "errLinkInvalid",
77
- not_https: "errLinkHttps",
78
- outside_domain: "errLinkDomain",
79
- invalid_domain: "errLinkAuthorizedDomain",
80
- };
81
-
82
- /** i18n key for a rejected `POST setup/run` / action; unknown codes render the raw server message. */
83
- export function startErrorKey(code: string | undefined): string | null {
84
- switch (code) {
85
- case "run_active":
86
- return "autoErrRunActive";
87
- case "remote_dashboard":
88
- return "autoErrRemote";
89
- default:
90
- return null;
91
- }
92
- }
93
-
94
- /** English sentences (the `t()` fallbacks for every dynamic key above). */
95
- export const AUTO_SETUP_ERROR_EN: Record<string, string> = {
96
- handoffGeneric: "Automatic setup stopped. Continue with the manual steps below.",
97
- handoffUnexpectedPage:
98
- "Google's console showed a page the automatic setup did not expect, so it stopped instead of guessing. Continue by hand from the highlighted step.",
99
- handoffLocale:
100
- "The console is not in English, so the automatic setup could not read it reliably. Switch the Google account's language to English, or continue by hand from the highlighted step.",
101
- handoffDomainBlocked:
102
- "The dedicated browser refused to open the Google Cloud console or Google sign-in. Add the domains listed below to the Browser plugin's allowed domains, or continue by hand.",
103
- handoffPublishCancelled: "The publish confirmation was cancelled in the browser window. Continue by hand from the highlighted step.",
104
- handoffTimeout: "The automatic setup waited 15 minutes for a step on your side and gave up. Continue by hand, or start it again.",
105
- handoffSecretCaptureFailed:
106
- "The OAuth client was created, but its secret could not be read. The secret cannot be shown again, so add a new one to that client.",
107
- handoffClientInUse:
108
- "An OAuth client with connected accounts is already configured, and the automatic setup never replaces a working client. Revoke the accounts first, or keep the current client.",
109
- handoffBrowserClosed: "The dedicated browser window was closed. Continue by hand, or start the automatic setup again.",
110
- handoffDisabled: "The dedicated browser is turned off in the Browser plugin settings. Turn it on, or continue by hand.",
111
- handoffUnloaded: "The Browser plugin is not loaded, so the dedicated browser is not available. Continue by hand.",
112
- handoffNoChrome: "No Chrome installation was found for the dedicated browser. Install Chrome, or continue by hand.",
113
- handoffNoDisplay: "This computer has no display for the dedicated browser window. Continue by hand.",
114
- handoffOwnedByOtherServer: "Another dashboard server on this computer owns the dedicated browser. Continue by hand.",
115
- handoffProfileInUse: "The dedicated browser profile is open in another Chrome window. Close it, or continue by hand.",
116
- handoffLaunchFailed: "The dedicated browser could not be started. Continue by hand.",
117
- autoErrRunActive: "An automatic setup is already running on this dashboard.",
118
- autoErrRemote: "Automatic setup only starts from the computer that runs the dashboard.",
119
- autoErrGeneric: "The automatic setup request failed.",
120
- errLinkInvalid: "Enter a full web address, for example https://example.com/privacy.",
121
- errLinkHttps: "The address must start with https://.",
122
- errLinkDomain: "The address must be on the authorized domain.",
123
- errLinkAuthorizedDomain: "Enter a domain name, for example github.com.",
124
- };
package/src/client/ui.ts DELETED
@@ -1,24 +0,0 @@
1
- /**
2
- * Client helpers shared by `GmailSettings.tsx` and `AutoSetup.tsx`: the plugin
3
- * REST helper and the secondary-button / text class recipes.
4
- * See change: add-gmail-auto-setup.
5
- */
6
-
7
- const API = "/api/plugins/gmail";
8
-
9
- /** JSON helper for the plugin routes; a failed reply throws `{ code: body.error, status, detail: body.message }`. */
10
- export async function api<T>(path: string, init?: RequestInit): Promise<T> {
11
- const res = await fetch(`${API}${path}`, {
12
- ...init,
13
- headers: init?.body ? { "content-type": "application/json" } : undefined,
14
- });
15
- const body = (await res.json().catch(() => ({}))) as T & { error?: string; message?: string };
16
- if (!res.ok) throw Object.assign(new Error(body.error ?? `HTTP ${res.status}`), { code: body.error, status: res.status, detail: body.message });
17
- return body;
18
- }
19
-
20
- // Secondary button recipe (`ui-contract.md`); `tap-target` = 44 px touch, 32 px from sm.
21
- export const btn =
22
- "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";
23
- export const muted = "text-xs text-[var(--text-secondary)]";
24
- export const errorText = "text-xs text-[var(--severity-error-fg)]";
@@ -1,196 +0,0 @@
1
- /**
2
- * Setup-wizard data (design D7): console deep links, copyable gcloud commands
3
- * and the sign-in-error → wizard-step map. Pure — the server never executes
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.
7
- * `ERROR_EN` also carries the hand-off reason sentences. See change: add-gmail-auto-setup.
8
- */
9
- import { type FlowCode, knownFlowCode } from "../shared/flow-codes.js";
10
- import { classifyProjectId, isEmail, normalizeEmail, normalizeProjectId } from "../shared/setup.js";
11
- import { AUTO_SETUP_ERROR_EN } from "./auto-setup.js";
12
-
13
- export type WizardStep = 1 | 2 | 3 | 4 | 5 | 6;
14
-
15
- const CONSOLE = "https://console.cloud.google.com";
16
-
17
- export interface ConsoleLinks {
18
- /** Never project-scoped: carries only `authuser`. */
19
- projectCreate: string;
20
- /** Console project picker (find the project id); never project-scoped. */
21
- projectList: string;
22
- /** Project-scoped links: `null` until the project id is valid. */
23
- gmailApi: string | null;
24
- branding: string | null;
25
- audience: string | null;
26
- clientCreate: string | null;
27
- }
28
-
29
- /** The owner account when it is a valid email (normalized), else `undefined`. */
30
- function validOwner(owner: string | undefined): string | undefined {
31
- if (!owner) return undefined;
32
- const email = normalizeEmail(owner);
33
- return isEmail(email) ? email : undefined;
34
- }
35
-
36
- /**
37
- * Console deep links (design D3). Project-scoped links exist only for a valid
38
- * project id and carry `project`; every non-null link carries `authuser` when
39
- * the owner account is a valid email. Query values are URL-encoded.
40
- */
41
- export function consoleLinks(projectId: string, owner?: string): ConsoleLinks {
42
- const email = validOwner(owner);
43
- const id = classifyProjectId(projectId) === "ok" ? normalizeProjectId(projectId) : undefined;
44
- const url = (path: string, withProject: boolean): string => {
45
- const q = new URLSearchParams();
46
- if (withProject && id) q.set("project", id);
47
- if (email) q.set("authuser", email);
48
- const qs = q.toString();
49
- return `${CONSOLE}${path}${qs ? `?${qs}` : ""}`;
50
- };
51
- return {
52
- projectCreate: url("/projectcreate", false),
53
- projectList: url("/cloud-resource-manager", false),
54
- gmailApi: id ? url("/apis/library/gmail.googleapis.com", true) : null,
55
- branding: id ? url("/auth/branding", true) : null,
56
- audience: id ? url("/auth/audience", true) : null,
57
- clientCreate: id ? url("/auth/clients/create", true) : null,
58
- };
59
- }
60
-
61
- export interface GcloudCommands {
62
- /** `gcloud auth login <email>` — only with a valid owner; run it once first. */
63
- authLogin: string | null;
64
- projectsList: string;
65
- /** `null` until the project id is valid (never a placeholder). */
66
- create: string | null;
67
- enable: string | null;
68
- }
69
-
70
- /**
71
- * POSIX-shell quote for a value the user will paste into a terminal. `isEmail` admits shell
72
- * metacharacters in the local part (`a;b@x.co`, `$(id)@x.co`), so anything outside the plain
73
- * address alphabet is single-quoted (embedded `'` as `'\''`); ordinary addresses stay bare.
74
- */
75
- function shellQuote(v: string): string {
76
- return /^[A-Za-z0-9@._+-]+$/.test(v) ? v : `'${v.replaceAll("'", "'\\''")}'`;
77
- }
78
-
79
- /** Copyable gcloud commands (design D3); `--account <email>` on every command but `auth login`. */
80
- export function gcloudCommands(projectId: string, owner?: string): GcloudCommands {
81
- const valid = validOwner(owner);
82
- const email = valid === undefined ? undefined : shellQuote(valid);
83
- const id = classifyProjectId(projectId) === "ok" ? normalizeProjectId(projectId) : undefined;
84
- const acct = (cmd: string): string => (email ? `${cmd} --account ${email}` : cmd);
85
- return {
86
- authLogin: email ? `gcloud auth login ${email}` : null,
87
- projectsList: acct("gcloud projects list"),
88
- create: id ? acct(`gcloud projects create ${id}`) : null,
89
- enable: id ? acct(`gcloud services enable gmail.googleapis.com --project ${id}`) : null,
90
- };
91
- }
92
-
93
- /**
94
- * Map a sign-in / upload error code to the wizard step that fixes it.
95
- * `admin_policy_enforced` → null: the fix is in the account's Workspace Admin
96
- * console, not in a wizard step (improve-gmail-settings-ux D2).
97
- */
98
- export function errorStep(code: string | undefined | null): WizardStep | null {
99
- switch (code) {
100
- case "access_denied":
101
- case "org_internal":
102
- return 3;
103
- case "redirect_uri_mismatch":
104
- case "web_client":
105
- case "not_installed":
106
- case "bad_client_id":
107
- return 4;
108
- case "invalid_client":
109
- case "missing_secret":
110
- case "not_json":
111
- case "no_client":
112
- case "client_in_use":
113
- return 5;
114
- default:
115
- return null;
116
- }
117
- }
118
-
119
- export { KNOWN_FLOW_CODES } from "../shared/flow-codes.js";
120
-
121
- /** i18n key per flow code (design D2). `cancelled` also matches the host's "Cancelled". */
122
- const CODE_KEY: Record<FlowCode, string> = {
123
- org_internal: "errOrgInternal",
124
- access_denied: "errAccessDenied",
125
- admin_policy_enforced: "errAdminPolicy",
126
- redirect_uri_mismatch: "errRedirectMismatch",
127
- invalid_client: "errInvalidClient",
128
- scope_missing: "errScopeMissing",
129
- account_mismatch: "errAccountMismatch",
130
- missing_refresh: "errMissingRefresh",
131
- email_unverified: "errEmailUnverified",
132
- invalid_redirect: "errInvalidRedirect",
133
- state_mismatch: "errStateMismatch",
134
- callback_failed: "errCallbackFailed",
135
- token_exchange_failed: "errTokenExchange",
136
- id_token_invalid: "errIdToken",
137
- authorization_failed: "errAuthorization",
138
- timeout: "errTimeout",
139
- start_timeout: "errStartTimeout",
140
- login_failed: "errLoginFailed",
141
- cancelled: "errCancelled",
142
- aborted: "errAborted",
143
- };
144
-
145
- /**
146
- * English sentence per error key (the catalogs carry only zh-CN / hu; a dynamic
147
- * key MUST pass this as its `t()` fallback). `{clientId}` is interpolated.
148
- */
149
- export const ERROR_EN: Record<string, string> = {
150
- errOrgInternal:
151
- "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).",
152
- errAccessDenied:
153
- "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.",
154
- errAdminPolicy:
155
- "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).",
156
- errRedirectMismatch: "Google rejected the redirect address. Create a Desktop app client, not a Web client (step 4).",
157
- errInvalidClient: "Google does not recognise the OAuth client. Download its JSON again and upload it (step 5).",
158
- errScopeMissing:
159
- "Google did not grant the Gmail permission. Google asks for it either as a checkbox you must tick, or on a second screen (\"wants additional access\") you must accept — finishing after the first screen only signs you in. Remove this app's access at myaccount.google.com/connections, then add the account again.",
160
- errAccountMismatch: "You signed in with a different Google account. Re-authenticate with the account shown in the row.",
161
- errMissingRefresh: "Google returned no long-lived token. Revoke the app at myaccount.google.com/permissions, then add the account again.",
162
- errEmailUnverified: "Google reports this account's email as unverified. Verify it with Google, then try again.",
163
- errInvalidRedirect: "The pasted address is not the redirect Google sent. Paste the full URL from the browser's address bar.",
164
- errStateMismatch: "The pasted redirect belongs to another sign-in. Start again and paste the URL from this sign-in.",
165
- errCallbackFailed: "The sign-in callback failed. Try again.",
166
- errTokenExchange: "Google refused to exchange the sign-in code. Check the uploaded client (step 5) and try again.",
167
- errIdToken: "Google's sign-in answer could not be verified. Try again.",
168
- errAuthorization: "Google reported a sign-in error. Try again; if it repeats, check the setup steps above.",
169
- errTimeout: "Sign-in timed out waiting for Google. If Google showed an error page, report it with the option below the sign-in link.",
170
- errStartTimeout: "The sign-in did not start in time. Try again.",
171
- errLoginFailed: "The sign-in could not start. Try again.",
172
- errCancelled: "Sign-in was cancelled.",
173
- errAborted: "Sign-in was aborted.",
174
- errGeneric: "Sign-in failed. Try again; if it keeps failing, check the setup steps above.",
175
- // Automatic setup: hand-off reasons + start/link errors (change: add-gmail-auto-setup).
176
- ...AUTO_SETUP_ERROR_EN,
177
- };
178
-
179
- /** i18n key for a terminal flow error; unknown input → `errGeneric` (exact match only). */
180
- export function errorKey(code: string | undefined | null): string {
181
- if (typeof code !== "string") return "errGeneric";
182
- if (code.toLowerCase() === "cancelled") return "errCancelled";
183
- const known = knownFlowCode(code);
184
- return known ? CODE_KEY[known] : "errGeneric";
185
- }
186
-
187
- /** English fallbacks for copy that mirrors a catalog key (the E30 test pins their content). */
188
- export const CONSENT_HINT_EN =
189
- "Google asks for the Gmail permission either as a checkbox (tick it) or on a second screen saying the app \"wants additional access\" (accept it). Stopping after the first screen only signs you in.";
190
-
191
- export const AUDIENCE_HELP_EN =
192
- "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. Publishing the app removes the 7-day token expiry. An unverified app shows Google's warning and admits at most 100 users. Accounts added while in Testing need one re-auth after publishing.";
193
-
194
- /** Sign-in notice for an External or unknown audience (design D11). See change: add-gmail-auto-setup. */
195
- export const UNVERIFIED_HINT_EN =
196
- "Google may show “Google hasn’t verified this app”. Choose Advanced, then continue to the app.";
@@ -1,27 +0,0 @@
1
- /**
2
- * Google token revocation (design D9). Best effort: bounded by a 5 s timeout,
3
- * never throws, never logs the token. See change: add-gmail-plugin.
4
- */
5
- import type { GoogleEndpoints } from "../shared/endpoints.js";
6
-
7
- const REVOKE_TIMEOUT_MS = 5_000;
8
-
9
- /** POST the token to Google's revoke endpoint. Resolves `true` on HTTP 200. */
10
- export async function revokeToken(
11
- endpoints: GoogleEndpoints,
12
- token: string,
13
- fetchImpl: typeof fetch = fetch,
14
- ): Promise<boolean> {
15
- if (!token) return false;
16
- try {
17
- const res = await fetchImpl(endpoints.revoke, {
18
- method: "POST",
19
- headers: { "content-type": "application/x-www-form-urlencoded" },
20
- body: new URLSearchParams({ token }).toString(),
21
- signal: AbortSignal.timeout(REVOKE_TIMEOUT_MS),
22
- });
23
- return res.ok;
24
- } catch {
25
- return false;
26
- }
27
- }
@@ -1,55 +0,0 @@
1
- /**
2
- * Structural contract of the `browser.dedicated` service the browser plugin
3
- * provides via `ctx.provide("browser.dedicated", …)` (design D2). Declared here,
4
- * not imported: the gmail plugin has no `dependsOn` on the browser plugin, so the
5
- * two meet only through this shape, resolved lazily with `ctx.consume`.
6
- * See change: add-gmail-auto-setup.
7
- */
8
-
9
- export const BROWSER_DEDICATED_SERVICE = "browser.dedicated";
10
-
11
- /** A refusal; `status` mirrors `POST /api/browser/dedicated/*`. */
12
- export interface BrowserRefusal {
13
- ok: false;
14
- status: number;
15
- /** `busy`, `disabled`, `unloaded`, `no-chrome`, `no-display`, `owned-by-other-server`, `profile-in-use`, `launch-failed`, `url-denied`, … */
16
- reason: string;
17
- /** `busy` only: session id or client label of the holder. */
18
- holder?: string;
19
- /** `busy` only: the holder's instance id (kept server-side, never in a run view). */
20
- instanceId?: string;
21
- message?: string;
22
- }
23
-
24
- export interface DedicatedBrowserStatus {
25
- /** Plugin loaded AND kill switch on. */
26
- enabled: boolean;
27
- available: boolean;
28
- reason?: string;
29
- /** Server-chosen downloads dir of the dedicated profile (never `~/Downloads`). */
30
- downloadsDir: string;
31
- instanceId?: string;
32
- holder?: { sessionId?: string; client?: string };
33
- }
34
-
35
- export interface DedicatedConnectOptions {
36
- /** Holder label, e.g. `gmail-setup`. */
37
- client: string;
38
- /** Close the current holder and register atomically. */
39
- takeover?: boolean;
40
- /** Tabs excluded from `browser_relay_status`; viewer subscribe refused. */
41
- private?: boolean;
42
- /** Throwaway browser context discarded with the instance. */
43
- ephemeral?: boolean;
44
- }
45
-
46
- export interface DedicatedBrowserService {
47
- status(): Promise<DedicatedBrowserStatus>;
48
- connect(opts: DedicatedConnectOptions): Promise<{ ok: true; cdpUrl: string; instanceId: string } | BrowserRefusal>;
49
- /** Hidden, server-owned tab (in the instance's context when `instanceId` is given). `https:` + allowed domains only. */
50
- open(opts: { url: string; instanceId?: string }): Promise<{ ok: true; tabId: string } | BrowserRefusal>;
51
- focus(tabId: string): Promise<{ ok: true } | BrowserRefusal>;
52
- /** Origin only (`https://accounts.google.com`), or `null` once the tab is gone. */
53
- tabOrigin(tabId: string): Promise<string | null>;
54
- disconnect(instanceId: string): Promise<void>;
55
- }
@@ -1,96 +0,0 @@
1
- /**
2
- * Secret capture (design D8): read the new client's id + secret from the
3
- * creation dialog in memory; when that fails, click "Download JSON", read the
4
- * newest new `client_secret_*.json` in the dedicated profile's downloads dir and
5
- * ALWAYS delete what the click produced. The values go through the same store
6
- * function as `PUT /client`. Nothing here logs, returns or throws the secret.
7
- * See change: add-gmail-auto-setup.
8
- */
9
- import { readdir, readFile, rm, stat } from "node:fs/promises";
10
- import path from "node:path";
11
- import { SetupControl, SetupHandoff } from "./errors.js";
12
- import { SEL, type StepEnv } from "./steps.js";
13
-
14
- const CLIENT_ID_RE = /[A-Za-z0-9._-]{1,200}\.apps\.googleusercontent\.com/;
15
- const SECRET_RE = /GOCSPX-[A-Za-z0-9_-]+/;
16
- const DOWNLOAD_RE = /^client_secret_[^/\\]*\.json$/;
17
-
18
- export interface CapturedClient {
19
- clientId: string;
20
- clientSecret: string;
21
- }
22
-
23
- /** Pure: pull id + secret out of the dialog's text. */
24
- export function parseClientDialog(text: string): CapturedClient | undefined {
25
- const clientId = CLIENT_ID_RE.exec(text)?.[0];
26
- const clientSecret = SECRET_RE.exec(text)?.[0];
27
- return clientId && clientSecret ? { clientId, clientSecret } : undefined;
28
- }
29
-
30
- async function downloads(dir: string): Promise<Set<string>> {
31
- try {
32
- return new Set((await readdir(dir)).filter((f) => DOWNLOAD_RE.test(f)));
33
- } catch {
34
- return new Set();
35
- }
36
- }
37
-
38
- /** Newest file in `dir` matching the pattern that is not in `before`. */
39
- async function newestNew(dir: string, before: Set<string>): Promise<string | undefined> {
40
- let best: { f: string; t: number } | undefined;
41
- for (const f of await downloads(dir)) {
42
- if (before.has(f) || !f.endsWith(".json")) continue;
43
- const t = (await stat(path.join(dir, f)).catch(() => undefined))?.mtimeMs ?? 0;
44
- if (!best || t >= best.t) best = { f, t };
45
- }
46
- return best?.f;
47
- }
48
-
49
- async function readDialog(env: StepEnv): Promise<CapturedClient | undefined> {
50
- try {
51
- return parseClientDialog(await env.dialogText());
52
- } catch (err) {
53
- if (err instanceof SetupControl) throw err;
54
- return undefined;
55
- }
56
- }
57
-
58
- async function readDownload(env: StepEnv, dir: string, before: Set<string>): Promise<CapturedClient | undefined> {
59
- try {
60
- await env.click(SEL.downloadJson);
61
- const file = await env.waitFor(() => newestNew(dir, before), env.timing.markerWaitMs);
62
- if (!file) return undefined;
63
- const json = JSON.parse(await readFile(path.join(dir, file), "utf8")) as {
64
- installed?: { client_id?: unknown; client_secret?: unknown };
65
- };
66
- const { client_id: clientId, client_secret: clientSecret } = json.installed ?? {};
67
- return typeof clientId === "string" && typeof clientSecret === "string" ? { clientId, clientSecret } : undefined;
68
- } catch (err) {
69
- if (err instanceof SetupControl) throw err;
70
- return undefined;
71
- }
72
- }
73
-
74
- export async function captureClient(env: StepEnv): Promise<void> {
75
- const dir = await env.downloadsDir();
76
- const before = await downloads(dir);
77
- try {
78
- const captured = (await readDialog(env)) ?? (await readDownload(env, dir, before));
79
- if (!captured) {
80
- await env.click(SEL.dialogClose).catch(() => undefined);
81
- throw new SetupHandoff("secret_capture_failed");
82
- }
83
- const stored = await env.storeClient({
84
- installed: { client_id: captured.clientId, client_secret: captured.clientSecret, project_id: env.projectId },
85
- });
86
- if (!stored.ok) throw new SetupHandoff(stored.error === "client_in_use" ? "client_in_use" : "secret_capture_failed");
87
- } catch (err) {
88
- if (err instanceof SetupControl) throw err;
89
- throw new SetupHandoff("secret_capture_failed");
90
- } finally {
91
- // Whatever the click produced is removed, also on failure.
92
- for (const f of await downloads(dir)) {
93
- if (!before.has(f)) await rm(path.join(dir, f), { force: true }).catch(() => undefined);
94
- }
95
- }
96
- }