@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.
@@ -14,10 +14,10 @@ import type {
14
14
  } from "@blackbelt-technology/dashboard-plugin-runtime/server";
15
15
  import rateLimit from "@fastify/rate-limit";
16
16
  import type { FastifyInstance, FastifyReply } from "fastify";
17
- import { validateClientJson } from "../shared/client-json.js";
18
17
  import type { GoogleEndpoints } from "../shared/endpoints.js";
19
18
  import { knownFlowCode } from "../shared/flow-codes.js";
20
- import { isTier, scopesCoverTier, type Tier } from "../shared/scopes.js";
19
+ import { isTier, scopesCoverFilters, scopesCoverTier, TIERS, type Tier } from "../shared/scopes.js";
20
+ import { classifyProjectId, isEmail, normalizeEmail, normalizeProjectId } from "../shared/setup.js";
21
21
  import { AccountError, type AccountStore, summarize } from "./accounts.js";
22
22
  import { revokeToken } from "./gmail-rest.js";
23
23
  import {
@@ -25,6 +25,10 @@ import {
25
25
  GmailFlowError,
26
26
  type GoogleLoginOptions, type GoogleSignInResult,
27
27
  } from "./google-oauth.js";
28
+ import type { DedicatedBrowserService } from "./setup/browser-service.js";
29
+ import { type RunDeps, SetupRunManager } from "./setup/run.js";
30
+ import { autoSetupState, registerSetupRoutes } from "./setup/setup-routes.js";
31
+ import { storeClient } from "./store-client.js";
28
32
 
29
33
  export interface GmailRouteDeps {
30
34
  store: AccountStore;
@@ -35,10 +39,47 @@ export interface GmailRouteDeps {
35
39
  fetchImpl?: typeof fetch;
36
40
  createCallback?: GoogleLoginOptions["createCallback"];
37
41
  newId?: () => string;
42
+ /** Plugin config seam (`ctx.getPluginConfig` / `ctx.updatePluginConfig`) for the saved setup fields. */
43
+ config?: {
44
+ get(): Record<string, unknown>;
45
+ update(partial: Record<string, unknown>): Promise<void>;
46
+ };
47
+ /** Lazy lookup of the browser plugin's `browser.dedicated` service (`ctx.consume`), per request. */
48
+ getBrowserService?: () => DedicatedBrowserService | undefined;
49
+ /** Test seams for the automatic setup run. */
50
+ setup?: Pick<RunDeps, "timing" | "wsFactory" | "newId">;
38
51
  }
39
52
 
40
53
  const PREFIX = "/api/plugins/gmail";
41
54
 
55
+ /** Optional `email` body field → `login_hint`; absent/empty is fine, a non-email is not. */
56
+ function parseLoginHint(raw: unknown): { ok: true; loginHint?: string } | { ok: false } {
57
+ if (raw === undefined || raw === null || raw === "") return { ok: true };
58
+ const email = typeof raw === "string" ? normalizeEmail(raw) : "";
59
+ return isEmail(email) ? { ok: true, loginHint: email } : { ok: false };
60
+ }
61
+
62
+ /** Validate a `PUT /setup` body; project id is checked (and reported) before the owner account. */
63
+ function parseSetupBody(
64
+ raw: unknown,
65
+ ): { ok: true; partial: Record<string, unknown> } | { ok: false; error: "invalid_project_id" | "invalid_owner_account" } {
66
+ const body = (raw ?? {}) as { projectId?: unknown; ownerAccount?: unknown };
67
+ const partial: Record<string, unknown> = {};
68
+ if (body.projectId !== undefined) {
69
+ if (typeof body.projectId !== "string") return { ok: false, error: "invalid_project_id" };
70
+ const id = normalizeProjectId(body.projectId);
71
+ if (id && classifyProjectId(id) !== "ok") return { ok: false, error: "invalid_project_id" };
72
+ partial.projectId = id || undefined;
73
+ }
74
+ if (body.ownerAccount !== undefined) {
75
+ if (typeof body.ownerAccount !== "string") return { ok: false, error: "invalid_owner_account" };
76
+ const email = normalizeEmail(body.ownerAccount);
77
+ if (email && !isEmail(email)) return { ok: false, error: "invalid_owner_account" };
78
+ partial.ownerAccount = email || undefined;
79
+ }
80
+ return { ok: true, partial };
81
+ }
82
+
42
83
  function accountErrorStatus(err: AccountError): number {
43
84
  if (err.code === "not_found") return 404;
44
85
  if (err.code === "alias_taken" || err.code === "ambiguous") return 409;
@@ -64,6 +105,8 @@ export async function mountGmailRoutes(fastify: FastifyInstance, deps: GmailRout
64
105
  reply: FastifyReply,
65
106
  tier: Tier,
66
107
  expect?: { sub: string; email: string },
108
+ /** `filters` set (level / re-auth / toggle) → request + require `gmail.settings.basic` iff true; unset (Add account) → leave the account's flag alone. */
109
+ opts?: { filters?: boolean; loginHint?: string },
67
110
  ) {
68
111
  if (!deps.oauth) return reply.code(501).send({ error: "oauth_unavailable" });
69
112
  const client = await store.getClient();
@@ -81,7 +124,8 @@ export async function mountGmailRoutes(fastify: FastifyInstance, deps: GmailRout
81
124
  client,
82
125
  endpoints,
83
126
  tier,
84
- loginHint: expect?.email,
127
+ filters: opts?.filters === true,
128
+ loginHint: expect?.email ?? opts?.loginHint,
85
129
  fetchImpl: deps.fetchImpl,
86
130
  createCallback: deps.createCallback,
87
131
  });
@@ -105,7 +149,10 @@ export async function mountGmailRoutes(fastify: FastifyInstance, deps: GmailRout
105
149
  const c = credential as GoogleSignInResult;
106
150
  if (expect && c.sub !== expect.sub) throw new GmailFlowError("account_mismatch");
107
151
  // 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");
152
+ // The filter scope is required whenever the flow asked for it (partial grant → nothing stored).
153
+ if (!scopesCoverTier(c.grantedScopes, c.tier) || (opts?.filters === true && !scopesCoverFilters(c.grantedScopes))) {
154
+ throw new GmailFlowError("scope_missing");
155
+ }
109
156
  const acct = await store.upsertFromSignIn({
110
157
  sub: c.sub,
111
158
  email: c.email,
@@ -115,6 +162,7 @@ export async function mountGmailRoutes(fastify: FastifyInstance, deps: GmailRout
115
162
  refresh: c.refresh || undefined,
116
163
  expires: c.expires,
117
164
  testingHint: c.testingHint,
165
+ filters: opts?.filters,
118
166
  });
119
167
  logger.info(`[gmail] sign-in ${acct.email} tier=${acct.tier}: ok`);
120
168
  } catch (err) {
@@ -129,6 +177,35 @@ export async function mountGmailRoutes(fastify: FastifyInstance, deps: GmailRout
129
177
  }
130
178
  }
131
179
 
180
+ /** Saved setup fields from plugin config (non-secret operator settings). */
181
+ function readSetup(): { projectId?: string; ownerAccount?: string } {
182
+ const cfg = deps.config?.get() ?? {};
183
+ const out: { projectId?: string; ownerAccount?: string } = {};
184
+ if (typeof cfg.projectId === "string" && cfg.projectId) out.projectId = cfg.projectId;
185
+ if (typeof cfg.ownerAccount === "string" && cfg.ownerAccount) out.ownerAccount = cfg.ownerAccount;
186
+ return out;
187
+ }
188
+
189
+ // The host's updatePluginConfig merges a snapshot taken before its awaits, so
190
+ // interleaved partial writes could drop a key: serialize them.
191
+ let setupQueue: Promise<unknown> = Promise.resolve();
192
+ function queueSetupWrite(fn: () => Promise<void> | undefined): Promise<void | undefined> {
193
+ const run = setupQueue.then(fn, fn);
194
+ setupQueue = run.catch(() => undefined);
195
+ return run;
196
+ }
197
+
198
+ const setupManager = new SetupRunManager({
199
+ getService: () => deps.getBrowserService?.(),
200
+ store,
201
+ logger,
202
+ saveSetup: async (partial) => {
203
+ await queueSetupWrite(() => deps.config?.update(partial));
204
+ },
205
+ ...deps.setup,
206
+ });
207
+ const setupRoutes = { prefix: PREFIX, guard: deps.networkGuard, store, manager: setupManager, getService: () => deps.getBrowserService?.() };
208
+
132
209
  await fastify.register(async (scope) => {
133
210
  await scope.register(rateLimit, {
134
211
  global: true,
@@ -138,35 +215,43 @@ export async function mountGmailRoutes(fastify: FastifyInstance, deps: GmailRout
138
215
  });
139
216
  const guarded = { preHandler: deps.networkGuard };
140
217
 
141
- scope.get(`${PREFIX}/state`, guarded, async () => {
218
+ scope.get(`${PREFIX}/state`, guarded, async (request) => {
142
219
  const client = await store.getClient();
143
220
  return {
144
221
  client: client ? { configured: true, clientId: client.clientId, projectId: client.projectId } : { configured: false },
145
222
  accounts: (await store.list()).map(summarize),
223
+ setup: readSetup(),
224
+ autoSetup: await autoSetupState(request, setupRoutes),
146
225
  };
147
226
  });
148
227
 
228
+ registerSetupRoutes(scope, setupRoutes);
229
+
230
+ scope.put(`${PREFIX}/setup`, guarded, async (request, reply) => {
231
+ if (!deps.config) return reply.code(501).send({ error: "config_unavailable" });
232
+ // Validate every provided key before any write; project id is reported first.
233
+ const parsed = parseSetupBody(request.body);
234
+ if (!parsed.ok) return reply.code(400).send({ error: parsed.error });
235
+ const partial = parsed.partial;
236
+ await queueSetupWrite(() => deps.config?.update(partial));
237
+ logger.info("[gmail] setup saved");
238
+ return { ok: true, setup: readSetup() };
239
+ });
240
+
149
241
  scope.put(`${PREFIX}/client`, guarded, async (request, reply) => {
150
- const result = validateClientJson((request.body as { json?: unknown } | null)?.json ?? request.body);
151
- if (!result.ok) return reply.code(400).send({ error: result.error.code, step: result.error.step });
152
- // Refresh tokens are bound to the client that minted them: swapping the
153
- // client under connected accounts would break every refresh silently.
154
- const current = await store.getClient();
155
- const changed =
156
- current &&
157
- (current.clientId !== result.client.clientId || current.clientSecret !== result.client.clientSecret);
158
- if (changed && (await store.list()).length > 0) {
159
- return reply.code(409).send({ error: "client_in_use", step: 5 });
160
- }
161
- await store.setClient(result.client);
162
- logger.info("[gmail] oauth client configured");
242
+ const result = await storeClient(store, (request.body as { json?: unknown } | null)?.json ?? request.body, logger);
243
+ if (!result.ok) return reply.code(result.status).send({ error: result.error, step: result.step });
163
244
  return { ok: true, clientId: result.client.clientId, projectId: result.client.projectId };
164
245
  });
165
246
 
166
247
  scope.post(`${PREFIX}/accounts`, guarded, async (request, reply) => {
167
- const tier = (request.body as { tier?: unknown } | null)?.tier ?? "readonly";
248
+ const body = (request.body ?? {}) as { tier?: unknown; email?: unknown };
249
+ const tier = body.tier ?? "readonly";
168
250
  if (!isTier(tier)) return reply.code(400).send({ error: "invalid_tier" });
169
- return startSignIn(reply, tier);
251
+ // Optional email → `login_hint` so Google skips the account chooser.
252
+ const hint = parseLoginHint(body.email);
253
+ if (!hint.ok) return reply.code(400).send({ error: "invalid_email" });
254
+ return startSignIn(reply, tier, undefined, { loginHint: hint.loginHint });
170
255
  });
171
256
 
172
257
  scope.post<{ Params: { sub: string } }>(`${PREFIX}/accounts/:sub/level`, guarded, async (request, reply) => {
@@ -174,20 +259,42 @@ export async function mountGmailRoutes(fastify: FastifyInstance, deps: GmailRout
174
259
  if (!isTier(tier)) return reply.code(400).send({ error: "invalid_tier" });
175
260
  const acct = await store.get(request.params.sub);
176
261
  if (!acct) return reply.code(404).send({ error: "not_found" });
177
- // Lowering (or a level the existing grant already covers) applies at once;
178
- // raising re-consents with the FULL scope set of the new level.
179
- if (acct.status === "ok" && scopesCoverTier(acct.scopes, tier)) {
262
+ // Lowering applies at once whatever the status or filters option (every
263
+ // lease is refused while `reauth_required`). A raise applies at once only
264
+ // when the account is `ok` and the stored grant covers the new level (and
265
+ // the filter scope when filters are on); else it re-consents with the FULL
266
+ // scope set of the new level plus `gmail.settings.basic` iff filters are on.
267
+ const lowering = TIERS.indexOf(tier) < TIERS.indexOf(acct.tier);
268
+ const covered =
269
+ acct.status === "ok" &&
270
+ scopesCoverTier(acct.scopes, tier) &&
271
+ (!acct.filters || scopesCoverFilters(acct.scopes));
272
+ if (lowering || covered) {
180
273
  const next = await store.setTier(acct.sub, tier);
181
274
  logger.info(`[gmail] level ${next.email} → ${tier}`);
182
275
  return { applied: true, account: summarize(next) };
183
276
  }
184
- return startSignIn(reply, tier, { sub: acct.sub, email: acct.email });
277
+ return startSignIn(reply, tier, { sub: acct.sub, email: acct.email }, { filters: acct.filters === true });
185
278
  });
186
279
 
187
280
  scope.post<{ Params: { sub: string } }>(`${PREFIX}/accounts/:sub/reauth`, guarded, async (request, reply) => {
188
281
  const acct = await store.get(request.params.sub);
189
282
  if (!acct) return reply.code(404).send({ error: "not_found" });
190
- return startSignIn(reply, acct.tier, { sub: acct.sub, email: acct.email });
283
+ return startSignIn(reply, acct.tier, { sub: acct.sub, email: acct.email }, { filters: acct.filters === true });
284
+ });
285
+
286
+ scope.post<{ Params: { sub: string } }>(`${PREFIX}/accounts/:sub/filters`, guarded, async (request, reply) => {
287
+ const enabled = (request.body as { enabled?: unknown } | null)?.enabled;
288
+ if (typeof enabled !== "boolean") return reply.code(400).send({ error: "invalid_enabled" });
289
+ const acct = await store.get(request.params.sub);
290
+ if (!acct) return reply.code(404).send({ error: "not_found" });
291
+ // Off is immediate; on is immediate only when the stored grant already covers tier + filters.
292
+ if (!enabled || (acct.status === "ok" && scopesCoverTier(acct.scopes, acct.tier) && scopesCoverFilters(acct.scopes))) {
293
+ const next = await store.setFilters(acct.sub, enabled);
294
+ logger.info(`[gmail] filters ${next.email} → ${enabled ? "on" : "off"}`);
295
+ return { applied: true, account: summarize(next) };
296
+ }
297
+ return startSignIn(reply, acct.tier, { sub: acct.sub, email: acct.email }, { filters: true });
191
298
  });
192
299
 
193
300
  scope.patch<{ Params: { sub: string } }>(`${PREFIX}/accounts/:sub`, guarded, async (request, reply) => {
@@ -0,0 +1,55 @@
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
+ }
@@ -0,0 +1,96 @@
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
+ }